opensips-js 0.1.12 → 0.1.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,12 +1,12 @@
1
- (function(tr,Lt){typeof exports=="object"&&typeof module<"u"?Lt(exports):typeof define=="function"&&define.amd?define(["exports"],Lt):(tr=typeof globalThis<"u"?globalThis:tr||self,Lt(tr.OpensipsJS={}))})(this,function(tr){"use strict";var h1=Object.defineProperty;var _1=(tr,Lt,Ht)=>Lt in tr?h1(tr,Lt,{enumerable:!0,configurable:!0,writable:!0,value:Ht}):tr[Lt]=Ht;var ln=(tr,Lt,Ht)=>(_1(tr,typeof Lt!="symbol"?Lt+"":Lt,Ht),Ht);var Lt=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Ht(f){return f&&f.__esModule&&Object.prototype.hasOwnProperty.call(f,"default")?f.default:f}const Uo={name:"jssip",title:"JsSIP",description:"the Javascript SIP library",version:"3.10.0",homepage:"https://jssip.net",contributors:["José Luis Millán <jmillan@aliax.net> (https://github.com/jmillan)","Iñaki Baz Castillo <ibc@aliax.net> (https://inakibaz.me)"],types:"lib/JsSIP.d.ts",main:"lib-es5/JsSIP.js",keywords:["sip","websocket","webrtc","node","browser","library"],license:"MIT",repository:{type:"git",url:"https://github.com/versatica/JsSIP.git"},bugs:{url:"https://github.com/versatica/JsSIP/issues"},dependencies:{"@types/events":"^3.0.0","@types/debug":"^4.1.7",debug:"^4.3.1",events:"^3.3.0","sdp-transform":"^2.14.1"},devDependencies:{"@babel/core":"^7.19.6","@babel/preset-env":"^7.19.4","ansi-colors":"^3.2.4",browserify:"^16.5.1",eslint:"^5.16.0","fancy-log":"^1.3.3",gulp:"^4.0.2","gulp-babel":"^8.0.0","gulp-eslint":"^5.0.0","gulp-expect-file":"^1.0.2","gulp-header":"^2.0.9","gulp-nodeunit-runner":"^0.2.2","gulp-plumber":"^1.2.1","gulp-rename":"^1.4.0","gulp-uglify-es":"^1.0.4",pegjs:"^0.7.0","vinyl-buffer":"^1.0.1","vinyl-source-stream":"^2.0.0"},scripts:{lint:"node npm-scripts.js lint",test:"node npm-scripts.js test",prepublish:"node npm-scripts.js prepublish",release:"node npm-scripts.js release"}};var Vf=Uo,hs={USER_AGENT:"".concat(Vf.title," ").concat(Vf.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 Po(f){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?Po=function(r){return typeof r}:Po=function(r){return r&&typeof Symbol=="function"&&r.constructor===Symbol&&r!==Symbol.prototype?"symbol":typeof r},Po(f)}function Lo(f,t){if(!(f instanceof t))throw new TypeError("Cannot call a class as a function")}function Ho(f,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");f.prototype=Object.create(t&&t.prototype,{constructor:{value:f,writable:!0,configurable:!0}}),t&&kl(f,t)}function Fo(f){var t=qf();return function(){var l=Nl(f),u;if(t){var s=Nl(this).constructor;u=Reflect.construct(l,arguments,s)}else u=l.apply(this,arguments);return KT(this,u)}}function KT(f,t){return t&&(Po(t)==="object"||typeof t=="function")?t:YT(f)}function YT(f){if(f===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return f}function nl(f){var t=typeof Map=="function"?new Map:void 0;return nl=function(l){if(l===null||!JT(l))return l;if(typeof l!="function")throw new TypeError("Super expression must either be null or a function");if(typeof t<"u"){if(t.has(l))return t.get(l);t.set(l,u)}function u(){return Bo(l,arguments,Nl(this).constructor)}return u.prototype=Object.create(l.prototype,{constructor:{value:u,enumerable:!1,writable:!0,configurable:!0}}),kl(u,l)},nl(f)}function Bo(f,t,r){return qf()?Bo=Reflect.construct:Bo=function(u,s,n){var g=[null];g.push.apply(g,s);var _=Function.bind.apply(u,g),v=new _;return n&&kl(v,n.prototype),v},Bo.apply(null,arguments)}function qf(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],function(){})),!0}catch{return!1}}function JT(f){return Function.toString.call(f).indexOf("[native code]")!==-1}function kl(f,t){return kl=Object.setPrototypeOf||function(l,u){return l.__proto__=u,l},kl(f,t)}function Nl(f){return Nl=Object.setPrototypeOf?Object.getPrototypeOf:function(r){return r.__proto__||Object.getPrototypeOf(r)},Nl(f)}var QT=function(f){Ho(r,f);var t=Fo(r);function r(l,u){var s;return Lo(this,r),s=t.call(this),s.code=1,s.name="CONFIGURATION_ERROR",s.parameter=l,s.value=u,s.message=s.value?"Invalid value ".concat(JSON.stringify(s.value),' for parameter "').concat(s.parameter,'"'):"Missing parameter: ".concat(s.parameter),s}return r}(nl(Error)),XT=function(f){Ho(r,f);var t=Fo(r);function r(l){var u;return Lo(this,r),u=t.call(this),u.code=2,u.name="INVALID_STATE_ERROR",u.status=l,u.message="Invalid status: ".concat(l),u}return r}(nl(Error)),ZT=function(f){Ho(r,f);var t=Fo(r);function r(l){var u;return Lo(this,r),u=t.call(this),u.code=3,u.name="NOT_SUPPORTED_ERROR",u.message=l,u}return r}(nl(Error)),e0=function(f){Ho(r,f);var t=Fo(r);function r(l){var u;return Lo(this,r),u=t.call(this),u.code=4,u.name="NOT_READY_ERROR",u.message=l,u}return r}(nl(Error)),yi={ConfigurationError:QT,InvalidStateError:XT,NotSupportedError:ZT,NotReadyError:e0},us={},lc,jf;function oc(){if(jf)return lc;jf=1;function f(s,n){if(!(s instanceof n))throw new TypeError("Cannot call a class as a function")}function t(s,n){for(var g=0;g<n.length;g++){var _=n[g];_.enumerable=_.enumerable||!1,_.configurable=!0,"value"in _&&(_.writable=!0),Object.defineProperty(s,_.key,_)}}function r(s,n,g){return n&&t(s.prototype,n),g&&t(s,g),s}var l=Ti(),u=on();return lc=function(){r(s,null,[{key:"parse",value:function(g){if(g=u.parse(g,"Name_Addr_Header"),g!==-1)return g}}]);function s(n,g,_){if(f(this,s),!n||!(n instanceof l))throw new TypeError('missing or invalid "uri" parameter');this._uri=n,this._parameters={},this.display_name=g;for(var v in _)Object.prototype.hasOwnProperty.call(_,v)&&this.setParam(v,_[v])}return r(s,[{key:"setParam",value:function(g,_){g&&(this._parameters[g.toLowerCase()]=typeof _>"u"||_===null?null:_.toString())}},{key:"getParam",value:function(g){if(g)return this._parameters[g.toLowerCase()]}},{key:"hasParam",value:function(g){if(g)return this._parameters.hasOwnProperty(g.toLowerCase())&&!0||!1}},{key:"deleteParam",value:function(g){if(g=g.toLowerCase(),this._parameters.hasOwnProperty(g)){var _=this._parameters[g];return delete this._parameters[g],_}}},{key:"clearParams",value:function(){this._parameters={}}},{key:"clone",value:function(){return new s(this._uri.clone(),this._display_name,JSON.parse(JSON.stringify(this._parameters)))}},{key:"_quote",value:function(g){return g.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}},{key:"toString",value:function(){var g=this._display_name?'"'.concat(this._quote(this._display_name),'" '):"";g+="<".concat(this._uri.toString(),">");for(var _ in this._parameters)Object.prototype.hasOwnProperty.call(this._parameters,_)&&(g+=";".concat(_),this._parameters[_]!==null&&(g+="=".concat(this._parameters[_])));return g}},{key:"uri",get:function(){return this._uri}},{key:"display_name",get:function(){return this._display_name},set:function(g){this._display_name=g===0?"0":g}}]),s}(),lc}var uc,Gf;function on(){return Gf||(Gf=1,uc=function(){function f(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 t={parse:function(l,u){var s={CRLF:C,DIGIT:R,ALPHA:D,HEXDIG:H,WSP:F,OCTET:q,DQUOTE:G,SP:te,HTAB:X,alphanum:we,reserved:Q,unreserved:re,mark:ke,escaped:Ne,LWS:Z,SWS:se,HCOLON:pe,TEXT_UTF8_TRIM:me,TEXT_UTF8char:be,UTF8_NONASCII:_e,UTF8_CONT:Ae,LHEX:le,token:oe,token_nodot:Oe,separators:rs,word:Re,STAR:ye,SLASH:ge,EQUAL:Le,LPAREN:et,RPAREN:vt,RAQUOT:xt,LAQUOT:dt,COMMA:ze,SEMI:Ye,COLON:Zt,LDQUOT:Mt,RDQUOT:nt,comment:rt,ctext:gt,quoted_string:ft,quoted_string_clean:Fe,qdtext:He,quoted_pair:qe,SIP_URI_noparams:yt,SIP_URI:Ct,uri_scheme:ns,uri_scheme_sips:Ut,uri_scheme_sip:ar,userinfo:vs,user:Oi,user_unreserved:Di,password:zn,hostport:pr,host:as,hostname:Pr,domainlabel:Vn,toplabel:pn,IPv6reference:Lr,IPv6address:Qe,h16:Ve,ls32:ls,IPv4address:lr,dec_octet:os,port:qn,uri_parameters:Hr,uri_parameter:jn,transport_param:ki,user_param:Gn,method_param:Ni,ttl_param:Wn,maddr_param:Mi,lr_param:Kn,other_param:Ui,pname:Yn,pvalue:Ar,paramchar:mr,param_unreserved:Fr,headers:Br,header:mn,hname:Pi,hvalue:zr,hnv_unreserved:Vr,Request_Response:kt,Request_Line:gr,Request_URI:bs,absoluteURI:qr,hier_part:It,net_path:jr,abs_path:gn,opaque_part:vn,uric:Gr,uric_no_slash:Li,path_segments:yn,segment:or,param:Ir,pchar:Wr,scheme:Da,authority:vr,srvr:Ys,reg_name:yr,query:Kr,SIP_Version:Yr,INVITEm:Jn,ACKm:Qn,OPTIONSm:Xn,BYEm:ot,CANCELm:Zn,REGISTERm:Hi,SUBSCRIBEm:Fi,NOTIFYm:Bi,REFERm:Tn,Method:Sn,Status_Line:ei,Status_Code:zi,extension_code:bt,Reason_Phrase:ur,Allow_Events:Sl,Call_ID:bn,Contact:ie,contact_param:Ls,name_addr:Js,display_name:Jr,contact_params:ti,c_p_q:ht,c_p_expires:cr,delta_seconds:Tr,qvalue:Vt,generic_param:qt,gen_value:Vi,Content_Disposition:ka,disp_type:wn,disp_param:si,handling_param:qi,Content_Encoding:Na,Content_Length:Ma,Content_Type:Ua,media_type:ji,m_type:Pa,discrete_type:Qr,composite_type:En,extension_token:Cn,x_token:La,m_subtype:An,m_parameter:In,m_value:ri,CSeq:ni,CSeq_value:Ha,Expires:bl,Event:Xr,event_type:Zr,From:Gi,from_param:Rn,tag_param:Fa,Max_Forwards:wl,Min_Expires:Rt,Name_Addr_Header:jt,Proxy_Authenticate:Rr,challenge:en,other_challenge:Bt,auth_param:Gt,digest_cln:Xe,realm:Pt,realm_value:ii,domain:dr,URI:qs,nonce:Ze,nonce_value:tn,opaque:he,stale:Je,algorithm:Wi,qop_options:sn,qop_value:ai,Proxy_Require:El,Record_Route:_t,rec_route:li,Reason:oi,reason_param:ui,reason_cause:Ba,Require:Cl,Route:ci,route_param:ms,Subscription_State:za,substate_value:di,subexp_params:Qs,event_reason_value:Va,Subject:Al,Supported:Il,To:Ki,to_param:Yi,Via:fi,via_param:rn,via_params:hi,via_ttl:Ji,via_maddr:Qi,via_received:Hs,via_branch:Xi,response_port:Zi,rport:ea,sent_protocol:ta,protocol_name:sa,transport:ra,sent_by:na,via_host:ia,via_port:_i,ttl:aa,WWW_Authenticate:Eo,Session_Expires:js,s_e_expires:pi,s_e_params:nn,s_e_refresher:la,extension_header:Gs,header_value:qa,message_body:Rl,uuid_URI:ja,uuid:Xs,hex4:Zs,hex8:oa,hex12:Ga,Refer_To:$l,Replaces:Wa,call_id:mi,replaces_param:ws,to_tag:ua,from_tag:ca,early_flag:Ka};if(u!==void 0){if(s[u]===void 0)throw new Error("Invalid rule name: "+f(u)+".")}else u="CRLF";var n=0,g=0,_=[];function v(e){n<g||(n>g&&(g=n,_=[]),_.push(e))}function C(){var e;return l.substr(n,2)===`\r
1
+ (function(tr,Lt){typeof exports=="object"&&typeof module<"u"?Lt(exports):typeof define=="function"&&define.amd?define(["exports"],Lt):(tr=typeof globalThis<"u"?globalThis:tr||self,Lt(tr.OpensipsJS={}))})(this,function(tr){"use strict";var h1=Object.defineProperty;var _1=(tr,Lt,Ht)=>Lt in tr?h1(tr,Lt,{enumerable:!0,configurable:!0,writable:!0,value:Ht}):tr[Lt]=Ht;var ln=(tr,Lt,Ht)=>(_1(tr,typeof Lt!="symbol"?Lt+"":Lt,Ht),Ht);var Lt=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Ht(f){return f&&f.__esModule&&Object.prototype.hasOwnProperty.call(f,"default")?f.default:f}const Uo={name:"jssip",title:"JsSIP",description:"the Javascript SIP library",version:"3.10.0",homepage:"https://jssip.net",contributors:["José Luis Millán <jmillan@aliax.net> (https://github.com/jmillan)","Iñaki Baz Castillo <ibc@aliax.net> (https://inakibaz.me)"],types:"lib/JsSIP.d.ts",main:"lib-es5/JsSIP.js",keywords:["sip","websocket","webrtc","node","browser","library"],license:"MIT",repository:{type:"git",url:"https://github.com/versatica/JsSIP.git"},bugs:{url:"https://github.com/versatica/JsSIP/issues"},dependencies:{"@types/events":"^3.0.0","@types/debug":"^4.1.7",debug:"^4.3.1",events:"^3.3.0","sdp-transform":"^2.14.1"},devDependencies:{"@babel/core":"^7.19.6","@babel/preset-env":"^7.19.4","ansi-colors":"^3.2.4",browserify:"^16.5.1",eslint:"^5.16.0","fancy-log":"^1.3.3",gulp:"^4.0.2","gulp-babel":"^8.0.0","gulp-eslint":"^5.0.0","gulp-expect-file":"^1.0.2","gulp-header":"^2.0.9","gulp-nodeunit-runner":"^0.2.2","gulp-plumber":"^1.2.1","gulp-rename":"^1.4.0","gulp-uglify-es":"^1.0.4",pegjs:"^0.7.0","vinyl-buffer":"^1.0.1","vinyl-source-stream":"^2.0.0"},scripts:{lint:"node npm-scripts.js lint",test:"node npm-scripts.js test",prepublish:"node npm-scripts.js prepublish",release:"node npm-scripts.js release"}};var zf=Uo,hs={USER_AGENT:"".concat(zf.title," ").concat(zf.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 Po(f){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?Po=function(r){return typeof r}:Po=function(r){return r&&typeof Symbol=="function"&&r.constructor===Symbol&&r!==Symbol.prototype?"symbol":typeof r},Po(f)}function Lo(f,t){if(!(f instanceof t))throw new TypeError("Cannot call a class as a function")}function Ho(f,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");f.prototype=Object.create(t&&t.prototype,{constructor:{value:f,writable:!0,configurable:!0}}),t&&kl(f,t)}function Fo(f){var t=Vf();return function(){var l=Nl(f),u;if(t){var s=Nl(this).constructor;u=Reflect.construct(l,arguments,s)}else u=l.apply(this,arguments);return KT(this,u)}}function KT(f,t){return t&&(Po(t)==="object"||typeof t=="function")?t:YT(f)}function YT(f){if(f===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return f}function nl(f){var t=typeof Map=="function"?new Map:void 0;return nl=function(l){if(l===null||!JT(l))return l;if(typeof l!="function")throw new TypeError("Super expression must either be null or a function");if(typeof t<"u"){if(t.has(l))return t.get(l);t.set(l,u)}function u(){return Bo(l,arguments,Nl(this).constructor)}return u.prototype=Object.create(l.prototype,{constructor:{value:u,enumerable:!1,writable:!0,configurable:!0}}),kl(u,l)},nl(f)}function Bo(f,t,r){return Vf()?Bo=Reflect.construct:Bo=function(u,s,n){var g=[null];g.push.apply(g,s);var _=Function.bind.apply(u,g),v=new _;return n&&kl(v,n.prototype),v},Bo.apply(null,arguments)}function Vf(){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 JT(f){return Function.toString.call(f).indexOf("[native code]")!==-1}function kl(f,t){return kl=Object.setPrototypeOf||function(l,u){return l.__proto__=u,l},kl(f,t)}function Nl(f){return Nl=Object.setPrototypeOf?Object.getPrototypeOf:function(r){return r.__proto__||Object.getPrototypeOf(r)},Nl(f)}var QT=function(f){Ho(r,f);var t=Fo(r);function r(l,u){var s;return Lo(this,r),s=t.call(this),s.code=1,s.name="CONFIGURATION_ERROR",s.parameter=l,s.value=u,s.message=s.value?"Invalid value ".concat(JSON.stringify(s.value),' for parameter "').concat(s.parameter,'"'):"Missing parameter: ".concat(s.parameter),s}return r}(nl(Error)),XT=function(f){Ho(r,f);var t=Fo(r);function r(l){var u;return Lo(this,r),u=t.call(this),u.code=2,u.name="INVALID_STATE_ERROR",u.status=l,u.message="Invalid status: ".concat(l),u}return r}(nl(Error)),ZT=function(f){Ho(r,f);var t=Fo(r);function r(l){var u;return Lo(this,r),u=t.call(this),u.code=3,u.name="NOT_SUPPORTED_ERROR",u.message=l,u}return r}(nl(Error)),e0=function(f){Ho(r,f);var t=Fo(r);function r(l){var u;return Lo(this,r),u=t.call(this),u.code=4,u.name="NOT_READY_ERROR",u.message=l,u}return r}(nl(Error)),yi={ConfigurationError:QT,InvalidStateError:XT,NotSupportedError:ZT,NotReadyError:e0},us={},lc,qf;function oc(){if(qf)return lc;qf=1;function f(s,n){if(!(s instanceof n))throw new TypeError("Cannot call a class as a function")}function t(s,n){for(var g=0;g<n.length;g++){var _=n[g];_.enumerable=_.enumerable||!1,_.configurable=!0,"value"in _&&(_.writable=!0),Object.defineProperty(s,_.key,_)}}function r(s,n,g){return n&&t(s.prototype,n),g&&t(s,g),s}var l=Ti(),u=on();return lc=function(){r(s,null,[{key:"parse",value:function(g){if(g=u.parse(g,"Name_Addr_Header"),g!==-1)return g}}]);function s(n,g,_){if(f(this,s),!n||!(n instanceof l))throw new TypeError('missing or invalid "uri" parameter');this._uri=n,this._parameters={},this.display_name=g;for(var v in _)Object.prototype.hasOwnProperty.call(_,v)&&this.setParam(v,_[v])}return r(s,[{key:"setParam",value:function(g,_){g&&(this._parameters[g.toLowerCase()]=typeof _>"u"||_===null?null:_.toString())}},{key:"getParam",value:function(g){if(g)return this._parameters[g.toLowerCase()]}},{key:"hasParam",value:function(g){if(g)return this._parameters.hasOwnProperty(g.toLowerCase())&&!0||!1}},{key:"deleteParam",value:function(g){if(g=g.toLowerCase(),this._parameters.hasOwnProperty(g)){var _=this._parameters[g];return delete this._parameters[g],_}}},{key:"clearParams",value:function(){this._parameters={}}},{key:"clone",value:function(){return new s(this._uri.clone(),this._display_name,JSON.parse(JSON.stringify(this._parameters)))}},{key:"_quote",value:function(g){return g.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}},{key:"toString",value:function(){var g=this._display_name?'"'.concat(this._quote(this._display_name),'" '):"";g+="<".concat(this._uri.toString(),">");for(var _ in this._parameters)Object.prototype.hasOwnProperty.call(this._parameters,_)&&(g+=";".concat(_),this._parameters[_]!==null&&(g+="=".concat(this._parameters[_])));return g}},{key:"uri",get:function(){return this._uri}},{key:"display_name",get:function(){return this._display_name},set:function(g){this._display_name=g===0?"0":g}}]),s}(),lc}var uc,jf;function on(){return jf||(jf=1,uc=function(){function f(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 t={parse:function(l,u){var s={CRLF:C,DIGIT:R,ALPHA:D,HEXDIG:H,WSP:F,OCTET:q,DQUOTE:G,SP:te,HTAB:X,alphanum:we,reserved:Q,unreserved:re,mark:ke,escaped:Ne,LWS:Z,SWS:se,HCOLON:pe,TEXT_UTF8_TRIM:me,TEXT_UTF8char:be,UTF8_NONASCII:_e,UTF8_CONT:Ae,LHEX:le,token:oe,token_nodot:Oe,separators:rs,word:Re,STAR:ye,SLASH:ge,EQUAL:Le,LPAREN:et,RPAREN:vt,RAQUOT:xt,LAQUOT:dt,COMMA:ze,SEMI:Ye,COLON:Zt,LDQUOT:Mt,RDQUOT:nt,comment:rt,ctext:gt,quoted_string:ft,quoted_string_clean:Fe,qdtext:He,quoted_pair:qe,SIP_URI_noparams:yt,SIP_URI:Ct,uri_scheme:ns,uri_scheme_sips:Ut,uri_scheme_sip:ar,userinfo:vs,user:Oi,user_unreserved:Di,password:zn,hostport:pr,host:as,hostname:Pr,domainlabel:Vn,toplabel:pn,IPv6reference:Lr,IPv6address:Qe,h16:Ve,ls32:ls,IPv4address:lr,dec_octet:os,port:qn,uri_parameters:Hr,uri_parameter:jn,transport_param:ki,user_param:Gn,method_param:Ni,ttl_param:Wn,maddr_param:Mi,lr_param:Kn,other_param:Ui,pname:Yn,pvalue:Ar,paramchar:mr,param_unreserved:Fr,headers:Br,header:mn,hname:Pi,hvalue:zr,hnv_unreserved:Vr,Request_Response:kt,Request_Line:gr,Request_URI:bs,absoluteURI:qr,hier_part:It,net_path:jr,abs_path:gn,opaque_part:vn,uric:Gr,uric_no_slash:Li,path_segments:yn,segment:or,param:Ir,pchar:Wr,scheme:Da,authority:vr,srvr:Ys,reg_name:yr,query:Kr,SIP_Version:Yr,INVITEm:Jn,ACKm:Qn,OPTIONSm:Xn,BYEm:ot,CANCELm:Zn,REGISTERm:Hi,SUBSCRIBEm:Fi,NOTIFYm:Bi,REFERm:Tn,Method:Sn,Status_Line:ei,Status_Code:zi,extension_code:bt,Reason_Phrase:ur,Allow_Events:Sl,Call_ID:bn,Contact:ie,contact_param:Ls,name_addr:Js,display_name:Jr,contact_params:ti,c_p_q:ht,c_p_expires:cr,delta_seconds:Tr,qvalue:Vt,generic_param:qt,gen_value:Vi,Content_Disposition:ka,disp_type:wn,disp_param:si,handling_param:qi,Content_Encoding:Na,Content_Length:Ma,Content_Type:Ua,media_type:ji,m_type:Pa,discrete_type:Qr,composite_type:En,extension_token:Cn,x_token:La,m_subtype:An,m_parameter:In,m_value:ri,CSeq:ni,CSeq_value:Ha,Expires:bl,Event:Xr,event_type:Zr,From:Gi,from_param:Rn,tag_param:Fa,Max_Forwards:wl,Min_Expires:Rt,Name_Addr_Header:jt,Proxy_Authenticate:Rr,challenge:en,other_challenge:Bt,auth_param:Gt,digest_cln:Xe,realm:Pt,realm_value:ii,domain:dr,URI:qs,nonce:Ze,nonce_value:tn,opaque:he,stale:Je,algorithm:Wi,qop_options:sn,qop_value:ai,Proxy_Require:El,Record_Route:_t,rec_route:li,Reason:oi,reason_param:ui,reason_cause:Ba,Require:Cl,Route:ci,route_param:ms,Subscription_State:za,substate_value:di,subexp_params:Qs,event_reason_value:Va,Subject:Al,Supported:Il,To:Ki,to_param:Yi,Via:fi,via_param:rn,via_params:hi,via_ttl:Ji,via_maddr:Qi,via_received:Hs,via_branch:Xi,response_port:Zi,rport:ea,sent_protocol:ta,protocol_name:sa,transport:ra,sent_by:na,via_host:ia,via_port:_i,ttl:aa,WWW_Authenticate:Eo,Session_Expires:js,s_e_expires:pi,s_e_params:nn,s_e_refresher:la,extension_header:Gs,header_value:qa,message_body:Rl,uuid_URI:ja,uuid:Xs,hex4:Zs,hex8:oa,hex12:Ga,Refer_To:$l,Replaces:Wa,call_id:mi,replaces_param:ws,to_tag:ua,from_tag:ca,early_flag:Ka};if(u!==void 0){if(s[u]===void 0)throw new Error("Invalid rule name: "+f(u)+".")}else u="CRLF";var n=0,g=0,_=[];function v(e){n<g||(n>g&&(g=n,_=[]),_.push(e))}function C(){var e;return l.substr(n,2)===`\r
2
2
  `?(e=`\r
3
3
  `,n+=2):(e=null,v('"\\r\\n"')),e}function R(){var e;return/^[0-9]/.test(l.charAt(n))?(e=l.charAt(n),n++):(e=null,v("[0-9]")),e}function D(){var e;return/^[a-zA-Z]/.test(l.charAt(n))?(e=l.charAt(n),n++):(e=null,v("[a-zA-Z]")),e}function H(){var e;return/^[0-9a-fA-F]/.test(l.charAt(n))?(e=l.charAt(n),n++):(e=null,v("[0-9a-fA-F]")),e}function F(){var e;return e=te(),e===null&&(e=X()),e}function q(){var e;return/^[\0-\xFF]/.test(l.charAt(n))?(e=l.charAt(n),n++):(e=null,v("[\\0-\\xFF]")),e}function G(){var e;return/^["]/.test(l.charAt(n))?(e=l.charAt(n),n++):(e=null,v('["]')),e}function te(){var e;return l.charCodeAt(n)===32?(e=" ",n++):(e=null,v('" "')),e}function X(){var e;return l.charCodeAt(n)===9?(e=" ",n++):(e=null,v('"\\t"')),e}function we(){var e;return/^[a-zA-Z0-9]/.test(l.charAt(n))?(e=l.charAt(n),n++):(e=null,v("[a-zA-Z0-9]")),e}function Q(){var e;return l.charCodeAt(n)===59?(e=";",n++):(e=null,v('";"')),e===null&&(l.charCodeAt(n)===47?(e="/",n++):(e=null,v('"/"')),e===null&&(l.charCodeAt(n)===63?(e="?",n++):(e=null,v('"?"')),e===null&&(l.charCodeAt(n)===58?(e=":",n++):(e=null,v('":"')),e===null&&(l.charCodeAt(n)===64?(e="@",n++):(e=null,v('"@"')),e===null&&(l.charCodeAt(n)===38?(e="&",n++):(e=null,v('"&"')),e===null&&(l.charCodeAt(n)===61?(e="=",n++):(e=null,v('"="')),e===null&&(l.charCodeAt(n)===43?(e="+",n++):(e=null,v('"+"')),e===null&&(l.charCodeAt(n)===36?(e="$",n++):(e=null,v('"$"')),e===null&&(l.charCodeAt(n)===44?(e=",",n++):(e=null,v('","'))))))))))),e}function re(){var e;return e=we(),e===null&&(e=ke()),e}function ke(){var e;return l.charCodeAt(n)===45?(e="-",n++):(e=null,v('"-"')),e===null&&(l.charCodeAt(n)===95?(e="_",n++):(e=null,v('"_"')),e===null&&(l.charCodeAt(n)===46?(e=".",n++):(e=null,v('"."')),e===null&&(l.charCodeAt(n)===33?(e="!",n++):(e=null,v('"!"')),e===null&&(l.charCodeAt(n)===126?(e="~",n++):(e=null,v('"~"')),e===null&&(l.charCodeAt(n)===42?(e="*",n++):(e=null,v('"*"')),e===null&&(l.charCodeAt(n)===39?(e="'",n++):(e=null,v(`"'"`)),e===null&&(l.charCodeAt(n)===40?(e="(",n++):(e=null,v('"("')),e===null&&(l.charCodeAt(n)===41?(e=")",n++):(e=null,v('")"')))))))))),e}function Ne(){var e,o,d,p,T;return p=n,T=n,l.charCodeAt(n)===37?(e="%",n++):(e=null,v('"%"')),e!==null?(o=H(),o!==null?(d=H(),d!==null?e=[e,o,d]:(e=null,n=T)):(e=null,n=T)):(e=null,n=T),e!==null&&(e=function(w,O){return O.join("")}(p,e)),e===null&&(n=p),e}function Z(){var e,o,d,p,T,w;for(p=n,T=n,w=n,e=[],o=F();o!==null;)e.push(o),o=F();if(e!==null?(o=C(),o!==null?e=[e,o]:(e=null,n=w)):(e=null,n=w),e=e!==null?e:"",e!==null){if(d=F(),d!==null)for(o=[];d!==null;)o.push(d),d=F();else o=null;o!==null?e=[e,o]:(e=null,n=T)}else e=null,n=T;return e!==null&&(e=function(O){return" "}()),e===null&&(n=p),e}function se(){var e;return e=Z(),e=e!==null?e:"",e}function pe(){var e,o,d,p,T;for(p=n,T=n,e=[],o=te(),o===null&&(o=X());o!==null;)e.push(o),o=te(),o===null&&(o=X());return e!==null?(l.charCodeAt(n)===58?(o=":",n++):(o=null,v('":"')),o!==null?(d=se(),d!==null?e=[e,o,d]:(e=null,n=T)):(e=null,n=T)):(e=null,n=T),e!==null&&(e=function(w){return":"}()),e===null&&(n=p),e}function me(){var e,o,d,p,T,w,O;if(T=n,w=n,o=be(),o!==null)for(e=[];o!==null;)e.push(o),o=be();else e=null;if(e!==null){for(o=[],O=n,d=[],p=Z();p!==null;)d.push(p),p=Z();for(d!==null?(p=be(),p!==null?d=[d,p]:(d=null,n=O)):(d=null,n=O);d!==null;){for(o.push(d),O=n,d=[],p=Z();p!==null;)d.push(p),p=Z();d!==null?(p=be(),p!==null?d=[d,p]:(d=null,n=O)):(d=null,n=O)}o!==null?e=[e,o]:(e=null,n=w)}else e=null,n=w;return e!==null&&(e=function(B){return l.substring(n,B)}(T)),e===null&&(n=T),e}function be(){var e;return/^[!-~]/.test(l.charAt(n))?(e=l.charAt(n),n++):(e=null,v("[!-~]")),e===null&&(e=_e()),e}function _e(){var e;return/^[\x80-\uFFFF]/.test(l.charAt(n))?(e=l.charAt(n),n++):(e=null,v("[\\x80-\\uFFFF]")),e}function Ae(){var e;return/^[\x80-\xBF]/.test(l.charAt(n))?(e=l.charAt(n),n++):(e=null,v("[\\x80-\\xBF]")),e}function le(){var e;return e=R(),e===null&&(/^[a-f]/.test(l.charAt(n))?(e=l.charAt(n),n++):(e=null,v("[a-f]"))),e}function oe(){var e,o,d;if(d=n,o=we(),o===null&&(l.charCodeAt(n)===45?(o="-",n++):(o=null,v('"-"')),o===null&&(l.charCodeAt(n)===46?(o=".",n++):(o=null,v('"."')),o===null&&(l.charCodeAt(n)===33?(o="!",n++):(o=null,v('"!"')),o===null&&(l.charCodeAt(n)===37?(o="%",n++):(o=null,v('"%"')),o===null&&(l.charCodeAt(n)===42?(o="*",n++):(o=null,v('"*"')),o===null&&(l.charCodeAt(n)===95?(o="_",n++):(o=null,v('"_"')),o===null&&(l.charCodeAt(n)===43?(o="+",n++):(o=null,v('"+"')),o===null&&(l.charCodeAt(n)===96?(o="`",n++):(o=null,v('"`"')),o===null&&(l.charCodeAt(n)===39?(o="'",n++):(o=null,v(`"'"`)),o===null&&(l.charCodeAt(n)===126?(o="~",n++):(o=null,v('"~"')))))))))))),o!==null)for(e=[];o!==null;)e.push(o),o=we(),o===null&&(l.charCodeAt(n)===45?(o="-",n++):(o=null,v('"-"')),o===null&&(l.charCodeAt(n)===46?(o=".",n++):(o=null,v('"."')),o===null&&(l.charCodeAt(n)===33?(o="!",n++):(o=null,v('"!"')),o===null&&(l.charCodeAt(n)===37?(o="%",n++):(o=null,v('"%"')),o===null&&(l.charCodeAt(n)===42?(o="*",n++):(o=null,v('"*"')),o===null&&(l.charCodeAt(n)===95?(o="_",n++):(o=null,v('"_"')),o===null&&(l.charCodeAt(n)===43?(o="+",n++):(o=null,v('"+"')),o===null&&(l.charCodeAt(n)===96?(o="`",n++):(o=null,v('"`"')),o===null&&(l.charCodeAt(n)===39?(o="'",n++):(o=null,v(`"'"`)),o===null&&(l.charCodeAt(n)===126?(o="~",n++):(o=null,v('"~"'))))))))))));else e=null;return e!==null&&(e=function(p){return l.substring(n,p)}(d)),e===null&&(n=d),e}function Oe(){var e,o,d;if(d=n,o=we(),o===null&&(l.charCodeAt(n)===45?(o="-",n++):(o=null,v('"-"')),o===null&&(l.charCodeAt(n)===33?(o="!",n++):(o=null,v('"!"')),o===null&&(l.charCodeAt(n)===37?(o="%",n++):(o=null,v('"%"')),o===null&&(l.charCodeAt(n)===42?(o="*",n++):(o=null,v('"*"')),o===null&&(l.charCodeAt(n)===95?(o="_",n++):(o=null,v('"_"')),o===null&&(l.charCodeAt(n)===43?(o="+",n++):(o=null,v('"+"')),o===null&&(l.charCodeAt(n)===96?(o="`",n++):(o=null,v('"`"')),o===null&&(l.charCodeAt(n)===39?(o="'",n++):(o=null,v(`"'"`)),o===null&&(l.charCodeAt(n)===126?(o="~",n++):(o=null,v('"~"'))))))))))),o!==null)for(e=[];o!==null;)e.push(o),o=we(),o===null&&(l.charCodeAt(n)===45?(o="-",n++):(o=null,v('"-"')),o===null&&(l.charCodeAt(n)===33?(o="!",n++):(o=null,v('"!"')),o===null&&(l.charCodeAt(n)===37?(o="%",n++):(o=null,v('"%"')),o===null&&(l.charCodeAt(n)===42?(o="*",n++):(o=null,v('"*"')),o===null&&(l.charCodeAt(n)===95?(o="_",n++):(o=null,v('"_"')),o===null&&(l.charCodeAt(n)===43?(o="+",n++):(o=null,v('"+"')),o===null&&(l.charCodeAt(n)===96?(o="`",n++):(o=null,v('"`"')),o===null&&(l.charCodeAt(n)===39?(o="'",n++):(o=null,v(`"'"`)),o===null&&(l.charCodeAt(n)===126?(o="~",n++):(o=null,v('"~"')))))))))));else e=null;return e!==null&&(e=function(p){return l.substring(n,p)}(d)),e===null&&(n=d),e}function rs(){var e;return l.charCodeAt(n)===40?(e="(",n++):(e=null,v('"("')),e===null&&(l.charCodeAt(n)===41?(e=")",n++):(e=null,v('")"')),e===null&&(l.charCodeAt(n)===60?(e="<",n++):(e=null,v('"<"')),e===null&&(l.charCodeAt(n)===62?(e=">",n++):(e=null,v('">"')),e===null&&(l.charCodeAt(n)===64?(e="@",n++):(e=null,v('"@"')),e===null&&(l.charCodeAt(n)===44?(e=",",n++):(e=null,v('","')),e===null&&(l.charCodeAt(n)===59?(e=";",n++):(e=null,v('";"')),e===null&&(l.charCodeAt(n)===58?(e=":",n++):(e=null,v('":"')),e===null&&(l.charCodeAt(n)===92?(e="\\",n++):(e=null,v('"\\\\"')),e===null&&(e=G(),e===null&&(l.charCodeAt(n)===47?(e="/",n++):(e=null,v('"/"')),e===null&&(l.charCodeAt(n)===91?(e="[",n++):(e=null,v('"["')),e===null&&(l.charCodeAt(n)===93?(e="]",n++):(e=null,v('"]"')),e===null&&(l.charCodeAt(n)===63?(e="?",n++):(e=null,v('"?"')),e===null&&(l.charCodeAt(n)===61?(e="=",n++):(e=null,v('"="')),e===null&&(l.charCodeAt(n)===123?(e="{",n++):(e=null,v('"{"')),e===null&&(l.charCodeAt(n)===125?(e="}",n++):(e=null,v('"}"')),e===null&&(e=te(),e===null&&(e=X())))))))))))))))))),e}function Re(){var e,o,d;if(d=n,o=we(),o===null&&(l.charCodeAt(n)===45?(o="-",n++):(o=null,v('"-"')),o===null&&(l.charCodeAt(n)===46?(o=".",n++):(o=null,v('"."')),o===null&&(l.charCodeAt(n)===33?(o="!",n++):(o=null,v('"!"')),o===null&&(l.charCodeAt(n)===37?(o="%",n++):(o=null,v('"%"')),o===null&&(l.charCodeAt(n)===42?(o="*",n++):(o=null,v('"*"')),o===null&&(l.charCodeAt(n)===95?(o="_",n++):(o=null,v('"_"')),o===null&&(l.charCodeAt(n)===43?(o="+",n++):(o=null,v('"+"')),o===null&&(l.charCodeAt(n)===96?(o="`",n++):(o=null,v('"`"')),o===null&&(l.charCodeAt(n)===39?(o="'",n++):(o=null,v(`"'"`)),o===null&&(l.charCodeAt(n)===126?(o="~",n++):(o=null,v('"~"')),o===null&&(l.charCodeAt(n)===40?(o="(",n++):(o=null,v('"("')),o===null&&(l.charCodeAt(n)===41?(o=")",n++):(o=null,v('")"')),o===null&&(l.charCodeAt(n)===60?(o="<",n++):(o=null,v('"<"')),o===null&&(l.charCodeAt(n)===62?(o=">",n++):(o=null,v('">"')),o===null&&(l.charCodeAt(n)===58?(o=":",n++):(o=null,v('":"')),o===null&&(l.charCodeAt(n)===92?(o="\\",n++):(o=null,v('"\\\\"')),o===null&&(o=G(),o===null&&(l.charCodeAt(n)===47?(o="/",n++):(o=null,v('"/"')),o===null&&(l.charCodeAt(n)===91?(o="[",n++):(o=null,v('"["')),o===null&&(l.charCodeAt(n)===93?(o="]",n++):(o=null,v('"]"')),o===null&&(l.charCodeAt(n)===63?(o="?",n++):(o=null,v('"?"')),o===null&&(l.charCodeAt(n)===123?(o="{",n++):(o=null,v('"{"')),o===null&&(l.charCodeAt(n)===125?(o="}",n++):(o=null,v('"}"'))))))))))))))))))))))))),o!==null)for(e=[];o!==null;)e.push(o),o=we(),o===null&&(l.charCodeAt(n)===45?(o="-",n++):(o=null,v('"-"')),o===null&&(l.charCodeAt(n)===46?(o=".",n++):(o=null,v('"."')),o===null&&(l.charCodeAt(n)===33?(o="!",n++):(o=null,v('"!"')),o===null&&(l.charCodeAt(n)===37?(o="%",n++):(o=null,v('"%"')),o===null&&(l.charCodeAt(n)===42?(o="*",n++):(o=null,v('"*"')),o===null&&(l.charCodeAt(n)===95?(o="_",n++):(o=null,v('"_"')),o===null&&(l.charCodeAt(n)===43?(o="+",n++):(o=null,v('"+"')),o===null&&(l.charCodeAt(n)===96?(o="`",n++):(o=null,v('"`"')),o===null&&(l.charCodeAt(n)===39?(o="'",n++):(o=null,v(`"'"`)),o===null&&(l.charCodeAt(n)===126?(o="~",n++):(o=null,v('"~"')),o===null&&(l.charCodeAt(n)===40?(o="(",n++):(o=null,v('"("')),o===null&&(l.charCodeAt(n)===41?(o=")",n++):(o=null,v('")"')),o===null&&(l.charCodeAt(n)===60?(o="<",n++):(o=null,v('"<"')),o===null&&(l.charCodeAt(n)===62?(o=">",n++):(o=null,v('">"')),o===null&&(l.charCodeAt(n)===58?(o=":",n++):(o=null,v('":"')),o===null&&(l.charCodeAt(n)===92?(o="\\",n++):(o=null,v('"\\\\"')),o===null&&(o=G(),o===null&&(l.charCodeAt(n)===47?(o="/",n++):(o=null,v('"/"')),o===null&&(l.charCodeAt(n)===91?(o="[",n++):(o=null,v('"["')),o===null&&(l.charCodeAt(n)===93?(o="]",n++):(o=null,v('"]"')),o===null&&(l.charCodeAt(n)===63?(o="?",n++):(o=null,v('"?"')),o===null&&(l.charCodeAt(n)===123?(o="{",n++):(o=null,v('"{"')),o===null&&(l.charCodeAt(n)===125?(o="}",n++):(o=null,v('"}"')))))))))))))))))))))))));else e=null;return e!==null&&(e=function(p){return l.substring(n,p)}(d)),e===null&&(n=d),e}function ye(){var e,o,d,p,T;return p=n,T=n,e=se(),e!==null?(l.charCodeAt(n)===42?(o="*",n++):(o=null,v('"*"')),o!==null?(d=se(),d!==null?e=[e,o,d]:(e=null,n=T)):(e=null,n=T)):(e=null,n=T),e!==null&&(e=function(w){return"*"}()),e===null&&(n=p),e}function ge(){var e,o,d,p,T;return p=n,T=n,e=se(),e!==null?(l.charCodeAt(n)===47?(o="/",n++):(o=null,v('"/"')),o!==null?(d=se(),d!==null?e=[e,o,d]:(e=null,n=T)):(e=null,n=T)):(e=null,n=T),e!==null&&(e=function(w){return"/"}()),e===null&&(n=p),e}function Le(){var e,o,d,p,T;return p=n,T=n,e=se(),e!==null?(l.charCodeAt(n)===61?(o="=",n++):(o=null,v('"="')),o!==null?(d=se(),d!==null?e=[e,o,d]:(e=null,n=T)):(e=null,n=T)):(e=null,n=T),e!==null&&(e=function(w){return"="}()),e===null&&(n=p),e}function et(){var e,o,d,p,T;return p=n,T=n,e=se(),e!==null?(l.charCodeAt(n)===40?(o="(",n++):(o=null,v('"("')),o!==null?(d=se(),d!==null?e=[e,o,d]:(e=null,n=T)):(e=null,n=T)):(e=null,n=T),e!==null&&(e=function(w){return"("}()),e===null&&(n=p),e}function vt(){var e,o,d,p,T;return p=n,T=n,e=se(),e!==null?(l.charCodeAt(n)===41?(o=")",n++):(o=null,v('")"')),o!==null?(d=se(),d!==null?e=[e,o,d]:(e=null,n=T)):(e=null,n=T)):(e=null,n=T),e!==null&&(e=function(w){return")"}()),e===null&&(n=p),e}function xt(){var e,o,d,p;return d=n,p=n,l.charCodeAt(n)===62?(e=">",n++):(e=null,v('">"')),e!==null?(o=se(),o!==null?e=[e,o]:(e=null,n=p)):(e=null,n=p),e!==null&&(e=function(T){return">"}()),e===null&&(n=d),e}function dt(){var e,o,d,p;return d=n,p=n,e=se(),e!==null?(l.charCodeAt(n)===60?(o="<",n++):(o=null,v('"<"')),o!==null?e=[e,o]:(e=null,n=p)):(e=null,n=p),e!==null&&(e=function(T){return"<"}()),e===null&&(n=d),e}function ze(){var e,o,d,p,T;return p=n,T=n,e=se(),e!==null?(l.charCodeAt(n)===44?(o=",",n++):(o=null,v('","')),o!==null?(d=se(),d!==null?e=[e,o,d]:(e=null,n=T)):(e=null,n=T)):(e=null,n=T),e!==null&&(e=function(w){return","}()),e===null&&(n=p),e}function Ye(){var e,o,d,p,T;return p=n,T=n,e=se(),e!==null?(l.charCodeAt(n)===59?(o=";",n++):(o=null,v('";"')),o!==null?(d=se(),d!==null?e=[e,o,d]:(e=null,n=T)):(e=null,n=T)):(e=null,n=T),e!==null&&(e=function(w){return";"}()),e===null&&(n=p),e}function Zt(){var e,o,d,p,T;return p=n,T=n,e=se(),e!==null?(l.charCodeAt(n)===58?(o=":",n++):(o=null,v('":"')),o!==null?(d=se(),d!==null?e=[e,o,d]:(e=null,n=T)):(e=null,n=T)):(e=null,n=T),e!==null&&(e=function(w){return":"}()),e===null&&(n=p),e}function Mt(){var e,o,d,p;return d=n,p=n,e=se(),e!==null?(o=G(),o!==null?e=[e,o]:(e=null,n=p)):(e=null,n=p),e!==null&&(e=function(T){return'"'}()),e===null&&(n=d),e}function nt(){var e,o,d,p;return d=n,p=n,e=G(),e!==null?(o=se(),o!==null?e=[e,o]:(e=null,n=p)):(e=null,n=p),e!==null&&(e=function(T){return'"'}()),e===null&&(n=d),e}function rt(){var e,o,d,p;if(p=n,e=et(),e!==null){for(o=[],d=gt(),d===null&&(d=qe(),d===null&&(d=rt()));d!==null;)o.push(d),d=gt(),d===null&&(d=qe(),d===null&&(d=rt()));o!==null?(d=vt(),d!==null?e=[e,o,d]:(e=null,n=p)):(e=null,n=p)}else e=null,n=p;return e}function gt(){var e;return/^[!-']/.test(l.charAt(n))?(e=l.charAt(n),n++):(e=null,v("[!-']")),e===null&&(/^[*-[]/.test(l.charAt(n))?(e=l.charAt(n),n++):(e=null,v("[*-[]")),e===null&&(/^[\]-~]/.test(l.charAt(n))?(e=l.charAt(n),n++):(e=null,v("[\\]-~]")),e===null&&(e=_e(),e===null&&(e=Z())))),e}function ft(){var e,o,d,p,T,w;if(T=n,w=n,e=se(),e!==null)if(o=G(),o!==null){for(d=[],p=He(),p===null&&(p=qe());p!==null;)d.push(p),p=He(),p===null&&(p=qe());d!==null?(p=G(),p!==null?e=[e,o,d,p]:(e=null,n=w)):(e=null,n=w)}else e=null,n=w;else e=null,n=w;return e!==null&&(e=function(O){return l.substring(n,O)}(T)),e===null&&(n=T),e}function Fe(){var e,o,d,p,T,w;if(T=n,w=n,e=se(),e!==null)if(o=G(),o!==null){for(d=[],p=He(),p===null&&(p=qe());p!==null;)d.push(p),p=He(),p===null&&(p=qe());d!==null?(p=G(),p!==null?e=[e,o,d,p]:(e=null,n=w)):(e=null,n=w)}else e=null,n=w;else e=null,n=w;return e!==null&&(e=function(O){var B=l.substring(n,O).trim();return B.substring(1,B.length-1).replace(/\\([\x00-\x09\x0b-\x0c\x0e-\x7f])/g,"$1")}(T)),e===null&&(n=T),e}function He(){var e;return e=Z(),e===null&&(l.charCodeAt(n)===33?(e="!",n++):(e=null,v('"!"')),e===null&&(/^[#-[]/.test(l.charAt(n))?(e=l.charAt(n),n++):(e=null,v("[#-[]")),e===null&&(/^[\]-~]/.test(l.charAt(n))?(e=l.charAt(n),n++):(e=null,v("[\\]-~]")),e===null&&(e=_e())))),e}function qe(){var e,o,d;return d=n,l.charCodeAt(n)===92?(e="\\",n++):(e=null,v('"\\\\"')),e!==null?(/^[\0-\t]/.test(l.charAt(n))?(o=l.charAt(n),n++):(o=null,v("[\\0-\\t]")),o===null&&(/^[\x0B-\f]/.test(l.charAt(n))?(o=l.charAt(n),n++):(o=null,v("[\\x0B-\\f]")),o===null&&(/^[\x0E-]/.test(l.charAt(n))?(o=l.charAt(n),n++):(o=null,v("[\\x0E-]")))),o!==null?e=[e,o]:(e=null,n=d)):(e=null,n=d),e}function yt(){var e,o,d,p,T,w;return T=n,w=n,e=ns(),e!==null?(l.charCodeAt(n)===58?(o=":",n++):(o=null,v('":"')),o!==null?(d=vs(),d=d!==null?d:"",d!==null?(p=pr(),p!==null?e=[e,o,d,p]:(e=null,n=w)):(e=null,n=w)):(e=null,n=w)):(e=null,n=w),e!==null&&(e=function(O){try{J.uri=new $r(J.scheme,J.user,J.host,J.port),delete J.scheme,delete J.user,delete J.host,delete J.host_type,delete J.port}catch{J=-1}}()),e===null&&(n=T),e}function Ct(){var e,o,d,p,T,w,O,B;return O=n,B=n,e=ns(),e!==null?(l.charCodeAt(n)===58?(o=":",n++):(o=null,v('":"')),o!==null?(d=vs(),d=d!==null?d:"",d!==null?(p=pr(),p!==null?(T=Hr(),T!==null?(w=Br(),w=w!==null?w:"",w!==null?e=[e,o,d,p,T,w]:(e=null,n=B)):(e=null,n=B)):(e=null,n=B)):(e=null,n=B)):(e=null,n=B)):(e=null,n=B),e!==null&&(e=function(ee){try{J.uri=new $r(J.scheme,J.user,J.host,J.port,J.uri_params,J.uri_headers),delete J.scheme,delete J.user,delete J.host,delete J.host_type,delete J.port,delete J.uri_params,u==="SIP_URI"&&(J=J.uri)}catch{J=-1}}()),e===null&&(n=O),e}function ns(){var e;return e=Ut(),e===null&&(e=ar()),e}function Ut(){var e,o;return o=n,l.substr(n,4).toLowerCase()==="sips"?(e=l.substr(n,4),n+=4):(e=null,v('"sips"')),e!==null&&(e=function(d,p){J.scheme=p.toLowerCase()}(o,e)),e===null&&(n=o),e}function ar(){var e,o;return o=n,l.substr(n,3).toLowerCase()==="sip"?(e=l.substr(n,3),n+=3):(e=null,v('"sip"')),e!==null&&(e=function(d,p){J.scheme=p.toLowerCase()}(o,e)),e===null&&(n=o),e}function vs(){var e,o,d,p,T,w;return p=n,T=n,e=Oi(),e!==null?(w=n,l.charCodeAt(n)===58?(o=":",n++):(o=null,v('":"')),o!==null?(d=zn(),d!==null?o=[o,d]:(o=null,n=w)):(o=null,n=w),o=o!==null?o:"",o!==null?(l.charCodeAt(n)===64?(d="@",n++):(d=null,v('"@"')),d!==null?e=[e,o,d]:(e=null,n=T)):(e=null,n=T)):(e=null,n=T),e!==null&&(e=function(O){J.user=decodeURIComponent(l.substring(n-1,O))}(p)),e===null&&(n=p),e}function Oi(){var e,o;if(o=re(),o===null&&(o=Ne(),o===null&&(o=Di())),o!==null)for(e=[];o!==null;)e.push(o),o=re(),o===null&&(o=Ne(),o===null&&(o=Di()));else e=null;return e}function Di(){var e;return l.charCodeAt(n)===38?(e="&",n++):(e=null,v('"&"')),e===null&&(l.charCodeAt(n)===61?(e="=",n++):(e=null,v('"="')),e===null&&(l.charCodeAt(n)===43?(e="+",n++):(e=null,v('"+"')),e===null&&(l.charCodeAt(n)===36?(e="$",n++):(e=null,v('"$"')),e===null&&(l.charCodeAt(n)===44?(e=",",n++):(e=null,v('","')),e===null&&(l.charCodeAt(n)===59?(e=";",n++):(e=null,v('";"')),e===null&&(l.charCodeAt(n)===63?(e="?",n++):(e=null,v('"?"')),e===null&&(l.charCodeAt(n)===47?(e="/",n++):(e=null,v('"/"'))))))))),e}function zn(){var e,o,d;for(d=n,e=[],o=re(),o===null&&(o=Ne(),o===null&&(l.charCodeAt(n)===38?(o="&",n++):(o=null,v('"&"')),o===null&&(l.charCodeAt(n)===61?(o="=",n++):(o=null,v('"="')),o===null&&(l.charCodeAt(n)===43?(o="+",n++):(o=null,v('"+"')),o===null&&(l.charCodeAt(n)===36?(o="$",n++):(o=null,v('"$"')),o===null&&(l.charCodeAt(n)===44?(o=",",n++):(o=null,v('","'))))))));o!==null;)e.push(o),o=re(),o===null&&(o=Ne(),o===null&&(l.charCodeAt(n)===38?(o="&",n++):(o=null,v('"&"')),o===null&&(l.charCodeAt(n)===61?(o="=",n++):(o=null,v('"="')),o===null&&(l.charCodeAt(n)===43?(o="+",n++):(o=null,v('"+"')),o===null&&(l.charCodeAt(n)===36?(o="$",n++):(o=null,v('"$"')),o===null&&(l.charCodeAt(n)===44?(o=",",n++):(o=null,v('","'))))))));return e!==null&&(e=function(p){J.password=l.substring(n,p)}(d)),e===null&&(n=d),e}function pr(){var e,o,d,p,T;return p=n,e=as(),e!==null?(T=n,l.charCodeAt(n)===58?(o=":",n++):(o=null,v('":"')),o!==null?(d=qn(),d!==null?o=[o,d]:(o=null,n=T)):(o=null,n=T),o=o!==null?o:"",o!==null?e=[e,o]:(e=null,n=p)):(e=null,n=p),e}function as(){var e,o;return o=n,e=Pr(),e===null&&(e=lr(),e===null&&(e=Lr())),e!==null&&(e=function(d){return J.host=l.substring(n,d).toLowerCase(),J.host}(o)),e===null&&(n=o),e}function Pr(){var e,o,d,p,T,w;for(p=n,T=n,e=[],w=n,o=Vn(),o!==null?(l.charCodeAt(n)===46?(d=".",n++):(d=null,v('"."')),d!==null?o=[o,d]:(o=null,n=w)):(o=null,n=w);o!==null;)e.push(o),w=n,o=Vn(),o!==null?(l.charCodeAt(n)===46?(d=".",n++):(d=null,v('"."')),d!==null?o=[o,d]:(o=null,n=w)):(o=null,n=w);return e!==null?(o=pn(),o!==null?(l.charCodeAt(n)===46?(d=".",n++):(d=null,v('"."')),d=d!==null?d:"",d!==null?e=[e,o,d]:(e=null,n=T)):(e=null,n=T)):(e=null,n=T),e!==null&&(e=function(O){return J.host_type="domain",l.substring(n,O)}(p)),e===null&&(n=p),e}function Vn(){var e,o,d,p;if(p=n,e=we(),e!==null){for(o=[],d=we(),d===null&&(l.charCodeAt(n)===45?(d="-",n++):(d=null,v('"-"')),d===null&&(l.charCodeAt(n)===95?(d="_",n++):(d=null,v('"_"'))));d!==null;)o.push(d),d=we(),d===null&&(l.charCodeAt(n)===45?(d="-",n++):(d=null,v('"-"')),d===null&&(l.charCodeAt(n)===95?(d="_",n++):(d=null,v('"_"'))));o!==null?e=[e,o]:(e=null,n=p)}else e=null,n=p;return e}function pn(){var e,o,d,p;if(p=n,e=D(),e!==null){for(o=[],d=we(),d===null&&(l.charCodeAt(n)===45?(d="-",n++):(d=null,v('"-"')),d===null&&(l.charCodeAt(n)===95?(d="_",n++):(d=null,v('"_"'))));d!==null;)o.push(d),d=we(),d===null&&(l.charCodeAt(n)===45?(d="-",n++):(d=null,v('"-"')),d===null&&(l.charCodeAt(n)===95?(d="_",n++):(d=null,v('"_"'))));o!==null?e=[e,o]:(e=null,n=p)}else e=null,n=p;return e}function Lr(){var e,o,d,p,T;return p=n,T=n,l.charCodeAt(n)===91?(e="[",n++):(e=null,v('"["')),e!==null?(o=Qe(),o!==null?(l.charCodeAt(n)===93?(d="]",n++):(d=null,v('"]"')),d!==null?e=[e,o,d]:(e=null,n=T)):(e=null,n=T)):(e=null,n=T),e!==null&&(e=function(w){return J.host_type="IPv6",l.substring(n,w)}(p)),e===null&&(n=p),e}function Qe(){var e,o,d,p,T,w,O,B,ee,Pe,At,Es,xr,ce,W,tt;return ce=n,W=n,e=Ve(),e!==null?(l.charCodeAt(n)===58?(o=":",n++):(o=null,v('":"')),o!==null?(d=Ve(),d!==null?(l.charCodeAt(n)===58?(p=":",n++):(p=null,v('":"')),p!==null?(T=Ve(),T!==null?(l.charCodeAt(n)===58?(w=":",n++):(w=null,v('":"')),w!==null?(O=Ve(),O!==null?(l.charCodeAt(n)===58?(B=":",n++):(B=null,v('":"')),B!==null?(ee=Ve(),ee!==null?(l.charCodeAt(n)===58?(Pe=":",n++):(Pe=null,v('":"')),Pe!==null?(At=Ve(),At!==null?(l.charCodeAt(n)===58?(Es=":",n++):(Es=null,v('":"')),Es!==null?(xr=ls(),xr!==null?e=[e,o,d,p,T,w,O,B,ee,Pe,At,Es,xr]:(e=null,n=W)):(e=null,n=W)):(e=null,n=W)):(e=null,n=W)):(e=null,n=W)):(e=null,n=W)):(e=null,n=W)):(e=null,n=W)):(e=null,n=W)):(e=null,n=W)):(e=null,n=W)):(e=null,n=W)):(e=null,n=W),e===null&&(W=n,l.substr(n,2)==="::"?(e="::",n+=2):(e=null,v('"::"')),e!==null?(o=Ve(),o!==null?(l.charCodeAt(n)===58?(d=":",n++):(d=null,v('":"')),d!==null?(p=Ve(),p!==null?(l.charCodeAt(n)===58?(T=":",n++):(T=null,v('":"')),T!==null?(w=Ve(),w!==null?(l.charCodeAt(n)===58?(O=":",n++):(O=null,v('":"')),O!==null?(B=Ve(),B!==null?(l.charCodeAt(n)===58?(ee=":",n++):(ee=null,v('":"')),ee!==null?(Pe=Ve(),Pe!==null?(l.charCodeAt(n)===58?(At=":",n++):(At=null,v('":"')),At!==null?(Es=ls(),Es!==null?e=[e,o,d,p,T,w,O,B,ee,Pe,At,Es]:(e=null,n=W)):(e=null,n=W)):(e=null,n=W)):(e=null,n=W)):(e=null,n=W)):(e=null,n=W)):(e=null,n=W)):(e=null,n=W)):(e=null,n=W)):(e=null,n=W)):(e=null,n=W)):(e=null,n=W),e===null&&(W=n,l.substr(n,2)==="::"?(e="::",n+=2):(e=null,v('"::"')),e!==null?(o=Ve(),o!==null?(l.charCodeAt(n)===58?(d=":",n++):(d=null,v('":"')),d!==null?(p=Ve(),p!==null?(l.charCodeAt(n)===58?(T=":",n++):(T=null,v('":"')),T!==null?(w=Ve(),w!==null?(l.charCodeAt(n)===58?(O=":",n++):(O=null,v('":"')),O!==null?(B=Ve(),B!==null?(l.charCodeAt(n)===58?(ee=":",n++):(ee=null,v('":"')),ee!==null?(Pe=ls(),Pe!==null?e=[e,o,d,p,T,w,O,B,ee,Pe]:(e=null,n=W)):(e=null,n=W)):(e=null,n=W)):(e=null,n=W)):(e=null,n=W)):(e=null,n=W)):(e=null,n=W)):(e=null,n=W)):(e=null,n=W)):(e=null,n=W),e===null&&(W=n,l.substr(n,2)==="::"?(e="::",n+=2):(e=null,v('"::"')),e!==null?(o=Ve(),o!==null?(l.charCodeAt(n)===58?(d=":",n++):(d=null,v('":"')),d!==null?(p=Ve(),p!==null?(l.charCodeAt(n)===58?(T=":",n++):(T=null,v('":"')),T!==null?(w=Ve(),w!==null?(l.charCodeAt(n)===58?(O=":",n++):(O=null,v('":"')),O!==null?(B=ls(),B!==null?e=[e,o,d,p,T,w,O,B]:(e=null,n=W)):(e=null,n=W)):(e=null,n=W)):(e=null,n=W)):(e=null,n=W)):(e=null,n=W)):(e=null,n=W)):(e=null,n=W),e===null&&(W=n,l.substr(n,2)==="::"?(e="::",n+=2):(e=null,v('"::"')),e!==null?(o=Ve(),o!==null?(l.charCodeAt(n)===58?(d=":",n++):(d=null,v('":"')),d!==null?(p=Ve(),p!==null?(l.charCodeAt(n)===58?(T=":",n++):(T=null,v('":"')),T!==null?(w=ls(),w!==null?e=[e,o,d,p,T,w]:(e=null,n=W)):(e=null,n=W)):(e=null,n=W)):(e=null,n=W)):(e=null,n=W)):(e=null,n=W),e===null&&(W=n,l.substr(n,2)==="::"?(e="::",n+=2):(e=null,v('"::"')),e!==null?(o=Ve(),o!==null?(l.charCodeAt(n)===58?(d=":",n++):(d=null,v('":"')),d!==null?(p=ls(),p!==null?e=[e,o,d,p]:(e=null,n=W)):(e=null,n=W)):(e=null,n=W)):(e=null,n=W),e===null&&(W=n,l.substr(n,2)==="::"?(e="::",n+=2):(e=null,v('"::"')),e!==null?(o=ls(),o!==null?e=[e,o]:(e=null,n=W)):(e=null,n=W),e===null&&(W=n,l.substr(n,2)==="::"?(e="::",n+=2):(e=null,v('"::"')),e!==null?(o=Ve(),o!==null?e=[e,o]:(e=null,n=W)):(e=null,n=W),e===null&&(W=n,e=Ve(),e!==null?(l.substr(n,2)==="::"?(o="::",n+=2):(o=null,v('"::"')),o!==null?(d=Ve(),d!==null?(l.charCodeAt(n)===58?(p=":",n++):(p=null,v('":"')),p!==null?(T=Ve(),T!==null?(l.charCodeAt(n)===58?(w=":",n++):(w=null,v('":"')),w!==null?(O=Ve(),O!==null?(l.charCodeAt(n)===58?(B=":",n++):(B=null,v('":"')),B!==null?(ee=Ve(),ee!==null?(l.charCodeAt(n)===58?(Pe=":",n++):(Pe=null,v('":"')),Pe!==null?(At=ls(),At!==null?e=[e,o,d,p,T,w,O,B,ee,Pe,At]:(e=null,n=W)):(e=null,n=W)):(e=null,n=W)):(e=null,n=W)):(e=null,n=W)):(e=null,n=W)):(e=null,n=W)):(e=null,n=W)):(e=null,n=W)):(e=null,n=W)):(e=null,n=W),e===null&&(W=n,e=Ve(),e!==null?(tt=n,l.charCodeAt(n)===58?(o=":",n++):(o=null,v('":"')),o!==null?(d=Ve(),d!==null?o=[o,d]:(o=null,n=tt)):(o=null,n=tt),o=o!==null?o:"",o!==null?(l.substr(n,2)==="::"?(d="::",n+=2):(d=null,v('"::"')),d!==null?(p=Ve(),p!==null?(l.charCodeAt(n)===58?(T=":",n++):(T=null,v('":"')),T!==null?(w=Ve(),w!==null?(l.charCodeAt(n)===58?(O=":",n++):(O=null,v('":"')),O!==null?(B=Ve(),B!==null?(l.charCodeAt(n)===58?(ee=":",n++):(ee=null,v('":"')),ee!==null?(Pe=ls(),Pe!==null?e=[e,o,d,p,T,w,O,B,ee,Pe]:(e=null,n=W)):(e=null,n=W)):(e=null,n=W)):(e=null,n=W)):(e=null,n=W)):(e=null,n=W)):(e=null,n=W)):(e=null,n=W)):(e=null,n=W)):(e=null,n=W),e===null&&(W=n,e=Ve(),e!==null?(tt=n,l.charCodeAt(n)===58?(o=":",n++):(o=null,v('":"')),o!==null?(d=Ve(),d!==null?o=[o,d]:(o=null,n=tt)):(o=null,n=tt),o=o!==null?o:"",o!==null?(tt=n,l.charCodeAt(n)===58?(d=":",n++):(d=null,v('":"')),d!==null?(p=Ve(),p!==null?d=[d,p]:(d=null,n=tt)):(d=null,n=tt),d=d!==null?d:"",d!==null?(l.substr(n,2)==="::"?(p="::",n+=2):(p=null,v('"::"')),p!==null?(T=Ve(),T!==null?(l.charCodeAt(n)===58?(w=":",n++):(w=null,v('":"')),w!==null?(O=Ve(),O!==null?(l.charCodeAt(n)===58?(B=":",n++):(B=null,v('":"')),B!==null?(ee=ls(),ee!==null?e=[e,o,d,p,T,w,O,B,ee]:(e=null,n=W)):(e=null,n=W)):(e=null,n=W)):(e=null,n=W)):(e=null,n=W)):(e=null,n=W)):(e=null,n=W)):(e=null,n=W)):(e=null,n=W),e===null&&(W=n,e=Ve(),e!==null?(tt=n,l.charCodeAt(n)===58?(o=":",n++):(o=null,v('":"')),o!==null?(d=Ve(),d!==null?o=[o,d]:(o=null,n=tt)):(o=null,n=tt),o=o!==null?o:"",o!==null?(tt=n,l.charCodeAt(n)===58?(d=":",n++):(d=null,v('":"')),d!==null?(p=Ve(),p!==null?d=[d,p]:(d=null,n=tt)):(d=null,n=tt),d=d!==null?d:"",d!==null?(tt=n,l.charCodeAt(n)===58?(p=":",n++):(p=null,v('":"')),p!==null?(T=Ve(),T!==null?p=[p,T]:(p=null,n=tt)):(p=null,n=tt),p=p!==null?p:"",p!==null?(l.substr(n,2)==="::"?(T="::",n+=2):(T=null,v('"::"')),T!==null?(w=Ve(),w!==null?(l.charCodeAt(n)===58?(O=":",n++):(O=null,v('":"')),O!==null?(B=ls(),B!==null?e=[e,o,d,p,T,w,O,B]:(e=null,n=W)):(e=null,n=W)):(e=null,n=W)):(e=null,n=W)):(e=null,n=W)):(e=null,n=W)):(e=null,n=W)):(e=null,n=W),e===null&&(W=n,e=Ve(),e!==null?(tt=n,l.charCodeAt(n)===58?(o=":",n++):(o=null,v('":"')),o!==null?(d=Ve(),d!==null?o=[o,d]:(o=null,n=tt)):(o=null,n=tt),o=o!==null?o:"",o!==null?(tt=n,l.charCodeAt(n)===58?(d=":",n++):(d=null,v('":"')),d!==null?(p=Ve(),p!==null?d=[d,p]:(d=null,n=tt)):(d=null,n=tt),d=d!==null?d:"",d!==null?(tt=n,l.charCodeAt(n)===58?(p=":",n++):(p=null,v('":"')),p!==null?(T=Ve(),T!==null?p=[p,T]:(p=null,n=tt)):(p=null,n=tt),p=p!==null?p:"",p!==null?(tt=n,l.charCodeAt(n)===58?(T=":",n++):(T=null,v('":"')),T!==null?(w=Ve(),w!==null?T=[T,w]:(T=null,n=tt)):(T=null,n=tt),T=T!==null?T:"",T!==null?(l.substr(n,2)==="::"?(w="::",n+=2):(w=null,v('"::"')),w!==null?(O=ls(),O!==null?e=[e,o,d,p,T,w,O]:(e=null,n=W)):(e=null,n=W)):(e=null,n=W)):(e=null,n=W)):(e=null,n=W)):(e=null,n=W)):(e=null,n=W),e===null&&(W=n,e=Ve(),e!==null?(tt=n,l.charCodeAt(n)===58?(o=":",n++):(o=null,v('":"')),o!==null?(d=Ve(),d!==null?o=[o,d]:(o=null,n=tt)):(o=null,n=tt),o=o!==null?o:"",o!==null?(tt=n,l.charCodeAt(n)===58?(d=":",n++):(d=null,v('":"')),d!==null?(p=Ve(),p!==null?d=[d,p]:(d=null,n=tt)):(d=null,n=tt),d=d!==null?d:"",d!==null?(tt=n,l.charCodeAt(n)===58?(p=":",n++):(p=null,v('":"')),p!==null?(T=Ve(),T!==null?p=[p,T]:(p=null,n=tt)):(p=null,n=tt),p=p!==null?p:"",p!==null?(tt=n,l.charCodeAt(n)===58?(T=":",n++):(T=null,v('":"')),T!==null?(w=Ve(),w!==null?T=[T,w]:(T=null,n=tt)):(T=null,n=tt),T=T!==null?T:"",T!==null?(tt=n,l.charCodeAt(n)===58?(w=":",n++):(w=null,v('":"')),w!==null?(O=Ve(),O!==null?w=[w,O]:(w=null,n=tt)):(w=null,n=tt),w=w!==null?w:"",w!==null?(l.substr(n,2)==="::"?(O="::",n+=2):(O=null,v('"::"')),O!==null?(B=Ve(),B!==null?e=[e,o,d,p,T,w,O,B]:(e=null,n=W)):(e=null,n=W)):(e=null,n=W)):(e=null,n=W)):(e=null,n=W)):(e=null,n=W)):(e=null,n=W)):(e=null,n=W),e===null&&(W=n,e=Ve(),e!==null?(tt=n,l.charCodeAt(n)===58?(o=":",n++):(o=null,v('":"')),o!==null?(d=Ve(),d!==null?o=[o,d]:(o=null,n=tt)):(o=null,n=tt),o=o!==null?o:"",o!==null?(tt=n,l.charCodeAt(n)===58?(d=":",n++):(d=null,v('":"')),d!==null?(p=Ve(),p!==null?d=[d,p]:(d=null,n=tt)):(d=null,n=tt),d=d!==null?d:"",d!==null?(tt=n,l.charCodeAt(n)===58?(p=":",n++):(p=null,v('":"')),p!==null?(T=Ve(),T!==null?p=[p,T]:(p=null,n=tt)):(p=null,n=tt),p=p!==null?p:"",p!==null?(tt=n,l.charCodeAt(n)===58?(T=":",n++):(T=null,v('":"')),T!==null?(w=Ve(),w!==null?T=[T,w]:(T=null,n=tt)):(T=null,n=tt),T=T!==null?T:"",T!==null?(tt=n,l.charCodeAt(n)===58?(w=":",n++):(w=null,v('":"')),w!==null?(O=Ve(),O!==null?w=[w,O]:(w=null,n=tt)):(w=null,n=tt),w=w!==null?w:"",w!==null?(tt=n,l.charCodeAt(n)===58?(O=":",n++):(O=null,v('":"')),O!==null?(B=Ve(),B!==null?O=[O,B]:(O=null,n=tt)):(O=null,n=tt),O=O!==null?O:"",O!==null?(l.substr(n,2)==="::"?(B="::",n+=2):(B=null,v('"::"')),B!==null?e=[e,o,d,p,T,w,O,B]:(e=null,n=W)):(e=null,n=W)):(e=null,n=W)):(e=null,n=W)):(e=null,n=W)):(e=null,n=W)):(e=null,n=W)):(e=null,n=W))))))))))))))),e!==null&&(e=function(Yu){return J.host_type="IPv6",l.substring(n,Yu)}(ce)),e===null&&(n=ce),e}function Ve(){var e,o,d,p,T;return T=n,e=H(),e!==null?(o=H(),o=o!==null?o:"",o!==null?(d=H(),d=d!==null?d:"",d!==null?(p=H(),p=p!==null?p:"",p!==null?e=[e,o,d,p]:(e=null,n=T)):(e=null,n=T)):(e=null,n=T)):(e=null,n=T),e}function ls(){var e,o,d,p;return p=n,e=Ve(),e!==null?(l.charCodeAt(n)===58?(o=":",n++):(o=null,v('":"')),o!==null?(d=Ve(),d!==null?e=[e,o,d]:(e=null,n=p)):(e=null,n=p)):(e=null,n=p),e===null&&(e=lr()),e}function lr(){var e,o,d,p,T,w,O,B,ee;return B=n,ee=n,e=os(),e!==null?(l.charCodeAt(n)===46?(o=".",n++):(o=null,v('"."')),o!==null?(d=os(),d!==null?(l.charCodeAt(n)===46?(p=".",n++):(p=null,v('"."')),p!==null?(T=os(),T!==null?(l.charCodeAt(n)===46?(w=".",n++):(w=null,v('"."')),w!==null?(O=os(),O!==null?e=[e,o,d,p,T,w,O]:(e=null,n=ee)):(e=null,n=ee)):(e=null,n=ee)):(e=null,n=ee)):(e=null,n=ee)):(e=null,n=ee)):(e=null,n=ee),e!==null&&(e=function(Pe){return J.host_type="IPv4",l.substring(n,Pe)}(B)),e===null&&(n=B),e}function os(){var e,o,d,p;return p=n,l.substr(n,2)==="25"?(e="25",n+=2):(e=null,v('"25"')),e!==null?(/^[0-5]/.test(l.charAt(n))?(o=l.charAt(n),n++):(o=null,v("[0-5]")),o!==null?e=[e,o]:(e=null,n=p)):(e=null,n=p),e===null&&(p=n,l.charCodeAt(n)===50?(e="2",n++):(e=null,v('"2"')),e!==null?(/^[0-4]/.test(l.charAt(n))?(o=l.charAt(n),n++):(o=null,v("[0-4]")),o!==null?(d=R(),d!==null?e=[e,o,d]:(e=null,n=p)):(e=null,n=p)):(e=null,n=p),e===null&&(p=n,l.charCodeAt(n)===49?(e="1",n++):(e=null,v('"1"')),e!==null?(o=R(),o!==null?(d=R(),d!==null?e=[e,o,d]:(e=null,n=p)):(e=null,n=p)):(e=null,n=p),e===null&&(p=n,/^[1-9]/.test(l.charAt(n))?(e=l.charAt(n),n++):(e=null,v("[1-9]")),e!==null?(o=R(),o!==null?e=[e,o]:(e=null,n=p)):(e=null,n=p),e===null&&(e=R())))),e}function qn(){var e,o,d,p,T,w,O;return w=n,O=n,e=R(),e=e!==null?e:"",e!==null?(o=R(),o=o!==null?o:"",o!==null?(d=R(),d=d!==null?d:"",d!==null?(p=R(),p=p!==null?p:"",p!==null?(T=R(),T=T!==null?T:"",T!==null?e=[e,o,d,p,T]:(e=null,n=O)):(e=null,n=O)):(e=null,n=O)):(e=null,n=O)):(e=null,n=O),e!==null&&(e=function(B,ee){return ee=parseInt(ee.join("")),J.port=ee,ee}(w,e)),e===null&&(n=w),e}function Hr(){var e,o,d,p;for(e=[],p=n,l.charCodeAt(n)===59?(o=";",n++):(o=null,v('";"')),o!==null?(d=jn(),d!==null?o=[o,d]:(o=null,n=p)):(o=null,n=p);o!==null;)e.push(o),p=n,l.charCodeAt(n)===59?(o=";",n++):(o=null,v('";"')),o!==null?(d=jn(),d!==null?o=[o,d]:(o=null,n=p)):(o=null,n=p);return e}function jn(){var e;return e=ki(),e===null&&(e=Gn(),e===null&&(e=Ni(),e===null&&(e=Wn(),e===null&&(e=Mi(),e===null&&(e=Kn(),e===null&&(e=Ui())))))),e}function ki(){var e,o,d,p;return d=n,p=n,l.substr(n,10).toLowerCase()==="transport="?(e=l.substr(n,10),n+=10):(e=null,v('"transport="')),e!==null?(l.substr(n,3).toLowerCase()==="udp"?(o=l.substr(n,3),n+=3):(o=null,v('"udp"')),o===null&&(l.substr(n,3).toLowerCase()==="tcp"?(o=l.substr(n,3),n+=3):(o=null,v('"tcp"')),o===null&&(l.substr(n,4).toLowerCase()==="sctp"?(o=l.substr(n,4),n+=4):(o=null,v('"sctp"')),o===null&&(l.substr(n,3).toLowerCase()==="tls"?(o=l.substr(n,3),n+=3):(o=null,v('"tls"')),o===null&&(o=oe())))),o!==null?e=[e,o]:(e=null,n=p)):(e=null,n=p),e!==null&&(e=function(T,w){J.uri_params||(J.uri_params={}),J.uri_params.transport=w.toLowerCase()}(d,e[1])),e===null&&(n=d),e}function Gn(){var e,o,d,p;return d=n,p=n,l.substr(n,5).toLowerCase()==="user="?(e=l.substr(n,5),n+=5):(e=null,v('"user="')),e!==null?(l.substr(n,5).toLowerCase()==="phone"?(o=l.substr(n,5),n+=5):(o=null,v('"phone"')),o===null&&(l.substr(n,2).toLowerCase()==="ip"?(o=l.substr(n,2),n+=2):(o=null,v('"ip"')),o===null&&(o=oe())),o!==null?e=[e,o]:(e=null,n=p)):(e=null,n=p),e!==null&&(e=function(T,w){J.uri_params||(J.uri_params={}),J.uri_params.user=w.toLowerCase()}(d,e[1])),e===null&&(n=d),e}function Ni(){var e,o,d,p;return d=n,p=n,l.substr(n,7).toLowerCase()==="method="?(e=l.substr(n,7),n+=7):(e=null,v('"method="')),e!==null?(o=Sn(),o!==null?e=[e,o]:(e=null,n=p)):(e=null,n=p),e!==null&&(e=function(T,w){J.uri_params||(J.uri_params={}),J.uri_params.method=w}(d,e[1])),e===null&&(n=d),e}function Wn(){var e,o,d,p;return d=n,p=n,l.substr(n,4).toLowerCase()==="ttl="?(e=l.substr(n,4),n+=4):(e=null,v('"ttl="')),e!==null?(o=aa(),o!==null?e=[e,o]:(e=null,n=p)):(e=null,n=p),e!==null&&(e=function(T,w){J.params||(J.params={}),J.params.ttl=w}(d,e[1])),e===null&&(n=d),e}function Mi(){var e,o,d,p;return d=n,p=n,l.substr(n,6).toLowerCase()==="maddr="?(e=l.substr(n,6),n+=6):(e=null,v('"maddr="')),e!==null?(o=as(),o!==null?e=[e,o]:(e=null,n=p)):(e=null,n=p),e!==null&&(e=function(T,w){J.uri_params||(J.uri_params={}),J.uri_params.maddr=w}(d,e[1])),e===null&&(n=d),e}function Kn(){var e,o,d,p,T,w;return p=n,T=n,l.substr(n,2).toLowerCase()==="lr"?(e=l.substr(n,2),n+=2):(e=null,v('"lr"')),e!==null?(w=n,l.charCodeAt(n)===61?(o="=",n++):(o=null,v('"="')),o!==null?(d=oe(),d!==null?o=[o,d]:(o=null,n=w)):(o=null,n=w),o=o!==null?o:"",o!==null?e=[e,o]:(e=null,n=T)):(e=null,n=T),e!==null&&(e=function(O){J.uri_params||(J.uri_params={}),J.uri_params.lr=void 0}()),e===null&&(n=p),e}function Ui(){var e,o,d,p,T,w;return p=n,T=n,e=Yn(),e!==null?(w=n,l.charCodeAt(n)===61?(o="=",n++):(o=null,v('"="')),o!==null?(d=Ar(),d!==null?o=[o,d]:(o=null,n=w)):(o=null,n=w),o=o!==null?o:"",o!==null?e=[e,o]:(e=null,n=T)):(e=null,n=T),e!==null&&(e=function(O,B,ee){J.uri_params||(J.uri_params={}),typeof ee>"u"?ee=void 0:ee=ee[1],J.uri_params[B.toLowerCase()]=ee}(p,e[0],e[1])),e===null&&(n=p),e}function Yn(){var e,o,d;if(d=n,o=mr(),o!==null)for(e=[];o!==null;)e.push(o),o=mr();else e=null;return e!==null&&(e=function(p,T){return T.join("")}(d,e)),e===null&&(n=d),e}function Ar(){var e,o,d;if(d=n,o=mr(),o!==null)for(e=[];o!==null;)e.push(o),o=mr();else e=null;return e!==null&&(e=function(p,T){return T.join("")}(d,e)),e===null&&(n=d),e}function mr(){var e;return e=Fr(),e===null&&(e=re(),e===null&&(e=Ne())),e}function Fr(){var e;return l.charCodeAt(n)===91?(e="[",n++):(e=null,v('"["')),e===null&&(l.charCodeAt(n)===93?(e="]",n++):(e=null,v('"]"')),e===null&&(l.charCodeAt(n)===47?(e="/",n++):(e=null,v('"/"')),e===null&&(l.charCodeAt(n)===58?(e=":",n++):(e=null,v('":"')),e===null&&(l.charCodeAt(n)===38?(e="&",n++):(e=null,v('"&"')),e===null&&(l.charCodeAt(n)===43?(e="+",n++):(e=null,v('"+"')),e===null&&(l.charCodeAt(n)===36?(e="$",n++):(e=null,v('"$"')))))))),e}function Br(){var e,o,d,p,T,w,O;if(w=n,l.charCodeAt(n)===63?(e="?",n++):(e=null,v('"?"')),e!==null)if(o=mn(),o!==null){for(d=[],O=n,l.charCodeAt(n)===38?(p="&",n++):(p=null,v('"&"')),p!==null?(T=mn(),T!==null?p=[p,T]:(p=null,n=O)):(p=null,n=O);p!==null;)d.push(p),O=n,l.charCodeAt(n)===38?(p="&",n++):(p=null,v('"&"')),p!==null?(T=mn(),T!==null?p=[p,T]:(p=null,n=O)):(p=null,n=O);d!==null?e=[e,o,d]:(e=null,n=w)}else e=null,n=w;else e=null,n=w;return e}function mn(){var e,o,d,p,T;return p=n,T=n,e=Pi(),e!==null?(l.charCodeAt(n)===61?(o="=",n++):(o=null,v('"="')),o!==null?(d=zr(),d!==null?e=[e,o,d]:(e=null,n=T)):(e=null,n=T)):(e=null,n=T),e!==null&&(e=function(w,O,B){O=O.join("").toLowerCase(),B=B.join(""),J.uri_headers||(J.uri_headers={}),J.uri_headers[O]?J.uri_headers[O].push(B):J.uri_headers[O]=[B]}(p,e[0],e[2])),e===null&&(n=p),e}function Pi(){var e,o;if(o=Vr(),o===null&&(o=re(),o===null&&(o=Ne())),o!==null)for(e=[];o!==null;)e.push(o),o=Vr(),o===null&&(o=re(),o===null&&(o=Ne()));else e=null;return e}function zr(){var e,o;for(e=[],o=Vr(),o===null&&(o=re(),o===null&&(o=Ne()));o!==null;)e.push(o),o=Vr(),o===null&&(o=re(),o===null&&(o=Ne()));return e}function Vr(){var e;return l.charCodeAt(n)===91?(e="[",n++):(e=null,v('"["')),e===null&&(l.charCodeAt(n)===93?(e="]",n++):(e=null,v('"]"')),e===null&&(l.charCodeAt(n)===47?(e="/",n++):(e=null,v('"/"')),e===null&&(l.charCodeAt(n)===63?(e="?",n++):(e=null,v('"?"')),e===null&&(l.charCodeAt(n)===58?(e=":",n++):(e=null,v('":"')),e===null&&(l.charCodeAt(n)===43?(e="+",n++):(e=null,v('"+"')),e===null&&(l.charCodeAt(n)===36?(e="$",n++):(e=null,v('"$"')))))))),e}function kt(){var e;return e=ei(),e===null&&(e=gr()),e}function gr(){var e,o,d,p,T,w;return w=n,e=Sn(),e!==null?(o=te(),o!==null?(d=bs(),d!==null?(p=te(),p!==null?(T=Yr(),T!==null?e=[e,o,d,p,T]:(e=null,n=w)):(e=null,n=w)):(e=null,n=w)):(e=null,n=w)):(e=null,n=w),e}function bs(){var e;return e=Ct(),e===null&&(e=qr()),e}function qr(){var e,o,d,p;return p=n,e=Da(),e!==null?(l.charCodeAt(n)===58?(o=":",n++):(o=null,v('":"')),o!==null?(d=It(),d===null&&(d=vn()),d!==null?e=[e,o,d]:(e=null,n=p)):(e=null,n=p)):(e=null,n=p),e}function It(){var e,o,d,p,T;return p=n,e=jr(),e===null&&(e=gn()),e!==null?(T=n,l.charCodeAt(n)===63?(o="?",n++):(o=null,v('"?"')),o!==null?(d=Kr(),d!==null?o=[o,d]:(o=null,n=T)):(o=null,n=T),o=o!==null?o:"",o!==null?e=[e,o]:(e=null,n=p)):(e=null,n=p),e}function jr(){var e,o,d,p;return p=n,l.substr(n,2)==="//"?(e="//",n+=2):(e=null,v('"//"')),e!==null?(o=vr(),o!==null?(d=gn(),d=d!==null?d:"",d!==null?e=[e,o,d]:(e=null,n=p)):(e=null,n=p)):(e=null,n=p),e}function gn(){var e,o,d;return d=n,l.charCodeAt(n)===47?(e="/",n++):(e=null,v('"/"')),e!==null?(o=yn(),o!==null?e=[e,o]:(e=null,n=d)):(e=null,n=d),e}function vn(){var e,o,d,p;if(p=n,e=Li(),e!==null){for(o=[],d=Gr();d!==null;)o.push(d),d=Gr();o!==null?e=[e,o]:(e=null,n=p)}else e=null,n=p;return e}function Gr(){var e;return e=Q(),e===null&&(e=re(),e===null&&(e=Ne())),e}function Li(){var e;return e=re(),e===null&&(e=Ne(),e===null&&(l.charCodeAt(n)===59?(e=";",n++):(e=null,v('";"')),e===null&&(l.charCodeAt(n)===63?(e="?",n++):(e=null,v('"?"')),e===null&&(l.charCodeAt(n)===58?(e=":",n++):(e=null,v('":"')),e===null&&(l.charCodeAt(n)===64?(e="@",n++):(e=null,v('"@"')),e===null&&(l.charCodeAt(n)===38?(e="&",n++):(e=null,v('"&"')),e===null&&(l.charCodeAt(n)===61?(e="=",n++):(e=null,v('"="')),e===null&&(l.charCodeAt(n)===43?(e="+",n++):(e=null,v('"+"')),e===null&&(l.charCodeAt(n)===36?(e="$",n++):(e=null,v('"$"')),e===null&&(l.charCodeAt(n)===44?(e=",",n++):(e=null,v('","')))))))))))),e}function yn(){var e,o,d,p,T,w;if(T=n,e=or(),e!==null){for(o=[],w=n,l.charCodeAt(n)===47?(d="/",n++):(d=null,v('"/"')),d!==null?(p=or(),p!==null?d=[d,p]:(d=null,n=w)):(d=null,n=w);d!==null;)o.push(d),w=n,l.charCodeAt(n)===47?(d="/",n++):(d=null,v('"/"')),d!==null?(p=or(),p!==null?d=[d,p]:(d=null,n=w)):(d=null,n=w);o!==null?e=[e,o]:(e=null,n=T)}else e=null,n=T;return e}function or(){var e,o,d,p,T,w;for(T=n,e=[],o=Wr();o!==null;)e.push(o),o=Wr();if(e!==null){for(o=[],w=n,l.charCodeAt(n)===59?(d=";",n++):(d=null,v('";"')),d!==null?(p=Ir(),p!==null?d=[d,p]:(d=null,n=w)):(d=null,n=w);d!==null;)o.push(d),w=n,l.charCodeAt(n)===59?(d=";",n++):(d=null,v('";"')),d!==null?(p=Ir(),p!==null?d=[d,p]:(d=null,n=w)):(d=null,n=w);o!==null?e=[e,o]:(e=null,n=T)}else e=null,n=T;return e}function Ir(){var e,o;for(e=[],o=Wr();o!==null;)e.push(o),o=Wr();return e}function Wr(){var e;return e=re(),e===null&&(e=Ne(),e===null&&(l.charCodeAt(n)===58?(e=":",n++):(e=null,v('":"')),e===null&&(l.charCodeAt(n)===64?(e="@",n++):(e=null,v('"@"')),e===null&&(l.charCodeAt(n)===38?(e="&",n++):(e=null,v('"&"')),e===null&&(l.charCodeAt(n)===61?(e="=",n++):(e=null,v('"="')),e===null&&(l.charCodeAt(n)===43?(e="+",n++):(e=null,v('"+"')),e===null&&(l.charCodeAt(n)===36?(e="$",n++):(e=null,v('"$"')),e===null&&(l.charCodeAt(n)===44?(e=",",n++):(e=null,v('","')))))))))),e}function Da(){var e,o,d,p,T;if(p=n,T=n,e=D(),e!==null){for(o=[],d=D(),d===null&&(d=R(),d===null&&(l.charCodeAt(n)===43?(d="+",n++):(d=null,v('"+"')),d===null&&(l.charCodeAt(n)===45?(d="-",n++):(d=null,v('"-"')),d===null&&(l.charCodeAt(n)===46?(d=".",n++):(d=null,v('"."'))))));d!==null;)o.push(d),d=D(),d===null&&(d=R(),d===null&&(l.charCodeAt(n)===43?(d="+",n++):(d=null,v('"+"')),d===null&&(l.charCodeAt(n)===45?(d="-",n++):(d=null,v('"-"')),d===null&&(l.charCodeAt(n)===46?(d=".",n++):(d=null,v('"."'))))));o!==null?e=[e,o]:(e=null,n=T)}else e=null,n=T;return e!==null&&(e=function(w){J.scheme=l.substring(n,w)}(p)),e===null&&(n=p),e}function vr(){var e;return e=Ys(),e===null&&(e=yr()),e}function Ys(){var e,o,d,p;return d=n,p=n,e=vs(),e!==null?(l.charCodeAt(n)===64?(o="@",n++):(o=null,v('"@"')),o!==null?e=[e,o]:(e=null,n=p)):(e=null,n=p),e=e!==null?e:"",e!==null?(o=pr(),o!==null?e=[e,o]:(e=null,n=d)):(e=null,n=d),e=e!==null?e:"",e}function yr(){var e,o;if(o=re(),o===null&&(o=Ne(),o===null&&(l.charCodeAt(n)===36?(o="$",n++):(o=null,v('"$"')),o===null&&(l.charCodeAt(n)===44?(o=",",n++):(o=null,v('","')),o===null&&(l.charCodeAt(n)===59?(o=";",n++):(o=null,v('";"')),o===null&&(l.charCodeAt(n)===58?(o=":",n++):(o=null,v('":"')),o===null&&(l.charCodeAt(n)===64?(o="@",n++):(o=null,v('"@"')),o===null&&(l.charCodeAt(n)===38?(o="&",n++):(o=null,v('"&"')),o===null&&(l.charCodeAt(n)===61?(o="=",n++):(o=null,v('"="')),o===null&&(l.charCodeAt(n)===43?(o="+",n++):(o=null,v('"+"'))))))))))),o!==null)for(e=[];o!==null;)e.push(o),o=re(),o===null&&(o=Ne(),o===null&&(l.charCodeAt(n)===36?(o="$",n++):(o=null,v('"$"')),o===null&&(l.charCodeAt(n)===44?(o=",",n++):(o=null,v('","')),o===null&&(l.charCodeAt(n)===59?(o=";",n++):(o=null,v('";"')),o===null&&(l.charCodeAt(n)===58?(o=":",n++):(o=null,v('":"')),o===null&&(l.charCodeAt(n)===64?(o="@",n++):(o=null,v('"@"')),o===null&&(l.charCodeAt(n)===38?(o="&",n++):(o=null,v('"&"')),o===null&&(l.charCodeAt(n)===61?(o="=",n++):(o=null,v('"="')),o===null&&(l.charCodeAt(n)===43?(o="+",n++):(o=null,v('"+"')))))))))));else e=null;return e}function Kr(){var e,o;for(e=[],o=Gr();o!==null;)e.push(o),o=Gr();return e}function Yr(){var e,o,d,p,T,w,O,B;if(O=n,B=n,l.substr(n,3).toLowerCase()==="sip"?(e=l.substr(n,3),n+=3):(e=null,v('"SIP"')),e!==null)if(l.charCodeAt(n)===47?(o="/",n++):(o=null,v('"/"')),o!==null){if(p=R(),p!==null)for(d=[];p!==null;)d.push(p),p=R();else d=null;if(d!==null)if(l.charCodeAt(n)===46?(p=".",n++):(p=null,v('"."')),p!==null){if(w=R(),w!==null)for(T=[];w!==null;)T.push(w),w=R();else T=null;T!==null?e=[e,o,d,p,T]:(e=null,n=B)}else e=null,n=B;else e=null,n=B}else e=null,n=B;else e=null,n=B;return e!==null&&(e=function(ee){J.sip_version=l.substring(n,ee)}(O)),e===null&&(n=O),e}function Jn(){var e;return l.substr(n,6)==="INVITE"?(e="INVITE",n+=6):(e=null,v('"INVITE"')),e}function Qn(){var e;return l.substr(n,3)==="ACK"?(e="ACK",n+=3):(e=null,v('"ACK"')),e}function Xn(){var e;return l.substr(n,7)==="OPTIONS"?(e="OPTIONS",n+=7):(e=null,v('"OPTIONS"')),e}function ot(){var e;return l.substr(n,3)==="BYE"?(e="BYE",n+=3):(e=null,v('"BYE"')),e}function Zn(){var e;return l.substr(n,6)==="CANCEL"?(e="CANCEL",n+=6):(e=null,v('"CANCEL"')),e}function Hi(){var e;return l.substr(n,8)==="REGISTER"?(e="REGISTER",n+=8):(e=null,v('"REGISTER"')),e}function Fi(){var e;return l.substr(n,9)==="SUBSCRIBE"?(e="SUBSCRIBE",n+=9):(e=null,v('"SUBSCRIBE"')),e}function Bi(){var e;return l.substr(n,6)==="NOTIFY"?(e="NOTIFY",n+=6):(e=null,v('"NOTIFY"')),e}function Tn(){var e;return l.substr(n,5)==="REFER"?(e="REFER",n+=5):(e=null,v('"REFER"')),e}function Sn(){var e,o;return o=n,e=Jn(),e===null&&(e=Qn(),e===null&&(e=Xn(),e===null&&(e=ot(),e===null&&(e=Zn(),e===null&&(e=Hi(),e===null&&(e=Fi(),e===null&&(e=Bi(),e===null&&(e=Tn(),e===null&&(e=oe()))))))))),e!==null&&(e=function(d){return J.method=l.substring(n,d),J.method}(o)),e===null&&(n=o),e}function ei(){var e,o,d,p,T,w;return w=n,e=Yr(),e!==null?(o=te(),o!==null?(d=zi(),d!==null?(p=te(),p!==null?(T=ur(),T!==null?e=[e,o,d,p,T]:(e=null,n=w)):(e=null,n=w)):(e=null,n=w)):(e=null,n=w)):(e=null,n=w),e}function zi(){var e,o;return o=n,e=bt(),e!==null&&(e=function(d,p){J.status_code=parseInt(p.join(""))}(o,e)),e===null&&(n=o),e}function bt(){var e,o,d,p;return p=n,e=R(),e!==null?(o=R(),o!==null?(d=R(),d!==null?e=[e,o,d]:(e=null,n=p)):(e=null,n=p)):(e=null,n=p),e}function ur(){var e,o,d;for(d=n,e=[],o=Q(),o===null&&(o=re(),o===null&&(o=Ne(),o===null&&(o=_e(),o===null&&(o=Ae(),o===null&&(o=te(),o===null&&(o=X()))))));o!==null;)e.push(o),o=Q(),o===null&&(o=re(),o===null&&(o=Ne(),o===null&&(o=_e(),o===null&&(o=Ae(),o===null&&(o=te(),o===null&&(o=X()))))));return e!==null&&(e=function(p){J.reason_phrase=l.substring(n,p)}(d)),e===null&&(n=d),e}function Sl(){var e,o,d,p,T,w;if(T=n,e=Zr(),e!==null){for(o=[],w=n,d=ze(),d!==null?(p=Zr(),p!==null?d=[d,p]:(d=null,n=w)):(d=null,n=w);d!==null;)o.push(d),w=n,d=ze(),d!==null?(p=Zr(),p!==null?d=[d,p]:(d=null,n=w)):(d=null,n=w);o!==null?e=[e,o]:(e=null,n=T)}else e=null,n=T;return e}function bn(){var e,o,d,p,T,w;return p=n,T=n,e=Re(),e!==null?(w=n,l.charCodeAt(n)===64?(o="@",n++):(o=null,v('"@"')),o!==null?(d=Re(),d!==null?o=[o,d]:(o=null,n=w)):(o=null,n=w),o=o!==null?o:"",o!==null?e=[e,o]:(e=null,n=T)):(e=null,n=T),e!==null&&(e=function(O){J=l.substring(n,O)}(p)),e===null&&(n=p),e}function ie(){var e,o,d,p,T,w,O;if(T=n,e=ye(),e===null)if(w=n,e=Ls(),e!==null){for(o=[],O=n,d=ze(),d!==null?(p=Ls(),p!==null?d=[d,p]:(d=null,n=O)):(d=null,n=O);d!==null;)o.push(d),O=n,d=ze(),d!==null?(p=Ls(),p!==null?d=[d,p]:(d=null,n=O)):(d=null,n=O);o!==null?e=[e,o]:(e=null,n=w)}else e=null,n=w;return e!==null&&(e=function(B){var ee,Pe;for(Pe=J.multi_header.length,ee=0;ee<Pe;ee++)if(J.multi_header[ee].parsed===null){J=null;break}J!==null?J=J.multi_header:J=-1}()),e===null&&(n=T),e}function Ls(){var e,o,d,p,T,w,O;if(T=n,w=n,e=yt(),e===null&&(e=Js()),e!==null){for(o=[],O=n,d=Ye(),d!==null?(p=ti(),p!==null?d=[d,p]:(d=null,n=O)):(d=null,n=O);d!==null;)o.push(d),O=n,d=Ye(),d!==null?(p=ti(),p!==null?d=[d,p]:(d=null,n=O)):(d=null,n=O);o!==null?e=[e,o]:(e=null,n=w)}else e=null,n=w;return e!==null&&(e=function(B){var ee;J.multi_header||(J.multi_header=[]);try{ee=new K(J.uri,J.display_name,J.params),delete J.uri,delete J.display_name,delete J.params}catch{ee=null}J.multi_header.push({possition:n,offset:B,parsed:ee})}(T)),e===null&&(n=T),e}function Js(){var e,o,d,p,T;return T=n,e=Jr(),e=e!==null?e:"",e!==null?(o=dt(),o!==null?(d=Ct(),d!==null?(p=xt(),p!==null?e=[e,o,d,p]:(e=null,n=T)):(e=null,n=T)):(e=null,n=T)):(e=null,n=T),e}function Jr(){var e,o,d,p,T,w,O;if(T=n,w=n,e=oe(),e!==null){for(o=[],O=n,d=Z(),d!==null?(p=oe(),p!==null?d=[d,p]:(d=null,n=O)):(d=null,n=O);d!==null;)o.push(d),O=n,d=Z(),d!==null?(p=oe(),p!==null?d=[d,p]:(d=null,n=O)):(d=null,n=O);o!==null?e=[e,o]:(e=null,n=w)}else e=null,n=w;return e===null&&(e=Fe()),e!==null&&(e=function(B,ee){typeof ee=="string"?J.display_name=ee:J.display_name=ee[1].reduce(function(Pe,At){return Pe+At[0]+At[1]},ee[0])}(T,e)),e===null&&(n=T),e}function ti(){var e;return e=ht(),e===null&&(e=cr(),e===null&&(e=qt())),e}function ht(){var e,o,d,p,T;return p=n,T=n,l.substr(n,1).toLowerCase()==="q"?(e=l.substr(n,1),n++):(e=null,v('"q"')),e!==null?(o=Le(),o!==null?(d=Vt(),d!==null?e=[e,o,d]:(e=null,n=T)):(e=null,n=T)):(e=null,n=T),e!==null&&(e=function(w,O){J.params||(J.params={}),J.params.q=O}(p,e[2])),e===null&&(n=p),e}function cr(){var e,o,d,p,T;return p=n,T=n,l.substr(n,7).toLowerCase()==="expires"?(e=l.substr(n,7),n+=7):(e=null,v('"expires"')),e!==null?(o=Le(),o!==null?(d=Tr(),d!==null?e=[e,o,d]:(e=null,n=T)):(e=null,n=T)):(e=null,n=T),e!==null&&(e=function(w,O){J.params||(J.params={}),J.params.expires=O}(p,e[2])),e===null&&(n=p),e}function Tr(){var e,o,d;if(d=n,o=R(),o!==null)for(e=[];o!==null;)e.push(o),o=R();else e=null;return e!==null&&(e=function(p,T){return parseInt(T.join(""))}(d,e)),e===null&&(n=d),e}function Vt(){var e,o,d,p,T,w,O,B;return w=n,O=n,l.charCodeAt(n)===48?(e="0",n++):(e=null,v('"0"')),e!==null?(B=n,l.charCodeAt(n)===46?(o=".",n++):(o=null,v('"."')),o!==null?(d=R(),d=d!==null?d:"",d!==null?(p=R(),p=p!==null?p:"",p!==null?(T=R(),T=T!==null?T:"",T!==null?o=[o,d,p,T]:(o=null,n=B)):(o=null,n=B)):(o=null,n=B)):(o=null,n=B),o=o!==null?o:"",o!==null?e=[e,o]:(e=null,n=O)):(e=null,n=O),e!==null&&(e=function(ee){return parseFloat(l.substring(n,ee))}(w)),e===null&&(n=w),e}function qt(){var e,o,d,p,T,w;return p=n,T=n,e=oe(),e!==null?(w=n,o=Le(),o!==null?(d=Vi(),d!==null?o=[o,d]:(o=null,n=w)):(o=null,n=w),o=o!==null?o:"",o!==null?e=[e,o]:(e=null,n=T)):(e=null,n=T),e!==null&&(e=function(O,B,ee){J.params||(J.params={}),typeof ee>"u"?ee=void 0:ee=ee[1],J.params[B.toLowerCase()]=ee}(p,e[0],e[1])),e===null&&(n=p),e}function Vi(){var e;return e=oe(),e===null&&(e=as(),e===null&&(e=ft())),e}function ka(){var e,o,d,p,T,w;if(T=n,e=wn(),e!==null){for(o=[],w=n,d=Ye(),d!==null?(p=si(),p!==null?d=[d,p]:(d=null,n=w)):(d=null,n=w);d!==null;)o.push(d),w=n,d=Ye(),d!==null?(p=si(),p!==null?d=[d,p]:(d=null,n=w)):(d=null,n=w);o!==null?e=[e,o]:(e=null,n=T)}else e=null,n=T;return e}function wn(){var e;return l.substr(n,6).toLowerCase()==="render"?(e=l.substr(n,6),n+=6):(e=null,v('"render"')),e===null&&(l.substr(n,7).toLowerCase()==="session"?(e=l.substr(n,7),n+=7):(e=null,v('"session"')),e===null&&(l.substr(n,4).toLowerCase()==="icon"?(e=l.substr(n,4),n+=4):(e=null,v('"icon"')),e===null&&(l.substr(n,5).toLowerCase()==="alert"?(e=l.substr(n,5),n+=5):(e=null,v('"alert"')),e===null&&(e=oe())))),e}function si(){var e;return e=qi(),e===null&&(e=qt()),e}function qi(){var e,o,d,p;return p=n,l.substr(n,8).toLowerCase()==="handling"?(e=l.substr(n,8),n+=8):(e=null,v('"handling"')),e!==null?(o=Le(),o!==null?(l.substr(n,8).toLowerCase()==="optional"?(d=l.substr(n,8),n+=8):(d=null,v('"optional"')),d===null&&(l.substr(n,8).toLowerCase()==="required"?(d=l.substr(n,8),n+=8):(d=null,v('"required"')),d===null&&(d=oe())),d!==null?e=[e,o,d]:(e=null,n=p)):(e=null,n=p)):(e=null,n=p),e}function Na(){var e,o,d,p,T,w;if(T=n,e=oe(),e!==null){for(o=[],w=n,d=ze(),d!==null?(p=oe(),p!==null?d=[d,p]:(d=null,n=w)):(d=null,n=w);d!==null;)o.push(d),w=n,d=ze(),d!==null?(p=oe(),p!==null?d=[d,p]:(d=null,n=w)):(d=null,n=w);o!==null?e=[e,o]:(e=null,n=T)}else e=null,n=T;return e}function Ma(){var e,o,d;if(d=n,o=R(),o!==null)for(e=[];o!==null;)e.push(o),o=R();else e=null;return e!==null&&(e=function(p,T){J=parseInt(T.join(""))}(d,e)),e===null&&(n=d),e}function Ua(){var e,o;return o=n,e=ji(),e!==null&&(e=function(d){J=l.substring(n,d)}(o)),e===null&&(n=o),e}function ji(){var e,o,d,p,T,w,O,B;if(O=n,e=Pa(),e!==null)if(o=ge(),o!==null)if(d=An(),d!==null){for(p=[],B=n,T=Ye(),T!==null?(w=In(),w!==null?T=[T,w]:(T=null,n=B)):(T=null,n=B);T!==null;)p.push(T),B=n,T=Ye(),T!==null?(w=In(),w!==null?T=[T,w]:(T=null,n=B)):(T=null,n=B);p!==null?e=[e,o,d,p]:(e=null,n=O)}else e=null,n=O;else e=null,n=O;else e=null,n=O;return e}function Pa(){var e;return e=Qr(),e===null&&(e=En()),e}function Qr(){var e;return l.substr(n,4).toLowerCase()==="text"?(e=l.substr(n,4),n+=4):(e=null,v('"text"')),e===null&&(l.substr(n,5).toLowerCase()==="image"?(e=l.substr(n,5),n+=5):(e=null,v('"image"')),e===null&&(l.substr(n,5).toLowerCase()==="audio"?(e=l.substr(n,5),n+=5):(e=null,v('"audio"')),e===null&&(l.substr(n,5).toLowerCase()==="video"?(e=l.substr(n,5),n+=5):(e=null,v('"video"')),e===null&&(l.substr(n,11).toLowerCase()==="application"?(e=l.substr(n,11),n+=11):(e=null,v('"application"')),e===null&&(e=Cn()))))),e}function En(){var e;return l.substr(n,7).toLowerCase()==="message"?(e=l.substr(n,7),n+=7):(e=null,v('"message"')),e===null&&(l.substr(n,9).toLowerCase()==="multipart"?(e=l.substr(n,9),n+=9):(e=null,v('"multipart"')),e===null&&(e=Cn())),e}function Cn(){var e;return e=oe(),e===null&&(e=La()),e}function La(){var e,o,d;return d=n,l.substr(n,2).toLowerCase()==="x-"?(e=l.substr(n,2),n+=2):(e=null,v('"x-"')),e!==null?(o=oe(),o!==null?e=[e,o]:(e=null,n=d)):(e=null,n=d),e}function An(){var e;return e=Cn(),e===null&&(e=oe()),e}function In(){var e,o,d,p;return p=n,e=oe(),e!==null?(o=Le(),o!==null?(d=ri(),d!==null?e=[e,o,d]:(e=null,n=p)):(e=null,n=p)):(e=null,n=p),e}function ri(){var e;return e=oe(),e===null&&(e=ft()),e}function ni(){var e,o,d,p;return p=n,e=Ha(),e!==null?(o=Z(),o!==null?(d=Sn(),d!==null?e=[e,o,d]:(e=null,n=p)):(e=null,n=p)):(e=null,n=p),e}function Ha(){var e,o,d;if(d=n,o=R(),o!==null)for(e=[];o!==null;)e.push(o),o=R();else e=null;return e!==null&&(e=function(p,T){J.value=parseInt(T.join(""))}(d,e)),e===null&&(n=d),e}function bl(){var e,o;return o=n,e=Tr(),e!==null&&(e=function(d,p){J=p}(o,e)),e===null&&(n=o),e}function Xr(){var e,o,d,p,T,w,O;if(T=n,w=n,e=Zr(),e!==null){for(o=[],O=n,d=Ye(),d!==null?(p=qt(),p!==null?d=[d,p]:(d=null,n=O)):(d=null,n=O);d!==null;)o.push(d),O=n,d=Ye(),d!==null?(p=qt(),p!==null?d=[d,p]:(d=null,n=O)):(d=null,n=O);o!==null?e=[e,o]:(e=null,n=w)}else e=null,n=w;return e!==null&&(e=function(B,ee){J.event=ee.join("").toLowerCase()}(T,e[0])),e===null&&(n=T),e}function Zr(){var e,o,d,p,T,w;if(T=n,e=Oe(),e!==null){for(o=[],w=n,l.charCodeAt(n)===46?(d=".",n++):(d=null,v('"."')),d!==null?(p=Oe(),p!==null?d=[d,p]:(d=null,n=w)):(d=null,n=w);d!==null;)o.push(d),w=n,l.charCodeAt(n)===46?(d=".",n++):(d=null,v('"."')),d!==null?(p=Oe(),p!==null?d=[d,p]:(d=null,n=w)):(d=null,n=w);o!==null?e=[e,o]:(e=null,n=T)}else e=null,n=T;return e}function Gi(){var e,o,d,p,T,w,O;if(T=n,w=n,e=yt(),e===null&&(e=Js()),e!==null){for(o=[],O=n,d=Ye(),d!==null?(p=Rn(),p!==null?d=[d,p]:(d=null,n=O)):(d=null,n=O);d!==null;)o.push(d),O=n,d=Ye(),d!==null?(p=Rn(),p!==null?d=[d,p]:(d=null,n=O)):(d=null,n=O);o!==null?e=[e,o]:(e=null,n=w)}else e=null,n=w;return e!==null&&(e=function(B){var ee=J.tag;try{J=new K(J.uri,J.display_name,J.params),ee&&J.setParam("tag",ee)}catch{J=-1}}()),e===null&&(n=T),e}function Rn(){var e;return e=Fa(),e===null&&(e=qt()),e}function Fa(){var e,o,d,p,T;return p=n,T=n,l.substr(n,3).toLowerCase()==="tag"?(e=l.substr(n,3),n+=3):(e=null,v('"tag"')),e!==null?(o=Le(),o!==null?(d=oe(),d!==null?e=[e,o,d]:(e=null,n=T)):(e=null,n=T)):(e=null,n=T),e!==null&&(e=function(w,O){J.tag=O}(p,e[2])),e===null&&(n=p),e}function wl(){var e,o,d;if(d=n,o=R(),o!==null)for(e=[];o!==null;)e.push(o),o=R();else e=null;return e!==null&&(e=function(p,T){J=parseInt(T.join(""))}(d,e)),e===null&&(n=d),e}function Rt(){var e,o;return o=n,e=Tr(),e!==null&&(e=function(d,p){J=p}(o,e)),e===null&&(n=o),e}function jt(){var e,o,d,p,T,w,O,B,ee,Pe;for(B=n,ee=n,e=[],o=Jr();o!==null;)e.push(o),o=Jr();if(e!==null)if(o=dt(),o!==null)if(d=Ct(),d!==null)if(p=xt(),p!==null){for(T=[],Pe=n,w=Ye(),w!==null?(O=qt(),O!==null?w=[w,O]:(w=null,n=Pe)):(w=null,n=Pe);w!==null;)T.push(w),Pe=n,w=Ye(),w!==null?(O=qt(),O!==null?w=[w,O]:(w=null,n=Pe)):(w=null,n=Pe);T!==null?e=[e,o,d,p,T]:(e=null,n=ee)}else e=null,n=ee;else e=null,n=ee;else e=null,n=ee;else e=null,n=ee;return e!==null&&(e=function(At){try{J=new K(J.uri,J.display_name,J.params)}catch{J=-1}}()),e===null&&(n=B),e}function Rr(){var e;return e=en(),e}function en(){var e,o,d,p,T,w,O,B;if(O=n,l.substr(n,6).toLowerCase()==="digest"?(e=l.substr(n,6),n+=6):(e=null,v('"Digest"')),e!==null)if(o=Z(),o!==null)if(d=Xe(),d!==null){for(p=[],B=n,T=ze(),T!==null?(w=Xe(),w!==null?T=[T,w]:(T=null,n=B)):(T=null,n=B);T!==null;)p.push(T),B=n,T=ze(),T!==null?(w=Xe(),w!==null?T=[T,w]:(T=null,n=B)):(T=null,n=B);p!==null?e=[e,o,d,p]:(e=null,n=O)}else e=null,n=O;else e=null,n=O;else e=null,n=O;return e===null&&(e=Bt()),e}function Bt(){var e,o,d,p,T,w,O,B;if(O=n,e=oe(),e!==null)if(o=Z(),o!==null)if(d=Gt(),d!==null){for(p=[],B=n,T=ze(),T!==null?(w=Gt(),w!==null?T=[T,w]:(T=null,n=B)):(T=null,n=B);T!==null;)p.push(T),B=n,T=ze(),T!==null?(w=Gt(),w!==null?T=[T,w]:(T=null,n=B)):(T=null,n=B);p!==null?e=[e,o,d,p]:(e=null,n=O)}else e=null,n=O;else e=null,n=O;else e=null,n=O;return e}function Gt(){var e,o,d,p;return p=n,e=oe(),e!==null?(o=Le(),o!==null?(d=oe(),d===null&&(d=ft()),d!==null?e=[e,o,d]:(e=null,n=p)):(e=null,n=p)):(e=null,n=p),e}function Xe(){var e;return e=Pt(),e===null&&(e=dr(),e===null&&(e=Ze(),e===null&&(e=he(),e===null&&(e=Je(),e===null&&(e=Wi(),e===null&&(e=sn(),e===null&&(e=Gt()))))))),e}function Pt(){var e,o,d,p;return p=n,l.substr(n,5).toLowerCase()==="realm"?(e=l.substr(n,5),n+=5):(e=null,v('"realm"')),e!==null?(o=Le(),o!==null?(d=ii(),d!==null?e=[e,o,d]:(e=null,n=p)):(e=null,n=p)):(e=null,n=p),e}function ii(){var e,o;return o=n,e=Fe(),e!==null&&(e=function(d,p){J.realm=p}(o,e)),e===null&&(n=o),e}function dr(){var e,o,d,p,T,w,O,B,ee;if(B=n,l.substr(n,6).toLowerCase()==="domain"?(e=l.substr(n,6),n+=6):(e=null,v('"domain"')),e!==null)if(o=Le(),o!==null)if(d=Mt(),d!==null)if(p=qs(),p!==null){if(T=[],ee=n,O=te(),O!==null)for(w=[];O!==null;)w.push(O),O=te();else w=null;for(w!==null?(O=qs(),O!==null?w=[w,O]:(w=null,n=ee)):(w=null,n=ee);w!==null;){if(T.push(w),ee=n,O=te(),O!==null)for(w=[];O!==null;)w.push(O),O=te();else w=null;w!==null?(O=qs(),O!==null?w=[w,O]:(w=null,n=ee)):(w=null,n=ee)}T!==null?(w=nt(),w!==null?e=[e,o,d,p,T,w]:(e=null,n=B)):(e=null,n=B)}else e=null,n=B;else e=null,n=B;else e=null,n=B;else e=null,n=B;return e}function qs(){var e;return e=qr(),e===null&&(e=gn()),e}function Ze(){var e,o,d,p;return p=n,l.substr(n,5).toLowerCase()==="nonce"?(e=l.substr(n,5),n+=5):(e=null,v('"nonce"')),e!==null?(o=Le(),o!==null?(d=tn(),d!==null?e=[e,o,d]:(e=null,n=p)):(e=null,n=p)):(e=null,n=p),e}function tn(){var e,o;return o=n,e=Fe(),e!==null&&(e=function(d,p){J.nonce=p}(o,e)),e===null&&(n=o),e}function he(){var e,o,d,p,T;return p=n,T=n,l.substr(n,6).toLowerCase()==="opaque"?(e=l.substr(n,6),n+=6):(e=null,v('"opaque"')),e!==null?(o=Le(),o!==null?(d=Fe(),d!==null?e=[e,o,d]:(e=null,n=T)):(e=null,n=T)):(e=null,n=T),e!==null&&(e=function(w,O){J.opaque=O}(p,e[2])),e===null&&(n=p),e}function Je(){var e,o,d,p,T;return p=n,l.substr(n,5).toLowerCase()==="stale"?(e=l.substr(n,5),n+=5):(e=null,v('"stale"')),e!==null?(o=Le(),o!==null?(T=n,l.substr(n,4).toLowerCase()==="true"?(d=l.substr(n,4),n+=4):(d=null,v('"true"')),d!==null&&(d=function(w){J.stale=!0}()),d===null&&(n=T),d===null&&(T=n,l.substr(n,5).toLowerCase()==="false"?(d=l.substr(n,5),n+=5):(d=null,v('"false"')),d!==null&&(d=function(w){J.stale=!1}()),d===null&&(n=T)),d!==null?e=[e,o,d]:(e=null,n=p)):(e=null,n=p)):(e=null,n=p),e}function Wi(){var e,o,d,p,T;return p=n,T=n,l.substr(n,9).toLowerCase()==="algorithm"?(e=l.substr(n,9),n+=9):(e=null,v('"algorithm"')),e!==null?(o=Le(),o!==null?(l.substr(n,3).toLowerCase()==="md5"?(d=l.substr(n,3),n+=3):(d=null,v('"MD5"')),d===null&&(l.substr(n,8).toLowerCase()==="md5-sess"?(d=l.substr(n,8),n+=8):(d=null,v('"MD5-sess"')),d===null&&(d=oe())),d!==null?e=[e,o,d]:(e=null,n=T)):(e=null,n=T)):(e=null,n=T),e!==null&&(e=function(w,O){J.algorithm=O.toUpperCase()}(p,e[2])),e===null&&(n=p),e}function sn(){var e,o,d,p,T,w,O,B,ee,Pe;if(B=n,l.substr(n,3).toLowerCase()==="qop"?(e=l.substr(n,3),n+=3):(e=null,v('"qop"')),e!==null)if(o=Le(),o!==null)if(d=Mt(),d!==null){if(ee=n,p=ai(),p!==null){for(T=[],Pe=n,l.charCodeAt(n)===44?(w=",",n++):(w=null,v('","')),w!==null?(O=ai(),O!==null?w=[w,O]:(w=null,n=Pe)):(w=null,n=Pe);w!==null;)T.push(w),Pe=n,l.charCodeAt(n)===44?(w=",",n++):(w=null,v('","')),w!==null?(O=ai(),O!==null?w=[w,O]:(w=null,n=Pe)):(w=null,n=Pe);T!==null?p=[p,T]:(p=null,n=ee)}else p=null,n=ee;p!==null?(T=nt(),T!==null?e=[e,o,d,p,T]:(e=null,n=B)):(e=null,n=B)}else e=null,n=B;else e=null,n=B;else e=null,n=B;return e}function ai(){var e,o;return o=n,l.substr(n,8).toLowerCase()==="auth-int"?(e=l.substr(n,8),n+=8):(e=null,v('"auth-int"')),e===null&&(l.substr(n,4).toLowerCase()==="auth"?(e=l.substr(n,4),n+=4):(e=null,v('"auth"')),e===null&&(e=oe())),e!==null&&(e=function(d,p){J.qop||(J.qop=[]),J.qop.push(p.toLowerCase())}(o,e)),e===null&&(n=o),e}function El(){var e,o,d,p,T,w;if(T=n,e=oe(),e!==null){for(o=[],w=n,d=ze(),d!==null?(p=oe(),p!==null?d=[d,p]:(d=null,n=w)):(d=null,n=w);d!==null;)o.push(d),w=n,d=ze(),d!==null?(p=oe(),p!==null?d=[d,p]:(d=null,n=w)):(d=null,n=w);o!==null?e=[e,o]:(e=null,n=T)}else e=null,n=T;return e}function _t(){var e,o,d,p,T,w,O;if(T=n,w=n,e=li(),e!==null){for(o=[],O=n,d=ze(),d!==null?(p=li(),p!==null?d=[d,p]:(d=null,n=O)):(d=null,n=O);d!==null;)o.push(d),O=n,d=ze(),d!==null?(p=li(),p!==null?d=[d,p]:(d=null,n=O)):(d=null,n=O);o!==null?e=[e,o]:(e=null,n=w)}else e=null,n=w;return e!==null&&(e=function(B){var ee,Pe;for(Pe=J.multi_header.length,ee=0;ee<Pe;ee++)if(J.multi_header[ee].parsed===null){J=null;break}J!==null?J=J.multi_header:J=-1}()),e===null&&(n=T),e}function li(){var e,o,d,p,T,w,O;if(T=n,w=n,e=Js(),e!==null){for(o=[],O=n,d=Ye(),d!==null?(p=qt(),p!==null?d=[d,p]:(d=null,n=O)):(d=null,n=O);d!==null;)o.push(d),O=n,d=Ye(),d!==null?(p=qt(),p!==null?d=[d,p]:(d=null,n=O)):(d=null,n=O);o!==null?e=[e,o]:(e=null,n=w)}else e=null,n=w;return e!==null&&(e=function(B){var ee;J.multi_header||(J.multi_header=[]);try{ee=new K(J.uri,J.display_name,J.params),delete J.uri,delete J.display_name,delete J.params}catch{ee=null}J.multi_header.push({possition:n,offset:B,parsed:ee})}(T)),e===null&&(n=T),e}function oi(){var e,o,d,p,T,w,O;if(T=n,w=n,l.substr(n,3).toLowerCase()==="sip"?(e=l.substr(n,3),n+=3):(e=null,v('"SIP"')),e===null&&(e=oe()),e!==null){for(o=[],O=n,d=Ye(),d!==null?(p=ui(),p!==null?d=[d,p]:(d=null,n=O)):(d=null,n=O);d!==null;)o.push(d),O=n,d=Ye(),d!==null?(p=ui(),p!==null?d=[d,p]:(d=null,n=O)):(d=null,n=O);o!==null?e=[e,o]:(e=null,n=w)}else e=null,n=w;return e!==null&&(e=function(B,ee){if(J.protocol=ee.toLowerCase(),J.params||(J.params={}),J.params.text&&J.params.text[0]==='"'){var Pe=J.params.text;J.text=Pe.substring(1,Pe.length-1),delete J.params.text}}(T,e[0])),e===null&&(n=T),e}function ui(){var e;return e=Ba(),e===null&&(e=qt()),e}function Ba(){var e,o,d,p,T,w;if(T=n,w=n,l.substr(n,5).toLowerCase()==="cause"?(e=l.substr(n,5),n+=5):(e=null,v('"cause"')),e!==null)if(o=Le(),o!==null){if(p=R(),p!==null)for(d=[];p!==null;)d.push(p),p=R();else d=null;d!==null?e=[e,o,d]:(e=null,n=w)}else e=null,n=w;else e=null,n=w;return e!==null&&(e=function(O,B){J.cause=parseInt(B.join(""))}(T,e[2])),e===null&&(n=T),e}function Cl(){var e,o,d,p,T,w;if(T=n,e=oe(),e!==null){for(o=[],w=n,d=ze(),d!==null?(p=oe(),p!==null?d=[d,p]:(d=null,n=w)):(d=null,n=w);d!==null;)o.push(d),w=n,d=ze(),d!==null?(p=oe(),p!==null?d=[d,p]:(d=null,n=w)):(d=null,n=w);o!==null?e=[e,o]:(e=null,n=T)}else e=null,n=T;return e}function ci(){var e,o,d,p,T,w;if(T=n,e=ms(),e!==null){for(o=[],w=n,d=ze(),d!==null?(p=ms(),p!==null?d=[d,p]:(d=null,n=w)):(d=null,n=w);d!==null;)o.push(d),w=n,d=ze(),d!==null?(p=ms(),p!==null?d=[d,p]:(d=null,n=w)):(d=null,n=w);o!==null?e=[e,o]:(e=null,n=T)}else e=null,n=T;return e}function ms(){var e,o,d,p,T,w;if(T=n,e=Js(),e!==null){for(o=[],w=n,d=Ye(),d!==null?(p=qt(),p!==null?d=[d,p]:(d=null,n=w)):(d=null,n=w);d!==null;)o.push(d),w=n,d=Ye(),d!==null?(p=qt(),p!==null?d=[d,p]:(d=null,n=w)):(d=null,n=w);o!==null?e=[e,o]:(e=null,n=T)}else e=null,n=T;return e}function za(){var e,o,d,p,T,w;if(T=n,e=di(),e!==null){for(o=[],w=n,d=Ye(),d!==null?(p=Qs(),p!==null?d=[d,p]:(d=null,n=w)):(d=null,n=w);d!==null;)o.push(d),w=n,d=Ye(),d!==null?(p=Qs(),p!==null?d=[d,p]:(d=null,n=w)):(d=null,n=w);o!==null?e=[e,o]:(e=null,n=T)}else e=null,n=T;return e}function di(){var e,o;return o=n,l.substr(n,6).toLowerCase()==="active"?(e=l.substr(n,6),n+=6):(e=null,v('"active"')),e===null&&(l.substr(n,7).toLowerCase()==="pending"?(e=l.substr(n,7),n+=7):(e=null,v('"pending"')),e===null&&(l.substr(n,10).toLowerCase()==="terminated"?(e=l.substr(n,10),n+=10):(e=null,v('"terminated"')),e===null&&(e=oe()))),e!==null&&(e=function(d){J.state=l.substring(n,d)}(o)),e===null&&(n=o),e}function Qs(){var e,o,d,p,T;return p=n,T=n,l.substr(n,6).toLowerCase()==="reason"?(e=l.substr(n,6),n+=6):(e=null,v('"reason"')),e!==null?(o=Le(),o!==null?(d=Va(),d!==null?e=[e,o,d]:(e=null,n=T)):(e=null,n=T)):(e=null,n=T),e!==null&&(e=function(w,O){typeof O<"u"&&(J.reason=O)}(p,e[2])),e===null&&(n=p),e===null&&(p=n,T=n,l.substr(n,7).toLowerCase()==="expires"?(e=l.substr(n,7),n+=7):(e=null,v('"expires"')),e!==null?(o=Le(),o!==null?(d=Tr(),d!==null?e=[e,o,d]:(e=null,n=T)):(e=null,n=T)):(e=null,n=T),e!==null&&(e=function(w,O){typeof O<"u"&&(J.expires=O)}(p,e[2])),e===null&&(n=p),e===null&&(p=n,T=n,l.substr(n,11).toLowerCase()==="retry_after"?(e=l.substr(n,11),n+=11):(e=null,v('"retry_after"')),e!==null?(o=Le(),o!==null?(d=Tr(),d!==null?e=[e,o,d]:(e=null,n=T)):(e=null,n=T)):(e=null,n=T),e!==null&&(e=function(w,O){typeof O<"u"&&(J.retry_after=O)}(p,e[2])),e===null&&(n=p),e===null&&(e=qt()))),e}function Va(){var e;return l.substr(n,11).toLowerCase()==="deactivated"?(e=l.substr(n,11),n+=11):(e=null,v('"deactivated"')),e===null&&(l.substr(n,9).toLowerCase()==="probation"?(e=l.substr(n,9),n+=9):(e=null,v('"probation"')),e===null&&(l.substr(n,8).toLowerCase()==="rejected"?(e=l.substr(n,8),n+=8):(e=null,v('"rejected"')),e===null&&(l.substr(n,7).toLowerCase()==="timeout"?(e=l.substr(n,7),n+=7):(e=null,v('"timeout"')),e===null&&(l.substr(n,6).toLowerCase()==="giveup"?(e=l.substr(n,6),n+=6):(e=null,v('"giveup"')),e===null&&(l.substr(n,10).toLowerCase()==="noresource"?(e=l.substr(n,10),n+=10):(e=null,v('"noresource"')),e===null&&(l.substr(n,9).toLowerCase()==="invariant"?(e=l.substr(n,9),n+=9):(e=null,v('"invariant"')),e===null&&(e=oe()))))))),e}function Al(){var e;return e=me(),e=e!==null?e:"",e}function Il(){var e,o,d,p,T,w;if(T=n,e=oe(),e!==null){for(o=[],w=n,d=ze(),d!==null?(p=oe(),p!==null?d=[d,p]:(d=null,n=w)):(d=null,n=w);d!==null;)o.push(d),w=n,d=ze(),d!==null?(p=oe(),p!==null?d=[d,p]:(d=null,n=w)):(d=null,n=w);o!==null?e=[e,o]:(e=null,n=T)}else e=null,n=T;return e=e!==null?e:"",e}function Ki(){var e,o,d,p,T,w,O;if(T=n,w=n,e=yt(),e===null&&(e=Js()),e!==null){for(o=[],O=n,d=Ye(),d!==null?(p=Yi(),p!==null?d=[d,p]:(d=null,n=O)):(d=null,n=O);d!==null;)o.push(d),O=n,d=Ye(),d!==null?(p=Yi(),p!==null?d=[d,p]:(d=null,n=O)):(d=null,n=O);o!==null?e=[e,o]:(e=null,n=w)}else e=null,n=w;return e!==null&&(e=function(B){var ee=J.tag;try{J=new K(J.uri,J.display_name,J.params),ee&&J.setParam("tag",ee)}catch{J=-1}}()),e===null&&(n=T),e}function Yi(){var e;return e=Fa(),e===null&&(e=qt()),e}function fi(){var e,o,d,p,T,w;if(T=n,e=rn(),e!==null){for(o=[],w=n,d=ze(),d!==null?(p=rn(),p!==null?d=[d,p]:(d=null,n=w)):(d=null,n=w);d!==null;)o.push(d),w=n,d=ze(),d!==null?(p=rn(),p!==null?d=[d,p]:(d=null,n=w)):(d=null,n=w);o!==null?e=[e,o]:(e=null,n=T)}else e=null,n=T;return e}function rn(){var e,o,d,p,T,w,O,B;if(O=n,e=ta(),e!==null)if(o=Z(),o!==null)if(d=na(),d!==null){for(p=[],B=n,T=Ye(),T!==null?(w=hi(),w!==null?T=[T,w]:(T=null,n=B)):(T=null,n=B);T!==null;)p.push(T),B=n,T=Ye(),T!==null?(w=hi(),w!==null?T=[T,w]:(T=null,n=B)):(T=null,n=B);p!==null?e=[e,o,d,p]:(e=null,n=O)}else e=null,n=O;else e=null,n=O;else e=null,n=O;return e}function hi(){var e;return e=Ji(),e===null&&(e=Qi(),e===null&&(e=Hs(),e===null&&(e=Xi(),e===null&&(e=Zi(),e===null&&(e=qt()))))),e}function Ji(){var e,o,d,p,T;return p=n,T=n,l.substr(n,3).toLowerCase()==="ttl"?(e=l.substr(n,3),n+=3):(e=null,v('"ttl"')),e!==null?(o=Le(),o!==null?(d=aa(),d!==null?e=[e,o,d]:(e=null,n=T)):(e=null,n=T)):(e=null,n=T),e!==null&&(e=function(w,O){J.ttl=O}(p,e[2])),e===null&&(n=p),e}function Qi(){var e,o,d,p,T;return p=n,T=n,l.substr(n,5).toLowerCase()==="maddr"?(e=l.substr(n,5),n+=5):(e=null,v('"maddr"')),e!==null?(o=Le(),o!==null?(d=as(),d!==null?e=[e,o,d]:(e=null,n=T)):(e=null,n=T)):(e=null,n=T),e!==null&&(e=function(w,O){J.maddr=O}(p,e[2])),e===null&&(n=p),e}function Hs(){var e,o,d,p,T;return p=n,T=n,l.substr(n,8).toLowerCase()==="received"?(e=l.substr(n,8),n+=8):(e=null,v('"received"')),e!==null?(o=Le(),o!==null?(d=lr(),d===null&&(d=Qe()),d!==null?e=[e,o,d]:(e=null,n=T)):(e=null,n=T)):(e=null,n=T),e!==null&&(e=function(w,O){J.received=O}(p,e[2])),e===null&&(n=p),e}function Xi(){var e,o,d,p,T;return p=n,T=n,l.substr(n,6).toLowerCase()==="branch"?(e=l.substr(n,6),n+=6):(e=null,v('"branch"')),e!==null?(o=Le(),o!==null?(d=oe(),d!==null?e=[e,o,d]:(e=null,n=T)):(e=null,n=T)):(e=null,n=T),e!==null&&(e=function(w,O){J.branch=O}(p,e[2])),e===null&&(n=p),e}function Zi(){var e,o,d,p,T;return p=n,l.substr(n,5).toLowerCase()==="rport"?(e=l.substr(n,5),n+=5):(e=null,v('"rport"')),e!==null?(T=n,o=Le(),o!==null?(d=ea(),d!==null?o=[o,d]:(o=null,n=T)):(o=null,n=T),o=o!==null?o:"",o!==null?e=[e,o]:(e=null,n=p)):(e=null,n=p),e}function ea(){var e,o,d,p,T,w,O;return w=n,O=n,e=R(),e=e!==null?e:"",e!==null?(o=R(),o=o!==null?o:"",o!==null?(d=R(),d=d!==null?d:"",d!==null?(p=R(),p=p!==null?p:"",p!==null?(T=R(),T=T!==null?T:"",T!==null?e=[e,o,d,p,T]:(e=null,n=O)):(e=null,n=O)):(e=null,n=O)):(e=null,n=O)):(e=null,n=O),e!==null&&(e=function(B,ee){J.rport=parseInt(ee.join(""))}(w,e)),e===null&&(n=w),e}function ta(){var e,o,d,p,T,w;return w=n,e=sa(),e!==null?(o=ge(),o!==null?(d=oe(),d!==null?(p=ge(),p!==null?(T=ra(),T!==null?e=[e,o,d,p,T]:(e=null,n=w)):(e=null,n=w)):(e=null,n=w)):(e=null,n=w)):(e=null,n=w),e}function sa(){var e,o;return o=n,l.substr(n,3).toLowerCase()==="sip"?(e=l.substr(n,3),n+=3):(e=null,v('"SIP"')),e===null&&(e=oe()),e!==null&&(e=function(d,p){J.protocol=p}(o,e)),e===null&&(n=o),e}function ra(){var e,o;return o=n,l.substr(n,3).toLowerCase()==="udp"?(e=l.substr(n,3),n+=3):(e=null,v('"UDP"')),e===null&&(l.substr(n,3).toLowerCase()==="tcp"?(e=l.substr(n,3),n+=3):(e=null,v('"TCP"')),e===null&&(l.substr(n,3).toLowerCase()==="tls"?(e=l.substr(n,3),n+=3):(e=null,v('"TLS"')),e===null&&(l.substr(n,4).toLowerCase()==="sctp"?(e=l.substr(n,4),n+=4):(e=null,v('"SCTP"')),e===null&&(e=oe())))),e!==null&&(e=function(d,p){J.transport=p}(o,e)),e===null&&(n=o),e}function na(){var e,o,d,p,T;return p=n,e=ia(),e!==null?(T=n,o=Zt(),o!==null?(d=_i(),d!==null?o=[o,d]:(o=null,n=T)):(o=null,n=T),o=o!==null?o:"",o!==null?e=[e,o]:(e=null,n=p)):(e=null,n=p),e}function ia(){var e,o;return o=n,e=lr(),e===null&&(e=Lr(),e===null&&(e=Pr())),e!==null&&(e=function(d){J.host=l.substring(n,d)}(o)),e===null&&(n=o),e}function _i(){var e,o,d,p,T,w,O;return w=n,O=n,e=R(),e=e!==null?e:"",e!==null?(o=R(),o=o!==null?o:"",o!==null?(d=R(),d=d!==null?d:"",d!==null?(p=R(),p=p!==null?p:"",p!==null?(T=R(),T=T!==null?T:"",T!==null?e=[e,o,d,p,T]:(e=null,n=O)):(e=null,n=O)):(e=null,n=O)):(e=null,n=O)):(e=null,n=O),e!==null&&(e=function(B,ee){J.port=parseInt(ee.join(""))}(w,e)),e===null&&(n=w),e}function aa(){var e,o,d,p,T;return p=n,T=n,e=R(),e!==null?(o=R(),o=o!==null?o:"",o!==null?(d=R(),d=d!==null?d:"",d!==null?e=[e,o,d]:(e=null,n=T)):(e=null,n=T)):(e=null,n=T),e!==null&&(e=function(w,O){return parseInt(O.join(""))}(p,e)),e===null&&(n=p),e}function Eo(){var e;return e=en(),e}function js(){var e,o,d,p,T,w;if(T=n,e=pi(),e!==null){for(o=[],w=n,d=Ye(),d!==null?(p=nn(),p!==null?d=[d,p]:(d=null,n=w)):(d=null,n=w);d!==null;)o.push(d),w=n,d=Ye(),d!==null?(p=nn(),p!==null?d=[d,p]:(d=null,n=w)):(d=null,n=w);o!==null?e=[e,o]:(e=null,n=T)}else e=null,n=T;return e}function pi(){var e,o;return o=n,e=Tr(),e!==null&&(e=function(d,p){J.expires=p}(o,e)),e===null&&(n=o),e}function nn(){var e;return e=la(),e===null&&(e=qt()),e}function la(){var e,o,d,p,T;return p=n,T=n,l.substr(n,9).toLowerCase()==="refresher"?(e=l.substr(n,9),n+=9):(e=null,v('"refresher"')),e!==null?(o=Le(),o!==null?(l.substr(n,3).toLowerCase()==="uac"?(d=l.substr(n,3),n+=3):(d=null,v('"uac"')),d===null&&(l.substr(n,3).toLowerCase()==="uas"?(d=l.substr(n,3),n+=3):(d=null,v('"uas"'))),d!==null?e=[e,o,d]:(e=null,n=T)):(e=null,n=T)):(e=null,n=T),e!==null&&(e=function(w,O){J.refresher=O.toLowerCase()}(p,e[2])),e===null&&(n=p),e}function Gs(){var e,o,d,p;return p=n,e=oe(),e!==null?(o=pe(),o!==null?(d=qa(),d!==null?e=[e,o,d]:(e=null,n=p)):(e=null,n=p)):(e=null,n=p),e}function qa(){var e,o;for(e=[],o=be(),o===null&&(o=Ae(),o===null&&(o=Z()));o!==null;)e.push(o),o=be(),o===null&&(o=Ae(),o===null&&(o=Z()));return e}function Rl(){var e,o;for(e=[],o=q();o!==null;)e.push(o),o=q();return e}function ja(){var e,o,d;return d=n,l.substr(n,5)==="uuid:"?(e="uuid:",n+=5):(e=null,v('"uuid:"')),e!==null?(o=Xs(),o!==null?e=[e,o]:(e=null,n=d)):(e=null,n=d),e}function Xs(){var e,o,d,p,T,w,O,B,ee,Pe,At;return Pe=n,At=n,e=oa(),e!==null?(l.charCodeAt(n)===45?(o="-",n++):(o=null,v('"-"')),o!==null?(d=Zs(),d!==null?(l.charCodeAt(n)===45?(p="-",n++):(p=null,v('"-"')),p!==null?(T=Zs(),T!==null?(l.charCodeAt(n)===45?(w="-",n++):(w=null,v('"-"')),w!==null?(O=Zs(),O!==null?(l.charCodeAt(n)===45?(B="-",n++):(B=null,v('"-"')),B!==null?(ee=Ga(),ee!==null?e=[e,o,d,p,T,w,O,B,ee]:(e=null,n=At)):(e=null,n=At)):(e=null,n=At)):(e=null,n=At)):(e=null,n=At)):(e=null,n=At)):(e=null,n=At)):(e=null,n=At)):(e=null,n=At),e!==null&&(e=function(Es,xr){J=l.substring(n+5,Es)}(Pe,e[0])),e===null&&(n=Pe),e}function Zs(){var e,o,d,p,T;return T=n,e=H(),e!==null?(o=H(),o!==null?(d=H(),d!==null?(p=H(),p!==null?e=[e,o,d,p]:(e=null,n=T)):(e=null,n=T)):(e=null,n=T)):(e=null,n=T),e}function oa(){var e,o,d;return d=n,e=Zs(),e!==null?(o=Zs(),o!==null?e=[e,o]:(e=null,n=d)):(e=null,n=d),e}function Ga(){var e,o,d,p;return p=n,e=Zs(),e!==null?(o=Zs(),o!==null?(d=Zs(),d!==null?e=[e,o,d]:(e=null,n=p)):(e=null,n=p)):(e=null,n=p),e}function $l(){var e,o,d,p,T,w,O;if(T=n,w=n,e=yt(),e===null&&(e=Js()),e!==null){for(o=[],O=n,d=Ye(),d!==null?(p=qt(),p!==null?d=[d,p]:(d=null,n=O)):(d=null,n=O);d!==null;)o.push(d),O=n,d=Ye(),d!==null?(p=qt(),p!==null?d=[d,p]:(d=null,n=O)):(d=null,n=O);o!==null?e=[e,o]:(e=null,n=w)}else e=null,n=w;return e!==null&&(e=function(B){try{J=new K(J.uri,J.display_name,J.params)}catch{J=-1}}()),e===null&&(n=T),e}function Wa(){var e,o,d,p,T,w;if(T=n,e=mi(),e!==null){for(o=[],w=n,d=Ye(),d!==null?(p=ws(),p!==null?d=[d,p]:(d=null,n=w)):(d=null,n=w);d!==null;)o.push(d),w=n,d=Ye(),d!==null?(p=ws(),p!==null?d=[d,p]:(d=null,n=w)):(d=null,n=w);o!==null?e=[e,o]:(e=null,n=T)}else e=null,n=T;return e}function mi(){var e,o,d,p,T,w;return p=n,T=n,e=Re(),e!==null?(w=n,l.charCodeAt(n)===64?(o="@",n++):(o=null,v('"@"')),o!==null?(d=Re(),d!==null?o=[o,d]:(o=null,n=w)):(o=null,n=w),o=o!==null?o:"",o!==null?e=[e,o]:(e=null,n=T)):(e=null,n=T),e!==null&&(e=function(O){J.call_id=l.substring(n,O)}(p)),e===null&&(n=p),e}function ws(){var e;return e=ua(),e===null&&(e=ca(),e===null&&(e=Ka(),e===null&&(e=qt()))),e}function ua(){var e,o,d,p,T;return p=n,T=n,l.substr(n,6)==="to-tag"?(e="to-tag",n+=6):(e=null,v('"to-tag"')),e!==null?(o=Le(),o!==null?(d=oe(),d!==null?e=[e,o,d]:(e=null,n=T)):(e=null,n=T)):(e=null,n=T),e!==null&&(e=function(w,O){J.to_tag=O}(p,e[2])),e===null&&(n=p),e}function ca(){var e,o,d,p,T;return p=n,T=n,l.substr(n,8)==="from-tag"?(e="from-tag",n+=8):(e=null,v('"from-tag"')),e!==null?(o=Le(),o!==null?(d=oe(),d!==null?e=[e,o,d]:(e=null,n=T)):(e=null,n=T)):(e=null,n=T),e!==null&&(e=function(w,O){J.from_tag=O}(p,e[2])),e===null&&(n=p),e}function Ka(){var e,o;return o=n,l.substr(n,10)==="early-only"?(e="early-only",n+=10):(e=null,v('"early-only"')),e!==null&&(e=function(d){J.early_only=!0}()),e===null&&(n=o),e}function xl(e){e.sort();for(var o=null,d=[],p=0;p<e.length;p++)e[p]!==o&&(d.push(e[p]),o=e[p]);return d}function Ya(){for(var e=1,o=1,d=!1,p=0;p<Math.max(n,g);p++){var T=l.charAt(p);T===`
4
- `?(d||e++,o=1,d=!1):T==="\r"||T==="\u2028"||T==="\u2029"?(e++,o=1,d=!0):(o++,d=!1)}return{line:e,column:o}}var $r=Ti(),K=oc(),J={},da=s[u]();if(da===null||n!==l.length){var fa=Math.max(n,g),ha=fa<l.length?l.charAt(fa):null,a=Ya();return new this.SyntaxError(xl(_),ha,fa,a.line,a.column),-1}return J},toSource:function(){return this._source}};return t.SyntaxError=function(r,l,u,s,n){function g(_,v){var C,R;switch(_.length){case 0:C="end of input";break;case 1:C=_[0];break;default:C=_.slice(0,_.length-1).join(", ")+" or "+_[_.length-1]}return R=v?f(v):"end of input","Expected "+C+" but "+R+" found."}this.name="SyntaxError",this.expected=r,this.found=l,this.message=g(r,l),this.offset=u,this.line=s,this.column=n},t.SyntaxError.prototype=Error.prototype,t}()),uc}var cc,Wf;function Ti(){if(Wf)return cc;Wf=1;function f(v,C){var R;if(typeof Symbol>"u"||v[Symbol.iterator]==null){if(Array.isArray(v)||(R=t(v))||C&&v&&typeof v.length=="number"){R&&(v=R);var D=0,H=function(){};return{s:H,n:function(){return D>=v.length?{done:!0}:{done:!1,value:v[D++]}},e:function(X){throw X},f:H}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
5
- In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var F=!0,q=!1,G;return{s:function(){R=v[Symbol.iterator]()},n:function(){var X=R.next();return F=X.done,X},e:function(X){q=!0,G=X},f:function(){try{!F&&R.return!=null&&R.return()}finally{if(q)throw G}}}}function t(v,C){if(v){if(typeof v=="string")return r(v,C);var R=Object.prototype.toString.call(v).slice(8,-1);if(R==="Object"&&v.constructor&&(R=v.constructor.name),R==="Map"||R==="Set")return Array.from(v);if(R==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(R))return r(v,C)}}function r(v,C){(C==null||C>v.length)&&(C=v.length);for(var R=0,D=new Array(C);R<C;R++)D[R]=v[R];return D}function l(v,C){if(!(v instanceof C))throw new TypeError("Cannot call a class as a function")}function u(v,C){for(var R=0;R<C.length;R++){var D=C[R];D.enumerable=D.enumerable||!1,D.configurable=!0,"value"in D&&(D.writable=!0),Object.defineProperty(v,D.key,D)}}function s(v,C,R){return C&&u(v.prototype,C),R&&u(v,R),v}var n=hs,g=Bs(),_=on();return cc=function(){s(v,null,[{key:"parse",value:function(R){if(R=_.parse(R,"SIP_URI"),R!==-1)return R}}]);function v(C,R,D,H){var F=arguments.length>4&&arguments[4]!==void 0?arguments[4]:{},q=arguments.length>5&&arguments[5]!==void 0?arguments[5]:{};if(l(this,v),!D)throw new TypeError('missing or invalid "host" parameter');this._parameters={},this._headers={},this._scheme=C||n.SIP,this._user=R,this._host=D,this._port=H;for(var G in F)Object.prototype.hasOwnProperty.call(F,G)&&this.setParam(G,F[G]);for(var te in q)Object.prototype.hasOwnProperty.call(q,te)&&this.setHeader(te,q[te])}return s(v,[{key:"setParam",value:function(R,D){R&&(this._parameters[R.toLowerCase()]=typeof D>"u"||D===null?null:D.toString())}},{key:"getParam",value:function(R){if(R)return this._parameters[R.toLowerCase()]}},{key:"hasParam",value:function(R){if(R)return this._parameters.hasOwnProperty(R.toLowerCase())&&!0||!1}},{key:"deleteParam",value:function(R){if(R=R.toLowerCase(),this._parameters.hasOwnProperty(R)){var D=this._parameters[R];return delete this._parameters[R],D}}},{key:"clearParams",value:function(){this._parameters={}}},{key:"setHeader",value:function(R,D){this._headers[g.headerize(R)]=Array.isArray(D)?D:[D]}},{key:"getHeader",value:function(R){if(R)return this._headers[g.headerize(R)]}},{key:"hasHeader",value:function(R){if(R)return this._headers.hasOwnProperty(g.headerize(R))&&!0||!1}},{key:"deleteHeader",value:function(R){if(R=g.headerize(R),this._headers.hasOwnProperty(R)){var D=this._headers[R];return delete this._headers[R],D}}},{key:"clearHeaders",value:function(){this._headers={}}},{key:"clone",value:function(){return new v(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 R=[],D="".concat(this._scheme,":");this._user&&(D+="".concat(g.escapeUser(this._user),"@")),D+=this._host,(this._port||this._port===0)&&(D+=":".concat(this._port));for(var H in this._parameters)Object.prototype.hasOwnProperty.call(this._parameters,H)&&(D+=";".concat(H),this._parameters[H]!==null&&(D+="=".concat(this._parameters[H])));for(var F in this._headers)if(Object.prototype.hasOwnProperty.call(this._headers,F)){var q=f(this._headers[F]),G;try{for(q.s();!(G=q.n()).done;){var te=G.value;R.push("".concat(F,"=").concat(te))}}catch(X){q.e(X)}finally{q.f()}}return R.length>0&&(D+="?".concat(R.join("&"))),D}},{key:"toAor",value:function(R){var D="".concat(this._scheme,":");return this._user&&(D+="".concat(g.escapeUser(this._user),"@")),D+=this._host,R&&(this._port||this._port===0)&&(D+=":".concat(this._port)),D}},{key:"scheme",get:function(){return this._scheme},set:function(R){this._scheme=R.toLowerCase()}},{key:"user",get:function(){return this._user},set:function(R){this._user=R}},{key:"host",get:function(){return this._host},set:function(R){this._host=R.toLowerCase()}},{key:"port",get:function(){return this._port},set:function(R){this._port=R===0?R:parseInt(R,10)||null}}]),v}(),cc}var Kf;function Bs(){if(Kf)return us;Kf=1;function f(C){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?f=function(D){return typeof D}:f=function(D){return D&&typeof Symbol=="function"&&D.constructor===Symbol&&D!==Symbol.prototype?"symbol":typeof D},f(C)}function t(C,R){var D;if(typeof Symbol>"u"||C[Symbol.iterator]==null){if(Array.isArray(C)||(D=r(C))||R&&C&&typeof C.length=="number"){D&&(C=D);var H=0,F=function(){};return{s:F,n:function(){return H>=C.length?{done:!0}:{done:!1,value:C[H++]}},e:function(we){throw we},f:F}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
6
- In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var q=!0,G=!1,te;return{s:function(){D=C[Symbol.iterator]()},n:function(){var we=D.next();return q=we.done,we},e:function(we){G=!0,te=we},f:function(){try{!q&&D.return!=null&&D.return()}finally{if(G)throw te}}}}function r(C,R){if(C){if(typeof C=="string")return l(C,R);var D=Object.prototype.toString.call(C).slice(8,-1);if(D==="Object"&&C.constructor&&(D=C.constructor.name),D==="Map"||D==="Set")return Array.from(C);if(D==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(D))return l(C,R)}}function l(C,R){(R==null||R>C.length)&&(R=C.length);for(var D=0,H=new Array(R);D<R;D++)H[D]=C[D];return H}var u=hs,s=Ti(),n=on();us.str_utf8_length=function(C){return unescape(encodeURIComponent(C)).length};var g=us.isFunction=function(C){return C!==void 0?Object.prototype.toString.call(C)==="[object Function]":!1};us.isString=function(C){return C!==void 0?Object.prototype.toString.call(C)==="[object String]":!1},us.isDecimal=function(C){return!isNaN(C)&&parseFloat(C)===parseInt(C,10)},us.isEmpty=function(C){return C===null||C===""||C===void 0||Array.isArray(C)&&C.length===0||typeof C=="number"&&isNaN(C)},us.hasMethods=function(C){for(var R=arguments.length,D=new Array(R>1?R-1:0),H=1;H<R;H++)D[H-1]=arguments[H];for(var F=0,q=D;F<q.length;F++){var G=q[F];if(g(C[G]))return!1}return!0};var _=us.createRandomToken=function(C){var R=arguments.length>1&&arguments[1]!==void 0?arguments[1]:32,D,H,F="";for(D=0;D<C;D++)H=Math.random()*R|0,F+=H.toString(R);return F};us.newTag=function(){return _(10)},us.newUUID=function(){var C="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(R){var D=Math.random()*16|0,H=R==="x"?D:D&3|8;return H.toString(16)});return C},us.hostType=function(C){if(C){if(C=n.parse(C,"host"),C!==-1)return C.host_type}else return};var v=us.escapeUser=function(C){return encodeURIComponent(decodeURIComponent(C)).replace(/%3A/ig,":").replace(/%2B/ig,"+").replace(/%3F/ig,"?").replace(/%2F/ig,"/")};return us.normalizeTarget=function(C,R){if(C){if(C instanceof s)return C;if(typeof C=="string"){var D=C.split("@"),H,F;switch(D.length){case 1:if(!R)return;H=C,F=R;break;case 2:H=D[0],F=D[1];break;default:H=D.slice(0,D.length-1).join("@"),F=D[D.length-1]}H=H.replace(/^(sips?|tel):/i,""),/^[-.()]*\+?[0-9\-.()]+$/.test(H)&&(H=H.replace(/[-.()]/g,"")),C="".concat(u.SIP,":").concat(v(H),"@").concat(F);var q;return(q=s.parse(C))?q:void 0}else return}else return},us.headerize=function(C){var R={"Call-Id":"Call-ID",Cseq:"CSeq","Www-Authenticate":"WWW-Authenticate"},D=C.toLowerCase().replace(/_/g,"-").split("-"),H="",F=D.length,q;for(q=0;q<F;q++)q!==0&&(H+="-"),H+=D[q].charAt(0).toUpperCase()+D[q].substring(1);return R[H]&&(H=R[H]),H},us.sipErrorCause=function(C){for(var R in u.SIP_ERROR_CAUSES)if(u.SIP_ERROR_CAUSES[R].indexOf(C)!==-1)return u.causes[R];return u.causes.SIP_FAILURE_CODE},us.getRandomTestNetIP=function(){function C(R,D){return Math.floor(Math.random()*(D-R+1)+R)}return"192.0.2.".concat(C(1,254))},us.calculateMD5=function(C){function R(Fe,He){return Fe<<He|Fe>>>32-He}function D(Fe,He){var qe=Fe&2147483648,yt=He&2147483648,Ct=Fe&1073741824,ns=He&1073741824,Ut=(Fe&1073741823)+(He&1073741823);return Ct&ns?Ut^2147483648^qe^yt:Ct|ns?Ut&1073741824?Ut^3221225472^qe^yt:Ut^1073741824^qe^yt:Ut^qe^yt}function H(Fe,He,qe){return Fe&He|~Fe&qe}function F(Fe,He,qe){return Fe&qe|He&~qe}function q(Fe,He,qe){return Fe^He^qe}function G(Fe,He,qe){return He^(Fe|~qe)}function te(Fe,He,qe,yt,Ct,ns,Ut){return Fe=D(Fe,D(D(H(He,qe,yt),Ct),Ut)),D(R(Fe,ns),He)}function X(Fe,He,qe,yt,Ct,ns,Ut){return Fe=D(Fe,D(D(F(He,qe,yt),Ct),Ut)),D(R(Fe,ns),He)}function we(Fe,He,qe,yt,Ct,ns,Ut){return Fe=D(Fe,D(D(q(He,qe,yt),Ct),Ut)),D(R(Fe,ns),He)}function Q(Fe,He,qe,yt,Ct,ns,Ut){return Fe=D(Fe,D(D(G(He,qe,yt),Ct),Ut)),D(R(Fe,ns),He)}function re(Fe){for(var He,qe=Fe.length,yt=qe+8,Ct=(yt-yt%64)/64,ns=(Ct+1)*16,Ut=new Array(ns-1),ar=0,vs=0;vs<qe;)He=(vs-vs%4)/4,ar=vs%4*8,Ut[He]=Ut[He]|Fe.charCodeAt(vs)<<ar,vs++;return He=(vs-vs%4)/4,ar=vs%4*8,Ut[He]=Ut[He]|128<<ar,Ut[ns-2]=qe<<3,Ut[ns-1]=qe>>>29,Ut}function ke(Fe){var He="",qe="",yt,Ct;for(Ct=0;Ct<=3;Ct++)yt=Fe>>>Ct*8&255,qe="0".concat(yt.toString(16)),He=He+qe.substr(qe.length-2,2);return He}function Ne(Fe){for(var He="",qe=0;qe<Fe.length;qe++){var yt=Fe.charCodeAt(qe);yt<128?He+=String.fromCharCode(yt):yt>127&&yt<2048?(He+=String.fromCharCode(yt>>6|192),He+=String.fromCharCode(yt&63|128)):(He+=String.fromCharCode(yt>>12|224),He+=String.fromCharCode(yt>>6&63|128),He+=String.fromCharCode(yt&63|128))}return He}var Z=[],se,pe,me,be,_e,Ae,le,oe,Oe,rs=7,Re=12,ye=17,ge=22,Le=5,et=9,vt=14,xt=20,dt=4,ze=11,Ye=16,Zt=23,Mt=6,nt=10,rt=15,gt=21;for(C=Ne(C),Z=re(C),Ae=1732584193,le=4023233417,oe=2562383102,Oe=271733878,se=0;se<Z.length;se+=16)pe=Ae,me=le,be=oe,_e=Oe,Ae=te(Ae,le,oe,Oe,Z[se+0],rs,3614090360),Oe=te(Oe,Ae,le,oe,Z[se+1],Re,3905402710),oe=te(oe,Oe,Ae,le,Z[se+2],ye,606105819),le=te(le,oe,Oe,Ae,Z[se+3],ge,3250441966),Ae=te(Ae,le,oe,Oe,Z[se+4],rs,4118548399),Oe=te(Oe,Ae,le,oe,Z[se+5],Re,1200080426),oe=te(oe,Oe,Ae,le,Z[se+6],ye,2821735955),le=te(le,oe,Oe,Ae,Z[se+7],ge,4249261313),Ae=te(Ae,le,oe,Oe,Z[se+8],rs,1770035416),Oe=te(Oe,Ae,le,oe,Z[se+9],Re,2336552879),oe=te(oe,Oe,Ae,le,Z[se+10],ye,4294925233),le=te(le,oe,Oe,Ae,Z[se+11],ge,2304563134),Ae=te(Ae,le,oe,Oe,Z[se+12],rs,1804603682),Oe=te(Oe,Ae,le,oe,Z[se+13],Re,4254626195),oe=te(oe,Oe,Ae,le,Z[se+14],ye,2792965006),le=te(le,oe,Oe,Ae,Z[se+15],ge,1236535329),Ae=X(Ae,le,oe,Oe,Z[se+1],Le,4129170786),Oe=X(Oe,Ae,le,oe,Z[se+6],et,3225465664),oe=X(oe,Oe,Ae,le,Z[se+11],vt,643717713),le=X(le,oe,Oe,Ae,Z[se+0],xt,3921069994),Ae=X(Ae,le,oe,Oe,Z[se+5],Le,3593408605),Oe=X(Oe,Ae,le,oe,Z[se+10],et,38016083),oe=X(oe,Oe,Ae,le,Z[se+15],vt,3634488961),le=X(le,oe,Oe,Ae,Z[se+4],xt,3889429448),Ae=X(Ae,le,oe,Oe,Z[se+9],Le,568446438),Oe=X(Oe,Ae,le,oe,Z[se+14],et,3275163606),oe=X(oe,Oe,Ae,le,Z[se+3],vt,4107603335),le=X(le,oe,Oe,Ae,Z[se+8],xt,1163531501),Ae=X(Ae,le,oe,Oe,Z[se+13],Le,2850285829),Oe=X(Oe,Ae,le,oe,Z[se+2],et,4243563512),oe=X(oe,Oe,Ae,le,Z[se+7],vt,1735328473),le=X(le,oe,Oe,Ae,Z[se+12],xt,2368359562),Ae=we(Ae,le,oe,Oe,Z[se+5],dt,4294588738),Oe=we(Oe,Ae,le,oe,Z[se+8],ze,2272392833),oe=we(oe,Oe,Ae,le,Z[se+11],Ye,1839030562),le=we(le,oe,Oe,Ae,Z[se+14],Zt,4259657740),Ae=we(Ae,le,oe,Oe,Z[se+1],dt,2763975236),Oe=we(Oe,Ae,le,oe,Z[se+4],ze,1272893353),oe=we(oe,Oe,Ae,le,Z[se+7],Ye,4139469664),le=we(le,oe,Oe,Ae,Z[se+10],Zt,3200236656),Ae=we(Ae,le,oe,Oe,Z[se+13],dt,681279174),Oe=we(Oe,Ae,le,oe,Z[se+0],ze,3936430074),oe=we(oe,Oe,Ae,le,Z[se+3],Ye,3572445317),le=we(le,oe,Oe,Ae,Z[se+6],Zt,76029189),Ae=we(Ae,le,oe,Oe,Z[se+9],dt,3654602809),Oe=we(Oe,Ae,le,oe,Z[se+12],ze,3873151461),oe=we(oe,Oe,Ae,le,Z[se+15],Ye,530742520),le=we(le,oe,Oe,Ae,Z[se+2],Zt,3299628645),Ae=Q(Ae,le,oe,Oe,Z[se+0],Mt,4096336452),Oe=Q(Oe,Ae,le,oe,Z[se+7],nt,1126891415),oe=Q(oe,Oe,Ae,le,Z[se+14],rt,2878612391),le=Q(le,oe,Oe,Ae,Z[se+5],gt,4237533241),Ae=Q(Ae,le,oe,Oe,Z[se+12],Mt,1700485571),Oe=Q(Oe,Ae,le,oe,Z[se+3],nt,2399980690),oe=Q(oe,Oe,Ae,le,Z[se+10],rt,4293915773),le=Q(le,oe,Oe,Ae,Z[se+1],gt,2240044497),Ae=Q(Ae,le,oe,Oe,Z[se+8],Mt,1873313359),Oe=Q(Oe,Ae,le,oe,Z[se+15],nt,4264355552),oe=Q(oe,Oe,Ae,le,Z[se+6],rt,2734768916),le=Q(le,oe,Oe,Ae,Z[se+13],gt,1309151649),Ae=Q(Ae,le,oe,Oe,Z[se+4],Mt,4149444226),Oe=Q(Oe,Ae,le,oe,Z[se+11],nt,3174756917),oe=Q(oe,Oe,Ae,le,Z[se+2],rt,718787259),le=Q(le,oe,Oe,Ae,Z[se+9],gt,3951481745),Ae=D(Ae,pe),le=D(le,me),oe=D(oe,be),Oe=D(Oe,_e);var ft=ke(Ae)+ke(le)+ke(oe)+ke(Oe);return ft.toLowerCase()},us.closeMediaStream=function(C){if(C)try{var R;if(C.getTracks){R=C.getTracks();var D=t(R),H;try{for(D.s();!(H=D.n()).done;){var F=H.value;F.stop()}}catch(re){D.e(re)}finally{D.f()}}else{R=C.getAudioTracks();var q=t(R),G;try{for(q.s();!(G=q.n()).done;){var te=G.value;te.stop()}}catch(re){q.e(re)}finally{q.f()}R=C.getVideoTracks();var X=t(R),we;try{for(X.s();!(we=X.n()).done;){var Q=we.value;Q.stop()}}catch(re){X.e(re)}finally{X.f()}}}catch{(typeof C.stop=="function"||f(C.stop)==="object")&&C.stop()}},us.cloneArray=function(C){return C&&C.slice()||[]},us.cloneObject=function(C){var R=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return C&&Object.assign({},C)||R},us}var dc={exports:{}},il=typeof Reflect=="object"?Reflect:null,Yf=il&&typeof il.apply=="function"?il.apply:function(t,r,l){return Function.prototype.apply.call(t,r,l)},zo;il&&typeof il.ownKeys=="function"?zo=il.ownKeys:Object.getOwnPropertySymbols?zo=function(t){return Object.getOwnPropertyNames(t).concat(Object.getOwnPropertySymbols(t))}:zo=function(t){return Object.getOwnPropertyNames(t)};function t0(f){console&&console.warn&&console.warn(f)}var Jf=Number.isNaN||function(t){return t!==t};function Ft(){Ft.init.call(this)}dc.exports=Ft,dc.exports.once=i0,Ft.EventEmitter=Ft,Ft.prototype._events=void 0,Ft.prototype._eventsCount=0,Ft.prototype._maxListeners=void 0;var Qf=10;function Vo(f){if(typeof f!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof f)}Object.defineProperty(Ft,"defaultMaxListeners",{enumerable:!0,get:function(){return Qf},set:function(f){if(typeof f!="number"||f<0||Jf(f))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+f+".");Qf=f}}),Ft.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},Ft.prototype.setMaxListeners=function(t){if(typeof t!="number"||t<0||Jf(t))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+t+".");return this._maxListeners=t,this};function Xf(f){return f._maxListeners===void 0?Ft.defaultMaxListeners:f._maxListeners}Ft.prototype.getMaxListeners=function(){return Xf(this)},Ft.prototype.emit=function(t){for(var r=[],l=1;l<arguments.length;l++)r.push(arguments[l]);var u=t==="error",s=this._events;if(s!==void 0)u=u&&s.error===void 0;else if(!u)return!1;if(u){var n;if(r.length>0&&(n=r[0]),n instanceof Error)throw n;var g=new Error("Unhandled error."+(n?" ("+n.message+")":""));throw g.context=n,g}var _=s[t];if(_===void 0)return!1;if(typeof _=="function")Yf(_,this,r);else for(var v=_.length,C=rh(_,v),l=0;l<v;++l)Yf(C[l],this,r);return!0};function Zf(f,t,r,l){var u,s,n;if(Vo(r),s=f._events,s===void 0?(s=f._events=Object.create(null),f._eventsCount=0):(s.newListener!==void 0&&(f.emit("newListener",t,r.listener?r.listener:r),s=f._events),n=s[t]),n===void 0)n=s[t]=r,++f._eventsCount;else if(typeof n=="function"?n=s[t]=l?[r,n]:[n,r]:l?n.unshift(r):n.push(r),u=Xf(f),u>0&&n.length>u&&!n.warned){n.warned=!0;var g=new Error("Possible EventEmitter memory leak detected. "+n.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");g.name="MaxListenersExceededWarning",g.emitter=f,g.type=t,g.count=n.length,t0(g)}return f}Ft.prototype.addListener=function(t,r){return Zf(this,t,r,!1)},Ft.prototype.on=Ft.prototype.addListener,Ft.prototype.prependListener=function(t,r){return Zf(this,t,r,!0)};function s0(){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 eh(f,t,r){var l={fired:!1,wrapFn:void 0,target:f,type:t,listener:r},u=s0.bind(l);return u.listener=r,l.wrapFn=u,u}Ft.prototype.once=function(t,r){return Vo(r),this.on(t,eh(this,t,r)),this},Ft.prototype.prependOnceListener=function(t,r){return Vo(r),this.prependListener(t,eh(this,t,r)),this},Ft.prototype.removeListener=function(t,r){var l,u,s,n,g;if(Vo(r),u=this._events,u===void 0)return this;if(l=u[t],l===void 0)return this;if(l===r||l.listener===r)--this._eventsCount===0?this._events=Object.create(null):(delete u[t],u.removeListener&&this.emit("removeListener",t,l.listener||r));else if(typeof l!="function"){for(s=-1,n=l.length-1;n>=0;n--)if(l[n]===r||l[n].listener===r){g=l[n].listener,s=n;break}if(s<0)return this;s===0?l.shift():r0(l,s),l.length===1&&(u[t]=l[0]),u.removeListener!==void 0&&this.emit("removeListener",t,g||r)}return this},Ft.prototype.off=Ft.prototype.removeListener,Ft.prototype.removeAllListeners=function(t){var r,l,u;if(l=this._events,l===void 0)return this;if(l.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):l[t]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete l[t]),this;if(arguments.length===0){var s=Object.keys(l),n;for(u=0;u<s.length;++u)n=s[u],n!=="removeListener"&&this.removeAllListeners(n);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(r=l[t],typeof r=="function")this.removeListener(t,r);else if(r!==void 0)for(u=r.length-1;u>=0;u--)this.removeListener(t,r[u]);return this};function th(f,t,r){var l=f._events;if(l===void 0)return[];var u=l[t];return u===void 0?[]:typeof u=="function"?r?[u.listener||u]:[u]:r?n0(u):rh(u,u.length)}Ft.prototype.listeners=function(t){return th(this,t,!0)},Ft.prototype.rawListeners=function(t){return th(this,t,!1)},Ft.listenerCount=function(f,t){return typeof f.listenerCount=="function"?f.listenerCount(t):sh.call(f,t)},Ft.prototype.listenerCount=sh;function sh(f){var t=this._events;if(t!==void 0){var r=t[f];if(typeof r=="function")return 1;if(r!==void 0)return r.length}return 0}Ft.prototype.eventNames=function(){return this._eventsCount>0?zo(this._events):[]};function rh(f,t){for(var r=new Array(t),l=0;l<t;++l)r[l]=f[l];return r}function r0(f,t){for(;t+1<f.length;t++)f[t]=f[t+1];f.pop()}function n0(f){for(var t=new Array(f.length),r=0;r<t.length;++r)t[r]=f[r].listener||f[r];return t}function i0(f,t){return new Promise(function(r,l){function u(n){f.removeListener(t,s),l(n)}function s(){typeof f.removeListener=="function"&&f.removeListener("error",u),r([].slice.call(arguments))}nh(f,t,s,{once:!0}),t!=="error"&&a0(f,u,{once:!0})})}function a0(f,t,r){typeof f.on=="function"&&nh(f,"error",t,r)}function nh(f,t,r,l){if(typeof f.on=="function")l.once?f.once(t,r):f.on(t,r);else if(typeof f.addEventListener=="function")f.addEventListener(t,function u(s){l.once&&f.removeEventListener(t,u),r(s)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof f)}var ys=dc.exports,fc={exports:{}},hc,ih;function l0(){if(ih)return hc;ih=1;var f=1e3,t=f*60,r=t*60,l=r*24,u=l*7,s=l*365.25;hc=function(C,R){R=R||{};var D=typeof C;if(D==="string"&&C.length>0)return n(C);if(D==="number"&&isFinite(C))return R.long?_(C):g(C);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(C))};function n(C){if(C=String(C),!(C.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(C);if(R){var D=parseFloat(R[1]),H=(R[2]||"ms").toLowerCase();switch(H){case"years":case"year":case"yrs":case"yr":case"y":return D*s;case"weeks":case"week":case"w":return D*u;case"days":case"day":case"d":return D*l;case"hours":case"hour":case"hrs":case"hr":case"h":return D*r;case"minutes":case"minute":case"mins":case"min":case"m":return D*t;case"seconds":case"second":case"secs":case"sec":case"s":return D*f;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return D;default:return}}}}function g(C){var R=Math.abs(C);return R>=l?Math.round(C/l)+"d":R>=r?Math.round(C/r)+"h":R>=t?Math.round(C/t)+"m":R>=f?Math.round(C/f)+"s":C+"ms"}function _(C){var R=Math.abs(C);return R>=l?v(C,R,l,"day"):R>=r?v(C,R,r,"hour"):R>=t?v(C,R,t,"minute"):R>=f?v(C,R,f,"second"):C+" ms"}function v(C,R,D,H){var F=R>=D*1.5;return Math.round(C/D)+" "+H+(F?"s":"")}return hc}function o0(f){r.debug=r,r.default=r,r.coerce=_,r.disable=s,r.enable=u,r.enabled=n,r.humanize=l0(),r.destroy=v,Object.keys(f).forEach(C=>{r[C]=f[C]}),r.names=[],r.skips=[],r.formatters={};function t(C){let R=0;for(let D=0;D<C.length;D++)R=(R<<5)-R+C.charCodeAt(D),R|=0;return r.colors[Math.abs(R)%r.colors.length]}r.selectColor=t;function r(C){let R,D=null,H,F;function q(...G){if(!q.enabled)return;const te=q,X=Number(new Date),we=X-(R||X);te.diff=we,te.prev=R,te.curr=X,R=X,G[0]=r.coerce(G[0]),typeof G[0]!="string"&&G.unshift("%O");let Q=0;G[0]=G[0].replace(/%([a-zA-Z%])/g,(ke,Ne)=>{if(ke==="%%")return"%";Q++;const Z=r.formatters[Ne];if(typeof Z=="function"){const se=G[Q];ke=Z.call(te,se),G.splice(Q,1),Q--}return ke}),r.formatArgs.call(te,G),(te.log||r.log).apply(te,G)}return q.namespace=C,q.useColors=r.useColors(),q.color=r.selectColor(C),q.extend=l,q.destroy=r.destroy,Object.defineProperty(q,"enabled",{enumerable:!0,configurable:!1,get:()=>D!==null?D:(H!==r.namespaces&&(H=r.namespaces,F=r.enabled(C)),F),set:G=>{D=G}}),typeof r.init=="function"&&r.init(q),q}function l(C,R){const D=r(this.namespace+(typeof R>"u"?":":R)+C);return D.log=this.log,D}function u(C){r.save(C),r.namespaces=C,r.names=[],r.skips=[];let R;const D=(typeof C=="string"?C:"").split(/[\s,]+/),H=D.length;for(R=0;R<H;R++)D[R]&&(C=D[R].replace(/\*/g,".*?"),C[0]==="-"?r.skips.push(new RegExp("^"+C.slice(1)+"$")):r.names.push(new RegExp("^"+C+"$")))}function s(){const C=[...r.names.map(g),...r.skips.map(g).map(R=>"-"+R)].join(",");return r.enable(""),C}function n(C){if(C[C.length-1]==="*")return!0;let R,D;for(R=0,D=r.skips.length;R<D;R++)if(r.skips[R].test(C))return!1;for(R=0,D=r.names.length;R<D;R++)if(r.names[R].test(C))return!0;return!1}function g(C){return C.toString().substring(2,C.toString().length-2).replace(/\.\*\?$/,"*")}function _(C){return C instanceof Error?C.stack||C.message:C}function v(){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 u0=o0;(function(f,t){t.formatArgs=l,t.save=u,t.load=s,t.useColors=r,t.storage=n(),t.destroy=(()=>{let _=!1;return()=>{_||(_=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),t.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function 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 l(_){if(_[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+_[0]+(this.useColors?"%c ":" ")+"+"+f.exports.humanize(this.diff),!this.useColors)return;const v="color: "+this.color;_.splice(1,0,v,"color: inherit");let C=0,R=0;_[0].replace(/%[a-zA-Z%]/g,D=>{D!=="%%"&&(C++,D==="%c"&&(R=C))}),_.splice(R,0,v)}t.log=console.debug||console.log||(()=>{});function u(_){try{_?t.storage.setItem("debug",_):t.storage.removeItem("debug")}catch{}}function s(){let _;try{_=t.storage.getItem("debug")}catch{}return!_&&typeof process<"u"&&"env"in process&&(_=process.env.DEBUG),_}function n(){try{return localStorage}catch{}}f.exports=u0(t);const{formatters:g}=f.exports;g.j=function(_){try{return JSON.stringify(_)}catch(v){return"[UnexpectedJSONParseError]: "+v.message}}})(fc,fc.exports);var al=fc.exports;function c0(f,t){if(!(f instanceof t))throw new TypeError("Cannot call a class as a function")}function ah(f,t){for(var r=0;r<t.length;r++){var l=t[r];l.enumerable=l.enumerable||!1,l.configurable=!0,"value"in l&&(l.writable=!0),Object.defineProperty(f,l.key,l)}}function d0(f,t,r){return t&&ah(f.prototype,t),r&&ah(f,r),f}var ll=al,ol="JsSIP",Ts=function(){function f(t){c0(this,f),t?(this._debug=ll.default("".concat(ol,":").concat(t)),this._warn=ll.default("".concat(ol,":WARN:").concat(t)),this._error=ll.default("".concat(ol,":ERROR:").concat(t))):(this._debug=ll.default(ol),this._warn=ll.default("".concat(ol,":WARN")),this._error=ll.default("".concat(ol,":ERROR"))),this._debug.log=console.info.bind(console),this._warn.log=console.warn.bind(console),this._error.log=console.error.bind(console)}return d0(f,[{key:"debug",get:function(){return this._debug}},{key:"warn",get:function(){return this._warn}},{key:"error",get:function(){return this._error}}]),f}(),sr={},lh={},oh={exports:{}},uh=oh.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(f){return f.encoding?"rtpmap:%d %s/%s/%s":f.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(f){return f.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(f){return f.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(f){return"extmap:%d"+(f.direction?"/%s":"%v")+(f["encrypt-uri"]?" %s":"%v")+" %s"+(f.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(f){return f.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(f){var t="candidate:%s %d %s %d %s %d typ %s";return t+=f.raddr!=null?" raddr %s rport %d":"%v%v",t+=f.tcptype!=null?" tcptype %s":"%v",f.generation!=null&&(t+=" generation %d"),t+=f["network-id"]!=null?" network-id %d":"%v",t+=f["network-cost"]!=null?" network-cost %d":"%v",t}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(f){var t="ssrc:%d";return f.attribute!=null&&(t+=" %s",f.value!=null&&(t+=":%s")),t}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(f){return f.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(f){return f.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(f){return"imageattr:%s %s %s"+(f.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(f){return"simulcast:%s %s"+(f.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(f){return"ts-refclk:%s"+(f.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(f){var t="mediaclk:";return t+=f.id!=null?"id=%s %s":"%v%s",t+=f.mediaClockValue!=null?"=%s":"",t+=f.rateNumerator!=null?" rate=%s":"",t+=f.rateDenominator!=null?"/%s":"",t}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};Object.keys(uh).forEach(function(f){var t=uh[f];t.forEach(function(r){r.reg||(r.reg=/(.*)/),r.format||(r.format="%s")})});var ch=oh.exports;(function(f){var t=function(g){return String(Number(g))===g?Number(g):g},r=function(g,_,v,C){if(C&&!v)_[C]=t(g[1]);else for(var R=0;R<v.length;R+=1)g[R+1]!=null&&(_[v[R]]=t(g[R+1]))},l=function(g,_,v){var C=g.name&&g.names;g.push&&!_[g.push]?_[g.push]=[]:C&&!_[g.name]&&(_[g.name]={});var R=g.push?{}:C?_[g.name]:_;r(v.match(g.reg),R,g.names,g.name),g.push&&_[g.push].push(R)},u=ch,s=RegExp.prototype.test.bind(/^([a-z])=(.*)/);f.parse=function(g){var _={},v=[],C=_;return g.split(/(\r\n|\r|\n)/).filter(s).forEach(function(R){var D=R[0],H=R.slice(2);D==="m"&&(v.push({rtp:[],fmtp:[]}),C=v[v.length-1]);for(var F=0;F<(u[D]||[]).length;F+=1){var q=u[D][F];if(q.reg.test(H))return l(q,C,H)}}),_.media=v,_};var n=function(g,_){var v=_.split(/=(.+)/,2);return v.length===2?g[v[0]]=t(v[1]):v.length===1&&_.length>1&&(g[v[0]]=void 0),g};f.parseParams=function(g){return g.split(/;\s?/).reduce(n,{})},f.parseFmtpConfig=f.parseParams,f.parsePayloads=function(g){return g.toString().split(" ").map(Number)},f.parseRemoteCandidates=function(g){for(var _=[],v=g.split(" ").map(t),C=0;C<v.length;C+=3)_.push({component:v[C],ip:v[C+1],port:v[C+2]});return _},f.parseImageAttributes=function(g){return g.split(" ").map(function(_){return _.substring(1,_.length-1).split(",").reduce(n,{})})},f.parseSimulcastStreamList=function(g){return g.split(";").map(function(_){return _.split(",").map(function(v){var C,R=!1;return v[0]!=="~"?C=t(v):(C=t(v.substring(1,v.length)),R=!0),{scid:C,paused:R}})})}})(lh);var _c=ch,f0=/%[sdv%]/g,h0=function(f){var t=1,r=arguments,l=r.length;return f.replace(f0,function(u){if(t>=l)return u;var s=r[t];switch(t+=1,u){case"%%":return"%";case"%s":return String(s);case"%d":return Number(s);case"%v":return""}})},Ml=function(f,t,r){var l=t.format instanceof Function?t.format(t.push?r:r[t.name]):t.format,u=[f+"="+l];if(t.names)for(var s=0;s<t.names.length;s+=1){var n=t.names[s];t.name?u.push(r[t.name][n]):u.push(r[t.names[s]])}else u.push(r[t.name]);return h0.apply(null,u)},_0=["v","o","s","i","u","e","p","c","b","t","r","z","a"],p0=["i","c","b","a"],m0=function(f,t){t=t||{},f.version==null&&(f.version=0),f.name==null&&(f.name=" "),f.media.forEach(function(s){s.payloads==null&&(s.payloads="")});var r=t.outerOrder||_0,l=t.innerOrder||p0,u=[];return r.forEach(function(s){_c[s].forEach(function(n){n.name in f&&f[n.name]!=null?u.push(Ml(s,n,f)):n.push in f&&f[n.push]!=null&&f[n.push].forEach(function(g){u.push(Ml(s,n,g))})})}),f.media.forEach(function(s){u.push(Ml("m",_c.m[0],s)),l.forEach(function(n){_c[n].forEach(function(g){g.name in s&&s[g.name]!=null?u.push(Ml(n,g,s)):g.push in s&&s[g.push]!=null&&s[g.push].forEach(function(_){u.push(Ml(n,g,_))})})})}),u.join(`\r
4
+ `?(d||e++,o=1,d=!1):T==="\r"||T==="\u2028"||T==="\u2029"?(e++,o=1,d=!0):(o++,d=!1)}return{line:e,column:o}}var $r=Ti(),K=oc(),J={},da=s[u]();if(da===null||n!==l.length){var fa=Math.max(n,g),ha=fa<l.length?l.charAt(fa):null,a=Ya();return new this.SyntaxError(xl(_),ha,fa,a.line,a.column),-1}return J},toSource:function(){return this._source}};return t.SyntaxError=function(r,l,u,s,n){function g(_,v){var C,R;switch(_.length){case 0:C="end of input";break;case 1:C=_[0];break;default:C=_.slice(0,_.length-1).join(", ")+" or "+_[_.length-1]}return R=v?f(v):"end of input","Expected "+C+" but "+R+" found."}this.name="SyntaxError",this.expected=r,this.found=l,this.message=g(r,l),this.offset=u,this.line=s,this.column=n},t.SyntaxError.prototype=Error.prototype,t}()),uc}var cc,Gf;function Ti(){if(Gf)return cc;Gf=1;function f(v,C){var R;if(typeof Symbol>"u"||v[Symbol.iterator]==null){if(Array.isArray(v)||(R=t(v))||C&&v&&typeof v.length=="number"){R&&(v=R);var D=0,H=function(){};return{s:H,n:function(){return D>=v.length?{done:!0}:{done:!1,value:v[D++]}},e:function(X){throw X},f:H}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
5
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var F=!0,q=!1,G;return{s:function(){R=v[Symbol.iterator]()},n:function(){var X=R.next();return F=X.done,X},e:function(X){q=!0,G=X},f:function(){try{!F&&R.return!=null&&R.return()}finally{if(q)throw G}}}}function t(v,C){if(v){if(typeof v=="string")return r(v,C);var R=Object.prototype.toString.call(v).slice(8,-1);if(R==="Object"&&v.constructor&&(R=v.constructor.name),R==="Map"||R==="Set")return Array.from(v);if(R==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(R))return r(v,C)}}function r(v,C){(C==null||C>v.length)&&(C=v.length);for(var R=0,D=new Array(C);R<C;R++)D[R]=v[R];return D}function l(v,C){if(!(v instanceof C))throw new TypeError("Cannot call a class as a function")}function u(v,C){for(var R=0;R<C.length;R++){var D=C[R];D.enumerable=D.enumerable||!1,D.configurable=!0,"value"in D&&(D.writable=!0),Object.defineProperty(v,D.key,D)}}function s(v,C,R){return C&&u(v.prototype,C),R&&u(v,R),v}var n=hs,g=Bs(),_=on();return cc=function(){s(v,null,[{key:"parse",value:function(R){if(R=_.parse(R,"SIP_URI"),R!==-1)return R}}]);function v(C,R,D,H){var F=arguments.length>4&&arguments[4]!==void 0?arguments[4]:{},q=arguments.length>5&&arguments[5]!==void 0?arguments[5]:{};if(l(this,v),!D)throw new TypeError('missing or invalid "host" parameter');this._parameters={},this._headers={},this._scheme=C||n.SIP,this._user=R,this._host=D,this._port=H;for(var G in F)Object.prototype.hasOwnProperty.call(F,G)&&this.setParam(G,F[G]);for(var te in q)Object.prototype.hasOwnProperty.call(q,te)&&this.setHeader(te,q[te])}return s(v,[{key:"setParam",value:function(R,D){R&&(this._parameters[R.toLowerCase()]=typeof D>"u"||D===null?null:D.toString())}},{key:"getParam",value:function(R){if(R)return this._parameters[R.toLowerCase()]}},{key:"hasParam",value:function(R){if(R)return this._parameters.hasOwnProperty(R.toLowerCase())&&!0||!1}},{key:"deleteParam",value:function(R){if(R=R.toLowerCase(),this._parameters.hasOwnProperty(R)){var D=this._parameters[R];return delete this._parameters[R],D}}},{key:"clearParams",value:function(){this._parameters={}}},{key:"setHeader",value:function(R,D){this._headers[g.headerize(R)]=Array.isArray(D)?D:[D]}},{key:"getHeader",value:function(R){if(R)return this._headers[g.headerize(R)]}},{key:"hasHeader",value:function(R){if(R)return this._headers.hasOwnProperty(g.headerize(R))&&!0||!1}},{key:"deleteHeader",value:function(R){if(R=g.headerize(R),this._headers.hasOwnProperty(R)){var D=this._headers[R];return delete this._headers[R],D}}},{key:"clearHeaders",value:function(){this._headers={}}},{key:"clone",value:function(){return new v(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 R=[],D="".concat(this._scheme,":");this._user&&(D+="".concat(g.escapeUser(this._user),"@")),D+=this._host,(this._port||this._port===0)&&(D+=":".concat(this._port));for(var H in this._parameters)Object.prototype.hasOwnProperty.call(this._parameters,H)&&(D+=";".concat(H),this._parameters[H]!==null&&(D+="=".concat(this._parameters[H])));for(var F in this._headers)if(Object.prototype.hasOwnProperty.call(this._headers,F)){var q=f(this._headers[F]),G;try{for(q.s();!(G=q.n()).done;){var te=G.value;R.push("".concat(F,"=").concat(te))}}catch(X){q.e(X)}finally{q.f()}}return R.length>0&&(D+="?".concat(R.join("&"))),D}},{key:"toAor",value:function(R){var D="".concat(this._scheme,":");return this._user&&(D+="".concat(g.escapeUser(this._user),"@")),D+=this._host,R&&(this._port||this._port===0)&&(D+=":".concat(this._port)),D}},{key:"scheme",get:function(){return this._scheme},set:function(R){this._scheme=R.toLowerCase()}},{key:"user",get:function(){return this._user},set:function(R){this._user=R}},{key:"host",get:function(){return this._host},set:function(R){this._host=R.toLowerCase()}},{key:"port",get:function(){return this._port},set:function(R){this._port=R===0?R:parseInt(R,10)||null}}]),v}(),cc}var Wf;function Bs(){if(Wf)return us;Wf=1;function f(C){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?f=function(D){return typeof D}:f=function(D){return D&&typeof Symbol=="function"&&D.constructor===Symbol&&D!==Symbol.prototype?"symbol":typeof D},f(C)}function t(C,R){var D;if(typeof Symbol>"u"||C[Symbol.iterator]==null){if(Array.isArray(C)||(D=r(C))||R&&C&&typeof C.length=="number"){D&&(C=D);var H=0,F=function(){};return{s:F,n:function(){return H>=C.length?{done:!0}:{done:!1,value:C[H++]}},e:function(we){throw we},f:F}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
6
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var q=!0,G=!1,te;return{s:function(){D=C[Symbol.iterator]()},n:function(){var we=D.next();return q=we.done,we},e:function(we){G=!0,te=we},f:function(){try{!q&&D.return!=null&&D.return()}finally{if(G)throw te}}}}function r(C,R){if(C){if(typeof C=="string")return l(C,R);var D=Object.prototype.toString.call(C).slice(8,-1);if(D==="Object"&&C.constructor&&(D=C.constructor.name),D==="Map"||D==="Set")return Array.from(C);if(D==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(D))return l(C,R)}}function l(C,R){(R==null||R>C.length)&&(R=C.length);for(var D=0,H=new Array(R);D<R;D++)H[D]=C[D];return H}var u=hs,s=Ti(),n=on();us.str_utf8_length=function(C){return unescape(encodeURIComponent(C)).length};var g=us.isFunction=function(C){return C!==void 0?Object.prototype.toString.call(C)==="[object Function]":!1};us.isString=function(C){return C!==void 0?Object.prototype.toString.call(C)==="[object String]":!1},us.isDecimal=function(C){return!isNaN(C)&&parseFloat(C)===parseInt(C,10)},us.isEmpty=function(C){return C===null||C===""||C===void 0||Array.isArray(C)&&C.length===0||typeof C=="number"&&isNaN(C)},us.hasMethods=function(C){for(var R=arguments.length,D=new Array(R>1?R-1:0),H=1;H<R;H++)D[H-1]=arguments[H];for(var F=0,q=D;F<q.length;F++){var G=q[F];if(g(C[G]))return!1}return!0};var _=us.createRandomToken=function(C){var R=arguments.length>1&&arguments[1]!==void 0?arguments[1]:32,D,H,F="";for(D=0;D<C;D++)H=Math.random()*R|0,F+=H.toString(R);return F};us.newTag=function(){return _(10)},us.newUUID=function(){var C="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(R){var D=Math.random()*16|0,H=R==="x"?D:D&3|8;return H.toString(16)});return C},us.hostType=function(C){if(C){if(C=n.parse(C,"host"),C!==-1)return C.host_type}else return};var v=us.escapeUser=function(C){return encodeURIComponent(decodeURIComponent(C)).replace(/%3A/ig,":").replace(/%2B/ig,"+").replace(/%3F/ig,"?").replace(/%2F/ig,"/")};return us.normalizeTarget=function(C,R){if(C){if(C instanceof s)return C;if(typeof C=="string"){var D=C.split("@"),H,F;switch(D.length){case 1:if(!R)return;H=C,F=R;break;case 2:H=D[0],F=D[1];break;default:H=D.slice(0,D.length-1).join("@"),F=D[D.length-1]}H=H.replace(/^(sips?|tel):/i,""),/^[-.()]*\+?[0-9\-.()]+$/.test(H)&&(H=H.replace(/[-.()]/g,"")),C="".concat(u.SIP,":").concat(v(H),"@").concat(F);var q;return(q=s.parse(C))?q:void 0}else return}else return},us.headerize=function(C){var R={"Call-Id":"Call-ID",Cseq:"CSeq","Www-Authenticate":"WWW-Authenticate"},D=C.toLowerCase().replace(/_/g,"-").split("-"),H="",F=D.length,q;for(q=0;q<F;q++)q!==0&&(H+="-"),H+=D[q].charAt(0).toUpperCase()+D[q].substring(1);return R[H]&&(H=R[H]),H},us.sipErrorCause=function(C){for(var R in u.SIP_ERROR_CAUSES)if(u.SIP_ERROR_CAUSES[R].indexOf(C)!==-1)return u.causes[R];return u.causes.SIP_FAILURE_CODE},us.getRandomTestNetIP=function(){function C(R,D){return Math.floor(Math.random()*(D-R+1)+R)}return"192.0.2.".concat(C(1,254))},us.calculateMD5=function(C){function R(Fe,He){return Fe<<He|Fe>>>32-He}function D(Fe,He){var qe=Fe&2147483648,yt=He&2147483648,Ct=Fe&1073741824,ns=He&1073741824,Ut=(Fe&1073741823)+(He&1073741823);return Ct&ns?Ut^2147483648^qe^yt:Ct|ns?Ut&1073741824?Ut^3221225472^qe^yt:Ut^1073741824^qe^yt:Ut^qe^yt}function H(Fe,He,qe){return Fe&He|~Fe&qe}function F(Fe,He,qe){return Fe&qe|He&~qe}function q(Fe,He,qe){return Fe^He^qe}function G(Fe,He,qe){return He^(Fe|~qe)}function te(Fe,He,qe,yt,Ct,ns,Ut){return Fe=D(Fe,D(D(H(He,qe,yt),Ct),Ut)),D(R(Fe,ns),He)}function X(Fe,He,qe,yt,Ct,ns,Ut){return Fe=D(Fe,D(D(F(He,qe,yt),Ct),Ut)),D(R(Fe,ns),He)}function we(Fe,He,qe,yt,Ct,ns,Ut){return Fe=D(Fe,D(D(q(He,qe,yt),Ct),Ut)),D(R(Fe,ns),He)}function Q(Fe,He,qe,yt,Ct,ns,Ut){return Fe=D(Fe,D(D(G(He,qe,yt),Ct),Ut)),D(R(Fe,ns),He)}function re(Fe){for(var He,qe=Fe.length,yt=qe+8,Ct=(yt-yt%64)/64,ns=(Ct+1)*16,Ut=new Array(ns-1),ar=0,vs=0;vs<qe;)He=(vs-vs%4)/4,ar=vs%4*8,Ut[He]=Ut[He]|Fe.charCodeAt(vs)<<ar,vs++;return He=(vs-vs%4)/4,ar=vs%4*8,Ut[He]=Ut[He]|128<<ar,Ut[ns-2]=qe<<3,Ut[ns-1]=qe>>>29,Ut}function ke(Fe){var He="",qe="",yt,Ct;for(Ct=0;Ct<=3;Ct++)yt=Fe>>>Ct*8&255,qe="0".concat(yt.toString(16)),He=He+qe.substr(qe.length-2,2);return He}function Ne(Fe){for(var He="",qe=0;qe<Fe.length;qe++){var yt=Fe.charCodeAt(qe);yt<128?He+=String.fromCharCode(yt):yt>127&&yt<2048?(He+=String.fromCharCode(yt>>6|192),He+=String.fromCharCode(yt&63|128)):(He+=String.fromCharCode(yt>>12|224),He+=String.fromCharCode(yt>>6&63|128),He+=String.fromCharCode(yt&63|128))}return He}var Z=[],se,pe,me,be,_e,Ae,le,oe,Oe,rs=7,Re=12,ye=17,ge=22,Le=5,et=9,vt=14,xt=20,dt=4,ze=11,Ye=16,Zt=23,Mt=6,nt=10,rt=15,gt=21;for(C=Ne(C),Z=re(C),Ae=1732584193,le=4023233417,oe=2562383102,Oe=271733878,se=0;se<Z.length;se+=16)pe=Ae,me=le,be=oe,_e=Oe,Ae=te(Ae,le,oe,Oe,Z[se+0],rs,3614090360),Oe=te(Oe,Ae,le,oe,Z[se+1],Re,3905402710),oe=te(oe,Oe,Ae,le,Z[se+2],ye,606105819),le=te(le,oe,Oe,Ae,Z[se+3],ge,3250441966),Ae=te(Ae,le,oe,Oe,Z[se+4],rs,4118548399),Oe=te(Oe,Ae,le,oe,Z[se+5],Re,1200080426),oe=te(oe,Oe,Ae,le,Z[se+6],ye,2821735955),le=te(le,oe,Oe,Ae,Z[se+7],ge,4249261313),Ae=te(Ae,le,oe,Oe,Z[se+8],rs,1770035416),Oe=te(Oe,Ae,le,oe,Z[se+9],Re,2336552879),oe=te(oe,Oe,Ae,le,Z[se+10],ye,4294925233),le=te(le,oe,Oe,Ae,Z[se+11],ge,2304563134),Ae=te(Ae,le,oe,Oe,Z[se+12],rs,1804603682),Oe=te(Oe,Ae,le,oe,Z[se+13],Re,4254626195),oe=te(oe,Oe,Ae,le,Z[se+14],ye,2792965006),le=te(le,oe,Oe,Ae,Z[se+15],ge,1236535329),Ae=X(Ae,le,oe,Oe,Z[se+1],Le,4129170786),Oe=X(Oe,Ae,le,oe,Z[se+6],et,3225465664),oe=X(oe,Oe,Ae,le,Z[se+11],vt,643717713),le=X(le,oe,Oe,Ae,Z[se+0],xt,3921069994),Ae=X(Ae,le,oe,Oe,Z[se+5],Le,3593408605),Oe=X(Oe,Ae,le,oe,Z[se+10],et,38016083),oe=X(oe,Oe,Ae,le,Z[se+15],vt,3634488961),le=X(le,oe,Oe,Ae,Z[se+4],xt,3889429448),Ae=X(Ae,le,oe,Oe,Z[se+9],Le,568446438),Oe=X(Oe,Ae,le,oe,Z[se+14],et,3275163606),oe=X(oe,Oe,Ae,le,Z[se+3],vt,4107603335),le=X(le,oe,Oe,Ae,Z[se+8],xt,1163531501),Ae=X(Ae,le,oe,Oe,Z[se+13],Le,2850285829),Oe=X(Oe,Ae,le,oe,Z[se+2],et,4243563512),oe=X(oe,Oe,Ae,le,Z[se+7],vt,1735328473),le=X(le,oe,Oe,Ae,Z[se+12],xt,2368359562),Ae=we(Ae,le,oe,Oe,Z[se+5],dt,4294588738),Oe=we(Oe,Ae,le,oe,Z[se+8],ze,2272392833),oe=we(oe,Oe,Ae,le,Z[se+11],Ye,1839030562),le=we(le,oe,Oe,Ae,Z[se+14],Zt,4259657740),Ae=we(Ae,le,oe,Oe,Z[se+1],dt,2763975236),Oe=we(Oe,Ae,le,oe,Z[se+4],ze,1272893353),oe=we(oe,Oe,Ae,le,Z[se+7],Ye,4139469664),le=we(le,oe,Oe,Ae,Z[se+10],Zt,3200236656),Ae=we(Ae,le,oe,Oe,Z[se+13],dt,681279174),Oe=we(Oe,Ae,le,oe,Z[se+0],ze,3936430074),oe=we(oe,Oe,Ae,le,Z[se+3],Ye,3572445317),le=we(le,oe,Oe,Ae,Z[se+6],Zt,76029189),Ae=we(Ae,le,oe,Oe,Z[se+9],dt,3654602809),Oe=we(Oe,Ae,le,oe,Z[se+12],ze,3873151461),oe=we(oe,Oe,Ae,le,Z[se+15],Ye,530742520),le=we(le,oe,Oe,Ae,Z[se+2],Zt,3299628645),Ae=Q(Ae,le,oe,Oe,Z[se+0],Mt,4096336452),Oe=Q(Oe,Ae,le,oe,Z[se+7],nt,1126891415),oe=Q(oe,Oe,Ae,le,Z[se+14],rt,2878612391),le=Q(le,oe,Oe,Ae,Z[se+5],gt,4237533241),Ae=Q(Ae,le,oe,Oe,Z[se+12],Mt,1700485571),Oe=Q(Oe,Ae,le,oe,Z[se+3],nt,2399980690),oe=Q(oe,Oe,Ae,le,Z[se+10],rt,4293915773),le=Q(le,oe,Oe,Ae,Z[se+1],gt,2240044497),Ae=Q(Ae,le,oe,Oe,Z[se+8],Mt,1873313359),Oe=Q(Oe,Ae,le,oe,Z[se+15],nt,4264355552),oe=Q(oe,Oe,Ae,le,Z[se+6],rt,2734768916),le=Q(le,oe,Oe,Ae,Z[se+13],gt,1309151649),Ae=Q(Ae,le,oe,Oe,Z[se+4],Mt,4149444226),Oe=Q(Oe,Ae,le,oe,Z[se+11],nt,3174756917),oe=Q(oe,Oe,Ae,le,Z[se+2],rt,718787259),le=Q(le,oe,Oe,Ae,Z[se+9],gt,3951481745),Ae=D(Ae,pe),le=D(le,me),oe=D(oe,be),Oe=D(Oe,_e);var ft=ke(Ae)+ke(le)+ke(oe)+ke(Oe);return ft.toLowerCase()},us.closeMediaStream=function(C){if(C)try{var R;if(C.getTracks){R=C.getTracks();var D=t(R),H;try{for(D.s();!(H=D.n()).done;){var F=H.value;F.stop()}}catch(re){D.e(re)}finally{D.f()}}else{R=C.getAudioTracks();var q=t(R),G;try{for(q.s();!(G=q.n()).done;){var te=G.value;te.stop()}}catch(re){q.e(re)}finally{q.f()}R=C.getVideoTracks();var X=t(R),we;try{for(X.s();!(we=X.n()).done;){var Q=we.value;Q.stop()}}catch(re){X.e(re)}finally{X.f()}}}catch{(typeof C.stop=="function"||f(C.stop)==="object")&&C.stop()}},us.cloneArray=function(C){return C&&C.slice()||[]},us.cloneObject=function(C){var R=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return C&&Object.assign({},C)||R},us}var dc={exports:{}},il=typeof Reflect=="object"?Reflect:null,Kf=il&&typeof il.apply=="function"?il.apply:function(t,r,l){return Function.prototype.apply.call(t,r,l)},zo;il&&typeof il.ownKeys=="function"?zo=il.ownKeys:Object.getOwnPropertySymbols?zo=function(t){return Object.getOwnPropertyNames(t).concat(Object.getOwnPropertySymbols(t))}:zo=function(t){return Object.getOwnPropertyNames(t)};function t0(f){console&&console.warn&&console.warn(f)}var Yf=Number.isNaN||function(t){return t!==t};function Ft(){Ft.init.call(this)}dc.exports=Ft,dc.exports.once=i0,Ft.EventEmitter=Ft,Ft.prototype._events=void 0,Ft.prototype._eventsCount=0,Ft.prototype._maxListeners=void 0;var Jf=10;function Vo(f){if(typeof f!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof f)}Object.defineProperty(Ft,"defaultMaxListeners",{enumerable:!0,get:function(){return Jf},set:function(f){if(typeof f!="number"||f<0||Yf(f))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+f+".");Jf=f}}),Ft.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},Ft.prototype.setMaxListeners=function(t){if(typeof t!="number"||t<0||Yf(t))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+t+".");return this._maxListeners=t,this};function Qf(f){return f._maxListeners===void 0?Ft.defaultMaxListeners:f._maxListeners}Ft.prototype.getMaxListeners=function(){return Qf(this)},Ft.prototype.emit=function(t){for(var r=[],l=1;l<arguments.length;l++)r.push(arguments[l]);var u=t==="error",s=this._events;if(s!==void 0)u=u&&s.error===void 0;else if(!u)return!1;if(u){var n;if(r.length>0&&(n=r[0]),n instanceof Error)throw n;var g=new Error("Unhandled error."+(n?" ("+n.message+")":""));throw g.context=n,g}var _=s[t];if(_===void 0)return!1;if(typeof _=="function")Kf(_,this,r);else for(var v=_.length,C=sh(_,v),l=0;l<v;++l)Kf(C[l],this,r);return!0};function Xf(f,t,r,l){var u,s,n;if(Vo(r),s=f._events,s===void 0?(s=f._events=Object.create(null),f._eventsCount=0):(s.newListener!==void 0&&(f.emit("newListener",t,r.listener?r.listener:r),s=f._events),n=s[t]),n===void 0)n=s[t]=r,++f._eventsCount;else if(typeof n=="function"?n=s[t]=l?[r,n]:[n,r]:l?n.unshift(r):n.push(r),u=Qf(f),u>0&&n.length>u&&!n.warned){n.warned=!0;var g=new Error("Possible EventEmitter memory leak detected. "+n.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");g.name="MaxListenersExceededWarning",g.emitter=f,g.type=t,g.count=n.length,t0(g)}return f}Ft.prototype.addListener=function(t,r){return Xf(this,t,r,!1)},Ft.prototype.on=Ft.prototype.addListener,Ft.prototype.prependListener=function(t,r){return Xf(this,t,r,!0)};function s0(){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 Zf(f,t,r){var l={fired:!1,wrapFn:void 0,target:f,type:t,listener:r},u=s0.bind(l);return u.listener=r,l.wrapFn=u,u}Ft.prototype.once=function(t,r){return Vo(r),this.on(t,Zf(this,t,r)),this},Ft.prototype.prependOnceListener=function(t,r){return Vo(r),this.prependListener(t,Zf(this,t,r)),this},Ft.prototype.removeListener=function(t,r){var l,u,s,n,g;if(Vo(r),u=this._events,u===void 0)return this;if(l=u[t],l===void 0)return this;if(l===r||l.listener===r)--this._eventsCount===0?this._events=Object.create(null):(delete u[t],u.removeListener&&this.emit("removeListener",t,l.listener||r));else if(typeof l!="function"){for(s=-1,n=l.length-1;n>=0;n--)if(l[n]===r||l[n].listener===r){g=l[n].listener,s=n;break}if(s<0)return this;s===0?l.shift():r0(l,s),l.length===1&&(u[t]=l[0]),u.removeListener!==void 0&&this.emit("removeListener",t,g||r)}return this},Ft.prototype.off=Ft.prototype.removeListener,Ft.prototype.removeAllListeners=function(t){var r,l,u;if(l=this._events,l===void 0)return this;if(l.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):l[t]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete l[t]),this;if(arguments.length===0){var s=Object.keys(l),n;for(u=0;u<s.length;++u)n=s[u],n!=="removeListener"&&this.removeAllListeners(n);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(r=l[t],typeof r=="function")this.removeListener(t,r);else if(r!==void 0)for(u=r.length-1;u>=0;u--)this.removeListener(t,r[u]);return this};function eh(f,t,r){var l=f._events;if(l===void 0)return[];var u=l[t];return u===void 0?[]:typeof u=="function"?r?[u.listener||u]:[u]:r?n0(u):sh(u,u.length)}Ft.prototype.listeners=function(t){return eh(this,t,!0)},Ft.prototype.rawListeners=function(t){return eh(this,t,!1)},Ft.listenerCount=function(f,t){return typeof f.listenerCount=="function"?f.listenerCount(t):th.call(f,t)},Ft.prototype.listenerCount=th;function th(f){var t=this._events;if(t!==void 0){var r=t[f];if(typeof r=="function")return 1;if(r!==void 0)return r.length}return 0}Ft.prototype.eventNames=function(){return this._eventsCount>0?zo(this._events):[]};function sh(f,t){for(var r=new Array(t),l=0;l<t;++l)r[l]=f[l];return r}function r0(f,t){for(;t+1<f.length;t++)f[t]=f[t+1];f.pop()}function n0(f){for(var t=new Array(f.length),r=0;r<t.length;++r)t[r]=f[r].listener||f[r];return t}function i0(f,t){return new Promise(function(r,l){function u(n){f.removeListener(t,s),l(n)}function s(){typeof f.removeListener=="function"&&f.removeListener("error",u),r([].slice.call(arguments))}rh(f,t,s,{once:!0}),t!=="error"&&a0(f,u,{once:!0})})}function a0(f,t,r){typeof f.on=="function"&&rh(f,"error",t,r)}function rh(f,t,r,l){if(typeof f.on=="function")l.once?f.once(t,r):f.on(t,r);else if(typeof f.addEventListener=="function")f.addEventListener(t,function u(s){l.once&&f.removeEventListener(t,u),r(s)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof f)}var ys=dc.exports,fc={exports:{}},hc,nh;function l0(){if(nh)return hc;nh=1;var f=1e3,t=f*60,r=t*60,l=r*24,u=l*7,s=l*365.25;hc=function(C,R){R=R||{};var D=typeof C;if(D==="string"&&C.length>0)return n(C);if(D==="number"&&isFinite(C))return R.long?_(C):g(C);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(C))};function n(C){if(C=String(C),!(C.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(C);if(R){var D=parseFloat(R[1]),H=(R[2]||"ms").toLowerCase();switch(H){case"years":case"year":case"yrs":case"yr":case"y":return D*s;case"weeks":case"week":case"w":return D*u;case"days":case"day":case"d":return D*l;case"hours":case"hour":case"hrs":case"hr":case"h":return D*r;case"minutes":case"minute":case"mins":case"min":case"m":return D*t;case"seconds":case"second":case"secs":case"sec":case"s":return D*f;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return D;default:return}}}}function g(C){var R=Math.abs(C);return R>=l?Math.round(C/l)+"d":R>=r?Math.round(C/r)+"h":R>=t?Math.round(C/t)+"m":R>=f?Math.round(C/f)+"s":C+"ms"}function _(C){var R=Math.abs(C);return R>=l?v(C,R,l,"day"):R>=r?v(C,R,r,"hour"):R>=t?v(C,R,t,"minute"):R>=f?v(C,R,f,"second"):C+" ms"}function v(C,R,D,H){var F=R>=D*1.5;return Math.round(C/D)+" "+H+(F?"s":"")}return hc}function o0(f){r.debug=r,r.default=r,r.coerce=_,r.disable=s,r.enable=u,r.enabled=n,r.humanize=l0(),r.destroy=v,Object.keys(f).forEach(C=>{r[C]=f[C]}),r.names=[],r.skips=[],r.formatters={};function t(C){let R=0;for(let D=0;D<C.length;D++)R=(R<<5)-R+C.charCodeAt(D),R|=0;return r.colors[Math.abs(R)%r.colors.length]}r.selectColor=t;function r(C){let R,D=null,H,F;function q(...G){if(!q.enabled)return;const te=q,X=Number(new Date),we=X-(R||X);te.diff=we,te.prev=R,te.curr=X,R=X,G[0]=r.coerce(G[0]),typeof G[0]!="string"&&G.unshift("%O");let Q=0;G[0]=G[0].replace(/%([a-zA-Z%])/g,(ke,Ne)=>{if(ke==="%%")return"%";Q++;const Z=r.formatters[Ne];if(typeof Z=="function"){const se=G[Q];ke=Z.call(te,se),G.splice(Q,1),Q--}return ke}),r.formatArgs.call(te,G),(te.log||r.log).apply(te,G)}return q.namespace=C,q.useColors=r.useColors(),q.color=r.selectColor(C),q.extend=l,q.destroy=r.destroy,Object.defineProperty(q,"enabled",{enumerable:!0,configurable:!1,get:()=>D!==null?D:(H!==r.namespaces&&(H=r.namespaces,F=r.enabled(C)),F),set:G=>{D=G}}),typeof r.init=="function"&&r.init(q),q}function l(C,R){const D=r(this.namespace+(typeof R>"u"?":":R)+C);return D.log=this.log,D}function u(C){r.save(C),r.namespaces=C,r.names=[],r.skips=[];let R;const D=(typeof C=="string"?C:"").split(/[\s,]+/),H=D.length;for(R=0;R<H;R++)D[R]&&(C=D[R].replace(/\*/g,".*?"),C[0]==="-"?r.skips.push(new RegExp("^"+C.slice(1)+"$")):r.names.push(new RegExp("^"+C+"$")))}function s(){const C=[...r.names.map(g),...r.skips.map(g).map(R=>"-"+R)].join(",");return r.enable(""),C}function n(C){if(C[C.length-1]==="*")return!0;let R,D;for(R=0,D=r.skips.length;R<D;R++)if(r.skips[R].test(C))return!1;for(R=0,D=r.names.length;R<D;R++)if(r.names[R].test(C))return!0;return!1}function g(C){return C.toString().substring(2,C.toString().length-2).replace(/\.\*\?$/,"*")}function _(C){return C instanceof Error?C.stack||C.message:C}function v(){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 u0=o0;(function(f,t){t.formatArgs=l,t.save=u,t.load=s,t.useColors=r,t.storage=n(),t.destroy=(()=>{let _=!1;return()=>{_||(_=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),t.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function 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 l(_){if(_[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+_[0]+(this.useColors?"%c ":" ")+"+"+f.exports.humanize(this.diff),!this.useColors)return;const v="color: "+this.color;_.splice(1,0,v,"color: inherit");let C=0,R=0;_[0].replace(/%[a-zA-Z%]/g,D=>{D!=="%%"&&(C++,D==="%c"&&(R=C))}),_.splice(R,0,v)}t.log=console.debug||console.log||(()=>{});function u(_){try{_?t.storage.setItem("debug",_):t.storage.removeItem("debug")}catch{}}function s(){let _;try{_=t.storage.getItem("debug")}catch{}return!_&&typeof process<"u"&&"env"in process&&(_=process.env.DEBUG),_}function n(){try{return localStorage}catch{}}f.exports=u0(t);const{formatters:g}=f.exports;g.j=function(_){try{return JSON.stringify(_)}catch(v){return"[UnexpectedJSONParseError]: "+v.message}}})(fc,fc.exports);var al=fc.exports;function c0(f,t){if(!(f instanceof t))throw new TypeError("Cannot call a class as a function")}function ih(f,t){for(var r=0;r<t.length;r++){var l=t[r];l.enumerable=l.enumerable||!1,l.configurable=!0,"value"in l&&(l.writable=!0),Object.defineProperty(f,l.key,l)}}function d0(f,t,r){return t&&ih(f.prototype,t),r&&ih(f,r),f}var ll=al,ol="JsSIP",Ts=function(){function f(t){c0(this,f),t?(this._debug=ll.default("".concat(ol,":").concat(t)),this._warn=ll.default("".concat(ol,":WARN:").concat(t)),this._error=ll.default("".concat(ol,":ERROR:").concat(t))):(this._debug=ll.default(ol),this._warn=ll.default("".concat(ol,":WARN")),this._error=ll.default("".concat(ol,":ERROR"))),this._debug.log=console.info.bind(console),this._warn.log=console.warn.bind(console),this._error.log=console.error.bind(console)}return d0(f,[{key:"debug",get:function(){return this._debug}},{key:"warn",get:function(){return this._warn}},{key:"error",get:function(){return this._error}}]),f}(),sr={},ah={},lh={exports:{}},oh=lh.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(f){return f.encoding?"rtpmap:%d %s/%s/%s":f.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(f){return f.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(f){return f.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(f){return"extmap:%d"+(f.direction?"/%s":"%v")+(f["encrypt-uri"]?" %s":"%v")+" %s"+(f.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(f){return f.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(f){var t="candidate:%s %d %s %d %s %d typ %s";return t+=f.raddr!=null?" raddr %s rport %d":"%v%v",t+=f.tcptype!=null?" tcptype %s":"%v",f.generation!=null&&(t+=" generation %d"),t+=f["network-id"]!=null?" network-id %d":"%v",t+=f["network-cost"]!=null?" network-cost %d":"%v",t}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(f){var t="ssrc:%d";return f.attribute!=null&&(t+=" %s",f.value!=null&&(t+=":%s")),t}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(f){return f.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(f){return f.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(f){return"imageattr:%s %s %s"+(f.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(f){return"simulcast:%s %s"+(f.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(f){return"ts-refclk:%s"+(f.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(f){var t="mediaclk:";return t+=f.id!=null?"id=%s %s":"%v%s",t+=f.mediaClockValue!=null?"=%s":"",t+=f.rateNumerator!=null?" rate=%s":"",t+=f.rateDenominator!=null?"/%s":"",t}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};Object.keys(oh).forEach(function(f){var t=oh[f];t.forEach(function(r){r.reg||(r.reg=/(.*)/),r.format||(r.format="%s")})});var uh=lh.exports;(function(f){var t=function(g){return String(Number(g))===g?Number(g):g},r=function(g,_,v,C){if(C&&!v)_[C]=t(g[1]);else for(var R=0;R<v.length;R+=1)g[R+1]!=null&&(_[v[R]]=t(g[R+1]))},l=function(g,_,v){var C=g.name&&g.names;g.push&&!_[g.push]?_[g.push]=[]:C&&!_[g.name]&&(_[g.name]={});var R=g.push?{}:C?_[g.name]:_;r(v.match(g.reg),R,g.names,g.name),g.push&&_[g.push].push(R)},u=uh,s=RegExp.prototype.test.bind(/^([a-z])=(.*)/);f.parse=function(g){var _={},v=[],C=_;return g.split(/(\r\n|\r|\n)/).filter(s).forEach(function(R){var D=R[0],H=R.slice(2);D==="m"&&(v.push({rtp:[],fmtp:[]}),C=v[v.length-1]);for(var F=0;F<(u[D]||[]).length;F+=1){var q=u[D][F];if(q.reg.test(H))return l(q,C,H)}}),_.media=v,_};var n=function(g,_){var v=_.split(/=(.+)/,2);return v.length===2?g[v[0]]=t(v[1]):v.length===1&&_.length>1&&(g[v[0]]=void 0),g};f.parseParams=function(g){return g.split(/;\s?/).reduce(n,{})},f.parseFmtpConfig=f.parseParams,f.parsePayloads=function(g){return g.toString().split(" ").map(Number)},f.parseRemoteCandidates=function(g){for(var _=[],v=g.split(" ").map(t),C=0;C<v.length;C+=3)_.push({component:v[C],ip:v[C+1],port:v[C+2]});return _},f.parseImageAttributes=function(g){return g.split(" ").map(function(_){return _.substring(1,_.length-1).split(",").reduce(n,{})})},f.parseSimulcastStreamList=function(g){return g.split(";").map(function(_){return _.split(",").map(function(v){var C,R=!1;return v[0]!=="~"?C=t(v):(C=t(v.substring(1,v.length)),R=!0),{scid:C,paused:R}})})}})(ah);var _c=uh,f0=/%[sdv%]/g,h0=function(f){var t=1,r=arguments,l=r.length;return f.replace(f0,function(u){if(t>=l)return u;var s=r[t];switch(t+=1,u){case"%%":return"%";case"%s":return String(s);case"%d":return Number(s);case"%v":return""}})},Ml=function(f,t,r){var l=t.format instanceof Function?t.format(t.push?r:r[t.name]):t.format,u=[f+"="+l];if(t.names)for(var s=0;s<t.names.length;s+=1){var n=t.names[s];t.name?u.push(r[t.name][n]):u.push(r[t.names[s]])}else u.push(r[t.name]);return h0.apply(null,u)},_0=["v","o","s","i","u","e","p","c","b","t","r","z","a"],p0=["i","c","b","a"],m0=function(f,t){t=t||{},f.version==null&&(f.version=0),f.name==null&&(f.name=" "),f.media.forEach(function(s){s.payloads==null&&(s.payloads="")});var r=t.outerOrder||_0,l=t.innerOrder||p0,u=[];return r.forEach(function(s){_c[s].forEach(function(n){n.name in f&&f[n.name]!=null?u.push(Ml(s,n,f)):n.push in f&&f[n.push]!=null&&f[n.push].forEach(function(g){u.push(Ml(s,n,g))})})}),f.media.forEach(function(s){u.push(Ml("m",_c.m[0],s)),l.forEach(function(n){_c[n].forEach(function(g){g.name in s&&s[g.name]!=null?u.push(Ml(n,g,s)):g.push in s&&s[g.push]!=null&&s[g.push].forEach(function(_){u.push(Ml(n,g,_))})})})}),u.join(`\r
7
7
  `)+`\r
8
- `},va=lh,g0=m0;sr.write=g0,sr.parse=va.parse,sr.parseParams=va.parseParams,sr.parseFmtpConfig=va.parseFmtpConfig,sr.parsePayloads=va.parsePayloads,sr.parseRemoteCandidates=va.parseRemoteCandidates,sr.parseImageAttributes=va.parseImageAttributes,sr.parseSimulcastStreamList=va.parseSimulcastStreamList;function qo(f){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?qo=function(r){return typeof r}:qo=function(r){return r&&typeof Symbol=="function"&&r.constructor===Symbol&&r!==Symbol.prototype?"symbol":typeof r},qo(f)}function pc(f,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");f.prototype=Object.create(t&&t.prototype,{constructor:{value:f,writable:!0,configurable:!0}}),t&&mc(f,t)}function mc(f,t){return mc=Object.setPrototypeOf||function(l,u){return l.__proto__=u,l},mc(f,t)}function gc(f){var t=T0();return function(){var l=jo(f),u;if(t){var s=jo(this).constructor;u=Reflect.construct(l,arguments,s)}else u=l.apply(this,arguments);return v0(this,u)}}function v0(f,t){return t&&(qo(t)==="object"||typeof t=="function")?t:y0(f)}function y0(f){if(f===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return f}function T0(){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 jo(f){return jo=Object.setPrototypeOf?Object.getPrototypeOf:function(r){return r.__proto__||Object.getPrototypeOf(r)},jo(f)}function br(f,t){var r;if(typeof Symbol>"u"||f[Symbol.iterator]==null){if(Array.isArray(f)||(r=S0(f))||t&&f&&typeof f.length=="number"){r&&(f=r);var l=0,u=function(){};return{s:u,n:function(){return l>=f.length?{done:!0}:{done:!1,value:f[l++]}},e:function(v){throw v},f:u}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
9
- In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var s=!0,n=!1,g;return{s:function(){r=f[Symbol.iterator]()},n:function(){var v=r.next();return s=v.done,v},e:function(v){n=!0,g=v},f:function(){try{!s&&r.return!=null&&r.return()}finally{if(n)throw g}}}}function S0(f,t){if(f){if(typeof f=="string")return dh(f,t);var r=Object.prototype.toString.call(f).slice(8,-1);if(r==="Object"&&f.constructor&&(r=f.constructor.name),r==="Map"||r==="Set")return Array.from(f);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return dh(f,t)}}function dh(f,t){(t==null||t>f.length)&&(t=f.length);for(var r=0,l=new Array(t);r<t;r++)l[r]=f[r];return l}function Ul(f,t){if(!(f instanceof t))throw new TypeError("Cannot call a class as a function")}function fh(f,t){for(var r=0;r<t.length;r++){var l=t[r];l.enumerable=l.enumerable||!1,l.configurable=!0,"value"in l&&(l.writable=!0),Object.defineProperty(f,l.key,l)}}function Go(f,t,r){return t&&fh(f.prototype,t),r&&fh(f,r),f}var hh=sr,b0=Ts,Is=hs,_s=Bs(),_h=oc(),w0=on(),vc=new b0("SIPMessage"),ph=function(){function f(t,r,l,u,s,n){if(Ul(this,f),!t||!r||!l)return null;u=u||{},this.ua=l,this.headers={},this.method=t,this.ruri=r,this.body=n,this.extraHeaders=_s.cloneArray(s),this.ua.configuration.extra_headers&&(this.extraHeaders=this.extraHeaders.concat(this.ua.configuration.extra_headers)),u.route_set?this.setHeader("route",u.route_set):l.configuration.use_preloaded_route&&this.setHeader("route","<".concat(l.transport.sip_uri,";lr>")),this.setHeader("via",""),this.setHeader("max-forwards",Is.MAX_FORWARDS);var g=u.to_uri||r,_=u.to_tag?{tag:u.to_tag}:null,v=typeof u.to_display_name<"u"?u.to_display_name:null;this.to=new _h(g,v,_),this.setHeader("to",this.to.toString());var C=u.from_uri||l.configuration.uri,R={tag:u.from_tag||_s.newTag()},D;typeof u.from_display_name<"u"?D=u.from_display_name:l.configuration.display_name?D=l.configuration.display_name:D=null,this.from=new _h(C,D,R),this.setHeader("from",this.from.toString());var H=u.call_id||l.configuration.jssip_id+_s.createRandomToken(15);this.call_id=H,this.setHeader("call-id",H);var F=u.cseq||Math.floor(Math.random()*1e4);this.cseq=F,this.setHeader("cseq","".concat(F," ").concat(t))}return Go(f,[{key:"setHeader",value:function(r,l){for(var u=new RegExp("^\\s*".concat(r,"\\s*:"),"i"),s=0;s<this.extraHeaders.length;s++)u.test(this.extraHeaders[s])&&this.extraHeaders.splice(s,1);this.headers[_s.headerize(r)]=Array.isArray(l)?l:[l]}},{key:"getHeader",value:function(r){var l=this.headers[_s.headerize(r)];if(l){if(l[0])return l[0]}else{var u=new RegExp("^\\s*".concat(r,"\\s*:"),"i"),s=br(this.extraHeaders),n;try{for(s.s();!(n=s.n()).done;){var g=n.value;if(u.test(g))return g.substring(g.indexOf(":")+1).trim()}}catch(_){s.e(_)}finally{s.f()}}}},{key:"getHeaders",value:function(r){var l=this.headers[_s.headerize(r)],u=[];if(l){var s=br(l),n;try{for(s.s();!(n=s.n()).done;){var g=n.value;u.push(g)}}catch(D){s.e(D)}finally{s.f()}return u}else{var _=new RegExp("^\\s*".concat(r,"\\s*:"),"i"),v=br(this.extraHeaders),C;try{for(v.s();!(C=v.n()).done;){var R=C.value;_.test(R)&&u.push(R.substring(R.indexOf(":")+1).trim())}}catch(D){v.e(D)}finally{v.f()}return u}}},{key:"hasHeader",value:function(r){if(this.headers[_s.headerize(r)])return!0;var l=new RegExp("^\\s*".concat(r,"\\s*:"),"i"),u=br(this.extraHeaders),s;try{for(u.s();!(s=u.n()).done;){var n=s.value;if(l.test(n))return!0}}catch(g){u.e(g)}finally{u.f()}return!1}},{key:"parseSDP",value:function(r){return!r&&this.sdp?this.sdp:(this.sdp=hh.parse(this.body||""),this.sdp)}},{key:"toString",value:function(){var r="".concat(this.method," ").concat(this.ruri,` SIP/2.0\r
8
+ `},va=ah,g0=m0;sr.write=g0,sr.parse=va.parse,sr.parseParams=va.parseParams,sr.parseFmtpConfig=va.parseFmtpConfig,sr.parsePayloads=va.parsePayloads,sr.parseRemoteCandidates=va.parseRemoteCandidates,sr.parseImageAttributes=va.parseImageAttributes,sr.parseSimulcastStreamList=va.parseSimulcastStreamList;function qo(f){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?qo=function(r){return typeof r}:qo=function(r){return r&&typeof Symbol=="function"&&r.constructor===Symbol&&r!==Symbol.prototype?"symbol":typeof r},qo(f)}function pc(f,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");f.prototype=Object.create(t&&t.prototype,{constructor:{value:f,writable:!0,configurable:!0}}),t&&mc(f,t)}function mc(f,t){return mc=Object.setPrototypeOf||function(l,u){return l.__proto__=u,l},mc(f,t)}function gc(f){var t=T0();return function(){var l=jo(f),u;if(t){var s=jo(this).constructor;u=Reflect.construct(l,arguments,s)}else u=l.apply(this,arguments);return v0(this,u)}}function v0(f,t){return t&&(qo(t)==="object"||typeof t=="function")?t:y0(f)}function y0(f){if(f===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return f}function T0(){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 jo(f){return jo=Object.setPrototypeOf?Object.getPrototypeOf:function(r){return r.__proto__||Object.getPrototypeOf(r)},jo(f)}function br(f,t){var r;if(typeof Symbol>"u"||f[Symbol.iterator]==null){if(Array.isArray(f)||(r=S0(f))||t&&f&&typeof f.length=="number"){r&&(f=r);var l=0,u=function(){};return{s:u,n:function(){return l>=f.length?{done:!0}:{done:!1,value:f[l++]}},e:function(v){throw v},f:u}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
9
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var s=!0,n=!1,g;return{s:function(){r=f[Symbol.iterator]()},n:function(){var v=r.next();return s=v.done,v},e:function(v){n=!0,g=v},f:function(){try{!s&&r.return!=null&&r.return()}finally{if(n)throw g}}}}function S0(f,t){if(f){if(typeof f=="string")return ch(f,t);var r=Object.prototype.toString.call(f).slice(8,-1);if(r==="Object"&&f.constructor&&(r=f.constructor.name),r==="Map"||r==="Set")return Array.from(f);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return ch(f,t)}}function ch(f,t){(t==null||t>f.length)&&(t=f.length);for(var r=0,l=new Array(t);r<t;r++)l[r]=f[r];return l}function Ul(f,t){if(!(f instanceof t))throw new TypeError("Cannot call a class as a function")}function dh(f,t){for(var r=0;r<t.length;r++){var l=t[r];l.enumerable=l.enumerable||!1,l.configurable=!0,"value"in l&&(l.writable=!0),Object.defineProperty(f,l.key,l)}}function Go(f,t,r){return t&&dh(f.prototype,t),r&&dh(f,r),f}var fh=sr,b0=Ts,Is=hs,_s=Bs(),hh=oc(),w0=on(),vc=new b0("SIPMessage"),_h=function(){function f(t,r,l,u,s,n){if(Ul(this,f),!t||!r||!l)return null;u=u||{},this.ua=l,this.headers={},this.method=t,this.ruri=r,this.body=n,this.extraHeaders=_s.cloneArray(s),this.ua.configuration.extra_headers&&(this.extraHeaders=this.extraHeaders.concat(this.ua.configuration.extra_headers)),u.route_set?this.setHeader("route",u.route_set):l.configuration.use_preloaded_route&&this.setHeader("route","<".concat(l.transport.sip_uri,";lr>")),this.setHeader("via",""),this.setHeader("max-forwards",Is.MAX_FORWARDS);var g=u.to_uri||r,_=u.to_tag?{tag:u.to_tag}:null,v=typeof u.to_display_name<"u"?u.to_display_name:null;this.to=new hh(g,v,_),this.setHeader("to",this.to.toString());var C=u.from_uri||l.configuration.uri,R={tag:u.from_tag||_s.newTag()},D;typeof u.from_display_name<"u"?D=u.from_display_name:l.configuration.display_name?D=l.configuration.display_name:D=null,this.from=new hh(C,D,R),this.setHeader("from",this.from.toString());var H=u.call_id||l.configuration.jssip_id+_s.createRandomToken(15);this.call_id=H,this.setHeader("call-id",H);var F=u.cseq||Math.floor(Math.random()*1e4);this.cseq=F,this.setHeader("cseq","".concat(F," ").concat(t))}return Go(f,[{key:"setHeader",value:function(r,l){for(var u=new RegExp("^\\s*".concat(r,"\\s*:"),"i"),s=0;s<this.extraHeaders.length;s++)u.test(this.extraHeaders[s])&&this.extraHeaders.splice(s,1);this.headers[_s.headerize(r)]=Array.isArray(l)?l:[l]}},{key:"getHeader",value:function(r){var l=this.headers[_s.headerize(r)];if(l){if(l[0])return l[0]}else{var u=new RegExp("^\\s*".concat(r,"\\s*:"),"i"),s=br(this.extraHeaders),n;try{for(s.s();!(n=s.n()).done;){var g=n.value;if(u.test(g))return g.substring(g.indexOf(":")+1).trim()}}catch(_){s.e(_)}finally{s.f()}}}},{key:"getHeaders",value:function(r){var l=this.headers[_s.headerize(r)],u=[];if(l){var s=br(l),n;try{for(s.s();!(n=s.n()).done;){var g=n.value;u.push(g)}}catch(D){s.e(D)}finally{s.f()}return u}else{var _=new RegExp("^\\s*".concat(r,"\\s*:"),"i"),v=br(this.extraHeaders),C;try{for(v.s();!(C=v.n()).done;){var R=C.value;_.test(R)&&u.push(R.substring(R.indexOf(":")+1).trim())}}catch(D){v.e(D)}finally{v.f()}return u}}},{key:"hasHeader",value:function(r){if(this.headers[_s.headerize(r)])return!0;var l=new RegExp("^\\s*".concat(r,"\\s*:"),"i"),u=br(this.extraHeaders),s;try{for(u.s();!(s=u.n()).done;){var n=s.value;if(l.test(n))return!0}}catch(g){u.e(g)}finally{u.f()}return!1}},{key:"parseSDP",value:function(r){return!r&&this.sdp?this.sdp:(this.sdp=fh.parse(this.body||""),this.sdp)}},{key:"toString",value:function(){var r="".concat(this.method," ").concat(this.ruri,` SIP/2.0\r
10
10
  `);for(var l in this.headers)if(Object.prototype.hasOwnProperty.call(this.headers,l)){var u=br(this.headers[l]),s;try{for(u.s();!(s=u.n()).done;){var n=s.value;r+="".concat(l,": ").concat(n,`\r
11
11
  `)}}catch(H){u.e(H)}finally{u.f()}}var g=br(this.extraHeaders),_;try{for(g.s();!(_=g.n()).done;){var v=_.value;r+="".concat(v.trim(),`\r
12
12
  `)}}catch(H){g.e(H)}finally{g.f()}var C=[];switch(this.method){case Is.REGISTER:C.push("path","gruu");break;case Is.INVITE:this.ua.configuration.session_timers&&C.push("timer"),(this.ua.contact.pub_gruu||this.ua.contact.temp_gruu)&&C.push("gruu"),C.push("ice","replaces");break;case Is.UPDATE:this.ua.configuration.session_timers&&C.push("timer"),C.push("ice");break}C.push("outbound");var R=this.ua.configuration.user_agent||Is.USER_AGENT;if(r+="Allow: ".concat(Is.ALLOWED_METHODS,`\r
@@ -16,7 +16,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
16
16
  \r
17
17
  `),r+=this.body}else r+=`Content-Length: 0\r
18
18
  \r
19
- `;return r}},{key:"clone",value:function(){var r=new f(this.method,this.ruri,this.ua);return Object.keys(this.headers).forEach(function(l){r.headers[l]=this.headers[l].slice()},this),r.body=this.body,r.extraHeaders=_s.cloneArray(this.extraHeaders),r.to=this.to,r.from=this.from,r.call_id=this.call_id,r.cseq=this.cseq,r}}]),f}(),E0=function(f){pc(r,f);var t=gc(r);function r(l,u,s,n,g){var _;return Ul(this,r),_=t.call(this,Is.INVITE,l,u,s,n,g),_.transaction=null,_}return Go(r,[{key:"cancel",value:function(u){this.transaction.cancel(u)}},{key:"clone",value:function(){var u=new r(this.ruri,this.ua);return Object.keys(this.headers).forEach(function(s){u.headers[s]=this.headers[s].slice()},this),u.body=this.body,u.extraHeaders=_s.cloneArray(this.extraHeaders),u.to=this.to,u.from=this.from,u.call_id=this.call_id,u.cseq=this.cseq,u.transaction=this.transaction,u}}]),r}(ph),mh=function(){function f(){Ul(this,f),this.data=null,this.headers=null,this.method=null,this.via=null,this.via_branch=null,this.call_id=null,this.cseq=null,this.from=null,this.from_tag=null,this.to=null,this.to_tag=null,this.body=null,this.sdp=null}return Go(f,[{key:"addHeader",value:function(r,l){var u={raw:l};r=_s.headerize(r),this.headers[r]?this.headers[r].push(u):this.headers[r]=[u]}},{key:"getHeader",value:function(r){var l=this.headers[_s.headerize(r)];if(l){if(l[0])return l[0].raw}else return}},{key:"getHeaders",value:function(r){var l=this.headers[_s.headerize(r)],u=[];if(!l)return[];var s=br(l),n;try{for(s.s();!(n=s.n()).done;){var g=n.value;u.push(g.raw)}}catch(_){s.e(_)}finally{s.f()}return u}},{key:"hasHeader",value:function(r){return!!this.headers[_s.headerize(r)]}},{key:"parseHeader",value:function(r){var l=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0;if(r=_s.headerize(r),this.headers[r]){if(l>=this.headers[r].length){vc.debug('not so many "'.concat(r,'" headers present'));return}}else{vc.debug('header "'.concat(r,'" not present'));return}var u=this.headers[r][l],s=u.raw;if(u.parsed)return u.parsed;var n=w0.parse(s,r.replace(/-/g,"_"));if(n===-1){this.headers[r].splice(l,1),vc.debug('error parsing "'.concat(r,'" header field with value "').concat(s,'"'));return}else return u.parsed=n,n}},{key:"s",value:function(r,l){return this.parseHeader(r,l)}},{key:"setHeader",value:function(r,l){var u={raw:l};this.headers[_s.headerize(r)]=[u]}},{key:"parseSDP",value:function(r){return!r&&this.sdp?this.sdp:(this.sdp=hh.parse(this.body||""),this.sdp)}},{key:"toString",value:function(){return this.data}}]),f}(),C0=function(f){pc(r,f);var t=gc(r);function r(l){var u;return Ul(this,r),u=t.call(this),u.ua=l,u.headers={},u.ruri=null,u.transport=null,u.server_transaction=null,u}return Go(r,[{key:"reply",value:function(u,s,n,g,_,v){var C=[],R=this.getHeader("To");if(u=u||null,s=s||null,!u||u<100||u>699)throw new TypeError("Invalid status_code: ".concat(u));if(s&&typeof s!="string"&&!(s instanceof String))throw new TypeError("Invalid reason_phrase: ".concat(s));s=s||Is.REASON_PHRASE[u]||"",n=_s.cloneArray(n),this.ua.configuration.extra_headers&&(n=n.concat(this.ua.configuration.extra_headers));var D="SIP/2.0 ".concat(u," ").concat(s,`\r
19
+ `;return r}},{key:"clone",value:function(){var r=new f(this.method,this.ruri,this.ua);return Object.keys(this.headers).forEach(function(l){r.headers[l]=this.headers[l].slice()},this),r.body=this.body,r.extraHeaders=_s.cloneArray(this.extraHeaders),r.to=this.to,r.from=this.from,r.call_id=this.call_id,r.cseq=this.cseq,r}}]),f}(),E0=function(f){pc(r,f);var t=gc(r);function r(l,u,s,n,g){var _;return Ul(this,r),_=t.call(this,Is.INVITE,l,u,s,n,g),_.transaction=null,_}return Go(r,[{key:"cancel",value:function(u){this.transaction.cancel(u)}},{key:"clone",value:function(){var u=new r(this.ruri,this.ua);return Object.keys(this.headers).forEach(function(s){u.headers[s]=this.headers[s].slice()},this),u.body=this.body,u.extraHeaders=_s.cloneArray(this.extraHeaders),u.to=this.to,u.from=this.from,u.call_id=this.call_id,u.cseq=this.cseq,u.transaction=this.transaction,u}}]),r}(_h),ph=function(){function f(){Ul(this,f),this.data=null,this.headers=null,this.method=null,this.via=null,this.via_branch=null,this.call_id=null,this.cseq=null,this.from=null,this.from_tag=null,this.to=null,this.to_tag=null,this.body=null,this.sdp=null}return Go(f,[{key:"addHeader",value:function(r,l){var u={raw:l};r=_s.headerize(r),this.headers[r]?this.headers[r].push(u):this.headers[r]=[u]}},{key:"getHeader",value:function(r){var l=this.headers[_s.headerize(r)];if(l){if(l[0])return l[0].raw}else return}},{key:"getHeaders",value:function(r){var l=this.headers[_s.headerize(r)],u=[];if(!l)return[];var s=br(l),n;try{for(s.s();!(n=s.n()).done;){var g=n.value;u.push(g.raw)}}catch(_){s.e(_)}finally{s.f()}return u}},{key:"hasHeader",value:function(r){return!!this.headers[_s.headerize(r)]}},{key:"parseHeader",value:function(r){var l=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0;if(r=_s.headerize(r),this.headers[r]){if(l>=this.headers[r].length){vc.debug('not so many "'.concat(r,'" headers present'));return}}else{vc.debug('header "'.concat(r,'" not present'));return}var u=this.headers[r][l],s=u.raw;if(u.parsed)return u.parsed;var n=w0.parse(s,r.replace(/-/g,"_"));if(n===-1){this.headers[r].splice(l,1),vc.debug('error parsing "'.concat(r,'" header field with value "').concat(s,'"'));return}else return u.parsed=n,n}},{key:"s",value:function(r,l){return this.parseHeader(r,l)}},{key:"setHeader",value:function(r,l){var u={raw:l};this.headers[_s.headerize(r)]=[u]}},{key:"parseSDP",value:function(r){return!r&&this.sdp?this.sdp:(this.sdp=fh.parse(this.body||""),this.sdp)}},{key:"toString",value:function(){return this.data}}]),f}(),C0=function(f){pc(r,f);var t=gc(r);function r(l){var u;return Ul(this,r),u=t.call(this),u.ua=l,u.headers={},u.ruri=null,u.transport=null,u.server_transaction=null,u}return Go(r,[{key:"reply",value:function(u,s,n,g,_,v){var C=[],R=this.getHeader("To");if(u=u||null,s=s||null,!u||u<100||u>699)throw new TypeError("Invalid status_code: ".concat(u));if(s&&typeof s!="string"&&!(s instanceof String))throw new TypeError("Invalid reason_phrase: ".concat(s));s=s||Is.REASON_PHRASE[u]||"",n=_s.cloneArray(n),this.ua.configuration.extra_headers&&(n=n.concat(this.ua.configuration.extra_headers));var D="SIP/2.0 ".concat(u," ").concat(s,`\r
20
20
  `);if(this.method===Is.INVITE&&u>100&&u<=200){var H=this.getHeaders("record-route"),F=br(H),q;try{for(F.s();!(q=F.n()).done;){var G=q.value;D+="Record-Route: ".concat(G,`\r
21
21
  `)}}catch(se){F.e(se)}finally{F.f()}}var te=this.getHeaders("via"),X=br(te),we;try{for(X.s();!(we=X.n()).done;){var Q=we.value;D+="Via: ".concat(Q,`\r
22
22
  `)}}catch(se){X.e(se)}finally{X.f()}!this.to_tag&&u>100?R+=";tag=".concat(_s.newTag()):this.to_tag&&!this.s("to").hasParam("tag")&&(R+=";tag=".concat(this.to_tag)),D+="To: ".concat(R,`\r
@@ -43,11 +43,11 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
43
43
  `),this.ua.configuration.extra_headers){var D=br(this.ua.configuration.extra_headers),H;try{for(D.s();!(H=D.n()).done;){var F=H.value;g+="".concat(F.trim(),`\r
44
44
  `)}}catch(q){D.e(q)}finally{D.f()}}g+="Content-Length: ".concat(0,`\r
45
45
  \r
46
- `),this.transport.send(g)}}]),r}(mh),A0=function(f){pc(r,f);var t=gc(r);function r(){var l;return Ul(this,r),l=t.call(this),l.headers={},l.status_code=null,l.reason_phrase=null,l}return r}(mh),xn={OutgoingRequest:ph,InitialOutgoingInviteRequest:E0,IncomingRequest:C0,IncomingResponse:A0};function I0(f,t){if(!(f instanceof t))throw new TypeError("Cannot call a class as a function")}function gh(f,t){for(var r=0;r<t.length;r++){var l=t[r];l.enumerable=l.enumerable||!1,l.configurable=!0,"value"in l&&(l.writable=!0),Object.defineProperty(f,l.key,l)}}function R0(f,t,r){return t&&gh(f.prototype,t),r&&gh(f,r),f}var $0=Ts,On=Bs(),Or=new $0("DigestAuthentication"),x0=function(){function f(t){I0(this,f),this._credentials=t,this._cnonce=null,this._nc=0,this._ncHex="00000000",this._algorithm=null,this._realm=null,this._nonce=null,this._opaque=null,this._stale=null,this._qop=null,this._method=null,this._uri=null,this._ha1=null,this._response=null}return R0(f,[{key:"get",value:function(r){switch(r){case"realm":return this._realm;case"ha1":return this._ha1;default:Or.warn('get() | cannot get "%s" parameter',r);return}}},{key:"authenticate",value:function(r,l){var u=r.method,s=r.ruri,n=r.body,g=arguments.length>2&&arguments[2]!==void 0?arguments[2]:null;if(this._algorithm=l.algorithm,this._realm=l.realm,this._nonce=l.nonce,this._opaque=l.opaque,this._stale=l.stale,this._algorithm){if(this._algorithm!=="MD5")return Or.warn('authenticate() | challenge with Digest algorithm different than "MD5", authentication aborted'),!1}else this._algorithm="MD5";if(!this._nonce)return Or.warn("authenticate() | challenge without Digest nonce, authentication aborted"),!1;if(!this._realm)return Or.warn("authenticate() | challenge without Digest realm, authentication aborted"),!1;if(!this._credentials.password){if(!this._credentials.ha1)return Or.warn("authenticate() | no plain SIP password nor ha1 provided, authentication aborted"),!1;if(this._credentials.realm!==this._realm)return Or.warn('authenticate() | no plain SIP password, and stored `realm` does not match the given `realm`, cannot authenticate [stored:"%s", given:"%s"]',this._credentials.realm,this._realm),!1}if(l.qop)if(l.qop.indexOf("auth-int")>-1)this._qop="auth-int";else if(l.qop.indexOf("auth")>-1)this._qop="auth";else return Or.warn('authenticate() | challenge without Digest qop different than "auth" or "auth-int", authentication aborted'),!1;else this._qop=null;this._method=u,this._uri=s,this._cnonce=g||On.createRandomToken(12),this._nc+=1;var _=Number(this._nc).toString(16);this._ncHex="00000000".substr(0,8-_.length)+_,this._nc===4294967296&&(this._nc=1,this._ncHex="00000001"),this._credentials.password?this._ha1=On.calculateMD5("".concat(this._credentials.username,":").concat(this._realm,":").concat(this._credentials.password)):this._ha1=this._credentials.ha1;var v,C;return this._qop==="auth"?(v="".concat(this._method,":").concat(this._uri),C=On.calculateMD5(v),Or.debug('authenticate() | using qop=auth [a2:"%s"]',v),this._response=On.calculateMD5("".concat(this._ha1,":").concat(this._nonce,":").concat(this._ncHex,":").concat(this._cnonce,":auth:").concat(C))):this._qop==="auth-int"?(v="".concat(this._method,":").concat(this._uri,":").concat(On.calculateMD5(n||"")),C=On.calculateMD5(v),Or.debug('authenticate() | using qop=auth-int [a2:"%s"]',v),this._response=On.calculateMD5("".concat(this._ha1,":").concat(this._nonce,":").concat(this._ncHex,":").concat(this._cnonce,":auth-int:").concat(C))):this._qop===null&&(v="".concat(this._method,":").concat(this._uri),C=On.calculateMD5(v),Or.debug('authenticate() | using qop=null [a2:"%s"]',v),this._response=On.calculateMD5("".concat(this._ha1,":").concat(this._nonce,":").concat(C))),Or.debug("authenticate() | response generated"),!0}},{key:"toString",value:function(){var r=[];if(!this._response)throw new Error("response field does not exist, cannot generate Authorization header");return r.push("algorithm=".concat(this._algorithm)),r.push('username="'.concat(this._credentials.username,'"')),r.push('realm="'.concat(this._realm,'"')),r.push('nonce="'.concat(this._nonce,'"')),r.push('uri="'.concat(this._uri,'"')),r.push('response="'.concat(this._response,'"')),this._opaque&&r.push('opaque="'.concat(this._opaque,'"')),this._qop&&(r.push("qop=".concat(this._qop)),r.push('cnonce="'.concat(this._cnonce,'"')),r.push("nc=".concat(this._ncHex))),"Digest ".concat(r.join(", "))}}]),f}(),Dn=500,O0=4e3,vh=5e3,yh={T1:Dn,T2:O0,T4:vh,TIMER_B:64*Dn,TIMER_D:0*Dn,TIMER_F:64*Dn,TIMER_H:64*Dn,TIMER_I:0*Dn,TIMER_J:0*Dn,TIMER_K:0*vh,TIMER_L:64*Dn,TIMER_M:64*Dn,PROVISIONAL_RESPONSE_INTERVAL:6e4};function Wo(f){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?Wo=function(r){return typeof r}:Wo=function(r){return r&&typeof Symbol=="function"&&r.constructor===Symbol&&r!==Symbol.prototype?"symbol":typeof r},Wo(f)}function Pl(f,t){if(!(f instanceof t))throw new TypeError("Cannot call a class as a function")}function Th(f,t){for(var r=0;r<t.length;r++){var l=t[r];l.enumerable=l.enumerable||!1,l.configurable=!0,"value"in l&&(l.writable=!0),Object.defineProperty(f,l.key,l)}}function Ll(f,t,r){return t&&Th(f.prototype,t),r&&Th(f,r),f}function Hl(f,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");f.prototype=Object.create(t&&t.prototype,{constructor:{value:f,writable:!0,configurable:!0}}),t&&yc(f,t)}function yc(f,t){return yc=Object.setPrototypeOf||function(l,u){return l.__proto__=u,l},yc(f,t)}function Fl(f){var t=k0();return function(){var l=Ko(f),u;if(t){var s=Ko(this).constructor;u=Reflect.construct(l,arguments,s)}else u=l.apply(this,arguments);return D0(this,u)}}function D0(f,t){return t&&(Wo(t)==="object"||typeof t=="function")?t:Si(f)}function Si(f){if(f===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return f}function k0(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],function(){})),!0}catch{return!1}}function Ko(f){return Ko=Object.setPrototypeOf?Object.getPrototypeOf:function(r){return r.__proto__||Object.getPrototypeOf(r)},Ko(f)}var Bl=ys.EventEmitter,zl=Ts,Vl=hs,Sh=xn,un=yh,bh=new zl("NonInviteClientTransaction"),Yo=new zl("InviteClientTransaction"),N0=new zl("AckClientTransaction"),wh=new zl("NonInviteServerTransaction"),Jo=new zl("InviteServerTransaction"),je={STATUS_TRYING:1,STATUS_PROCEEDING:2,STATUS_CALLING:3,STATUS_ACCEPTED:4,STATUS_COMPLETED:5,STATUS_TERMINATED:6,STATUS_CONFIRMED:7,NON_INVITE_CLIENT:"nict",NON_INVITE_SERVER:"nist",INVITE_CLIENT:"ict",INVITE_SERVER:"ist"},M0=function(f){Hl(r,f);var t=Fl(r);function r(l,u,s,n){var g;Pl(this,r),g=t.call(this),g.type=je.NON_INVITE_CLIENT,g.id="z9hG4bK".concat(Math.floor(Math.random()*1e7)),g.ua=l,g.transport=u,g.request=s,g.eventHandlers=n;var _="SIP/2.0/".concat(u.via_transport);return _+=" ".concat(l.configuration.via_host,";branch=").concat(g.id),g.request.setHeader("via",_),g.ua.newTransaction(Si(g)),g}return Ll(r,[{key:"stateChanged",value:function(u){this.state=u,this.emit("stateChanged")}},{key:"send",value:function(){var u=this;this.stateChanged(je.STATUS_TRYING),this.F=setTimeout(function(){u.timer_F()},un.TIMER_F),this.transport.send(this.request)||this.onTransportError()}},{key:"onTransportError",value:function(){bh.debug("transport error occurred, deleting transaction ".concat(this.id)),clearTimeout(this.F),clearTimeout(this.K),this.stateChanged(je.STATUS_TERMINATED),this.ua.destroyTransaction(this),this.eventHandlers.onTransportError()}},{key:"timer_F",value:function(){bh.debug("Timer F expired for transaction ".concat(this.id)),this.stateChanged(je.STATUS_TERMINATED),this.ua.destroyTransaction(this),this.eventHandlers.onRequestTimeout()}},{key:"timer_K",value:function(){this.stateChanged(je.STATUS_TERMINATED),this.ua.destroyTransaction(this)}},{key:"receiveResponse",value:function(u){var s=this,n=u.status_code;if(n<200)switch(this.state){case je.STATUS_TRYING:case je.STATUS_PROCEEDING:this.stateChanged(je.STATUS_PROCEEDING),this.eventHandlers.onReceiveResponse(u);break}else switch(this.state){case je.STATUS_TRYING:case je.STATUS_PROCEEDING:this.stateChanged(je.STATUS_COMPLETED),clearTimeout(this.F),n===408?this.eventHandlers.onRequestTimeout():this.eventHandlers.onReceiveResponse(u),this.K=setTimeout(function(){s.timer_K()},un.TIMER_K);break;case je.STATUS_COMPLETED:break}}},{key:"C",get:function(){return je}}]),r}(Bl),U0=function(f){Hl(r,f);var t=Fl(r);function r(l,u,s,n){var g;Pl(this,r),g=t.call(this),g.type=je.INVITE_CLIENT,g.id="z9hG4bK".concat(Math.floor(Math.random()*1e7)),g.ua=l,g.transport=u,g.request=s,g.eventHandlers=n,s.transaction=Si(g);var _="SIP/2.0/".concat(u.via_transport);return _+=" ".concat(l.configuration.via_host,";branch=").concat(g.id),g.request.setHeader("via",_),g.ua.newTransaction(Si(g)),g}return Ll(r,[{key:"stateChanged",value:function(u){this.state=u,this.emit("stateChanged")}},{key:"send",value:function(){var u=this;this.stateChanged(je.STATUS_CALLING),this.B=setTimeout(function(){u.timer_B()},un.TIMER_B),this.transport.send(this.request)||this.onTransportError()}},{key:"onTransportError",value:function(){clearTimeout(this.B),clearTimeout(this.D),clearTimeout(this.M),this.state!==je.STATUS_ACCEPTED&&(Yo.debug("transport error occurred, deleting transaction ".concat(this.id)),this.eventHandlers.onTransportError()),this.stateChanged(je.STATUS_TERMINATED),this.ua.destroyTransaction(this)}},{key:"timer_M",value:function(){Yo.debug("Timer M expired for transaction ".concat(this.id)),this.state===je.STATUS_ACCEPTED&&(clearTimeout(this.B),this.stateChanged(je.STATUS_TERMINATED),this.ua.destroyTransaction(this))}},{key:"timer_B",value:function(){Yo.debug("Timer B expired for transaction ".concat(this.id)),this.state===je.STATUS_CALLING&&(this.stateChanged(je.STATUS_TERMINATED),this.ua.destroyTransaction(this),this.eventHandlers.onRequestTimeout())}},{key:"timer_D",value:function(){Yo.debug("Timer D expired for transaction ".concat(this.id)),clearTimeout(this.B),this.stateChanged(je.STATUS_TERMINATED),this.ua.destroyTransaction(this)}},{key:"sendACK",value:function(u){var s=this,n=new Sh.OutgoingRequest(Vl.ACK,this.request.ruri,this.ua,{route_set:this.request.getHeaders("route"),call_id:this.request.getHeader("call-id"),cseq:this.request.cseq});n.setHeader("from",this.request.getHeader("from")),n.setHeader("via",this.request.getHeader("via")),n.setHeader("to",u.getHeader("to")),this.D=setTimeout(function(){s.timer_D()},un.TIMER_D),this.transport.send(n)}},{key:"cancel",value:function(u){if(this.state===je.STATUS_PROCEEDING){var s=new Sh.OutgoingRequest(Vl.CANCEL,this.request.ruri,this.ua,{route_set:this.request.getHeaders("route"),call_id:this.request.getHeader("call-id"),cseq:this.request.cseq});s.setHeader("from",this.request.getHeader("from")),s.setHeader("via",this.request.getHeader("via")),s.setHeader("to",this.request.getHeader("to")),u&&s.setHeader("reason",u),this.transport.send(s)}}},{key:"receiveResponse",value:function(u){var s=this,n=u.status_code;if(n>=100&&n<=199)switch(this.state){case je.STATUS_CALLING:this.stateChanged(je.STATUS_PROCEEDING),this.eventHandlers.onReceiveResponse(u);break;case je.STATUS_PROCEEDING:this.eventHandlers.onReceiveResponse(u);break}else if(n>=200&&n<=299)switch(this.state){case je.STATUS_CALLING:case je.STATUS_PROCEEDING:this.stateChanged(je.STATUS_ACCEPTED),this.M=setTimeout(function(){s.timer_M()},un.TIMER_M),this.eventHandlers.onReceiveResponse(u);break;case je.STATUS_ACCEPTED:this.eventHandlers.onReceiveResponse(u);break}else if(n>=300&&n<=699)switch(this.state){case je.STATUS_CALLING:case je.STATUS_PROCEEDING:this.stateChanged(je.STATUS_COMPLETED),this.sendACK(u),this.eventHandlers.onReceiveResponse(u);break;case je.STATUS_COMPLETED:this.sendACK(u);break}}},{key:"C",get:function(){return je}}]),r}(Bl),P0=function(f){Hl(r,f);var t=Fl(r);function r(l,u,s,n){var g;Pl(this,r),g=t.call(this),g.id="z9hG4bK".concat(Math.floor(Math.random()*1e7)),g.transport=u,g.request=s,g.eventHandlers=n;var _="SIP/2.0/".concat(u.via_transport);return _+=" ".concat(l.configuration.via_host,";branch=").concat(g.id),g.request.setHeader("via",_),g}return Ll(r,[{key:"send",value:function(){this.transport.send(this.request)||this.onTransportError()}},{key:"onTransportError",value:function(){N0.debug("transport error occurred for transaction ".concat(this.id)),this.eventHandlers.onTransportError()}},{key:"C",get:function(){return je}}]),r}(Bl),L0=function(f){Hl(r,f);var t=Fl(r);function r(l,u,s){var n;return Pl(this,r),n=t.call(this),n.type=je.NON_INVITE_SERVER,n.id=s.via_branch,n.ua=l,n.transport=u,n.request=s,n.last_response="",s.server_transaction=Si(n),n.state=je.STATUS_TRYING,l.newTransaction(Si(n)),n}return Ll(r,[{key:"stateChanged",value:function(u){this.state=u,this.emit("stateChanged")}},{key:"timer_J",value:function(){wh.debug("Timer J expired for transaction ".concat(this.id)),this.stateChanged(je.STATUS_TERMINATED),this.ua.destroyTransaction(this)}},{key:"onTransportError",value:function(){this.transportError||(this.transportError=!0,wh.debug("transport error occurred, deleting transaction ".concat(this.id)),clearTimeout(this.J),this.stateChanged(je.STATUS_TERMINATED),this.ua.destroyTransaction(this))}},{key:"receiveResponse",value:function(u,s,n,g){var _=this;if(u===100)switch(this.state){case je.STATUS_TRYING:this.stateChanged(je.STATUS_PROCEEDING),this.transport.send(s)||this.onTransportError();break;case je.STATUS_PROCEEDING:this.last_response=s,this.transport.send(s)?n&&n():(this.onTransportError(),g&&g());break}else if(u>=200&&u<=699)switch(this.state){case je.STATUS_TRYING:case je.STATUS_PROCEEDING:this.stateChanged(je.STATUS_COMPLETED),this.last_response=s,this.J=setTimeout(function(){_.timer_J()},un.TIMER_J),this.transport.send(s)?n&&n():(this.onTransportError(),g&&g());break;case je.STATUS_COMPLETED:break}}},{key:"C",get:function(){return je}}]),r}(Bl),H0=function(f){Hl(r,f);var t=Fl(r);function r(l,u,s){var n;return Pl(this,r),n=t.call(this),n.type=je.INVITE_SERVER,n.id=s.via_branch,n.ua=l,n.transport=u,n.request=s,n.last_response="",s.server_transaction=Si(n),n.state=je.STATUS_PROCEEDING,l.newTransaction(Si(n)),n.resendProvisionalTimer=null,s.reply(100),n}return Ll(r,[{key:"stateChanged",value:function(u){this.state=u,this.emit("stateChanged")}},{key:"timer_H",value:function(){Jo.debug("Timer H expired for transaction ".concat(this.id)),this.state===je.STATUS_COMPLETED&&Jo.debug("ACK not received, dialog will be terminated"),this.stateChanged(je.STATUS_TERMINATED),this.ua.destroyTransaction(this)}},{key:"timer_I",value:function(){this.stateChanged(je.STATUS_TERMINATED),this.ua.destroyTransaction(this)}},{key:"timer_L",value:function(){Jo.debug("Timer L expired for transaction ".concat(this.id)),this.state===je.STATUS_ACCEPTED&&(this.stateChanged(je.STATUS_TERMINATED),this.ua.destroyTransaction(this))}},{key:"onTransportError",value:function(){this.transportError||(this.transportError=!0,Jo.debug("transport error occurred, deleting transaction ".concat(this.id)),this.resendProvisionalTimer!==null&&(clearInterval(this.resendProvisionalTimer),this.resendProvisionalTimer=null),clearTimeout(this.L),clearTimeout(this.H),clearTimeout(this.I),this.stateChanged(je.STATUS_TERMINATED),this.ua.destroyTransaction(this))}},{key:"resend_provisional",value:function(){this.transport.send(this.last_response)||this.onTransportError()}},{key:"receiveResponse",value:function(u,s,n,g){var _=this;if(u>=100&&u<=199)switch(this.state){case je.STATUS_PROCEEDING:this.transport.send(s)||this.onTransportError(),this.last_response=s;break}if(u>100&&u<=199&&this.state===je.STATUS_PROCEEDING)this.resendProvisionalTimer===null&&(this.resendProvisionalTimer=setInterval(function(){_.resend_provisional()},un.PROVISIONAL_RESPONSE_INTERVAL));else if(u>=200&&u<=299)switch(this.state){case je.STATUS_PROCEEDING:this.stateChanged(je.STATUS_ACCEPTED),this.last_response=s,this.L=setTimeout(function(){_.timer_L()},un.TIMER_L),this.resendProvisionalTimer!==null&&(clearInterval(this.resendProvisionalTimer),this.resendProvisionalTimer=null);case je.STATUS_ACCEPTED:this.transport.send(s)?n&&n():(this.onTransportError(),g&&g());break}else if(u>=300&&u<=699)switch(this.state){case je.STATUS_PROCEEDING:this.resendProvisionalTimer!==null&&(clearInterval(this.resendProvisionalTimer),this.resendProvisionalTimer=null),this.transport.send(s)?(this.stateChanged(je.STATUS_COMPLETED),this.H=setTimeout(function(){_.timer_H()},un.TIMER_H),n&&n()):(this.onTransportError(),g&&g());break}}},{key:"C",get:function(){return je}}]),r}(Bl);function F0(f,t){var r=f._transactions,l;switch(t.method){case Vl.INVITE:if(l=r.ist[t.via_branch],l){switch(l.state){case je.STATUS_PROCEEDING:l.transport.send(l.last_response);break;case je.STATUS_ACCEPTED:break}return!0}break;case Vl.ACK:if(l=r.ist[t.via_branch],l){if(l.state===je.STATUS_ACCEPTED)return!1;if(l.state===je.STATUS_COMPLETED)return l.state=je.STATUS_CONFIRMED,l.I=setTimeout(function(){l.timer_I()},un.TIMER_I),!0}else return!1;break;case Vl.CANCEL:return l=r.ist[t.via_branch],l?(t.reply_sl(200),l.state!==je.STATUS_PROCEEDING):(t.reply_sl(481),!0);default:if(l=r.nist[t.via_branch],l){switch(l.state){case je.STATUS_TRYING:break;case je.STATUS_PROCEEDING:case je.STATUS_COMPLETED:l.transport.send(l.last_response);break}return!0}break}}var ql={C:je,NonInviteClientTransaction:M0,InviteClientTransaction:U0,AckClientTransaction:P0,NonInviteServerTransaction:L0,InviteServerTransaction:H0,checkTransaction:F0};function B0(f,t){if(!(f instanceof t))throw new TypeError("Cannot call a class as a function")}function Eh(f,t){for(var r=0;r<t.length;r++){var l=t[r];l.enumerable=l.enumerable||!1,l.configurable=!0,"value"in l&&(l.writable=!0),Object.defineProperty(f,l.key,l)}}function z0(f,t,r){return t&&Eh(f.prototype,t),r&&Eh(f,r),f}var V0=Ts,Ch=hs,q0=x0,Tc=ql,j0=new V0("RequestSender"),Sc={onRequestTimeout:function(){},onTransportError:function(){},onReceiveResponse:function(){},onAuthenticated:function(){}},jl=function(){function f(t,r,l){B0(this,f),this._ua=t,this._eventHandlers=l,this._method=r.method,this._request=r,this._auth=null,this._challenged=!1,this._staled=!1;for(var u in Sc)Object.prototype.hasOwnProperty.call(Sc,u)&&(this._eventHandlers[u]||(this._eventHandlers[u]=Sc[u]));t.status===t.C.STATUS_USER_CLOSED&&(this._method!==Ch.BYE||this._method!==Ch.ACK)&&this._eventHandlers.onTransportError()}return z0(f,[{key:"send",value:function(){var r=this,l={onRequestTimeout:function(){r._eventHandlers.onRequestTimeout()},onTransportError:function(){r._eventHandlers.onTransportError()},onReceiveResponse:function(s){r._receiveResponse(s)}};switch(this._method){case"INVITE":this.clientTransaction=new Tc.InviteClientTransaction(this._ua,this._ua.transport,this._request,l);break;case"ACK":this.clientTransaction=new Tc.AckClientTransaction(this._ua,this._ua.transport,this._request,l);break;default:this.clientTransaction=new Tc.NonInviteClientTransaction(this._ua,this._ua.transport,this._request,l)}this._ua._configuration.authorization_jwt&&this._request.setHeader("Authorization",this._ua._configuration.authorization_jwt),this.clientTransaction.send()}},{key:"_receiveResponse",value:function(r){var l,u,s=r.status_code;if((s===401||s===407)&&(this._ua.configuration.password!==null||this._ua.configuration.ha1!==null)){if(r.status_code===401?(l=r.parseHeader("www-authenticate"),u="authorization"):(l=r.parseHeader("proxy-authenticate"),u="proxy-authorization"),!l){j0.debug("".concat(r.status_code," with wrong or missing challenge, cannot authenticate")),this._eventHandlers.onReceiveResponse(r);return}if(!this._challenged||!this._staled&&l.stale===!0){if(this._auth||(this._auth=new q0({username:this._ua.configuration.authorization_user,password:this._ua.configuration.password,realm:this._ua.configuration.realm,ha1:this._ua.configuration.ha1})),!this._auth.authenticate(this._request,l)){this._eventHandlers.onReceiveResponse(r);return}this._challenged=!0,this._ua.set("realm",this._auth.get("realm")),this._ua.set("ha1",this._auth.get("ha1")),l.stale&&(this._staled=!0),this._request=this._request.clone(),this._request.cseq+=1,this._request.setHeader("cseq","".concat(this._request.cseq," ").concat(this._method)),this._request.setHeader(u,this._auth.toString()),this._eventHandlers.onAuthenticated(this._request),this.send()}else this._eventHandlers.onReceiveResponse(r)}else this._eventHandlers.onReceiveResponse(r)}}]),f}();function G0(f,t){if(!(f instanceof t))throw new TypeError("Cannot call a class as a function")}function Ah(f,t){for(var r=0;r<t.length;r++){var l=t[r];l.enumerable=l.enumerable||!1,l.configurable=!0,"value"in l&&(l.writable=!0),Object.defineProperty(f,l.key,l)}}function W0(f,t,r){return t&&Ah(f.prototype,t),r&&Ah(f,r),f}var K0=Ts,bc=Bs(),ya=hs,Ih=xn,Rh=jl,Gl=new K0("Registrator"),Qo=10,Y0=function(){function f(t,r){G0(this,f),this._reg_id=1,this._ua=t,this._transport=r,this._registrar=t.configuration.registrar_server,this._expires=t.configuration.register_expires,this._call_id=bc.createRandomToken(22),this._cseq=0,this._to_uri=t.configuration.uri,this._registrationTimer=null,this._registering=!1,this._registered=!1,this._contact=this._ua.contact.toString(),this._contact+=";+sip.ice",this._extraHeaders=[],this._extraContactParams="",this._sipInstance='"<urn:uuid:'.concat(this._ua.configuration.instance_id,'>"'),this._contact+=";reg-id=".concat(this._reg_id),this._contact+=";+sip.instance=".concat(this._sipInstance)}return W0(f,[{key:"setExtraHeaders",value:function(r){Array.isArray(r)||(r=[]),this._extraHeaders=r.slice()}},{key:"setExtraContactParams",value:function(r){r instanceof Object||(r={}),this._extraContactParams="";for(var l in r)if(Object.prototype.hasOwnProperty.call(r,l)){var u=r[l];this._extraContactParams+=";".concat(l),u&&(this._extraContactParams+="=".concat(u))}}},{key:"register",value:function(){var r=this;if(this._registering){Gl.debug("Register request in progress...");return}var l=this._extraHeaders.slice();l.push("Contact: ".concat(this._contact,";expires=").concat(this._expires).concat(this._extraContactParams)),l.push("Expires: ".concat(this._expires));var u=new Ih.OutgoingRequest(ya.REGISTER,this._registrar,this._ua,{to_uri:this._to_uri,call_id:this._call_id,cseq:this._cseq+=1},l),s=new Rh(this._ua,u,{onRequestTimeout:function(){r._registrationFailure(null,ya.causes.REQUEST_TIMEOUT)},onTransportError:function(){r._registrationFailure(null,ya.causes.CONNECTION_ERROR)},onAuthenticated:function(){r._cseq+=1},onReceiveResponse:function(g){if(g.cseq===r._cseq)switch(r._registrationTimer!==null&&(clearTimeout(r._registrationTimer),r._registrationTimer=null),!0){case/^1[0-9]{2}$/.test(g.status_code):break;case/^2[0-9]{2}$/.test(g.status_code):{if(r._registering=!1,!g.hasHeader("Contact")){Gl.debug("no Contact header in response to REGISTER, response ignored");break}var _=g.headers.Contact.reduce(function(H,F){return H.concat(F.parsed)},[]),v=_.find(function(H){return r._sipInstance===H.getParam("+sip.instance")&&r._reg_id===parseInt(H.getParam("reg-id"))});if(v||(v=_.find(function(H){return H.uri.user===r._ua.contact.uri.user})),!v){Gl.debug("no Contact header pointing to us, response ignored");break}var C=v.getParam("expires");!C&&g.hasHeader("expires")&&(C=g.getHeader("expires")),C||(C=r._expires),C=Number(C),C<Qo&&(C=Qo);var R=C>64?C*1e3/2+Math.floor((C/2-32)*1e3*Math.random()):C*1e3-5e3;r._registrationTimer=setTimeout(function(){r._registrationTimer=null,r._ua.listeners("registrationExpiring").length===0?r.register():r._ua.emit("registrationExpiring")},R),v.hasParam("temp-gruu")&&(r._ua.contact.temp_gruu=v.getParam("temp-gruu").replace(/"/g,"")),v.hasParam("pub-gruu")&&(r._ua.contact.pub_gruu=v.getParam("pub-gruu").replace(/"/g,"")),r._registered||(r._registered=!0,r._ua.registered({response:g}));break}case/^423$/.test(g.status_code):{g.hasHeader("min-expires")?(r._expires=Number(g.getHeader("min-expires")),r._expires<Qo&&(r._expires=Qo),r.register()):(Gl.debug("423 response received for REGISTER without Min-Expires"),r._registrationFailure(g,ya.causes.SIP_FAILURE_CODE));break}default:{var D=bc.sipErrorCause(g.status_code);r._registrationFailure(g,D)}}}});this._registering=!0,s.send()}},{key:"unregister",value:function(){var r=this,l=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!this._registered){Gl.debug("already unregistered");return}this._registered=!1,this._registrationTimer!==null&&(clearTimeout(this._registrationTimer),this._registrationTimer=null);var u=this._extraHeaders.slice();l.all?u.push("Contact: *".concat(this._extraContactParams)):u.push("Contact: ".concat(this._contact,";expires=0").concat(this._extraContactParams)),u.push("Expires: 0");var s=new Ih.OutgoingRequest(ya.REGISTER,this._registrar,this._ua,{to_uri:this._to_uri,call_id:this._call_id,cseq:this._cseq+=1},u),n=new Rh(this._ua,s,{onRequestTimeout:function(){r._unregistered(null,ya.causes.REQUEST_TIMEOUT)},onTransportError:function(){r._unregistered(null,ya.causes.CONNECTION_ERROR)},onAuthenticated:function(){r._cseq+=1},onReceiveResponse:function(_){switch(!0){case/^1[0-9]{2}$/.test(_.status_code):break;case/^2[0-9]{2}$/.test(_.status_code):r._unregistered(_);break;default:{var v=bc.sipErrorCause(_.status_code);r._unregistered(_,v)}}}});n.send()}},{key:"close",value:function(){this._registered&&this.unregister()}},{key:"onTransportClosed",value:function(){this._registering=!1,this._registrationTimer!==null&&(clearTimeout(this._registrationTimer),this._registrationTimer=null),this._registered&&(this._registered=!1,this._ua.unregistered({}))}},{key:"_registrationFailure",value:function(r,l){this._registering=!1,this._ua.registrationFailed({response:r||null,cause:l}),this._registered&&(this._registered=!1,this._ua.unregistered({response:r||null,cause:l}))}},{key:"_unregistered",value:function(r,l){this._registering=!1,this._registered=!1,this._ua.unregistered({response:r||null,cause:l||null})}},{key:"registered",get:function(){return this._registered}}]),f}();function J0(f,t){if(!(f instanceof t))throw new TypeError("Cannot call a class as a function")}function $h(f,t){for(var r=0;r<t.length;r++){var l=t[r];l.enumerable=l.enumerable||!1,l.configurable=!0,"value"in l&&(l.writable=!0),Object.defineProperty(f,l.key,l)}}function Q0(f,t,r){return t&&$h(f.prototype,t),r&&$h(f,r),f}var wc=hs,Xo=ql,X0=jl,Ec={onRequestTimeout:function(){},onTransportError:function(){},onSuccessResponse:function(){},onErrorResponse:function(){},onAuthenticated:function(){},onDialogError:function(){}},Z0=function(){function f(t,r,l){J0(this,f),this._dialog=t,this._ua=t._ua,this._request=r,this._eventHandlers=l,this._reattempt=!1,this._reattemptTimer=null;for(var u in Ec)Object.prototype.hasOwnProperty.call(Ec,u)&&(this._eventHandlers[u]||(this._eventHandlers[u]=Ec[u]))}return Q0(f,[{key:"send",value:function(){var r=this,l=new X0(this._ua,this._request,{onRequestTimeout:function(){r._eventHandlers.onRequestTimeout()},onTransportError:function(){r._eventHandlers.onTransportError()},onAuthenticated:function(n){r._eventHandlers.onAuthenticated(n)},onReceiveResponse:function(n){r._receiveResponse(n)}});if(l.send(),(this._request.method===wc.INVITE||this._request.method===wc.UPDATE&&this._request.body)&&l.clientTransaction.state!==Xo.C.STATUS_TERMINATED){this._dialog.uac_pending_reply=!0;var u=function s(){(l.clientTransaction.state===Xo.C.STATUS_ACCEPTED||l.clientTransaction.state===Xo.C.STATUS_COMPLETED||l.clientTransaction.state===Xo.C.STATUS_TERMINATED)&&(l.clientTransaction.removeListener("stateChanged",s),r._dialog.uac_pending_reply=!1)};l.clientTransaction.on("stateChanged",u)}}},{key:"_receiveResponse",value:function(r){var l=this;r.status_code===408||r.status_code===481?this._eventHandlers.onDialogError(r):r.method===wc.INVITE&&r.status_code===491?this._reattempt?r.status_code>=200&&r.status_code<300?this._eventHandlers.onSuccessResponse(r):r.status_code>=300&&this._eventHandlers.onErrorResponse(r):(this._request.cseq=this._dialog.local_seqnum+=1,this._reattemptTimer=setTimeout(function(){l._dialog.isTerminated()||(l._reattempt=!0,l.send())},1e3)):r.status_code>=200&&r.status_code<300?this._eventHandlers.onSuccessResponse(r):r.status_code>=300&&this._eventHandlers.onErrorResponse(r)}},{key:"request",get:function(){return this._request}}]),f}();function eS(f,t){if(!(f instanceof t))throw new TypeError("Cannot call a class as a function")}function xh(f,t){for(var r=0;r<t.length;r++){var l=t[r];l.enumerable=l.enumerable||!1,l.configurable=!0,"value"in l&&(l.writable=!0),Object.defineProperty(f,l.key,l)}}function Oh(f,t,r){return t&&xh(f.prototype,t),r&&xh(f,r),f}var tS=Ts,Dh=xn,bi=hs,Wl=ql,sS=Z0,Cc=Bs(),Ac=new tS("Dialog"),wi={STATUS_EARLY:1,STATUS_CONFIRMED:2,STATUS_TERMINATED:3},rS=function(){Oh(f,null,[{key:"C",get:function(){return wi}}]);function f(t,r,l){var u=arguments.length>3&&arguments[3]!==void 0?arguments[3]:wi.STATUS_CONFIRMED;if(eS(this,f),this._owner=t,this._ua=t._ua,this._uac_pending_reply=!1,this._uas_pending_reply=!1,!r.hasHeader("contact"))return{error:"unable to create a Dialog without Contact header field"};r instanceof Dh.IncomingResponse&&(u=r.status_code<200?wi.STATUS_EARLY:wi.STATUS_CONFIRMED);var s=r.parseHeader("contact");l==="UAS"?(this._id={call_id:r.call_id,local_tag:r.to_tag,remote_tag:r.from_tag,toString:function(){return this.call_id+this.local_tag+this.remote_tag}},this._state=u,this._remote_seqnum=r.cseq,this._local_uri=r.parseHeader("to").uri,this._remote_uri=r.parseHeader("from").uri,this._remote_target=s.uri,this._route_set=r.getHeaders("record-route"),this._ack_seqnum=this._remote_seqnum):l==="UAC"&&(this._id={call_id:r.call_id,local_tag:r.from_tag,remote_tag:r.to_tag,toString:function(){return this.call_id+this.local_tag+this.remote_tag}},this._state=u,this._local_seqnum=r.cseq,this._local_uri=r.parseHeader("from").uri,this._remote_uri=r.parseHeader("to").uri,this._remote_target=s.uri,this._route_set=r.getHeaders("record-route").reverse(),this._ack_seqnum=null),this._ua.newDialog(this),Ac.debug("new ".concat(l," dialog created with status ").concat(this._state===wi.STATUS_EARLY?"EARLY":"CONFIRMED"))}return Oh(f,[{key:"isTerminated",value:function(){return this._status===wi.STATUS_TERMINATED}},{key:"update",value:function(r,l){this._state=wi.STATUS_CONFIRMED,Ac.debug("dialog ".concat(this._id.toString()," changed to CONFIRMED state")),l==="UAC"&&(this._route_set=r.getHeaders("record-route").reverse())}},{key:"terminate",value:function(){Ac.debug("dialog ".concat(this._id.toString()," deleted")),this._ua.destroyDialog(this),this._state=wi.STATUS_TERMINATED}},{key:"sendRequest",value:function(r){var l=this,u=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},s=Cc.cloneArray(u.extraHeaders),n=Cc.cloneObject(u.eventHandlers),g=u.body||null,_=this._createRequest(r,s,g);n.onAuthenticated=function(){l._local_seqnum+=1};var v=new sS(this,_,n);return v.send(),_}},{key:"receiveRequest",value:function(r){this._checkInDialogRequest(r)&&(r.method===bi.ACK&&this._ack_seqnum!==null?this._ack_seqnum=null:r.method===bi.INVITE&&(this._ack_seqnum=r.cseq),this._owner.receiveRequest(r))}},{key:"_createRequest",value:function(r,l,u){l=Cc.cloneArray(l),this._local_seqnum||(this._local_seqnum=Math.floor(Math.random()*1e4));var s=r===bi.CANCEL||r===bi.ACK?this._local_seqnum:this._local_seqnum+=1,n=new Dh.OutgoingRequest(r,this._remote_target,this._ua,{cseq:s,call_id:this._id.call_id,from_uri:this._local_uri,from_tag:this._id.local_tag,to_uri:this._remote_uri,to_tag:this._id.remote_tag,route_set:this._route_set},l,u);return n}},{key:"_checkInDialogRequest",value:function(r){var l=this;if(!this._remote_seqnum)this._remote_seqnum=r.cseq;else if(r.cseq<this._remote_seqnum)if(r.method===bi.ACK){if(this._ack_seqnum===null||r.cseq!==this._ack_seqnum)return!1}else return r.reply(500),!1;else r.cseq>this._remote_seqnum&&(this._remote_seqnum=r.cseq);if(r.method===bi.INVITE||r.method===bi.UPDATE&&r.body){if(this._uac_pending_reply===!0)r.reply(491);else if(this._uas_pending_reply===!0){var u=(Math.random()*10|0)+1;return r.reply(500,null,["Retry-After:".concat(u)]),!1}else{this._uas_pending_reply=!0;var s=function n(){(r.server_transaction.state===Wl.C.STATUS_ACCEPTED||r.server_transaction.state===Wl.C.STATUS_COMPLETED||r.server_transaction.state===Wl.C.STATUS_TERMINATED)&&(r.server_transaction.removeListener("stateChanged",n),l._uas_pending_reply=!1)};r.server_transaction.on("stateChanged",s)}r.hasHeader("contact")&&r.server_transaction.on("stateChanged",function(){r.server_transaction.state===Wl.C.STATUS_ACCEPTED&&(l._remote_target=r.parseHeader("contact").uri)})}else r.method===bi.NOTIFY&&r.hasHeader("contact")&&r.server_transaction.on("stateChanged",function(){r.server_transaction.state===Wl.C.STATUS_COMPLETED&&(l._remote_target=r.parseHeader("contact").uri)});return!0}},{key:"id",get:function(){return this._id}},{key:"local_seqnum",get:function(){return this._local_seqnum},set:function(r){this._local_seqnum=r}},{key:"owner",get:function(){return this._owner}},{key:"uac_pending_reply",get:function(){return this._uac_pending_reply},set:function(r){this._uac_pending_reply=r}},{key:"uas_pending_reply",get:function(){return this._uas_pending_reply}}]),f}(),Ic={exports:{}};function Zo(f){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?Zo=function(r){return typeof r}:Zo=function(r){return r&&typeof Symbol=="function"&&r.constructor===Symbol&&r!==Symbol.prototype?"symbol":typeof r},Zo(f)}function nS(f,t){if(!(f instanceof t))throw new TypeError("Cannot call a class as a function")}function kh(f,t){for(var r=0;r<t.length;r++){var l=t[r];l.enumerable=l.enumerable||!1,l.configurable=!0,"value"in l&&(l.writable=!0),Object.defineProperty(f,l.key,l)}}function iS(f,t,r){return t&&kh(f.prototype,t),r&&kh(f,r),f}function aS(f,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");f.prototype=Object.create(t&&t.prototype,{constructor:{value:f,writable:!0,configurable:!0}}),t&&Rc(f,t)}function Rc(f,t){return Rc=Object.setPrototypeOf||function(l,u){return l.__proto__=u,l},Rc(f,t)}function lS(f){var t=cS();return function(){var l=eu(f),u;if(t){var s=eu(this).constructor;u=Reflect.construct(l,arguments,s)}else u=l.apply(this,arguments);return oS(this,u)}}function oS(f,t){return t&&(Zo(t)==="object"||typeof t=="function")?t:uS(f)}function uS(f){if(f===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return f}function cS(){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 eu(f){return eu=Object.setPrototypeOf?Object.getPrototypeOf:function(r){return r.__proto__||Object.getPrototypeOf(r)},eu(f)}var dS=ys.EventEmitter,fS=Ts,hS=hs,_S=yi,Nh=Bs(),pS=new fS("RTCSession:DTMF"),Mh={MIN_DURATION:70,MAX_DURATION:6e3,DEFAULT_DURATION:100,MIN_INTER_TONE_GAP:50,DEFAULT_INTER_TONE_GAP:500};Ic.exports=function(f){aS(r,f);var t=lS(r);function r(l){var u;return nS(this,r),u=t.call(this),u._session=l,u._direction=null,u._tone=null,u._duration=null,u._request=null,u}return iS(r,[{key:"send",value:function(u){var s=this,n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(u===void 0)throw new TypeError("Not enough arguments");if(this._direction="outgoing",this._session.status!==this._session.C.STATUS_CONFIRMED&&this._session.status!==this._session.C.STATUS_WAITING_FOR_ACK)throw new _S.InvalidStateError(this._session.status);var g=Nh.cloneArray(n.extraHeaders);if(this.eventHandlers=Nh.cloneObject(n.eventHandlers),typeof u=="string")u=u.toUpperCase();else if(typeof u=="number")u=u.toString();else throw new TypeError("Invalid tone: ".concat(u));if(u.match(/^[0-9A-DR#*]$/))this._tone=u;else throw new TypeError("Invalid tone: ".concat(u));this._duration=n.duration,g.push("Content-Type: application/dtmf-relay");var _="Signal=".concat(this._tone,`\r
46
+ `),this.transport.send(g)}}]),r}(ph),A0=function(f){pc(r,f);var t=gc(r);function r(){var l;return Ul(this,r),l=t.call(this),l.headers={},l.status_code=null,l.reason_phrase=null,l}return r}(ph),xn={OutgoingRequest:_h,InitialOutgoingInviteRequest:E0,IncomingRequest:C0,IncomingResponse:A0};function I0(f,t){if(!(f instanceof t))throw new TypeError("Cannot call a class as a function")}function mh(f,t){for(var r=0;r<t.length;r++){var l=t[r];l.enumerable=l.enumerable||!1,l.configurable=!0,"value"in l&&(l.writable=!0),Object.defineProperty(f,l.key,l)}}function R0(f,t,r){return t&&mh(f.prototype,t),r&&mh(f,r),f}var $0=Ts,On=Bs(),Or=new $0("DigestAuthentication"),x0=function(){function f(t){I0(this,f),this._credentials=t,this._cnonce=null,this._nc=0,this._ncHex="00000000",this._algorithm=null,this._realm=null,this._nonce=null,this._opaque=null,this._stale=null,this._qop=null,this._method=null,this._uri=null,this._ha1=null,this._response=null}return R0(f,[{key:"get",value:function(r){switch(r){case"realm":return this._realm;case"ha1":return this._ha1;default:Or.warn('get() | cannot get "%s" parameter',r);return}}},{key:"authenticate",value:function(r,l){var u=r.method,s=r.ruri,n=r.body,g=arguments.length>2&&arguments[2]!==void 0?arguments[2]:null;if(this._algorithm=l.algorithm,this._realm=l.realm,this._nonce=l.nonce,this._opaque=l.opaque,this._stale=l.stale,this._algorithm){if(this._algorithm!=="MD5")return Or.warn('authenticate() | challenge with Digest algorithm different than "MD5", authentication aborted'),!1}else this._algorithm="MD5";if(!this._nonce)return Or.warn("authenticate() | challenge without Digest nonce, authentication aborted"),!1;if(!this._realm)return Or.warn("authenticate() | challenge without Digest realm, authentication aborted"),!1;if(!this._credentials.password){if(!this._credentials.ha1)return Or.warn("authenticate() | no plain SIP password nor ha1 provided, authentication aborted"),!1;if(this._credentials.realm!==this._realm)return Or.warn('authenticate() | no plain SIP password, and stored `realm` does not match the given `realm`, cannot authenticate [stored:"%s", given:"%s"]',this._credentials.realm,this._realm),!1}if(l.qop)if(l.qop.indexOf("auth-int")>-1)this._qop="auth-int";else if(l.qop.indexOf("auth")>-1)this._qop="auth";else return Or.warn('authenticate() | challenge without Digest qop different than "auth" or "auth-int", authentication aborted'),!1;else this._qop=null;this._method=u,this._uri=s,this._cnonce=g||On.createRandomToken(12),this._nc+=1;var _=Number(this._nc).toString(16);this._ncHex="00000000".substr(0,8-_.length)+_,this._nc===4294967296&&(this._nc=1,this._ncHex="00000001"),this._credentials.password?this._ha1=On.calculateMD5("".concat(this._credentials.username,":").concat(this._realm,":").concat(this._credentials.password)):this._ha1=this._credentials.ha1;var v,C;return this._qop==="auth"?(v="".concat(this._method,":").concat(this._uri),C=On.calculateMD5(v),Or.debug('authenticate() | using qop=auth [a2:"%s"]',v),this._response=On.calculateMD5("".concat(this._ha1,":").concat(this._nonce,":").concat(this._ncHex,":").concat(this._cnonce,":auth:").concat(C))):this._qop==="auth-int"?(v="".concat(this._method,":").concat(this._uri,":").concat(On.calculateMD5(n||"")),C=On.calculateMD5(v),Or.debug('authenticate() | using qop=auth-int [a2:"%s"]',v),this._response=On.calculateMD5("".concat(this._ha1,":").concat(this._nonce,":").concat(this._ncHex,":").concat(this._cnonce,":auth-int:").concat(C))):this._qop===null&&(v="".concat(this._method,":").concat(this._uri),C=On.calculateMD5(v),Or.debug('authenticate() | using qop=null [a2:"%s"]',v),this._response=On.calculateMD5("".concat(this._ha1,":").concat(this._nonce,":").concat(C))),Or.debug("authenticate() | response generated"),!0}},{key:"toString",value:function(){var r=[];if(!this._response)throw new Error("response field does not exist, cannot generate Authorization header");return r.push("algorithm=".concat(this._algorithm)),r.push('username="'.concat(this._credentials.username,'"')),r.push('realm="'.concat(this._realm,'"')),r.push('nonce="'.concat(this._nonce,'"')),r.push('uri="'.concat(this._uri,'"')),r.push('response="'.concat(this._response,'"')),this._opaque&&r.push('opaque="'.concat(this._opaque,'"')),this._qop&&(r.push("qop=".concat(this._qop)),r.push('cnonce="'.concat(this._cnonce,'"')),r.push("nc=".concat(this._ncHex))),"Digest ".concat(r.join(", "))}}]),f}(),Dn=500,O0=4e3,gh=5e3,vh={T1:Dn,T2:O0,T4:gh,TIMER_B:64*Dn,TIMER_D:0*Dn,TIMER_F:64*Dn,TIMER_H:64*Dn,TIMER_I:0*Dn,TIMER_J:0*Dn,TIMER_K:0*gh,TIMER_L:64*Dn,TIMER_M:64*Dn,PROVISIONAL_RESPONSE_INTERVAL:6e4};function Wo(f){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?Wo=function(r){return typeof r}:Wo=function(r){return r&&typeof Symbol=="function"&&r.constructor===Symbol&&r!==Symbol.prototype?"symbol":typeof r},Wo(f)}function Pl(f,t){if(!(f instanceof t))throw new TypeError("Cannot call a class as a function")}function yh(f,t){for(var r=0;r<t.length;r++){var l=t[r];l.enumerable=l.enumerable||!1,l.configurable=!0,"value"in l&&(l.writable=!0),Object.defineProperty(f,l.key,l)}}function Ll(f,t,r){return t&&yh(f.prototype,t),r&&yh(f,r),f}function Hl(f,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");f.prototype=Object.create(t&&t.prototype,{constructor:{value:f,writable:!0,configurable:!0}}),t&&yc(f,t)}function yc(f,t){return yc=Object.setPrototypeOf||function(l,u){return l.__proto__=u,l},yc(f,t)}function Fl(f){var t=k0();return function(){var l=Ko(f),u;if(t){var s=Ko(this).constructor;u=Reflect.construct(l,arguments,s)}else u=l.apply(this,arguments);return D0(this,u)}}function D0(f,t){return t&&(Wo(t)==="object"||typeof t=="function")?t:Si(f)}function Si(f){if(f===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return f}function k0(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],function(){})),!0}catch{return!1}}function Ko(f){return Ko=Object.setPrototypeOf?Object.getPrototypeOf:function(r){return r.__proto__||Object.getPrototypeOf(r)},Ko(f)}var Bl=ys.EventEmitter,zl=Ts,Vl=hs,Th=xn,un=vh,Sh=new zl("NonInviteClientTransaction"),Yo=new zl("InviteClientTransaction"),N0=new zl("AckClientTransaction"),bh=new zl("NonInviteServerTransaction"),Jo=new zl("InviteServerTransaction"),je={STATUS_TRYING:1,STATUS_PROCEEDING:2,STATUS_CALLING:3,STATUS_ACCEPTED:4,STATUS_COMPLETED:5,STATUS_TERMINATED:6,STATUS_CONFIRMED:7,NON_INVITE_CLIENT:"nict",NON_INVITE_SERVER:"nist",INVITE_CLIENT:"ict",INVITE_SERVER:"ist"},M0=function(f){Hl(r,f);var t=Fl(r);function r(l,u,s,n){var g;Pl(this,r),g=t.call(this),g.type=je.NON_INVITE_CLIENT,g.id="z9hG4bK".concat(Math.floor(Math.random()*1e7)),g.ua=l,g.transport=u,g.request=s,g.eventHandlers=n;var _="SIP/2.0/".concat(u.via_transport);return _+=" ".concat(l.configuration.via_host,";branch=").concat(g.id),g.request.setHeader("via",_),g.ua.newTransaction(Si(g)),g}return Ll(r,[{key:"stateChanged",value:function(u){this.state=u,this.emit("stateChanged")}},{key:"send",value:function(){var u=this;this.stateChanged(je.STATUS_TRYING),this.F=setTimeout(function(){u.timer_F()},un.TIMER_F),this.transport.send(this.request)||this.onTransportError()}},{key:"onTransportError",value:function(){Sh.debug("transport error occurred, deleting transaction ".concat(this.id)),clearTimeout(this.F),clearTimeout(this.K),this.stateChanged(je.STATUS_TERMINATED),this.ua.destroyTransaction(this),this.eventHandlers.onTransportError()}},{key:"timer_F",value:function(){Sh.debug("Timer F expired for transaction ".concat(this.id)),this.stateChanged(je.STATUS_TERMINATED),this.ua.destroyTransaction(this),this.eventHandlers.onRequestTimeout()}},{key:"timer_K",value:function(){this.stateChanged(je.STATUS_TERMINATED),this.ua.destroyTransaction(this)}},{key:"receiveResponse",value:function(u){var s=this,n=u.status_code;if(n<200)switch(this.state){case je.STATUS_TRYING:case je.STATUS_PROCEEDING:this.stateChanged(je.STATUS_PROCEEDING),this.eventHandlers.onReceiveResponse(u);break}else switch(this.state){case je.STATUS_TRYING:case je.STATUS_PROCEEDING:this.stateChanged(je.STATUS_COMPLETED),clearTimeout(this.F),n===408?this.eventHandlers.onRequestTimeout():this.eventHandlers.onReceiveResponse(u),this.K=setTimeout(function(){s.timer_K()},un.TIMER_K);break;case je.STATUS_COMPLETED:break}}},{key:"C",get:function(){return je}}]),r}(Bl),U0=function(f){Hl(r,f);var t=Fl(r);function r(l,u,s,n){var g;Pl(this,r),g=t.call(this),g.type=je.INVITE_CLIENT,g.id="z9hG4bK".concat(Math.floor(Math.random()*1e7)),g.ua=l,g.transport=u,g.request=s,g.eventHandlers=n,s.transaction=Si(g);var _="SIP/2.0/".concat(u.via_transport);return _+=" ".concat(l.configuration.via_host,";branch=").concat(g.id),g.request.setHeader("via",_),g.ua.newTransaction(Si(g)),g}return Ll(r,[{key:"stateChanged",value:function(u){this.state=u,this.emit("stateChanged")}},{key:"send",value:function(){var u=this;this.stateChanged(je.STATUS_CALLING),this.B=setTimeout(function(){u.timer_B()},un.TIMER_B),this.transport.send(this.request)||this.onTransportError()}},{key:"onTransportError",value:function(){clearTimeout(this.B),clearTimeout(this.D),clearTimeout(this.M),this.state!==je.STATUS_ACCEPTED&&(Yo.debug("transport error occurred, deleting transaction ".concat(this.id)),this.eventHandlers.onTransportError()),this.stateChanged(je.STATUS_TERMINATED),this.ua.destroyTransaction(this)}},{key:"timer_M",value:function(){Yo.debug("Timer M expired for transaction ".concat(this.id)),this.state===je.STATUS_ACCEPTED&&(clearTimeout(this.B),this.stateChanged(je.STATUS_TERMINATED),this.ua.destroyTransaction(this))}},{key:"timer_B",value:function(){Yo.debug("Timer B expired for transaction ".concat(this.id)),this.state===je.STATUS_CALLING&&(this.stateChanged(je.STATUS_TERMINATED),this.ua.destroyTransaction(this),this.eventHandlers.onRequestTimeout())}},{key:"timer_D",value:function(){Yo.debug("Timer D expired for transaction ".concat(this.id)),clearTimeout(this.B),this.stateChanged(je.STATUS_TERMINATED),this.ua.destroyTransaction(this)}},{key:"sendACK",value:function(u){var s=this,n=new Th.OutgoingRequest(Vl.ACK,this.request.ruri,this.ua,{route_set:this.request.getHeaders("route"),call_id:this.request.getHeader("call-id"),cseq:this.request.cseq});n.setHeader("from",this.request.getHeader("from")),n.setHeader("via",this.request.getHeader("via")),n.setHeader("to",u.getHeader("to")),this.D=setTimeout(function(){s.timer_D()},un.TIMER_D),this.transport.send(n)}},{key:"cancel",value:function(u){if(this.state===je.STATUS_PROCEEDING){var s=new Th.OutgoingRequest(Vl.CANCEL,this.request.ruri,this.ua,{route_set:this.request.getHeaders("route"),call_id:this.request.getHeader("call-id"),cseq:this.request.cseq});s.setHeader("from",this.request.getHeader("from")),s.setHeader("via",this.request.getHeader("via")),s.setHeader("to",this.request.getHeader("to")),u&&s.setHeader("reason",u),this.transport.send(s)}}},{key:"receiveResponse",value:function(u){var s=this,n=u.status_code;if(n>=100&&n<=199)switch(this.state){case je.STATUS_CALLING:this.stateChanged(je.STATUS_PROCEEDING),this.eventHandlers.onReceiveResponse(u);break;case je.STATUS_PROCEEDING:this.eventHandlers.onReceiveResponse(u);break}else if(n>=200&&n<=299)switch(this.state){case je.STATUS_CALLING:case je.STATUS_PROCEEDING:this.stateChanged(je.STATUS_ACCEPTED),this.M=setTimeout(function(){s.timer_M()},un.TIMER_M),this.eventHandlers.onReceiveResponse(u);break;case je.STATUS_ACCEPTED:this.eventHandlers.onReceiveResponse(u);break}else if(n>=300&&n<=699)switch(this.state){case je.STATUS_CALLING:case je.STATUS_PROCEEDING:this.stateChanged(je.STATUS_COMPLETED),this.sendACK(u),this.eventHandlers.onReceiveResponse(u);break;case je.STATUS_COMPLETED:this.sendACK(u);break}}},{key:"C",get:function(){return je}}]),r}(Bl),P0=function(f){Hl(r,f);var t=Fl(r);function r(l,u,s,n){var g;Pl(this,r),g=t.call(this),g.id="z9hG4bK".concat(Math.floor(Math.random()*1e7)),g.transport=u,g.request=s,g.eventHandlers=n;var _="SIP/2.0/".concat(u.via_transport);return _+=" ".concat(l.configuration.via_host,";branch=").concat(g.id),g.request.setHeader("via",_),g}return Ll(r,[{key:"send",value:function(){this.transport.send(this.request)||this.onTransportError()}},{key:"onTransportError",value:function(){N0.debug("transport error occurred for transaction ".concat(this.id)),this.eventHandlers.onTransportError()}},{key:"C",get:function(){return je}}]),r}(Bl),L0=function(f){Hl(r,f);var t=Fl(r);function r(l,u,s){var n;return Pl(this,r),n=t.call(this),n.type=je.NON_INVITE_SERVER,n.id=s.via_branch,n.ua=l,n.transport=u,n.request=s,n.last_response="",s.server_transaction=Si(n),n.state=je.STATUS_TRYING,l.newTransaction(Si(n)),n}return Ll(r,[{key:"stateChanged",value:function(u){this.state=u,this.emit("stateChanged")}},{key:"timer_J",value:function(){bh.debug("Timer J expired for transaction ".concat(this.id)),this.stateChanged(je.STATUS_TERMINATED),this.ua.destroyTransaction(this)}},{key:"onTransportError",value:function(){this.transportError||(this.transportError=!0,bh.debug("transport error occurred, deleting transaction ".concat(this.id)),clearTimeout(this.J),this.stateChanged(je.STATUS_TERMINATED),this.ua.destroyTransaction(this))}},{key:"receiveResponse",value:function(u,s,n,g){var _=this;if(u===100)switch(this.state){case je.STATUS_TRYING:this.stateChanged(je.STATUS_PROCEEDING),this.transport.send(s)||this.onTransportError();break;case je.STATUS_PROCEEDING:this.last_response=s,this.transport.send(s)?n&&n():(this.onTransportError(),g&&g());break}else if(u>=200&&u<=699)switch(this.state){case je.STATUS_TRYING:case je.STATUS_PROCEEDING:this.stateChanged(je.STATUS_COMPLETED),this.last_response=s,this.J=setTimeout(function(){_.timer_J()},un.TIMER_J),this.transport.send(s)?n&&n():(this.onTransportError(),g&&g());break;case je.STATUS_COMPLETED:break}}},{key:"C",get:function(){return je}}]),r}(Bl),H0=function(f){Hl(r,f);var t=Fl(r);function r(l,u,s){var n;return Pl(this,r),n=t.call(this),n.type=je.INVITE_SERVER,n.id=s.via_branch,n.ua=l,n.transport=u,n.request=s,n.last_response="",s.server_transaction=Si(n),n.state=je.STATUS_PROCEEDING,l.newTransaction(Si(n)),n.resendProvisionalTimer=null,s.reply(100),n}return Ll(r,[{key:"stateChanged",value:function(u){this.state=u,this.emit("stateChanged")}},{key:"timer_H",value:function(){Jo.debug("Timer H expired for transaction ".concat(this.id)),this.state===je.STATUS_COMPLETED&&Jo.debug("ACK not received, dialog will be terminated"),this.stateChanged(je.STATUS_TERMINATED),this.ua.destroyTransaction(this)}},{key:"timer_I",value:function(){this.stateChanged(je.STATUS_TERMINATED),this.ua.destroyTransaction(this)}},{key:"timer_L",value:function(){Jo.debug("Timer L expired for transaction ".concat(this.id)),this.state===je.STATUS_ACCEPTED&&(this.stateChanged(je.STATUS_TERMINATED),this.ua.destroyTransaction(this))}},{key:"onTransportError",value:function(){this.transportError||(this.transportError=!0,Jo.debug("transport error occurred, deleting transaction ".concat(this.id)),this.resendProvisionalTimer!==null&&(clearInterval(this.resendProvisionalTimer),this.resendProvisionalTimer=null),clearTimeout(this.L),clearTimeout(this.H),clearTimeout(this.I),this.stateChanged(je.STATUS_TERMINATED),this.ua.destroyTransaction(this))}},{key:"resend_provisional",value:function(){this.transport.send(this.last_response)||this.onTransportError()}},{key:"receiveResponse",value:function(u,s,n,g){var _=this;if(u>=100&&u<=199)switch(this.state){case je.STATUS_PROCEEDING:this.transport.send(s)||this.onTransportError(),this.last_response=s;break}if(u>100&&u<=199&&this.state===je.STATUS_PROCEEDING)this.resendProvisionalTimer===null&&(this.resendProvisionalTimer=setInterval(function(){_.resend_provisional()},un.PROVISIONAL_RESPONSE_INTERVAL));else if(u>=200&&u<=299)switch(this.state){case je.STATUS_PROCEEDING:this.stateChanged(je.STATUS_ACCEPTED),this.last_response=s,this.L=setTimeout(function(){_.timer_L()},un.TIMER_L),this.resendProvisionalTimer!==null&&(clearInterval(this.resendProvisionalTimer),this.resendProvisionalTimer=null);case je.STATUS_ACCEPTED:this.transport.send(s)?n&&n():(this.onTransportError(),g&&g());break}else if(u>=300&&u<=699)switch(this.state){case je.STATUS_PROCEEDING:this.resendProvisionalTimer!==null&&(clearInterval(this.resendProvisionalTimer),this.resendProvisionalTimer=null),this.transport.send(s)?(this.stateChanged(je.STATUS_COMPLETED),this.H=setTimeout(function(){_.timer_H()},un.TIMER_H),n&&n()):(this.onTransportError(),g&&g());break}}},{key:"C",get:function(){return je}}]),r}(Bl);function F0(f,t){var r=f._transactions,l;switch(t.method){case Vl.INVITE:if(l=r.ist[t.via_branch],l){switch(l.state){case je.STATUS_PROCEEDING:l.transport.send(l.last_response);break;case je.STATUS_ACCEPTED:break}return!0}break;case Vl.ACK:if(l=r.ist[t.via_branch],l){if(l.state===je.STATUS_ACCEPTED)return!1;if(l.state===je.STATUS_COMPLETED)return l.state=je.STATUS_CONFIRMED,l.I=setTimeout(function(){l.timer_I()},un.TIMER_I),!0}else return!1;break;case Vl.CANCEL:return l=r.ist[t.via_branch],l?(t.reply_sl(200),l.state!==je.STATUS_PROCEEDING):(t.reply_sl(481),!0);default:if(l=r.nist[t.via_branch],l){switch(l.state){case je.STATUS_TRYING:break;case je.STATUS_PROCEEDING:case je.STATUS_COMPLETED:l.transport.send(l.last_response);break}return!0}break}}var ql={C:je,NonInviteClientTransaction:M0,InviteClientTransaction:U0,AckClientTransaction:P0,NonInviteServerTransaction:L0,InviteServerTransaction:H0,checkTransaction:F0};function B0(f,t){if(!(f instanceof t))throw new TypeError("Cannot call a class as a function")}function wh(f,t){for(var r=0;r<t.length;r++){var l=t[r];l.enumerable=l.enumerable||!1,l.configurable=!0,"value"in l&&(l.writable=!0),Object.defineProperty(f,l.key,l)}}function z0(f,t,r){return t&&wh(f.prototype,t),r&&wh(f,r),f}var V0=Ts,Eh=hs,q0=x0,Tc=ql,j0=new V0("RequestSender"),Sc={onRequestTimeout:function(){},onTransportError:function(){},onReceiveResponse:function(){},onAuthenticated:function(){}},jl=function(){function f(t,r,l){B0(this,f),this._ua=t,this._eventHandlers=l,this._method=r.method,this._request=r,this._auth=null,this._challenged=!1,this._staled=!1;for(var u in Sc)Object.prototype.hasOwnProperty.call(Sc,u)&&(this._eventHandlers[u]||(this._eventHandlers[u]=Sc[u]));t.status===t.C.STATUS_USER_CLOSED&&(this._method!==Eh.BYE||this._method!==Eh.ACK)&&this._eventHandlers.onTransportError()}return z0(f,[{key:"send",value:function(){var r=this,l={onRequestTimeout:function(){r._eventHandlers.onRequestTimeout()},onTransportError:function(){r._eventHandlers.onTransportError()},onReceiveResponse:function(s){r._receiveResponse(s)}};switch(this._method){case"INVITE":this.clientTransaction=new Tc.InviteClientTransaction(this._ua,this._ua.transport,this._request,l);break;case"ACK":this.clientTransaction=new Tc.AckClientTransaction(this._ua,this._ua.transport,this._request,l);break;default:this.clientTransaction=new Tc.NonInviteClientTransaction(this._ua,this._ua.transport,this._request,l)}this._ua._configuration.authorization_jwt&&this._request.setHeader("Authorization",this._ua._configuration.authorization_jwt),this.clientTransaction.send()}},{key:"_receiveResponse",value:function(r){var l,u,s=r.status_code;if((s===401||s===407)&&(this._ua.configuration.password!==null||this._ua.configuration.ha1!==null)){if(r.status_code===401?(l=r.parseHeader("www-authenticate"),u="authorization"):(l=r.parseHeader("proxy-authenticate"),u="proxy-authorization"),!l){j0.debug("".concat(r.status_code," with wrong or missing challenge, cannot authenticate")),this._eventHandlers.onReceiveResponse(r);return}if(!this._challenged||!this._staled&&l.stale===!0){if(this._auth||(this._auth=new q0({username:this._ua.configuration.authorization_user,password:this._ua.configuration.password,realm:this._ua.configuration.realm,ha1:this._ua.configuration.ha1})),!this._auth.authenticate(this._request,l)){this._eventHandlers.onReceiveResponse(r);return}this._challenged=!0,this._ua.set("realm",this._auth.get("realm")),this._ua.set("ha1",this._auth.get("ha1")),l.stale&&(this._staled=!0),this._request=this._request.clone(),this._request.cseq+=1,this._request.setHeader("cseq","".concat(this._request.cseq," ").concat(this._method)),this._request.setHeader(u,this._auth.toString()),this._eventHandlers.onAuthenticated(this._request),this.send()}else this._eventHandlers.onReceiveResponse(r)}else this._eventHandlers.onReceiveResponse(r)}}]),f}();function G0(f,t){if(!(f instanceof t))throw new TypeError("Cannot call a class as a function")}function Ch(f,t){for(var r=0;r<t.length;r++){var l=t[r];l.enumerable=l.enumerable||!1,l.configurable=!0,"value"in l&&(l.writable=!0),Object.defineProperty(f,l.key,l)}}function W0(f,t,r){return t&&Ch(f.prototype,t),r&&Ch(f,r),f}var K0=Ts,bc=Bs(),ya=hs,Ah=xn,Ih=jl,Gl=new K0("Registrator"),Qo=10,Y0=function(){function f(t,r){G0(this,f),this._reg_id=1,this._ua=t,this._transport=r,this._registrar=t.configuration.registrar_server,this._expires=t.configuration.register_expires,this._call_id=bc.createRandomToken(22),this._cseq=0,this._to_uri=t.configuration.uri,this._registrationTimer=null,this._registering=!1,this._registered=!1,this._contact=this._ua.contact.toString(),this._contact+=";+sip.ice",this._extraHeaders=[],this._extraContactParams="",this._sipInstance='"<urn:uuid:'.concat(this._ua.configuration.instance_id,'>"'),this._contact+=";reg-id=".concat(this._reg_id),this._contact+=";+sip.instance=".concat(this._sipInstance)}return W0(f,[{key:"setExtraHeaders",value:function(r){Array.isArray(r)||(r=[]),this._extraHeaders=r.slice()}},{key:"setExtraContactParams",value:function(r){r instanceof Object||(r={}),this._extraContactParams="";for(var l in r)if(Object.prototype.hasOwnProperty.call(r,l)){var u=r[l];this._extraContactParams+=";".concat(l),u&&(this._extraContactParams+="=".concat(u))}}},{key:"register",value:function(){var r=this;if(this._registering){Gl.debug("Register request in progress...");return}var l=this._extraHeaders.slice();l.push("Contact: ".concat(this._contact,";expires=").concat(this._expires).concat(this._extraContactParams)),l.push("Expires: ".concat(this._expires));var u=new Ah.OutgoingRequest(ya.REGISTER,this._registrar,this._ua,{to_uri:this._to_uri,call_id:this._call_id,cseq:this._cseq+=1},l),s=new Ih(this._ua,u,{onRequestTimeout:function(){r._registrationFailure(null,ya.causes.REQUEST_TIMEOUT)},onTransportError:function(){r._registrationFailure(null,ya.causes.CONNECTION_ERROR)},onAuthenticated:function(){r._cseq+=1},onReceiveResponse:function(g){if(g.cseq===r._cseq)switch(r._registrationTimer!==null&&(clearTimeout(r._registrationTimer),r._registrationTimer=null),!0){case/^1[0-9]{2}$/.test(g.status_code):break;case/^2[0-9]{2}$/.test(g.status_code):{if(r._registering=!1,!g.hasHeader("Contact")){Gl.debug("no Contact header in response to REGISTER, response ignored");break}var _=g.headers.Contact.reduce(function(H,F){return H.concat(F.parsed)},[]),v=_.find(function(H){return r._sipInstance===H.getParam("+sip.instance")&&r._reg_id===parseInt(H.getParam("reg-id"))});if(v||(v=_.find(function(H){return H.uri.user===r._ua.contact.uri.user})),!v){Gl.debug("no Contact header pointing to us, response ignored");break}var C=v.getParam("expires");!C&&g.hasHeader("expires")&&(C=g.getHeader("expires")),C||(C=r._expires),C=Number(C),C<Qo&&(C=Qo);var R=C>64?C*1e3/2+Math.floor((C/2-32)*1e3*Math.random()):C*1e3-5e3;r._registrationTimer=setTimeout(function(){r._registrationTimer=null,r._ua.listeners("registrationExpiring").length===0?r.register():r._ua.emit("registrationExpiring")},R),v.hasParam("temp-gruu")&&(r._ua.contact.temp_gruu=v.getParam("temp-gruu").replace(/"/g,"")),v.hasParam("pub-gruu")&&(r._ua.contact.pub_gruu=v.getParam("pub-gruu").replace(/"/g,"")),r._registered||(r._registered=!0,r._ua.registered({response:g}));break}case/^423$/.test(g.status_code):{g.hasHeader("min-expires")?(r._expires=Number(g.getHeader("min-expires")),r._expires<Qo&&(r._expires=Qo),r.register()):(Gl.debug("423 response received for REGISTER without Min-Expires"),r._registrationFailure(g,ya.causes.SIP_FAILURE_CODE));break}default:{var D=bc.sipErrorCause(g.status_code);r._registrationFailure(g,D)}}}});this._registering=!0,s.send()}},{key:"unregister",value:function(){var r=this,l=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!this._registered){Gl.debug("already unregistered");return}this._registered=!1,this._registrationTimer!==null&&(clearTimeout(this._registrationTimer),this._registrationTimer=null);var u=this._extraHeaders.slice();l.all?u.push("Contact: *".concat(this._extraContactParams)):u.push("Contact: ".concat(this._contact,";expires=0").concat(this._extraContactParams)),u.push("Expires: 0");var s=new Ah.OutgoingRequest(ya.REGISTER,this._registrar,this._ua,{to_uri:this._to_uri,call_id:this._call_id,cseq:this._cseq+=1},u),n=new Ih(this._ua,s,{onRequestTimeout:function(){r._unregistered(null,ya.causes.REQUEST_TIMEOUT)},onTransportError:function(){r._unregistered(null,ya.causes.CONNECTION_ERROR)},onAuthenticated:function(){r._cseq+=1},onReceiveResponse:function(_){switch(!0){case/^1[0-9]{2}$/.test(_.status_code):break;case/^2[0-9]{2}$/.test(_.status_code):r._unregistered(_);break;default:{var v=bc.sipErrorCause(_.status_code);r._unregistered(_,v)}}}});n.send()}},{key:"close",value:function(){this._registered&&this.unregister()}},{key:"onTransportClosed",value:function(){this._registering=!1,this._registrationTimer!==null&&(clearTimeout(this._registrationTimer),this._registrationTimer=null),this._registered&&(this._registered=!1,this._ua.unregistered({}))}},{key:"_registrationFailure",value:function(r,l){this._registering=!1,this._ua.registrationFailed({response:r||null,cause:l}),this._registered&&(this._registered=!1,this._ua.unregistered({response:r||null,cause:l}))}},{key:"_unregistered",value:function(r,l){this._registering=!1,this._registered=!1,this._ua.unregistered({response:r||null,cause:l||null})}},{key:"registered",get:function(){return this._registered}}]),f}();function J0(f,t){if(!(f instanceof t))throw new TypeError("Cannot call a class as a function")}function Rh(f,t){for(var r=0;r<t.length;r++){var l=t[r];l.enumerable=l.enumerable||!1,l.configurable=!0,"value"in l&&(l.writable=!0),Object.defineProperty(f,l.key,l)}}function Q0(f,t,r){return t&&Rh(f.prototype,t),r&&Rh(f,r),f}var wc=hs,Xo=ql,X0=jl,Ec={onRequestTimeout:function(){},onTransportError:function(){},onSuccessResponse:function(){},onErrorResponse:function(){},onAuthenticated:function(){},onDialogError:function(){}},Z0=function(){function f(t,r,l){J0(this,f),this._dialog=t,this._ua=t._ua,this._request=r,this._eventHandlers=l,this._reattempt=!1,this._reattemptTimer=null;for(var u in Ec)Object.prototype.hasOwnProperty.call(Ec,u)&&(this._eventHandlers[u]||(this._eventHandlers[u]=Ec[u]))}return Q0(f,[{key:"send",value:function(){var r=this,l=new X0(this._ua,this._request,{onRequestTimeout:function(){r._eventHandlers.onRequestTimeout()},onTransportError:function(){r._eventHandlers.onTransportError()},onAuthenticated:function(n){r._eventHandlers.onAuthenticated(n)},onReceiveResponse:function(n){r._receiveResponse(n)}});if(l.send(),(this._request.method===wc.INVITE||this._request.method===wc.UPDATE&&this._request.body)&&l.clientTransaction.state!==Xo.C.STATUS_TERMINATED){this._dialog.uac_pending_reply=!0;var u=function s(){(l.clientTransaction.state===Xo.C.STATUS_ACCEPTED||l.clientTransaction.state===Xo.C.STATUS_COMPLETED||l.clientTransaction.state===Xo.C.STATUS_TERMINATED)&&(l.clientTransaction.removeListener("stateChanged",s),r._dialog.uac_pending_reply=!1)};l.clientTransaction.on("stateChanged",u)}}},{key:"_receiveResponse",value:function(r){var l=this;r.status_code===408||r.status_code===481?this._eventHandlers.onDialogError(r):r.method===wc.INVITE&&r.status_code===491?this._reattempt?r.status_code>=200&&r.status_code<300?this._eventHandlers.onSuccessResponse(r):r.status_code>=300&&this._eventHandlers.onErrorResponse(r):(this._request.cseq=this._dialog.local_seqnum+=1,this._reattemptTimer=setTimeout(function(){l._dialog.isTerminated()||(l._reattempt=!0,l.send())},1e3)):r.status_code>=200&&r.status_code<300?this._eventHandlers.onSuccessResponse(r):r.status_code>=300&&this._eventHandlers.onErrorResponse(r)}},{key:"request",get:function(){return this._request}}]),f}();function eS(f,t){if(!(f instanceof t))throw new TypeError("Cannot call a class as a function")}function $h(f,t){for(var r=0;r<t.length;r++){var l=t[r];l.enumerable=l.enumerable||!1,l.configurable=!0,"value"in l&&(l.writable=!0),Object.defineProperty(f,l.key,l)}}function xh(f,t,r){return t&&$h(f.prototype,t),r&&$h(f,r),f}var tS=Ts,Oh=xn,bi=hs,Wl=ql,sS=Z0,Cc=Bs(),Ac=new tS("Dialog"),wi={STATUS_EARLY:1,STATUS_CONFIRMED:2,STATUS_TERMINATED:3},rS=function(){xh(f,null,[{key:"C",get:function(){return wi}}]);function f(t,r,l){var u=arguments.length>3&&arguments[3]!==void 0?arguments[3]:wi.STATUS_CONFIRMED;if(eS(this,f),this._owner=t,this._ua=t._ua,this._uac_pending_reply=!1,this._uas_pending_reply=!1,!r.hasHeader("contact"))return{error:"unable to create a Dialog without Contact header field"};r instanceof Oh.IncomingResponse&&(u=r.status_code<200?wi.STATUS_EARLY:wi.STATUS_CONFIRMED);var s=r.parseHeader("contact");l==="UAS"?(this._id={call_id:r.call_id,local_tag:r.to_tag,remote_tag:r.from_tag,toString:function(){return this.call_id+this.local_tag+this.remote_tag}},this._state=u,this._remote_seqnum=r.cseq,this._local_uri=r.parseHeader("to").uri,this._remote_uri=r.parseHeader("from").uri,this._remote_target=s.uri,this._route_set=r.getHeaders("record-route"),this._ack_seqnum=this._remote_seqnum):l==="UAC"&&(this._id={call_id:r.call_id,local_tag:r.from_tag,remote_tag:r.to_tag,toString:function(){return this.call_id+this.local_tag+this.remote_tag}},this._state=u,this._local_seqnum=r.cseq,this._local_uri=r.parseHeader("from").uri,this._remote_uri=r.parseHeader("to").uri,this._remote_target=s.uri,this._route_set=r.getHeaders("record-route").reverse(),this._ack_seqnum=null),this._ua.newDialog(this),Ac.debug("new ".concat(l," dialog created with status ").concat(this._state===wi.STATUS_EARLY?"EARLY":"CONFIRMED"))}return xh(f,[{key:"isTerminated",value:function(){return this._status===wi.STATUS_TERMINATED}},{key:"update",value:function(r,l){this._state=wi.STATUS_CONFIRMED,Ac.debug("dialog ".concat(this._id.toString()," changed to CONFIRMED state")),l==="UAC"&&(this._route_set=r.getHeaders("record-route").reverse())}},{key:"terminate",value:function(){Ac.debug("dialog ".concat(this._id.toString()," deleted")),this._ua.destroyDialog(this),this._state=wi.STATUS_TERMINATED}},{key:"sendRequest",value:function(r){var l=this,u=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},s=Cc.cloneArray(u.extraHeaders),n=Cc.cloneObject(u.eventHandlers),g=u.body||null,_=this._createRequest(r,s,g);n.onAuthenticated=function(){l._local_seqnum+=1};var v=new sS(this,_,n);return v.send(),_}},{key:"receiveRequest",value:function(r){this._checkInDialogRequest(r)&&(r.method===bi.ACK&&this._ack_seqnum!==null?this._ack_seqnum=null:r.method===bi.INVITE&&(this._ack_seqnum=r.cseq),this._owner.receiveRequest(r))}},{key:"_createRequest",value:function(r,l,u){l=Cc.cloneArray(l),this._local_seqnum||(this._local_seqnum=Math.floor(Math.random()*1e4));var s=r===bi.CANCEL||r===bi.ACK?this._local_seqnum:this._local_seqnum+=1,n=new Oh.OutgoingRequest(r,this._remote_target,this._ua,{cseq:s,call_id:this._id.call_id,from_uri:this._local_uri,from_tag:this._id.local_tag,to_uri:this._remote_uri,to_tag:this._id.remote_tag,route_set:this._route_set},l,u);return n}},{key:"_checkInDialogRequest",value:function(r){var l=this;if(!this._remote_seqnum)this._remote_seqnum=r.cseq;else if(r.cseq<this._remote_seqnum)if(r.method===bi.ACK){if(this._ack_seqnum===null||r.cseq!==this._ack_seqnum)return!1}else return r.reply(500),!1;else r.cseq>this._remote_seqnum&&(this._remote_seqnum=r.cseq);if(r.method===bi.INVITE||r.method===bi.UPDATE&&r.body){if(this._uac_pending_reply===!0)r.reply(491);else if(this._uas_pending_reply===!0){var u=(Math.random()*10|0)+1;return r.reply(500,null,["Retry-After:".concat(u)]),!1}else{this._uas_pending_reply=!0;var s=function n(){(r.server_transaction.state===Wl.C.STATUS_ACCEPTED||r.server_transaction.state===Wl.C.STATUS_COMPLETED||r.server_transaction.state===Wl.C.STATUS_TERMINATED)&&(r.server_transaction.removeListener("stateChanged",n),l._uas_pending_reply=!1)};r.server_transaction.on("stateChanged",s)}r.hasHeader("contact")&&r.server_transaction.on("stateChanged",function(){r.server_transaction.state===Wl.C.STATUS_ACCEPTED&&(l._remote_target=r.parseHeader("contact").uri)})}else r.method===bi.NOTIFY&&r.hasHeader("contact")&&r.server_transaction.on("stateChanged",function(){r.server_transaction.state===Wl.C.STATUS_COMPLETED&&(l._remote_target=r.parseHeader("contact").uri)});return!0}},{key:"id",get:function(){return this._id}},{key:"local_seqnum",get:function(){return this._local_seqnum},set:function(r){this._local_seqnum=r}},{key:"owner",get:function(){return this._owner}},{key:"uac_pending_reply",get:function(){return this._uac_pending_reply},set:function(r){this._uac_pending_reply=r}},{key:"uas_pending_reply",get:function(){return this._uas_pending_reply}}]),f}(),Ic={exports:{}};function Zo(f){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?Zo=function(r){return typeof r}:Zo=function(r){return r&&typeof Symbol=="function"&&r.constructor===Symbol&&r!==Symbol.prototype?"symbol":typeof r},Zo(f)}function nS(f,t){if(!(f instanceof t))throw new TypeError("Cannot call a class as a function")}function Dh(f,t){for(var r=0;r<t.length;r++){var l=t[r];l.enumerable=l.enumerable||!1,l.configurable=!0,"value"in l&&(l.writable=!0),Object.defineProperty(f,l.key,l)}}function iS(f,t,r){return t&&Dh(f.prototype,t),r&&Dh(f,r),f}function aS(f,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");f.prototype=Object.create(t&&t.prototype,{constructor:{value:f,writable:!0,configurable:!0}}),t&&Rc(f,t)}function Rc(f,t){return Rc=Object.setPrototypeOf||function(l,u){return l.__proto__=u,l},Rc(f,t)}function lS(f){var t=cS();return function(){var l=eu(f),u;if(t){var s=eu(this).constructor;u=Reflect.construct(l,arguments,s)}else u=l.apply(this,arguments);return oS(this,u)}}function oS(f,t){return t&&(Zo(t)==="object"||typeof t=="function")?t:uS(f)}function uS(f){if(f===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return f}function cS(){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 eu(f){return eu=Object.setPrototypeOf?Object.getPrototypeOf:function(r){return r.__proto__||Object.getPrototypeOf(r)},eu(f)}var dS=ys.EventEmitter,fS=Ts,hS=hs,_S=yi,kh=Bs(),pS=new fS("RTCSession:DTMF"),Nh={MIN_DURATION:70,MAX_DURATION:6e3,DEFAULT_DURATION:100,MIN_INTER_TONE_GAP:50,DEFAULT_INTER_TONE_GAP:500};Ic.exports=function(f){aS(r,f);var t=lS(r);function r(l){var u;return nS(this,r),u=t.call(this),u._session=l,u._direction=null,u._tone=null,u._duration=null,u._request=null,u}return iS(r,[{key:"send",value:function(u){var s=this,n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(u===void 0)throw new TypeError("Not enough arguments");if(this._direction="outgoing",this._session.status!==this._session.C.STATUS_CONFIRMED&&this._session.status!==this._session.C.STATUS_WAITING_FOR_ACK)throw new _S.InvalidStateError(this._session.status);var g=kh.cloneArray(n.extraHeaders);if(this.eventHandlers=kh.cloneObject(n.eventHandlers),typeof u=="string")u=u.toUpperCase();else if(typeof u=="number")u=u.toString();else throw new TypeError("Invalid tone: ".concat(u));if(u.match(/^[0-9A-DR#*]$/))this._tone=u;else throw new TypeError("Invalid tone: ".concat(u));this._duration=n.duration,g.push("Content-Type: application/dtmf-relay");var _="Signal=".concat(this._tone,`\r
47
47
  `);_+="Duration=".concat(this._duration),this._session.newDTMF({originator:"local",dtmf:this,request:this._request}),this._session.sendRequest(hS.INFO,{extraHeaders:g,eventHandlers:{onSuccessResponse:function(C){s.emit("succeeded",{originator:"remote",response:C})},onErrorResponse:function(C){s.eventHandlers.onFailed&&s.eventHandlers.onFailed(),s.emit("failed",{originator:"remote",response:C})},onRequestTimeout:function(){s._session.onRequestTimeout()},onTransportError:function(){s._session.onTransportError()},onDialogError:function(){s._session.onDialogError()}},body:_})}},{key:"init_incoming",value:function(u){var s=/^(Signal\s*?=\s*?)([0-9A-D#*]{1})(\s)?.*/,n=/^(Duration\s?=\s?)([0-9]{1,4})(\s)?.*/;if(this._direction="incoming",this._request=u,u.reply(200),u.body){var g=u.body.split(`
48
- `);g.length>=1&&s.test(g[0])&&(this._tone=g[0].replace(s,"$2")),g.length>=2&&n.test(g[1])&&(this._duration=parseInt(g[1].replace(n,"$2"),10))}this._duration||(this._duration=Mh.DEFAULT_DURATION),this._tone?this._session.newDTMF({originator:"remote",dtmf:this,request:u}):pS.debug("invalid INFO DTMF received, discarded")}},{key:"tone",get:function(){return this._tone}},{key:"duration",get:function(){return this._duration}}]),r}(dS),Ic.exports.C=Mh;var mS=Ic.exports;function tu(f){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?tu=function(r){return typeof r}:tu=function(r){return r&&typeof Symbol=="function"&&r.constructor===Symbol&&r!==Symbol.prototype?"symbol":typeof r},tu(f)}function gS(f,t){if(!(f instanceof t))throw new TypeError("Cannot call a class as a function")}function Uh(f,t){for(var r=0;r<t.length;r++){var l=t[r];l.enumerable=l.enumerable||!1,l.configurable=!0,"value"in l&&(l.writable=!0),Object.defineProperty(f,l.key,l)}}function vS(f,t,r){return t&&Uh(f.prototype,t),r&&Uh(f,r),f}function yS(f,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");f.prototype=Object.create(t&&t.prototype,{constructor:{value:f,writable:!0,configurable:!0}}),t&&$c(f,t)}function $c(f,t){return $c=Object.setPrototypeOf||function(l,u){return l.__proto__=u,l},$c(f,t)}function TS(f){var t=wS();return function(){var l=su(f),u;if(t){var s=su(this).constructor;u=Reflect.construct(l,arguments,s)}else u=l.apply(this,arguments);return SS(this,u)}}function SS(f,t){return t&&(tu(t)==="object"||typeof t=="function")?t:bS(f)}function bS(f){if(f===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return f}function wS(){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 su(f){return su=Object.setPrototypeOf?Object.getPrototypeOf:function(r){return r.__proto__||Object.getPrototypeOf(r)},su(f)}var ES=ys.EventEmitter,CS=hs,AS=yi,IS=Bs(),RS=function(f){yS(r,f);var t=TS(r);function r(l){var u;return gS(this,r),u=t.call(this),u._session=l,u._direction=null,u._contentType=null,u._body=null,u}return vS(r,[{key:"send",value:function(u,s){var n=this,g=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};if(this._direction="outgoing",u===void 0)throw new TypeError("Not enough arguments");if(this._session.status!==this._session.C.STATUS_CONFIRMED&&this._session.status!==this._session.C.STATUS_WAITING_FOR_ACK)throw new AS.InvalidStateError(this._session.status);this._contentType=u,this._body=s;var _=IS.cloneArray(g.extraHeaders);_.push("Content-Type: ".concat(u)),this._session.newInfo({originator:"local",info:this,request:this.request}),this._session.sendRequest(CS.INFO,{extraHeaders:_,eventHandlers:{onSuccessResponse:function(C){n.emit("succeeded",{originator:"remote",response:C})},onErrorResponse:function(C){n.emit("failed",{originator:"remote",response:C})},onTransportError:function(){n._session.onTransportError()},onRequestTimeout:function(){n._session.onRequestTimeout()},onDialogError:function(){n._session.onDialogError()}},body:s})}},{key:"init_incoming",value:function(u){this._direction="incoming",this.request=u,u.reply(200),this._contentType=u.hasHeader("Content-Type")?u.getHeader("Content-Type").toLowerCase():void 0,this._body=u.body,this._session.newInfo({originator:"remote",info:this,request:u})}},{key:"contentType",get:function(){return this._contentType}},{key:"body",get:function(){return this._body}}]),r}(ES);function $S(f,t){if(!(f instanceof t))throw new TypeError("Cannot call a class as a function")}function Ph(f,t){for(var r=0;r<t.length;r++){var l=t[r];l.enumerable=l.enumerable||!1,l.configurable=!0,"value"in l&&(l.writable=!0),Object.defineProperty(f,l.key,l)}}function xS(f,t,r){return t&&Ph(f.prototype,t),r&&Ph(f,r),f}var OS=Ts,Lh=hs,DS=new OS("RTCSession:ReferNotifier"),xc={event_type:"refer",body_type:"message/sipfrag;version=2.0",expires:300},kS=function(){function f(t,r,l){$S(this,f),this._session=t,this._id=r,this._expires=l||xc.expires,this._active=!0,this.notify(100)}return xS(f,[{key:"notify",value:function(r,l){if(DS.debug("notify()"),this._active!==!1){l=l||Lh.REASON_PHRASE[r]||"";var u;r>=200?u="terminated;reason=noresource":u="active;expires=".concat(this._expires),this._session.sendRequest(Lh.NOTIFY,{extraHeaders:["Event: ".concat(xc.event_type,";id=").concat(this._id),"Subscription-State: ".concat(u),"Content-Type: ".concat(xc.body_type)],body:"SIP/2.0 ".concat(r," ").concat(l),eventHandlers:{onErrorResponse:function(){this._active=!1}}})}}}]),f}();function ru(f){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?ru=function(r){return typeof r}:ru=function(r){return r&&typeof Symbol=="function"&&r.constructor===Symbol&&r!==Symbol.prototype?"symbol":typeof r},ru(f)}function NS(f,t){if(!(f instanceof t))throw new TypeError("Cannot call a class as a function")}function Hh(f,t){for(var r=0;r<t.length;r++){var l=t[r];l.enumerable=l.enumerable||!1,l.configurable=!0,"value"in l&&(l.writable=!0),Object.defineProperty(f,l.key,l)}}function MS(f,t,r){return t&&Hh(f.prototype,t),r&&Hh(f,r),f}function US(f,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");f.prototype=Object.create(t&&t.prototype,{constructor:{value:f,writable:!0,configurable:!0}}),t&&Oc(f,t)}function Oc(f,t){return Oc=Object.setPrototypeOf||function(l,u){return l.__proto__=u,l},Oc(f,t)}function PS(f){var t=FS();return function(){var l=nu(f),u;if(t){var s=nu(this).constructor;u=Reflect.construct(l,arguments,s)}else u=l.apply(this,arguments);return LS(this,u)}}function LS(f,t){return t&&(ru(t)==="object"||typeof t=="function")?t:HS(f)}function HS(f){if(f===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return f}function FS(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],function(){})),!0}catch{return!1}}function nu(f){return nu=Object.setPrototypeOf?Object.getPrototypeOf:function(r){return r.__proto__||Object.getPrototypeOf(r)},nu(f)}var BS=ys.EventEmitter,zS=Ts,Kl=hs,VS=on(),Fh=Bs(),Ta=new zS("RTCSession:ReferSubscriber"),qS=function(f){US(r,f);var t=PS(r);function r(l){var u;return NS(this,r),u=t.call(this),u._id=null,u._session=l,u}return MS(r,[{key:"sendRefer",value:function(u){var s=this,n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};Ta.debug("sendRefer()");var g=Fh.cloneArray(n.extraHeaders),_=Fh.cloneObject(n.eventHandlers);for(var v in _)Object.prototype.hasOwnProperty.call(_,v)&&this.on(v,_[v]);var C=null;n.replaces&&(C=n.replaces._request.call_id,C+=";to-tag=".concat(n.replaces._to_tag),C+=";from-tag=".concat(n.replaces._from_tag),C=encodeURIComponent(C));var R="Refer-To: <".concat(u).concat(C?"?Replaces=".concat(C):"",">");if(g.push(R),!g.some(function(F){return F.toLowerCase().startsWith("referred-by:")})){var D="Referred-By: <".concat(this._session._ua._configuration.uri._scheme,":").concat(this._session._ua._configuration.uri._user,"@").concat(this._session._ua._configuration.uri._host,">");g.push(D)}g.push("Contact: ".concat(this._session.contact));var H=this._session.sendRequest(Kl.REFER,{extraHeaders:g,eventHandlers:{onSuccessResponse:function(q){s._requestSucceeded(q)},onErrorResponse:function(q){s._requestFailed(q,Kl.causes.REJECTED)},onTransportError:function(){s._requestFailed(null,Kl.causes.CONNECTION_ERROR)},onRequestTimeout:function(){s._requestFailed(null,Kl.causes.REQUEST_TIMEOUT)},onDialogError:function(){s._requestFailed(null,Kl.causes.DIALOG_ERROR)}}});this._id=H.cseq}},{key:"receiveNotify",value:function(u){if(Ta.debug("receiveNotify()"),!!u.body){var s=VS.parse(u.body.trim().split(`\r
48
+ `);g.length>=1&&s.test(g[0])&&(this._tone=g[0].replace(s,"$2")),g.length>=2&&n.test(g[1])&&(this._duration=parseInt(g[1].replace(n,"$2"),10))}this._duration||(this._duration=Nh.DEFAULT_DURATION),this._tone?this._session.newDTMF({originator:"remote",dtmf:this,request:u}):pS.debug("invalid INFO DTMF received, discarded")}},{key:"tone",get:function(){return this._tone}},{key:"duration",get:function(){return this._duration}}]),r}(dS),Ic.exports.C=Nh;var mS=Ic.exports;function tu(f){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?tu=function(r){return typeof r}:tu=function(r){return r&&typeof Symbol=="function"&&r.constructor===Symbol&&r!==Symbol.prototype?"symbol":typeof r},tu(f)}function gS(f,t){if(!(f instanceof t))throw new TypeError("Cannot call a class as a function")}function Mh(f,t){for(var r=0;r<t.length;r++){var l=t[r];l.enumerable=l.enumerable||!1,l.configurable=!0,"value"in l&&(l.writable=!0),Object.defineProperty(f,l.key,l)}}function vS(f,t,r){return t&&Mh(f.prototype,t),r&&Mh(f,r),f}function yS(f,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");f.prototype=Object.create(t&&t.prototype,{constructor:{value:f,writable:!0,configurable:!0}}),t&&$c(f,t)}function $c(f,t){return $c=Object.setPrototypeOf||function(l,u){return l.__proto__=u,l},$c(f,t)}function TS(f){var t=wS();return function(){var l=su(f),u;if(t){var s=su(this).constructor;u=Reflect.construct(l,arguments,s)}else u=l.apply(this,arguments);return SS(this,u)}}function SS(f,t){return t&&(tu(t)==="object"||typeof t=="function")?t:bS(f)}function bS(f){if(f===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return f}function wS(){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 su(f){return su=Object.setPrototypeOf?Object.getPrototypeOf:function(r){return r.__proto__||Object.getPrototypeOf(r)},su(f)}var ES=ys.EventEmitter,CS=hs,AS=yi,IS=Bs(),RS=function(f){yS(r,f);var t=TS(r);function r(l){var u;return gS(this,r),u=t.call(this),u._session=l,u._direction=null,u._contentType=null,u._body=null,u}return vS(r,[{key:"send",value:function(u,s){var n=this,g=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};if(this._direction="outgoing",u===void 0)throw new TypeError("Not enough arguments");if(this._session.status!==this._session.C.STATUS_CONFIRMED&&this._session.status!==this._session.C.STATUS_WAITING_FOR_ACK)throw new AS.InvalidStateError(this._session.status);this._contentType=u,this._body=s;var _=IS.cloneArray(g.extraHeaders);_.push("Content-Type: ".concat(u)),this._session.newInfo({originator:"local",info:this,request:this.request}),this._session.sendRequest(CS.INFO,{extraHeaders:_,eventHandlers:{onSuccessResponse:function(C){n.emit("succeeded",{originator:"remote",response:C})},onErrorResponse:function(C){n.emit("failed",{originator:"remote",response:C})},onTransportError:function(){n._session.onTransportError()},onRequestTimeout:function(){n._session.onRequestTimeout()},onDialogError:function(){n._session.onDialogError()}},body:s})}},{key:"init_incoming",value:function(u){this._direction="incoming",this.request=u,u.reply(200),this._contentType=u.hasHeader("Content-Type")?u.getHeader("Content-Type").toLowerCase():void 0,this._body=u.body,this._session.newInfo({originator:"remote",info:this,request:u})}},{key:"contentType",get:function(){return this._contentType}},{key:"body",get:function(){return this._body}}]),r}(ES);function $S(f,t){if(!(f instanceof t))throw new TypeError("Cannot call a class as a function")}function Uh(f,t){for(var r=0;r<t.length;r++){var l=t[r];l.enumerable=l.enumerable||!1,l.configurable=!0,"value"in l&&(l.writable=!0),Object.defineProperty(f,l.key,l)}}function xS(f,t,r){return t&&Uh(f.prototype,t),r&&Uh(f,r),f}var OS=Ts,Ph=hs,DS=new OS("RTCSession:ReferNotifier"),xc={event_type:"refer",body_type:"message/sipfrag;version=2.0",expires:300},kS=function(){function f(t,r,l){$S(this,f),this._session=t,this._id=r,this._expires=l||xc.expires,this._active=!0,this.notify(100)}return xS(f,[{key:"notify",value:function(r,l){if(DS.debug("notify()"),this._active!==!1){l=l||Ph.REASON_PHRASE[r]||"";var u;r>=200?u="terminated;reason=noresource":u="active;expires=".concat(this._expires),this._session.sendRequest(Ph.NOTIFY,{extraHeaders:["Event: ".concat(xc.event_type,";id=").concat(this._id),"Subscription-State: ".concat(u),"Content-Type: ".concat(xc.body_type)],body:"SIP/2.0 ".concat(r," ").concat(l),eventHandlers:{onErrorResponse:function(){this._active=!1}}})}}}]),f}();function ru(f){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?ru=function(r){return typeof r}:ru=function(r){return r&&typeof Symbol=="function"&&r.constructor===Symbol&&r!==Symbol.prototype?"symbol":typeof r},ru(f)}function NS(f,t){if(!(f instanceof t))throw new TypeError("Cannot call a class as a function")}function Lh(f,t){for(var r=0;r<t.length;r++){var l=t[r];l.enumerable=l.enumerable||!1,l.configurable=!0,"value"in l&&(l.writable=!0),Object.defineProperty(f,l.key,l)}}function MS(f,t,r){return t&&Lh(f.prototype,t),r&&Lh(f,r),f}function US(f,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");f.prototype=Object.create(t&&t.prototype,{constructor:{value:f,writable:!0,configurable:!0}}),t&&Oc(f,t)}function Oc(f,t){return Oc=Object.setPrototypeOf||function(l,u){return l.__proto__=u,l},Oc(f,t)}function PS(f){var t=FS();return function(){var l=nu(f),u;if(t){var s=nu(this).constructor;u=Reflect.construct(l,arguments,s)}else u=l.apply(this,arguments);return LS(this,u)}}function LS(f,t){return t&&(ru(t)==="object"||typeof t=="function")?t:HS(f)}function HS(f){if(f===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return f}function FS(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],function(){})),!0}catch{return!1}}function nu(f){return nu=Object.setPrototypeOf?Object.getPrototypeOf:function(r){return r.__proto__||Object.getPrototypeOf(r)},nu(f)}var BS=ys.EventEmitter,zS=Ts,Kl=hs,VS=on(),Hh=Bs(),Ta=new zS("RTCSession:ReferSubscriber"),qS=function(f){US(r,f);var t=PS(r);function r(l){var u;return NS(this,r),u=t.call(this),u._id=null,u._session=l,u}return MS(r,[{key:"sendRefer",value:function(u){var s=this,n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};Ta.debug("sendRefer()");var g=Hh.cloneArray(n.extraHeaders),_=Hh.cloneObject(n.eventHandlers);for(var v in _)Object.prototype.hasOwnProperty.call(_,v)&&this.on(v,_[v]);var C=null;n.replaces&&(C=n.replaces._request.call_id,C+=";to-tag=".concat(n.replaces._to_tag),C+=";from-tag=".concat(n.replaces._from_tag),C=encodeURIComponent(C));var R="Refer-To: <".concat(u).concat(C?"?Replaces=".concat(C):"",">");if(g.push(R),!g.some(function(F){return F.toLowerCase().startsWith("referred-by:")})){var D="Referred-By: <".concat(this._session._ua._configuration.uri._scheme,":").concat(this._session._ua._configuration.uri._user,"@").concat(this._session._ua._configuration.uri._host,">");g.push(D)}g.push("Contact: ".concat(this._session.contact));var H=this._session.sendRequest(Kl.REFER,{extraHeaders:g,eventHandlers:{onSuccessResponse:function(q){s._requestSucceeded(q)},onErrorResponse:function(q){s._requestFailed(q,Kl.causes.REJECTED)},onTransportError:function(){s._requestFailed(null,Kl.causes.CONNECTION_ERROR)},onRequestTimeout:function(){s._requestFailed(null,Kl.causes.REQUEST_TIMEOUT)},onDialogError:function(){s._requestFailed(null,Kl.causes.DIALOG_ERROR)}}});this._id=H.cseq}},{key:"receiveNotify",value:function(u){if(Ta.debug("receiveNotify()"),!!u.body){var s=VS.parse(u.body.trim().split(`\r
49
49
  `,1)[0],"Status_Line");if(s===-1){Ta.debug('receiveNotify() | error parsing NOTIFY body: "'.concat(u.body,'"'));return}switch(!0){case/^100$/.test(s.status_code):this.emit("trying",{request:u,status_line:s});break;case/^1[0-9]{2}$/.test(s.status_code):this.emit("progress",{request:u,status_line:s});break;case/^2[0-9]{2}$/.test(s.status_code):this.emit("accepted",{request:u,status_line:s});break;default:this.emit("failed",{request:u,status_line:s});break}}}},{key:"_requestSucceeded",value:function(u){Ta.debug("REFER succeeded"),Ta.debug('emit "requestSucceeded"'),this.emit("requestSucceeded",{response:u})}},{key:"_requestFailed",value:function(u,s){Ta.debug("REFER failed"),Ta.debug('emit "requestFailed"'),this.emit("requestFailed",{response:u||null,cause:s})}},{key:"id",get:function(){return this._id}}]),r}(BS);function iu(f){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?iu=function(r){return typeof r}:iu=function(r){return r&&typeof Symbol=="function"&&r.constructor===Symbol&&r!==Symbol.prototype?"symbol":typeof r},iu(f)}function kn(f,t){var r;if(typeof Symbol>"u"||f[Symbol.iterator]==null){if(Array.isArray(f)||(r=jS(f))||t&&f&&typeof f.length=="number"){r&&(f=r);var l=0,u=function(){};return{s:u,n:function(){return l>=f.length?{done:!0}:{done:!1,value:f[l++]}},e:function(v){throw v},f:u}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
50
- In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var s=!0,n=!1,g;return{s:function(){r=f[Symbol.iterator]()},n:function(){var v=r.next();return s=v.done,v},e:function(v){n=!0,g=v},f:function(){try{!s&&r.return!=null&&r.return()}finally{if(n)throw g}}}}function jS(f,t){if(f){if(typeof f=="string")return Bh(f,t);var r=Object.prototype.toString.call(f).slice(8,-1);if(r==="Object"&&f.constructor&&(r=f.constructor.name),r==="Map"||r==="Set")return Array.from(f);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return Bh(f,t)}}function Bh(f,t){(t==null||t>f.length)&&(t=f.length);for(var r=0,l=new Array(t);r<t;r++)l[r]=f[r];return l}function GS(f,t){if(!(f instanceof t))throw new TypeError("Cannot call a class as a function")}function zh(f,t){for(var r=0;r<t.length;r++){var l=t[r];l.enumerable=l.enumerable||!1,l.configurable=!0,"value"in l&&(l.writable=!0),Object.defineProperty(f,l.key,l)}}function Vh(f,t,r){return t&&zh(f.prototype,t),r&&zh(f,r),f}function WS(f,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");f.prototype=Object.create(t&&t.prototype,{constructor:{value:f,writable:!0,configurable:!0}}),t&&Dc(f,t)}function Dc(f,t){return Dc=Object.setPrototypeOf||function(l,u){return l.__proto__=u,l},Dc(f,t)}function KS(f){var t=QS();return function(){var l=au(f),u;if(t){var s=au(this).constructor;u=Reflect.construct(l,arguments,s)}else u=l.apply(this,arguments);return YS(this,u)}}function YS(f,t){return t&&(iu(t)==="object"||typeof t=="function")?t:JS(f)}function JS(f){if(f===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return f}function QS(){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 au(f){return au=Object.setPrototypeOf?Object.getPrototypeOf:function(r){return r.__proto__||Object.getPrototypeOf(r)},au(f)}var XS=ys.EventEmitter,qh=sr,ZS=Ts,Ge=hs,Sa=yi,jh=ql,Qt=Bs(),Yl=yh,eb=xn,lu=rS,tb=jl,hr=mS,Gh=RS,sb=kS,rb=qS,Wh=Ti(),Ee=new ZS("RTCSession"),$e={STATUS_NULL:0,STATUS_INVITE_SENT:1,STATUS_1XX_RECEIVED:2,STATUS_INVITE_RECEIVED:3,STATUS_WAITING_FOR_ANSWER:4,STATUS_ANSWERED:5,STATUS_WAITING_FOR_ACK:6,STATUS_CANCELED:7,STATUS_TERMINATED:8,STATUS_CONFIRMED:9},ou=["audio","video"],nb=function(f){WS(r,f);var t=KS(r);Vh(r,null,[{key:"C",get:function(){return $e}}]);function r(l){var u;return GS(this,r),Ee.debug("new"),u=t.call(this),u._id=null,u._ua=l,u._status=$e.STATUS_NULL,u._dialog=null,u._earlyDialogs={},u._contact=null,u._from_tag=null,u._to_tag=null,u._connection=null,u._connectionPromiseQueue=Promise.resolve(),u._request=null,u._is_canceled=!1,u._cancel_reason="",u._is_confirmed=!1,u._late_sdp=!1,u._rtcOfferConstraints=null,u._rtcAnswerConstraints=null,u._localMediaStream=null,u._localMediaStreamLocallyGenerated=!1,u._rtcReady=!0,u._iceReady=!1,u._timers={ackTimer:null,expiresTimer:null,invite2xxTimer:null,userNoAnswerTimer:null},u._direction=null,u._local_identity=null,u._remote_identity=null,u._start_time=null,u._end_time=null,u._tones=null,u._audioMuted=!1,u._videoMuted=!1,u._localHold=!1,u._remoteHold=!1,u._sessionTimers={enabled:u._ua.configuration.session_timers,refreshMethod:u._ua.configuration.session_timers_refresh_method,defaultExpires:Ge.SESSION_EXPIRES,currentExpires:null,running:!1,refresher:!1,timer:null},u._referSubscribers={},u._data={},u}return Vh(r,[{key:"isInProgress",value:function(){switch(this._status){case $e.STATUS_NULL:case $e.STATUS_INVITE_SENT:case $e.STATUS_1XX_RECEIVED:case $e.STATUS_INVITE_RECEIVED:case $e.STATUS_WAITING_FOR_ANSWER:return!0;default:return!1}}},{key:"isEstablished",value:function(){switch(this._status){case $e.STATUS_ANSWERED:case $e.STATUS_WAITING_FOR_ACK:case $e.STATUS_CONFIRMED:return!0;default:return!1}}},{key:"isEnded",value:function(){switch(this._status){case $e.STATUS_CANCELED:case $e.STATUS_TERMINATED:return!0;default:return!1}}},{key:"isMuted",value:function(){return{audio:this._audioMuted,video:this._videoMuted}}},{key:"isOnHold",value:function(){return{local:this._localHold,remote:this._remoteHold}}},{key:"connect",value:function(u){var s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},n=arguments.length>2?arguments[2]:void 0;Ee.debug("connect()");var g=u,_=Qt.cloneObject(s.eventHandlers),v=Qt.cloneArray(s.extraHeaders),C=Qt.cloneObject(s.mediaConstraints,{audio:!0,video:!0}),R=s.mediaStream||null,D=Qt.cloneObject(s.pcConfig,{iceServers:[]}),H=s.rtcConstraints||null,F=s.rtcOfferConstraints||null;if(this._rtcOfferConstraints=F,this._rtcAnswerConstraints=s.rtcAnswerConstraints||null,this._data=s.data||this._data,u===void 0)throw new TypeError("Not enough arguments");if(this._status!==$e.STATUS_NULL)throw new Sa.InvalidStateError(this._status);if(!window.RTCPeerConnection)throw new Sa.NotSupportedError("WebRTC not supported");if(u=this._ua.normalizeTarget(u),!u)throw new TypeError("Invalid target: ".concat(g));this._sessionTimers.enabled&&Qt.isDecimal(s.sessionTimersExpires)&&(s.sessionTimersExpires>=Ge.MIN_SESSION_EXPIRES?this._sessionTimers.defaultExpires=s.sessionTimersExpires:this._sessionTimers.defaultExpires=Ge.SESSION_EXPIRES);for(var q in _)Object.prototype.hasOwnProperty.call(_,q)&&this.on(q,_[q]);this._from_tag=Qt.newTag();var G=s.anonymous||!1,te={from_tag:this._from_tag};this._contact=this._ua.contact.toString({anonymous:G,outbound:!0}),G?(te.from_display_name="Anonymous",te.from_uri=new Wh("sip","anonymous","anonymous.invalid"),v.push("P-Preferred-Identity: ".concat(this._ua.configuration.uri.toString())),v.push("Privacy: id")):s.fromUserName&&(te.from_uri=new Wh("sip",s.fromUserName,this._ua.configuration.uri.host),v.push("P-Preferred-Identity: ".concat(this._ua.configuration.uri.toString()))),s.fromDisplayName&&(te.from_display_name=s.fromDisplayName),v.push("Contact: ".concat(this._contact)),v.push("Content-Type: application/sdp"),this._sessionTimers.enabled&&v.push("Session-Expires: ".concat(this._sessionTimers.defaultExpires).concat(this._ua.configuration.session_timers_force_refresher?";refresher=uac":"")),this._request=new eb.InitialOutgoingInviteRequest(u,this._ua,te,v),this._id=this._request.call_id+this._from_tag,this._createRTCConnection(D,H),this._direction="outgoing",this._local_identity=this._request.from,this._remote_identity=this._request.to,n&&n(this),this._newRTCSession("local",this._request),this._sendInitialRequest(C,F,R)}},{key:"init_incoming",value:function(u,s){var n=this;Ee.debug("init_incoming()");var g,_=u.hasHeader("Content-Type")?u.getHeader("Content-Type").toLowerCase():void 0;if(u.body&&_!=="application/sdp"){u.reply(415);return}if(this._status=$e.STATUS_INVITE_RECEIVED,this._from_tag=u.from_tag,this._id=u.call_id+this._from_tag,this._request=u,this._contact=this._ua.contact.toString(),u.hasHeader("expires")&&(g=u.getHeader("expires")*1e3),u.to_tag=Qt.newTag(),!this._createDialog(u,"UAS",!0)){u.reply(500,"Missing Contact header field");return}u.body?this._late_sdp=!1:this._late_sdp=!0,this._status=$e.STATUS_WAITING_FOR_ANSWER,this._timers.userNoAnswerTimer=setTimeout(function(){u.reply(408),n._failed("local",null,Ge.causes.NO_ANSWER)},this._ua.configuration.no_answer_timeout),g&&(this._timers.expiresTimer=setTimeout(function(){n._status===$e.STATUS_WAITING_FOR_ANSWER&&(u.reply(487),n._failed("system",null,Ge.causes.EXPIRES))},g)),this._direction="incoming",this._local_identity=u.to,this._remote_identity=u.from,s&&s(this),this._newRTCSession("remote",u),this._status!==$e.STATUS_TERMINATED&&(u.reply(180,null,["Contact: ".concat(this._contact)]),this._progress("local",null))}},{key:"answer",value:function(){var u=this,s=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Ee.debug("answer()");var n=this._request,g=Qt.cloneArray(s.extraHeaders),_=Qt.cloneObject(s.mediaConstraints),v=s.mediaStream||null,C=Qt.cloneObject(s.pcConfig,{iceServers:[]}),R=s.rtcConstraints||null,D=s.rtcAnswerConstraints||null,H=Qt.cloneObject(s.rtcOfferConstraints),F,q=!1,G=!1,te=!1,X=!1;if(this._rtcAnswerConstraints=D,this._rtcOfferConstraints=s.rtcOfferConstraints||null,this._data=s.data||this._data,this._direction!=="incoming")throw new Sa.NotSupportedError('"answer" not supported for outgoing RTCSession');if(this._status!==$e.STATUS_WAITING_FOR_ANSWER)throw new Sa.InvalidStateError(this._status);if(this._sessionTimers.enabled&&Qt.isDecimal(s.sessionTimersExpires)&&(s.sessionTimersExpires>=Ge.MIN_SESSION_EXPIRES?this._sessionTimers.defaultExpires=s.sessionTimersExpires:this._sessionTimers.defaultExpires=Ge.SESSION_EXPIRES),this._status=$e.STATUS_ANSWERED,!this._createDialog(n,"UAS")){n.reply(500,"Error creating dialog");return}clearTimeout(this._timers.userNoAnswerTimer),g.unshift("Contact: ".concat(this._contact));var we=n.parseSDP();Array.isArray(we.media)||(we.media=[we.media]);var Q=kn(we.media),re;try{for(Q.s();!(re=Q.n()).done;){var ke=re.value;ke.type==="audio"&&(q=!0,(!ke.direction||ke.direction==="sendrecv")&&(te=!0)),ke.type==="video"&&(G=!0,(!ke.direction||ke.direction==="sendrecv")&&(X=!0))}}catch(_e){Q.e(_e)}finally{Q.f()}if(v&&_.audio===!1){F=v.getAudioTracks();var Ne=kn(F),Z;try{for(Ne.s();!(Z=Ne.n()).done;){var se=Z.value;v.removeTrack(se)}}catch(_e){Ne.e(_e)}finally{Ne.f()}}if(v&&_.video===!1){F=v.getVideoTracks();var pe=kn(F),me;try{for(pe.s();!(me=pe.n()).done;){var be=me.value;v.removeTrack(be)}}catch(_e){pe.e(_e)}finally{pe.f()}}!v&&_.audio===void 0&&(_.audio=te),!v&&_.video===void 0&&(_.video=X),!v&&!q&&!H.offerToReceiveAudio&&(_.audio=!1),!v&&!G&&!H.offerToReceiveVideo&&(_.video=!1),this._createRTCConnection(C,R),Promise.resolve().then(function(){if(v)return v;if(_.audio||_.video)return u._localMediaStreamLocallyGenerated=!0,navigator.mediaDevices.getUserMedia(_).catch(function(_e){throw u._status===$e.STATUS_TERMINATED?new Error("terminated"):(n.reply(480),u._failed("local",null,Ge.causes.USER_DENIED_MEDIA_ACCESS),Ee.warn('emit "getusermediafailed" [error:%o]',_e),u.emit("getusermediafailed",_e),new Error("getUserMedia() failed"))})}).then(function(_e){if(u._status===$e.STATUS_TERMINATED)throw new Error("terminated");u._localMediaStream=_e,_e&&_e.getTracks().forEach(function(Ae){u._connection.addTrack(Ae,_e)})}).then(function(){if(!u._late_sdp){var _e={originator:"remote",type:"offer",sdp:n.body};Ee.debug('emit "sdp"'),u.emit("sdp",_e);var Ae=new RTCSessionDescription({type:"offer",sdp:_e.sdp});return u._connectionPromiseQueue=u._connectionPromiseQueue.then(function(){return u._connection.setRemoteDescription(Ae)}).catch(function(le){throw n.reply(488),u._failed("system",null,Ge.causes.WEBRTC_ERROR),Ee.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',le),u.emit("peerconnection:setremotedescriptionfailed",le),new Error("peerconnection.setRemoteDescription() failed")}),u._connectionPromiseQueue}}).then(function(){if(u._status===$e.STATUS_TERMINATED)throw new Error("terminated");return u._connecting(n),u._late_sdp?u._createLocalDescription("offer",u._rtcOfferConstraints).catch(function(){throw n.reply(500),new Error("_createLocalDescription() failed")}):u._createLocalDescription("answer",D).catch(function(){throw n.reply(500),new Error("_createLocalDescription() failed")})}).then(function(_e){if(u._status===$e.STATUS_TERMINATED)throw new Error("terminated");u._handleSessionTimersInIncomingRequest(n,g),n.reply(200,null,g,_e,function(){u._status=$e.STATUS_WAITING_FOR_ACK,u._setInvite2xxTimer(n,_e),u._setACKTimer(),u._accepted("local")},function(){u._failed("system",null,Ge.causes.CONNECTION_ERROR)})}).catch(function(_e){u._status!==$e.STATUS_TERMINATED&&Ee.warn(_e)})}},{key:"terminate",value:function(){var u=this,s=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Ee.debug("terminate()");var n=s.cause||Ge.causes.BYE,g=Qt.cloneArray(s.extraHeaders),_=s.body,v,C=s.status_code,R=s.reason_phrase;if(this._status===$e.STATUS_TERMINATED)throw new Sa.InvalidStateError(this._status);switch(this._status){case $e.STATUS_NULL:case $e.STATUS_INVITE_SENT:case $e.STATUS_1XX_RECEIVED:if(Ee.debug("canceling session"),C&&(C<200||C>=700))throw new TypeError("Invalid status_code: ".concat(C));C&&(R=R||Ge.REASON_PHRASE[C]||"",v="SIP ;cause=".concat(C,' ;text="').concat(R,'"')),this._status===$e.STATUS_NULL||this._status===$e.STATUS_INVITE_SENT?(this._is_canceled=!0,this._cancel_reason=v):this._status===$e.STATUS_1XX_RECEIVED&&this._request.cancel(v),this._status=$e.STATUS_CANCELED,this._failed("local",null,Ge.causes.CANCELED);break;case $e.STATUS_WAITING_FOR_ANSWER:case $e.STATUS_ANSWERED:if(Ee.debug("rejecting session"),C=C||480,C<300||C>=700)throw new TypeError("Invalid status_code: ".concat(C));this._request.reply(C,R,g,_),this._failed("local",null,Ge.causes.REJECTED);break;case $e.STATUS_WAITING_FOR_ACK:case $e.STATUS_CONFIRMED:if(Ee.debug("terminating session"),R=s.reason_phrase||Ge.REASON_PHRASE[C]||"",C&&(C<200||C>=700))throw new TypeError("Invalid status_code: ".concat(C));if(C&&g.push("Reason: SIP ;cause=".concat(C,'; text="').concat(R,'"')),this._status===$e.STATUS_WAITING_FOR_ACK&&this._direction==="incoming"&&this._request.server_transaction.state!==jh.C.STATUS_TERMINATED){var D=this._dialog;this.receiveRequest=function(H){var F=H.method;F===Ge.ACK&&(u.sendRequest(Ge.BYE,{extraHeaders:g,body:_}),D.terminate())},this._request.server_transaction.on("stateChanged",function(){u._request.server_transaction.state===jh.C.STATUS_TERMINATED&&(u.sendRequest(Ge.BYE,{extraHeaders:g,body:_}),D.terminate())}),this._ended("local",null,n),this._dialog=D,this._ua.newDialog(D)}else this.sendRequest(Ge.BYE,{extraHeaders:g,body:_}),this._ended("local",null,n)}}},{key:"sendDTMF",value:function(u){var s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};Ee.debug("sendDTMF() | tones: %s",u);var n=0,g=s.duration||null,_=s.interToneGap||null,v=s.transportType||Ge.DTMF_TRANSPORT.INFO;if(u===void 0)throw new TypeError("Not enough arguments");if(this._status!==$e.STATUS_CONFIRMED&&this._status!==$e.STATUS_WAITING_FOR_ACK&&this._status!==$e.STATUS_1XX_RECEIVED)throw new Sa.InvalidStateError(this._status);if(v!==Ge.DTMF_TRANSPORT.INFO&&v!==Ge.DTMF_TRANSPORT.RFC2833)throw new TypeError("invalid transportType: ".concat(v));if(typeof u=="number"&&(u=u.toString()),!u||typeof u!="string"||!u.match(/^[0-9A-DR#*,]+$/i))throw new TypeError("Invalid tones: ".concat(u));if(g&&!Qt.isDecimal(g))throw new TypeError("Invalid tone duration: ".concat(g));if(g?g<hr.C.MIN_DURATION?(Ee.debug('"duration" value is lower than the minimum allowed, setting it to '.concat(hr.C.MIN_DURATION," milliseconds")),g=hr.C.MIN_DURATION):g>hr.C.MAX_DURATION?(Ee.debug('"duration" value is greater than the maximum allowed, setting it to '.concat(hr.C.MAX_DURATION," milliseconds")),g=hr.C.MAX_DURATION):g=Math.abs(g):g=hr.C.DEFAULT_DURATION,s.duration=g,_&&!Qt.isDecimal(_))throw new TypeError("Invalid interToneGap: ".concat(_));if(_?_<hr.C.MIN_INTER_TONE_GAP?(Ee.debug('"interToneGap" value is lower than the minimum allowed, setting it to '.concat(hr.C.MIN_INTER_TONE_GAP," milliseconds")),_=hr.C.MIN_INTER_TONE_GAP):_=Math.abs(_):_=hr.C.DEFAULT_INTER_TONE_GAP,v===Ge.DTMF_TRANSPORT.RFC2833){var C=this._getDTMFRTPSender();C&&(u=C.toneBuffer+u,C.insertDTMF(u,g,_));return}if(this._tones){this._tones+=u;return}this._tones=u,R.call(this);function R(){var D=this,H;if(this._status===$e.STATUS_TERMINATED||!this._tones||n>=this._tones.length){this._tones=null;return}var F=this._tones[n];if(n+=1,F===",")H=2e3;else{var q=new hr(this);s.eventHandlers={onFailed:function(){D._tones=null}},q.send(F,s),H=g+_}setTimeout(R.bind(this),H)}}},{key:"sendInfo",value:function(u,s){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};if(Ee.debug("sendInfo()"),this._status!==$e.STATUS_CONFIRMED&&this._status!==$e.STATUS_WAITING_FOR_ACK&&this._status!==$e.STATUS_1XX_RECEIVED)throw new Sa.InvalidStateError(this._status);var g=new Gh(this);g.send(u,s,n)}},{key:"mute",value:function(){var u=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{audio:!0,video:!1};Ee.debug("mute()");var s=!1,n=!1;this._audioMuted===!1&&u.audio&&(s=!0,this._audioMuted=!0,this._toggleMuteAudio(!0)),this._videoMuted===!1&&u.video&&(n=!0,this._videoMuted=!0,this._toggleMuteVideo(!0)),(s===!0||n===!0)&&this._onmute({audio:s,video:n})}},{key:"unmute",value:function(){var u=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{audio:!0,video:!0};Ee.debug("unmute()");var s=!1,n=!1;this._audioMuted===!0&&u.audio&&(s=!0,this._audioMuted=!1,this._localHold===!1&&this._toggleMuteAudio(!1)),this._videoMuted===!0&&u.video&&(n=!0,this._videoMuted=!1,this._localHold===!1&&this._toggleMuteVideo(!1)),(s===!0||n===!0)&&this._onunmute({audio:s,video:n})}},{key:"hold",value:function(){var u=this,s=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},n=arguments.length>1?arguments[1]:void 0;if(Ee.debug("hold()"),this._status!==$e.STATUS_WAITING_FOR_ACK&&this._status!==$e.STATUS_CONFIRMED||this._localHold===!0||!this._isReadyToReOffer())return!1;this._localHold=!0,this._onhold("local");var g={succeeded:function(){n&&n()},failed:function(){u.terminate({cause:Ge.causes.WEBRTC_ERROR,status_code:500,reason_phrase:"Hold Failed"})}};return s.useUpdate?this._sendUpdate({sdpOffer:!0,eventHandlers:g,extraHeaders:s.extraHeaders}):this._sendReinvite({eventHandlers:g,extraHeaders:s.extraHeaders}),!0}},{key:"unhold",value:function(){var u=this,s=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},n=arguments.length>1?arguments[1]:void 0;if(Ee.debug("unhold()"),this._status!==$e.STATUS_WAITING_FOR_ACK&&this._status!==$e.STATUS_CONFIRMED||this._localHold===!1||!this._isReadyToReOffer())return!1;this._localHold=!1,this._onunhold("local");var g={succeeded:function(){n&&n()},failed:function(){u.terminate({cause:Ge.causes.WEBRTC_ERROR,status_code:500,reason_phrase:"Unhold Failed"})}};return s.useUpdate?this._sendUpdate({sdpOffer:!0,eventHandlers:g,extraHeaders:s.extraHeaders}):this._sendReinvite({eventHandlers:g,extraHeaders:s.extraHeaders}),!0}},{key:"renegotiate",value:function(){var u=this,s=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},n=arguments.length>1?arguments[1]:void 0;Ee.debug("renegotiate()");var g=s.rtcOfferConstraints||null;if(this._status!==$e.STATUS_WAITING_FOR_ACK&&this._status!==$e.STATUS_CONFIRMED||!this._isReadyToReOffer())return!1;var _={succeeded:function(){n&&n()},failed:function(){u.terminate({cause:Ge.causes.WEBRTC_ERROR,status_code:500,reason_phrase:"Media Renegotiation Failed"})}};return this._setLocalMediaStatus(),s.useUpdate?this._sendUpdate({sdpOffer:!0,eventHandlers:_,rtcOfferConstraints:g,extraHeaders:s.extraHeaders}):this._sendReinvite({eventHandlers:_,rtcOfferConstraints:g,extraHeaders:s.extraHeaders}),!0}},{key:"refer",value:function(u,s){var n=this;Ee.debug("refer()");var g=u;if(this._status!==$e.STATUS_WAITING_FOR_ACK&&this._status!==$e.STATUS_CONFIRMED)return!1;if(u=this._ua.normalizeTarget(u),!u)throw new TypeError("Invalid target: ".concat(g));var _=new rb(this);_.sendRefer(u,s);var v=_.id;return this._referSubscribers[v]=_,_.on("requestFailed",function(){delete n._referSubscribers[v]}),_.on("accepted",function(){delete n._referSubscribers[v]}),_.on("failed",function(){delete n._referSubscribers[v]}),_}},{key:"sendRequest",value:function(u,s){return Ee.debug("sendRequest()"),this._dialog.sendRequest(u,s)}},{key:"receiveRequest",value:function(u){var s=this;if(Ee.debug("receiveRequest()"),u.method===Ge.CANCEL)(this._status===$e.STATUS_WAITING_FOR_ANSWER||this._status===$e.STATUS_ANSWERED)&&(this._status=$e.STATUS_CANCELED,this._request.reply(487),this._failed("remote",u,Ge.causes.CANCELED));else switch(u.method){case Ge.ACK:if(this._status!==$e.STATUS_WAITING_FOR_ACK)return;if(this._status=$e.STATUS_CONFIRMED,clearTimeout(this._timers.ackTimer),clearTimeout(this._timers.invite2xxTimer),this._late_sdp){if(!u.body){this.terminate({cause:Ge.causes.MISSING_SDP,status_code:400});break}var n={originator:"remote",type:"answer",sdp:u.body};Ee.debug('emit "sdp"'),this.emit("sdp",n);var g=new RTCSessionDescription({type:"answer",sdp:n.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(function(){return s._connection.setRemoteDescription(g)}).then(function(){s._is_confirmed||s._confirmed("remote",u)}).catch(function(v){s.terminate({cause:Ge.causes.BAD_MEDIA_DESCRIPTION,status_code:488}),Ee.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',v),s.emit("peerconnection:setremotedescriptionfailed",v)})}else this._is_confirmed||this._confirmed("remote",u);break;case Ge.BYE:this._status===$e.STATUS_CONFIRMED||this._status===$e.STATUS_WAITING_FOR_ACK?(u.reply(200),this._ended("remote",u,Ge.causes.BYE)):this._status===$e.STATUS_INVITE_RECEIVED||this._status===$e.STATUS_WAITING_FOR_ANSWER?(u.reply(200),this._request.reply(487,"BYE Received"),this._ended("remote",u,Ge.causes.BYE)):u.reply(403,"Wrong Status");break;case Ge.INVITE:this._status===$e.STATUS_CONFIRMED?u.hasHeader("replaces")?this._receiveReplaces(u):this._receiveReinvite(u):u.reply(403,"Wrong Status");break;case Ge.INFO:if(this._status===$e.STATUS_1XX_RECEIVED||this._status===$e.STATUS_WAITING_FOR_ANSWER||this._status===$e.STATUS_ANSWERED||this._status===$e.STATUS_WAITING_FOR_ACK||this._status===$e.STATUS_CONFIRMED){var _=u.hasHeader("Content-Type")?u.getHeader("Content-Type").toLowerCase():void 0;_&&_.match(/^application\/dtmf-relay/i)?new hr(this).init_incoming(u):_!==void 0?new Gh(this).init_incoming(u):u.reply(415)}else u.reply(403,"Wrong Status");break;case Ge.UPDATE:this._status===$e.STATUS_CONFIRMED?this._receiveUpdate(u):u.reply(403,"Wrong Status");break;case Ge.REFER:this._status===$e.STATUS_CONFIRMED?this._receiveRefer(u):u.reply(403,"Wrong Status");break;case Ge.NOTIFY:this._status===$e.STATUS_CONFIRMED?this._receiveNotify(u):u.reply(403,"Wrong Status");break;default:u.reply(501)}}},{key:"onTransportError",value:function(){Ee.warn("onTransportError()"),this._status!==$e.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:Ge.causes.CONNECTION_ERROR,cause:Ge.causes.CONNECTION_ERROR})}},{key:"onRequestTimeout",value:function(){Ee.warn("onRequestTimeout()"),this._status!==$e.STATUS_TERMINATED&&this.terminate({status_code:408,reason_phrase:Ge.causes.REQUEST_TIMEOUT,cause:Ge.causes.REQUEST_TIMEOUT})}},{key:"onDialogError",value:function(){Ee.warn("onDialogError()"),this._status!==$e.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:Ge.causes.DIALOG_ERROR,cause:Ge.causes.DIALOG_ERROR})}},{key:"newDTMF",value:function(u){Ee.debug("newDTMF()"),this.emit("newDTMF",u)}},{key:"newInfo",value:function(u){Ee.debug("newInfo()"),this.emit("newInfo",u)}},{key:"_isReadyToReOffer",value:function(){return this._rtcReady?this._dialog?this._dialog.uac_pending_reply===!0||this._dialog.uas_pending_reply===!0?(Ee.debug("_isReadyToReOffer() | there is another INVITE/UPDATE transaction in progress"),!1):!0:(Ee.debug("_isReadyToReOffer() | session not established yet"),!1):(Ee.debug("_isReadyToReOffer() | internal WebRTC status not ready"),!1)}},{key:"_close",value:function(){if(Ee.debug("close()"),this._localMediaStream&&this._localMediaStreamLocallyGenerated&&(Ee.debug("close() | closing local MediaStream"),Qt.closeMediaStream(this._localMediaStream)),this._status!==$e.STATUS_TERMINATED){if(this._status=$e.STATUS_TERMINATED,this._connection)try{this._connection.close()}catch(g){Ee.warn("close() | error closing the RTCPeerConnection: %o",g)}for(var u in this._timers)Object.prototype.hasOwnProperty.call(this._timers,u)&&clearTimeout(this._timers[u]);clearTimeout(this._sessionTimers.timer),this._dialog&&(this._dialog.terminate(),delete this._dialog);for(var s in this._earlyDialogs)Object.prototype.hasOwnProperty.call(this._earlyDialogs,s)&&(this._earlyDialogs[s].terminate(),delete this._earlyDialogs[s]);for(var n in this._referSubscribers)Object.prototype.hasOwnProperty.call(this._referSubscribers,n)&&delete this._referSubscribers[n];this._ua.destroyRTCSession(this)}}},{key:"_setInvite2xxTimer",value:function(u,s){var n=Yl.T1;function g(){this._status===$e.STATUS_WAITING_FOR_ACK&&(u.reply(200,null,["Contact: ".concat(this._contact)],s),n<Yl.T2&&(n=n*2,n>Yl.T2&&(n=Yl.T2)),this._timers.invite2xxTimer=setTimeout(g.bind(this),n))}this._timers.invite2xxTimer=setTimeout(g.bind(this),n)}},{key:"_setACKTimer",value:function(){var u=this;this._timers.ackTimer=setTimeout(function(){u._status===$e.STATUS_WAITING_FOR_ACK&&(Ee.debug("no ACK received, terminating the session"),clearTimeout(u._timers.invite2xxTimer),u.sendRequest(Ge.BYE),u._ended("remote",null,Ge.causes.NO_ACK))},Yl.TIMER_H)}},{key:"_createRTCConnection",value:function(u,s){var n=this;this._connection=new RTCPeerConnection(u,s),this._connection.addEventListener("iceconnectionstatechange",function(){var g=n._connection.iceConnectionState;g==="failed"&&n.terminate({cause:Ge.causes.RTP_TIMEOUT,status_code:408,reason_phrase:Ge.causes.RTP_TIMEOUT})}),Ee.debug('emit "peerconnection"'),this.emit("peerconnection",{peerconnection:this._connection})}},{key:"_createLocalDescription",value:function(u,s){var n=this;if(Ee.debug("createLocalDescription()"),u!=="offer"&&u!=="answer")throw new Error('createLocalDescription() | invalid type "'.concat(u,'"'));var g=this._connection;return this._rtcReady=!1,Promise.resolve().then(function(){return u==="offer"?g.createOffer(s).catch(function(_){return Ee.warn('emit "peerconnection:createofferfailed" [error:%o]',_),n.emit("peerconnection:createofferfailed",_),Promise.reject(_)}):g.createAnswer(s).catch(function(_){return Ee.warn('emit "peerconnection:createanswerfailed" [error:%o]',_),n.emit("peerconnection:createanswerfailed",_),Promise.reject(_)})}).then(function(_){return g.setLocalDescription(_).catch(function(v){return n._rtcReady=!0,Ee.warn('emit "peerconnection:setlocaldescriptionfailed" [error:%o]',v),n.emit("peerconnection:setlocaldescriptionfailed",v),Promise.reject(v)})}).then(function(){var _=s&&s.iceRestart;if(g.iceGatheringState==="complete"&&!_||g.iceGatheringState==="gathering"&&n._iceReady){n._rtcReady=!0;var v={originator:"local",type:u,sdp:g.localDescription.sdp};return Ee.debug('emit "sdp"'),n.emit("sdp",v),Promise.resolve(v.sdp)}return new Promise(function(C){var R=!1,D,H;n._iceReady=!1;var F=function(){g.removeEventListener("icecandidate",D),g.removeEventListener("icegatheringstatechange",H),R=!0,n._rtcReady=!0,n._iceReady=!0;var G={originator:"local",type:u,sdp:g.localDescription.sdp};Ee.debug('emit "sdp"'),n.emit("sdp",G),C(G.sdp)};g.addEventListener("icecandidate",D=function(G){var te=G.candidate;te?n.emit("icecandidate",{candidate:te,ready:F}):R||F()}),g.addEventListener("icegatheringstatechange",H=function(){g.iceGatheringState==="complete"&&!R&&F()})})})}},{key:"_createDialog",value:function(u,s,n){var g=s==="UAS"?u.to_tag:u.from_tag,_=s==="UAS"?u.from_tag:u.to_tag,v=u.call_id+g+_,C=this._earlyDialogs[v];if(n)return C?!0:(C=new lu(this,u,s,lu.C.STATUS_EARLY),C.error?(Ee.debug(C.error),this._failed("remote",u,Ge.causes.INTERNAL_ERROR),!1):(this._earlyDialogs[v]=C,!0));if(this._from_tag=u.from_tag,this._to_tag=u.to_tag,C)return C.update(u,s),this._dialog=C,delete this._earlyDialogs[v],!0;var R=new lu(this,u,s);return R.error?(Ee.debug(R.error),this._failed("remote",u,Ge.causes.INTERNAL_ERROR),!1):(this._dialog=R,!0)}},{key:"_receiveReinvite",value:function(u){var s=this;Ee.debug("receiveReinvite()");var n=u.hasHeader("Content-Type")?u.getHeader("Content-Type").toLowerCase():void 0,g={request:u,callback:void 0,reject:v.bind(this)},_=!1;function v(){var R=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};_=!0;var D=R.status_code||403,H=R.reason_phrase||"",F=Qt.cloneArray(R.extraHeaders);if(this._status!==$e.STATUS_CONFIRMED)return!1;if(D<300||D>=700)throw new TypeError("Invalid status_code: ".concat(D));u.reply(D,H,F)}if(this.emit("reinvite",g),_)return;if(this._late_sdp=!1,!u.body){this._late_sdp=!0,this._remoteHold&&(this._remoteHold=!1,this._onunhold("remote")),this._connectionPromiseQueue=this._connectionPromiseQueue.then(function(){return s._createLocalDescription("offer",s._rtcOfferConstraints)}).then(function(R){C.call(s,R)}).catch(function(){u.reply(500)});return}if(n!=="application/sdp"){Ee.debug("invalid Content-Type"),u.reply(415);return}this._processInDialogSdpOffer(u).then(function(R){s._status!==$e.STATUS_TERMINATED&&C.call(s,R)}).catch(function(R){Ee.warn(R)});function C(R){var D=this,H=["Contact: ".concat(this._contact)];this._handleSessionTimersInIncomingRequest(u,H),this._late_sdp&&(R=this._mangleOffer(R)),u.reply(200,null,H,R,function(){D._status=$e.STATUS_WAITING_FOR_ACK,D._setInvite2xxTimer(u,R),D._setACKTimer()}),typeof g.callback=="function"&&g.callback()}}},{key:"_receiveUpdate",value:function(u){var s=this;Ee.debug("receiveUpdate()");var n=u.hasHeader("Content-Type")?u.getHeader("Content-Type").toLowerCase():void 0,g={request:u,callback:void 0,reject:v.bind(this)},_=!1;function v(){var R=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};_=!0;var D=R.status_code||403,H=R.reason_phrase||"",F=Qt.cloneArray(R.extraHeaders);if(this._status!==$e.STATUS_CONFIRMED)return!1;if(D<300||D>=700)throw new TypeError("Invalid status_code: ".concat(D));u.reply(D,H,F)}if(this.emit("update",g),_)return;if(!u.body){C.call(this,null);return}if(n!=="application/sdp"){Ee.debug("invalid Content-Type"),u.reply(415);return}this._processInDialogSdpOffer(u).then(function(R){s._status!==$e.STATUS_TERMINATED&&C.call(s,R)}).catch(function(R){Ee.warn(R)});function C(R){var D=["Contact: ".concat(this._contact)];this._handleSessionTimersInIncomingRequest(u,D),u.reply(200,null,D,R),typeof g.callback=="function"&&g.callback()}}},{key:"_processInDialogSdpOffer",value:function(u){var s=this;Ee.debug("_processInDialogSdpOffer()");var n=u.parseSDP(),g=!1,_=kn(n.media),v;try{for(_.s();!(v=_.n()).done;){var C=v.value;if(ou.indexOf(C.type)!==-1){var R=C.direction||n.direction||"sendrecv";if(R==="sendonly"||R==="inactive")g=!0;else{g=!1;break}}}}catch(F){_.e(F)}finally{_.f()}var D={originator:"remote",type:"offer",sdp:u.body};Ee.debug('emit "sdp"'),this.emit("sdp",D);var H=new RTCSessionDescription({type:"offer",sdp:D.sdp});return this._connectionPromiseQueue=this._connectionPromiseQueue.then(function(){if(s._status===$e.STATUS_TERMINATED)throw new Error("terminated");return s._connection.setRemoteDescription(H).catch(function(F){throw u.reply(488),Ee.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',F),s.emit("peerconnection:setremotedescriptionfailed",F),F})}).then(function(){if(s._status===$e.STATUS_TERMINATED)throw new Error("terminated");s._remoteHold===!0&&g===!1?(s._remoteHold=!1,s._onunhold("remote")):s._remoteHold===!1&&g===!0&&(s._remoteHold=!0,s._onhold("remote"))}).then(function(){if(s._status===$e.STATUS_TERMINATED)throw new Error("terminated");return s._createLocalDescription("answer",s._rtcAnswerConstraints).catch(function(F){throw u.reply(500),Ee.warn('emit "peerconnection:createtelocaldescriptionfailed" [error:%o]',F),F})}).catch(function(F){Ee.warn("_processInDialogSdpOffer() failed [error: %o]",F)}),this._connectionPromiseQueue}},{key:"_receiveRefer",value:function(u){var s=this;if(Ee.debug("receiveRefer()"),!u.refer_to){Ee.debug("no Refer-To header field present in REFER"),u.reply(400);return}if(u.refer_to.uri.scheme!==Ge.SIP){Ee.debug("Refer-To header field points to a non-SIP URI scheme"),u.reply(416);return}u.reply(202);var n=new sb(this,u.cseq);Ee.debug('emit "refer"'),this.emit("refer",{request:u,accept:function(C,R){g.call(s,C,R)},reject:function(){_.call(s)}});function g(v){var C=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(v=typeof v=="function"?v:null,this._status!==$e.STATUS_WAITING_FOR_ACK&&this._status!==$e.STATUS_CONFIRMED)return!1;var R=new r(this._ua);if(R.on("progress",function(H){var F=H.response;n.notify(F.status_code,F.reason_phrase)}),R.on("accepted",function(H){var F=H.response;n.notify(F.status_code,F.reason_phrase)}),R.on("_failed",function(H){var F=H.message,q=H.cause;F?n.notify(F.status_code,F.reason_phrase):n.notify(487,q)}),u.refer_to.uri.hasHeader("replaces")){var D=decodeURIComponent(u.refer_to.uri.getHeader("replaces"));C.extraHeaders=Qt.cloneArray(C.extraHeaders),C.extraHeaders.push("Replaces: ".concat(D))}R.connect(u.refer_to.uri.toAor(),C,v)}function _(){n.notify(603)}}},{key:"_receiveNotify",value:function(u){switch(Ee.debug("receiveNotify()"),u.event||u.reply(400),u.event.event){case"refer":{var s,n;if(u.event.params&&u.event.params.id)s=u.event.params.id,n=this._referSubscribers[s];else if(Object.keys(this._referSubscribers).length===1)n=this._referSubscribers[Object.keys(this._referSubscribers)[0]];else{u.reply(400,"Missing event id parameter");return}if(!n){u.reply(481,"Subscription does not exist");return}n.receiveNotify(u),u.reply(200);break}default:u.reply(489)}}},{key:"_receiveReplaces",value:function(u){var s=this;Ee.debug("receiveReplaces()");function n(_){var v=this;if(this._status!==$e.STATUS_WAITING_FOR_ACK&&this._status!==$e.STATUS_CONFIRMED)return!1;var C=new r(this._ua);C.on("confirmed",function(){v.terminate()}),C.init_incoming(u,_)}function g(){Ee.debug("Replaced INVITE rejected by the user"),u.reply(486)}this.emit("replaces",{request:u,accept:function(v){n.call(s,v)},reject:function(){g.call(s)}})}},{key:"_sendInitialRequest",value:function(u,s,n){var g=this,_=new tb(this._ua,this._request,{onRequestTimeout:function(){g.onRequestTimeout()},onTransportError:function(){g.onTransportError()},onAuthenticated:function(C){g._request=C},onReceiveResponse:function(C){g._receiveInviteResponse(C)}});Promise.resolve().then(function(){if(n)return n;if(u.audio||u.video)return g._localMediaStreamLocallyGenerated=!0,navigator.mediaDevices.getUserMedia(u).catch(function(v){throw g._status===$e.STATUS_TERMINATED?new Error("terminated"):(g._failed("local",null,Ge.causes.USER_DENIED_MEDIA_ACCESS),Ee.warn('emit "getusermediafailed" [error:%o]',v),g.emit("getusermediafailed",v),v)})}).then(function(v){if(g._status===$e.STATUS_TERMINATED)throw new Error("terminated");return g._localMediaStream=v,v&&v.getTracks().forEach(function(C){g._connection.addTrack(C,v)}),g._connecting(g._request),g._createLocalDescription("offer",s).catch(function(C){throw g._failed("local",null,Ge.causes.WEBRTC_ERROR),C})}).then(function(v){if(g._is_canceled||g._status===$e.STATUS_TERMINATED)throw new Error("terminated");g._request.body=v,g._status=$e.STATUS_INVITE_SENT,Ee.debug('emit "sending" [request:%o]',g._request),g.emit("sending",{request:g._request}),_.send()}).catch(function(v){g._status!==$e.STATUS_TERMINATED&&Ee.warn(v)})}},{key:"_getDTMFRTPSender",value:function(){var u=this._connection.getSenders().find(function(s){return s.track&&s.track.kind==="audio"});if(!(u&&u.dtmf)){Ee.warn("sendDTMF() | no local audio track to send DTMF with");return}return u.dtmf}},{key:"_receiveInviteResponse",value:function(u){var s=this;if(Ee.debug("receiveInviteResponse()"),this._dialog&&u.status_code>=200&&u.status_code<=299)if(this._dialog.id.call_id===u.call_id&&this._dialog.id.local_tag===u.from_tag&&this._dialog.id.remote_tag===u.to_tag){this.sendRequest(Ge.ACK);return}else{var n=new lu(this,u,"UAC");if(n.error!==void 0){Ee.debug(n.error);return}this.sendRequest(Ge.ACK),this.sendRequest(Ge.BYE);return}if(this._is_canceled){u.status_code>=100&&u.status_code<200?this._request.cancel(this._cancel_reason):u.status_code>=200&&u.status_code<299&&this._acceptAndTerminate(u);return}if(!(this._status!==$e.STATUS_INVITE_SENT&&this._status!==$e.STATUS_1XX_RECEIVED))switch(!0){case/^100$/.test(u.status_code):this._status=$e.STATUS_1XX_RECEIVED;break;case/^1[0-9]{2}$/.test(u.status_code):{if(!u.to_tag){Ee.debug("1xx response received without to tag");break}if(u.hasHeader("contact")&&!this._createDialog(u,"UAC",!0))break;if(this._status=$e.STATUS_1XX_RECEIVED,!u.body){this._progress("remote",u);break}var g={originator:"remote",type:"answer",sdp:u.body};Ee.debug('emit "sdp"'),this.emit("sdp",g);var _=new RTCSessionDescription({type:"answer",sdp:g.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(function(){return s._connection.setRemoteDescription(_)}).then(function(){return s._progress("remote",u)}).catch(function(D){Ee.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',D),s.emit("peerconnection:setremotedescriptionfailed",D)});break}case/^2[0-9]{2}$/.test(u.status_code):{if(this._status=$e.STATUS_CONFIRMED,!u.body){this._acceptAndTerminate(u,400,Ge.causes.MISSING_SDP),this._failed("remote",u,Ge.causes.BAD_MEDIA_DESCRIPTION);break}if(!this._createDialog(u,"UAC"))break;var v={originator:"remote",type:"answer",sdp:u.body};Ee.debug('emit "sdp"'),this.emit("sdp",v);var C=new RTCSessionDescription({type:"answer",sdp:v.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(function(){if(s._connection.signalingState==="stable")return s._connection.createOffer(s._rtcOfferConstraints).then(function(D){return s._connection.setLocalDescription(D)}).catch(function(D){s._acceptAndTerminate(u,500,D.toString()),s._failed("local",u,Ge.causes.WEBRTC_ERROR)})}).then(function(){s._connection.setRemoteDescription(C).then(function(){s._handleSessionTimersInIncomingResponse(u),s._accepted("remote",u),s.sendRequest(Ge.ACK),s._confirmed("local",null)}).catch(function(D){s._acceptAndTerminate(u,488,"Not Acceptable Here"),s._failed("remote",u,Ge.causes.BAD_MEDIA_DESCRIPTION),Ee.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',D),s.emit("peerconnection:setremotedescriptionfailed",D)})});break}default:{var R=Qt.sipErrorCause(u.status_code);this._failed("remote",u,R)}}}},{key:"_sendReinvite",value:function(){var u=this,s=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Ee.debug("sendReinvite()");var n=Qt.cloneArray(s.extraHeaders),g=Qt.cloneObject(s.eventHandlers),_=s.rtcOfferConstraints||this._rtcOfferConstraints||null,v=!1;n.push("Contact: ".concat(this._contact)),n.push("Content-Type: application/sdp"),this._sessionTimers.running&&n.push("Session-Expires: ".concat(this._sessionTimers.currentExpires,";refresher=").concat(this._sessionTimers.refresher?"uac":"uas")),this._connectionPromiseQueue=this._connectionPromiseQueue.then(function(){return u._createLocalDescription("offer",_)}).then(function(D){D=u._mangleOffer(D);var H={originator:"local",type:"offer",sdp:D};Ee.debug('emit "sdp"'),u.emit("sdp",H),u.sendRequest(Ge.INVITE,{extraHeaders:n,body:D,eventHandlers:{onSuccessResponse:function(q){C.call(u,q),v=!0},onErrorResponse:function(q){R.call(u,q)},onTransportError:function(){u.onTransportError()},onRequestTimeout:function(){u.onRequestTimeout()},onDialogError:function(){u.onDialogError()}}})}).catch(function(){R()});function C(D){var H=this;if(this._status!==$e.STATUS_TERMINATED&&(this.sendRequest(Ge.ACK),!v)){if(this._handleSessionTimersInIncomingResponse(D),D.body){if(!D.hasHeader("Content-Type")||D.getHeader("Content-Type").toLowerCase()!=="application/sdp"){R.call(this);return}}else{R.call(this);return}var F={originator:"remote",type:"answer",sdp:D.body};Ee.debug('emit "sdp"'),this.emit("sdp",F);var q=new RTCSessionDescription({type:"answer",sdp:F.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(function(){return H._connection.setRemoteDescription(q)}).then(function(){g.succeeded&&g.succeeded(D)}).catch(function(G){R.call(H),Ee.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',G),H.emit("peerconnection:setremotedescriptionfailed",G)})}}function R(D){g.failed&&g.failed(D)}}},{key:"_sendUpdate",value:function(){var u=this,s=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Ee.debug("sendUpdate()");var n=Qt.cloneArray(s.extraHeaders),g=Qt.cloneObject(s.eventHandlers),_=s.rtcOfferConstraints||this._rtcOfferConstraints||null,v=s.sdpOffer||!1,C=!1;n.push("Contact: ".concat(this._contact)),this._sessionTimers.running&&n.push("Session-Expires: ".concat(this._sessionTimers.currentExpires,";refresher=").concat(this._sessionTimers.refresher?"uac":"uas")),v?(n.push("Content-Type: application/sdp"),this._connectionPromiseQueue=this._connectionPromiseQueue.then(function(){return u._createLocalDescription("offer",_)}).then(function(H){H=u._mangleOffer(H);var F={originator:"local",type:"offer",sdp:H};Ee.debug('emit "sdp"'),u.emit("sdp",F),u.sendRequest(Ge.UPDATE,{extraHeaders:n,body:H,eventHandlers:{onSuccessResponse:function(G){R.call(u,G),C=!0},onErrorResponse:function(G){D.call(u,G)},onTransportError:function(){u.onTransportError()},onRequestTimeout:function(){u.onRequestTimeout()},onDialogError:function(){u.onDialogError()}}})}).catch(function(){D.call(u)})):this.sendRequest(Ge.UPDATE,{extraHeaders:n,eventHandlers:{onSuccessResponse:function(F){R.call(u,F)},onErrorResponse:function(F){D.call(u,F)},onTransportError:function(){u.onTransportError()},onRequestTimeout:function(){u.onRequestTimeout()},onDialogError:function(){u.onDialogError()}}});function R(H){var F=this;if(this._status!==$e.STATUS_TERMINATED&&!C)if(this._handleSessionTimersInIncomingResponse(H),v){if(H.body){if(!H.hasHeader("Content-Type")||H.getHeader("Content-Type").toLowerCase()!=="application/sdp"){D.call(this);return}}else{D.call(this);return}var q={originator:"remote",type:"answer",sdp:H.body};Ee.debug('emit "sdp"'),this.emit("sdp",q);var G=new RTCSessionDescription({type:"answer",sdp:q.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(function(){return F._connection.setRemoteDescription(G)}).then(function(){g.succeeded&&g.succeeded(H)}).catch(function(te){D.call(F),Ee.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',te),F.emit("peerconnection:setremotedescriptionfailed",te)})}else g.succeeded&&g.succeeded(H)}function D(H){g.failed&&g.failed(H)}}},{key:"_acceptAndTerminate",value:function(u,s,n){Ee.debug("acceptAndTerminate()");var g=[];s&&(n=n||Ge.REASON_PHRASE[s]||"",g.push("Reason: SIP ;cause=".concat(s,'; text="').concat(n,'"'))),(this._dialog||this._createDialog(u,"UAC"))&&(this.sendRequest(Ge.ACK),this.sendRequest(Ge.BYE,{extraHeaders:g})),this._status=$e.STATUS_TERMINATED}},{key:"_mangleOffer",value:function(u){if(!this._localHold&&!this._remoteHold)return u;if(u=qh.parse(u),this._localHold&&!this._remoteHold){Ee.debug("mangleOffer() | me on hold, mangling offer");var s=kn(u.media),n;try{for(s.s();!(n=s.n()).done;){var g=n.value;ou.indexOf(g.type)!==-1&&(g.direction?g.direction==="sendrecv"?g.direction="sendonly":g.direction==="recvonly"&&(g.direction="inactive"):g.direction="sendonly")}}catch(F){s.e(F)}finally{s.f()}}else if(this._localHold&&this._remoteHold){Ee.debug("mangleOffer() | both on hold, mangling offer");var _=kn(u.media),v;try{for(_.s();!(v=_.n()).done;){var C=v.value;ou.indexOf(C.type)!==-1&&(C.direction="inactive")}}catch(F){_.e(F)}finally{_.f()}}else if(this._remoteHold){Ee.debug("mangleOffer() | remote on hold, mangling offer");var R=kn(u.media),D;try{for(R.s();!(D=R.n()).done;){var H=D.value;ou.indexOf(H.type)!==-1&&(H.direction?H.direction==="sendrecv"?H.direction="recvonly":H.direction==="recvonly"&&(H.direction="inactive"):H.direction="recvonly")}}catch(F){R.e(F)}finally{R.f()}}return qh.write(u)}},{key:"_setLocalMediaStatus",value:function(){var u=!0,s=!0;(this._localHold||this._remoteHold)&&(u=!1,s=!1),this._audioMuted&&(u=!1),this._videoMuted&&(s=!1),this._toggleMuteAudio(!u),this._toggleMuteVideo(!s)}},{key:"_handleSessionTimersInIncomingRequest",value:function(u,s){if(this._sessionTimers.enabled){var n;u.session_expires&&u.session_expires>=Ge.MIN_SESSION_EXPIRES?(this._sessionTimers.currentExpires=u.session_expires,n=u.session_expires_refresher||"uas"):(this._sessionTimers.currentExpires=this._sessionTimers.defaultExpires,n="uas"),s.push("Session-Expires: ".concat(this._sessionTimers.currentExpires,";refresher=").concat(n)),this._sessionTimers.refresher=n==="uas",this._runSessionTimer()}}},{key:"_handleSessionTimersInIncomingResponse",value:function(u){if(this._sessionTimers.enabled){var s;u.session_expires&&u.session_expires>=Ge.MIN_SESSION_EXPIRES?(this._sessionTimers.currentExpires=u.session_expires,s=u.session_expires_refresher||"uac"):(this._sessionTimers.currentExpires=this._sessionTimers.defaultExpires,s="uac"),this._sessionTimers.refresher=s==="uac",this._runSessionTimer()}}},{key:"_runSessionTimer",value:function(){var u=this,s=this._sessionTimers.currentExpires;this._sessionTimers.running=!0,clearTimeout(this._sessionTimers.timer),this._sessionTimers.refresher?this._sessionTimers.timer=setTimeout(function(){u._status!==$e.STATUS_TERMINATED&&u._isReadyToReOffer()&&(Ee.debug("runSessionTimer() | sending session refresh request"),u._sessionTimers.refreshMethod===Ge.UPDATE?u._sendUpdate():u._sendReinvite())},s*500):this._sessionTimers.timer=setTimeout(function(){u._status!==$e.STATUS_TERMINATED&&(Ee.warn("runSessionTimer() | timer expired, terminating the session"),u.terminate({cause:Ge.causes.REQUEST_TIMEOUT,status_code:408,reason_phrase:"Session Timer Expired"}))},s*1100)}},{key:"_toggleMuteAudio",value:function(u){var s=this._connection.getSenders().filter(function(v){return v.track&&v.track.kind==="audio"}),n=kn(s),g;try{for(n.s();!(g=n.n()).done;){var _=g.value;_.track.enabled=!u}}catch(v){n.e(v)}finally{n.f()}}},{key:"_toggleMuteVideo",value:function(u){var s=this._connection.getSenders().filter(function(v){return v.track&&v.track.kind==="video"}),n=kn(s),g;try{for(n.s();!(g=n.n()).done;){var _=g.value;_.track.enabled=!u}}catch(v){n.e(v)}finally{n.f()}}},{key:"_newRTCSession",value:function(u,s){Ee.debug("newRTCSession()"),this._ua.newRTCSession(this,{originator:u,session:this,request:s})}},{key:"_connecting",value:function(u){Ee.debug("session connecting"),Ee.debug('emit "connecting"'),this.emit("connecting",{request:u})}},{key:"_progress",value:function(u,s){Ee.debug("session progress"),Ee.debug('emit "progress"'),this.emit("progress",{originator:u,response:s||null})}},{key:"_accepted",value:function(u,s){Ee.debug("session accepted"),this._start_time=new Date,Ee.debug('emit "accepted"'),this.emit("accepted",{originator:u,response:s||null})}},{key:"_confirmed",value:function(u,s){Ee.debug("session confirmed"),this._is_confirmed=!0,Ee.debug('emit "confirmed"'),this.emit("confirmed",{originator:u,ack:s||null})}},{key:"_ended",value:function(u,s,n){Ee.debug("session ended"),this._end_time=new Date,this._close(),Ee.debug('emit "ended"'),this.emit("ended",{originator:u,message:s||null,cause:n})}},{key:"_failed",value:function(u,s,n){Ee.debug("session failed"),Ee.debug('emit "_failed"'),this.emit("_failed",{originator:u,message:s||null,cause:n}),this._close(),Ee.debug('emit "failed"'),this.emit("failed",{originator:u,message:s||null,cause:n})}},{key:"_onhold",value:function(u){Ee.debug("session onhold"),this._setLocalMediaStatus(),Ee.debug('emit "hold"'),this.emit("hold",{originator:u})}},{key:"_onunhold",value:function(u){Ee.debug("session onunhold"),this._setLocalMediaStatus(),Ee.debug('emit "unhold"'),this.emit("unhold",{originator:u})}},{key:"_onmute",value:function(u){var s=u.audio,n=u.video;Ee.debug("session onmute"),this._setLocalMediaStatus(),Ee.debug('emit "muted"'),this.emit("muted",{audio:s,video:n})}},{key:"_onunmute",value:function(u){var s=u.audio,n=u.video;Ee.debug("session onunmute"),this._setLocalMediaStatus(),Ee.debug('emit "unmuted"'),this.emit("unmuted",{audio:s,video:n})}},{key:"C",get:function(){return $e}},{key:"causes",get:function(){return Ge.causes}},{key:"id",get:function(){return this._id}},{key:"connection",get:function(){return this._connection}},{key:"contact",get:function(){return this._contact}},{key:"direction",get:function(){return this._direction}},{key:"local_identity",get:function(){return this._local_identity}},{key:"remote_identity",get:function(){return this._remote_identity}},{key:"start_time",get:function(){return this._start_time}},{key:"end_time",get:function(){return this._end_time}},{key:"data",get:function(){return this._data},set:function(u){this._data=u}},{key:"status",get:function(){return this._status}}]),r}(XS);function uu(f){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?uu=function(r){return typeof r}:uu=function(r){return r&&typeof Symbol=="function"&&r.constructor===Symbol&&r!==Symbol.prototype?"symbol":typeof r},uu(f)}function ib(f,t){if(!(f instanceof t))throw new TypeError("Cannot call a class as a function")}function Kh(f,t){for(var r=0;r<t.length;r++){var l=t[r];l.enumerable=l.enumerable||!1,l.configurable=!0,"value"in l&&(l.writable=!0),Object.defineProperty(f,l.key,l)}}function ab(f,t,r){return t&&Kh(f.prototype,t),r&&Kh(f,r),f}function lb(f,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");f.prototype=Object.create(t&&t.prototype,{constructor:{value:f,writable:!0,configurable:!0}}),t&&kc(f,t)}function kc(f,t){return kc=Object.setPrototypeOf||function(l,u){return l.__proto__=u,l},kc(f,t)}function ob(f){var t=db();return function(){var l=cu(f),u;if(t){var s=cu(this).constructor;u=Reflect.construct(l,arguments,s)}else u=l.apply(this,arguments);return ub(this,u)}}function ub(f,t){return t&&(uu(t)==="object"||typeof t=="function")?t:cb(f)}function cb(f){if(f===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return f}function db(){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 cu(f){return cu=Object.setPrototypeOf?Object.getPrototypeOf:function(r){return r.__proto__||Object.getPrototypeOf(r)},cu(f)}var fb=ys.EventEmitter,hb=Ts,Nc=hs,_b=xn,Jl=Bs(),pb=jl,Yh=yi,mb=Ti(),du=new hb("Message"),gb=function(f){lb(r,f);var t=ob(r);function r(l){var u;return ib(this,r),u=t.call(this),u._ua=l,u._request=null,u._closed=!1,u._direction=null,u._local_identity=null,u._remote_identity=null,u._is_replied=!1,u._data={},u}return ab(r,[{key:"send",value:function(u,s){var n=this,g=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},_=u;if(u===void 0||s===void 0)throw new TypeError("Not enough arguments");if(u=this._ua.normalizeTarget(u),!u)throw new TypeError("Invalid target: ".concat(_));var v=Jl.cloneArray(g.extraHeaders),C=Jl.cloneObject(g.eventHandlers),R=g.contentType||"text/plain",D={};g.fromUserName&&(D.from_uri=new mb("sip",g.fromUserName,this._ua.configuration.uri.host),v.push("P-Preferred-Identity: ".concat(this._ua.configuration.uri.toString()))),g.fromDisplayName&&(D.from_display_name=g.fromDisplayName);for(var H in C)Object.prototype.hasOwnProperty.call(C,H)&&this.on(H,C[H]);v.push("Content-Type: ".concat(R)),this._request=new _b.OutgoingRequest(Nc.MESSAGE,u,this._ua,D,v),s&&(this._request.body=s);var F=new pb(this._ua,this._request,{onRequestTimeout:function(){n._onRequestTimeout()},onTransportError:function(){n._onTransportError()},onReceiveResponse:function(G){n._receiveResponse(G)}});this._newMessage("local",this._request),F.send()}},{key:"init_incoming",value:function(u){this._request=u,this._newMessage("remote",u),this._is_replied||(this._is_replied=!0,u.reply(200)),this._close()}},{key:"accept",value:function(){var u=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},s=Jl.cloneArray(u.extraHeaders),n=u.body;if(this._direction!=="incoming")throw new Yh.NotSupportedError('"accept" not supported for outgoing Message');if(this._is_replied)throw new Error("incoming Message already replied");this._is_replied=!0,this._request.reply(200,null,s,n)}},{key:"reject",value:function(){var u=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},s=u.status_code||480,n=u.reason_phrase,g=Jl.cloneArray(u.extraHeaders),_=u.body;if(this._direction!=="incoming")throw new Yh.NotSupportedError('"reject" not supported for outgoing Message');if(this._is_replied)throw new Error("incoming Message already replied");if(s<300||s>=700)throw new TypeError("Invalid status_code: ".concat(s));this._is_replied=!0,this._request.reply(s,n,g,_)}},{key:"_receiveResponse",value:function(u){if(!this._closed)switch(!0){case/^1[0-9]{2}$/.test(u.status_code):break;case/^2[0-9]{2}$/.test(u.status_code):this._succeeded("remote",u);break;default:{var s=Jl.sipErrorCause(u.status_code);this._failed("remote",u,s);break}}}},{key:"_onRequestTimeout",value:function(){this._closed||this._failed("system",null,Nc.causes.REQUEST_TIMEOUT)}},{key:"_onTransportError",value:function(){this._closed||this._failed("system",null,Nc.causes.CONNECTION_ERROR)}},{key:"_close",value:function(){this._closed=!0,this._ua.destroyMessage(this)}},{key:"_newMessage",value:function(u,s){u==="remote"?(this._direction="incoming",this._local_identity=s.to,this._remote_identity=s.from):u==="local"&&(this._direction="outgoing",this._local_identity=s.from,this._remote_identity=s.to),this._ua.newMessage(this,{originator:u,message:this,request:s})}},{key:"_failed",value:function(u,s,n){du.debug("MESSAGE failed"),this._close(),du.debug('emit "failed"'),this.emit("failed",{originator:u,response:s||null,cause:n})}},{key:"_succeeded",value:function(u,s){du.debug("MESSAGE succeeded"),this._close(),du.debug('emit "succeeded"'),this.emit("succeeded",{originator:u,response:s})}},{key:"direction",get:function(){return this._direction}},{key:"local_identity",get:function(){return this._local_identity}},{key:"remote_identity",get:function(){return this._remote_identity}}]),r}(fb);function fu(f){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?fu=function(r){return typeof r}:fu=function(r){return r&&typeof Symbol=="function"&&r.constructor===Symbol&&r!==Symbol.prototype?"symbol":typeof r},fu(f)}function vb(f,t){if(!(f instanceof t))throw new TypeError("Cannot call a class as a function")}function Jh(f,t){for(var r=0;r<t.length;r++){var l=t[r];l.enumerable=l.enumerable||!1,l.configurable=!0,"value"in l&&(l.writable=!0),Object.defineProperty(f,l.key,l)}}function yb(f,t,r){return t&&Jh(f.prototype,t),r&&Jh(f,r),f}function Tb(f,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");f.prototype=Object.create(t&&t.prototype,{constructor:{value:f,writable:!0,configurable:!0}}),t&&Mc(f,t)}function Mc(f,t){return Mc=Object.setPrototypeOf||function(l,u){return l.__proto__=u,l},Mc(f,t)}function Sb(f){var t=Eb();return function(){var l=hu(f),u;if(t){var s=hu(this).constructor;u=Reflect.construct(l,arguments,s)}else u=l.apply(this,arguments);return bb(this,u)}}function bb(f,t){return t&&(fu(t)==="object"||typeof t=="function")?t:wb(f)}function wb(f){if(f===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return f}function Eb(){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 hu(f){return hu=Object.setPrototypeOf?Object.getPrototypeOf:function(r){return r.__proto__||Object.getPrototypeOf(r)},hu(f)}var Cb=ys.EventEmitter,Ab=Ts,Uc=hs,Ib=xn,Ql=Bs(),Rb=jl,Qh=yi,_u=new Ab("Options"),$b=function(f){Tb(r,f);var t=Sb(r);function r(l){var u;return vb(this,r),u=t.call(this),u._ua=l,u._request=null,u._closed=!1,u._direction=null,u._local_identity=null,u._remote_identity=null,u._is_replied=!1,u._data={},u}return yb(r,[{key:"send",value:function(u,s){var n=this,g=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},_=u;if(u===void 0)throw new TypeError("A target is required for OPTIONS");if(u=this._ua.normalizeTarget(u),!u)throw new TypeError("Invalid target: ".concat(_));var v=Ql.cloneArray(g.extraHeaders),C=Ql.cloneObject(g.eventHandlers),R=g.contentType||"application/sdp";for(var D in C)Object.prototype.hasOwnProperty.call(C,D)&&this.on(D,C[D]);v.push("Content-Type: ".concat(R)),this._request=new Ib.OutgoingRequest(Uc.OPTIONS,u,this._ua,null,v),s&&(this._request.body=s);var H=new Rb(this._ua,this._request,{onRequestTimeout:function(){n._onRequestTimeout()},onTransportError:function(){n._onTransportError()},onReceiveResponse:function(q){n._receiveResponse(q)}});this._newOptions("local",this._request),H.send()}},{key:"init_incoming",value:function(u){this._request=u,this._newOptions("remote",u),this._is_replied||(this._is_replied=!0,u.reply(200)),this._close()}},{key:"accept",value:function(){var u=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},s=Ql.cloneArray(u.extraHeaders),n=u.body;if(this._direction!=="incoming")throw new Qh.NotSupportedError('"accept" not supported for outgoing Options');if(this._is_replied)throw new Error("incoming Options already replied");this._is_replied=!0,this._request.reply(200,null,s,n)}},{key:"reject",value:function(){var u=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},s=u.status_code||480,n=u.reason_phrase,g=Ql.cloneArray(u.extraHeaders),_=u.body;if(this._direction!=="incoming")throw new Qh.NotSupportedError('"reject" not supported for outgoing Options');if(this._is_replied)throw new Error("incoming Options already replied");if(s<300||s>=700)throw new TypeError("Invalid status_code: ".concat(s));this._is_replied=!0,this._request.reply(s,n,g,_)}},{key:"_receiveResponse",value:function(u){if(!this._closed)switch(!0){case/^1[0-9]{2}$/.test(u.status_code):break;case/^2[0-9]{2}$/.test(u.status_code):this._succeeded("remote",u);break;default:{var s=Ql.sipErrorCause(u.status_code);this._failed("remote",u,s);break}}}},{key:"_onRequestTimeout",value:function(){this._closed||this._failed("system",null,Uc.causes.REQUEST_TIMEOUT)}},{key:"_onTransportError",value:function(){this._closed||this._failed("system",null,Uc.causes.CONNECTION_ERROR)}},{key:"_close",value:function(){this._closed=!0,this._ua.destroyMessage(this)}},{key:"_newOptions",value:function(u,s){u==="remote"?(this._direction="incoming",this._local_identity=s.to,this._remote_identity=s.from):u==="local"&&(this._direction="outgoing",this._local_identity=s.from,this._remote_identity=s.to),this._ua.newOptions(this,{originator:u,message:this,request:s})}},{key:"_failed",value:function(u,s,n){_u.debug("OPTIONS failed"),this._close(),_u.debug('emit "failed"'),this.emit("failed",{originator:u,response:s||null,cause:n})}},{key:"_succeeded",value:function(u,s){_u.debug("OPTIONS succeeded"),this._close(),_u.debug('emit "succeeded"'),this.emit("succeeded",{originator:u,response:s})}},{key:"direction",get:function(){return this._direction}},{key:"local_identity",get:function(){return this._local_identity}},{key:"remote_identity",get:function(){return this._remote_identity}}]),r}(Cb),Pc={},xb=Ts,Lc=Bs(),Ob=on(),Xl=new xb("Socket");Pc.isSocket=function(f){if(Array.isArray(f))return!1;if(typeof f>"u")return Xl.warn("undefined JsSIP.Socket instance"),!1;try{if(!Lc.isString(f.url))throw Xl.warn("missing or invalid JsSIP.Socket url property"),new Error("Missing or invalid JsSIP.Socket url property");if(!Lc.isString(f.via_transport))throw Xl.warn("missing or invalid JsSIP.Socket via_transport property"),new Error("Missing or invalid JsSIP.Socket via_transport property");if(Ob.parse(f.sip_uri,"SIP_URI")===-1)throw Xl.warn("missing or invalid JsSIP.Socket sip_uri property"),new Error("missing or invalid JsSIP.Socket sip_uri property")}catch{return!1}try{["connect","disconnect","send"].forEach(function(t){if(!Lc.isFunction(f[t]))throw Xl.warn("missing or invalid JsSIP.Socket method: ".concat(t)),new Error("Missing or invalid JsSIP.Socket method: ".concat(t))})}catch{return!1}return!0};function Db(f,t){if(!(f instanceof t))throw new TypeError("Cannot call a class as a function")}function Xh(f,t){for(var r=0;r<t.length;r++){var l=t[r];l.enumerable=l.enumerable||!1,l.configurable=!0,"value"in l&&(l.writable=!0),Object.defineProperty(f,l.key,l)}}function kb(f,t,r){return t&&Xh(f.prototype,t),r&&Xh(f,r),f}var Nb=Ts,Mb=Pc,Zh=hs,rr=new Nb("Transport"),wr={STATUS_CONNECTED:0,STATUS_CONNECTING:1,STATUS_DISCONNECTED:2,SOCKET_STATUS_READY:0,SOCKET_STATUS_ERROR:1,recovery_options:{min_interval:Zh.CONNECTION_RECOVERY_MIN_INTERVAL,max_interval:Zh.CONNECTION_RECOVERY_MAX_INTERVAL}},Ub=function(){function f(t){var r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:wr.recovery_options;Db(this,f),rr.debug("new()"),this.status=wr.STATUS_DISCONNECTED,this.socket=null,this.sockets=[],this.recovery_options=r,this.recover_attempts=0,this.recovery_timer=null,this.close_requested=!1;try{this.textDecoder=new TextDecoder("utf8")}catch(l){rr.warn("cannot use TextDecoder: ".concat(l))}if(typeof t>"u")throw new TypeError("Invalid argument. undefined 'sockets' argument");t instanceof Array||(t=[t]),t.forEach(function(l){if(!Mb.isSocket(l.socket))throw new TypeError("Invalid argument. invalid 'JsSIP.Socket' instance");if(l.weight&&!Number(l.weight))throw new TypeError("Invalid argument. 'weight' attribute is not a number");this.sockets.push({socket:l.socket,weight:l.weight||0,status:wr.SOCKET_STATUS_READY})},this),this._getSocket()}return kb(f,[{key:"connect",value:function(){if(rr.debug("connect()"),this.isConnected()){rr.debug("Transport is already connected");return}else if(this.isConnecting()){rr.debug("Transport is connecting");return}this.close_requested=!1,this.status=wr.STATUS_CONNECTING,this.onconnecting({socket:this.socket,attempts:this.recover_attempts}),this.close_requested||(this.socket.onconnect=this._onConnect.bind(this),this.socket.ondisconnect=this._onDisconnect.bind(this),this.socket.ondata=this._onData.bind(this),this.socket.connect())}},{key:"disconnect",value:function(){rr.debug("close()"),this.close_requested=!0,this.recover_attempts=0,this.status=wr.STATUS_DISCONNECTED,this.recovery_timer!==null&&(clearTimeout(this.recovery_timer),this.recovery_timer=null),this.socket.onconnect=function(){},this.socket.ondisconnect=function(){},this.socket.ondata=function(){},this.socket.disconnect(),this.ondisconnect({socket:this.socket,error:!1})}},{key:"send",value:function(r){if(rr.debug("send()"),!this.isConnected())return rr.warn("unable to send message, transport is not connected"),!1;var l=r.toString();return rr.debug(`sending message:
50
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var s=!0,n=!1,g;return{s:function(){r=f[Symbol.iterator]()},n:function(){var v=r.next();return s=v.done,v},e:function(v){n=!0,g=v},f:function(){try{!s&&r.return!=null&&r.return()}finally{if(n)throw g}}}}function jS(f,t){if(f){if(typeof f=="string")return Fh(f,t);var r=Object.prototype.toString.call(f).slice(8,-1);if(r==="Object"&&f.constructor&&(r=f.constructor.name),r==="Map"||r==="Set")return Array.from(f);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return Fh(f,t)}}function Fh(f,t){(t==null||t>f.length)&&(t=f.length);for(var r=0,l=new Array(t);r<t;r++)l[r]=f[r];return l}function GS(f,t){if(!(f instanceof t))throw new TypeError("Cannot call a class as a function")}function Bh(f,t){for(var r=0;r<t.length;r++){var l=t[r];l.enumerable=l.enumerable||!1,l.configurable=!0,"value"in l&&(l.writable=!0),Object.defineProperty(f,l.key,l)}}function zh(f,t,r){return t&&Bh(f.prototype,t),r&&Bh(f,r),f}function WS(f,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");f.prototype=Object.create(t&&t.prototype,{constructor:{value:f,writable:!0,configurable:!0}}),t&&Dc(f,t)}function Dc(f,t){return Dc=Object.setPrototypeOf||function(l,u){return l.__proto__=u,l},Dc(f,t)}function KS(f){var t=QS();return function(){var l=au(f),u;if(t){var s=au(this).constructor;u=Reflect.construct(l,arguments,s)}else u=l.apply(this,arguments);return YS(this,u)}}function YS(f,t){return t&&(iu(t)==="object"||typeof t=="function")?t:JS(f)}function JS(f){if(f===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return f}function QS(){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 au(f){return au=Object.setPrototypeOf?Object.getPrototypeOf:function(r){return r.__proto__||Object.getPrototypeOf(r)},au(f)}var XS=ys.EventEmitter,Vh=sr,ZS=Ts,Ge=hs,Sa=yi,qh=ql,Qt=Bs(),Yl=vh,eb=xn,lu=rS,tb=jl,hr=mS,jh=RS,sb=kS,rb=qS,Gh=Ti(),Ee=new ZS("RTCSession"),$e={STATUS_NULL:0,STATUS_INVITE_SENT:1,STATUS_1XX_RECEIVED:2,STATUS_INVITE_RECEIVED:3,STATUS_WAITING_FOR_ANSWER:4,STATUS_ANSWERED:5,STATUS_WAITING_FOR_ACK:6,STATUS_CANCELED:7,STATUS_TERMINATED:8,STATUS_CONFIRMED:9},ou=["audio","video"],nb=function(f){WS(r,f);var t=KS(r);zh(r,null,[{key:"C",get:function(){return $e}}]);function r(l){var u;return GS(this,r),Ee.debug("new"),u=t.call(this),u._id=null,u._ua=l,u._status=$e.STATUS_NULL,u._dialog=null,u._earlyDialogs={},u._contact=null,u._from_tag=null,u._to_tag=null,u._connection=null,u._connectionPromiseQueue=Promise.resolve(),u._request=null,u._is_canceled=!1,u._cancel_reason="",u._is_confirmed=!1,u._late_sdp=!1,u._rtcOfferConstraints=null,u._rtcAnswerConstraints=null,u._localMediaStream=null,u._localMediaStreamLocallyGenerated=!1,u._rtcReady=!0,u._iceReady=!1,u._timers={ackTimer:null,expiresTimer:null,invite2xxTimer:null,userNoAnswerTimer:null},u._direction=null,u._local_identity=null,u._remote_identity=null,u._start_time=null,u._end_time=null,u._tones=null,u._audioMuted=!1,u._videoMuted=!1,u._localHold=!1,u._remoteHold=!1,u._sessionTimers={enabled:u._ua.configuration.session_timers,refreshMethod:u._ua.configuration.session_timers_refresh_method,defaultExpires:Ge.SESSION_EXPIRES,currentExpires:null,running:!1,refresher:!1,timer:null},u._referSubscribers={},u._data={},u}return zh(r,[{key:"isInProgress",value:function(){switch(this._status){case $e.STATUS_NULL:case $e.STATUS_INVITE_SENT:case $e.STATUS_1XX_RECEIVED:case $e.STATUS_INVITE_RECEIVED:case $e.STATUS_WAITING_FOR_ANSWER:return!0;default:return!1}}},{key:"isEstablished",value:function(){switch(this._status){case $e.STATUS_ANSWERED:case $e.STATUS_WAITING_FOR_ACK:case $e.STATUS_CONFIRMED:return!0;default:return!1}}},{key:"isEnded",value:function(){switch(this._status){case $e.STATUS_CANCELED:case $e.STATUS_TERMINATED:return!0;default:return!1}}},{key:"isMuted",value:function(){return{audio:this._audioMuted,video:this._videoMuted}}},{key:"isOnHold",value:function(){return{local:this._localHold,remote:this._remoteHold}}},{key:"connect",value:function(u){var s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},n=arguments.length>2?arguments[2]:void 0;Ee.debug("connect()");var g=u,_=Qt.cloneObject(s.eventHandlers),v=Qt.cloneArray(s.extraHeaders),C=Qt.cloneObject(s.mediaConstraints,{audio:!0,video:!0}),R=s.mediaStream||null,D=Qt.cloneObject(s.pcConfig,{iceServers:[]}),H=s.rtcConstraints||null,F=s.rtcOfferConstraints||null;if(this._rtcOfferConstraints=F,this._rtcAnswerConstraints=s.rtcAnswerConstraints||null,this._data=s.data||this._data,u===void 0)throw new TypeError("Not enough arguments");if(this._status!==$e.STATUS_NULL)throw new Sa.InvalidStateError(this._status);if(!window.RTCPeerConnection)throw new Sa.NotSupportedError("WebRTC not supported");if(u=this._ua.normalizeTarget(u),!u)throw new TypeError("Invalid target: ".concat(g));this._sessionTimers.enabled&&Qt.isDecimal(s.sessionTimersExpires)&&(s.sessionTimersExpires>=Ge.MIN_SESSION_EXPIRES?this._sessionTimers.defaultExpires=s.sessionTimersExpires:this._sessionTimers.defaultExpires=Ge.SESSION_EXPIRES);for(var q in _)Object.prototype.hasOwnProperty.call(_,q)&&this.on(q,_[q]);this._from_tag=Qt.newTag();var G=s.anonymous||!1,te={from_tag:this._from_tag};this._contact=this._ua.contact.toString({anonymous:G,outbound:!0}),G?(te.from_display_name="Anonymous",te.from_uri=new Gh("sip","anonymous","anonymous.invalid"),v.push("P-Preferred-Identity: ".concat(this._ua.configuration.uri.toString())),v.push("Privacy: id")):s.fromUserName&&(te.from_uri=new Gh("sip",s.fromUserName,this._ua.configuration.uri.host),v.push("P-Preferred-Identity: ".concat(this._ua.configuration.uri.toString()))),s.fromDisplayName&&(te.from_display_name=s.fromDisplayName),v.push("Contact: ".concat(this._contact)),v.push("Content-Type: application/sdp"),this._sessionTimers.enabled&&v.push("Session-Expires: ".concat(this._sessionTimers.defaultExpires).concat(this._ua.configuration.session_timers_force_refresher?";refresher=uac":"")),this._request=new eb.InitialOutgoingInviteRequest(u,this._ua,te,v),this._id=this._request.call_id+this._from_tag,this._createRTCConnection(D,H),this._direction="outgoing",this._local_identity=this._request.from,this._remote_identity=this._request.to,n&&n(this),this._newRTCSession("local",this._request),this._sendInitialRequest(C,F,R)}},{key:"init_incoming",value:function(u,s){var n=this;Ee.debug("init_incoming()");var g,_=u.hasHeader("Content-Type")?u.getHeader("Content-Type").toLowerCase():void 0;if(u.body&&_!=="application/sdp"){u.reply(415);return}if(this._status=$e.STATUS_INVITE_RECEIVED,this._from_tag=u.from_tag,this._id=u.call_id+this._from_tag,this._request=u,this._contact=this._ua.contact.toString(),u.hasHeader("expires")&&(g=u.getHeader("expires")*1e3),u.to_tag=Qt.newTag(),!this._createDialog(u,"UAS",!0)){u.reply(500,"Missing Contact header field");return}u.body?this._late_sdp=!1:this._late_sdp=!0,this._status=$e.STATUS_WAITING_FOR_ANSWER,this._timers.userNoAnswerTimer=setTimeout(function(){u.reply(408),n._failed("local",null,Ge.causes.NO_ANSWER)},this._ua.configuration.no_answer_timeout),g&&(this._timers.expiresTimer=setTimeout(function(){n._status===$e.STATUS_WAITING_FOR_ANSWER&&(u.reply(487),n._failed("system",null,Ge.causes.EXPIRES))},g)),this._direction="incoming",this._local_identity=u.to,this._remote_identity=u.from,s&&s(this),this._newRTCSession("remote",u),this._status!==$e.STATUS_TERMINATED&&(u.reply(180,null,["Contact: ".concat(this._contact)]),this._progress("local",null))}},{key:"answer",value:function(){var u=this,s=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Ee.debug("answer()");var n=this._request,g=Qt.cloneArray(s.extraHeaders),_=Qt.cloneObject(s.mediaConstraints),v=s.mediaStream||null,C=Qt.cloneObject(s.pcConfig,{iceServers:[]}),R=s.rtcConstraints||null,D=s.rtcAnswerConstraints||null,H=Qt.cloneObject(s.rtcOfferConstraints),F,q=!1,G=!1,te=!1,X=!1;if(this._rtcAnswerConstraints=D,this._rtcOfferConstraints=s.rtcOfferConstraints||null,this._data=s.data||this._data,this._direction!=="incoming")throw new Sa.NotSupportedError('"answer" not supported for outgoing RTCSession');if(this._status!==$e.STATUS_WAITING_FOR_ANSWER)throw new Sa.InvalidStateError(this._status);if(this._sessionTimers.enabled&&Qt.isDecimal(s.sessionTimersExpires)&&(s.sessionTimersExpires>=Ge.MIN_SESSION_EXPIRES?this._sessionTimers.defaultExpires=s.sessionTimersExpires:this._sessionTimers.defaultExpires=Ge.SESSION_EXPIRES),this._status=$e.STATUS_ANSWERED,!this._createDialog(n,"UAS")){n.reply(500,"Error creating dialog");return}clearTimeout(this._timers.userNoAnswerTimer),g.unshift("Contact: ".concat(this._contact));var we=n.parseSDP();Array.isArray(we.media)||(we.media=[we.media]);var Q=kn(we.media),re;try{for(Q.s();!(re=Q.n()).done;){var ke=re.value;ke.type==="audio"&&(q=!0,(!ke.direction||ke.direction==="sendrecv")&&(te=!0)),ke.type==="video"&&(G=!0,(!ke.direction||ke.direction==="sendrecv")&&(X=!0))}}catch(_e){Q.e(_e)}finally{Q.f()}if(v&&_.audio===!1){F=v.getAudioTracks();var Ne=kn(F),Z;try{for(Ne.s();!(Z=Ne.n()).done;){var se=Z.value;v.removeTrack(se)}}catch(_e){Ne.e(_e)}finally{Ne.f()}}if(v&&_.video===!1){F=v.getVideoTracks();var pe=kn(F),me;try{for(pe.s();!(me=pe.n()).done;){var be=me.value;v.removeTrack(be)}}catch(_e){pe.e(_e)}finally{pe.f()}}!v&&_.audio===void 0&&(_.audio=te),!v&&_.video===void 0&&(_.video=X),!v&&!q&&!H.offerToReceiveAudio&&(_.audio=!1),!v&&!G&&!H.offerToReceiveVideo&&(_.video=!1),this._createRTCConnection(C,R),Promise.resolve().then(function(){if(v)return v;if(_.audio||_.video)return u._localMediaStreamLocallyGenerated=!0,navigator.mediaDevices.getUserMedia(_).catch(function(_e){throw u._status===$e.STATUS_TERMINATED?new Error("terminated"):(n.reply(480),u._failed("local",null,Ge.causes.USER_DENIED_MEDIA_ACCESS),Ee.warn('emit "getusermediafailed" [error:%o]',_e),u.emit("getusermediafailed",_e),new Error("getUserMedia() failed"))})}).then(function(_e){if(u._status===$e.STATUS_TERMINATED)throw new Error("terminated");u._localMediaStream=_e,_e&&_e.getTracks().forEach(function(Ae){u._connection.addTrack(Ae,_e)})}).then(function(){if(!u._late_sdp){var _e={originator:"remote",type:"offer",sdp:n.body};Ee.debug('emit "sdp"'),u.emit("sdp",_e);var Ae=new RTCSessionDescription({type:"offer",sdp:_e.sdp});return u._connectionPromiseQueue=u._connectionPromiseQueue.then(function(){return u._connection.setRemoteDescription(Ae)}).catch(function(le){throw n.reply(488),u._failed("system",null,Ge.causes.WEBRTC_ERROR),Ee.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',le),u.emit("peerconnection:setremotedescriptionfailed",le),new Error("peerconnection.setRemoteDescription() failed")}),u._connectionPromiseQueue}}).then(function(){if(u._status===$e.STATUS_TERMINATED)throw new Error("terminated");return u._connecting(n),u._late_sdp?u._createLocalDescription("offer",u._rtcOfferConstraints).catch(function(){throw n.reply(500),new Error("_createLocalDescription() failed")}):u._createLocalDescription("answer",D).catch(function(){throw n.reply(500),new Error("_createLocalDescription() failed")})}).then(function(_e){if(u._status===$e.STATUS_TERMINATED)throw new Error("terminated");u._handleSessionTimersInIncomingRequest(n,g),n.reply(200,null,g,_e,function(){u._status=$e.STATUS_WAITING_FOR_ACK,u._setInvite2xxTimer(n,_e),u._setACKTimer(),u._accepted("local")},function(){u._failed("system",null,Ge.causes.CONNECTION_ERROR)})}).catch(function(_e){u._status!==$e.STATUS_TERMINATED&&Ee.warn(_e)})}},{key:"terminate",value:function(){var u=this,s=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Ee.debug("terminate()");var n=s.cause||Ge.causes.BYE,g=Qt.cloneArray(s.extraHeaders),_=s.body,v,C=s.status_code,R=s.reason_phrase;if(this._status===$e.STATUS_TERMINATED)throw new Sa.InvalidStateError(this._status);switch(this._status){case $e.STATUS_NULL:case $e.STATUS_INVITE_SENT:case $e.STATUS_1XX_RECEIVED:if(Ee.debug("canceling session"),C&&(C<200||C>=700))throw new TypeError("Invalid status_code: ".concat(C));C&&(R=R||Ge.REASON_PHRASE[C]||"",v="SIP ;cause=".concat(C,' ;text="').concat(R,'"')),this._status===$e.STATUS_NULL||this._status===$e.STATUS_INVITE_SENT?(this._is_canceled=!0,this._cancel_reason=v):this._status===$e.STATUS_1XX_RECEIVED&&this._request.cancel(v),this._status=$e.STATUS_CANCELED,this._failed("local",null,Ge.causes.CANCELED);break;case $e.STATUS_WAITING_FOR_ANSWER:case $e.STATUS_ANSWERED:if(Ee.debug("rejecting session"),C=C||480,C<300||C>=700)throw new TypeError("Invalid status_code: ".concat(C));this._request.reply(C,R,g,_),this._failed("local",null,Ge.causes.REJECTED);break;case $e.STATUS_WAITING_FOR_ACK:case $e.STATUS_CONFIRMED:if(Ee.debug("terminating session"),R=s.reason_phrase||Ge.REASON_PHRASE[C]||"",C&&(C<200||C>=700))throw new TypeError("Invalid status_code: ".concat(C));if(C&&g.push("Reason: SIP ;cause=".concat(C,'; text="').concat(R,'"')),this._status===$e.STATUS_WAITING_FOR_ACK&&this._direction==="incoming"&&this._request.server_transaction.state!==qh.C.STATUS_TERMINATED){var D=this._dialog;this.receiveRequest=function(H){var F=H.method;F===Ge.ACK&&(u.sendRequest(Ge.BYE,{extraHeaders:g,body:_}),D.terminate())},this._request.server_transaction.on("stateChanged",function(){u._request.server_transaction.state===qh.C.STATUS_TERMINATED&&(u.sendRequest(Ge.BYE,{extraHeaders:g,body:_}),D.terminate())}),this._ended("local",null,n),this._dialog=D,this._ua.newDialog(D)}else this.sendRequest(Ge.BYE,{extraHeaders:g,body:_}),this._ended("local",null,n)}}},{key:"sendDTMF",value:function(u){var s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};Ee.debug("sendDTMF() | tones: %s",u);var n=0,g=s.duration||null,_=s.interToneGap||null,v=s.transportType||Ge.DTMF_TRANSPORT.INFO;if(u===void 0)throw new TypeError("Not enough arguments");if(this._status!==$e.STATUS_CONFIRMED&&this._status!==$e.STATUS_WAITING_FOR_ACK&&this._status!==$e.STATUS_1XX_RECEIVED)throw new Sa.InvalidStateError(this._status);if(v!==Ge.DTMF_TRANSPORT.INFO&&v!==Ge.DTMF_TRANSPORT.RFC2833)throw new TypeError("invalid transportType: ".concat(v));if(typeof u=="number"&&(u=u.toString()),!u||typeof u!="string"||!u.match(/^[0-9A-DR#*,]+$/i))throw new TypeError("Invalid tones: ".concat(u));if(g&&!Qt.isDecimal(g))throw new TypeError("Invalid tone duration: ".concat(g));if(g?g<hr.C.MIN_DURATION?(Ee.debug('"duration" value is lower than the minimum allowed, setting it to '.concat(hr.C.MIN_DURATION," milliseconds")),g=hr.C.MIN_DURATION):g>hr.C.MAX_DURATION?(Ee.debug('"duration" value is greater than the maximum allowed, setting it to '.concat(hr.C.MAX_DURATION," milliseconds")),g=hr.C.MAX_DURATION):g=Math.abs(g):g=hr.C.DEFAULT_DURATION,s.duration=g,_&&!Qt.isDecimal(_))throw new TypeError("Invalid interToneGap: ".concat(_));if(_?_<hr.C.MIN_INTER_TONE_GAP?(Ee.debug('"interToneGap" value is lower than the minimum allowed, setting it to '.concat(hr.C.MIN_INTER_TONE_GAP," milliseconds")),_=hr.C.MIN_INTER_TONE_GAP):_=Math.abs(_):_=hr.C.DEFAULT_INTER_TONE_GAP,v===Ge.DTMF_TRANSPORT.RFC2833){var C=this._getDTMFRTPSender();C&&(u=C.toneBuffer+u,C.insertDTMF(u,g,_));return}if(this._tones){this._tones+=u;return}this._tones=u,R.call(this);function R(){var D=this,H;if(this._status===$e.STATUS_TERMINATED||!this._tones||n>=this._tones.length){this._tones=null;return}var F=this._tones[n];if(n+=1,F===",")H=2e3;else{var q=new hr(this);s.eventHandlers={onFailed:function(){D._tones=null}},q.send(F,s),H=g+_}setTimeout(R.bind(this),H)}}},{key:"sendInfo",value:function(u,s){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};if(Ee.debug("sendInfo()"),this._status!==$e.STATUS_CONFIRMED&&this._status!==$e.STATUS_WAITING_FOR_ACK&&this._status!==$e.STATUS_1XX_RECEIVED)throw new Sa.InvalidStateError(this._status);var g=new jh(this);g.send(u,s,n)}},{key:"mute",value:function(){var u=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{audio:!0,video:!1};Ee.debug("mute()");var s=!1,n=!1;this._audioMuted===!1&&u.audio&&(s=!0,this._audioMuted=!0,this._toggleMuteAudio(!0)),this._videoMuted===!1&&u.video&&(n=!0,this._videoMuted=!0,this._toggleMuteVideo(!0)),(s===!0||n===!0)&&this._onmute({audio:s,video:n})}},{key:"unmute",value:function(){var u=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{audio:!0,video:!0};Ee.debug("unmute()");var s=!1,n=!1;this._audioMuted===!0&&u.audio&&(s=!0,this._audioMuted=!1,this._localHold===!1&&this._toggleMuteAudio(!1)),this._videoMuted===!0&&u.video&&(n=!0,this._videoMuted=!1,this._localHold===!1&&this._toggleMuteVideo(!1)),(s===!0||n===!0)&&this._onunmute({audio:s,video:n})}},{key:"hold",value:function(){var u=this,s=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},n=arguments.length>1?arguments[1]:void 0;if(Ee.debug("hold()"),this._status!==$e.STATUS_WAITING_FOR_ACK&&this._status!==$e.STATUS_CONFIRMED||this._localHold===!0||!this._isReadyToReOffer())return!1;this._localHold=!0,this._onhold("local");var g={succeeded:function(){n&&n()},failed:function(){u.terminate({cause:Ge.causes.WEBRTC_ERROR,status_code:500,reason_phrase:"Hold Failed"})}};return s.useUpdate?this._sendUpdate({sdpOffer:!0,eventHandlers:g,extraHeaders:s.extraHeaders}):this._sendReinvite({eventHandlers:g,extraHeaders:s.extraHeaders}),!0}},{key:"unhold",value:function(){var u=this,s=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},n=arguments.length>1?arguments[1]:void 0;if(Ee.debug("unhold()"),this._status!==$e.STATUS_WAITING_FOR_ACK&&this._status!==$e.STATUS_CONFIRMED||this._localHold===!1||!this._isReadyToReOffer())return!1;this._localHold=!1,this._onunhold("local");var g={succeeded:function(){n&&n()},failed:function(){u.terminate({cause:Ge.causes.WEBRTC_ERROR,status_code:500,reason_phrase:"Unhold Failed"})}};return s.useUpdate?this._sendUpdate({sdpOffer:!0,eventHandlers:g,extraHeaders:s.extraHeaders}):this._sendReinvite({eventHandlers:g,extraHeaders:s.extraHeaders}),!0}},{key:"renegotiate",value:function(){var u=this,s=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},n=arguments.length>1?arguments[1]:void 0;Ee.debug("renegotiate()");var g=s.rtcOfferConstraints||null;if(this._status!==$e.STATUS_WAITING_FOR_ACK&&this._status!==$e.STATUS_CONFIRMED||!this._isReadyToReOffer())return!1;var _={succeeded:function(){n&&n()},failed:function(){u.terminate({cause:Ge.causes.WEBRTC_ERROR,status_code:500,reason_phrase:"Media Renegotiation Failed"})}};return this._setLocalMediaStatus(),s.useUpdate?this._sendUpdate({sdpOffer:!0,eventHandlers:_,rtcOfferConstraints:g,extraHeaders:s.extraHeaders}):this._sendReinvite({eventHandlers:_,rtcOfferConstraints:g,extraHeaders:s.extraHeaders}),!0}},{key:"refer",value:function(u,s){var n=this;Ee.debug("refer()");var g=u;if(this._status!==$e.STATUS_WAITING_FOR_ACK&&this._status!==$e.STATUS_CONFIRMED)return!1;if(u=this._ua.normalizeTarget(u),!u)throw new TypeError("Invalid target: ".concat(g));var _=new rb(this);_.sendRefer(u,s);var v=_.id;return this._referSubscribers[v]=_,_.on("requestFailed",function(){delete n._referSubscribers[v]}),_.on("accepted",function(){delete n._referSubscribers[v]}),_.on("failed",function(){delete n._referSubscribers[v]}),_}},{key:"sendRequest",value:function(u,s){return Ee.debug("sendRequest()"),this._dialog.sendRequest(u,s)}},{key:"receiveRequest",value:function(u){var s=this;if(Ee.debug("receiveRequest()"),u.method===Ge.CANCEL)(this._status===$e.STATUS_WAITING_FOR_ANSWER||this._status===$e.STATUS_ANSWERED)&&(this._status=$e.STATUS_CANCELED,this._request.reply(487),this._failed("remote",u,Ge.causes.CANCELED));else switch(u.method){case Ge.ACK:if(this._status!==$e.STATUS_WAITING_FOR_ACK)return;if(this._status=$e.STATUS_CONFIRMED,clearTimeout(this._timers.ackTimer),clearTimeout(this._timers.invite2xxTimer),this._late_sdp){if(!u.body){this.terminate({cause:Ge.causes.MISSING_SDP,status_code:400});break}var n={originator:"remote",type:"answer",sdp:u.body};Ee.debug('emit "sdp"'),this.emit("sdp",n);var g=new RTCSessionDescription({type:"answer",sdp:n.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(function(){return s._connection.setRemoteDescription(g)}).then(function(){s._is_confirmed||s._confirmed("remote",u)}).catch(function(v){s.terminate({cause:Ge.causes.BAD_MEDIA_DESCRIPTION,status_code:488}),Ee.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',v),s.emit("peerconnection:setremotedescriptionfailed",v)})}else this._is_confirmed||this._confirmed("remote",u);break;case Ge.BYE:this._status===$e.STATUS_CONFIRMED||this._status===$e.STATUS_WAITING_FOR_ACK?(u.reply(200),this._ended("remote",u,Ge.causes.BYE)):this._status===$e.STATUS_INVITE_RECEIVED||this._status===$e.STATUS_WAITING_FOR_ANSWER?(u.reply(200),this._request.reply(487,"BYE Received"),this._ended("remote",u,Ge.causes.BYE)):u.reply(403,"Wrong Status");break;case Ge.INVITE:this._status===$e.STATUS_CONFIRMED?u.hasHeader("replaces")?this._receiveReplaces(u):this._receiveReinvite(u):u.reply(403,"Wrong Status");break;case Ge.INFO:if(this._status===$e.STATUS_1XX_RECEIVED||this._status===$e.STATUS_WAITING_FOR_ANSWER||this._status===$e.STATUS_ANSWERED||this._status===$e.STATUS_WAITING_FOR_ACK||this._status===$e.STATUS_CONFIRMED){var _=u.hasHeader("Content-Type")?u.getHeader("Content-Type").toLowerCase():void 0;_&&_.match(/^application\/dtmf-relay/i)?new hr(this).init_incoming(u):_!==void 0?new jh(this).init_incoming(u):u.reply(415)}else u.reply(403,"Wrong Status");break;case Ge.UPDATE:this._status===$e.STATUS_CONFIRMED?this._receiveUpdate(u):u.reply(403,"Wrong Status");break;case Ge.REFER:this._status===$e.STATUS_CONFIRMED?this._receiveRefer(u):u.reply(403,"Wrong Status");break;case Ge.NOTIFY:this._status===$e.STATUS_CONFIRMED?this._receiveNotify(u):u.reply(403,"Wrong Status");break;default:u.reply(501)}}},{key:"onTransportError",value:function(){Ee.warn("onTransportError()"),this._status!==$e.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:Ge.causes.CONNECTION_ERROR,cause:Ge.causes.CONNECTION_ERROR})}},{key:"onRequestTimeout",value:function(){Ee.warn("onRequestTimeout()"),this._status!==$e.STATUS_TERMINATED&&this.terminate({status_code:408,reason_phrase:Ge.causes.REQUEST_TIMEOUT,cause:Ge.causes.REQUEST_TIMEOUT})}},{key:"onDialogError",value:function(){Ee.warn("onDialogError()"),this._status!==$e.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:Ge.causes.DIALOG_ERROR,cause:Ge.causes.DIALOG_ERROR})}},{key:"newDTMF",value:function(u){Ee.debug("newDTMF()"),this.emit("newDTMF",u)}},{key:"newInfo",value:function(u){Ee.debug("newInfo()"),this.emit("newInfo",u)}},{key:"_isReadyToReOffer",value:function(){return this._rtcReady?this._dialog?this._dialog.uac_pending_reply===!0||this._dialog.uas_pending_reply===!0?(Ee.debug("_isReadyToReOffer() | there is another INVITE/UPDATE transaction in progress"),!1):!0:(Ee.debug("_isReadyToReOffer() | session not established yet"),!1):(Ee.debug("_isReadyToReOffer() | internal WebRTC status not ready"),!1)}},{key:"_close",value:function(){if(Ee.debug("close()"),this._localMediaStream&&this._localMediaStreamLocallyGenerated&&(Ee.debug("close() | closing local MediaStream"),Qt.closeMediaStream(this._localMediaStream)),this._status!==$e.STATUS_TERMINATED){if(this._status=$e.STATUS_TERMINATED,this._connection)try{this._connection.close()}catch(g){Ee.warn("close() | error closing the RTCPeerConnection: %o",g)}for(var u in this._timers)Object.prototype.hasOwnProperty.call(this._timers,u)&&clearTimeout(this._timers[u]);clearTimeout(this._sessionTimers.timer),this._dialog&&(this._dialog.terminate(),delete this._dialog);for(var s in this._earlyDialogs)Object.prototype.hasOwnProperty.call(this._earlyDialogs,s)&&(this._earlyDialogs[s].terminate(),delete this._earlyDialogs[s]);for(var n in this._referSubscribers)Object.prototype.hasOwnProperty.call(this._referSubscribers,n)&&delete this._referSubscribers[n];this._ua.destroyRTCSession(this)}}},{key:"_setInvite2xxTimer",value:function(u,s){var n=Yl.T1;function g(){this._status===$e.STATUS_WAITING_FOR_ACK&&(u.reply(200,null,["Contact: ".concat(this._contact)],s),n<Yl.T2&&(n=n*2,n>Yl.T2&&(n=Yl.T2)),this._timers.invite2xxTimer=setTimeout(g.bind(this),n))}this._timers.invite2xxTimer=setTimeout(g.bind(this),n)}},{key:"_setACKTimer",value:function(){var u=this;this._timers.ackTimer=setTimeout(function(){u._status===$e.STATUS_WAITING_FOR_ACK&&(Ee.debug("no ACK received, terminating the session"),clearTimeout(u._timers.invite2xxTimer),u.sendRequest(Ge.BYE),u._ended("remote",null,Ge.causes.NO_ACK))},Yl.TIMER_H)}},{key:"_createRTCConnection",value:function(u,s){var n=this;this._connection=new RTCPeerConnection(u,s),this._connection.addEventListener("iceconnectionstatechange",function(){var g=n._connection.iceConnectionState;g==="failed"&&n.terminate({cause:Ge.causes.RTP_TIMEOUT,status_code:408,reason_phrase:Ge.causes.RTP_TIMEOUT})}),Ee.debug('emit "peerconnection"'),this.emit("peerconnection",{peerconnection:this._connection})}},{key:"_createLocalDescription",value:function(u,s){var n=this;if(Ee.debug("createLocalDescription()"),u!=="offer"&&u!=="answer")throw new Error('createLocalDescription() | invalid type "'.concat(u,'"'));var g=this._connection;return this._rtcReady=!1,Promise.resolve().then(function(){return u==="offer"?g.createOffer(s).catch(function(_){return Ee.warn('emit "peerconnection:createofferfailed" [error:%o]',_),n.emit("peerconnection:createofferfailed",_),Promise.reject(_)}):g.createAnswer(s).catch(function(_){return Ee.warn('emit "peerconnection:createanswerfailed" [error:%o]',_),n.emit("peerconnection:createanswerfailed",_),Promise.reject(_)})}).then(function(_){return g.setLocalDescription(_).catch(function(v){return n._rtcReady=!0,Ee.warn('emit "peerconnection:setlocaldescriptionfailed" [error:%o]',v),n.emit("peerconnection:setlocaldescriptionfailed",v),Promise.reject(v)})}).then(function(){var _=s&&s.iceRestart;if(g.iceGatheringState==="complete"&&!_||g.iceGatheringState==="gathering"&&n._iceReady){n._rtcReady=!0;var v={originator:"local",type:u,sdp:g.localDescription.sdp};return Ee.debug('emit "sdp"'),n.emit("sdp",v),Promise.resolve(v.sdp)}return new Promise(function(C){var R=!1,D,H;n._iceReady=!1;var F=function(){g.removeEventListener("icecandidate",D),g.removeEventListener("icegatheringstatechange",H),R=!0,n._rtcReady=!0,n._iceReady=!0;var G={originator:"local",type:u,sdp:g.localDescription.sdp};Ee.debug('emit "sdp"'),n.emit("sdp",G),C(G.sdp)};g.addEventListener("icecandidate",D=function(G){var te=G.candidate;te?n.emit("icecandidate",{candidate:te,ready:F}):R||F()}),g.addEventListener("icegatheringstatechange",H=function(){g.iceGatheringState==="complete"&&!R&&F()})})})}},{key:"_createDialog",value:function(u,s,n){var g=s==="UAS"?u.to_tag:u.from_tag,_=s==="UAS"?u.from_tag:u.to_tag,v=u.call_id+g+_,C=this._earlyDialogs[v];if(n)return C?!0:(C=new lu(this,u,s,lu.C.STATUS_EARLY),C.error?(Ee.debug(C.error),this._failed("remote",u,Ge.causes.INTERNAL_ERROR),!1):(this._earlyDialogs[v]=C,!0));if(this._from_tag=u.from_tag,this._to_tag=u.to_tag,C)return C.update(u,s),this._dialog=C,delete this._earlyDialogs[v],!0;var R=new lu(this,u,s);return R.error?(Ee.debug(R.error),this._failed("remote",u,Ge.causes.INTERNAL_ERROR),!1):(this._dialog=R,!0)}},{key:"_receiveReinvite",value:function(u){var s=this;Ee.debug("receiveReinvite()");var n=u.hasHeader("Content-Type")?u.getHeader("Content-Type").toLowerCase():void 0,g={request:u,callback:void 0,reject:v.bind(this)},_=!1;function v(){var R=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};_=!0;var D=R.status_code||403,H=R.reason_phrase||"",F=Qt.cloneArray(R.extraHeaders);if(this._status!==$e.STATUS_CONFIRMED)return!1;if(D<300||D>=700)throw new TypeError("Invalid status_code: ".concat(D));u.reply(D,H,F)}if(this.emit("reinvite",g),_)return;if(this._late_sdp=!1,!u.body){this._late_sdp=!0,this._remoteHold&&(this._remoteHold=!1,this._onunhold("remote")),this._connectionPromiseQueue=this._connectionPromiseQueue.then(function(){return s._createLocalDescription("offer",s._rtcOfferConstraints)}).then(function(R){C.call(s,R)}).catch(function(){u.reply(500)});return}if(n!=="application/sdp"){Ee.debug("invalid Content-Type"),u.reply(415);return}this._processInDialogSdpOffer(u).then(function(R){s._status!==$e.STATUS_TERMINATED&&C.call(s,R)}).catch(function(R){Ee.warn(R)});function C(R){var D=this,H=["Contact: ".concat(this._contact)];this._handleSessionTimersInIncomingRequest(u,H),this._late_sdp&&(R=this._mangleOffer(R)),u.reply(200,null,H,R,function(){D._status=$e.STATUS_WAITING_FOR_ACK,D._setInvite2xxTimer(u,R),D._setACKTimer()}),typeof g.callback=="function"&&g.callback()}}},{key:"_receiveUpdate",value:function(u){var s=this;Ee.debug("receiveUpdate()");var n=u.hasHeader("Content-Type")?u.getHeader("Content-Type").toLowerCase():void 0,g={request:u,callback:void 0,reject:v.bind(this)},_=!1;function v(){var R=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};_=!0;var D=R.status_code||403,H=R.reason_phrase||"",F=Qt.cloneArray(R.extraHeaders);if(this._status!==$e.STATUS_CONFIRMED)return!1;if(D<300||D>=700)throw new TypeError("Invalid status_code: ".concat(D));u.reply(D,H,F)}if(this.emit("update",g),_)return;if(!u.body){C.call(this,null);return}if(n!=="application/sdp"){Ee.debug("invalid Content-Type"),u.reply(415);return}this._processInDialogSdpOffer(u).then(function(R){s._status!==$e.STATUS_TERMINATED&&C.call(s,R)}).catch(function(R){Ee.warn(R)});function C(R){var D=["Contact: ".concat(this._contact)];this._handleSessionTimersInIncomingRequest(u,D),u.reply(200,null,D,R),typeof g.callback=="function"&&g.callback()}}},{key:"_processInDialogSdpOffer",value:function(u){var s=this;Ee.debug("_processInDialogSdpOffer()");var n=u.parseSDP(),g=!1,_=kn(n.media),v;try{for(_.s();!(v=_.n()).done;){var C=v.value;if(ou.indexOf(C.type)!==-1){var R=C.direction||n.direction||"sendrecv";if(R==="sendonly"||R==="inactive")g=!0;else{g=!1;break}}}}catch(F){_.e(F)}finally{_.f()}var D={originator:"remote",type:"offer",sdp:u.body};Ee.debug('emit "sdp"'),this.emit("sdp",D);var H=new RTCSessionDescription({type:"offer",sdp:D.sdp});return this._connectionPromiseQueue=this._connectionPromiseQueue.then(function(){if(s._status===$e.STATUS_TERMINATED)throw new Error("terminated");return s._connection.setRemoteDescription(H).catch(function(F){throw u.reply(488),Ee.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',F),s.emit("peerconnection:setremotedescriptionfailed",F),F})}).then(function(){if(s._status===$e.STATUS_TERMINATED)throw new Error("terminated");s._remoteHold===!0&&g===!1?(s._remoteHold=!1,s._onunhold("remote")):s._remoteHold===!1&&g===!0&&(s._remoteHold=!0,s._onhold("remote"))}).then(function(){if(s._status===$e.STATUS_TERMINATED)throw new Error("terminated");return s._createLocalDescription("answer",s._rtcAnswerConstraints).catch(function(F){throw u.reply(500),Ee.warn('emit "peerconnection:createtelocaldescriptionfailed" [error:%o]',F),F})}).catch(function(F){Ee.warn("_processInDialogSdpOffer() failed [error: %o]",F)}),this._connectionPromiseQueue}},{key:"_receiveRefer",value:function(u){var s=this;if(Ee.debug("receiveRefer()"),!u.refer_to){Ee.debug("no Refer-To header field present in REFER"),u.reply(400);return}if(u.refer_to.uri.scheme!==Ge.SIP){Ee.debug("Refer-To header field points to a non-SIP URI scheme"),u.reply(416);return}u.reply(202);var n=new sb(this,u.cseq);Ee.debug('emit "refer"'),this.emit("refer",{request:u,accept:function(C,R){g.call(s,C,R)},reject:function(){_.call(s)}});function g(v){var C=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(v=typeof v=="function"?v:null,this._status!==$e.STATUS_WAITING_FOR_ACK&&this._status!==$e.STATUS_CONFIRMED)return!1;var R=new r(this._ua);if(R.on("progress",function(H){var F=H.response;n.notify(F.status_code,F.reason_phrase)}),R.on("accepted",function(H){var F=H.response;n.notify(F.status_code,F.reason_phrase)}),R.on("_failed",function(H){var F=H.message,q=H.cause;F?n.notify(F.status_code,F.reason_phrase):n.notify(487,q)}),u.refer_to.uri.hasHeader("replaces")){var D=decodeURIComponent(u.refer_to.uri.getHeader("replaces"));C.extraHeaders=Qt.cloneArray(C.extraHeaders),C.extraHeaders.push("Replaces: ".concat(D))}R.connect(u.refer_to.uri.toAor(),C,v)}function _(){n.notify(603)}}},{key:"_receiveNotify",value:function(u){switch(Ee.debug("receiveNotify()"),u.event||u.reply(400),u.event.event){case"refer":{var s,n;if(u.event.params&&u.event.params.id)s=u.event.params.id,n=this._referSubscribers[s];else if(Object.keys(this._referSubscribers).length===1)n=this._referSubscribers[Object.keys(this._referSubscribers)[0]];else{u.reply(400,"Missing event id parameter");return}if(!n){u.reply(481,"Subscription does not exist");return}n.receiveNotify(u),u.reply(200);break}default:u.reply(489)}}},{key:"_receiveReplaces",value:function(u){var s=this;Ee.debug("receiveReplaces()");function n(_){var v=this;if(this._status!==$e.STATUS_WAITING_FOR_ACK&&this._status!==$e.STATUS_CONFIRMED)return!1;var C=new r(this._ua);C.on("confirmed",function(){v.terminate()}),C.init_incoming(u,_)}function g(){Ee.debug("Replaced INVITE rejected by the user"),u.reply(486)}this.emit("replaces",{request:u,accept:function(v){n.call(s,v)},reject:function(){g.call(s)}})}},{key:"_sendInitialRequest",value:function(u,s,n){var g=this,_=new tb(this._ua,this._request,{onRequestTimeout:function(){g.onRequestTimeout()},onTransportError:function(){g.onTransportError()},onAuthenticated:function(C){g._request=C},onReceiveResponse:function(C){g._receiveInviteResponse(C)}});Promise.resolve().then(function(){if(n)return n;if(u.audio||u.video)return g._localMediaStreamLocallyGenerated=!0,navigator.mediaDevices.getUserMedia(u).catch(function(v){throw g._status===$e.STATUS_TERMINATED?new Error("terminated"):(g._failed("local",null,Ge.causes.USER_DENIED_MEDIA_ACCESS),Ee.warn('emit "getusermediafailed" [error:%o]',v),g.emit("getusermediafailed",v),v)})}).then(function(v){if(g._status===$e.STATUS_TERMINATED)throw new Error("terminated");return g._localMediaStream=v,v&&v.getTracks().forEach(function(C){g._connection.addTrack(C,v)}),g._connecting(g._request),g._createLocalDescription("offer",s).catch(function(C){throw g._failed("local",null,Ge.causes.WEBRTC_ERROR),C})}).then(function(v){if(g._is_canceled||g._status===$e.STATUS_TERMINATED)throw new Error("terminated");g._request.body=v,g._status=$e.STATUS_INVITE_SENT,Ee.debug('emit "sending" [request:%o]',g._request),g.emit("sending",{request:g._request}),_.send()}).catch(function(v){g._status!==$e.STATUS_TERMINATED&&Ee.warn(v)})}},{key:"_getDTMFRTPSender",value:function(){var u=this._connection.getSenders().find(function(s){return s.track&&s.track.kind==="audio"});if(!(u&&u.dtmf)){Ee.warn("sendDTMF() | no local audio track to send DTMF with");return}return u.dtmf}},{key:"_receiveInviteResponse",value:function(u){var s=this;if(Ee.debug("receiveInviteResponse()"),this._dialog&&u.status_code>=200&&u.status_code<=299)if(this._dialog.id.call_id===u.call_id&&this._dialog.id.local_tag===u.from_tag&&this._dialog.id.remote_tag===u.to_tag){this.sendRequest(Ge.ACK);return}else{var n=new lu(this,u,"UAC");if(n.error!==void 0){Ee.debug(n.error);return}this.sendRequest(Ge.ACK),this.sendRequest(Ge.BYE);return}if(this._is_canceled){u.status_code>=100&&u.status_code<200?this._request.cancel(this._cancel_reason):u.status_code>=200&&u.status_code<299&&this._acceptAndTerminate(u);return}if(!(this._status!==$e.STATUS_INVITE_SENT&&this._status!==$e.STATUS_1XX_RECEIVED))switch(!0){case/^100$/.test(u.status_code):this._status=$e.STATUS_1XX_RECEIVED;break;case/^1[0-9]{2}$/.test(u.status_code):{if(!u.to_tag){Ee.debug("1xx response received without to tag");break}if(u.hasHeader("contact")&&!this._createDialog(u,"UAC",!0))break;if(this._status=$e.STATUS_1XX_RECEIVED,!u.body){this._progress("remote",u);break}var g={originator:"remote",type:"answer",sdp:u.body};Ee.debug('emit "sdp"'),this.emit("sdp",g);var _=new RTCSessionDescription({type:"answer",sdp:g.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(function(){return s._connection.setRemoteDescription(_)}).then(function(){return s._progress("remote",u)}).catch(function(D){Ee.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',D),s.emit("peerconnection:setremotedescriptionfailed",D)});break}case/^2[0-9]{2}$/.test(u.status_code):{if(this._status=$e.STATUS_CONFIRMED,!u.body){this._acceptAndTerminate(u,400,Ge.causes.MISSING_SDP),this._failed("remote",u,Ge.causes.BAD_MEDIA_DESCRIPTION);break}if(!this._createDialog(u,"UAC"))break;var v={originator:"remote",type:"answer",sdp:u.body};Ee.debug('emit "sdp"'),this.emit("sdp",v);var C=new RTCSessionDescription({type:"answer",sdp:v.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(function(){if(s._connection.signalingState==="stable")return s._connection.createOffer(s._rtcOfferConstraints).then(function(D){return s._connection.setLocalDescription(D)}).catch(function(D){s._acceptAndTerminate(u,500,D.toString()),s._failed("local",u,Ge.causes.WEBRTC_ERROR)})}).then(function(){s._connection.setRemoteDescription(C).then(function(){s._handleSessionTimersInIncomingResponse(u),s._accepted("remote",u),s.sendRequest(Ge.ACK),s._confirmed("local",null)}).catch(function(D){s._acceptAndTerminate(u,488,"Not Acceptable Here"),s._failed("remote",u,Ge.causes.BAD_MEDIA_DESCRIPTION),Ee.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',D),s.emit("peerconnection:setremotedescriptionfailed",D)})});break}default:{var R=Qt.sipErrorCause(u.status_code);this._failed("remote",u,R)}}}},{key:"_sendReinvite",value:function(){var u=this,s=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Ee.debug("sendReinvite()");var n=Qt.cloneArray(s.extraHeaders),g=Qt.cloneObject(s.eventHandlers),_=s.rtcOfferConstraints||this._rtcOfferConstraints||null,v=!1;n.push("Contact: ".concat(this._contact)),n.push("Content-Type: application/sdp"),this._sessionTimers.running&&n.push("Session-Expires: ".concat(this._sessionTimers.currentExpires,";refresher=").concat(this._sessionTimers.refresher?"uac":"uas")),this._connectionPromiseQueue=this._connectionPromiseQueue.then(function(){return u._createLocalDescription("offer",_)}).then(function(D){D=u._mangleOffer(D);var H={originator:"local",type:"offer",sdp:D};Ee.debug('emit "sdp"'),u.emit("sdp",H),u.sendRequest(Ge.INVITE,{extraHeaders:n,body:D,eventHandlers:{onSuccessResponse:function(q){C.call(u,q),v=!0},onErrorResponse:function(q){R.call(u,q)},onTransportError:function(){u.onTransportError()},onRequestTimeout:function(){u.onRequestTimeout()},onDialogError:function(){u.onDialogError()}}})}).catch(function(){R()});function C(D){var H=this;if(this._status!==$e.STATUS_TERMINATED&&(this.sendRequest(Ge.ACK),!v)){if(this._handleSessionTimersInIncomingResponse(D),D.body){if(!D.hasHeader("Content-Type")||D.getHeader("Content-Type").toLowerCase()!=="application/sdp"){R.call(this);return}}else{R.call(this);return}var F={originator:"remote",type:"answer",sdp:D.body};Ee.debug('emit "sdp"'),this.emit("sdp",F);var q=new RTCSessionDescription({type:"answer",sdp:F.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(function(){return H._connection.setRemoteDescription(q)}).then(function(){g.succeeded&&g.succeeded(D)}).catch(function(G){R.call(H),Ee.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',G),H.emit("peerconnection:setremotedescriptionfailed",G)})}}function R(D){g.failed&&g.failed(D)}}},{key:"_sendUpdate",value:function(){var u=this,s=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Ee.debug("sendUpdate()");var n=Qt.cloneArray(s.extraHeaders),g=Qt.cloneObject(s.eventHandlers),_=s.rtcOfferConstraints||this._rtcOfferConstraints||null,v=s.sdpOffer||!1,C=!1;n.push("Contact: ".concat(this._contact)),this._sessionTimers.running&&n.push("Session-Expires: ".concat(this._sessionTimers.currentExpires,";refresher=").concat(this._sessionTimers.refresher?"uac":"uas")),v?(n.push("Content-Type: application/sdp"),this._connectionPromiseQueue=this._connectionPromiseQueue.then(function(){return u._createLocalDescription("offer",_)}).then(function(H){H=u._mangleOffer(H);var F={originator:"local",type:"offer",sdp:H};Ee.debug('emit "sdp"'),u.emit("sdp",F),u.sendRequest(Ge.UPDATE,{extraHeaders:n,body:H,eventHandlers:{onSuccessResponse:function(G){R.call(u,G),C=!0},onErrorResponse:function(G){D.call(u,G)},onTransportError:function(){u.onTransportError()},onRequestTimeout:function(){u.onRequestTimeout()},onDialogError:function(){u.onDialogError()}}})}).catch(function(){D.call(u)})):this.sendRequest(Ge.UPDATE,{extraHeaders:n,eventHandlers:{onSuccessResponse:function(F){R.call(u,F)},onErrorResponse:function(F){D.call(u,F)},onTransportError:function(){u.onTransportError()},onRequestTimeout:function(){u.onRequestTimeout()},onDialogError:function(){u.onDialogError()}}});function R(H){var F=this;if(this._status!==$e.STATUS_TERMINATED&&!C)if(this._handleSessionTimersInIncomingResponse(H),v){if(H.body){if(!H.hasHeader("Content-Type")||H.getHeader("Content-Type").toLowerCase()!=="application/sdp"){D.call(this);return}}else{D.call(this);return}var q={originator:"remote",type:"answer",sdp:H.body};Ee.debug('emit "sdp"'),this.emit("sdp",q);var G=new RTCSessionDescription({type:"answer",sdp:q.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(function(){return F._connection.setRemoteDescription(G)}).then(function(){g.succeeded&&g.succeeded(H)}).catch(function(te){D.call(F),Ee.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',te),F.emit("peerconnection:setremotedescriptionfailed",te)})}else g.succeeded&&g.succeeded(H)}function D(H){g.failed&&g.failed(H)}}},{key:"_acceptAndTerminate",value:function(u,s,n){Ee.debug("acceptAndTerminate()");var g=[];s&&(n=n||Ge.REASON_PHRASE[s]||"",g.push("Reason: SIP ;cause=".concat(s,'; text="').concat(n,'"'))),(this._dialog||this._createDialog(u,"UAC"))&&(this.sendRequest(Ge.ACK),this.sendRequest(Ge.BYE,{extraHeaders:g})),this._status=$e.STATUS_TERMINATED}},{key:"_mangleOffer",value:function(u){if(!this._localHold&&!this._remoteHold)return u;if(u=Vh.parse(u),this._localHold&&!this._remoteHold){Ee.debug("mangleOffer() | me on hold, mangling offer");var s=kn(u.media),n;try{for(s.s();!(n=s.n()).done;){var g=n.value;ou.indexOf(g.type)!==-1&&(g.direction?g.direction==="sendrecv"?g.direction="sendonly":g.direction==="recvonly"&&(g.direction="inactive"):g.direction="sendonly")}}catch(F){s.e(F)}finally{s.f()}}else if(this._localHold&&this._remoteHold){Ee.debug("mangleOffer() | both on hold, mangling offer");var _=kn(u.media),v;try{for(_.s();!(v=_.n()).done;){var C=v.value;ou.indexOf(C.type)!==-1&&(C.direction="inactive")}}catch(F){_.e(F)}finally{_.f()}}else if(this._remoteHold){Ee.debug("mangleOffer() | remote on hold, mangling offer");var R=kn(u.media),D;try{for(R.s();!(D=R.n()).done;){var H=D.value;ou.indexOf(H.type)!==-1&&(H.direction?H.direction==="sendrecv"?H.direction="recvonly":H.direction==="recvonly"&&(H.direction="inactive"):H.direction="recvonly")}}catch(F){R.e(F)}finally{R.f()}}return Vh.write(u)}},{key:"_setLocalMediaStatus",value:function(){var u=!0,s=!0;(this._localHold||this._remoteHold)&&(u=!1,s=!1),this._audioMuted&&(u=!1),this._videoMuted&&(s=!1),this._toggleMuteAudio(!u),this._toggleMuteVideo(!s)}},{key:"_handleSessionTimersInIncomingRequest",value:function(u,s){if(this._sessionTimers.enabled){var n;u.session_expires&&u.session_expires>=Ge.MIN_SESSION_EXPIRES?(this._sessionTimers.currentExpires=u.session_expires,n=u.session_expires_refresher||"uas"):(this._sessionTimers.currentExpires=this._sessionTimers.defaultExpires,n="uas"),s.push("Session-Expires: ".concat(this._sessionTimers.currentExpires,";refresher=").concat(n)),this._sessionTimers.refresher=n==="uas",this._runSessionTimer()}}},{key:"_handleSessionTimersInIncomingResponse",value:function(u){if(this._sessionTimers.enabled){var s;u.session_expires&&u.session_expires>=Ge.MIN_SESSION_EXPIRES?(this._sessionTimers.currentExpires=u.session_expires,s=u.session_expires_refresher||"uac"):(this._sessionTimers.currentExpires=this._sessionTimers.defaultExpires,s="uac"),this._sessionTimers.refresher=s==="uac",this._runSessionTimer()}}},{key:"_runSessionTimer",value:function(){var u=this,s=this._sessionTimers.currentExpires;this._sessionTimers.running=!0,clearTimeout(this._sessionTimers.timer),this._sessionTimers.refresher?this._sessionTimers.timer=setTimeout(function(){u._status!==$e.STATUS_TERMINATED&&u._isReadyToReOffer()&&(Ee.debug("runSessionTimer() | sending session refresh request"),u._sessionTimers.refreshMethod===Ge.UPDATE?u._sendUpdate():u._sendReinvite())},s*500):this._sessionTimers.timer=setTimeout(function(){u._status!==$e.STATUS_TERMINATED&&(Ee.warn("runSessionTimer() | timer expired, terminating the session"),u.terminate({cause:Ge.causes.REQUEST_TIMEOUT,status_code:408,reason_phrase:"Session Timer Expired"}))},s*1100)}},{key:"_toggleMuteAudio",value:function(u){var s=this._connection.getSenders().filter(function(v){return v.track&&v.track.kind==="audio"}),n=kn(s),g;try{for(n.s();!(g=n.n()).done;){var _=g.value;_.track.enabled=!u}}catch(v){n.e(v)}finally{n.f()}}},{key:"_toggleMuteVideo",value:function(u){var s=this._connection.getSenders().filter(function(v){return v.track&&v.track.kind==="video"}),n=kn(s),g;try{for(n.s();!(g=n.n()).done;){var _=g.value;_.track.enabled=!u}}catch(v){n.e(v)}finally{n.f()}}},{key:"_newRTCSession",value:function(u,s){Ee.debug("newRTCSession()"),this._ua.newRTCSession(this,{originator:u,session:this,request:s})}},{key:"_connecting",value:function(u){Ee.debug("session connecting"),Ee.debug('emit "connecting"'),this.emit("connecting",{request:u})}},{key:"_progress",value:function(u,s){Ee.debug("session progress"),Ee.debug('emit "progress"'),this.emit("progress",{originator:u,response:s||null})}},{key:"_accepted",value:function(u,s){Ee.debug("session accepted"),this._start_time=new Date,Ee.debug('emit "accepted"'),this.emit("accepted",{originator:u,response:s||null})}},{key:"_confirmed",value:function(u,s){Ee.debug("session confirmed"),this._is_confirmed=!0,Ee.debug('emit "confirmed"'),this.emit("confirmed",{originator:u,ack:s||null})}},{key:"_ended",value:function(u,s,n){Ee.debug("session ended"),this._end_time=new Date,this._close(),Ee.debug('emit "ended"'),this.emit("ended",{originator:u,message:s||null,cause:n})}},{key:"_failed",value:function(u,s,n){Ee.debug("session failed"),Ee.debug('emit "_failed"'),this.emit("_failed",{originator:u,message:s||null,cause:n}),this._close(),Ee.debug('emit "failed"'),this.emit("failed",{originator:u,message:s||null,cause:n})}},{key:"_onhold",value:function(u){Ee.debug("session onhold"),this._setLocalMediaStatus(),Ee.debug('emit "hold"'),this.emit("hold",{originator:u})}},{key:"_onunhold",value:function(u){Ee.debug("session onunhold"),this._setLocalMediaStatus(),Ee.debug('emit "unhold"'),this.emit("unhold",{originator:u})}},{key:"_onmute",value:function(u){var s=u.audio,n=u.video;Ee.debug("session onmute"),this._setLocalMediaStatus(),Ee.debug('emit "muted"'),this.emit("muted",{audio:s,video:n})}},{key:"_onunmute",value:function(u){var s=u.audio,n=u.video;Ee.debug("session onunmute"),this._setLocalMediaStatus(),Ee.debug('emit "unmuted"'),this.emit("unmuted",{audio:s,video:n})}},{key:"C",get:function(){return $e}},{key:"causes",get:function(){return Ge.causes}},{key:"id",get:function(){return this._id}},{key:"connection",get:function(){return this._connection}},{key:"contact",get:function(){return this._contact}},{key:"direction",get:function(){return this._direction}},{key:"local_identity",get:function(){return this._local_identity}},{key:"remote_identity",get:function(){return this._remote_identity}},{key:"start_time",get:function(){return this._start_time}},{key:"end_time",get:function(){return this._end_time}},{key:"data",get:function(){return this._data},set:function(u){this._data=u}},{key:"status",get:function(){return this._status}}]),r}(XS);function uu(f){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?uu=function(r){return typeof r}:uu=function(r){return r&&typeof Symbol=="function"&&r.constructor===Symbol&&r!==Symbol.prototype?"symbol":typeof r},uu(f)}function ib(f,t){if(!(f instanceof t))throw new TypeError("Cannot call a class as a function")}function Wh(f,t){for(var r=0;r<t.length;r++){var l=t[r];l.enumerable=l.enumerable||!1,l.configurable=!0,"value"in l&&(l.writable=!0),Object.defineProperty(f,l.key,l)}}function ab(f,t,r){return t&&Wh(f.prototype,t),r&&Wh(f,r),f}function lb(f,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");f.prototype=Object.create(t&&t.prototype,{constructor:{value:f,writable:!0,configurable:!0}}),t&&kc(f,t)}function kc(f,t){return kc=Object.setPrototypeOf||function(l,u){return l.__proto__=u,l},kc(f,t)}function ob(f){var t=db();return function(){var l=cu(f),u;if(t){var s=cu(this).constructor;u=Reflect.construct(l,arguments,s)}else u=l.apply(this,arguments);return ub(this,u)}}function ub(f,t){return t&&(uu(t)==="object"||typeof t=="function")?t:cb(f)}function cb(f){if(f===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return f}function db(){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 cu(f){return cu=Object.setPrototypeOf?Object.getPrototypeOf:function(r){return r.__proto__||Object.getPrototypeOf(r)},cu(f)}var fb=ys.EventEmitter,hb=Ts,Nc=hs,_b=xn,Jl=Bs(),pb=jl,Kh=yi,mb=Ti(),du=new hb("Message"),gb=function(f){lb(r,f);var t=ob(r);function r(l){var u;return ib(this,r),u=t.call(this),u._ua=l,u._request=null,u._closed=!1,u._direction=null,u._local_identity=null,u._remote_identity=null,u._is_replied=!1,u._data={},u}return ab(r,[{key:"send",value:function(u,s){var n=this,g=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},_=u;if(u===void 0||s===void 0)throw new TypeError("Not enough arguments");if(u=this._ua.normalizeTarget(u),!u)throw new TypeError("Invalid target: ".concat(_));var v=Jl.cloneArray(g.extraHeaders),C=Jl.cloneObject(g.eventHandlers),R=g.contentType||"text/plain",D={};g.fromUserName&&(D.from_uri=new mb("sip",g.fromUserName,this._ua.configuration.uri.host),v.push("P-Preferred-Identity: ".concat(this._ua.configuration.uri.toString()))),g.fromDisplayName&&(D.from_display_name=g.fromDisplayName);for(var H in C)Object.prototype.hasOwnProperty.call(C,H)&&this.on(H,C[H]);v.push("Content-Type: ".concat(R)),this._request=new _b.OutgoingRequest(Nc.MESSAGE,u,this._ua,D,v),s&&(this._request.body=s);var F=new pb(this._ua,this._request,{onRequestTimeout:function(){n._onRequestTimeout()},onTransportError:function(){n._onTransportError()},onReceiveResponse:function(G){n._receiveResponse(G)}});this._newMessage("local",this._request),F.send()}},{key:"init_incoming",value:function(u){this._request=u,this._newMessage("remote",u),this._is_replied||(this._is_replied=!0,u.reply(200)),this._close()}},{key:"accept",value:function(){var u=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},s=Jl.cloneArray(u.extraHeaders),n=u.body;if(this._direction!=="incoming")throw new Kh.NotSupportedError('"accept" not supported for outgoing Message');if(this._is_replied)throw new Error("incoming Message already replied");this._is_replied=!0,this._request.reply(200,null,s,n)}},{key:"reject",value:function(){var u=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},s=u.status_code||480,n=u.reason_phrase,g=Jl.cloneArray(u.extraHeaders),_=u.body;if(this._direction!=="incoming")throw new Kh.NotSupportedError('"reject" not supported for outgoing Message');if(this._is_replied)throw new Error("incoming Message already replied");if(s<300||s>=700)throw new TypeError("Invalid status_code: ".concat(s));this._is_replied=!0,this._request.reply(s,n,g,_)}},{key:"_receiveResponse",value:function(u){if(!this._closed)switch(!0){case/^1[0-9]{2}$/.test(u.status_code):break;case/^2[0-9]{2}$/.test(u.status_code):this._succeeded("remote",u);break;default:{var s=Jl.sipErrorCause(u.status_code);this._failed("remote",u,s);break}}}},{key:"_onRequestTimeout",value:function(){this._closed||this._failed("system",null,Nc.causes.REQUEST_TIMEOUT)}},{key:"_onTransportError",value:function(){this._closed||this._failed("system",null,Nc.causes.CONNECTION_ERROR)}},{key:"_close",value:function(){this._closed=!0,this._ua.destroyMessage(this)}},{key:"_newMessage",value:function(u,s){u==="remote"?(this._direction="incoming",this._local_identity=s.to,this._remote_identity=s.from):u==="local"&&(this._direction="outgoing",this._local_identity=s.from,this._remote_identity=s.to),this._ua.newMessage(this,{originator:u,message:this,request:s})}},{key:"_failed",value:function(u,s,n){du.debug("MESSAGE failed"),this._close(),du.debug('emit "failed"'),this.emit("failed",{originator:u,response:s||null,cause:n})}},{key:"_succeeded",value:function(u,s){du.debug("MESSAGE succeeded"),this._close(),du.debug('emit "succeeded"'),this.emit("succeeded",{originator:u,response:s})}},{key:"direction",get:function(){return this._direction}},{key:"local_identity",get:function(){return this._local_identity}},{key:"remote_identity",get:function(){return this._remote_identity}}]),r}(fb);function fu(f){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?fu=function(r){return typeof r}:fu=function(r){return r&&typeof Symbol=="function"&&r.constructor===Symbol&&r!==Symbol.prototype?"symbol":typeof r},fu(f)}function vb(f,t){if(!(f instanceof t))throw new TypeError("Cannot call a class as a function")}function Yh(f,t){for(var r=0;r<t.length;r++){var l=t[r];l.enumerable=l.enumerable||!1,l.configurable=!0,"value"in l&&(l.writable=!0),Object.defineProperty(f,l.key,l)}}function yb(f,t,r){return t&&Yh(f.prototype,t),r&&Yh(f,r),f}function Tb(f,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");f.prototype=Object.create(t&&t.prototype,{constructor:{value:f,writable:!0,configurable:!0}}),t&&Mc(f,t)}function Mc(f,t){return Mc=Object.setPrototypeOf||function(l,u){return l.__proto__=u,l},Mc(f,t)}function Sb(f){var t=Eb();return function(){var l=hu(f),u;if(t){var s=hu(this).constructor;u=Reflect.construct(l,arguments,s)}else u=l.apply(this,arguments);return bb(this,u)}}function bb(f,t){return t&&(fu(t)==="object"||typeof t=="function")?t:wb(f)}function wb(f){if(f===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return f}function Eb(){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 hu(f){return hu=Object.setPrototypeOf?Object.getPrototypeOf:function(r){return r.__proto__||Object.getPrototypeOf(r)},hu(f)}var Cb=ys.EventEmitter,Ab=Ts,Uc=hs,Ib=xn,Ql=Bs(),Rb=jl,Jh=yi,_u=new Ab("Options"),$b=function(f){Tb(r,f);var t=Sb(r);function r(l){var u;return vb(this,r),u=t.call(this),u._ua=l,u._request=null,u._closed=!1,u._direction=null,u._local_identity=null,u._remote_identity=null,u._is_replied=!1,u._data={},u}return yb(r,[{key:"send",value:function(u,s){var n=this,g=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},_=u;if(u===void 0)throw new TypeError("A target is required for OPTIONS");if(u=this._ua.normalizeTarget(u),!u)throw new TypeError("Invalid target: ".concat(_));var v=Ql.cloneArray(g.extraHeaders),C=Ql.cloneObject(g.eventHandlers),R=g.contentType||"application/sdp";for(var D in C)Object.prototype.hasOwnProperty.call(C,D)&&this.on(D,C[D]);v.push("Content-Type: ".concat(R)),this._request=new Ib.OutgoingRequest(Uc.OPTIONS,u,this._ua,null,v),s&&(this._request.body=s);var H=new Rb(this._ua,this._request,{onRequestTimeout:function(){n._onRequestTimeout()},onTransportError:function(){n._onTransportError()},onReceiveResponse:function(q){n._receiveResponse(q)}});this._newOptions("local",this._request),H.send()}},{key:"init_incoming",value:function(u){this._request=u,this._newOptions("remote",u),this._is_replied||(this._is_replied=!0,u.reply(200)),this._close()}},{key:"accept",value:function(){var u=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},s=Ql.cloneArray(u.extraHeaders),n=u.body;if(this._direction!=="incoming")throw new Jh.NotSupportedError('"accept" not supported for outgoing Options');if(this._is_replied)throw new Error("incoming Options already replied");this._is_replied=!0,this._request.reply(200,null,s,n)}},{key:"reject",value:function(){var u=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},s=u.status_code||480,n=u.reason_phrase,g=Ql.cloneArray(u.extraHeaders),_=u.body;if(this._direction!=="incoming")throw new Jh.NotSupportedError('"reject" not supported for outgoing Options');if(this._is_replied)throw new Error("incoming Options already replied");if(s<300||s>=700)throw new TypeError("Invalid status_code: ".concat(s));this._is_replied=!0,this._request.reply(s,n,g,_)}},{key:"_receiveResponse",value:function(u){if(!this._closed)switch(!0){case/^1[0-9]{2}$/.test(u.status_code):break;case/^2[0-9]{2}$/.test(u.status_code):this._succeeded("remote",u);break;default:{var s=Ql.sipErrorCause(u.status_code);this._failed("remote",u,s);break}}}},{key:"_onRequestTimeout",value:function(){this._closed||this._failed("system",null,Uc.causes.REQUEST_TIMEOUT)}},{key:"_onTransportError",value:function(){this._closed||this._failed("system",null,Uc.causes.CONNECTION_ERROR)}},{key:"_close",value:function(){this._closed=!0,this._ua.destroyMessage(this)}},{key:"_newOptions",value:function(u,s){u==="remote"?(this._direction="incoming",this._local_identity=s.to,this._remote_identity=s.from):u==="local"&&(this._direction="outgoing",this._local_identity=s.from,this._remote_identity=s.to),this._ua.newOptions(this,{originator:u,message:this,request:s})}},{key:"_failed",value:function(u,s,n){_u.debug("OPTIONS failed"),this._close(),_u.debug('emit "failed"'),this.emit("failed",{originator:u,response:s||null,cause:n})}},{key:"_succeeded",value:function(u,s){_u.debug("OPTIONS succeeded"),this._close(),_u.debug('emit "succeeded"'),this.emit("succeeded",{originator:u,response:s})}},{key:"direction",get:function(){return this._direction}},{key:"local_identity",get:function(){return this._local_identity}},{key:"remote_identity",get:function(){return this._remote_identity}}]),r}(Cb),Pc={},xb=Ts,Lc=Bs(),Ob=on(),Xl=new xb("Socket");Pc.isSocket=function(f){if(Array.isArray(f))return!1;if(typeof f>"u")return Xl.warn("undefined JsSIP.Socket instance"),!1;try{if(!Lc.isString(f.url))throw Xl.warn("missing or invalid JsSIP.Socket url property"),new Error("Missing or invalid JsSIP.Socket url property");if(!Lc.isString(f.via_transport))throw Xl.warn("missing or invalid JsSIP.Socket via_transport property"),new Error("Missing or invalid JsSIP.Socket via_transport property");if(Ob.parse(f.sip_uri,"SIP_URI")===-1)throw Xl.warn("missing or invalid JsSIP.Socket sip_uri property"),new Error("missing or invalid JsSIP.Socket sip_uri property")}catch{return!1}try{["connect","disconnect","send"].forEach(function(t){if(!Lc.isFunction(f[t]))throw Xl.warn("missing or invalid JsSIP.Socket method: ".concat(t)),new Error("Missing or invalid JsSIP.Socket method: ".concat(t))})}catch{return!1}return!0};function Db(f,t){if(!(f instanceof t))throw new TypeError("Cannot call a class as a function")}function Qh(f,t){for(var r=0;r<t.length;r++){var l=t[r];l.enumerable=l.enumerable||!1,l.configurable=!0,"value"in l&&(l.writable=!0),Object.defineProperty(f,l.key,l)}}function kb(f,t,r){return t&&Qh(f.prototype,t),r&&Qh(f,r),f}var Nb=Ts,Mb=Pc,Xh=hs,rr=new Nb("Transport"),wr={STATUS_CONNECTED:0,STATUS_CONNECTING:1,STATUS_DISCONNECTED:2,SOCKET_STATUS_READY:0,SOCKET_STATUS_ERROR:1,recovery_options:{min_interval:Xh.CONNECTION_RECOVERY_MIN_INTERVAL,max_interval:Xh.CONNECTION_RECOVERY_MAX_INTERVAL}},Ub=function(){function f(t){var r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:wr.recovery_options;Db(this,f),rr.debug("new()"),this.status=wr.STATUS_DISCONNECTED,this.socket=null,this.sockets=[],this.recovery_options=r,this.recover_attempts=0,this.recovery_timer=null,this.close_requested=!1;try{this.textDecoder=new TextDecoder("utf8")}catch(l){rr.warn("cannot use TextDecoder: ".concat(l))}if(typeof t>"u")throw new TypeError("Invalid argument. undefined 'sockets' argument");t instanceof Array||(t=[t]),t.forEach(function(l){if(!Mb.isSocket(l.socket))throw new TypeError("Invalid argument. invalid 'JsSIP.Socket' instance");if(l.weight&&!Number(l.weight))throw new TypeError("Invalid argument. 'weight' attribute is not a number");this.sockets.push({socket:l.socket,weight:l.weight||0,status:wr.SOCKET_STATUS_READY})},this),this._getSocket()}return kb(f,[{key:"connect",value:function(){if(rr.debug("connect()"),this.isConnected()){rr.debug("Transport is already connected");return}else if(this.isConnecting()){rr.debug("Transport is connecting");return}this.close_requested=!1,this.status=wr.STATUS_CONNECTING,this.onconnecting({socket:this.socket,attempts:this.recover_attempts}),this.close_requested||(this.socket.onconnect=this._onConnect.bind(this),this.socket.ondisconnect=this._onDisconnect.bind(this),this.socket.ondata=this._onData.bind(this),this.socket.connect())}},{key:"disconnect",value:function(){rr.debug("close()"),this.close_requested=!0,this.recover_attempts=0,this.status=wr.STATUS_DISCONNECTED,this.recovery_timer!==null&&(clearTimeout(this.recovery_timer),this.recovery_timer=null),this.socket.onconnect=function(){},this.socket.ondisconnect=function(){},this.socket.ondata=function(){},this.socket.disconnect(),this.ondisconnect({socket:this.socket,error:!1})}},{key:"send",value:function(r){if(rr.debug("send()"),!this.isConnected())return rr.warn("unable to send message, transport is not connected"),!1;var l=r.toString();return rr.debug(`sending message:
51
51
 
52
52
  `.concat(l,`
53
53
  `)),this.socket.send(l)}},{key:"isConnected",value:function(){return this.status===wr.STATUS_CONNECTED}},{key:"isConnecting",value:function(){return this.status===wr.STATUS_CONNECTING}},{key:"_reconnect",value:function(){var r=this;this.recover_attempts+=1;var l=Math.floor(Math.random()*Math.pow(2,this.recover_attempts)+1);l<this.recovery_options.min_interval?l=this.recovery_options.min_interval:l>this.recovery_options.max_interval&&(l=this.recovery_options.max_interval),rr.debug("reconnection attempt: ".concat(this.recover_attempts,". next connection attempt in ").concat(l," seconds")),this.recovery_timer=setTimeout(function(){!r.close_requested&&!(r.isConnected()||r.isConnecting())&&(r._getSocket(),r.connect())},l*1e3)}},{key:"_getSocket",value:function(){var r=[];if(this.sockets.forEach(function(u){u.status!==wr.SOCKET_STATUS_ERROR&&(r.length===0?r.push(u):u.weight>r[0].weight?r=[u]:u.weight===r[0].weight&&r.push(u))}),r.length===0){this.sockets.forEach(function(u){u.status=wr.SOCKET_STATUS_READY}),this._getSocket();return}var l=Math.floor(Math.random()*r.length);this.socket=r[l].socket}},{key:"_onConnect",value:function(){this.recover_attempts=0,this.status=wr.STATUS_CONNECTED,this.recovery_timer!==null&&(clearTimeout(this.recovery_timer),this.recovery_timer=null),this.onconnect({socket:this})}},{key:"_onDisconnect",value:function(r,l,u){this.status=wr.STATUS_DISCONNECTED,this.ondisconnect({socket:this.socket,error:r,code:l,reason:u}),!this.close_requested&&(this.sockets.forEach(function(s){this.socket===s.socket&&(s.status=wr.SOCKET_STATUS_ERROR)},this),this._reconnect(r))}},{key:"_onData",value:function(r){if(r===`\r
@@ -57,22 +57,22 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
57
57
  `))}else rr.debug(`received text message:
58
58
 
59
59
  `.concat(r,`
60
- `));this.ondata({transport:this,message:r})}},{key:"via_transport",get:function(){return this.socket.via_transport}},{key:"url",get:function(){return this.socket.url}},{key:"sip_uri",get:function(){return this.socket.sip_uri}}]),f}(),e_={};function t_(f,t){var r;if(typeof Symbol>"u"||f[Symbol.iterator]==null){if(Array.isArray(f)||(r=Pb(f))||t&&f&&typeof f.length=="number"){r&&(f=r);var l=0,u=function(){};return{s:u,n:function(){return l>=f.length?{done:!0}:{done:!1,value:f[l++]}},e:function(v){throw v},f:u}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
61
- In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var s=!0,n=!1,g;return{s:function(){r=f[Symbol.iterator]()},n:function(){var v=r.next();return s=v.done,v},e:function(v){n=!0,g=v},f:function(){try{!s&&r.return!=null&&r.return()}finally{if(n)throw g}}}}function Pb(f,t){if(f){if(typeof f=="string")return s_(f,t);var r=Object.prototype.toString.call(f).slice(8,-1);if(r==="Object"&&f.constructor&&(r=f.constructor.name),r==="Map"||r==="Set")return Array.from(f);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return s_(f,t)}}function s_(f,t){(t==null||t>f.length)&&(t=f.length);for(var r=0,l=new Array(t);r<t;r++)l[r]=f[r];return l}var Lb=Ts,Hc=on(),Fc=xn,pu=new Lb("Parser");e_.parseMessage=function(f,t){var r,l,u=f.indexOf(`\r
60
+ `));this.ondata({transport:this,message:r})}},{key:"via_transport",get:function(){return this.socket.via_transport}},{key:"url",get:function(){return this.socket.url}},{key:"sip_uri",get:function(){return this.socket.sip_uri}}]),f}(),Zh={};function e_(f,t){var r;if(typeof Symbol>"u"||f[Symbol.iterator]==null){if(Array.isArray(f)||(r=Pb(f))||t&&f&&typeof f.length=="number"){r&&(f=r);var l=0,u=function(){};return{s:u,n:function(){return l>=f.length?{done:!0}:{done:!1,value:f[l++]}},e:function(v){throw v},f:u}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
61
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var s=!0,n=!1,g;return{s:function(){r=f[Symbol.iterator]()},n:function(){var v=r.next();return s=v.done,v},e:function(v){n=!0,g=v},f:function(){try{!s&&r.return!=null&&r.return()}finally{if(n)throw g}}}}function Pb(f,t){if(f){if(typeof f=="string")return t_(f,t);var r=Object.prototype.toString.call(f).slice(8,-1);if(r==="Object"&&f.constructor&&(r=f.constructor.name),r==="Map"||r==="Set")return Array.from(f);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return t_(f,t)}}function t_(f,t){(t==null||t>f.length)&&(t=f.length);for(var r=0,l=new Array(t);r<t;r++)l[r]=f[r];return l}var Lb=Ts,Hc=on(),Fc=xn,pu=new Lb("Parser");Zh.parseMessage=function(f,t){var r,l,u=f.indexOf(`\r
62
62
  `);if(u===-1){pu.warn("parseMessage() | no CRLF found, not a SIP message");return}var s=f.substring(0,u),n=Hc.parse(s,"Request_Response");if(n===-1){pu.warn('parseMessage() | error parsing first line of SIP message: "'.concat(s,'"'));return}else n.status_code?(r=new Fc.IncomingResponse,r.status_code=n.status_code,r.reason_phrase=n.reason_phrase):(r=new Fc.IncomingRequest(t),r.method=n.method,r.ruri=n.uri);r.data=f;for(var g=u+2;;){if(u=Hb(f,g),u===-2){l=g+2;break}else if(u===-1){pu.warn("parseMessage() | malformed message");return}if(n=Fb(r,f,g,u),n!==!0){pu.warn("parseMessage() |",n.error);return}g=u+2}if(r.hasHeader("content-length")){var _=r.getHeader("content-length");r.body=f.substr(l,_)}else r.body=f.substring(l);return r};function Hb(f,t){var r=t,l=0,u=0;if(f.substring(r,r+2).match(/(^\r\n)/))return-2;for(;l===0;){if(u=f.indexOf(`\r
63
- `,r),u===-1)return u;!f.substring(u+2,u+4).match(/(^\r\n)/)&&f.charAt(u+2).match(/(^\s+)/)?r=u+2:l=u}return l}function Fb(f,t,r,l){var u,s=t.indexOf(":",r),n=t.substring(r,s).trim(),g=t.substring(s+1,l).trim();switch(n.toLowerCase()){case"via":case"v":f.addHeader("via",g),f.getHeaders("via").length===1?(u=f.parseHeader("Via"),u&&(f.via=u,f.via_branch=u.branch)):u=0;break;case"from":case"f":f.setHeader("from",g),u=f.parseHeader("from"),u&&(f.from=u,f.from_tag=u.getParam("tag"));break;case"to":case"t":f.setHeader("to",g),u=f.parseHeader("to"),u&&(f.to=u,f.to_tag=u.getParam("tag"));break;case"record-route":if(u=Hc.parse(g,"Record_Route"),u===-1)u=void 0;else{var _=t_(u),v;try{for(_.s();!(v=_.n()).done;){var C=v.value;f.addHeader("record-route",g.substring(C.possition,C.offset)),f.headers["Record-Route"][f.getHeaders("record-route").length-1].parsed=C.parsed}}catch(F){_.e(F)}finally{_.f()}}break;case"call-id":case"i":f.setHeader("call-id",g),u=f.parseHeader("call-id"),u&&(f.call_id=g);break;case"contact":case"m":if(u=Hc.parse(g,"Contact"),u===-1)u=void 0;else{var R=t_(u),D;try{for(R.s();!(D=R.n()).done;){var H=D.value;f.addHeader("contact",g.substring(H.possition,H.offset)),f.headers.Contact[f.getHeaders("contact").length-1].parsed=H.parsed}}catch(F){R.e(F)}finally{R.f()}}break;case"content-length":case"l":f.setHeader("content-length",g),u=f.parseHeader("content-length");break;case"content-type":case"c":f.setHeader("content-type",g),u=f.parseHeader("content-type");break;case"cseq":f.setHeader("cseq",g),u=f.parseHeader("cseq"),u&&(f.cseq=u.value),f instanceof Fc.IncomingResponse&&(f.method=u.method);break;case"max-forwards":f.setHeader("max-forwards",g),u=f.parseHeader("max-forwards");break;case"www-authenticate":f.setHeader("www-authenticate",g),u=f.parseHeader("www-authenticate");break;case"proxy-authenticate":f.setHeader("proxy-authenticate",g),u=f.parseHeader("proxy-authenticate");break;case"session-expires":case"x":f.setHeader("session-expires",g),u=f.parseHeader("session-expires"),u&&(f.session_expires=u.expires,f.session_expires_refresher=u.refresher);break;case"refer-to":case"r":f.setHeader("refer-to",g),u=f.parseHeader("refer-to"),u&&(f.refer_to=u);break;case"replaces":f.setHeader("replaces",g),u=f.parseHeader("replaces"),u&&(f.replaces=u);break;case"event":case"o":f.setHeader("event",g),u=f.parseHeader("event"),u&&(f.event=u);break;default:f.addHeader(n,g),u=0}return u===void 0?{error:'error parsing header "'.concat(n,'"')}:!0}function mu(f,t){var r;if(typeof Symbol>"u"||f[Symbol.iterator]==null){if(Array.isArray(f)||(r=Bb(f))||t&&f&&typeof f.length=="number"){r&&(f=r);var l=0,u=function(){};return{s:u,n:function(){return l>=f.length?{done:!0}:{done:!1,value:f[l++]}},e:function(v){throw v},f:u}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
64
- In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var s=!0,n=!1,g;return{s:function(){r=f[Symbol.iterator]()},n:function(){var v=r.next();return s=v.done,v},e:function(v){n=!0,g=v},f:function(){try{!s&&r.return!=null&&r.return()}finally{if(n)throw g}}}}function Bb(f,t){if(f){if(typeof f=="string")return r_(f,t);var r=Object.prototype.toString.call(f).slice(8,-1);if(r==="Object"&&f.constructor&&(r=f.constructor.name),r==="Map"||r==="Set")return Array.from(f);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return r_(f,t)}}function r_(f,t){(t==null||t>f.length)&&(t=f.length);for(var r=0,l=new Array(t);r<t;r++)l[r]=f[r];return l}var zb=Ts,n_=hs,i_=xn,Bc=Bs(),zc=new zb("sanityCheck"),Vb=[Zb],qb=[Wb,Kb,Yb,Jb],jb=[Qb,Xb],Wt,cn,a_,Gb=function(f,t,r){Wt=f,cn=t,a_=r;var l=mu(Vb),u;try{for(l.s();!(u=l.n()).done;){var s=u.value;if(s()===!1)return!1}}catch(D){l.e(D)}finally{l.f()}if(Wt instanceof i_.IncomingRequest){var n=mu(qb),g;try{for(n.s();!(g=n.n()).done;){var _=g.value;if(_()===!1)return!1}}catch(D){n.e(D)}finally{n.f()}}else if(Wt instanceof i_.IncomingResponse){var v=mu(jb),C;try{for(v.s();!(C=v.n()).done;){var R=C.value;if(R()===!1)return!1}}catch(D){v.e(D)}finally{v.f()}}return!0};function Wb(){if(Wt.s("to").uri.scheme!=="sip")return Zl(416),!1}function Kb(){if(!Wt.to_tag&&Wt.call_id.substr(0,5)===cn.configuration.jssip_id)return Zl(482),!1}function Yb(){var f=Bc.str_utf8_length(Wt.body),t=Wt.getHeader("content-length");if(f<t)return Zl(400),!1}function Jb(){var f=Wt.from_tag,t=Wt.call_id,r=Wt.cseq,l;if(!Wt.to_tag)if(Wt.method===n_.INVITE){if(cn._transactions.ist[Wt.via_branch])return!1;for(var u in cn._transactions.ist)if(Object.prototype.hasOwnProperty.call(cn._transactions.ist,u)&&(l=cn._transactions.ist[u],l.request.from_tag===f&&l.request.call_id===t&&l.request.cseq===r))return Zl(482),!1}else{if(cn._transactions.nist[Wt.via_branch])return!1;for(var s in cn._transactions.nist)if(Object.prototype.hasOwnProperty.call(cn._transactions.nist,s)&&(l=cn._transactions.nist[s],l.request.from_tag===f&&l.request.call_id===t&&l.request.cseq===r))return Zl(482),!1}}function Qb(){if(Wt.getHeaders("via").length>1)return zc.debug("more than one Via header field present in the response, dropping the response"),!1}function Xb(){var f=Bc.str_utf8_length(Wt.body),t=Wt.getHeader("content-length");if(f<t)return zc.debug("message body length is lower than the value in Content-Length header field, dropping the response"),!1}function Zb(){for(var f=["from","to","call_id","cseq","via"],t=0,r=f;t<r.length;t++){var l=r[t];if(!Wt.hasHeader(l))return zc.debug("missing mandatory header field : ".concat(l,", dropping the response")),!1}}function Zl(f){var t=Wt.getHeaders("via"),r,l="SIP/2.0 ".concat(f," ").concat(n_.REASON_PHRASE[f],`\r
63
+ `,r),u===-1)return u;!f.substring(u+2,u+4).match(/(^\r\n)/)&&f.charAt(u+2).match(/(^\s+)/)?r=u+2:l=u}return l}function Fb(f,t,r,l){var u,s=t.indexOf(":",r),n=t.substring(r,s).trim(),g=t.substring(s+1,l).trim();switch(n.toLowerCase()){case"via":case"v":f.addHeader("via",g),f.getHeaders("via").length===1?(u=f.parseHeader("Via"),u&&(f.via=u,f.via_branch=u.branch)):u=0;break;case"from":case"f":f.setHeader("from",g),u=f.parseHeader("from"),u&&(f.from=u,f.from_tag=u.getParam("tag"));break;case"to":case"t":f.setHeader("to",g),u=f.parseHeader("to"),u&&(f.to=u,f.to_tag=u.getParam("tag"));break;case"record-route":if(u=Hc.parse(g,"Record_Route"),u===-1)u=void 0;else{var _=e_(u),v;try{for(_.s();!(v=_.n()).done;){var C=v.value;f.addHeader("record-route",g.substring(C.possition,C.offset)),f.headers["Record-Route"][f.getHeaders("record-route").length-1].parsed=C.parsed}}catch(F){_.e(F)}finally{_.f()}}break;case"call-id":case"i":f.setHeader("call-id",g),u=f.parseHeader("call-id"),u&&(f.call_id=g);break;case"contact":case"m":if(u=Hc.parse(g,"Contact"),u===-1)u=void 0;else{var R=e_(u),D;try{for(R.s();!(D=R.n()).done;){var H=D.value;f.addHeader("contact",g.substring(H.possition,H.offset)),f.headers.Contact[f.getHeaders("contact").length-1].parsed=H.parsed}}catch(F){R.e(F)}finally{R.f()}}break;case"content-length":case"l":f.setHeader("content-length",g),u=f.parseHeader("content-length");break;case"content-type":case"c":f.setHeader("content-type",g),u=f.parseHeader("content-type");break;case"cseq":f.setHeader("cseq",g),u=f.parseHeader("cseq"),u&&(f.cseq=u.value),f instanceof Fc.IncomingResponse&&(f.method=u.method);break;case"max-forwards":f.setHeader("max-forwards",g),u=f.parseHeader("max-forwards");break;case"www-authenticate":f.setHeader("www-authenticate",g),u=f.parseHeader("www-authenticate");break;case"proxy-authenticate":f.setHeader("proxy-authenticate",g),u=f.parseHeader("proxy-authenticate");break;case"session-expires":case"x":f.setHeader("session-expires",g),u=f.parseHeader("session-expires"),u&&(f.session_expires=u.expires,f.session_expires_refresher=u.refresher);break;case"refer-to":case"r":f.setHeader("refer-to",g),u=f.parseHeader("refer-to"),u&&(f.refer_to=u);break;case"replaces":f.setHeader("replaces",g),u=f.parseHeader("replaces"),u&&(f.replaces=u);break;case"event":case"o":f.setHeader("event",g),u=f.parseHeader("event"),u&&(f.event=u);break;default:f.addHeader(n,g),u=0}return u===void 0?{error:'error parsing header "'.concat(n,'"')}:!0}function mu(f,t){var r;if(typeof Symbol>"u"||f[Symbol.iterator]==null){if(Array.isArray(f)||(r=Bb(f))||t&&f&&typeof f.length=="number"){r&&(f=r);var l=0,u=function(){};return{s:u,n:function(){return l>=f.length?{done:!0}:{done:!1,value:f[l++]}},e:function(v){throw v},f:u}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
64
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var s=!0,n=!1,g;return{s:function(){r=f[Symbol.iterator]()},n:function(){var v=r.next();return s=v.done,v},e:function(v){n=!0,g=v},f:function(){try{!s&&r.return!=null&&r.return()}finally{if(n)throw g}}}}function Bb(f,t){if(f){if(typeof f=="string")return s_(f,t);var r=Object.prototype.toString.call(f).slice(8,-1);if(r==="Object"&&f.constructor&&(r=f.constructor.name),r==="Map"||r==="Set")return Array.from(f);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return s_(f,t)}}function s_(f,t){(t==null||t>f.length)&&(t=f.length);for(var r=0,l=new Array(t);r<t;r++)l[r]=f[r];return l}var zb=Ts,r_=hs,n_=xn,Bc=Bs(),zc=new zb("sanityCheck"),Vb=[Zb],qb=[Wb,Kb,Yb,Jb],jb=[Qb,Xb],Wt,cn,i_,Gb=function(f,t,r){Wt=f,cn=t,i_=r;var l=mu(Vb),u;try{for(l.s();!(u=l.n()).done;){var s=u.value;if(s()===!1)return!1}}catch(D){l.e(D)}finally{l.f()}if(Wt instanceof n_.IncomingRequest){var n=mu(qb),g;try{for(n.s();!(g=n.n()).done;){var _=g.value;if(_()===!1)return!1}}catch(D){n.e(D)}finally{n.f()}}else if(Wt instanceof n_.IncomingResponse){var v=mu(jb),C;try{for(v.s();!(C=v.n()).done;){var R=C.value;if(R()===!1)return!1}}catch(D){v.e(D)}finally{v.f()}}return!0};function Wb(){if(Wt.s("to").uri.scheme!=="sip")return Zl(416),!1}function Kb(){if(!Wt.to_tag&&Wt.call_id.substr(0,5)===cn.configuration.jssip_id)return Zl(482),!1}function Yb(){var f=Bc.str_utf8_length(Wt.body),t=Wt.getHeader("content-length");if(f<t)return Zl(400),!1}function Jb(){var f=Wt.from_tag,t=Wt.call_id,r=Wt.cseq,l;if(!Wt.to_tag)if(Wt.method===r_.INVITE){if(cn._transactions.ist[Wt.via_branch])return!1;for(var u in cn._transactions.ist)if(Object.prototype.hasOwnProperty.call(cn._transactions.ist,u)&&(l=cn._transactions.ist[u],l.request.from_tag===f&&l.request.call_id===t&&l.request.cseq===r))return Zl(482),!1}else{if(cn._transactions.nist[Wt.via_branch])return!1;for(var s in cn._transactions.nist)if(Object.prototype.hasOwnProperty.call(cn._transactions.nist,s)&&(l=cn._transactions.nist[s],l.request.from_tag===f&&l.request.call_id===t&&l.request.cseq===r))return Zl(482),!1}}function Qb(){if(Wt.getHeaders("via").length>1)return zc.debug("more than one Via header field present in the response, dropping the response"),!1}function Xb(){var f=Bc.str_utf8_length(Wt.body),t=Wt.getHeader("content-length");if(f<t)return zc.debug("message body length is lower than the value in Content-Length header field, dropping the response"),!1}function Zb(){for(var f=["from","to","call_id","cseq","via"],t=0,r=f;t<r.length;t++){var l=r[t];if(!Wt.hasHeader(l))return zc.debug("missing mandatory header field : ".concat(l,", dropping the response")),!1}}function Zl(f){var t=Wt.getHeaders("via"),r,l="SIP/2.0 ".concat(f," ").concat(r_.REASON_PHRASE[f],`\r
65
65
  `),u=mu(t),s;try{for(u.s();!(s=u.n()).done;){var n=s.value;l+="Via: ".concat(n,`\r
66
66
  `)}}catch(g){u.e(g)}finally{u.f()}r=Wt.getHeader("To"),Wt.to_tag||(r+=";tag=".concat(Bc.newTag())),l+="To: ".concat(r,`\r
67
67
  `),l+="From: ".concat(Wt.getHeader("From"),`\r
68
68
  `),l+="Call-ID: ".concat(Wt.call_id,`\r
69
69
  `),l+="CSeq: ".concat(Wt.cseq," ").concat(Wt.method,`\r
70
70
  `),l+=`\r
71
- `,a_.send(l)}var Vc={};function l_(f,t){var r;if(typeof Symbol>"u"||f[Symbol.iterator]==null){if(Array.isArray(f)||(r=ew(f))||t&&f&&typeof f.length=="number"){r&&(f=r);var l=0,u=function(){};return{s:u,n:function(){return l>=f.length?{done:!0}:{done:!1,value:f[l++]}},e:function(v){throw v},f:u}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
72
- In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var s=!0,n=!1,g;return{s:function(){r=f[Symbol.iterator]()},n:function(){var v=r.next();return s=v.done,v},e:function(v){n=!0,g=v},f:function(){try{!s&&r.return!=null&&r.return()}finally{if(n)throw g}}}}function ew(f,t){if(f){if(typeof f=="string")return o_(f,t);var r=Object.prototype.toString.call(f).slice(8,-1);if(r==="Object"&&f.constructor&&(r=f.constructor.name),r==="Map"||r==="Set")return Array.from(f);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return o_(f,t)}}function o_(f,t){(t==null||t>f.length)&&(t=f.length);for(var r=0,l=new Array(t);r<t;r++)l[r]=f[r];return l}var ul=Bs(),ba=hs,qc=on(),u_=Ti(),jc=Pc,Gc=yi;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:ba.UPDATE,session_timers_force_refresher:!1,no_answer_timeout:60,register:!0,register_expires:600,registrar_server:null,sockets:null,connection_recovery_max_interval:ba.CONNECTION_RECOVERY_MAX_INTERVAL,connection_recovery_min_interval:ba.CONNECTION_RECOVERY_MIN_INTERVAL,extra_headers:null,via_host:"".concat(ul.createRandomToken(12),".invalid")};var gu={mandatory:{sockets:function(t){var r=[];if(jc.isSocket(t))r.push({socket:t});else if(Array.isArray(t)&&t.length){var l=l_(t),u;try{for(l.s();!(u=l.n()).done;){var s=u.value;Object.prototype.hasOwnProperty.call(s,"socket")&&jc.isSocket(s.socket)?r.push(s):jc.isSocket(s)&&r.push({socket:s})}}catch(n){l.e(n)}finally{l.f()}}else return;return r},uri:function(t){/^sip:/i.test(t)||(t="".concat(ba.SIP,":").concat(t));var r=u_.parse(t);if(r)return r.user?r:void 0}},optional:{authorization_user:function(t){if(qc.parse('"'.concat(t,'"'),"quoted_string")!==-1)return t},authorization_jwt:function(t){if(typeof t=="string")return t},user_agent:function(t){if(typeof t=="string")return t},connection_recovery_max_interval:function(t){if(ul.isDecimal(t)){var r=Number(t);if(r>0)return r}},connection_recovery_min_interval:function(t){if(ul.isDecimal(t)){var r=Number(t);if(r>0)return r}},contact_uri:function(t){if(typeof t=="string"){var r=qc.parse(t,"SIP_URI");if(r!==-1)return r}},display_name:function(t){return t},instance_id:function(t){if(/^uuid:/i.test(t)&&(t=t.substr(5)),qc.parse(t,"uuid")!==-1)return t},no_answer_timeout:function(t){if(ul.isDecimal(t)){var r=Number(t);if(r>0)return r}},session_timers:function(t){if(typeof t=="boolean")return t},session_timers_refresh_method:function(t){if(typeof t=="string"&&(t=t.toUpperCase(),t===ba.INVITE||t===ba.UPDATE))return t},session_timers_force_refresher:function(t){if(typeof t=="boolean")return t},password:function(t){return String(t)},realm:function(t){return String(t)},ha1:function(t){return String(t)},register:function(t){if(typeof t=="boolean")return t},register_expires:function(t){if(ul.isDecimal(t)){var r=Number(t);if(r>0)return r}},registrar_server:function(t){/^sip:/i.test(t)||(t="".concat(ba.SIP,":").concat(t));var r=u_.parse(t);if(r)return r.user?void 0:r},use_preloaded_route:function(t){if(typeof t=="boolean")return t},extra_headers:function(t){var r=[];if(Array.isArray(t)&&t.length){var l=l_(t),u;try{for(l.s();!(u=l.n()).done;){var s=u.value;typeof s=="string"&&r.push(s)}}catch(n){l.e(n)}finally{l.f()}}else return;return r}}};Vc.load=function(f,t){for(var r in gu.mandatory)if(t.hasOwnProperty(r)){var l=t[r],u=gu.mandatory[r](l);if(u!==void 0)f[r]=u;else throw new Gc.ConfigurationError(r,l)}else throw new Gc.ConfigurationError(r);for(var s in gu.optional)if(t.hasOwnProperty(s)){var n=t[s];if(ul.isEmpty(n))continue;var g=gu.optional[s](n);if(g!==void 0)f[s]=g;else throw new Gc.ConfigurationError(s,n)}};function vu(f){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?vu=function(r){return typeof r}:vu=function(r){return r&&typeof Symbol=="function"&&r.constructor===Symbol&&r!==Symbol.prototype?"symbol":typeof r},vu(f)}function tw(f,t){if(!(f instanceof t))throw new TypeError("Cannot call a class as a function")}function c_(f,t){for(var r=0;r<t.length;r++){var l=t[r];l.enumerable=l.enumerable||!1,l.configurable=!0,"value"in l&&(l.writable=!0),Object.defineProperty(f,l.key,l)}}function d_(f,t,r){return t&&c_(f.prototype,t),r&&c_(f,r),f}function sw(f,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");f.prototype=Object.create(t&&t.prototype,{constructor:{value:f,writable:!0,configurable:!0}}),t&&Wc(f,t)}function Wc(f,t){return Wc=Object.setPrototypeOf||function(l,u){return l.__proto__=u,l},Wc(f,t)}function rw(f){var t=iw();return function(){var l=yu(f),u;if(t){var s=yu(this).constructor;u=Reflect.construct(l,arguments,s)}else u=l.apply(this,arguments);return nw(this,u)}}function nw(f,t){return t&&(vu(t)==="object"||typeof t=="function")?t:f_(f)}function f_(f){if(f===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return f}function iw(){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 yu(f){return yu=Object.setPrototypeOf?Object.getPrototypeOf:function(r){return r.__proto__||Object.getPrototypeOf(r)},yu(f)}var aw=ys.EventEmitter,lw=Ts,Rs=hs,ow=Y0,h_=nb,__=gb,p_=$b,Kc=ql,uw=Ub,Tu=Bs(),cw=yi,dw=Ti(),fw=e_,Yc=xn,hw=Gb,Jc=Vc,Yt=new lw("UA"),$s={STATUS_INIT:0,STATUS_READY:1,STATUS_USER_CLOSED:2,STATUS_NOT_READY:3,CONFIGURATION_ERROR:1,NETWORK_ERROR:2},_w=function(f){sw(r,f);var t=rw(r);d_(r,null,[{key:"C",get:function(){return $s}}]);function r(l){var u;if(tw(this,r),Yt.debug("new() [configuration:%o]",l),u=t.call(this),u._cache={credentials:{}},u._configuration=Object.assign({},Jc.settings),u._dynConfiguration={},u._dialogs={},u._applicants={},u._sessions={},u._transport=null,u._contact=null,u._status=$s.STATUS_INIT,u._error=null,u._transactions={nist:{},nict:{},ist:{},ict:{}},u._data={},u._closeTimer=null,l===void 0)throw new TypeError("Not enough arguments");try{u._loadConfig(l)}catch(s){throw u._status=$s.STATUS_NOT_READY,u._error=$s.CONFIGURATION_ERROR,s}return u._registrator=new ow(f_(u)),u}return d_(r,[{key:"start",value:function(){Yt.debug("start()"),this._status===$s.STATUS_INIT?this._transport.connect():this._status===$s.STATUS_USER_CLOSED?(Yt.debug("restarting UA"),this._closeTimer!==null&&(clearTimeout(this._closeTimer),this._closeTimer=null,this._transport.disconnect()),this._status=$s.STATUS_INIT,this._transport.connect()):this._status===$s.STATUS_READY?Yt.debug("UA is in READY status, not restarted"):Yt.debug("ERROR: connection is down, Auto-Recovery system is trying to reconnect"),this._dynConfiguration.register=this._configuration.register}},{key:"register",value:function(){Yt.debug("register()"),this._dynConfiguration.register=!0,this._registrator.register()}},{key:"unregister",value:function(u){Yt.debug("unregister()"),this._dynConfiguration.register=!1,this._registrator.unregister(u)}},{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(u,s){Yt.debug("call()");var n=new h_(this);return n.connect(u,s),n}},{key:"sendMessage",value:function(u,s,n){Yt.debug("sendMessage()");var g=new __(this);return g.send(u,s,n),g}},{key:"sendOptions",value:function(u,s,n){Yt.debug("sendOptions()");var g=new p_(this);return g.send(u,s,n),g}},{key:"terminateSessions",value:function(u){Yt.debug("terminateSessions()");for(var s in this._sessions)this._sessions[s].isEnded()||this._sessions[s].terminate(u)}},{key:"stop",value:function(){var u=this;if(Yt.debug("stop()"),this._dynConfiguration={},this._status===$s.STATUS_USER_CLOSED){Yt.debug("UA already closed");return}this._registrator.close();var s=Object.keys(this._sessions).length;for(var n in this._sessions)if(Object.prototype.hasOwnProperty.call(this._sessions,n)){Yt.debug("closing session ".concat(n));try{this._sessions[n].terminate()}catch{}}for(var g in this._applicants)if(Object.prototype.hasOwnProperty.call(this._applicants,g))try{this._applicants[g].close()}catch{}this._status=$s.STATUS_USER_CLOSED;var _=Object.keys(this._transactions.nict).length+Object.keys(this._transactions.nist).length+Object.keys(this._transactions.ict).length+Object.keys(this._transactions.ist).length;_===0&&s===0?this._transport.disconnect():this._closeTimer=setTimeout(function(){u._closeTimer=null,u._transport.disconnect()},2e3)}},{key:"normalizeTarget",value:function(u){return Tu.normalizeTarget(u,this._configuration.hostport_params)}},{key:"get",value:function(u){switch(u){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:Yt.warn('get() | cannot get "%s" parameter in runtime',u);return}}},{key:"set",value:function(u,s){switch(u){case"authorization_user":{this._configuration.authorization_user=String(s);break}case"password":{this._configuration.password=String(s);break}case"realm":{this._configuration.realm=String(s);break}case"ha1":{this._configuration.ha1=String(s),this._configuration.password=null;break}case"authorization_jwt":{this._configuration.authorization_jwt=String(s);break}case"display_name":{this._configuration.display_name=s;break}default:return Yt.warn('set() | cannot set "%s" parameter in runtime',u),!1}return!0}},{key:"newTransaction",value:function(u){this._transactions[u.type][u.id]=u,this.emit("newTransaction",{transaction:u})}},{key:"destroyTransaction",value:function(u){delete this._transactions[u.type][u.id],this.emit("transactionDestroyed",{transaction:u})}},{key:"newDialog",value:function(u){this._dialogs[u.id]=u}},{key:"destroyDialog",value:function(u){delete this._dialogs[u.id]}},{key:"newMessage",value:function(u,s){this._applicants[u]=u,this.emit("newMessage",s)}},{key:"newOptions",value:function(u,s){this._applicants[u]=u,this.emit("newOptions",s)}},{key:"destroyMessage",value:function(u){delete this._applicants[u]}},{key:"newRTCSession",value:function(u,s){this._sessions[u.id]=u,this.emit("newRTCSession",s)}},{key:"destroyRTCSession",value:function(u){delete this._sessions[u.id]}},{key:"registered",value:function(u){this.emit("registered",u)}},{key:"unregistered",value:function(u){this.emit("unregistered",u)}},{key:"registrationFailed",value:function(u){this.emit("registrationFailed",u)}},{key:"receiveRequest",value:function(u){var s=u.method;if(u.ruri.user!==this._configuration.uri.user&&u.ruri.user!==this._contact.uri.user){Yt.debug("Request-URI does not point to us"),u.method!==Rs.ACK&&u.reply_sl(404);return}if(u.ruri.scheme===Rs.SIPS){u.reply_sl(416);return}if(!Kc.checkTransaction(this,u)){if(s===Rs.INVITE?new Kc.InviteServerTransaction(this,this._transport,u):s!==Rs.ACK&&s!==Rs.CANCEL&&new Kc.NonInviteServerTransaction(this,this._transport,u),s===Rs.OPTIONS){if(this.listeners("newOptions").length===0){u.reply(200);return}var n=new p_(this);n.init_incoming(u)}else if(s===Rs.MESSAGE){if(this.listeners("newMessage").length===0){u.reply(405);return}var g=new __(this);g.init_incoming(u)}else if(s===Rs.INVITE&&!u.to_tag&&this.listeners("newRTCSession").length===0){u.reply(405);return}var _,v;if(u.to_tag)_=this._findDialog(u.call_id,u.from_tag,u.to_tag),_?_.receiveRequest(u):s===Rs.NOTIFY?(v=this._findSession(u),v?v.receiveRequest(u):(Yt.debug("received NOTIFY request for a non existent subscription"),u.reply(481,"Subscription does not exist"))):s!==Rs.ACK&&u.reply(481);else switch(s){case Rs.INVITE:if(window.RTCPeerConnection)if(u.hasHeader("replaces")){var C=u.replaces;_=this._findDialog(C.call_id,C.from_tag,C.to_tag),_?(v=_.owner,v.isEnded()?u.reply(603):v.receiveRequest(u)):u.reply(481)}else v=new h_(this),v.init_incoming(u);else Yt.warn("INVITE received but WebRTC is not supported"),u.reply(488);break;case Rs.BYE:u.reply(481);break;case Rs.CANCEL:v=this._findSession(u),v?v.receiveRequest(u):Yt.debug("received CANCEL request for a non existent session");break;case Rs.ACK:break;case Rs.NOTIFY:this.emit("sipEvent",{event:u.event,request:u}),u.reply(200);break;default:u.reply(405);break}}}},{key:"_findSession",value:function(u){var s=u.call_id,n=u.from_tag,g=u.to_tag,_=s+n,v=this._sessions[_],C=s+g,R=this._sessions[C];return v||R||null}},{key:"_findDialog",value:function(u,s,n){var g=u+s+n,_=this._dialogs[g];return _||(g=u+n+s,_=this._dialogs[g],_||null)}},{key:"_loadConfig",value:function(u){try{Jc.load(this._configuration,u)}catch(C){throw C}this._configuration.display_name===0&&(this._configuration.display_name="0"),this._configuration.instance_id||(this._configuration.instance_id=Tu.newUUID()),this._configuration.jssip_id=Tu.createRandomToken(5);var s=this._configuration.uri.clone();s.user=null,this._configuration.hostport_params=s.toString().replace(/^sip:/i,"");try{this._transport=new uw(this._configuration.sockets,{max_interval:this._configuration.connection_recovery_max_interval,min_interval:this._configuration.connection_recovery_min_interval}),this._transport.onconnecting=pw.bind(this),this._transport.onconnect=mw.bind(this),this._transport.ondisconnect=gw.bind(this),this._transport.ondata=vw.bind(this)}catch(C){throw Yt.warn(C),new cw.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 n=this._configuration.uri.clone();n.user=null,n.clearParams(),n.clearHeaders(),this._configuration.registrar_server=n}this._configuration.no_answer_timeout*=1e3,this._configuration.contact_uri?this._configuration.via_host=this._configuration.contact_uri.host:this._configuration.contact_uri=new dw("sip",Tu.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 R=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},D=R.anonymous||null,H=R.outbound||null,F="<";return D?F+=this.temp_gruu||"sip:anonymous@anonymous.invalid;transport=ws":F+=this.pub_gruu||this.uri.toString(),H&&(D?!this.temp_gruu:!this.pub_gruu)&&(F+=";ob"),F+=">",F}};var g=["authorization_user","password","realm","ha1","authorization_jwt","display_name","register"];for(var _ in this._configuration)Object.prototype.hasOwnProperty.call(this._configuration,_)&&(g.indexOf(_)!==-1?Object.defineProperty(this._configuration,_,{writable:!0,configurable:!1}):Object.defineProperty(this._configuration,_,{writable:!1,configurable:!1}));Yt.debug("configuration parameters after validation:");for(var v in this._configuration)if(Object.prototype.hasOwnProperty.call(Jc.settings,v))switch(v){case"uri":case"registrar_server":Yt.debug("- ".concat(v,": ").concat(this._configuration[v]));break;case"password":case"ha1":case"authorization_jwt":Yt.debug("- ".concat(v,": NOT SHOWN"));break;default:Yt.debug("- ".concat(v,": ").concat(JSON.stringify(this._configuration[v])))}}},{key:"C",get:function(){return $s}},{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}(aw);function pw(f){this.emit("connecting",f)}function mw(f){this._status!==$s.STATUS_USER_CLOSED&&(this._status=$s.STATUS_READY,this._error=null,this.emit("connected",f),this._dynConfiguration.register&&this._registrator.register())}function gw(f){for(var t=["nict","ict","nist","ist"],r=0,l=t;r<l.length;r++){var u=l[r];for(var s in this._transactions[u])Object.prototype.hasOwnProperty.call(this._transactions[u],s)&&this._transactions[u][s].onTransportError()}this.emit("disconnected",f),this._registrator.onTransportClosed(),this._status!==$s.STATUS_USER_CLOSED&&(this._status=$s.STATUS_NOT_READY,this._error=$s.NETWORK_ERROR)}function vw(f){var t=f.transport,r=f.message;if(r=fw.parseMessage(r,this),!!r&&!(this._status===$s.STATUS_USER_CLOSED&&r instanceof Yc.IncomingRequest)&&hw(r,this,t)){if(r instanceof Yc.IncomingRequest)r.transport=t,this.receiveRequest(r);else if(r instanceof Yc.IncomingResponse){var l;switch(r.method){case Rs.INVITE:l=this._transactions.ict[r.via_branch],l&&l.receiveResponse(r);break;case Rs.ACK:break;default:l=this._transactions.nict[r.via_branch],l&&l.receiveResponse(r);break}}}}function yw(f,t){if(!(f instanceof t))throw new TypeError("Cannot call a class as a function")}function m_(f,t){for(var r=0;r<t.length;r++){var l=t[r];l.enumerable=l.enumerable||!1,l.configurable=!0,"value"in l&&(l.writable=!0),Object.defineProperty(f,l.key,l)}}function Tw(f,t,r){return t&&m_(f.prototype,t),r&&m_(f,r),f}var Sw=Ts,bw=on(),Ws=new Sw("WebSocketInterface"),ww=function(){function f(t){yw(this,f),Ws.debug('new() [url:"%s"]',t),this._url=t,this._sip_uri=null,this._via_transport=null,this._ws=null;var r=bw.parse(t,"absoluteURI");if(r===-1)throw Ws.warn("invalid WebSocket URI: ".concat(t)),new TypeError("Invalid argument: ".concat(t));if(r.scheme!=="wss"&&r.scheme!=="ws")throw Ws.warn("invalid WebSocket URI scheme: ".concat(r.scheme)),new TypeError("Invalid argument: ".concat(t));this._sip_uri="sip:".concat(r.host).concat(r.port?":".concat(r.port):"",";transport=ws"),this._via_transport=r.scheme.toUpperCase()}return Tw(f,[{key:"connect",value:function(){if(Ws.debug("connect()"),this.isConnected()){Ws.debug("WebSocket ".concat(this._url," is already connected"));return}else if(this.isConnecting()){Ws.debug("WebSocket ".concat(this._url," is connecting"));return}this._ws&&this.disconnect(),Ws.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(r){this._onError(r)}}},{key:"disconnect",value:function(){Ws.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(r){return Ws.debug("send()"),this.isConnected()?(this._ws.send(r),!0):(Ws.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(){Ws.debug("WebSocket ".concat(this._url," connected")),this.onconnect()}},{key:"_onClose",value:function(r){var l=r.wasClean,u=r.code,s=r.reason;Ws.debug("WebSocket ".concat(this._url," closed")),l===!1&&Ws.debug("WebSocket abrupt disconnection"),this.ondisconnect(!l,u,s)}},{key:"_onMessage",value:function(r){var l=r.data;Ws.debug("received WebSocket message"),this.ondata(l)}},{key:"_onError",value:function(r){Ws.warn("WebSocket ".concat(this._url," error: "),r)}},{key:"via_transport",get:function(){return this._via_transport},set:function(r){this._via_transport=r.toUpperCase()}},{key:"sip_uri",get:function(){return this._sip_uri}},{key:"url",get:function(){return this._url}}]),f}(),Qc=Uo,Ew=hs,Cw=yi,Aw=Bs(),Iw=_w,Rw=Ti(),$w=oc(),xw=on(),Ow=ww,Dw=al("JsSIP");Dw("version %s",Qc.version);var g_={C:Ew,Exceptions:Cw,Utils:Aw,UA:Iw,URI:Rw,NameAddrHeader:$w,WebSocketInterface:Ow,Grammar:xw,debug:al,get name(){return Qc.title},get version(){return Qc.version}};const cl=al,dl="JsSIP";var gs=class{constructor(t){t?(this._debug=cl.default(`${dl}:${t}`),this._warn=cl.default(`${dl}:WARN:${t}`),this._error=cl.default(`${dl}:ERROR:${t}`)):(this._debug=cl.default(dl),this._warn=cl.default(`${dl}:WARN`),this._error=cl.default(`${dl}: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 Su=Ht(gs),v_=Uo;var Et={USER_AGENT:`${v_.title} ${v_.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 fe=Ht(Et);var cs={},Xc,y_;function Zc(){if(y_)return Xc;y_=1;const f=Nn(),t=Dr();return Xc=class qT{static parse(l){if(l=t.parse(l,"Name_Addr_Header"),l!==-1)return l}constructor(l,u,s){if(!l||!(l instanceof f))throw new TypeError('missing or invalid "uri" parameter');this._uri=l,this._parameters={},this.display_name=u;for(const n in s)Object.prototype.hasOwnProperty.call(s,n)&&this.setParam(n,s[n])}get uri(){return this._uri}get display_name(){return this._display_name}set display_name(l){this._display_name=l===0?"0":l}setParam(l,u){l&&(this._parameters[l.toLowerCase()]=typeof u>"u"||u===null?null:u.toString())}getParam(l){if(l)return this._parameters[l.toLowerCase()]}hasParam(l){if(l)return this._parameters.hasOwnProperty(l.toLowerCase())&&!0||!1}deleteParam(l){if(l=l.toLowerCase(),this._parameters.hasOwnProperty(l)){const u=this._parameters[l];return delete this._parameters[l],u}}clearParams(){this._parameters={}}clone(){return new qT(this._uri.clone(),this._display_name,JSON.parse(JSON.stringify(this._parameters)))}_quote(l){return l.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}toString(){let l=this._display_name?`"${this._quote(this._display_name)}" `:"";l+=`<${this._uri.toString()}>`;for(const u in this._parameters)Object.prototype.hasOwnProperty.call(this._parameters,u)&&(l+=`;${u}`,this._parameters[u]!==null&&(l+=`=${this._parameters[u]}`));return l}},Xc}var ed,T_;function Dr(){return T_||(T_=1,ed=function(){function f(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 t={parse:function(r,l){var u={CRLF:v,DIGIT:C,ALPHA:R,HEXDIG:D,WSP:H,OCTET:F,DQUOTE:q,SP:G,HTAB:te,alphanum:X,reserved:we,unreserved:Q,mark:re,escaped:ke,LWS:Ne,SWS:Z,HCOLON:se,TEXT_UTF8_TRIM:pe,TEXT_UTF8char:me,UTF8_NONASCII:be,UTF8_CONT:_e,LHEX:Ae,token:le,token_nodot:oe,separators:Oe,word:rs,STAR:Re,SLASH:ye,EQUAL:ge,LPAREN:Le,RPAREN:et,RAQUOT:vt,LAQUOT:xt,COMMA:dt,SEMI:ze,COLON:Ye,LDQUOT:Zt,RDQUOT:Mt,comment:nt,ctext:rt,quoted_string:gt,quoted_string_clean:ft,qdtext:Fe,quoted_pair:He,SIP_URI_noparams:qe,SIP_URI:yt,uri_scheme:Ct,uri_scheme_sips:ns,uri_scheme_sip:Ut,userinfo:ar,user:vs,user_unreserved:Oi,password:Di,hostport:zn,host:pr,hostname:as,domainlabel:Pr,toplabel:Vn,IPv6reference:pn,IPv6address:Lr,h16:Qe,ls32:Ve,IPv4address:ls,dec_octet:lr,port:os,uri_parameters:qn,uri_parameter:Hr,transport_param:jn,user_param:ki,method_param:Gn,ttl_param:Ni,maddr_param:Wn,lr_param:Mi,other_param:Kn,pname:Ui,pvalue:Yn,paramchar:Ar,param_unreserved:mr,headers:Fr,header:Br,hname:mn,hvalue:Pi,hnv_unreserved:zr,Request_Response:Vr,Request_Line:kt,Request_URI:gr,absoluteURI:bs,hier_part:qr,net_path:It,abs_path:jr,opaque_part:gn,uric:vn,uric_no_slash:Gr,path_segments:Li,segment:yn,param:or,pchar:Ir,scheme:Wr,authority:Da,srvr:vr,reg_name:Ys,query:yr,SIP_Version:Kr,INVITEm:Yr,ACKm:Jn,OPTIONSm:Qn,BYEm:Xn,CANCELm:ot,REGISTERm:Zn,SUBSCRIBEm:Hi,NOTIFYm:Fi,REFERm:Bi,Method:Tn,Status_Line:Sn,Status_Code:ei,extension_code:zi,Reason_Phrase:bt,Allow_Events:ur,Call_ID:Sl,Contact:bn,contact_param:ie,name_addr:Ls,display_name:Js,contact_params:Jr,c_p_q:ti,c_p_expires:ht,delta_seconds:cr,qvalue:Tr,generic_param:Vt,gen_value:qt,Content_Disposition:Vi,disp_type:ka,disp_param:wn,handling_param:si,Content_Encoding:qi,Content_Length:Na,Content_Type:Ma,media_type:Ua,m_type:ji,discrete_type:Pa,composite_type:Qr,extension_token:En,x_token:Cn,m_subtype:La,m_parameter:An,m_value:In,CSeq:ri,CSeq_value:ni,Expires:Ha,Event:bl,event_type:Xr,From:Zr,from_param:Gi,tag_param:Rn,Max_Forwards:Fa,Min_Expires:wl,Name_Addr_Header:Rt,Proxy_Authenticate:jt,challenge:Rr,other_challenge:en,auth_param:Bt,digest_cln:Gt,realm:Xe,realm_value:Pt,domain:ii,URI:dr,nonce:qs,nonce_value:Ze,opaque:tn,stale:he,algorithm:Je,qop_options:Wi,qop_value:sn,Proxy_Require:ai,Record_Route:El,rec_route:_t,Reason:li,reason_param:oi,reason_cause:ui,Require:Ba,Route:Cl,route_param:ci,Subscription_State:ms,substate_value:za,subexp_params:di,event_reason_value:Qs,Subject:Va,Supported:Al,To:Il,to_param:Ki,Via:Yi,via_param:fi,via_params:rn,via_ttl:hi,via_maddr:Ji,via_received:Qi,via_branch:Hs,response_port:Xi,rport:Zi,sent_protocol:ea,protocol_name:ta,transport:sa,sent_by:ra,via_host:na,via_port:ia,ttl:_i,WWW_Authenticate:aa,Session_Expires:Eo,s_e_expires:js,s_e_params:pi,s_e_refresher:nn,extension_header:la,header_value:Gs,message_body:qa,uuid_URI:Rl,uuid:ja,hex4:Xs,hex8:Zs,hex12:oa,Refer_To:Ga,Replaces:$l,call_id:Wa,replaces_param:mi,to_tag:ws,from_tag:ua,early_flag:ca};if(l!==void 0){if(u[l]===void 0)throw new Error("Invalid rule name: "+f(l)+".")}else l="CRLF";var s=0,n=0,g=[];function _(a){s<n||(s>n&&(n=s,g=[]),g.push(a))}function v(){var a;return r.substr(s,2)===`\r
71
+ `,i_.send(l)}var Vc={};function a_(f,t){var r;if(typeof Symbol>"u"||f[Symbol.iterator]==null){if(Array.isArray(f)||(r=ew(f))||t&&f&&typeof f.length=="number"){r&&(f=r);var l=0,u=function(){};return{s:u,n:function(){return l>=f.length?{done:!0}:{done:!1,value:f[l++]}},e:function(v){throw v},f:u}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
72
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var s=!0,n=!1,g;return{s:function(){r=f[Symbol.iterator]()},n:function(){var v=r.next();return s=v.done,v},e:function(v){n=!0,g=v},f:function(){try{!s&&r.return!=null&&r.return()}finally{if(n)throw g}}}}function ew(f,t){if(f){if(typeof f=="string")return l_(f,t);var r=Object.prototype.toString.call(f).slice(8,-1);if(r==="Object"&&f.constructor&&(r=f.constructor.name),r==="Map"||r==="Set")return Array.from(f);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return l_(f,t)}}function l_(f,t){(t==null||t>f.length)&&(t=f.length);for(var r=0,l=new Array(t);r<t;r++)l[r]=f[r];return l}var ul=Bs(),ba=hs,qc=on(),o_=Ti(),jc=Pc,Gc=yi;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:ba.UPDATE,session_timers_force_refresher:!1,no_answer_timeout:60,register:!0,register_expires:600,registrar_server:null,sockets:null,connection_recovery_max_interval:ba.CONNECTION_RECOVERY_MAX_INTERVAL,connection_recovery_min_interval:ba.CONNECTION_RECOVERY_MIN_INTERVAL,extra_headers:null,via_host:"".concat(ul.createRandomToken(12),".invalid")};var gu={mandatory:{sockets:function(t){var r=[];if(jc.isSocket(t))r.push({socket:t});else if(Array.isArray(t)&&t.length){var l=a_(t),u;try{for(l.s();!(u=l.n()).done;){var s=u.value;Object.prototype.hasOwnProperty.call(s,"socket")&&jc.isSocket(s.socket)?r.push(s):jc.isSocket(s)&&r.push({socket:s})}}catch(n){l.e(n)}finally{l.f()}}else return;return r},uri:function(t){/^sip:/i.test(t)||(t="".concat(ba.SIP,":").concat(t));var r=o_.parse(t);if(r)return r.user?r:void 0}},optional:{authorization_user:function(t){if(qc.parse('"'.concat(t,'"'),"quoted_string")!==-1)return t},authorization_jwt:function(t){if(typeof t=="string")return t},user_agent:function(t){if(typeof t=="string")return t},connection_recovery_max_interval:function(t){if(ul.isDecimal(t)){var r=Number(t);if(r>0)return r}},connection_recovery_min_interval:function(t){if(ul.isDecimal(t)){var r=Number(t);if(r>0)return r}},contact_uri:function(t){if(typeof t=="string"){var r=qc.parse(t,"SIP_URI");if(r!==-1)return r}},display_name:function(t){return t},instance_id:function(t){if(/^uuid:/i.test(t)&&(t=t.substr(5)),qc.parse(t,"uuid")!==-1)return t},no_answer_timeout:function(t){if(ul.isDecimal(t)){var r=Number(t);if(r>0)return r}},session_timers:function(t){if(typeof t=="boolean")return t},session_timers_refresh_method:function(t){if(typeof t=="string"&&(t=t.toUpperCase(),t===ba.INVITE||t===ba.UPDATE))return t},session_timers_force_refresher:function(t){if(typeof t=="boolean")return t},password:function(t){return String(t)},realm:function(t){return String(t)},ha1:function(t){return String(t)},register:function(t){if(typeof t=="boolean")return t},register_expires:function(t){if(ul.isDecimal(t)){var r=Number(t);if(r>0)return r}},registrar_server:function(t){/^sip:/i.test(t)||(t="".concat(ba.SIP,":").concat(t));var r=o_.parse(t);if(r)return r.user?void 0:r},use_preloaded_route:function(t){if(typeof t=="boolean")return t},extra_headers:function(t){var r=[];if(Array.isArray(t)&&t.length){var l=a_(t),u;try{for(l.s();!(u=l.n()).done;){var s=u.value;typeof s=="string"&&r.push(s)}}catch(n){l.e(n)}finally{l.f()}}else return;return r}}};Vc.load=function(f,t){for(var r in gu.mandatory)if(t.hasOwnProperty(r)){var l=t[r],u=gu.mandatory[r](l);if(u!==void 0)f[r]=u;else throw new Gc.ConfigurationError(r,l)}else throw new Gc.ConfigurationError(r);for(var s in gu.optional)if(t.hasOwnProperty(s)){var n=t[s];if(ul.isEmpty(n))continue;var g=gu.optional[s](n);if(g!==void 0)f[s]=g;else throw new Gc.ConfigurationError(s,n)}};function vu(f){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?vu=function(r){return typeof r}:vu=function(r){return r&&typeof Symbol=="function"&&r.constructor===Symbol&&r!==Symbol.prototype?"symbol":typeof r},vu(f)}function tw(f,t){if(!(f instanceof t))throw new TypeError("Cannot call a class as a function")}function u_(f,t){for(var r=0;r<t.length;r++){var l=t[r];l.enumerable=l.enumerable||!1,l.configurable=!0,"value"in l&&(l.writable=!0),Object.defineProperty(f,l.key,l)}}function c_(f,t,r){return t&&u_(f.prototype,t),r&&u_(f,r),f}function sw(f,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");f.prototype=Object.create(t&&t.prototype,{constructor:{value:f,writable:!0,configurable:!0}}),t&&Wc(f,t)}function Wc(f,t){return Wc=Object.setPrototypeOf||function(l,u){return l.__proto__=u,l},Wc(f,t)}function rw(f){var t=iw();return function(){var l=yu(f),u;if(t){var s=yu(this).constructor;u=Reflect.construct(l,arguments,s)}else u=l.apply(this,arguments);return nw(this,u)}}function nw(f,t){return t&&(vu(t)==="object"||typeof t=="function")?t:d_(f)}function d_(f){if(f===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return f}function iw(){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 yu(f){return yu=Object.setPrototypeOf?Object.getPrototypeOf:function(r){return r.__proto__||Object.getPrototypeOf(r)},yu(f)}var aw=ys.EventEmitter,lw=Ts,Rs=hs,ow=Y0,f_=nb,h_=gb,__=$b,Kc=ql,uw=Ub,Tu=Bs(),cw=yi,dw=Ti(),fw=Zh,Yc=xn,hw=Gb,Jc=Vc,Yt=new lw("UA"),$s={STATUS_INIT:0,STATUS_READY:1,STATUS_USER_CLOSED:2,STATUS_NOT_READY:3,CONFIGURATION_ERROR:1,NETWORK_ERROR:2},_w=function(f){sw(r,f);var t=rw(r);c_(r,null,[{key:"C",get:function(){return $s}}]);function r(l){var u;if(tw(this,r),Yt.debug("new() [configuration:%o]",l),u=t.call(this),u._cache={credentials:{}},u._configuration=Object.assign({},Jc.settings),u._dynConfiguration={},u._dialogs={},u._applicants={},u._sessions={},u._transport=null,u._contact=null,u._status=$s.STATUS_INIT,u._error=null,u._transactions={nist:{},nict:{},ist:{},ict:{}},u._data={},u._closeTimer=null,l===void 0)throw new TypeError("Not enough arguments");try{u._loadConfig(l)}catch(s){throw u._status=$s.STATUS_NOT_READY,u._error=$s.CONFIGURATION_ERROR,s}return u._registrator=new ow(d_(u)),u}return c_(r,[{key:"start",value:function(){Yt.debug("start()"),this._status===$s.STATUS_INIT?this._transport.connect():this._status===$s.STATUS_USER_CLOSED?(Yt.debug("restarting UA"),this._closeTimer!==null&&(clearTimeout(this._closeTimer),this._closeTimer=null,this._transport.disconnect()),this._status=$s.STATUS_INIT,this._transport.connect()):this._status===$s.STATUS_READY?Yt.debug("UA is in READY status, not restarted"):Yt.debug("ERROR: connection is down, Auto-Recovery system is trying to reconnect"),this._dynConfiguration.register=this._configuration.register}},{key:"register",value:function(){Yt.debug("register()"),this._dynConfiguration.register=!0,this._registrator.register()}},{key:"unregister",value:function(u){Yt.debug("unregister()"),this._dynConfiguration.register=!1,this._registrator.unregister(u)}},{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(u,s){Yt.debug("call()");var n=new f_(this);return n.connect(u,s),n}},{key:"sendMessage",value:function(u,s,n){Yt.debug("sendMessage()");var g=new h_(this);return g.send(u,s,n),g}},{key:"sendOptions",value:function(u,s,n){Yt.debug("sendOptions()");var g=new __(this);return g.send(u,s,n),g}},{key:"terminateSessions",value:function(u){Yt.debug("terminateSessions()");for(var s in this._sessions)this._sessions[s].isEnded()||this._sessions[s].terminate(u)}},{key:"stop",value:function(){var u=this;if(Yt.debug("stop()"),this._dynConfiguration={},this._status===$s.STATUS_USER_CLOSED){Yt.debug("UA already closed");return}this._registrator.close();var s=Object.keys(this._sessions).length;for(var n in this._sessions)if(Object.prototype.hasOwnProperty.call(this._sessions,n)){Yt.debug("closing session ".concat(n));try{this._sessions[n].terminate()}catch{}}for(var g in this._applicants)if(Object.prototype.hasOwnProperty.call(this._applicants,g))try{this._applicants[g].close()}catch{}this._status=$s.STATUS_USER_CLOSED;var _=Object.keys(this._transactions.nict).length+Object.keys(this._transactions.nist).length+Object.keys(this._transactions.ict).length+Object.keys(this._transactions.ist).length;_===0&&s===0?this._transport.disconnect():this._closeTimer=setTimeout(function(){u._closeTimer=null,u._transport.disconnect()},2e3)}},{key:"normalizeTarget",value:function(u){return Tu.normalizeTarget(u,this._configuration.hostport_params)}},{key:"get",value:function(u){switch(u){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:Yt.warn('get() | cannot get "%s" parameter in runtime',u);return}}},{key:"set",value:function(u,s){switch(u){case"authorization_user":{this._configuration.authorization_user=String(s);break}case"password":{this._configuration.password=String(s);break}case"realm":{this._configuration.realm=String(s);break}case"ha1":{this._configuration.ha1=String(s),this._configuration.password=null;break}case"authorization_jwt":{this._configuration.authorization_jwt=String(s);break}case"display_name":{this._configuration.display_name=s;break}default:return Yt.warn('set() | cannot set "%s" parameter in runtime',u),!1}return!0}},{key:"newTransaction",value:function(u){this._transactions[u.type][u.id]=u,this.emit("newTransaction",{transaction:u})}},{key:"destroyTransaction",value:function(u){delete this._transactions[u.type][u.id],this.emit("transactionDestroyed",{transaction:u})}},{key:"newDialog",value:function(u){this._dialogs[u.id]=u}},{key:"destroyDialog",value:function(u){delete this._dialogs[u.id]}},{key:"newMessage",value:function(u,s){this._applicants[u]=u,this.emit("newMessage",s)}},{key:"newOptions",value:function(u,s){this._applicants[u]=u,this.emit("newOptions",s)}},{key:"destroyMessage",value:function(u){delete this._applicants[u]}},{key:"newRTCSession",value:function(u,s){this._sessions[u.id]=u,this.emit("newRTCSession",s)}},{key:"destroyRTCSession",value:function(u){delete this._sessions[u.id]}},{key:"registered",value:function(u){this.emit("registered",u)}},{key:"unregistered",value:function(u){this.emit("unregistered",u)}},{key:"registrationFailed",value:function(u){this.emit("registrationFailed",u)}},{key:"receiveRequest",value:function(u){var s=u.method;if(u.ruri.user!==this._configuration.uri.user&&u.ruri.user!==this._contact.uri.user){Yt.debug("Request-URI does not point to us"),u.method!==Rs.ACK&&u.reply_sl(404);return}if(u.ruri.scheme===Rs.SIPS){u.reply_sl(416);return}if(!Kc.checkTransaction(this,u)){if(s===Rs.INVITE?new Kc.InviteServerTransaction(this,this._transport,u):s!==Rs.ACK&&s!==Rs.CANCEL&&new Kc.NonInviteServerTransaction(this,this._transport,u),s===Rs.OPTIONS){if(this.listeners("newOptions").length===0){u.reply(200);return}var n=new __(this);n.init_incoming(u)}else if(s===Rs.MESSAGE){if(this.listeners("newMessage").length===0){u.reply(405);return}var g=new h_(this);g.init_incoming(u)}else if(s===Rs.INVITE&&!u.to_tag&&this.listeners("newRTCSession").length===0){u.reply(405);return}var _,v;if(u.to_tag)_=this._findDialog(u.call_id,u.from_tag,u.to_tag),_?_.receiveRequest(u):s===Rs.NOTIFY?(v=this._findSession(u),v?v.receiveRequest(u):(Yt.debug("received NOTIFY request for a non existent subscription"),u.reply(481,"Subscription does not exist"))):s!==Rs.ACK&&u.reply(481);else switch(s){case Rs.INVITE:if(window.RTCPeerConnection)if(u.hasHeader("replaces")){var C=u.replaces;_=this._findDialog(C.call_id,C.from_tag,C.to_tag),_?(v=_.owner,v.isEnded()?u.reply(603):v.receiveRequest(u)):u.reply(481)}else v=new f_(this),v.init_incoming(u);else Yt.warn("INVITE received but WebRTC is not supported"),u.reply(488);break;case Rs.BYE:u.reply(481);break;case Rs.CANCEL:v=this._findSession(u),v?v.receiveRequest(u):Yt.debug("received CANCEL request for a non existent session");break;case Rs.ACK:break;case Rs.NOTIFY:this.emit("sipEvent",{event:u.event,request:u}),u.reply(200);break;default:u.reply(405);break}}}},{key:"_findSession",value:function(u){var s=u.call_id,n=u.from_tag,g=u.to_tag,_=s+n,v=this._sessions[_],C=s+g,R=this._sessions[C];return v||R||null}},{key:"_findDialog",value:function(u,s,n){var g=u+s+n,_=this._dialogs[g];return _||(g=u+n+s,_=this._dialogs[g],_||null)}},{key:"_loadConfig",value:function(u){try{Jc.load(this._configuration,u)}catch(C){throw C}this._configuration.display_name===0&&(this._configuration.display_name="0"),this._configuration.instance_id||(this._configuration.instance_id=Tu.newUUID()),this._configuration.jssip_id=Tu.createRandomToken(5);var s=this._configuration.uri.clone();s.user=null,this._configuration.hostport_params=s.toString().replace(/^sip:/i,"");try{this._transport=new uw(this._configuration.sockets,{max_interval:this._configuration.connection_recovery_max_interval,min_interval:this._configuration.connection_recovery_min_interval}),this._transport.onconnecting=pw.bind(this),this._transport.onconnect=mw.bind(this),this._transport.ondisconnect=gw.bind(this),this._transport.ondata=vw.bind(this)}catch(C){throw Yt.warn(C),new cw.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 n=this._configuration.uri.clone();n.user=null,n.clearParams(),n.clearHeaders(),this._configuration.registrar_server=n}this._configuration.no_answer_timeout*=1e3,this._configuration.contact_uri?this._configuration.via_host=this._configuration.contact_uri.host:this._configuration.contact_uri=new dw("sip",Tu.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 R=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},D=R.anonymous||null,H=R.outbound||null,F="<";return D?F+=this.temp_gruu||"sip:anonymous@anonymous.invalid;transport=ws":F+=this.pub_gruu||this.uri.toString(),H&&(D?!this.temp_gruu:!this.pub_gruu)&&(F+=";ob"),F+=">",F}};var g=["authorization_user","password","realm","ha1","authorization_jwt","display_name","register"];for(var _ in this._configuration)Object.prototype.hasOwnProperty.call(this._configuration,_)&&(g.indexOf(_)!==-1?Object.defineProperty(this._configuration,_,{writable:!0,configurable:!1}):Object.defineProperty(this._configuration,_,{writable:!1,configurable:!1}));Yt.debug("configuration parameters after validation:");for(var v in this._configuration)if(Object.prototype.hasOwnProperty.call(Jc.settings,v))switch(v){case"uri":case"registrar_server":Yt.debug("- ".concat(v,": ").concat(this._configuration[v]));break;case"password":case"ha1":case"authorization_jwt":Yt.debug("- ".concat(v,": NOT SHOWN"));break;default:Yt.debug("- ".concat(v,": ").concat(JSON.stringify(this._configuration[v])))}}},{key:"C",get:function(){return $s}},{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}(aw);function pw(f){this.emit("connecting",f)}function mw(f){this._status!==$s.STATUS_USER_CLOSED&&(this._status=$s.STATUS_READY,this._error=null,this.emit("connected",f),this._dynConfiguration.register&&this._registrator.register())}function gw(f){for(var t=["nict","ict","nist","ist"],r=0,l=t;r<l.length;r++){var u=l[r];for(var s in this._transactions[u])Object.prototype.hasOwnProperty.call(this._transactions[u],s)&&this._transactions[u][s].onTransportError()}this.emit("disconnected",f),this._registrator.onTransportClosed(),this._status!==$s.STATUS_USER_CLOSED&&(this._status=$s.STATUS_NOT_READY,this._error=$s.NETWORK_ERROR)}function vw(f){var t=f.transport,r=f.message;if(r=fw.parseMessage(r,this),!!r&&!(this._status===$s.STATUS_USER_CLOSED&&r instanceof Yc.IncomingRequest)&&hw(r,this,t)){if(r instanceof Yc.IncomingRequest)r.transport=t,this.receiveRequest(r);else if(r instanceof Yc.IncomingResponse){var l;switch(r.method){case Rs.INVITE:l=this._transactions.ict[r.via_branch],l&&l.receiveResponse(r);break;case Rs.ACK:break;default:l=this._transactions.nict[r.via_branch],l&&l.receiveResponse(r);break}}}}function yw(f,t){if(!(f instanceof t))throw new TypeError("Cannot call a class as a function")}function p_(f,t){for(var r=0;r<t.length;r++){var l=t[r];l.enumerable=l.enumerable||!1,l.configurable=!0,"value"in l&&(l.writable=!0),Object.defineProperty(f,l.key,l)}}function Tw(f,t,r){return t&&p_(f.prototype,t),r&&p_(f,r),f}var Sw=Ts,bw=on(),Ws=new Sw("WebSocketInterface"),ww=function(){function f(t){yw(this,f),Ws.debug('new() [url:"%s"]',t),this._url=t,this._sip_uri=null,this._via_transport=null,this._ws=null;var r=bw.parse(t,"absoluteURI");if(r===-1)throw Ws.warn("invalid WebSocket URI: ".concat(t)),new TypeError("Invalid argument: ".concat(t));if(r.scheme!=="wss"&&r.scheme!=="ws")throw Ws.warn("invalid WebSocket URI scheme: ".concat(r.scheme)),new TypeError("Invalid argument: ".concat(t));this._sip_uri="sip:".concat(r.host).concat(r.port?":".concat(r.port):"",";transport=ws"),this._via_transport=r.scheme.toUpperCase()}return Tw(f,[{key:"connect",value:function(){if(Ws.debug("connect()"),this.isConnected()){Ws.debug("WebSocket ".concat(this._url," is already connected"));return}else if(this.isConnecting()){Ws.debug("WebSocket ".concat(this._url," is connecting"));return}this._ws&&this.disconnect(),Ws.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(r){this._onError(r)}}},{key:"disconnect",value:function(){Ws.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(r){return Ws.debug("send()"),this.isConnected()?(this._ws.send(r),!0):(Ws.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(){Ws.debug("WebSocket ".concat(this._url," connected")),this.onconnect()}},{key:"_onClose",value:function(r){var l=r.wasClean,u=r.code,s=r.reason;Ws.debug("WebSocket ".concat(this._url," closed")),l===!1&&Ws.debug("WebSocket abrupt disconnection"),this.ondisconnect(!l,u,s)}},{key:"_onMessage",value:function(r){var l=r.data;Ws.debug("received WebSocket message"),this.ondata(l)}},{key:"_onError",value:function(r){Ws.warn("WebSocket ".concat(this._url," error: "),r)}},{key:"via_transport",get:function(){return this._via_transport},set:function(r){this._via_transport=r.toUpperCase()}},{key:"sip_uri",get:function(){return this._sip_uri}},{key:"url",get:function(){return this._url}}]),f}(),Qc=Uo,Ew=hs,Cw=yi,Aw=Bs(),Iw=_w,Rw=Ti(),$w=oc(),xw=on(),Ow=ww,Dw=al("JsSIP");Dw("version %s",Qc.version);var m_={C:Ew,Exceptions:Cw,Utils:Aw,UA:Iw,URI:Rw,NameAddrHeader:$w,WebSocketInterface:Ow,Grammar:xw,debug:al,get name(){return Qc.title},get version(){return Qc.version}};const cl=al,dl="JsSIP";var gs=class{constructor(t){t?(this._debug=cl.default(`${dl}:${t}`),this._warn=cl.default(`${dl}:WARN:${t}`),this._error=cl.default(`${dl}:ERROR:${t}`)):(this._debug=cl.default(dl),this._warn=cl.default(`${dl}:WARN`),this._error=cl.default(`${dl}: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 Su=Ht(gs),g_=Uo;var Et={USER_AGENT:`${g_.title} ${g_.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 fe=Ht(Et);var cs={},Xc,v_;function Zc(){if(v_)return Xc;v_=1;const f=Nn(),t=Dr();return Xc=class qT{static parse(l){if(l=t.parse(l,"Name_Addr_Header"),l!==-1)return l}constructor(l,u,s){if(!l||!(l instanceof f))throw new TypeError('missing or invalid "uri" parameter');this._uri=l,this._parameters={},this.display_name=u;for(const n in s)Object.prototype.hasOwnProperty.call(s,n)&&this.setParam(n,s[n])}get uri(){return this._uri}get display_name(){return this._display_name}set display_name(l){this._display_name=l===0?"0":l}setParam(l,u){l&&(this._parameters[l.toLowerCase()]=typeof u>"u"||u===null?null:u.toString())}getParam(l){if(l)return this._parameters[l.toLowerCase()]}hasParam(l){if(l)return this._parameters.hasOwnProperty(l.toLowerCase())&&!0||!1}deleteParam(l){if(l=l.toLowerCase(),this._parameters.hasOwnProperty(l)){const u=this._parameters[l];return delete this._parameters[l],u}}clearParams(){this._parameters={}}clone(){return new qT(this._uri.clone(),this._display_name,JSON.parse(JSON.stringify(this._parameters)))}_quote(l){return l.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}toString(){let l=this._display_name?`"${this._quote(this._display_name)}" `:"";l+=`<${this._uri.toString()}>`;for(const u in this._parameters)Object.prototype.hasOwnProperty.call(this._parameters,u)&&(l+=`;${u}`,this._parameters[u]!==null&&(l+=`=${this._parameters[u]}`));return l}},Xc}var ed,y_;function Dr(){return y_||(y_=1,ed=function(){function f(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 t={parse:function(r,l){var u={CRLF:v,DIGIT:C,ALPHA:R,HEXDIG:D,WSP:H,OCTET:F,DQUOTE:q,SP:G,HTAB:te,alphanum:X,reserved:we,unreserved:Q,mark:re,escaped:ke,LWS:Ne,SWS:Z,HCOLON:se,TEXT_UTF8_TRIM:pe,TEXT_UTF8char:me,UTF8_NONASCII:be,UTF8_CONT:_e,LHEX:Ae,token:le,token_nodot:oe,separators:Oe,word:rs,STAR:Re,SLASH:ye,EQUAL:ge,LPAREN:Le,RPAREN:et,RAQUOT:vt,LAQUOT:xt,COMMA:dt,SEMI:ze,COLON:Ye,LDQUOT:Zt,RDQUOT:Mt,comment:nt,ctext:rt,quoted_string:gt,quoted_string_clean:ft,qdtext:Fe,quoted_pair:He,SIP_URI_noparams:qe,SIP_URI:yt,uri_scheme:Ct,uri_scheme_sips:ns,uri_scheme_sip:Ut,userinfo:ar,user:vs,user_unreserved:Oi,password:Di,hostport:zn,host:pr,hostname:as,domainlabel:Pr,toplabel:Vn,IPv6reference:pn,IPv6address:Lr,h16:Qe,ls32:Ve,IPv4address:ls,dec_octet:lr,port:os,uri_parameters:qn,uri_parameter:Hr,transport_param:jn,user_param:ki,method_param:Gn,ttl_param:Ni,maddr_param:Wn,lr_param:Mi,other_param:Kn,pname:Ui,pvalue:Yn,paramchar:Ar,param_unreserved:mr,headers:Fr,header:Br,hname:mn,hvalue:Pi,hnv_unreserved:zr,Request_Response:Vr,Request_Line:kt,Request_URI:gr,absoluteURI:bs,hier_part:qr,net_path:It,abs_path:jr,opaque_part:gn,uric:vn,uric_no_slash:Gr,path_segments:Li,segment:yn,param:or,pchar:Ir,scheme:Wr,authority:Da,srvr:vr,reg_name:Ys,query:yr,SIP_Version:Kr,INVITEm:Yr,ACKm:Jn,OPTIONSm:Qn,BYEm:Xn,CANCELm:ot,REGISTERm:Zn,SUBSCRIBEm:Hi,NOTIFYm:Fi,REFERm:Bi,Method:Tn,Status_Line:Sn,Status_Code:ei,extension_code:zi,Reason_Phrase:bt,Allow_Events:ur,Call_ID:Sl,Contact:bn,contact_param:ie,name_addr:Ls,display_name:Js,contact_params:Jr,c_p_q:ti,c_p_expires:ht,delta_seconds:cr,qvalue:Tr,generic_param:Vt,gen_value:qt,Content_Disposition:Vi,disp_type:ka,disp_param:wn,handling_param:si,Content_Encoding:qi,Content_Length:Na,Content_Type:Ma,media_type:Ua,m_type:ji,discrete_type:Pa,composite_type:Qr,extension_token:En,x_token:Cn,m_subtype:La,m_parameter:An,m_value:In,CSeq:ri,CSeq_value:ni,Expires:Ha,Event:bl,event_type:Xr,From:Zr,from_param:Gi,tag_param:Rn,Max_Forwards:Fa,Min_Expires:wl,Name_Addr_Header:Rt,Proxy_Authenticate:jt,challenge:Rr,other_challenge:en,auth_param:Bt,digest_cln:Gt,realm:Xe,realm_value:Pt,domain:ii,URI:dr,nonce:qs,nonce_value:Ze,opaque:tn,stale:he,algorithm:Je,qop_options:Wi,qop_value:sn,Proxy_Require:ai,Record_Route:El,rec_route:_t,Reason:li,reason_param:oi,reason_cause:ui,Require:Ba,Route:Cl,route_param:ci,Subscription_State:ms,substate_value:za,subexp_params:di,event_reason_value:Qs,Subject:Va,Supported:Al,To:Il,to_param:Ki,Via:Yi,via_param:fi,via_params:rn,via_ttl:hi,via_maddr:Ji,via_received:Qi,via_branch:Hs,response_port:Xi,rport:Zi,sent_protocol:ea,protocol_name:ta,transport:sa,sent_by:ra,via_host:na,via_port:ia,ttl:_i,WWW_Authenticate:aa,Session_Expires:Eo,s_e_expires:js,s_e_params:pi,s_e_refresher:nn,extension_header:la,header_value:Gs,message_body:qa,uuid_URI:Rl,uuid:ja,hex4:Xs,hex8:Zs,hex12:oa,Refer_To:Ga,Replaces:$l,call_id:Wa,replaces_param:mi,to_tag:ws,from_tag:ua,early_flag:ca};if(l!==void 0){if(u[l]===void 0)throw new Error("Invalid rule name: "+f(l)+".")}else l="CRLF";var s=0,n=0,g=[];function _(a){s<n||(s>n&&(n=s,g=[]),g.push(a))}function v(){var a;return r.substr(s,2)===`\r
73
73
  `?(a=`\r
74
74
  `,s+=2):(a=null,_('"\\r\\n"')),a}function C(){var a;return/^[0-9]/.test(r.charAt(s))?(a=r.charAt(s),s++):(a=null,_("[0-9]")),a}function R(){var a;return/^[a-zA-Z]/.test(r.charAt(s))?(a=r.charAt(s),s++):(a=null,_("[a-zA-Z]")),a}function D(){var a;return/^[0-9a-fA-F]/.test(r.charAt(s))?(a=r.charAt(s),s++):(a=null,_("[0-9a-fA-F]")),a}function H(){var a;return a=G(),a===null&&(a=te()),a}function F(){var a;return/^[\0-\xFF]/.test(r.charAt(s))?(a=r.charAt(s),s++):(a=null,_("[\\0-\\xFF]")),a}function q(){var a;return/^["]/.test(r.charAt(s))?(a=r.charAt(s),s++):(a=null,_('["]')),a}function G(){var a;return r.charCodeAt(s)===32?(a=" ",s++):(a=null,_('" "')),a}function te(){var a;return r.charCodeAt(s)===9?(a=" ",s++):(a=null,_('"\\t"')),a}function X(){var a;return/^[a-zA-Z0-9]/.test(r.charAt(s))?(a=r.charAt(s),s++):(a=null,_("[a-zA-Z0-9]")),a}function we(){var a;return r.charCodeAt(s)===59?(a=";",s++):(a=null,_('";"')),a===null&&(r.charCodeAt(s)===47?(a="/",s++):(a=null,_('"/"')),a===null&&(r.charCodeAt(s)===63?(a="?",s++):(a=null,_('"?"')),a===null&&(r.charCodeAt(s)===58?(a=":",s++):(a=null,_('":"')),a===null&&(r.charCodeAt(s)===64?(a="@",s++):(a=null,_('"@"')),a===null&&(r.charCodeAt(s)===38?(a="&",s++):(a=null,_('"&"')),a===null&&(r.charCodeAt(s)===61?(a="=",s++):(a=null,_('"="')),a===null&&(r.charCodeAt(s)===43?(a="+",s++):(a=null,_('"+"')),a===null&&(r.charCodeAt(s)===36?(a="$",s++):(a=null,_('"$"')),a===null&&(r.charCodeAt(s)===44?(a=",",s++):(a=null,_('","'))))))))))),a}function Q(){var a;return a=X(),a===null&&(a=re()),a}function re(){var a;return r.charCodeAt(s)===45?(a="-",s++):(a=null,_('"-"')),a===null&&(r.charCodeAt(s)===95?(a="_",s++):(a=null,_('"_"')),a===null&&(r.charCodeAt(s)===46?(a=".",s++):(a=null,_('"."')),a===null&&(r.charCodeAt(s)===33?(a="!",s++):(a=null,_('"!"')),a===null&&(r.charCodeAt(s)===126?(a="~",s++):(a=null,_('"~"')),a===null&&(r.charCodeAt(s)===42?(a="*",s++):(a=null,_('"*"')),a===null&&(r.charCodeAt(s)===39?(a="'",s++):(a=null,_(`"'"`)),a===null&&(r.charCodeAt(s)===40?(a="(",s++):(a=null,_('"("')),a===null&&(r.charCodeAt(s)===41?(a=")",s++):(a=null,_('")"')))))))))),a}function ke(){var a,e,o,d,p;return d=s,p=s,r.charCodeAt(s)===37?(a="%",s++):(a=null,_('"%"')),a!==null?(e=D(),e!==null?(o=D(),o!==null?a=[a,e,o]:(a=null,s=p)):(a=null,s=p)):(a=null,s=p),a!==null&&(a=function(T,w){return w.join("")}(d,a)),a===null&&(s=d),a}function Ne(){var a,e,o,d,p,T;for(d=s,p=s,T=s,a=[],e=H();e!==null;)a.push(e),e=H();if(a!==null?(e=v(),e!==null?a=[a,e]:(a=null,s=T)):(a=null,s=T),a=a!==null?a:"",a!==null){if(o=H(),o!==null)for(e=[];o!==null;)e.push(o),o=H();else e=null;e!==null?a=[a,e]:(a=null,s=p)}else a=null,s=p;return a!==null&&(a=function(w){return" "}()),a===null&&(s=d),a}function Z(){var a;return a=Ne(),a=a!==null?a:"",a}function se(){var a,e,o,d,p;for(d=s,p=s,a=[],e=G(),e===null&&(e=te());e!==null;)a.push(e),e=G(),e===null&&(e=te());return a!==null?(r.charCodeAt(s)===58?(e=":",s++):(e=null,_('":"')),e!==null?(o=Z(),o!==null?a=[a,e,o]:(a=null,s=p)):(a=null,s=p)):(a=null,s=p),a!==null&&(a=function(T){return":"}()),a===null&&(s=d),a}function pe(){var a,e,o,d,p,T,w;if(p=s,T=s,e=me(),e!==null)for(a=[];e!==null;)a.push(e),e=me();else a=null;if(a!==null){for(e=[],w=s,o=[],d=Ne();d!==null;)o.push(d),d=Ne();for(o!==null?(d=me(),d!==null?o=[o,d]:(o=null,s=w)):(o=null,s=w);o!==null;){for(e.push(o),w=s,o=[],d=Ne();d!==null;)o.push(d),d=Ne();o!==null?(d=me(),d!==null?o=[o,d]:(o=null,s=w)):(o=null,s=w)}e!==null?a=[a,e]:(a=null,s=T)}else a=null,s=T;return a!==null&&(a=function(O){return r.substring(s,O)}(p)),a===null&&(s=p),a}function me(){var a;return/^[!-~]/.test(r.charAt(s))?(a=r.charAt(s),s++):(a=null,_("[!-~]")),a===null&&(a=be()),a}function be(){var a;return/^[\x80-\uFFFF]/.test(r.charAt(s))?(a=r.charAt(s),s++):(a=null,_("[\\x80-\\uFFFF]")),a}function _e(){var a;return/^[\x80-\xBF]/.test(r.charAt(s))?(a=r.charAt(s),s++):(a=null,_("[\\x80-\\xBF]")),a}function Ae(){var a;return a=C(),a===null&&(/^[a-f]/.test(r.charAt(s))?(a=r.charAt(s),s++):(a=null,_("[a-f]"))),a}function le(){var a,e,o;if(o=s,e=X(),e===null&&(r.charCodeAt(s)===45?(e="-",s++):(e=null,_('"-"')),e===null&&(r.charCodeAt(s)===46?(e=".",s++):(e=null,_('"."')),e===null&&(r.charCodeAt(s)===33?(e="!",s++):(e=null,_('"!"')),e===null&&(r.charCodeAt(s)===37?(e="%",s++):(e=null,_('"%"')),e===null&&(r.charCodeAt(s)===42?(e="*",s++):(e=null,_('"*"')),e===null&&(r.charCodeAt(s)===95?(e="_",s++):(e=null,_('"_"')),e===null&&(r.charCodeAt(s)===43?(e="+",s++):(e=null,_('"+"')),e===null&&(r.charCodeAt(s)===96?(e="`",s++):(e=null,_('"`"')),e===null&&(r.charCodeAt(s)===39?(e="'",s++):(e=null,_(`"'"`)),e===null&&(r.charCodeAt(s)===126?(e="~",s++):(e=null,_('"~"')))))))))))),e!==null)for(a=[];e!==null;)a.push(e),e=X(),e===null&&(r.charCodeAt(s)===45?(e="-",s++):(e=null,_('"-"')),e===null&&(r.charCodeAt(s)===46?(e=".",s++):(e=null,_('"."')),e===null&&(r.charCodeAt(s)===33?(e="!",s++):(e=null,_('"!"')),e===null&&(r.charCodeAt(s)===37?(e="%",s++):(e=null,_('"%"')),e===null&&(r.charCodeAt(s)===42?(e="*",s++):(e=null,_('"*"')),e===null&&(r.charCodeAt(s)===95?(e="_",s++):(e=null,_('"_"')),e===null&&(r.charCodeAt(s)===43?(e="+",s++):(e=null,_('"+"')),e===null&&(r.charCodeAt(s)===96?(e="`",s++):(e=null,_('"`"')),e===null&&(r.charCodeAt(s)===39?(e="'",s++):(e=null,_(`"'"`)),e===null&&(r.charCodeAt(s)===126?(e="~",s++):(e=null,_('"~"'))))))))))));else a=null;return a!==null&&(a=function(d){return r.substring(s,d)}(o)),a===null&&(s=o),a}function oe(){var a,e,o;if(o=s,e=X(),e===null&&(r.charCodeAt(s)===45?(e="-",s++):(e=null,_('"-"')),e===null&&(r.charCodeAt(s)===33?(e="!",s++):(e=null,_('"!"')),e===null&&(r.charCodeAt(s)===37?(e="%",s++):(e=null,_('"%"')),e===null&&(r.charCodeAt(s)===42?(e="*",s++):(e=null,_('"*"')),e===null&&(r.charCodeAt(s)===95?(e="_",s++):(e=null,_('"_"')),e===null&&(r.charCodeAt(s)===43?(e="+",s++):(e=null,_('"+"')),e===null&&(r.charCodeAt(s)===96?(e="`",s++):(e=null,_('"`"')),e===null&&(r.charCodeAt(s)===39?(e="'",s++):(e=null,_(`"'"`)),e===null&&(r.charCodeAt(s)===126?(e="~",s++):(e=null,_('"~"'))))))))))),e!==null)for(a=[];e!==null;)a.push(e),e=X(),e===null&&(r.charCodeAt(s)===45?(e="-",s++):(e=null,_('"-"')),e===null&&(r.charCodeAt(s)===33?(e="!",s++):(e=null,_('"!"')),e===null&&(r.charCodeAt(s)===37?(e="%",s++):(e=null,_('"%"')),e===null&&(r.charCodeAt(s)===42?(e="*",s++):(e=null,_('"*"')),e===null&&(r.charCodeAt(s)===95?(e="_",s++):(e=null,_('"_"')),e===null&&(r.charCodeAt(s)===43?(e="+",s++):(e=null,_('"+"')),e===null&&(r.charCodeAt(s)===96?(e="`",s++):(e=null,_('"`"')),e===null&&(r.charCodeAt(s)===39?(e="'",s++):(e=null,_(`"'"`)),e===null&&(r.charCodeAt(s)===126?(e="~",s++):(e=null,_('"~"')))))))))));else a=null;return a!==null&&(a=function(d){return r.substring(s,d)}(o)),a===null&&(s=o),a}function Oe(){var a;return r.charCodeAt(s)===40?(a="(",s++):(a=null,_('"("')),a===null&&(r.charCodeAt(s)===41?(a=")",s++):(a=null,_('")"')),a===null&&(r.charCodeAt(s)===60?(a="<",s++):(a=null,_('"<"')),a===null&&(r.charCodeAt(s)===62?(a=">",s++):(a=null,_('">"')),a===null&&(r.charCodeAt(s)===64?(a="@",s++):(a=null,_('"@"')),a===null&&(r.charCodeAt(s)===44?(a=",",s++):(a=null,_('","')),a===null&&(r.charCodeAt(s)===59?(a=";",s++):(a=null,_('";"')),a===null&&(r.charCodeAt(s)===58?(a=":",s++):(a=null,_('":"')),a===null&&(r.charCodeAt(s)===92?(a="\\",s++):(a=null,_('"\\\\"')),a===null&&(a=q(),a===null&&(r.charCodeAt(s)===47?(a="/",s++):(a=null,_('"/"')),a===null&&(r.charCodeAt(s)===91?(a="[",s++):(a=null,_('"["')),a===null&&(r.charCodeAt(s)===93?(a="]",s++):(a=null,_('"]"')),a===null&&(r.charCodeAt(s)===63?(a="?",s++):(a=null,_('"?"')),a===null&&(r.charCodeAt(s)===61?(a="=",s++):(a=null,_('"="')),a===null&&(r.charCodeAt(s)===123?(a="{",s++):(a=null,_('"{"')),a===null&&(r.charCodeAt(s)===125?(a="}",s++):(a=null,_('"}"')),a===null&&(a=G(),a===null&&(a=te())))))))))))))))))),a}function rs(){var a,e,o;if(o=s,e=X(),e===null&&(r.charCodeAt(s)===45?(e="-",s++):(e=null,_('"-"')),e===null&&(r.charCodeAt(s)===46?(e=".",s++):(e=null,_('"."')),e===null&&(r.charCodeAt(s)===33?(e="!",s++):(e=null,_('"!"')),e===null&&(r.charCodeAt(s)===37?(e="%",s++):(e=null,_('"%"')),e===null&&(r.charCodeAt(s)===42?(e="*",s++):(e=null,_('"*"')),e===null&&(r.charCodeAt(s)===95?(e="_",s++):(e=null,_('"_"')),e===null&&(r.charCodeAt(s)===43?(e="+",s++):(e=null,_('"+"')),e===null&&(r.charCodeAt(s)===96?(e="`",s++):(e=null,_('"`"')),e===null&&(r.charCodeAt(s)===39?(e="'",s++):(e=null,_(`"'"`)),e===null&&(r.charCodeAt(s)===126?(e="~",s++):(e=null,_('"~"')),e===null&&(r.charCodeAt(s)===40?(e="(",s++):(e=null,_('"("')),e===null&&(r.charCodeAt(s)===41?(e=")",s++):(e=null,_('")"')),e===null&&(r.charCodeAt(s)===60?(e="<",s++):(e=null,_('"<"')),e===null&&(r.charCodeAt(s)===62?(e=">",s++):(e=null,_('">"')),e===null&&(r.charCodeAt(s)===58?(e=":",s++):(e=null,_('":"')),e===null&&(r.charCodeAt(s)===92?(e="\\",s++):(e=null,_('"\\\\"')),e===null&&(e=q(),e===null&&(r.charCodeAt(s)===47?(e="/",s++):(e=null,_('"/"')),e===null&&(r.charCodeAt(s)===91?(e="[",s++):(e=null,_('"["')),e===null&&(r.charCodeAt(s)===93?(e="]",s++):(e=null,_('"]"')),e===null&&(r.charCodeAt(s)===63?(e="?",s++):(e=null,_('"?"')),e===null&&(r.charCodeAt(s)===123?(e="{",s++):(e=null,_('"{"')),e===null&&(r.charCodeAt(s)===125?(e="}",s++):(e=null,_('"}"'))))))))))))))))))))))))),e!==null)for(a=[];e!==null;)a.push(e),e=X(),e===null&&(r.charCodeAt(s)===45?(e="-",s++):(e=null,_('"-"')),e===null&&(r.charCodeAt(s)===46?(e=".",s++):(e=null,_('"."')),e===null&&(r.charCodeAt(s)===33?(e="!",s++):(e=null,_('"!"')),e===null&&(r.charCodeAt(s)===37?(e="%",s++):(e=null,_('"%"')),e===null&&(r.charCodeAt(s)===42?(e="*",s++):(e=null,_('"*"')),e===null&&(r.charCodeAt(s)===95?(e="_",s++):(e=null,_('"_"')),e===null&&(r.charCodeAt(s)===43?(e="+",s++):(e=null,_('"+"')),e===null&&(r.charCodeAt(s)===96?(e="`",s++):(e=null,_('"`"')),e===null&&(r.charCodeAt(s)===39?(e="'",s++):(e=null,_(`"'"`)),e===null&&(r.charCodeAt(s)===126?(e="~",s++):(e=null,_('"~"')),e===null&&(r.charCodeAt(s)===40?(e="(",s++):(e=null,_('"("')),e===null&&(r.charCodeAt(s)===41?(e=")",s++):(e=null,_('")"')),e===null&&(r.charCodeAt(s)===60?(e="<",s++):(e=null,_('"<"')),e===null&&(r.charCodeAt(s)===62?(e=">",s++):(e=null,_('">"')),e===null&&(r.charCodeAt(s)===58?(e=":",s++):(e=null,_('":"')),e===null&&(r.charCodeAt(s)===92?(e="\\",s++):(e=null,_('"\\\\"')),e===null&&(e=q(),e===null&&(r.charCodeAt(s)===47?(e="/",s++):(e=null,_('"/"')),e===null&&(r.charCodeAt(s)===91?(e="[",s++):(e=null,_('"["')),e===null&&(r.charCodeAt(s)===93?(e="]",s++):(e=null,_('"]"')),e===null&&(r.charCodeAt(s)===63?(e="?",s++):(e=null,_('"?"')),e===null&&(r.charCodeAt(s)===123?(e="{",s++):(e=null,_('"{"')),e===null&&(r.charCodeAt(s)===125?(e="}",s++):(e=null,_('"}"')))))))))))))))))))))))));else a=null;return a!==null&&(a=function(d){return r.substring(s,d)}(o)),a===null&&(s=o),a}function Re(){var a,e,o,d,p;return d=s,p=s,a=Z(),a!==null?(r.charCodeAt(s)===42?(e="*",s++):(e=null,_('"*"')),e!==null?(o=Z(),o!==null?a=[a,e,o]:(a=null,s=p)):(a=null,s=p)):(a=null,s=p),a!==null&&(a=function(T){return"*"}()),a===null&&(s=d),a}function ye(){var a,e,o,d,p;return d=s,p=s,a=Z(),a!==null?(r.charCodeAt(s)===47?(e="/",s++):(e=null,_('"/"')),e!==null?(o=Z(),o!==null?a=[a,e,o]:(a=null,s=p)):(a=null,s=p)):(a=null,s=p),a!==null&&(a=function(T){return"/"}()),a===null&&(s=d),a}function ge(){var a,e,o,d,p;return d=s,p=s,a=Z(),a!==null?(r.charCodeAt(s)===61?(e="=",s++):(e=null,_('"="')),e!==null?(o=Z(),o!==null?a=[a,e,o]:(a=null,s=p)):(a=null,s=p)):(a=null,s=p),a!==null&&(a=function(T){return"="}()),a===null&&(s=d),a}function Le(){var a,e,o,d,p;return d=s,p=s,a=Z(),a!==null?(r.charCodeAt(s)===40?(e="(",s++):(e=null,_('"("')),e!==null?(o=Z(),o!==null?a=[a,e,o]:(a=null,s=p)):(a=null,s=p)):(a=null,s=p),a!==null&&(a=function(T){return"("}()),a===null&&(s=d),a}function et(){var a,e,o,d,p;return d=s,p=s,a=Z(),a!==null?(r.charCodeAt(s)===41?(e=")",s++):(e=null,_('")"')),e!==null?(o=Z(),o!==null?a=[a,e,o]:(a=null,s=p)):(a=null,s=p)):(a=null,s=p),a!==null&&(a=function(T){return")"}()),a===null&&(s=d),a}function vt(){var a,e,o,d;return o=s,d=s,r.charCodeAt(s)===62?(a=">",s++):(a=null,_('">"')),a!==null?(e=Z(),e!==null?a=[a,e]:(a=null,s=d)):(a=null,s=d),a!==null&&(a=function(p){return">"}()),a===null&&(s=o),a}function xt(){var a,e,o,d;return o=s,d=s,a=Z(),a!==null?(r.charCodeAt(s)===60?(e="<",s++):(e=null,_('"<"')),e!==null?a=[a,e]:(a=null,s=d)):(a=null,s=d),a!==null&&(a=function(p){return"<"}()),a===null&&(s=o),a}function dt(){var a,e,o,d,p;return d=s,p=s,a=Z(),a!==null?(r.charCodeAt(s)===44?(e=",",s++):(e=null,_('","')),e!==null?(o=Z(),o!==null?a=[a,e,o]:(a=null,s=p)):(a=null,s=p)):(a=null,s=p),a!==null&&(a=function(T){return","}()),a===null&&(s=d),a}function ze(){var a,e,o,d,p;return d=s,p=s,a=Z(),a!==null?(r.charCodeAt(s)===59?(e=";",s++):(e=null,_('";"')),e!==null?(o=Z(),o!==null?a=[a,e,o]:(a=null,s=p)):(a=null,s=p)):(a=null,s=p),a!==null&&(a=function(T){return";"}()),a===null&&(s=d),a}function Ye(){var a,e,o,d,p;return d=s,p=s,a=Z(),a!==null?(r.charCodeAt(s)===58?(e=":",s++):(e=null,_('":"')),e!==null?(o=Z(),o!==null?a=[a,e,o]:(a=null,s=p)):(a=null,s=p)):(a=null,s=p),a!==null&&(a=function(T){return":"}()),a===null&&(s=d),a}function Zt(){var a,e,o,d;return o=s,d=s,a=Z(),a!==null?(e=q(),e!==null?a=[a,e]:(a=null,s=d)):(a=null,s=d),a!==null&&(a=function(p){return'"'}()),a===null&&(s=o),a}function Mt(){var a,e,o,d;return o=s,d=s,a=q(),a!==null?(e=Z(),e!==null?a=[a,e]:(a=null,s=d)):(a=null,s=d),a!==null&&(a=function(p){return'"'}()),a===null&&(s=o),a}function nt(){var a,e,o,d;if(d=s,a=Le(),a!==null){for(e=[],o=rt(),o===null&&(o=He(),o===null&&(o=nt()));o!==null;)e.push(o),o=rt(),o===null&&(o=He(),o===null&&(o=nt()));e!==null?(o=et(),o!==null?a=[a,e,o]:(a=null,s=d)):(a=null,s=d)}else a=null,s=d;return a}function rt(){var a;return/^[!-']/.test(r.charAt(s))?(a=r.charAt(s),s++):(a=null,_("[!-']")),a===null&&(/^[*-[]/.test(r.charAt(s))?(a=r.charAt(s),s++):(a=null,_("[*-[]")),a===null&&(/^[\]-~]/.test(r.charAt(s))?(a=r.charAt(s),s++):(a=null,_("[\\]-~]")),a===null&&(a=be(),a===null&&(a=Ne())))),a}function gt(){var a,e,o,d,p,T;if(p=s,T=s,a=Z(),a!==null)if(e=q(),e!==null){for(o=[],d=Fe(),d===null&&(d=He());d!==null;)o.push(d),d=Fe(),d===null&&(d=He());o!==null?(d=q(),d!==null?a=[a,e,o,d]:(a=null,s=T)):(a=null,s=T)}else a=null,s=T;else a=null,s=T;return a!==null&&(a=function(w){return r.substring(s,w)}(p)),a===null&&(s=p),a}function ft(){var a,e,o,d,p,T;if(p=s,T=s,a=Z(),a!==null)if(e=q(),e!==null){for(o=[],d=Fe(),d===null&&(d=He());d!==null;)o.push(d),d=Fe(),d===null&&(d=He());o!==null?(d=q(),d!==null?a=[a,e,o,d]:(a=null,s=T)):(a=null,s=T)}else a=null,s=T;else a=null,s=T;return a!==null&&(a=function(w){var O=r.substring(s,w).trim();return O.substring(1,O.length-1).replace(/\\([\x00-\x09\x0b-\x0c\x0e-\x7f])/g,"$1")}(p)),a===null&&(s=p),a}function Fe(){var a;return a=Ne(),a===null&&(r.charCodeAt(s)===33?(a="!",s++):(a=null,_('"!"')),a===null&&(/^[#-[]/.test(r.charAt(s))?(a=r.charAt(s),s++):(a=null,_("[#-[]")),a===null&&(/^[\]-~]/.test(r.charAt(s))?(a=r.charAt(s),s++):(a=null,_("[\\]-~]")),a===null&&(a=be())))),a}function He(){var a,e,o;return o=s,r.charCodeAt(s)===92?(a="\\",s++):(a=null,_('"\\\\"')),a!==null?(/^[\0-\t]/.test(r.charAt(s))?(e=r.charAt(s),s++):(e=null,_("[\\0-\\t]")),e===null&&(/^[\x0B-\f]/.test(r.charAt(s))?(e=r.charAt(s),s++):(e=null,_("[\\x0B-\\f]")),e===null&&(/^[\x0E-]/.test(r.charAt(s))?(e=r.charAt(s),s++):(e=null,_("[\\x0E-]")))),e!==null?a=[a,e]:(a=null,s=o)):(a=null,s=o),a}function qe(){var a,e,o,d,p,T;return p=s,T=s,a=Ct(),a!==null?(r.charCodeAt(s)===58?(e=":",s++):(e=null,_('":"')),e!==null?(o=ar(),o=o!==null?o:"",o!==null?(d=zn(),d!==null?a=[a,e,o,d]:(a=null,s=T)):(a=null,s=T)):(a=null,s=T)):(a=null,s=T),a!==null&&(a=function(w){try{K.uri=new Ya(K.scheme,K.user,K.host,K.port),delete K.scheme,delete K.user,delete K.host,delete K.host_type,delete K.port}catch{K=-1}}()),a===null&&(s=p),a}function yt(){var a,e,o,d,p,T,w,O;return w=s,O=s,a=Ct(),a!==null?(r.charCodeAt(s)===58?(e=":",s++):(e=null,_('":"')),e!==null?(o=ar(),o=o!==null?o:"",o!==null?(d=zn(),d!==null?(p=qn(),p!==null?(T=Fr(),T=T!==null?T:"",T!==null?a=[a,e,o,d,p,T]:(a=null,s=O)):(a=null,s=O)):(a=null,s=O)):(a=null,s=O)):(a=null,s=O)):(a=null,s=O),a!==null&&(a=function(B){try{K.uri=new Ya(K.scheme,K.user,K.host,K.port,K.uri_params,K.uri_headers),delete K.scheme,delete K.user,delete K.host,delete K.host_type,delete K.port,delete K.uri_params,l==="SIP_URI"&&(K=K.uri)}catch{K=-1}}()),a===null&&(s=w),a}function Ct(){var a;return a=ns(),a===null&&(a=Ut()),a}function ns(){var a,e;return e=s,r.substr(s,4).toLowerCase()==="sips"?(a=r.substr(s,4),s+=4):(a=null,_('"sips"')),a!==null&&(a=function(o,d){K.scheme=d.toLowerCase()}(e,a)),a===null&&(s=e),a}function Ut(){var a,e;return e=s,r.substr(s,3).toLowerCase()==="sip"?(a=r.substr(s,3),s+=3):(a=null,_('"sip"')),a!==null&&(a=function(o,d){K.scheme=d.toLowerCase()}(e,a)),a===null&&(s=e),a}function ar(){var a,e,o,d,p,T;return d=s,p=s,a=vs(),a!==null?(T=s,r.charCodeAt(s)===58?(e=":",s++):(e=null,_('":"')),e!==null?(o=Di(),o!==null?e=[e,o]:(e=null,s=T)):(e=null,s=T),e=e!==null?e:"",e!==null?(r.charCodeAt(s)===64?(o="@",s++):(o=null,_('"@"')),o!==null?a=[a,e,o]:(a=null,s=p)):(a=null,s=p)):(a=null,s=p),a!==null&&(a=function(w){K.user=decodeURIComponent(r.substring(s-1,w))}(d)),a===null&&(s=d),a}function vs(){var a,e;if(e=Q(),e===null&&(e=ke(),e===null&&(e=Oi())),e!==null)for(a=[];e!==null;)a.push(e),e=Q(),e===null&&(e=ke(),e===null&&(e=Oi()));else a=null;return a}function Oi(){var a;return r.charCodeAt(s)===38?(a="&",s++):(a=null,_('"&"')),a===null&&(r.charCodeAt(s)===61?(a="=",s++):(a=null,_('"="')),a===null&&(r.charCodeAt(s)===43?(a="+",s++):(a=null,_('"+"')),a===null&&(r.charCodeAt(s)===36?(a="$",s++):(a=null,_('"$"')),a===null&&(r.charCodeAt(s)===44?(a=",",s++):(a=null,_('","')),a===null&&(r.charCodeAt(s)===59?(a=";",s++):(a=null,_('";"')),a===null&&(r.charCodeAt(s)===63?(a="?",s++):(a=null,_('"?"')),a===null&&(r.charCodeAt(s)===47?(a="/",s++):(a=null,_('"/"'))))))))),a}function Di(){var a,e,o;for(o=s,a=[],e=Q(),e===null&&(e=ke(),e===null&&(r.charCodeAt(s)===38?(e="&",s++):(e=null,_('"&"')),e===null&&(r.charCodeAt(s)===61?(e="=",s++):(e=null,_('"="')),e===null&&(r.charCodeAt(s)===43?(e="+",s++):(e=null,_('"+"')),e===null&&(r.charCodeAt(s)===36?(e="$",s++):(e=null,_('"$"')),e===null&&(r.charCodeAt(s)===44?(e=",",s++):(e=null,_('","'))))))));e!==null;)a.push(e),e=Q(),e===null&&(e=ke(),e===null&&(r.charCodeAt(s)===38?(e="&",s++):(e=null,_('"&"')),e===null&&(r.charCodeAt(s)===61?(e="=",s++):(e=null,_('"="')),e===null&&(r.charCodeAt(s)===43?(e="+",s++):(e=null,_('"+"')),e===null&&(r.charCodeAt(s)===36?(e="$",s++):(e=null,_('"$"')),e===null&&(r.charCodeAt(s)===44?(e=",",s++):(e=null,_('","'))))))));return a!==null&&(a=function(d){K.password=r.substring(s,d)}(o)),a===null&&(s=o),a}function zn(){var a,e,o,d,p;return d=s,a=pr(),a!==null?(p=s,r.charCodeAt(s)===58?(e=":",s++):(e=null,_('":"')),e!==null?(o=os(),o!==null?e=[e,o]:(e=null,s=p)):(e=null,s=p),e=e!==null?e:"",e!==null?a=[a,e]:(a=null,s=d)):(a=null,s=d),a}function pr(){var a,e;return e=s,a=as(),a===null&&(a=ls(),a===null&&(a=pn())),a!==null&&(a=function(o){return K.host=r.substring(s,o).toLowerCase(),K.host}(e)),a===null&&(s=e),a}function as(){var a,e,o,d,p,T;for(d=s,p=s,a=[],T=s,e=Pr(),e!==null?(r.charCodeAt(s)===46?(o=".",s++):(o=null,_('"."')),o!==null?e=[e,o]:(e=null,s=T)):(e=null,s=T);e!==null;)a.push(e),T=s,e=Pr(),e!==null?(r.charCodeAt(s)===46?(o=".",s++):(o=null,_('"."')),o!==null?e=[e,o]:(e=null,s=T)):(e=null,s=T);return a!==null?(e=Vn(),e!==null?(r.charCodeAt(s)===46?(o=".",s++):(o=null,_('"."')),o=o!==null?o:"",o!==null?a=[a,e,o]:(a=null,s=p)):(a=null,s=p)):(a=null,s=p),a!==null&&(a=function(w){return K.host_type="domain",r.substring(s,w)}(d)),a===null&&(s=d),a}function Pr(){var a,e,o,d;if(d=s,a=X(),a!==null){for(e=[],o=X(),o===null&&(r.charCodeAt(s)===45?(o="-",s++):(o=null,_('"-"')),o===null&&(r.charCodeAt(s)===95?(o="_",s++):(o=null,_('"_"'))));o!==null;)e.push(o),o=X(),o===null&&(r.charCodeAt(s)===45?(o="-",s++):(o=null,_('"-"')),o===null&&(r.charCodeAt(s)===95?(o="_",s++):(o=null,_('"_"'))));e!==null?a=[a,e]:(a=null,s=d)}else a=null,s=d;return a}function Vn(){var a,e,o,d;if(d=s,a=R(),a!==null){for(e=[],o=X(),o===null&&(r.charCodeAt(s)===45?(o="-",s++):(o=null,_('"-"')),o===null&&(r.charCodeAt(s)===95?(o="_",s++):(o=null,_('"_"'))));o!==null;)e.push(o),o=X(),o===null&&(r.charCodeAt(s)===45?(o="-",s++):(o=null,_('"-"')),o===null&&(r.charCodeAt(s)===95?(o="_",s++):(o=null,_('"_"'))));e!==null?a=[a,e]:(a=null,s=d)}else a=null,s=d;return a}function pn(){var a,e,o,d,p;return d=s,p=s,r.charCodeAt(s)===91?(a="[",s++):(a=null,_('"["')),a!==null?(e=Lr(),e!==null?(r.charCodeAt(s)===93?(o="]",s++):(o=null,_('"]"')),o!==null?a=[a,e,o]:(a=null,s=p)):(a=null,s=p)):(a=null,s=p),a!==null&&(a=function(T){return K.host_type="IPv6",r.substring(s,T)}(d)),a===null&&(s=d),a}function Lr(){var a,e,o,d,p,T,w,O,B,ee,Pe,At,Es,xr,ce,W;return xr=s,ce=s,a=Qe(),a!==null?(r.charCodeAt(s)===58?(e=":",s++):(e=null,_('":"')),e!==null?(o=Qe(),o!==null?(r.charCodeAt(s)===58?(d=":",s++):(d=null,_('":"')),d!==null?(p=Qe(),p!==null?(r.charCodeAt(s)===58?(T=":",s++):(T=null,_('":"')),T!==null?(w=Qe(),w!==null?(r.charCodeAt(s)===58?(O=":",s++):(O=null,_('":"')),O!==null?(B=Qe(),B!==null?(r.charCodeAt(s)===58?(ee=":",s++):(ee=null,_('":"')),ee!==null?(Pe=Qe(),Pe!==null?(r.charCodeAt(s)===58?(At=":",s++):(At=null,_('":"')),At!==null?(Es=Ve(),Es!==null?a=[a,e,o,d,p,T,w,O,B,ee,Pe,At,Es]:(a=null,s=ce)):(a=null,s=ce)):(a=null,s=ce)):(a=null,s=ce)):(a=null,s=ce)):(a=null,s=ce)):(a=null,s=ce)):(a=null,s=ce)):(a=null,s=ce)):(a=null,s=ce)):(a=null,s=ce)):(a=null,s=ce)):(a=null,s=ce),a===null&&(ce=s,r.substr(s,2)==="::"?(a="::",s+=2):(a=null,_('"::"')),a!==null?(e=Qe(),e!==null?(r.charCodeAt(s)===58?(o=":",s++):(o=null,_('":"')),o!==null?(d=Qe(),d!==null?(r.charCodeAt(s)===58?(p=":",s++):(p=null,_('":"')),p!==null?(T=Qe(),T!==null?(r.charCodeAt(s)===58?(w=":",s++):(w=null,_('":"')),w!==null?(O=Qe(),O!==null?(r.charCodeAt(s)===58?(B=":",s++):(B=null,_('":"')),B!==null?(ee=Qe(),ee!==null?(r.charCodeAt(s)===58?(Pe=":",s++):(Pe=null,_('":"')),Pe!==null?(At=Ve(),At!==null?a=[a,e,o,d,p,T,w,O,B,ee,Pe,At]:(a=null,s=ce)):(a=null,s=ce)):(a=null,s=ce)):(a=null,s=ce)):(a=null,s=ce)):(a=null,s=ce)):(a=null,s=ce)):(a=null,s=ce)):(a=null,s=ce)):(a=null,s=ce)):(a=null,s=ce)):(a=null,s=ce),a===null&&(ce=s,r.substr(s,2)==="::"?(a="::",s+=2):(a=null,_('"::"')),a!==null?(e=Qe(),e!==null?(r.charCodeAt(s)===58?(o=":",s++):(o=null,_('":"')),o!==null?(d=Qe(),d!==null?(r.charCodeAt(s)===58?(p=":",s++):(p=null,_('":"')),p!==null?(T=Qe(),T!==null?(r.charCodeAt(s)===58?(w=":",s++):(w=null,_('":"')),w!==null?(O=Qe(),O!==null?(r.charCodeAt(s)===58?(B=":",s++):(B=null,_('":"')),B!==null?(ee=Ve(),ee!==null?a=[a,e,o,d,p,T,w,O,B,ee]:(a=null,s=ce)):(a=null,s=ce)):(a=null,s=ce)):(a=null,s=ce)):(a=null,s=ce)):(a=null,s=ce)):(a=null,s=ce)):(a=null,s=ce)):(a=null,s=ce)):(a=null,s=ce),a===null&&(ce=s,r.substr(s,2)==="::"?(a="::",s+=2):(a=null,_('"::"')),a!==null?(e=Qe(),e!==null?(r.charCodeAt(s)===58?(o=":",s++):(o=null,_('":"')),o!==null?(d=Qe(),d!==null?(r.charCodeAt(s)===58?(p=":",s++):(p=null,_('":"')),p!==null?(T=Qe(),T!==null?(r.charCodeAt(s)===58?(w=":",s++):(w=null,_('":"')),w!==null?(O=Ve(),O!==null?a=[a,e,o,d,p,T,w,O]:(a=null,s=ce)):(a=null,s=ce)):(a=null,s=ce)):(a=null,s=ce)):(a=null,s=ce)):(a=null,s=ce)):(a=null,s=ce)):(a=null,s=ce),a===null&&(ce=s,r.substr(s,2)==="::"?(a="::",s+=2):(a=null,_('"::"')),a!==null?(e=Qe(),e!==null?(r.charCodeAt(s)===58?(o=":",s++):(o=null,_('":"')),o!==null?(d=Qe(),d!==null?(r.charCodeAt(s)===58?(p=":",s++):(p=null,_('":"')),p!==null?(T=Ve(),T!==null?a=[a,e,o,d,p,T]:(a=null,s=ce)):(a=null,s=ce)):(a=null,s=ce)):(a=null,s=ce)):(a=null,s=ce)):(a=null,s=ce),a===null&&(ce=s,r.substr(s,2)==="::"?(a="::",s+=2):(a=null,_('"::"')),a!==null?(e=Qe(),e!==null?(r.charCodeAt(s)===58?(o=":",s++):(o=null,_('":"')),o!==null?(d=Ve(),d!==null?a=[a,e,o,d]:(a=null,s=ce)):(a=null,s=ce)):(a=null,s=ce)):(a=null,s=ce),a===null&&(ce=s,r.substr(s,2)==="::"?(a="::",s+=2):(a=null,_('"::"')),a!==null?(e=Ve(),e!==null?a=[a,e]:(a=null,s=ce)):(a=null,s=ce),a===null&&(ce=s,r.substr(s,2)==="::"?(a="::",s+=2):(a=null,_('"::"')),a!==null?(e=Qe(),e!==null?a=[a,e]:(a=null,s=ce)):(a=null,s=ce),a===null&&(ce=s,a=Qe(),a!==null?(r.substr(s,2)==="::"?(e="::",s+=2):(e=null,_('"::"')),e!==null?(o=Qe(),o!==null?(r.charCodeAt(s)===58?(d=":",s++):(d=null,_('":"')),d!==null?(p=Qe(),p!==null?(r.charCodeAt(s)===58?(T=":",s++):(T=null,_('":"')),T!==null?(w=Qe(),w!==null?(r.charCodeAt(s)===58?(O=":",s++):(O=null,_('":"')),O!==null?(B=Qe(),B!==null?(r.charCodeAt(s)===58?(ee=":",s++):(ee=null,_('":"')),ee!==null?(Pe=Ve(),Pe!==null?a=[a,e,o,d,p,T,w,O,B,ee,Pe]:(a=null,s=ce)):(a=null,s=ce)):(a=null,s=ce)):(a=null,s=ce)):(a=null,s=ce)):(a=null,s=ce)):(a=null,s=ce)):(a=null,s=ce)):(a=null,s=ce)):(a=null,s=ce)):(a=null,s=ce),a===null&&(ce=s,a=Qe(),a!==null?(W=s,r.charCodeAt(s)===58?(e=":",s++):(e=null,_('":"')),e!==null?(o=Qe(),o!==null?e=[e,o]:(e=null,s=W)):(e=null,s=W),e=e!==null?e:"",e!==null?(r.substr(s,2)==="::"?(o="::",s+=2):(o=null,_('"::"')),o!==null?(d=Qe(),d!==null?(r.charCodeAt(s)===58?(p=":",s++):(p=null,_('":"')),p!==null?(T=Qe(),T!==null?(r.charCodeAt(s)===58?(w=":",s++):(w=null,_('":"')),w!==null?(O=Qe(),O!==null?(r.charCodeAt(s)===58?(B=":",s++):(B=null,_('":"')),B!==null?(ee=Ve(),ee!==null?a=[a,e,o,d,p,T,w,O,B,ee]:(a=null,s=ce)):(a=null,s=ce)):(a=null,s=ce)):(a=null,s=ce)):(a=null,s=ce)):(a=null,s=ce)):(a=null,s=ce)):(a=null,s=ce)):(a=null,s=ce)):(a=null,s=ce),a===null&&(ce=s,a=Qe(),a!==null?(W=s,r.charCodeAt(s)===58?(e=":",s++):(e=null,_('":"')),e!==null?(o=Qe(),o!==null?e=[e,o]:(e=null,s=W)):(e=null,s=W),e=e!==null?e:"",e!==null?(W=s,r.charCodeAt(s)===58?(o=":",s++):(o=null,_('":"')),o!==null?(d=Qe(),d!==null?o=[o,d]:(o=null,s=W)):(o=null,s=W),o=o!==null?o:"",o!==null?(r.substr(s,2)==="::"?(d="::",s+=2):(d=null,_('"::"')),d!==null?(p=Qe(),p!==null?(r.charCodeAt(s)===58?(T=":",s++):(T=null,_('":"')),T!==null?(w=Qe(),w!==null?(r.charCodeAt(s)===58?(O=":",s++):(O=null,_('":"')),O!==null?(B=Ve(),B!==null?a=[a,e,o,d,p,T,w,O,B]:(a=null,s=ce)):(a=null,s=ce)):(a=null,s=ce)):(a=null,s=ce)):(a=null,s=ce)):(a=null,s=ce)):(a=null,s=ce)):(a=null,s=ce)):(a=null,s=ce),a===null&&(ce=s,a=Qe(),a!==null?(W=s,r.charCodeAt(s)===58?(e=":",s++):(e=null,_('":"')),e!==null?(o=Qe(),o!==null?e=[e,o]:(e=null,s=W)):(e=null,s=W),e=e!==null?e:"",e!==null?(W=s,r.charCodeAt(s)===58?(o=":",s++):(o=null,_('":"')),o!==null?(d=Qe(),d!==null?o=[o,d]:(o=null,s=W)):(o=null,s=W),o=o!==null?o:"",o!==null?(W=s,r.charCodeAt(s)===58?(d=":",s++):(d=null,_('":"')),d!==null?(p=Qe(),p!==null?d=[d,p]:(d=null,s=W)):(d=null,s=W),d=d!==null?d:"",d!==null?(r.substr(s,2)==="::"?(p="::",s+=2):(p=null,_('"::"')),p!==null?(T=Qe(),T!==null?(r.charCodeAt(s)===58?(w=":",s++):(w=null,_('":"')),w!==null?(O=Ve(),O!==null?a=[a,e,o,d,p,T,w,O]:(a=null,s=ce)):(a=null,s=ce)):(a=null,s=ce)):(a=null,s=ce)):(a=null,s=ce)):(a=null,s=ce)):(a=null,s=ce)):(a=null,s=ce),a===null&&(ce=s,a=Qe(),a!==null?(W=s,r.charCodeAt(s)===58?(e=":",s++):(e=null,_('":"')),e!==null?(o=Qe(),o!==null?e=[e,o]:(e=null,s=W)):(e=null,s=W),e=e!==null?e:"",e!==null?(W=s,r.charCodeAt(s)===58?(o=":",s++):(o=null,_('":"')),o!==null?(d=Qe(),d!==null?o=[o,d]:(o=null,s=W)):(o=null,s=W),o=o!==null?o:"",o!==null?(W=s,r.charCodeAt(s)===58?(d=":",s++):(d=null,_('":"')),d!==null?(p=Qe(),p!==null?d=[d,p]:(d=null,s=W)):(d=null,s=W),d=d!==null?d:"",d!==null?(W=s,r.charCodeAt(s)===58?(p=":",s++):(p=null,_('":"')),p!==null?(T=Qe(),T!==null?p=[p,T]:(p=null,s=W)):(p=null,s=W),p=p!==null?p:"",p!==null?(r.substr(s,2)==="::"?(T="::",s+=2):(T=null,_('"::"')),T!==null?(w=Ve(),w!==null?a=[a,e,o,d,p,T,w]:(a=null,s=ce)):(a=null,s=ce)):(a=null,s=ce)):(a=null,s=ce)):(a=null,s=ce)):(a=null,s=ce)):(a=null,s=ce),a===null&&(ce=s,a=Qe(),a!==null?(W=s,r.charCodeAt(s)===58?(e=":",s++):(e=null,_('":"')),e!==null?(o=Qe(),o!==null?e=[e,o]:(e=null,s=W)):(e=null,s=W),e=e!==null?e:"",e!==null?(W=s,r.charCodeAt(s)===58?(o=":",s++):(o=null,_('":"')),o!==null?(d=Qe(),d!==null?o=[o,d]:(o=null,s=W)):(o=null,s=W),o=o!==null?o:"",o!==null?(W=s,r.charCodeAt(s)===58?(d=":",s++):(d=null,_('":"')),d!==null?(p=Qe(),p!==null?d=[d,p]:(d=null,s=W)):(d=null,s=W),d=d!==null?d:"",d!==null?(W=s,r.charCodeAt(s)===58?(p=":",s++):(p=null,_('":"')),p!==null?(T=Qe(),T!==null?p=[p,T]:(p=null,s=W)):(p=null,s=W),p=p!==null?p:"",p!==null?(W=s,r.charCodeAt(s)===58?(T=":",s++):(T=null,_('":"')),T!==null?(w=Qe(),w!==null?T=[T,w]:(T=null,s=W)):(T=null,s=W),T=T!==null?T:"",T!==null?(r.substr(s,2)==="::"?(w="::",s+=2):(w=null,_('"::"')),w!==null?(O=Qe(),O!==null?a=[a,e,o,d,p,T,w,O]:(a=null,s=ce)):(a=null,s=ce)):(a=null,s=ce)):(a=null,s=ce)):(a=null,s=ce)):(a=null,s=ce)):(a=null,s=ce)):(a=null,s=ce),a===null&&(ce=s,a=Qe(),a!==null?(W=s,r.charCodeAt(s)===58?(e=":",s++):(e=null,_('":"')),e!==null?(o=Qe(),o!==null?e=[e,o]:(e=null,s=W)):(e=null,s=W),e=e!==null?e:"",e!==null?(W=s,r.charCodeAt(s)===58?(o=":",s++):(o=null,_('":"')),o!==null?(d=Qe(),d!==null?o=[o,d]:(o=null,s=W)):(o=null,s=W),o=o!==null?o:"",o!==null?(W=s,r.charCodeAt(s)===58?(d=":",s++):(d=null,_('":"')),d!==null?(p=Qe(),p!==null?d=[d,p]:(d=null,s=W)):(d=null,s=W),d=d!==null?d:"",d!==null?(W=s,r.charCodeAt(s)===58?(p=":",s++):(p=null,_('":"')),p!==null?(T=Qe(),T!==null?p=[p,T]:(p=null,s=W)):(p=null,s=W),p=p!==null?p:"",p!==null?(W=s,r.charCodeAt(s)===58?(T=":",s++):(T=null,_('":"')),T!==null?(w=Qe(),w!==null?T=[T,w]:(T=null,s=W)):(T=null,s=W),T=T!==null?T:"",T!==null?(W=s,r.charCodeAt(s)===58?(w=":",s++):(w=null,_('":"')),w!==null?(O=Qe(),O!==null?w=[w,O]:(w=null,s=W)):(w=null,s=W),w=w!==null?w:"",w!==null?(r.substr(s,2)==="::"?(O="::",s+=2):(O=null,_('"::"')),O!==null?a=[a,e,o,d,p,T,w,O]:(a=null,s=ce)):(a=null,s=ce)):(a=null,s=ce)):(a=null,s=ce)):(a=null,s=ce)):(a=null,s=ce)):(a=null,s=ce)):(a=null,s=ce))))))))))))))),a!==null&&(a=function(tt){return K.host_type="IPv6",r.substring(s,tt)}(xr)),a===null&&(s=xr),a}function Qe(){var a,e,o,d,p;return p=s,a=D(),a!==null?(e=D(),e=e!==null?e:"",e!==null?(o=D(),o=o!==null?o:"",o!==null?(d=D(),d=d!==null?d:"",d!==null?a=[a,e,o,d]:(a=null,s=p)):(a=null,s=p)):(a=null,s=p)):(a=null,s=p),a}function Ve(){var a,e,o,d;return d=s,a=Qe(),a!==null?(r.charCodeAt(s)===58?(e=":",s++):(e=null,_('":"')),e!==null?(o=Qe(),o!==null?a=[a,e,o]:(a=null,s=d)):(a=null,s=d)):(a=null,s=d),a===null&&(a=ls()),a}function ls(){var a,e,o,d,p,T,w,O,B;return O=s,B=s,a=lr(),a!==null?(r.charCodeAt(s)===46?(e=".",s++):(e=null,_('"."')),e!==null?(o=lr(),o!==null?(r.charCodeAt(s)===46?(d=".",s++):(d=null,_('"."')),d!==null?(p=lr(),p!==null?(r.charCodeAt(s)===46?(T=".",s++):(T=null,_('"."')),T!==null?(w=lr(),w!==null?a=[a,e,o,d,p,T,w]:(a=null,s=B)):(a=null,s=B)):(a=null,s=B)):(a=null,s=B)):(a=null,s=B)):(a=null,s=B)):(a=null,s=B),a!==null&&(a=function(ee){return K.host_type="IPv4",r.substring(s,ee)}(O)),a===null&&(s=O),a}function lr(){var a,e,o,d;return d=s,r.substr(s,2)==="25"?(a="25",s+=2):(a=null,_('"25"')),a!==null?(/^[0-5]/.test(r.charAt(s))?(e=r.charAt(s),s++):(e=null,_("[0-5]")),e!==null?a=[a,e]:(a=null,s=d)):(a=null,s=d),a===null&&(d=s,r.charCodeAt(s)===50?(a="2",s++):(a=null,_('"2"')),a!==null?(/^[0-4]/.test(r.charAt(s))?(e=r.charAt(s),s++):(e=null,_("[0-4]")),e!==null?(o=C(),o!==null?a=[a,e,o]:(a=null,s=d)):(a=null,s=d)):(a=null,s=d),a===null&&(d=s,r.charCodeAt(s)===49?(a="1",s++):(a=null,_('"1"')),a!==null?(e=C(),e!==null?(o=C(),o!==null?a=[a,e,o]:(a=null,s=d)):(a=null,s=d)):(a=null,s=d),a===null&&(d=s,/^[1-9]/.test(r.charAt(s))?(a=r.charAt(s),s++):(a=null,_("[1-9]")),a!==null?(e=C(),e!==null?a=[a,e]:(a=null,s=d)):(a=null,s=d),a===null&&(a=C())))),a}function os(){var a,e,o,d,p,T,w;return T=s,w=s,a=C(),a=a!==null?a:"",a!==null?(e=C(),e=e!==null?e:"",e!==null?(o=C(),o=o!==null?o:"",o!==null?(d=C(),d=d!==null?d:"",d!==null?(p=C(),p=p!==null?p:"",p!==null?a=[a,e,o,d,p]:(a=null,s=w)):(a=null,s=w)):(a=null,s=w)):(a=null,s=w)):(a=null,s=w),a!==null&&(a=function(O,B){return B=parseInt(B.join("")),K.port=B,B}(T,a)),a===null&&(s=T),a}function qn(){var a,e,o,d;for(a=[],d=s,r.charCodeAt(s)===59?(e=";",s++):(e=null,_('";"')),e!==null?(o=Hr(),o!==null?e=[e,o]:(e=null,s=d)):(e=null,s=d);e!==null;)a.push(e),d=s,r.charCodeAt(s)===59?(e=";",s++):(e=null,_('";"')),e!==null?(o=Hr(),o!==null?e=[e,o]:(e=null,s=d)):(e=null,s=d);return a}function Hr(){var a;return a=jn(),a===null&&(a=ki(),a===null&&(a=Gn(),a===null&&(a=Ni(),a===null&&(a=Wn(),a===null&&(a=Mi(),a===null&&(a=Kn())))))),a}function jn(){var a,e,o,d;return o=s,d=s,r.substr(s,10).toLowerCase()==="transport="?(a=r.substr(s,10),s+=10):(a=null,_('"transport="')),a!==null?(r.substr(s,3).toLowerCase()==="udp"?(e=r.substr(s,3),s+=3):(e=null,_('"udp"')),e===null&&(r.substr(s,3).toLowerCase()==="tcp"?(e=r.substr(s,3),s+=3):(e=null,_('"tcp"')),e===null&&(r.substr(s,4).toLowerCase()==="sctp"?(e=r.substr(s,4),s+=4):(e=null,_('"sctp"')),e===null&&(r.substr(s,3).toLowerCase()==="tls"?(e=r.substr(s,3),s+=3):(e=null,_('"tls"')),e===null&&(e=le())))),e!==null?a=[a,e]:(a=null,s=d)):(a=null,s=d),a!==null&&(a=function(p,T){K.uri_params||(K.uri_params={}),K.uri_params.transport=T.toLowerCase()}(o,a[1])),a===null&&(s=o),a}function ki(){var a,e,o,d;return o=s,d=s,r.substr(s,5).toLowerCase()==="user="?(a=r.substr(s,5),s+=5):(a=null,_('"user="')),a!==null?(r.substr(s,5).toLowerCase()==="phone"?(e=r.substr(s,5),s+=5):(e=null,_('"phone"')),e===null&&(r.substr(s,2).toLowerCase()==="ip"?(e=r.substr(s,2),s+=2):(e=null,_('"ip"')),e===null&&(e=le())),e!==null?a=[a,e]:(a=null,s=d)):(a=null,s=d),a!==null&&(a=function(p,T){K.uri_params||(K.uri_params={}),K.uri_params.user=T.toLowerCase()}(o,a[1])),a===null&&(s=o),a}function Gn(){var a,e,o,d;return o=s,d=s,r.substr(s,7).toLowerCase()==="method="?(a=r.substr(s,7),s+=7):(a=null,_('"method="')),a!==null?(e=Tn(),e!==null?a=[a,e]:(a=null,s=d)):(a=null,s=d),a!==null&&(a=function(p,T){K.uri_params||(K.uri_params={}),K.uri_params.method=T}(o,a[1])),a===null&&(s=o),a}function Ni(){var a,e,o,d;return o=s,d=s,r.substr(s,4).toLowerCase()==="ttl="?(a=r.substr(s,4),s+=4):(a=null,_('"ttl="')),a!==null?(e=_i(),e!==null?a=[a,e]:(a=null,s=d)):(a=null,s=d),a!==null&&(a=function(p,T){K.params||(K.params={}),K.params.ttl=T}(o,a[1])),a===null&&(s=o),a}function Wn(){var a,e,o,d;return o=s,d=s,r.substr(s,6).toLowerCase()==="maddr="?(a=r.substr(s,6),s+=6):(a=null,_('"maddr="')),a!==null?(e=pr(),e!==null?a=[a,e]:(a=null,s=d)):(a=null,s=d),a!==null&&(a=function(p,T){K.uri_params||(K.uri_params={}),K.uri_params.maddr=T}(o,a[1])),a===null&&(s=o),a}function Mi(){var a,e,o,d,p,T;return d=s,p=s,r.substr(s,2).toLowerCase()==="lr"?(a=r.substr(s,2),s+=2):(a=null,_('"lr"')),a!==null?(T=s,r.charCodeAt(s)===61?(e="=",s++):(e=null,_('"="')),e!==null?(o=le(),o!==null?e=[e,o]:(e=null,s=T)):(e=null,s=T),e=e!==null?e:"",e!==null?a=[a,e]:(a=null,s=p)):(a=null,s=p),a!==null&&(a=function(w){K.uri_params||(K.uri_params={}),K.uri_params.lr=void 0}()),a===null&&(s=d),a}function Kn(){var a,e,o,d,p,T;return d=s,p=s,a=Ui(),a!==null?(T=s,r.charCodeAt(s)===61?(e="=",s++):(e=null,_('"="')),e!==null?(o=Yn(),o!==null?e=[e,o]:(e=null,s=T)):(e=null,s=T),e=e!==null?e:"",e!==null?a=[a,e]:(a=null,s=p)):(a=null,s=p),a!==null&&(a=function(w,O,B){K.uri_params||(K.uri_params={}),typeof B>"u"?B=void 0:B=B[1],K.uri_params[O.toLowerCase()]=B}(d,a[0],a[1])),a===null&&(s=d),a}function Ui(){var a,e,o;if(o=s,e=Ar(),e!==null)for(a=[];e!==null;)a.push(e),e=Ar();else a=null;return a!==null&&(a=function(d,p){return p.join("")}(o,a)),a===null&&(s=o),a}function Yn(){var a,e,o;if(o=s,e=Ar(),e!==null)for(a=[];e!==null;)a.push(e),e=Ar();else a=null;return a!==null&&(a=function(d,p){return p.join("")}(o,a)),a===null&&(s=o),a}function Ar(){var a;return a=mr(),a===null&&(a=Q(),a===null&&(a=ke())),a}function mr(){var a;return r.charCodeAt(s)===91?(a="[",s++):(a=null,_('"["')),a===null&&(r.charCodeAt(s)===93?(a="]",s++):(a=null,_('"]"')),a===null&&(r.charCodeAt(s)===47?(a="/",s++):(a=null,_('"/"')),a===null&&(r.charCodeAt(s)===58?(a=":",s++):(a=null,_('":"')),a===null&&(r.charCodeAt(s)===38?(a="&",s++):(a=null,_('"&"')),a===null&&(r.charCodeAt(s)===43?(a="+",s++):(a=null,_('"+"')),a===null&&(r.charCodeAt(s)===36?(a="$",s++):(a=null,_('"$"')))))))),a}function Fr(){var a,e,o,d,p,T,w;if(T=s,r.charCodeAt(s)===63?(a="?",s++):(a=null,_('"?"')),a!==null)if(e=Br(),e!==null){for(o=[],w=s,r.charCodeAt(s)===38?(d="&",s++):(d=null,_('"&"')),d!==null?(p=Br(),p!==null?d=[d,p]:(d=null,s=w)):(d=null,s=w);d!==null;)o.push(d),w=s,r.charCodeAt(s)===38?(d="&",s++):(d=null,_('"&"')),d!==null?(p=Br(),p!==null?d=[d,p]:(d=null,s=w)):(d=null,s=w);o!==null?a=[a,e,o]:(a=null,s=T)}else a=null,s=T;else a=null,s=T;return a}function Br(){var a,e,o,d,p;return d=s,p=s,a=mn(),a!==null?(r.charCodeAt(s)===61?(e="=",s++):(e=null,_('"="')),e!==null?(o=Pi(),o!==null?a=[a,e,o]:(a=null,s=p)):(a=null,s=p)):(a=null,s=p),a!==null&&(a=function(T,w,O){w=w.join("").toLowerCase(),O=O.join(""),K.uri_headers||(K.uri_headers={}),K.uri_headers[w]?K.uri_headers[w].push(O):K.uri_headers[w]=[O]}(d,a[0],a[2])),a===null&&(s=d),a}function mn(){var a,e;if(e=zr(),e===null&&(e=Q(),e===null&&(e=ke())),e!==null)for(a=[];e!==null;)a.push(e),e=zr(),e===null&&(e=Q(),e===null&&(e=ke()));else a=null;return a}function Pi(){var a,e;for(a=[],e=zr(),e===null&&(e=Q(),e===null&&(e=ke()));e!==null;)a.push(e),e=zr(),e===null&&(e=Q(),e===null&&(e=ke()));return a}function zr(){var a;return r.charCodeAt(s)===91?(a="[",s++):(a=null,_('"["')),a===null&&(r.charCodeAt(s)===93?(a="]",s++):(a=null,_('"]"')),a===null&&(r.charCodeAt(s)===47?(a="/",s++):(a=null,_('"/"')),a===null&&(r.charCodeAt(s)===63?(a="?",s++):(a=null,_('"?"')),a===null&&(r.charCodeAt(s)===58?(a=":",s++):(a=null,_('":"')),a===null&&(r.charCodeAt(s)===43?(a="+",s++):(a=null,_('"+"')),a===null&&(r.charCodeAt(s)===36?(a="$",s++):(a=null,_('"$"')))))))),a}function Vr(){var a;return a=Sn(),a===null&&(a=kt()),a}function kt(){var a,e,o,d,p,T;return T=s,a=Tn(),a!==null?(e=G(),e!==null?(o=gr(),o!==null?(d=G(),d!==null?(p=Kr(),p!==null?a=[a,e,o,d,p]:(a=null,s=T)):(a=null,s=T)):(a=null,s=T)):(a=null,s=T)):(a=null,s=T),a}function gr(){var a;return a=yt(),a===null&&(a=bs()),a}function bs(){var a,e,o,d;return d=s,a=Wr(),a!==null?(r.charCodeAt(s)===58?(e=":",s++):(e=null,_('":"')),e!==null?(o=qr(),o===null&&(o=gn()),o!==null?a=[a,e,o]:(a=null,s=d)):(a=null,s=d)):(a=null,s=d),a}function qr(){var a,e,o,d,p;return d=s,a=It(),a===null&&(a=jr()),a!==null?(p=s,r.charCodeAt(s)===63?(e="?",s++):(e=null,_('"?"')),e!==null?(o=yr(),o!==null?e=[e,o]:(e=null,s=p)):(e=null,s=p),e=e!==null?e:"",e!==null?a=[a,e]:(a=null,s=d)):(a=null,s=d),a}function It(){var a,e,o,d;return d=s,r.substr(s,2)==="//"?(a="//",s+=2):(a=null,_('"//"')),a!==null?(e=Da(),e!==null?(o=jr(),o=o!==null?o:"",o!==null?a=[a,e,o]:(a=null,s=d)):(a=null,s=d)):(a=null,s=d),a}function jr(){var a,e,o;return o=s,r.charCodeAt(s)===47?(a="/",s++):(a=null,_('"/"')),a!==null?(e=Li(),e!==null?a=[a,e]:(a=null,s=o)):(a=null,s=o),a}function gn(){var a,e,o,d;if(d=s,a=Gr(),a!==null){for(e=[],o=vn();o!==null;)e.push(o),o=vn();e!==null?a=[a,e]:(a=null,s=d)}else a=null,s=d;return a}function vn(){var a;return a=we(),a===null&&(a=Q(),a===null&&(a=ke())),a}function Gr(){var a;return a=Q(),a===null&&(a=ke(),a===null&&(r.charCodeAt(s)===59?(a=";",s++):(a=null,_('";"')),a===null&&(r.charCodeAt(s)===63?(a="?",s++):(a=null,_('"?"')),a===null&&(r.charCodeAt(s)===58?(a=":",s++):(a=null,_('":"')),a===null&&(r.charCodeAt(s)===64?(a="@",s++):(a=null,_('"@"')),a===null&&(r.charCodeAt(s)===38?(a="&",s++):(a=null,_('"&"')),a===null&&(r.charCodeAt(s)===61?(a="=",s++):(a=null,_('"="')),a===null&&(r.charCodeAt(s)===43?(a="+",s++):(a=null,_('"+"')),a===null&&(r.charCodeAt(s)===36?(a="$",s++):(a=null,_('"$"')),a===null&&(r.charCodeAt(s)===44?(a=",",s++):(a=null,_('","')))))))))))),a}function Li(){var a,e,o,d,p,T;if(p=s,a=yn(),a!==null){for(e=[],T=s,r.charCodeAt(s)===47?(o="/",s++):(o=null,_('"/"')),o!==null?(d=yn(),d!==null?o=[o,d]:(o=null,s=T)):(o=null,s=T);o!==null;)e.push(o),T=s,r.charCodeAt(s)===47?(o="/",s++):(o=null,_('"/"')),o!==null?(d=yn(),d!==null?o=[o,d]:(o=null,s=T)):(o=null,s=T);e!==null?a=[a,e]:(a=null,s=p)}else a=null,s=p;return a}function yn(){var a,e,o,d,p,T;for(p=s,a=[],e=Ir();e!==null;)a.push(e),e=Ir();if(a!==null){for(e=[],T=s,r.charCodeAt(s)===59?(o=";",s++):(o=null,_('";"')),o!==null?(d=or(),d!==null?o=[o,d]:(o=null,s=T)):(o=null,s=T);o!==null;)e.push(o),T=s,r.charCodeAt(s)===59?(o=";",s++):(o=null,_('";"')),o!==null?(d=or(),d!==null?o=[o,d]:(o=null,s=T)):(o=null,s=T);e!==null?a=[a,e]:(a=null,s=p)}else a=null,s=p;return a}function or(){var a,e;for(a=[],e=Ir();e!==null;)a.push(e),e=Ir();return a}function Ir(){var a;return a=Q(),a===null&&(a=ke(),a===null&&(r.charCodeAt(s)===58?(a=":",s++):(a=null,_('":"')),a===null&&(r.charCodeAt(s)===64?(a="@",s++):(a=null,_('"@"')),a===null&&(r.charCodeAt(s)===38?(a="&",s++):(a=null,_('"&"')),a===null&&(r.charCodeAt(s)===61?(a="=",s++):(a=null,_('"="')),a===null&&(r.charCodeAt(s)===43?(a="+",s++):(a=null,_('"+"')),a===null&&(r.charCodeAt(s)===36?(a="$",s++):(a=null,_('"$"')),a===null&&(r.charCodeAt(s)===44?(a=",",s++):(a=null,_('","')))))))))),a}function Wr(){var a,e,o,d,p;if(d=s,p=s,a=R(),a!==null){for(e=[],o=R(),o===null&&(o=C(),o===null&&(r.charCodeAt(s)===43?(o="+",s++):(o=null,_('"+"')),o===null&&(r.charCodeAt(s)===45?(o="-",s++):(o=null,_('"-"')),o===null&&(r.charCodeAt(s)===46?(o=".",s++):(o=null,_('"."'))))));o!==null;)e.push(o),o=R(),o===null&&(o=C(),o===null&&(r.charCodeAt(s)===43?(o="+",s++):(o=null,_('"+"')),o===null&&(r.charCodeAt(s)===45?(o="-",s++):(o=null,_('"-"')),o===null&&(r.charCodeAt(s)===46?(o=".",s++):(o=null,_('"."'))))));e!==null?a=[a,e]:(a=null,s=p)}else a=null,s=p;return a!==null&&(a=function(T){K.scheme=r.substring(s,T)}(d)),a===null&&(s=d),a}function Da(){var a;return a=vr(),a===null&&(a=Ys()),a}function vr(){var a,e,o,d;return o=s,d=s,a=ar(),a!==null?(r.charCodeAt(s)===64?(e="@",s++):(e=null,_('"@"')),e!==null?a=[a,e]:(a=null,s=d)):(a=null,s=d),a=a!==null?a:"",a!==null?(e=zn(),e!==null?a=[a,e]:(a=null,s=o)):(a=null,s=o),a=a!==null?a:"",a}function Ys(){var a,e;if(e=Q(),e===null&&(e=ke(),e===null&&(r.charCodeAt(s)===36?(e="$",s++):(e=null,_('"$"')),e===null&&(r.charCodeAt(s)===44?(e=",",s++):(e=null,_('","')),e===null&&(r.charCodeAt(s)===59?(e=";",s++):(e=null,_('";"')),e===null&&(r.charCodeAt(s)===58?(e=":",s++):(e=null,_('":"')),e===null&&(r.charCodeAt(s)===64?(e="@",s++):(e=null,_('"@"')),e===null&&(r.charCodeAt(s)===38?(e="&",s++):(e=null,_('"&"')),e===null&&(r.charCodeAt(s)===61?(e="=",s++):(e=null,_('"="')),e===null&&(r.charCodeAt(s)===43?(e="+",s++):(e=null,_('"+"'))))))))))),e!==null)for(a=[];e!==null;)a.push(e),e=Q(),e===null&&(e=ke(),e===null&&(r.charCodeAt(s)===36?(e="$",s++):(e=null,_('"$"')),e===null&&(r.charCodeAt(s)===44?(e=",",s++):(e=null,_('","')),e===null&&(r.charCodeAt(s)===59?(e=";",s++):(e=null,_('";"')),e===null&&(r.charCodeAt(s)===58?(e=":",s++):(e=null,_('":"')),e===null&&(r.charCodeAt(s)===64?(e="@",s++):(e=null,_('"@"')),e===null&&(r.charCodeAt(s)===38?(e="&",s++):(e=null,_('"&"')),e===null&&(r.charCodeAt(s)===61?(e="=",s++):(e=null,_('"="')),e===null&&(r.charCodeAt(s)===43?(e="+",s++):(e=null,_('"+"')))))))))));else a=null;return a}function yr(){var a,e;for(a=[],e=vn();e!==null;)a.push(e),e=vn();return a}function Kr(){var a,e,o,d,p,T,w,O;if(w=s,O=s,r.substr(s,3).toLowerCase()==="sip"?(a=r.substr(s,3),s+=3):(a=null,_('"SIP"')),a!==null)if(r.charCodeAt(s)===47?(e="/",s++):(e=null,_('"/"')),e!==null){if(d=C(),d!==null)for(o=[];d!==null;)o.push(d),d=C();else o=null;if(o!==null)if(r.charCodeAt(s)===46?(d=".",s++):(d=null,_('"."')),d!==null){if(T=C(),T!==null)for(p=[];T!==null;)p.push(T),T=C();else p=null;p!==null?a=[a,e,o,d,p]:(a=null,s=O)}else a=null,s=O;else a=null,s=O}else a=null,s=O;else a=null,s=O;return a!==null&&(a=function(B){K.sip_version=r.substring(s,B)}(w)),a===null&&(s=w),a}function Yr(){var a;return r.substr(s,6)==="INVITE"?(a="INVITE",s+=6):(a=null,_('"INVITE"')),a}function Jn(){var a;return r.substr(s,3)==="ACK"?(a="ACK",s+=3):(a=null,_('"ACK"')),a}function Qn(){var a;return r.substr(s,7)==="OPTIONS"?(a="OPTIONS",s+=7):(a=null,_('"OPTIONS"')),a}function Xn(){var a;return r.substr(s,3)==="BYE"?(a="BYE",s+=3):(a=null,_('"BYE"')),a}function ot(){var a;return r.substr(s,6)==="CANCEL"?(a="CANCEL",s+=6):(a=null,_('"CANCEL"')),a}function Zn(){var a;return r.substr(s,8)==="REGISTER"?(a="REGISTER",s+=8):(a=null,_('"REGISTER"')),a}function Hi(){var a;return r.substr(s,9)==="SUBSCRIBE"?(a="SUBSCRIBE",s+=9):(a=null,_('"SUBSCRIBE"')),a}function Fi(){var a;return r.substr(s,6)==="NOTIFY"?(a="NOTIFY",s+=6):(a=null,_('"NOTIFY"')),a}function Bi(){var a;return r.substr(s,5)==="REFER"?(a="REFER",s+=5):(a=null,_('"REFER"')),a}function Tn(){var a,e;return e=s,a=Yr(),a===null&&(a=Jn(),a===null&&(a=Qn(),a===null&&(a=Xn(),a===null&&(a=ot(),a===null&&(a=Zn(),a===null&&(a=Hi(),a===null&&(a=Fi(),a===null&&(a=Bi(),a===null&&(a=le()))))))))),a!==null&&(a=function(o){return K.method=r.substring(s,o),K.method}(e)),a===null&&(s=e),a}function Sn(){var a,e,o,d,p,T;return T=s,a=Kr(),a!==null?(e=G(),e!==null?(o=ei(),o!==null?(d=G(),d!==null?(p=bt(),p!==null?a=[a,e,o,d,p]:(a=null,s=T)):(a=null,s=T)):(a=null,s=T)):(a=null,s=T)):(a=null,s=T),a}function ei(){var a,e;return e=s,a=zi(),a!==null&&(a=function(o,d){K.status_code=parseInt(d.join(""))}(e,a)),a===null&&(s=e),a}function zi(){var a,e,o,d;return d=s,a=C(),a!==null?(e=C(),e!==null?(o=C(),o!==null?a=[a,e,o]:(a=null,s=d)):(a=null,s=d)):(a=null,s=d),a}function bt(){var a,e,o;for(o=s,a=[],e=we(),e===null&&(e=Q(),e===null&&(e=ke(),e===null&&(e=be(),e===null&&(e=_e(),e===null&&(e=G(),e===null&&(e=te()))))));e!==null;)a.push(e),e=we(),e===null&&(e=Q(),e===null&&(e=ke(),e===null&&(e=be(),e===null&&(e=_e(),e===null&&(e=G(),e===null&&(e=te()))))));return a!==null&&(a=function(d){K.reason_phrase=r.substring(s,d)}(o)),a===null&&(s=o),a}function ur(){var a,e,o,d,p,T;if(p=s,a=Xr(),a!==null){for(e=[],T=s,o=dt(),o!==null?(d=Xr(),d!==null?o=[o,d]:(o=null,s=T)):(o=null,s=T);o!==null;)e.push(o),T=s,o=dt(),o!==null?(d=Xr(),d!==null?o=[o,d]:(o=null,s=T)):(o=null,s=T);e!==null?a=[a,e]:(a=null,s=p)}else a=null,s=p;return a}function Sl(){var a,e,o,d,p,T;return d=s,p=s,a=rs(),a!==null?(T=s,r.charCodeAt(s)===64?(e="@",s++):(e=null,_('"@"')),e!==null?(o=rs(),o!==null?e=[e,o]:(e=null,s=T)):(e=null,s=T),e=e!==null?e:"",e!==null?a=[a,e]:(a=null,s=p)):(a=null,s=p),a!==null&&(a=function(w){K=r.substring(s,w)}(d)),a===null&&(s=d),a}function bn(){var a,e,o,d,p,T,w;if(p=s,a=Re(),a===null)if(T=s,a=ie(),a!==null){for(e=[],w=s,o=dt(),o!==null?(d=ie(),d!==null?o=[o,d]:(o=null,s=w)):(o=null,s=w);o!==null;)e.push(o),w=s,o=dt(),o!==null?(d=ie(),d!==null?o=[o,d]:(o=null,s=w)):(o=null,s=w);e!==null?a=[a,e]:(a=null,s=T)}else a=null,s=T;return a!==null&&(a=function(O){var B,ee;for(ee=K.multi_header.length,B=0;B<ee;B++)if(K.multi_header[B].parsed===null){K=null;break}K!==null?K=K.multi_header:K=-1}()),a===null&&(s=p),a}function ie(){var a,e,o,d,p,T,w;if(p=s,T=s,a=qe(),a===null&&(a=Ls()),a!==null){for(e=[],w=s,o=ze(),o!==null?(d=Jr(),d!==null?o=[o,d]:(o=null,s=w)):(o=null,s=w);o!==null;)e.push(o),w=s,o=ze(),o!==null?(d=Jr(),d!==null?o=[o,d]:(o=null,s=w)):(o=null,s=w);e!==null?a=[a,e]:(a=null,s=T)}else a=null,s=T;return a!==null&&(a=function(O){var B;K.multi_header||(K.multi_header=[]);try{B=new $r(K.uri,K.display_name,K.params),delete K.uri,delete K.display_name,delete K.params}catch{B=null}K.multi_header.push({possition:s,offset:O,parsed:B})}(p)),a===null&&(s=p),a}function Ls(){var a,e,o,d,p;return p=s,a=Js(),a=a!==null?a:"",a!==null?(e=xt(),e!==null?(o=yt(),o!==null?(d=vt(),d!==null?a=[a,e,o,d]:(a=null,s=p)):(a=null,s=p)):(a=null,s=p)):(a=null,s=p),a}function Js(){var a,e,o,d,p,T,w;if(p=s,T=s,a=le(),a!==null){for(e=[],w=s,o=Ne(),o!==null?(d=le(),d!==null?o=[o,d]:(o=null,s=w)):(o=null,s=w);o!==null;)e.push(o),w=s,o=Ne(),o!==null?(d=le(),d!==null?o=[o,d]:(o=null,s=w)):(o=null,s=w);e!==null?a=[a,e]:(a=null,s=T)}else a=null,s=T;return a===null&&(a=ft()),a!==null&&(a=function(O,B){typeof B=="string"?K.display_name=B:K.display_name=B[1].reduce(function(ee,Pe){return ee+Pe[0]+Pe[1]},B[0])}(p,a)),a===null&&(s=p),a}function Jr(){var a;return a=ti(),a===null&&(a=ht(),a===null&&(a=Vt())),a}function ti(){var a,e,o,d,p;return d=s,p=s,r.substr(s,1).toLowerCase()==="q"?(a=r.substr(s,1),s++):(a=null,_('"q"')),a!==null?(e=ge(),e!==null?(o=Tr(),o!==null?a=[a,e,o]:(a=null,s=p)):(a=null,s=p)):(a=null,s=p),a!==null&&(a=function(T,w){K.params||(K.params={}),K.params.q=w}(d,a[2])),a===null&&(s=d),a}function ht(){var a,e,o,d,p;return d=s,p=s,r.substr(s,7).toLowerCase()==="expires"?(a=r.substr(s,7),s+=7):(a=null,_('"expires"')),a!==null?(e=ge(),e!==null?(o=cr(),o!==null?a=[a,e,o]:(a=null,s=p)):(a=null,s=p)):(a=null,s=p),a!==null&&(a=function(T,w){K.params||(K.params={}),K.params.expires=w}(d,a[2])),a===null&&(s=d),a}function cr(){var a,e,o;if(o=s,e=C(),e!==null)for(a=[];e!==null;)a.push(e),e=C();else a=null;return a!==null&&(a=function(d,p){return parseInt(p.join(""))}(o,a)),a===null&&(s=o),a}function Tr(){var a,e,o,d,p,T,w,O;return T=s,w=s,r.charCodeAt(s)===48?(a="0",s++):(a=null,_('"0"')),a!==null?(O=s,r.charCodeAt(s)===46?(e=".",s++):(e=null,_('"."')),e!==null?(o=C(),o=o!==null?o:"",o!==null?(d=C(),d=d!==null?d:"",d!==null?(p=C(),p=p!==null?p:"",p!==null?e=[e,o,d,p]:(e=null,s=O)):(e=null,s=O)):(e=null,s=O)):(e=null,s=O),e=e!==null?e:"",e!==null?a=[a,e]:(a=null,s=w)):(a=null,s=w),a!==null&&(a=function(B){return parseFloat(r.substring(s,B))}(T)),a===null&&(s=T),a}function Vt(){var a,e,o,d,p,T;return d=s,p=s,a=le(),a!==null?(T=s,e=ge(),e!==null?(o=qt(),o!==null?e=[e,o]:(e=null,s=T)):(e=null,s=T),e=e!==null?e:"",e!==null?a=[a,e]:(a=null,s=p)):(a=null,s=p),a!==null&&(a=function(w,O,B){K.params||(K.params={}),typeof B>"u"?B=void 0:B=B[1],K.params[O.toLowerCase()]=B}(d,a[0],a[1])),a===null&&(s=d),a}function qt(){var a;return a=le(),a===null&&(a=pr(),a===null&&(a=gt())),a}function Vi(){var a,e,o,d,p,T;if(p=s,a=ka(),a!==null){for(e=[],T=s,o=ze(),o!==null?(d=wn(),d!==null?o=[o,d]:(o=null,s=T)):(o=null,s=T);o!==null;)e.push(o),T=s,o=ze(),o!==null?(d=wn(),d!==null?o=[o,d]:(o=null,s=T)):(o=null,s=T);e!==null?a=[a,e]:(a=null,s=p)}else a=null,s=p;return a}function ka(){var a;return r.substr(s,6).toLowerCase()==="render"?(a=r.substr(s,6),s+=6):(a=null,_('"render"')),a===null&&(r.substr(s,7).toLowerCase()==="session"?(a=r.substr(s,7),s+=7):(a=null,_('"session"')),a===null&&(r.substr(s,4).toLowerCase()==="icon"?(a=r.substr(s,4),s+=4):(a=null,_('"icon"')),a===null&&(r.substr(s,5).toLowerCase()==="alert"?(a=r.substr(s,5),s+=5):(a=null,_('"alert"')),a===null&&(a=le())))),a}function wn(){var a;return a=si(),a===null&&(a=Vt()),a}function si(){var a,e,o,d;return d=s,r.substr(s,8).toLowerCase()==="handling"?(a=r.substr(s,8),s+=8):(a=null,_('"handling"')),a!==null?(e=ge(),e!==null?(r.substr(s,8).toLowerCase()==="optional"?(o=r.substr(s,8),s+=8):(o=null,_('"optional"')),o===null&&(r.substr(s,8).toLowerCase()==="required"?(o=r.substr(s,8),s+=8):(o=null,_('"required"')),o===null&&(o=le())),o!==null?a=[a,e,o]:(a=null,s=d)):(a=null,s=d)):(a=null,s=d),a}function qi(){var a,e,o,d,p,T;if(p=s,a=le(),a!==null){for(e=[],T=s,o=dt(),o!==null?(d=le(),d!==null?o=[o,d]:(o=null,s=T)):(o=null,s=T);o!==null;)e.push(o),T=s,o=dt(),o!==null?(d=le(),d!==null?o=[o,d]:(o=null,s=T)):(o=null,s=T);e!==null?a=[a,e]:(a=null,s=p)}else a=null,s=p;return a}function Na(){var a,e,o;if(o=s,e=C(),e!==null)for(a=[];e!==null;)a.push(e),e=C();else a=null;return a!==null&&(a=function(d,p){K=parseInt(p.join(""))}(o,a)),a===null&&(s=o),a}function Ma(){var a,e;return e=s,a=Ua(),a!==null&&(a=function(o){K=r.substring(s,o)}(e)),a===null&&(s=e),a}function Ua(){var a,e,o,d,p,T,w,O;if(w=s,a=ji(),a!==null)if(e=ye(),e!==null)if(o=La(),o!==null){for(d=[],O=s,p=ze(),p!==null?(T=An(),T!==null?p=[p,T]:(p=null,s=O)):(p=null,s=O);p!==null;)d.push(p),O=s,p=ze(),p!==null?(T=An(),T!==null?p=[p,T]:(p=null,s=O)):(p=null,s=O);d!==null?a=[a,e,o,d]:(a=null,s=w)}else a=null,s=w;else a=null,s=w;else a=null,s=w;return a}function ji(){var a;return a=Pa(),a===null&&(a=Qr()),a}function Pa(){var a;return r.substr(s,4).toLowerCase()==="text"?(a=r.substr(s,4),s+=4):(a=null,_('"text"')),a===null&&(r.substr(s,5).toLowerCase()==="image"?(a=r.substr(s,5),s+=5):(a=null,_('"image"')),a===null&&(r.substr(s,5).toLowerCase()==="audio"?(a=r.substr(s,5),s+=5):(a=null,_('"audio"')),a===null&&(r.substr(s,5).toLowerCase()==="video"?(a=r.substr(s,5),s+=5):(a=null,_('"video"')),a===null&&(r.substr(s,11).toLowerCase()==="application"?(a=r.substr(s,11),s+=11):(a=null,_('"application"')),a===null&&(a=En()))))),a}function Qr(){var a;return r.substr(s,7).toLowerCase()==="message"?(a=r.substr(s,7),s+=7):(a=null,_('"message"')),a===null&&(r.substr(s,9).toLowerCase()==="multipart"?(a=r.substr(s,9),s+=9):(a=null,_('"multipart"')),a===null&&(a=En())),a}function En(){var a;return a=le(),a===null&&(a=Cn()),a}function Cn(){var a,e,o;return o=s,r.substr(s,2).toLowerCase()==="x-"?(a=r.substr(s,2),s+=2):(a=null,_('"x-"')),a!==null?(e=le(),e!==null?a=[a,e]:(a=null,s=o)):(a=null,s=o),a}function La(){var a;return a=En(),a===null&&(a=le()),a}function An(){var a,e,o,d;return d=s,a=le(),a!==null?(e=ge(),e!==null?(o=In(),o!==null?a=[a,e,o]:(a=null,s=d)):(a=null,s=d)):(a=null,s=d),a}function In(){var a;return a=le(),a===null&&(a=gt()),a}function ri(){var a,e,o,d;return d=s,a=ni(),a!==null?(e=Ne(),e!==null?(o=Tn(),o!==null?a=[a,e,o]:(a=null,s=d)):(a=null,s=d)):(a=null,s=d),a}function ni(){var a,e,o;if(o=s,e=C(),e!==null)for(a=[];e!==null;)a.push(e),e=C();else a=null;return a!==null&&(a=function(d,p){K.value=parseInt(p.join(""))}(o,a)),a===null&&(s=o),a}function Ha(){var a,e;return e=s,a=cr(),a!==null&&(a=function(o,d){K=d}(e,a)),a===null&&(s=e),a}function bl(){var a,e,o,d,p,T,w;if(p=s,T=s,a=Xr(),a!==null){for(e=[],w=s,o=ze(),o!==null?(d=Vt(),d!==null?o=[o,d]:(o=null,s=w)):(o=null,s=w);o!==null;)e.push(o),w=s,o=ze(),o!==null?(d=Vt(),d!==null?o=[o,d]:(o=null,s=w)):(o=null,s=w);e!==null?a=[a,e]:(a=null,s=T)}else a=null,s=T;return a!==null&&(a=function(O,B){K.event=B.join("").toLowerCase()}(p,a[0])),a===null&&(s=p),a}function Xr(){var a,e,o,d,p,T;if(p=s,a=oe(),a!==null){for(e=[],T=s,r.charCodeAt(s)===46?(o=".",s++):(o=null,_('"."')),o!==null?(d=oe(),d!==null?o=[o,d]:(o=null,s=T)):(o=null,s=T);o!==null;)e.push(o),T=s,r.charCodeAt(s)===46?(o=".",s++):(o=null,_('"."')),o!==null?(d=oe(),d!==null?o=[o,d]:(o=null,s=T)):(o=null,s=T);e!==null?a=[a,e]:(a=null,s=p)}else a=null,s=p;return a}function Zr(){var a,e,o,d,p,T,w;if(p=s,T=s,a=qe(),a===null&&(a=Ls()),a!==null){for(e=[],w=s,o=ze(),o!==null?(d=Gi(),d!==null?o=[o,d]:(o=null,s=w)):(o=null,s=w);o!==null;)e.push(o),w=s,o=ze(),o!==null?(d=Gi(),d!==null?o=[o,d]:(o=null,s=w)):(o=null,s=w);e!==null?a=[a,e]:(a=null,s=T)}else a=null,s=T;return a!==null&&(a=function(O){var B=K.tag;try{K=new $r(K.uri,K.display_name,K.params),B&&K.setParam("tag",B)}catch{K=-1}}()),a===null&&(s=p),a}function Gi(){var a;return a=Rn(),a===null&&(a=Vt()),a}function Rn(){var a,e,o,d,p;return d=s,p=s,r.substr(s,3).toLowerCase()==="tag"?(a=r.substr(s,3),s+=3):(a=null,_('"tag"')),a!==null?(e=ge(),e!==null?(o=le(),o!==null?a=[a,e,o]:(a=null,s=p)):(a=null,s=p)):(a=null,s=p),a!==null&&(a=function(T,w){K.tag=w}(d,a[2])),a===null&&(s=d),a}function Fa(){var a,e,o;if(o=s,e=C(),e!==null)for(a=[];e!==null;)a.push(e),e=C();else a=null;return a!==null&&(a=function(d,p){K=parseInt(p.join(""))}(o,a)),a===null&&(s=o),a}function wl(){var a,e;return e=s,a=cr(),a!==null&&(a=function(o,d){K=d}(e,a)),a===null&&(s=e),a}function Rt(){var a,e,o,d,p,T,w,O,B,ee;for(O=s,B=s,a=[],e=Js();e!==null;)a.push(e),e=Js();if(a!==null)if(e=xt(),e!==null)if(o=yt(),o!==null)if(d=vt(),d!==null){for(p=[],ee=s,T=ze(),T!==null?(w=Vt(),w!==null?T=[T,w]:(T=null,s=ee)):(T=null,s=ee);T!==null;)p.push(T),ee=s,T=ze(),T!==null?(w=Vt(),w!==null?T=[T,w]:(T=null,s=ee)):(T=null,s=ee);p!==null?a=[a,e,o,d,p]:(a=null,s=B)}else a=null,s=B;else a=null,s=B;else a=null,s=B;else a=null,s=B;return a!==null&&(a=function(Pe){try{K=new $r(K.uri,K.display_name,K.params)}catch{K=-1}}()),a===null&&(s=O),a}function jt(){var a;return a=Rr(),a}function Rr(){var a,e,o,d,p,T,w,O;if(w=s,r.substr(s,6).toLowerCase()==="digest"?(a=r.substr(s,6),s+=6):(a=null,_('"Digest"')),a!==null)if(e=Ne(),e!==null)if(o=Gt(),o!==null){for(d=[],O=s,p=dt(),p!==null?(T=Gt(),T!==null?p=[p,T]:(p=null,s=O)):(p=null,s=O);p!==null;)d.push(p),O=s,p=dt(),p!==null?(T=Gt(),T!==null?p=[p,T]:(p=null,s=O)):(p=null,s=O);d!==null?a=[a,e,o,d]:(a=null,s=w)}else a=null,s=w;else a=null,s=w;else a=null,s=w;return a===null&&(a=en()),a}function en(){var a,e,o,d,p,T,w,O;if(w=s,a=le(),a!==null)if(e=Ne(),e!==null)if(o=Bt(),o!==null){for(d=[],O=s,p=dt(),p!==null?(T=Bt(),T!==null?p=[p,T]:(p=null,s=O)):(p=null,s=O);p!==null;)d.push(p),O=s,p=dt(),p!==null?(T=Bt(),T!==null?p=[p,T]:(p=null,s=O)):(p=null,s=O);d!==null?a=[a,e,o,d]:(a=null,s=w)}else a=null,s=w;else a=null,s=w;else a=null,s=w;return a}function Bt(){var a,e,o,d;return d=s,a=le(),a!==null?(e=ge(),e!==null?(o=le(),o===null&&(o=gt()),o!==null?a=[a,e,o]:(a=null,s=d)):(a=null,s=d)):(a=null,s=d),a}function Gt(){var a;return a=Xe(),a===null&&(a=ii(),a===null&&(a=qs(),a===null&&(a=tn(),a===null&&(a=he(),a===null&&(a=Je(),a===null&&(a=Wi(),a===null&&(a=Bt()))))))),a}function Xe(){var a,e,o,d;return d=s,r.substr(s,5).toLowerCase()==="realm"?(a=r.substr(s,5),s+=5):(a=null,_('"realm"')),a!==null?(e=ge(),e!==null?(o=Pt(),o!==null?a=[a,e,o]:(a=null,s=d)):(a=null,s=d)):(a=null,s=d),a}function Pt(){var a,e;return e=s,a=ft(),a!==null&&(a=function(o,d){K.realm=d}(e,a)),a===null&&(s=e),a}function ii(){var a,e,o,d,p,T,w,O,B;if(O=s,r.substr(s,6).toLowerCase()==="domain"?(a=r.substr(s,6),s+=6):(a=null,_('"domain"')),a!==null)if(e=ge(),e!==null)if(o=Zt(),o!==null)if(d=dr(),d!==null){if(p=[],B=s,w=G(),w!==null)for(T=[];w!==null;)T.push(w),w=G();else T=null;for(T!==null?(w=dr(),w!==null?T=[T,w]:(T=null,s=B)):(T=null,s=B);T!==null;){if(p.push(T),B=s,w=G(),w!==null)for(T=[];w!==null;)T.push(w),w=G();else T=null;T!==null?(w=dr(),w!==null?T=[T,w]:(T=null,s=B)):(T=null,s=B)}p!==null?(T=Mt(),T!==null?a=[a,e,o,d,p,T]:(a=null,s=O)):(a=null,s=O)}else a=null,s=O;else a=null,s=O;else a=null,s=O;else a=null,s=O;return a}function dr(){var a;return a=bs(),a===null&&(a=jr()),a}function qs(){var a,e,o,d;return d=s,r.substr(s,5).toLowerCase()==="nonce"?(a=r.substr(s,5),s+=5):(a=null,_('"nonce"')),a!==null?(e=ge(),e!==null?(o=Ze(),o!==null?a=[a,e,o]:(a=null,s=d)):(a=null,s=d)):(a=null,s=d),a}function Ze(){var a,e;return e=s,a=ft(),a!==null&&(a=function(o,d){K.nonce=d}(e,a)),a===null&&(s=e),a}function tn(){var a,e,o,d,p;return d=s,p=s,r.substr(s,6).toLowerCase()==="opaque"?(a=r.substr(s,6),s+=6):(a=null,_('"opaque"')),a!==null?(e=ge(),e!==null?(o=ft(),o!==null?a=[a,e,o]:(a=null,s=p)):(a=null,s=p)):(a=null,s=p),a!==null&&(a=function(T,w){K.opaque=w}(d,a[2])),a===null&&(s=d),a}function he(){var a,e,o,d,p;return d=s,r.substr(s,5).toLowerCase()==="stale"?(a=r.substr(s,5),s+=5):(a=null,_('"stale"')),a!==null?(e=ge(),e!==null?(p=s,r.substr(s,4).toLowerCase()==="true"?(o=r.substr(s,4),s+=4):(o=null,_('"true"')),o!==null&&(o=function(T){K.stale=!0}()),o===null&&(s=p),o===null&&(p=s,r.substr(s,5).toLowerCase()==="false"?(o=r.substr(s,5),s+=5):(o=null,_('"false"')),o!==null&&(o=function(T){K.stale=!1}()),o===null&&(s=p)),o!==null?a=[a,e,o]:(a=null,s=d)):(a=null,s=d)):(a=null,s=d),a}function Je(){var a,e,o,d,p;return d=s,p=s,r.substr(s,9).toLowerCase()==="algorithm"?(a=r.substr(s,9),s+=9):(a=null,_('"algorithm"')),a!==null?(e=ge(),e!==null?(r.substr(s,3).toLowerCase()==="md5"?(o=r.substr(s,3),s+=3):(o=null,_('"MD5"')),o===null&&(r.substr(s,8).toLowerCase()==="md5-sess"?(o=r.substr(s,8),s+=8):(o=null,_('"MD5-sess"')),o===null&&(o=le())),o!==null?a=[a,e,o]:(a=null,s=p)):(a=null,s=p)):(a=null,s=p),a!==null&&(a=function(T,w){K.algorithm=w.toUpperCase()}(d,a[2])),a===null&&(s=d),a}function Wi(){var a,e,o,d,p,T,w,O,B,ee;if(O=s,r.substr(s,3).toLowerCase()==="qop"?(a=r.substr(s,3),s+=3):(a=null,_('"qop"')),a!==null)if(e=ge(),e!==null)if(o=Zt(),o!==null){if(B=s,d=sn(),d!==null){for(p=[],ee=s,r.charCodeAt(s)===44?(T=",",s++):(T=null,_('","')),T!==null?(w=sn(),w!==null?T=[T,w]:(T=null,s=ee)):(T=null,s=ee);T!==null;)p.push(T),ee=s,r.charCodeAt(s)===44?(T=",",s++):(T=null,_('","')),T!==null?(w=sn(),w!==null?T=[T,w]:(T=null,s=ee)):(T=null,s=ee);p!==null?d=[d,p]:(d=null,s=B)}else d=null,s=B;d!==null?(p=Mt(),p!==null?a=[a,e,o,d,p]:(a=null,s=O)):(a=null,s=O)}else a=null,s=O;else a=null,s=O;else a=null,s=O;return a}function sn(){var a,e;return e=s,r.substr(s,8).toLowerCase()==="auth-int"?(a=r.substr(s,8),s+=8):(a=null,_('"auth-int"')),a===null&&(r.substr(s,4).toLowerCase()==="auth"?(a=r.substr(s,4),s+=4):(a=null,_('"auth"')),a===null&&(a=le())),a!==null&&(a=function(o,d){K.qop||(K.qop=[]),K.qop.push(d.toLowerCase())}(e,a)),a===null&&(s=e),a}function ai(){var a,e,o,d,p,T;if(p=s,a=le(),a!==null){for(e=[],T=s,o=dt(),o!==null?(d=le(),d!==null?o=[o,d]:(o=null,s=T)):(o=null,s=T);o!==null;)e.push(o),T=s,o=dt(),o!==null?(d=le(),d!==null?o=[o,d]:(o=null,s=T)):(o=null,s=T);e!==null?a=[a,e]:(a=null,s=p)}else a=null,s=p;return a}function El(){var a,e,o,d,p,T,w;if(p=s,T=s,a=_t(),a!==null){for(e=[],w=s,o=dt(),o!==null?(d=_t(),d!==null?o=[o,d]:(o=null,s=w)):(o=null,s=w);o!==null;)e.push(o),w=s,o=dt(),o!==null?(d=_t(),d!==null?o=[o,d]:(o=null,s=w)):(o=null,s=w);e!==null?a=[a,e]:(a=null,s=T)}else a=null,s=T;return a!==null&&(a=function(O){var B,ee;for(ee=K.multi_header.length,B=0;B<ee;B++)if(K.multi_header[B].parsed===null){K=null;break}K!==null?K=K.multi_header:K=-1}()),a===null&&(s=p),a}function _t(){var a,e,o,d,p,T,w;if(p=s,T=s,a=Ls(),a!==null){for(e=[],w=s,o=ze(),o!==null?(d=Vt(),d!==null?o=[o,d]:(o=null,s=w)):(o=null,s=w);o!==null;)e.push(o),w=s,o=ze(),o!==null?(d=Vt(),d!==null?o=[o,d]:(o=null,s=w)):(o=null,s=w);e!==null?a=[a,e]:(a=null,s=T)}else a=null,s=T;return a!==null&&(a=function(O){var B;K.multi_header||(K.multi_header=[]);try{B=new $r(K.uri,K.display_name,K.params),delete K.uri,delete K.display_name,delete K.params}catch{B=null}K.multi_header.push({possition:s,offset:O,parsed:B})}(p)),a===null&&(s=p),a}function li(){var a,e,o,d,p,T,w;if(p=s,T=s,r.substr(s,3).toLowerCase()==="sip"?(a=r.substr(s,3),s+=3):(a=null,_('"SIP"')),a===null&&(a=le()),a!==null){for(e=[],w=s,o=ze(),o!==null?(d=oi(),d!==null?o=[o,d]:(o=null,s=w)):(o=null,s=w);o!==null;)e.push(o),w=s,o=ze(),o!==null?(d=oi(),d!==null?o=[o,d]:(o=null,s=w)):(o=null,s=w);e!==null?a=[a,e]:(a=null,s=T)}else a=null,s=T;return a!==null&&(a=function(O,B){if(K.protocol=B.toLowerCase(),K.params||(K.params={}),K.params.text&&K.params.text[0]==='"'){var ee=K.params.text;K.text=ee.substring(1,ee.length-1),delete K.params.text}}(p,a[0])),a===null&&(s=p),a}function oi(){var a;return a=ui(),a===null&&(a=Vt()),a}function ui(){var a,e,o,d,p,T;if(p=s,T=s,r.substr(s,5).toLowerCase()==="cause"?(a=r.substr(s,5),s+=5):(a=null,_('"cause"')),a!==null)if(e=ge(),e!==null){if(d=C(),d!==null)for(o=[];d!==null;)o.push(d),d=C();else o=null;o!==null?a=[a,e,o]:(a=null,s=T)}else a=null,s=T;else a=null,s=T;return a!==null&&(a=function(w,O){K.cause=parseInt(O.join(""))}(p,a[2])),a===null&&(s=p),a}function Ba(){var a,e,o,d,p,T;if(p=s,a=le(),a!==null){for(e=[],T=s,o=dt(),o!==null?(d=le(),d!==null?o=[o,d]:(o=null,s=T)):(o=null,s=T);o!==null;)e.push(o),T=s,o=dt(),o!==null?(d=le(),d!==null?o=[o,d]:(o=null,s=T)):(o=null,s=T);e!==null?a=[a,e]:(a=null,s=p)}else a=null,s=p;return a}function Cl(){var a,e,o,d,p,T;if(p=s,a=ci(),a!==null){for(e=[],T=s,o=dt(),o!==null?(d=ci(),d!==null?o=[o,d]:(o=null,s=T)):(o=null,s=T);o!==null;)e.push(o),T=s,o=dt(),o!==null?(d=ci(),d!==null?o=[o,d]:(o=null,s=T)):(o=null,s=T);e!==null?a=[a,e]:(a=null,s=p)}else a=null,s=p;return a}function ci(){var a,e,o,d,p,T;if(p=s,a=Ls(),a!==null){for(e=[],T=s,o=ze(),o!==null?(d=Vt(),d!==null?o=[o,d]:(o=null,s=T)):(o=null,s=T);o!==null;)e.push(o),T=s,o=ze(),o!==null?(d=Vt(),d!==null?o=[o,d]:(o=null,s=T)):(o=null,s=T);e!==null?a=[a,e]:(a=null,s=p)}else a=null,s=p;return a}function ms(){var a,e,o,d,p,T;if(p=s,a=za(),a!==null){for(e=[],T=s,o=ze(),o!==null?(d=di(),d!==null?o=[o,d]:(o=null,s=T)):(o=null,s=T);o!==null;)e.push(o),T=s,o=ze(),o!==null?(d=di(),d!==null?o=[o,d]:(o=null,s=T)):(o=null,s=T);e!==null?a=[a,e]:(a=null,s=p)}else a=null,s=p;return a}function za(){var a,e;return e=s,r.substr(s,6).toLowerCase()==="active"?(a=r.substr(s,6),s+=6):(a=null,_('"active"')),a===null&&(r.substr(s,7).toLowerCase()==="pending"?(a=r.substr(s,7),s+=7):(a=null,_('"pending"')),a===null&&(r.substr(s,10).toLowerCase()==="terminated"?(a=r.substr(s,10),s+=10):(a=null,_('"terminated"')),a===null&&(a=le()))),a!==null&&(a=function(o){K.state=r.substring(s,o)}(e)),a===null&&(s=e),a}function di(){var a,e,o,d,p;return d=s,p=s,r.substr(s,6).toLowerCase()==="reason"?(a=r.substr(s,6),s+=6):(a=null,_('"reason"')),a!==null?(e=ge(),e!==null?(o=Qs(),o!==null?a=[a,e,o]:(a=null,s=p)):(a=null,s=p)):(a=null,s=p),a!==null&&(a=function(T,w){typeof w<"u"&&(K.reason=w)}(d,a[2])),a===null&&(s=d),a===null&&(d=s,p=s,r.substr(s,7).toLowerCase()==="expires"?(a=r.substr(s,7),s+=7):(a=null,_('"expires"')),a!==null?(e=ge(),e!==null?(o=cr(),o!==null?a=[a,e,o]:(a=null,s=p)):(a=null,s=p)):(a=null,s=p),a!==null&&(a=function(T,w){typeof w<"u"&&(K.expires=w)}(d,a[2])),a===null&&(s=d),a===null&&(d=s,p=s,r.substr(s,11).toLowerCase()==="retry_after"?(a=r.substr(s,11),s+=11):(a=null,_('"retry_after"')),a!==null?(e=ge(),e!==null?(o=cr(),o!==null?a=[a,e,o]:(a=null,s=p)):(a=null,s=p)):(a=null,s=p),a!==null&&(a=function(T,w){typeof w<"u"&&(K.retry_after=w)}(d,a[2])),a===null&&(s=d),a===null&&(a=Vt()))),a}function Qs(){var a;return r.substr(s,11).toLowerCase()==="deactivated"?(a=r.substr(s,11),s+=11):(a=null,_('"deactivated"')),a===null&&(r.substr(s,9).toLowerCase()==="probation"?(a=r.substr(s,9),s+=9):(a=null,_('"probation"')),a===null&&(r.substr(s,8).toLowerCase()==="rejected"?(a=r.substr(s,8),s+=8):(a=null,_('"rejected"')),a===null&&(r.substr(s,7).toLowerCase()==="timeout"?(a=r.substr(s,7),s+=7):(a=null,_('"timeout"')),a===null&&(r.substr(s,6).toLowerCase()==="giveup"?(a=r.substr(s,6),s+=6):(a=null,_('"giveup"')),a===null&&(r.substr(s,10).toLowerCase()==="noresource"?(a=r.substr(s,10),s+=10):(a=null,_('"noresource"')),a===null&&(r.substr(s,9).toLowerCase()==="invariant"?(a=r.substr(s,9),s+=9):(a=null,_('"invariant"')),a===null&&(a=le()))))))),a}function Va(){var a;return a=pe(),a=a!==null?a:"",a}function Al(){var a,e,o,d,p,T;if(p=s,a=le(),a!==null){for(e=[],T=s,o=dt(),o!==null?(d=le(),d!==null?o=[o,d]:(o=null,s=T)):(o=null,s=T);o!==null;)e.push(o),T=s,o=dt(),o!==null?(d=le(),d!==null?o=[o,d]:(o=null,s=T)):(o=null,s=T);e!==null?a=[a,e]:(a=null,s=p)}else a=null,s=p;return a=a!==null?a:"",a}function Il(){var a,e,o,d,p,T,w;if(p=s,T=s,a=qe(),a===null&&(a=Ls()),a!==null){for(e=[],w=s,o=ze(),o!==null?(d=Ki(),d!==null?o=[o,d]:(o=null,s=w)):(o=null,s=w);o!==null;)e.push(o),w=s,o=ze(),o!==null?(d=Ki(),d!==null?o=[o,d]:(o=null,s=w)):(o=null,s=w);e!==null?a=[a,e]:(a=null,s=T)}else a=null,s=T;return a!==null&&(a=function(O){var B=K.tag;try{K=new $r(K.uri,K.display_name,K.params),B&&K.setParam("tag",B)}catch{K=-1}}()),a===null&&(s=p),a}function Ki(){var a;return a=Rn(),a===null&&(a=Vt()),a}function Yi(){var a,e,o,d,p,T;if(p=s,a=fi(),a!==null){for(e=[],T=s,o=dt(),o!==null?(d=fi(),d!==null?o=[o,d]:(o=null,s=T)):(o=null,s=T);o!==null;)e.push(o),T=s,o=dt(),o!==null?(d=fi(),d!==null?o=[o,d]:(o=null,s=T)):(o=null,s=T);e!==null?a=[a,e]:(a=null,s=p)}else a=null,s=p;return a}function fi(){var a,e,o,d,p,T,w,O;if(w=s,a=ea(),a!==null)if(e=Ne(),e!==null)if(o=ra(),o!==null){for(d=[],O=s,p=ze(),p!==null?(T=rn(),T!==null?p=[p,T]:(p=null,s=O)):(p=null,s=O);p!==null;)d.push(p),O=s,p=ze(),p!==null?(T=rn(),T!==null?p=[p,T]:(p=null,s=O)):(p=null,s=O);d!==null?a=[a,e,o,d]:(a=null,s=w)}else a=null,s=w;else a=null,s=w;else a=null,s=w;return a}function rn(){var a;return a=hi(),a===null&&(a=Ji(),a===null&&(a=Qi(),a===null&&(a=Hs(),a===null&&(a=Xi(),a===null&&(a=Vt()))))),a}function hi(){var a,e,o,d,p;return d=s,p=s,r.substr(s,3).toLowerCase()==="ttl"?(a=r.substr(s,3),s+=3):(a=null,_('"ttl"')),a!==null?(e=ge(),e!==null?(o=_i(),o!==null?a=[a,e,o]:(a=null,s=p)):(a=null,s=p)):(a=null,s=p),a!==null&&(a=function(T,w){K.ttl=w}(d,a[2])),a===null&&(s=d),a}function Ji(){var a,e,o,d,p;return d=s,p=s,r.substr(s,5).toLowerCase()==="maddr"?(a=r.substr(s,5),s+=5):(a=null,_('"maddr"')),a!==null?(e=ge(),e!==null?(o=pr(),o!==null?a=[a,e,o]:(a=null,s=p)):(a=null,s=p)):(a=null,s=p),a!==null&&(a=function(T,w){K.maddr=w}(d,a[2])),a===null&&(s=d),a}function Qi(){var a,e,o,d,p;return d=s,p=s,r.substr(s,8).toLowerCase()==="received"?(a=r.substr(s,8),s+=8):(a=null,_('"received"')),a!==null?(e=ge(),e!==null?(o=ls(),o===null&&(o=Lr()),o!==null?a=[a,e,o]:(a=null,s=p)):(a=null,s=p)):(a=null,s=p),a!==null&&(a=function(T,w){K.received=w}(d,a[2])),a===null&&(s=d),a}function Hs(){var a,e,o,d,p;return d=s,p=s,r.substr(s,6).toLowerCase()==="branch"?(a=r.substr(s,6),s+=6):(a=null,_('"branch"')),a!==null?(e=ge(),e!==null?(o=le(),o!==null?a=[a,e,o]:(a=null,s=p)):(a=null,s=p)):(a=null,s=p),a!==null&&(a=function(T,w){K.branch=w}(d,a[2])),a===null&&(s=d),a}function Xi(){var a,e,o,d,p;return d=s,r.substr(s,5).toLowerCase()==="rport"?(a=r.substr(s,5),s+=5):(a=null,_('"rport"')),a!==null?(p=s,e=ge(),e!==null?(o=Zi(),o!==null?e=[e,o]:(e=null,s=p)):(e=null,s=p),e=e!==null?e:"",e!==null?a=[a,e]:(a=null,s=d)):(a=null,s=d),a}function Zi(){var a,e,o,d,p,T,w;return T=s,w=s,a=C(),a=a!==null?a:"",a!==null?(e=C(),e=e!==null?e:"",e!==null?(o=C(),o=o!==null?o:"",o!==null?(d=C(),d=d!==null?d:"",d!==null?(p=C(),p=p!==null?p:"",p!==null?a=[a,e,o,d,p]:(a=null,s=w)):(a=null,s=w)):(a=null,s=w)):(a=null,s=w)):(a=null,s=w),a!==null&&(a=function(O,B){K.rport=parseInt(B.join(""))}(T,a)),a===null&&(s=T),a}function ea(){var a,e,o,d,p,T;return T=s,a=ta(),a!==null?(e=ye(),e!==null?(o=le(),o!==null?(d=ye(),d!==null?(p=sa(),p!==null?a=[a,e,o,d,p]:(a=null,s=T)):(a=null,s=T)):(a=null,s=T)):(a=null,s=T)):(a=null,s=T),a}function ta(){var a,e;return e=s,r.substr(s,3).toLowerCase()==="sip"?(a=r.substr(s,3),s+=3):(a=null,_('"SIP"')),a===null&&(a=le()),a!==null&&(a=function(o,d){K.protocol=d}(e,a)),a===null&&(s=e),a}function sa(){var a,e;return e=s,r.substr(s,3).toLowerCase()==="udp"?(a=r.substr(s,3),s+=3):(a=null,_('"UDP"')),a===null&&(r.substr(s,3).toLowerCase()==="tcp"?(a=r.substr(s,3),s+=3):(a=null,_('"TCP"')),a===null&&(r.substr(s,3).toLowerCase()==="tls"?(a=r.substr(s,3),s+=3):(a=null,_('"TLS"')),a===null&&(r.substr(s,4).toLowerCase()==="sctp"?(a=r.substr(s,4),s+=4):(a=null,_('"SCTP"')),a===null&&(a=le())))),a!==null&&(a=function(o,d){K.transport=d}(e,a)),a===null&&(s=e),a}function ra(){var a,e,o,d,p;return d=s,a=na(),a!==null?(p=s,e=Ye(),e!==null?(o=ia(),o!==null?e=[e,o]:(e=null,s=p)):(e=null,s=p),e=e!==null?e:"",e!==null?a=[a,e]:(a=null,s=d)):(a=null,s=d),a}function na(){var a,e;return e=s,a=ls(),a===null&&(a=pn(),a===null&&(a=as())),a!==null&&(a=function(o){K.host=r.substring(s,o)}(e)),a===null&&(s=e),a}function ia(){var a,e,o,d,p,T,w;return T=s,w=s,a=C(),a=a!==null?a:"",a!==null?(e=C(),e=e!==null?e:"",e!==null?(o=C(),o=o!==null?o:"",o!==null?(d=C(),d=d!==null?d:"",d!==null?(p=C(),p=p!==null?p:"",p!==null?a=[a,e,o,d,p]:(a=null,s=w)):(a=null,s=w)):(a=null,s=w)):(a=null,s=w)):(a=null,s=w),a!==null&&(a=function(O,B){K.port=parseInt(B.join(""))}(T,a)),a===null&&(s=T),a}function _i(){var a,e,o,d,p;return d=s,p=s,a=C(),a!==null?(e=C(),e=e!==null?e:"",e!==null?(o=C(),o=o!==null?o:"",o!==null?a=[a,e,o]:(a=null,s=p)):(a=null,s=p)):(a=null,s=p),a!==null&&(a=function(T,w){return parseInt(w.join(""))}(d,a)),a===null&&(s=d),a}function aa(){var a;return a=Rr(),a}function Eo(){var a,e,o,d,p,T;if(p=s,a=js(),a!==null){for(e=[],T=s,o=ze(),o!==null?(d=pi(),d!==null?o=[o,d]:(o=null,s=T)):(o=null,s=T);o!==null;)e.push(o),T=s,o=ze(),o!==null?(d=pi(),d!==null?o=[o,d]:(o=null,s=T)):(o=null,s=T);e!==null?a=[a,e]:(a=null,s=p)}else a=null,s=p;return a}function js(){var a,e;return e=s,a=cr(),a!==null&&(a=function(o,d){K.expires=d}(e,a)),a===null&&(s=e),a}function pi(){var a;return a=nn(),a===null&&(a=Vt()),a}function nn(){var a,e,o,d,p;return d=s,p=s,r.substr(s,9).toLowerCase()==="refresher"?(a=r.substr(s,9),s+=9):(a=null,_('"refresher"')),a!==null?(e=ge(),e!==null?(r.substr(s,3).toLowerCase()==="uac"?(o=r.substr(s,3),s+=3):(o=null,_('"uac"')),o===null&&(r.substr(s,3).toLowerCase()==="uas"?(o=r.substr(s,3),s+=3):(o=null,_('"uas"'))),o!==null?a=[a,e,o]:(a=null,s=p)):(a=null,s=p)):(a=null,s=p),a!==null&&(a=function(T,w){K.refresher=w.toLowerCase()}(d,a[2])),a===null&&(s=d),a}function la(){var a,e,o,d;return d=s,a=le(),a!==null?(e=se(),e!==null?(o=Gs(),o!==null?a=[a,e,o]:(a=null,s=d)):(a=null,s=d)):(a=null,s=d),a}function Gs(){var a,e;for(a=[],e=me(),e===null&&(e=_e(),e===null&&(e=Ne()));e!==null;)a.push(e),e=me(),e===null&&(e=_e(),e===null&&(e=Ne()));return a}function qa(){var a,e;for(a=[],e=F();e!==null;)a.push(e),e=F();return a}function Rl(){var a,e,o;return o=s,r.substr(s,5)==="uuid:"?(a="uuid:",s+=5):(a=null,_('"uuid:"')),a!==null?(e=ja(),e!==null?a=[a,e]:(a=null,s=o)):(a=null,s=o),a}function ja(){var a,e,o,d,p,T,w,O,B,ee,Pe;return ee=s,Pe=s,a=Zs(),a!==null?(r.charCodeAt(s)===45?(e="-",s++):(e=null,_('"-"')),e!==null?(o=Xs(),o!==null?(r.charCodeAt(s)===45?(d="-",s++):(d=null,_('"-"')),d!==null?(p=Xs(),p!==null?(r.charCodeAt(s)===45?(T="-",s++):(T=null,_('"-"')),T!==null?(w=Xs(),w!==null?(r.charCodeAt(s)===45?(O="-",s++):(O=null,_('"-"')),O!==null?(B=oa(),B!==null?a=[a,e,o,d,p,T,w,O,B]:(a=null,s=Pe)):(a=null,s=Pe)):(a=null,s=Pe)):(a=null,s=Pe)):(a=null,s=Pe)):(a=null,s=Pe)):(a=null,s=Pe)):(a=null,s=Pe)):(a=null,s=Pe),a!==null&&(a=function(At,Es){K=r.substring(s+5,At)}(ee,a[0])),a===null&&(s=ee),a}function Xs(){var a,e,o,d,p;return p=s,a=D(),a!==null?(e=D(),e!==null?(o=D(),o!==null?(d=D(),d!==null?a=[a,e,o,d]:(a=null,s=p)):(a=null,s=p)):(a=null,s=p)):(a=null,s=p),a}function Zs(){var a,e,o;return o=s,a=Xs(),a!==null?(e=Xs(),e!==null?a=[a,e]:(a=null,s=o)):(a=null,s=o),a}function oa(){var a,e,o,d;return d=s,a=Xs(),a!==null?(e=Xs(),e!==null?(o=Xs(),o!==null?a=[a,e,o]:(a=null,s=d)):(a=null,s=d)):(a=null,s=d),a}function Ga(){var a,e,o,d,p,T,w;if(p=s,T=s,a=qe(),a===null&&(a=Ls()),a!==null){for(e=[],w=s,o=ze(),o!==null?(d=Vt(),d!==null?o=[o,d]:(o=null,s=w)):(o=null,s=w);o!==null;)e.push(o),w=s,o=ze(),o!==null?(d=Vt(),d!==null?o=[o,d]:(o=null,s=w)):(o=null,s=w);e!==null?a=[a,e]:(a=null,s=T)}else a=null,s=T;return a!==null&&(a=function(O){try{K=new $r(K.uri,K.display_name,K.params)}catch{K=-1}}()),a===null&&(s=p),a}function $l(){var a,e,o,d,p,T;if(p=s,a=Wa(),a!==null){for(e=[],T=s,o=ze(),o!==null?(d=mi(),d!==null?o=[o,d]:(o=null,s=T)):(o=null,s=T);o!==null;)e.push(o),T=s,o=ze(),o!==null?(d=mi(),d!==null?o=[o,d]:(o=null,s=T)):(o=null,s=T);e!==null?a=[a,e]:(a=null,s=p)}else a=null,s=p;return a}function Wa(){var a,e,o,d,p,T;return d=s,p=s,a=rs(),a!==null?(T=s,r.charCodeAt(s)===64?(e="@",s++):(e=null,_('"@"')),e!==null?(o=rs(),o!==null?e=[e,o]:(e=null,s=T)):(e=null,s=T),e=e!==null?e:"",e!==null?a=[a,e]:(a=null,s=p)):(a=null,s=p),a!==null&&(a=function(w){K.call_id=r.substring(s,w)}(d)),a===null&&(s=d),a}function mi(){var a;return a=ws(),a===null&&(a=ua(),a===null&&(a=ca(),a===null&&(a=Vt()))),a}function ws(){var a,e,o,d,p;return d=s,p=s,r.substr(s,6)==="to-tag"?(a="to-tag",s+=6):(a=null,_('"to-tag"')),a!==null?(e=ge(),e!==null?(o=le(),o!==null?a=[a,e,o]:(a=null,s=p)):(a=null,s=p)):(a=null,s=p),a!==null&&(a=function(T,w){K.to_tag=w}(d,a[2])),a===null&&(s=d),a}function ua(){var a,e,o,d,p;return d=s,p=s,r.substr(s,8)==="from-tag"?(a="from-tag",s+=8):(a=null,_('"from-tag"')),a!==null?(e=ge(),e!==null?(o=le(),o!==null?a=[a,e,o]:(a=null,s=p)):(a=null,s=p)):(a=null,s=p),a!==null&&(a=function(T,w){K.from_tag=w}(d,a[2])),a===null&&(s=d),a}function ca(){var a,e;return e=s,r.substr(s,10)==="early-only"?(a="early-only",s+=10):(a=null,_('"early-only"')),a!==null&&(a=function(o){K.early_only=!0}()),a===null&&(s=e),a}function Ka(a){a.sort();for(var e=null,o=[],d=0;d<a.length;d++)a[d]!==e&&(o.push(a[d]),e=a[d]);return o}function xl(){for(var a=1,e=1,o=!1,d=0;d<Math.max(s,n);d++){var p=r.charAt(d);p===`
75
- `?(o||a++,e=1,o=!1):p==="\r"||p==="\u2028"||p==="\u2029"?(a++,e=1,o=!0):(e++,o=!1)}return{line:a,column:e}}var Ya=Nn(),$r=Zc(),K={},J=u[l]();if(J===null||s!==r.length){var da=Math.max(s,n),fa=da<r.length?r.charAt(da):null,ha=xl();return new this.SyntaxError(Ka(g),fa,da,ha.line,ha.column),-1}return K},toSource:function(){return this._source}};return t.SyntaxError=function(r,l,u,s,n){function g(_,v){var C,R;switch(_.length){case 0:C="end of input";break;case 1:C=_[0];break;default:C=_.slice(0,_.length-1).join(", ")+" or "+_[_.length-1]}return R=v?f(v):"end of input","Expected "+C+" but "+R+" found."}this.name="SyntaxError",this.expected=r,this.found=l,this.message=g(r,l),this.offset=u,this.line=s,this.column=n},t.SyntaxError.prototype=Error.prototype,t}()),ed}var td,S_;function Nn(){if(S_)return td;S_=1;const f=Et,t=xs(),r=Dr();return td=class jT{static parse(u){if(u=r.parse(u,"SIP_URI"),u!==-1)return u}constructor(u,s,n,g,_={},v={}){if(!n)throw new TypeError('missing or invalid "host" parameter');this._parameters={},this._headers={},this._scheme=u||f.SIP,this._user=s,this._host=n,this._port=g;for(const C in _)Object.prototype.hasOwnProperty.call(_,C)&&this.setParam(C,_[C]);for(const C in v)Object.prototype.hasOwnProperty.call(v,C)&&this.setHeader(C,v[C])}get scheme(){return this._scheme}set scheme(u){this._scheme=u.toLowerCase()}get user(){return this._user}set user(u){this._user=u}get host(){return this._host}set host(u){this._host=u.toLowerCase()}get port(){return this._port}set port(u){this._port=u===0?u:parseInt(u,10)||null}setParam(u,s){u&&(this._parameters[u.toLowerCase()]=typeof s>"u"||s===null?null:s.toString())}getParam(u){if(u)return this._parameters[u.toLowerCase()]}hasParam(u){if(u)return this._parameters.hasOwnProperty(u.toLowerCase())&&!0||!1}deleteParam(u){if(u=u.toLowerCase(),this._parameters.hasOwnProperty(u)){const s=this._parameters[u];return delete this._parameters[u],s}}clearParams(){this._parameters={}}setHeader(u,s){this._headers[t.headerize(u)]=Array.isArray(s)?s:[s]}getHeader(u){if(u)return this._headers[t.headerize(u)]}hasHeader(u){if(u)return this._headers.hasOwnProperty(t.headerize(u))&&!0||!1}deleteHeader(u){if(u=t.headerize(u),this._headers.hasOwnProperty(u)){const s=this._headers[u];return delete this._headers[u],s}}clearHeaders(){this._headers={}}clone(){return new jT(this._scheme,this._user,this._host,this._port,JSON.parse(JSON.stringify(this._parameters)),JSON.parse(JSON.stringify(this._headers)))}toString(){const u=[];let s=`${this._scheme}:`;this._user&&(s+=`${t.escapeUser(this._user)}@`),s+=this._host,(this._port||this._port===0)&&(s+=`:${this._port}`);for(const n in this._parameters)Object.prototype.hasOwnProperty.call(this._parameters,n)&&(s+=`;${n}`,this._parameters[n]!==null&&(s+=`=${this._parameters[n]}`));for(const n in this._headers)if(Object.prototype.hasOwnProperty.call(this._headers,n))for(const g of this._headers[n])u.push(`${n}=${g}`);return u.length>0&&(s+=`?${u.join("&")}`),s}toAor(u){let s=`${this._scheme}:`;return this._user&&(s+=`${t.escapeUser(this._user)}@`),s+=this._host,u&&(this._port||this._port===0)&&(s+=`:${this._port}`),s}},td}var b_;function xs(){if(b_)return cs;b_=1;const f=Et,t=Nn(),r=Dr();cs.str_utf8_length=n=>unescape(encodeURIComponent(n)).length;const l=cs.isFunction=n=>n!==void 0?Object.prototype.toString.call(n)==="[object Function]":!1;cs.isString=n=>n!==void 0?Object.prototype.toString.call(n)==="[object String]":!1,cs.isDecimal=n=>!isNaN(n)&&parseFloat(n)===parseInt(n,10),cs.isEmpty=n=>n===null||n===""||n===void 0||Array.isArray(n)&&n.length===0||typeof n=="number"&&isNaN(n),cs.hasMethods=function(n,...g){for(const _ of g)if(l(n[_]))return!1;return!0};const u=cs.createRandomToken=(n,g=32)=>{let _,v,C="";for(_=0;_<n;_++)v=Math.random()*g|0,C+=v.toString(g);return C};cs.newTag=()=>u(10),cs.newUUID=()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,g=>{const _=Math.random()*16|0;return(g==="x"?_:_&3|8).toString(16)}),cs.hostType=n=>{if(n){if(n=r.parse(n,"host"),n!==-1)return n.host_type}else return};const s=cs.escapeUser=n=>encodeURIComponent(decodeURIComponent(n)).replace(/%3A/ig,":").replace(/%2B/ig,"+").replace(/%3F/ig,"?").replace(/%2F/ig,"/");return cs.normalizeTarget=(n,g)=>{if(n){if(n instanceof t)return n;if(typeof n=="string"){const _=n.split("@");let v,C;switch(_.length){case 1:if(!g)return;v=n,C=g;break;case 2:v=_[0],C=_[1];break;default:v=_.slice(0,_.length-1).join("@"),C=_[_.length-1]}v=v.replace(/^(sips?|tel):/i,""),/^[-.()]*\+?[0-9\-.()]+$/.test(v)&&(v=v.replace(/[-.()]/g,"")),n=`${f.SIP}:${s(v)}@${C}`;let R;return(R=t.parse(n))?R:void 0}else return}else return},cs.headerize=n=>{const g={"Call-Id":"Call-ID",Cseq:"CSeq","Www-Authenticate":"WWW-Authenticate"},_=n.toLowerCase().replace(/_/g,"-").split("-");let v="";const C=_.length;let R;for(R=0;R<C;R++)R!==0&&(v+="-"),v+=_[R].charAt(0).toUpperCase()+_[R].substring(1);return g[v]&&(v=g[v]),v},cs.sipErrorCause=n=>{for(const g in f.SIP_ERROR_CAUSES)if(f.SIP_ERROR_CAUSES[g].indexOf(n)!==-1)return f.causes[g];return f.causes.SIP_FAILURE_CODE},cs.getRandomTestNetIP=()=>{function n(g,_){return Math.floor(Math.random()*(_-g+1)+g)}return`192.0.2.${n(1,254)}`},cs.calculateMD5=n=>{function g(nt,rt){return nt<<rt|nt>>>32-rt}function _(nt,rt){const gt=nt&2147483648,ft=rt&2147483648,Fe=nt&1073741824,He=rt&1073741824,qe=(nt&1073741823)+(rt&1073741823);return Fe&He?qe^2147483648^gt^ft:Fe|He?qe&1073741824?qe^3221225472^gt^ft:qe^1073741824^gt^ft:qe^gt^ft}function v(nt,rt,gt){return nt&rt|~nt&gt}function C(nt,rt,gt){return nt&gt|rt&~gt}function R(nt,rt,gt){return nt^rt^gt}function D(nt,rt,gt){return rt^(nt|~gt)}function H(nt,rt,gt,ft,Fe,He,qe){return nt=_(nt,_(_(v(rt,gt,ft),Fe),qe)),_(g(nt,He),rt)}function F(nt,rt,gt,ft,Fe,He,qe){return nt=_(nt,_(_(C(rt,gt,ft),Fe),qe)),_(g(nt,He),rt)}function q(nt,rt,gt,ft,Fe,He,qe){return nt=_(nt,_(_(R(rt,gt,ft),Fe),qe)),_(g(nt,He),rt)}function G(nt,rt,gt,ft,Fe,He,qe){return nt=_(nt,_(_(D(rt,gt,ft),Fe),qe)),_(g(nt,He),rt)}function te(nt){let rt;const gt=nt.length,ft=gt+8,He=((ft-ft%64)/64+1)*16,qe=new Array(He-1);let yt=0,Ct=0;for(;Ct<gt;)rt=(Ct-Ct%4)/4,yt=Ct%4*8,qe[rt]=qe[rt]|nt.charCodeAt(Ct)<<yt,Ct++;return rt=(Ct-Ct%4)/4,yt=Ct%4*8,qe[rt]=qe[rt]|128<<yt,qe[He-2]=gt<<3,qe[He-1]=gt>>>29,qe}function X(nt){let rt="",gt="",ft,Fe;for(Fe=0;Fe<=3;Fe++)ft=nt>>>Fe*8&255,gt=`0${ft.toString(16)}`,rt=rt+gt.substr(gt.length-2,2);return rt}function we(nt){let rt="";for(let gt=0;gt<nt.length;gt++){const ft=nt.charCodeAt(gt);ft<128?rt+=String.fromCharCode(ft):ft>127&&ft<2048?(rt+=String.fromCharCode(ft>>6|192),rt+=String.fromCharCode(ft&63|128)):(rt+=String.fromCharCode(ft>>12|224),rt+=String.fromCharCode(ft>>6&63|128),rt+=String.fromCharCode(ft&63|128))}return rt}let Q=[],re,ke,Ne,Z,se,pe,me,be,_e;const Ae=7,le=12,oe=17,Oe=22,rs=5,Re=9,ye=14,ge=20,Le=4,et=11,vt=16,xt=23,dt=6,ze=10,Ye=15,Zt=21;for(n=we(n),Q=te(n),pe=1732584193,me=4023233417,be=2562383102,_e=271733878,re=0;re<Q.length;re+=16)ke=pe,Ne=me,Z=be,se=_e,pe=H(pe,me,be,_e,Q[re+0],Ae,3614090360),_e=H(_e,pe,me,be,Q[re+1],le,3905402710),be=H(be,_e,pe,me,Q[re+2],oe,606105819),me=H(me,be,_e,pe,Q[re+3],Oe,3250441966),pe=H(pe,me,be,_e,Q[re+4],Ae,4118548399),_e=H(_e,pe,me,be,Q[re+5],le,1200080426),be=H(be,_e,pe,me,Q[re+6],oe,2821735955),me=H(me,be,_e,pe,Q[re+7],Oe,4249261313),pe=H(pe,me,be,_e,Q[re+8],Ae,1770035416),_e=H(_e,pe,me,be,Q[re+9],le,2336552879),be=H(be,_e,pe,me,Q[re+10],oe,4294925233),me=H(me,be,_e,pe,Q[re+11],Oe,2304563134),pe=H(pe,me,be,_e,Q[re+12],Ae,1804603682),_e=H(_e,pe,me,be,Q[re+13],le,4254626195),be=H(be,_e,pe,me,Q[re+14],oe,2792965006),me=H(me,be,_e,pe,Q[re+15],Oe,1236535329),pe=F(pe,me,be,_e,Q[re+1],rs,4129170786),_e=F(_e,pe,me,be,Q[re+6],Re,3225465664),be=F(be,_e,pe,me,Q[re+11],ye,643717713),me=F(me,be,_e,pe,Q[re+0],ge,3921069994),pe=F(pe,me,be,_e,Q[re+5],rs,3593408605),_e=F(_e,pe,me,be,Q[re+10],Re,38016083),be=F(be,_e,pe,me,Q[re+15],ye,3634488961),me=F(me,be,_e,pe,Q[re+4],ge,3889429448),pe=F(pe,me,be,_e,Q[re+9],rs,568446438),_e=F(_e,pe,me,be,Q[re+14],Re,3275163606),be=F(be,_e,pe,me,Q[re+3],ye,4107603335),me=F(me,be,_e,pe,Q[re+8],ge,1163531501),pe=F(pe,me,be,_e,Q[re+13],rs,2850285829),_e=F(_e,pe,me,be,Q[re+2],Re,4243563512),be=F(be,_e,pe,me,Q[re+7],ye,1735328473),me=F(me,be,_e,pe,Q[re+12],ge,2368359562),pe=q(pe,me,be,_e,Q[re+5],Le,4294588738),_e=q(_e,pe,me,be,Q[re+8],et,2272392833),be=q(be,_e,pe,me,Q[re+11],vt,1839030562),me=q(me,be,_e,pe,Q[re+14],xt,4259657740),pe=q(pe,me,be,_e,Q[re+1],Le,2763975236),_e=q(_e,pe,me,be,Q[re+4],et,1272893353),be=q(be,_e,pe,me,Q[re+7],vt,4139469664),me=q(me,be,_e,pe,Q[re+10],xt,3200236656),pe=q(pe,me,be,_e,Q[re+13],Le,681279174),_e=q(_e,pe,me,be,Q[re+0],et,3936430074),be=q(be,_e,pe,me,Q[re+3],vt,3572445317),me=q(me,be,_e,pe,Q[re+6],xt,76029189),pe=q(pe,me,be,_e,Q[re+9],Le,3654602809),_e=q(_e,pe,me,be,Q[re+12],et,3873151461),be=q(be,_e,pe,me,Q[re+15],vt,530742520),me=q(me,be,_e,pe,Q[re+2],xt,3299628645),pe=G(pe,me,be,_e,Q[re+0],dt,4096336452),_e=G(_e,pe,me,be,Q[re+7],ze,1126891415),be=G(be,_e,pe,me,Q[re+14],Ye,2878612391),me=G(me,be,_e,pe,Q[re+5],Zt,4237533241),pe=G(pe,me,be,_e,Q[re+12],dt,1700485571),_e=G(_e,pe,me,be,Q[re+3],ze,2399980690),be=G(be,_e,pe,me,Q[re+10],Ye,4293915773),me=G(me,be,_e,pe,Q[re+1],Zt,2240044497),pe=G(pe,me,be,_e,Q[re+8],dt,1873313359),_e=G(_e,pe,me,be,Q[re+15],ze,4264355552),be=G(be,_e,pe,me,Q[re+6],Ye,2734768916),me=G(me,be,_e,pe,Q[re+13],Zt,1309151649),pe=G(pe,me,be,_e,Q[re+4],dt,4149444226),_e=G(_e,pe,me,be,Q[re+11],ze,3174756917),be=G(be,_e,pe,me,Q[re+2],Ye,718787259),me=G(me,be,_e,pe,Q[re+9],Zt,3951481745),pe=_(pe,ke),me=_(me,Ne),be=_(be,Z),_e=_(_e,se);return(X(pe)+X(me)+X(be)+X(_e)).toLowerCase()},cs.closeMediaStream=n=>{if(n)try{let g;if(n.getTracks){g=n.getTracks();for(const _ of g)_.stop()}else{g=n.getAudioTracks();for(const _ of g)_.stop();g=n.getVideoTracks();for(const _ of g)_.stop()}}catch{(typeof n.stop=="function"||typeof n.stop=="object")&&n.stop()}},cs.cloneArray=n=>n&&n.slice()||[],cs.cloneObject=(n,g={})=>n&&Object.assign({},n)||g,cs}const w_=sr,kw=gs,Os=Et,ps=xs(),E_=Zc(),Nw=Dr(),sd=new kw("SIPMessage");class bu{constructor(t,r,l,u,s,n){if(!t||!r||!l)return null;u=u||{},this.ua=l,this.headers={},this.method=t,this.ruri=r,this.body=n,this.extraHeaders=ps.cloneArray(s),this.ua.configuration.extra_headers&&(this.extraHeaders=this.extraHeaders.concat(this.ua.configuration.extra_headers)),u.route_set?this.setHeader("route",u.route_set):l.configuration.use_preloaded_route&&this.setHeader("route",`<${l.transport.sip_uri};lr>`),this.setHeader("via",""),this.setHeader("max-forwards",Os.MAX_FORWARDS);const g=u.to_uri||r,_=u.to_tag?{tag:u.to_tag}:null,v=typeof u.to_display_name<"u"?u.to_display_name:null;this.to=new E_(g,v,_),this.setHeader("to",this.to.toString());const C=u.from_uri||l.configuration.uri,R={tag:u.from_tag||ps.newTag()};let D;typeof u.from_display_name<"u"?D=u.from_display_name:l.configuration.display_name?D=l.configuration.display_name:D=null,this.from=new E_(C,D,R),this.setHeader("from",this.from.toString());const H=u.call_id||l.configuration.jssip_id+ps.createRandomToken(15);this.call_id=H,this.setHeader("call-id",H);const F=u.cseq||Math.floor(Math.random()*1e4);this.cseq=F,this.setHeader("cseq",`${F} ${t}`)}setHeader(t,r){const l=new RegExp(`^\\s*${t}\\s*:`,"i");for(let u=0;u<this.extraHeaders.length;u++)l.test(this.extraHeaders[u])&&this.extraHeaders.splice(u,1);this.headers[ps.headerize(t)]=Array.isArray(r)?r:[r]}getHeader(t){const r=this.headers[ps.headerize(t)];if(r){if(r[0])return r[0]}else{const l=new RegExp(`^\\s*${t}\\s*:`,"i");for(const u of this.extraHeaders)if(l.test(u))return u.substring(u.indexOf(":")+1).trim()}}getHeaders(t){const r=this.headers[ps.headerize(t)],l=[];if(r){for(const u of r)l.push(u);return l}else{const u=new RegExp(`^\\s*${t}\\s*:`,"i");for(const s of this.extraHeaders)u.test(s)&&l.push(s.substring(s.indexOf(":")+1).trim());return l}}hasHeader(t){if(this.headers[ps.headerize(t)])return!0;{const r=new RegExp(`^\\s*${t}\\s*:`,"i");for(const l of this.extraHeaders)if(r.test(l))return!0}return!1}parseSDP(t){return!t&&this.sdp?this.sdp:(this.sdp=w_.parse(this.body||""),this.sdp)}toString(){let t=`${this.method} ${this.ruri} SIP/2.0\r
75
+ `?(o||a++,e=1,o=!1):p==="\r"||p==="\u2028"||p==="\u2029"?(a++,e=1,o=!0):(e++,o=!1)}return{line:a,column:e}}var Ya=Nn(),$r=Zc(),K={},J=u[l]();if(J===null||s!==r.length){var da=Math.max(s,n),fa=da<r.length?r.charAt(da):null,ha=xl();return new this.SyntaxError(Ka(g),fa,da,ha.line,ha.column),-1}return K},toSource:function(){return this._source}};return t.SyntaxError=function(r,l,u,s,n){function g(_,v){var C,R;switch(_.length){case 0:C="end of input";break;case 1:C=_[0];break;default:C=_.slice(0,_.length-1).join(", ")+" or "+_[_.length-1]}return R=v?f(v):"end of input","Expected "+C+" but "+R+" found."}this.name="SyntaxError",this.expected=r,this.found=l,this.message=g(r,l),this.offset=u,this.line=s,this.column=n},t.SyntaxError.prototype=Error.prototype,t}()),ed}var td,T_;function Nn(){if(T_)return td;T_=1;const f=Et,t=xs(),r=Dr();return td=class jT{static parse(u){if(u=r.parse(u,"SIP_URI"),u!==-1)return u}constructor(u,s,n,g,_={},v={}){if(!n)throw new TypeError('missing or invalid "host" parameter');this._parameters={},this._headers={},this._scheme=u||f.SIP,this._user=s,this._host=n,this._port=g;for(const C in _)Object.prototype.hasOwnProperty.call(_,C)&&this.setParam(C,_[C]);for(const C in v)Object.prototype.hasOwnProperty.call(v,C)&&this.setHeader(C,v[C])}get scheme(){return this._scheme}set scheme(u){this._scheme=u.toLowerCase()}get user(){return this._user}set user(u){this._user=u}get host(){return this._host}set host(u){this._host=u.toLowerCase()}get port(){return this._port}set port(u){this._port=u===0?u:parseInt(u,10)||null}setParam(u,s){u&&(this._parameters[u.toLowerCase()]=typeof s>"u"||s===null?null:s.toString())}getParam(u){if(u)return this._parameters[u.toLowerCase()]}hasParam(u){if(u)return this._parameters.hasOwnProperty(u.toLowerCase())&&!0||!1}deleteParam(u){if(u=u.toLowerCase(),this._parameters.hasOwnProperty(u)){const s=this._parameters[u];return delete this._parameters[u],s}}clearParams(){this._parameters={}}setHeader(u,s){this._headers[t.headerize(u)]=Array.isArray(s)?s:[s]}getHeader(u){if(u)return this._headers[t.headerize(u)]}hasHeader(u){if(u)return this._headers.hasOwnProperty(t.headerize(u))&&!0||!1}deleteHeader(u){if(u=t.headerize(u),this._headers.hasOwnProperty(u)){const s=this._headers[u];return delete this._headers[u],s}}clearHeaders(){this._headers={}}clone(){return new jT(this._scheme,this._user,this._host,this._port,JSON.parse(JSON.stringify(this._parameters)),JSON.parse(JSON.stringify(this._headers)))}toString(){const u=[];let s=`${this._scheme}:`;this._user&&(s+=`${t.escapeUser(this._user)}@`),s+=this._host,(this._port||this._port===0)&&(s+=`:${this._port}`);for(const n in this._parameters)Object.prototype.hasOwnProperty.call(this._parameters,n)&&(s+=`;${n}`,this._parameters[n]!==null&&(s+=`=${this._parameters[n]}`));for(const n in this._headers)if(Object.prototype.hasOwnProperty.call(this._headers,n))for(const g of this._headers[n])u.push(`${n}=${g}`);return u.length>0&&(s+=`?${u.join("&")}`),s}toAor(u){let s=`${this._scheme}:`;return this._user&&(s+=`${t.escapeUser(this._user)}@`),s+=this._host,u&&(this._port||this._port===0)&&(s+=`:${this._port}`),s}},td}var S_;function xs(){if(S_)return cs;S_=1;const f=Et,t=Nn(),r=Dr();cs.str_utf8_length=n=>unescape(encodeURIComponent(n)).length;const l=cs.isFunction=n=>n!==void 0?Object.prototype.toString.call(n)==="[object Function]":!1;cs.isString=n=>n!==void 0?Object.prototype.toString.call(n)==="[object String]":!1,cs.isDecimal=n=>!isNaN(n)&&parseFloat(n)===parseInt(n,10),cs.isEmpty=n=>n===null||n===""||n===void 0||Array.isArray(n)&&n.length===0||typeof n=="number"&&isNaN(n),cs.hasMethods=function(n,...g){for(const _ of g)if(l(n[_]))return!1;return!0};const u=cs.createRandomToken=(n,g=32)=>{let _,v,C="";for(_=0;_<n;_++)v=Math.random()*g|0,C+=v.toString(g);return C};cs.newTag=()=>u(10),cs.newUUID=()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,g=>{const _=Math.random()*16|0;return(g==="x"?_:_&3|8).toString(16)}),cs.hostType=n=>{if(n){if(n=r.parse(n,"host"),n!==-1)return n.host_type}else return};const s=cs.escapeUser=n=>encodeURIComponent(decodeURIComponent(n)).replace(/%3A/ig,":").replace(/%2B/ig,"+").replace(/%3F/ig,"?").replace(/%2F/ig,"/");return cs.normalizeTarget=(n,g)=>{if(n){if(n instanceof t)return n;if(typeof n=="string"){const _=n.split("@");let v,C;switch(_.length){case 1:if(!g)return;v=n,C=g;break;case 2:v=_[0],C=_[1];break;default:v=_.slice(0,_.length-1).join("@"),C=_[_.length-1]}v=v.replace(/^(sips?|tel):/i,""),/^[-.()]*\+?[0-9\-.()]+$/.test(v)&&(v=v.replace(/[-.()]/g,"")),n=`${f.SIP}:${s(v)}@${C}`;let R;return(R=t.parse(n))?R:void 0}else return}else return},cs.headerize=n=>{const g={"Call-Id":"Call-ID",Cseq:"CSeq","Www-Authenticate":"WWW-Authenticate"},_=n.toLowerCase().replace(/_/g,"-").split("-");let v="";const C=_.length;let R;for(R=0;R<C;R++)R!==0&&(v+="-"),v+=_[R].charAt(0).toUpperCase()+_[R].substring(1);return g[v]&&(v=g[v]),v},cs.sipErrorCause=n=>{for(const g in f.SIP_ERROR_CAUSES)if(f.SIP_ERROR_CAUSES[g].indexOf(n)!==-1)return f.causes[g];return f.causes.SIP_FAILURE_CODE},cs.getRandomTestNetIP=()=>{function n(g,_){return Math.floor(Math.random()*(_-g+1)+g)}return`192.0.2.${n(1,254)}`},cs.calculateMD5=n=>{function g(nt,rt){return nt<<rt|nt>>>32-rt}function _(nt,rt){const gt=nt&2147483648,ft=rt&2147483648,Fe=nt&1073741824,He=rt&1073741824,qe=(nt&1073741823)+(rt&1073741823);return Fe&He?qe^2147483648^gt^ft:Fe|He?qe&1073741824?qe^3221225472^gt^ft:qe^1073741824^gt^ft:qe^gt^ft}function v(nt,rt,gt){return nt&rt|~nt&gt}function C(nt,rt,gt){return nt&gt|rt&~gt}function R(nt,rt,gt){return nt^rt^gt}function D(nt,rt,gt){return rt^(nt|~gt)}function H(nt,rt,gt,ft,Fe,He,qe){return nt=_(nt,_(_(v(rt,gt,ft),Fe),qe)),_(g(nt,He),rt)}function F(nt,rt,gt,ft,Fe,He,qe){return nt=_(nt,_(_(C(rt,gt,ft),Fe),qe)),_(g(nt,He),rt)}function q(nt,rt,gt,ft,Fe,He,qe){return nt=_(nt,_(_(R(rt,gt,ft),Fe),qe)),_(g(nt,He),rt)}function G(nt,rt,gt,ft,Fe,He,qe){return nt=_(nt,_(_(D(rt,gt,ft),Fe),qe)),_(g(nt,He),rt)}function te(nt){let rt;const gt=nt.length,ft=gt+8,He=((ft-ft%64)/64+1)*16,qe=new Array(He-1);let yt=0,Ct=0;for(;Ct<gt;)rt=(Ct-Ct%4)/4,yt=Ct%4*8,qe[rt]=qe[rt]|nt.charCodeAt(Ct)<<yt,Ct++;return rt=(Ct-Ct%4)/4,yt=Ct%4*8,qe[rt]=qe[rt]|128<<yt,qe[He-2]=gt<<3,qe[He-1]=gt>>>29,qe}function X(nt){let rt="",gt="",ft,Fe;for(Fe=0;Fe<=3;Fe++)ft=nt>>>Fe*8&255,gt=`0${ft.toString(16)}`,rt=rt+gt.substr(gt.length-2,2);return rt}function we(nt){let rt="";for(let gt=0;gt<nt.length;gt++){const ft=nt.charCodeAt(gt);ft<128?rt+=String.fromCharCode(ft):ft>127&&ft<2048?(rt+=String.fromCharCode(ft>>6|192),rt+=String.fromCharCode(ft&63|128)):(rt+=String.fromCharCode(ft>>12|224),rt+=String.fromCharCode(ft>>6&63|128),rt+=String.fromCharCode(ft&63|128))}return rt}let Q=[],re,ke,Ne,Z,se,pe,me,be,_e;const Ae=7,le=12,oe=17,Oe=22,rs=5,Re=9,ye=14,ge=20,Le=4,et=11,vt=16,xt=23,dt=6,ze=10,Ye=15,Zt=21;for(n=we(n),Q=te(n),pe=1732584193,me=4023233417,be=2562383102,_e=271733878,re=0;re<Q.length;re+=16)ke=pe,Ne=me,Z=be,se=_e,pe=H(pe,me,be,_e,Q[re+0],Ae,3614090360),_e=H(_e,pe,me,be,Q[re+1],le,3905402710),be=H(be,_e,pe,me,Q[re+2],oe,606105819),me=H(me,be,_e,pe,Q[re+3],Oe,3250441966),pe=H(pe,me,be,_e,Q[re+4],Ae,4118548399),_e=H(_e,pe,me,be,Q[re+5],le,1200080426),be=H(be,_e,pe,me,Q[re+6],oe,2821735955),me=H(me,be,_e,pe,Q[re+7],Oe,4249261313),pe=H(pe,me,be,_e,Q[re+8],Ae,1770035416),_e=H(_e,pe,me,be,Q[re+9],le,2336552879),be=H(be,_e,pe,me,Q[re+10],oe,4294925233),me=H(me,be,_e,pe,Q[re+11],Oe,2304563134),pe=H(pe,me,be,_e,Q[re+12],Ae,1804603682),_e=H(_e,pe,me,be,Q[re+13],le,4254626195),be=H(be,_e,pe,me,Q[re+14],oe,2792965006),me=H(me,be,_e,pe,Q[re+15],Oe,1236535329),pe=F(pe,me,be,_e,Q[re+1],rs,4129170786),_e=F(_e,pe,me,be,Q[re+6],Re,3225465664),be=F(be,_e,pe,me,Q[re+11],ye,643717713),me=F(me,be,_e,pe,Q[re+0],ge,3921069994),pe=F(pe,me,be,_e,Q[re+5],rs,3593408605),_e=F(_e,pe,me,be,Q[re+10],Re,38016083),be=F(be,_e,pe,me,Q[re+15],ye,3634488961),me=F(me,be,_e,pe,Q[re+4],ge,3889429448),pe=F(pe,me,be,_e,Q[re+9],rs,568446438),_e=F(_e,pe,me,be,Q[re+14],Re,3275163606),be=F(be,_e,pe,me,Q[re+3],ye,4107603335),me=F(me,be,_e,pe,Q[re+8],ge,1163531501),pe=F(pe,me,be,_e,Q[re+13],rs,2850285829),_e=F(_e,pe,me,be,Q[re+2],Re,4243563512),be=F(be,_e,pe,me,Q[re+7],ye,1735328473),me=F(me,be,_e,pe,Q[re+12],ge,2368359562),pe=q(pe,me,be,_e,Q[re+5],Le,4294588738),_e=q(_e,pe,me,be,Q[re+8],et,2272392833),be=q(be,_e,pe,me,Q[re+11],vt,1839030562),me=q(me,be,_e,pe,Q[re+14],xt,4259657740),pe=q(pe,me,be,_e,Q[re+1],Le,2763975236),_e=q(_e,pe,me,be,Q[re+4],et,1272893353),be=q(be,_e,pe,me,Q[re+7],vt,4139469664),me=q(me,be,_e,pe,Q[re+10],xt,3200236656),pe=q(pe,me,be,_e,Q[re+13],Le,681279174),_e=q(_e,pe,me,be,Q[re+0],et,3936430074),be=q(be,_e,pe,me,Q[re+3],vt,3572445317),me=q(me,be,_e,pe,Q[re+6],xt,76029189),pe=q(pe,me,be,_e,Q[re+9],Le,3654602809),_e=q(_e,pe,me,be,Q[re+12],et,3873151461),be=q(be,_e,pe,me,Q[re+15],vt,530742520),me=q(me,be,_e,pe,Q[re+2],xt,3299628645),pe=G(pe,me,be,_e,Q[re+0],dt,4096336452),_e=G(_e,pe,me,be,Q[re+7],ze,1126891415),be=G(be,_e,pe,me,Q[re+14],Ye,2878612391),me=G(me,be,_e,pe,Q[re+5],Zt,4237533241),pe=G(pe,me,be,_e,Q[re+12],dt,1700485571),_e=G(_e,pe,me,be,Q[re+3],ze,2399980690),be=G(be,_e,pe,me,Q[re+10],Ye,4293915773),me=G(me,be,_e,pe,Q[re+1],Zt,2240044497),pe=G(pe,me,be,_e,Q[re+8],dt,1873313359),_e=G(_e,pe,me,be,Q[re+15],ze,4264355552),be=G(be,_e,pe,me,Q[re+6],Ye,2734768916),me=G(me,be,_e,pe,Q[re+13],Zt,1309151649),pe=G(pe,me,be,_e,Q[re+4],dt,4149444226),_e=G(_e,pe,me,be,Q[re+11],ze,3174756917),be=G(be,_e,pe,me,Q[re+2],Ye,718787259),me=G(me,be,_e,pe,Q[re+9],Zt,3951481745),pe=_(pe,ke),me=_(me,Ne),be=_(be,Z),_e=_(_e,se);return(X(pe)+X(me)+X(be)+X(_e)).toLowerCase()},cs.closeMediaStream=n=>{if(n)try{let g;if(n.getTracks){g=n.getTracks();for(const _ of g)_.stop()}else{g=n.getAudioTracks();for(const _ of g)_.stop();g=n.getVideoTracks();for(const _ of g)_.stop()}}catch{(typeof n.stop=="function"||typeof n.stop=="object")&&n.stop()}},cs.cloneArray=n=>n&&n.slice()||[],cs.cloneObject=(n,g={})=>n&&Object.assign({},n)||g,cs}const b_=sr,kw=gs,Os=Et,ps=xs(),w_=Zc(),Nw=Dr(),sd=new kw("SIPMessage");class bu{constructor(t,r,l,u,s,n){if(!t||!r||!l)return null;u=u||{},this.ua=l,this.headers={},this.method=t,this.ruri=r,this.body=n,this.extraHeaders=ps.cloneArray(s),this.ua.configuration.extra_headers&&(this.extraHeaders=this.extraHeaders.concat(this.ua.configuration.extra_headers)),u.route_set?this.setHeader("route",u.route_set):l.configuration.use_preloaded_route&&this.setHeader("route",`<${l.transport.sip_uri};lr>`),this.setHeader("via",""),this.setHeader("max-forwards",Os.MAX_FORWARDS);const g=u.to_uri||r,_=u.to_tag?{tag:u.to_tag}:null,v=typeof u.to_display_name<"u"?u.to_display_name:null;this.to=new w_(g,v,_),this.setHeader("to",this.to.toString());const C=u.from_uri||l.configuration.uri,R={tag:u.from_tag||ps.newTag()};let D;typeof u.from_display_name<"u"?D=u.from_display_name:l.configuration.display_name?D=l.configuration.display_name:D=null,this.from=new w_(C,D,R),this.setHeader("from",this.from.toString());const H=u.call_id||l.configuration.jssip_id+ps.createRandomToken(15);this.call_id=H,this.setHeader("call-id",H);const F=u.cseq||Math.floor(Math.random()*1e4);this.cseq=F,this.setHeader("cseq",`${F} ${t}`)}setHeader(t,r){const l=new RegExp(`^\\s*${t}\\s*:`,"i");for(let u=0;u<this.extraHeaders.length;u++)l.test(this.extraHeaders[u])&&this.extraHeaders.splice(u,1);this.headers[ps.headerize(t)]=Array.isArray(r)?r:[r]}getHeader(t){const r=this.headers[ps.headerize(t)];if(r){if(r[0])return r[0]}else{const l=new RegExp(`^\\s*${t}\\s*:`,"i");for(const u of this.extraHeaders)if(l.test(u))return u.substring(u.indexOf(":")+1).trim()}}getHeaders(t){const r=this.headers[ps.headerize(t)],l=[];if(r){for(const u of r)l.push(u);return l}else{const u=new RegExp(`^\\s*${t}\\s*:`,"i");for(const s of this.extraHeaders)u.test(s)&&l.push(s.substring(s.indexOf(":")+1).trim());return l}}hasHeader(t){if(this.headers[ps.headerize(t)])return!0;{const r=new RegExp(`^\\s*${t}\\s*:`,"i");for(const l of this.extraHeaders)if(r.test(l))return!0}return!1}parseSDP(t){return!t&&this.sdp?this.sdp:(this.sdp=b_.parse(this.body||""),this.sdp)}toString(){let t=`${this.method} ${this.ruri} SIP/2.0\r
76
76
  `;for(const u in this.headers)if(Object.prototype.hasOwnProperty.call(this.headers,u))for(const s of this.headers[u])t+=`${u}: ${s}\r
77
77
  `;for(const u of this.extraHeaders)t+=`${u.trim()}\r
78
78
  `;const r=[];switch(this.method){case Os.REGISTER:r.push("path","gruu");break;case Os.INVITE:this.ua.configuration.session_timers&&r.push("timer"),(this.ua.contact.pub_gruu||this.ua.contact.temp_gruu)&&r.push("gruu"),r.push("ice","replaces");break;case Os.UPDATE:this.ua.configuration.session_timers&&r.push("timer"),r.push("ice");break}r.push("outbound");const l=this.ua.configuration.user_agent||Os.USER_AGENT;if(t+=`Allow: ${Os.ALLOWED_METHODS}\r
@@ -82,7 +82,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
82
82
  \r
83
83
  `,t+=this.body}else t+=`Content-Length: 0\r
84
84
  \r
85
- `;return t}clone(){const t=new bu(this.method,this.ruri,this.ua);return Object.keys(this.headers).forEach(function(r){t.headers[r]=this.headers[r].slice()},this),t.body=this.body,t.extraHeaders=ps.cloneArray(this.extraHeaders),t.to=this.to,t.from=this.from,t.call_id=this.call_id,t.cseq=this.cseq,t}}class rd extends bu{constructor(t,r,l,u,s){super(Os.INVITE,t,r,l,u,s),this.transaction=null}cancel(t){this.transaction.cancel(t)}clone(){const t=new rd(this.ruri,this.ua);return Object.keys(this.headers).forEach(function(r){t.headers[r]=this.headers[r].slice()},this),t.body=this.body,t.extraHeaders=ps.cloneArray(this.extraHeaders),t.to=this.to,t.from=this.from,t.call_id=this.call_id,t.cseq=this.cseq,t.transaction=this.transaction,t}}class C_{constructor(){this.data=null,this.headers=null,this.method=null,this.via=null,this.via_branch=null,this.call_id=null,this.cseq=null,this.from=null,this.from_tag=null,this.to=null,this.to_tag=null,this.body=null,this.sdp=null}addHeader(t,r){const l={raw:r};t=ps.headerize(t),this.headers[t]?this.headers[t].push(l):this.headers[t]=[l]}getHeader(t){const r=this.headers[ps.headerize(t)];if(r){if(r[0])return r[0].raw}else return}getHeaders(t){const r=this.headers[ps.headerize(t)],l=[];if(!r)return[];for(const u of r)l.push(u.raw);return l}hasHeader(t){return!!this.headers[ps.headerize(t)]}parseHeader(t,r=0){if(t=ps.headerize(t),this.headers[t]){if(r>=this.headers[t].length){sd.debug(`not so many "${t}" headers present`);return}}else{sd.debug(`header "${t}" not present`);return}const l=this.headers[t][r],u=l.raw;if(l.parsed)return l.parsed;const s=Nw.parse(u,t.replace(/-/g,"_"));if(s===-1){this.headers[t].splice(r,1),sd.debug(`error parsing "${t}" header field with value "${u}"`);return}else return l.parsed=s,s}s(t,r){return this.parseHeader(t,r)}setHeader(t,r){const l={raw:r};this.headers[ps.headerize(t)]=[l]}parseSDP(t){return!t&&this.sdp?this.sdp:(this.sdp=w_.parse(this.body||""),this.sdp)}toString(){return this.data}}class Mw extends C_{constructor(t){super(),this.ua=t,this.headers={},this.ruri=null,this.transport=null,this.server_transaction=null}reply(t,r,l,u,s,n){const g=[];let _=this.getHeader("To");if(t=t||null,r=r||null,!t||t<100||t>699)throw new TypeError(`Invalid status_code: ${t}`);if(r&&typeof r!="string"&&!(r instanceof String))throw new TypeError(`Invalid reason_phrase: ${r}`);r=r||Os.REASON_PHRASE[t]||"",l=ps.cloneArray(l),this.ua.configuration.extra_headers&&(l=l.concat(this.ua.configuration.extra_headers));let v=`SIP/2.0 ${t} ${r}\r
85
+ `;return t}clone(){const t=new bu(this.method,this.ruri,this.ua);return Object.keys(this.headers).forEach(function(r){t.headers[r]=this.headers[r].slice()},this),t.body=this.body,t.extraHeaders=ps.cloneArray(this.extraHeaders),t.to=this.to,t.from=this.from,t.call_id=this.call_id,t.cseq=this.cseq,t}}class rd extends bu{constructor(t,r,l,u,s){super(Os.INVITE,t,r,l,u,s),this.transaction=null}cancel(t){this.transaction.cancel(t)}clone(){const t=new rd(this.ruri,this.ua);return Object.keys(this.headers).forEach(function(r){t.headers[r]=this.headers[r].slice()},this),t.body=this.body,t.extraHeaders=ps.cloneArray(this.extraHeaders),t.to=this.to,t.from=this.from,t.call_id=this.call_id,t.cseq=this.cseq,t.transaction=this.transaction,t}}class E_{constructor(){this.data=null,this.headers=null,this.method=null,this.via=null,this.via_branch=null,this.call_id=null,this.cseq=null,this.from=null,this.from_tag=null,this.to=null,this.to_tag=null,this.body=null,this.sdp=null}addHeader(t,r){const l={raw:r};t=ps.headerize(t),this.headers[t]?this.headers[t].push(l):this.headers[t]=[l]}getHeader(t){const r=this.headers[ps.headerize(t)];if(r){if(r[0])return r[0].raw}else return}getHeaders(t){const r=this.headers[ps.headerize(t)],l=[];if(!r)return[];for(const u of r)l.push(u.raw);return l}hasHeader(t){return!!this.headers[ps.headerize(t)]}parseHeader(t,r=0){if(t=ps.headerize(t),this.headers[t]){if(r>=this.headers[t].length){sd.debug(`not so many "${t}" headers present`);return}}else{sd.debug(`header "${t}" not present`);return}const l=this.headers[t][r],u=l.raw;if(l.parsed)return l.parsed;const s=Nw.parse(u,t.replace(/-/g,"_"));if(s===-1){this.headers[t].splice(r,1),sd.debug(`error parsing "${t}" header field with value "${u}"`);return}else return l.parsed=s,s}s(t,r){return this.parseHeader(t,r)}setHeader(t,r){const l={raw:r};this.headers[ps.headerize(t)]=[l]}parseSDP(t){return!t&&this.sdp?this.sdp:(this.sdp=b_.parse(this.body||""),this.sdp)}toString(){return this.data}}class Mw extends E_{constructor(t){super(),this.ua=t,this.headers={},this.ruri=null,this.transport=null,this.server_transaction=null}reply(t,r,l,u,s,n){const g=[];let _=this.getHeader("To");if(t=t||null,r=r||null,!t||t<100||t>699)throw new TypeError(`Invalid status_code: ${t}`);if(r&&typeof r!="string"&&!(r instanceof String))throw new TypeError(`Invalid reason_phrase: ${r}`);r=r||Os.REASON_PHRASE[t]||"",l=ps.cloneArray(l),this.ua.configuration.extra_headers&&(l=l.concat(this.ua.configuration.extra_headers));let v=`SIP/2.0 ${t} ${r}\r
86
86
  `;if(this.method===Os.INVITE&&t>100&&t<=200){const R=this.getHeaders("record-route");for(const D of R)v+=`Record-Route: ${D}\r
87
87
  `}const C=this.getHeaders("via");for(const R of C)v+=`Via: ${R}\r
88
88
  `;!this.to_tag&&t>100?_+=`;tag=${ps.newTag()}`:this.to_tag&&!this.s("to").hasParam("tag")&&(_+=`;tag=${this.to_tag}`),v+=`To: ${_}\r
@@ -109,10 +109,10 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
109
109
  `,this.ua.configuration.extra_headers)for(const n of this.ua.configuration.extra_headers)u+=`${n.trim()}\r
110
110
  `;u+=`Content-Length: 0\r
111
111
  \r
112
- `,this.transport.send(u)}}class Uw extends C_{constructor(){super(),this.headers={},this.status_code=null,this.reason_phrase=null}}var Ds={OutgoingRequest:bu,InitialOutgoingInviteRequest:rd,IncomingRequest:Mw,IncomingResponse:Uw};const fl=Ht(Ds),Pw=gs,Mn=xs(),kr=new Pw("DigestAuthentication");var A_=class{constructor(t){this._credentials=t,this._cnonce=null,this._nc=0,this._ncHex="00000000",this._algorithm=null,this._realm=null,this._nonce=null,this._opaque=null,this._stale=null,this._qop=null,this._method=null,this._uri=null,this._ha1=null,this._response=null}get(t){switch(t){case"realm":return this._realm;case"ha1":return this._ha1;default:kr.warn('get() | cannot get "%s" parameter',t);return}}authenticate({method:t,ruri:r,body:l},u,s=null){if(this._algorithm=u.algorithm,this._realm=u.realm,this._nonce=u.nonce,this._opaque=u.opaque,this._stale=u.stale,this._algorithm){if(this._algorithm!=="MD5")return kr.warn('authenticate() | challenge with Digest algorithm different than "MD5", authentication aborted'),!1}else this._algorithm="MD5";if(!this._nonce)return kr.warn("authenticate() | challenge without Digest nonce, authentication aborted"),!1;if(!this._realm)return kr.warn("authenticate() | challenge without Digest realm, authentication aborted"),!1;if(!this._credentials.password){if(!this._credentials.ha1)return kr.warn("authenticate() | no plain SIP password nor ha1 provided, authentication aborted"),!1;if(this._credentials.realm!==this._realm)return kr.warn('authenticate() | no plain SIP password, and stored `realm` does not match the given `realm`, cannot authenticate [stored:"%s", given:"%s"]',this._credentials.realm,this._realm),!1}if(u.qop)if(u.qop.indexOf("auth-int")>-1)this._qop="auth-int";else if(u.qop.indexOf("auth")>-1)this._qop="auth";else return kr.warn('authenticate() | challenge without Digest qop different than "auth" or "auth-int", authentication aborted'),!1;else this._qop=null;this._method=t,this._uri=r,this._cnonce=s||Mn.createRandomToken(12),this._nc+=1;const n=Number(this._nc).toString(16);this._ncHex="00000000".substr(0,8-n.length)+n,this._nc===4294967296&&(this._nc=1,this._ncHex="00000001"),this._credentials.password?this._ha1=Mn.calculateMD5(`${this._credentials.username}:${this._realm}:${this._credentials.password}`):this._ha1=this._credentials.ha1;let g,_;return this._qop==="auth"?(g=`${this._method}:${this._uri}`,_=Mn.calculateMD5(g),kr.debug('authenticate() | using qop=auth [a2:"%s"]',g),this._response=Mn.calculateMD5(`${this._ha1}:${this._nonce}:${this._ncHex}:${this._cnonce}:auth:${_}`)):this._qop==="auth-int"?(g=`${this._method}:${this._uri}:${Mn.calculateMD5(l||"")}`,_=Mn.calculateMD5(g),kr.debug('authenticate() | using qop=auth-int [a2:"%s"]',g),this._response=Mn.calculateMD5(`${this._ha1}:${this._nonce}:${this._ncHex}:${this._cnonce}:auth-int:${_}`)):this._qop===null&&(g=`${this._method}:${this._uri}`,_=Mn.calculateMD5(g),kr.debug('authenticate() | using qop=null [a2:"%s"]',g),this._response=Mn.calculateMD5(`${this._ha1}:${this._nonce}:${_}`)),kr.debug("authenticate() | response generated"),!0}toString(){const t=[];if(!this._response)throw new Error("response field does not exist, cannot generate Authorization header");return t.push(`algorithm=${this._algorithm}`),t.push(`username="${this._credentials.username}"`),t.push(`realm="${this._realm}"`),t.push(`nonce="${this._nonce}"`),t.push(`uri="${this._uri}"`),t.push(`response="${this._response}"`),this._opaque&&t.push(`opaque="${this._opaque}"`),this._qop&&(t.push(`qop=${this._qop}`),t.push(`cnonce="${this._cnonce}"`),t.push(`nc=${this._ncHex}`)),`Digest ${t.join(", ")}`}};const Lw=Ht(A_),Un=500,Hw=4e3,I_=5e3;var nd={T1:Un,T2:Hw,T4:I_,TIMER_B:64*Un,TIMER_D:0*Un,TIMER_F:64*Un,TIMER_H:64*Un,TIMER_I:0*Un,TIMER_J:0*Un,TIMER_K:0*I_,TIMER_L:64*Un,TIMER_M:64*Un,PROVISIONAL_RESPONSE_INTERVAL:6e4};const eo=Ht(nd),to=ys.EventEmitter,so=gs,ro=Et,R_=Ds,dn=nd,$_=new so("NonInviteClientTransaction"),wu=new so("InviteClientTransaction"),Fw=new so("AckClientTransaction"),x_=new so("NonInviteServerTransaction"),Eu=new so("InviteServerTransaction"),We={STATUS_TRYING:1,STATUS_PROCEEDING:2,STATUS_CALLING:3,STATUS_ACCEPTED:4,STATUS_COMPLETED:5,STATUS_TERMINATED:6,STATUS_CONFIRMED:7,NON_INVITE_CLIENT:"nict",NON_INVITE_SERVER:"nist",INVITE_CLIENT:"ict",INVITE_SERVER:"ist"};class Bw extends to{constructor(t,r,l,u){super(),this.type=We.NON_INVITE_CLIENT,this.id=`z9hG4bK${Math.floor(Math.random()*1e7)}`,this.ua=t,this.transport=r,this.request=l,this.eventHandlers=u;let s=`SIP/2.0/${r.via_transport}`;s+=` ${t.configuration.via_host};branch=${this.id}`,this.request.setHeader("via",s),this.ua.newTransaction(this)}get C(){return We}stateChanged(t){this.state=t,this.emit("stateChanged")}send(){this.stateChanged(We.STATUS_TRYING),this.F=setTimeout(()=>{this.timer_F()},dn.TIMER_F),this.transport.send(this.request)||this.onTransportError()}onTransportError(){$_.debug(`transport error occurred, deleting transaction ${this.id}`),clearTimeout(this.F),clearTimeout(this.K),this.stateChanged(We.STATUS_TERMINATED),this.ua.destroyTransaction(this),this.eventHandlers.onTransportError()}timer_F(){$_.debug(`Timer F expired for transaction ${this.id}`),this.stateChanged(We.STATUS_TERMINATED),this.ua.destroyTransaction(this),this.eventHandlers.onRequestTimeout()}timer_K(){this.stateChanged(We.STATUS_TERMINATED),this.ua.destroyTransaction(this)}receiveResponse(t){const r=t.status_code;if(r<200)switch(this.state){case We.STATUS_TRYING:case We.STATUS_PROCEEDING:this.stateChanged(We.STATUS_PROCEEDING),this.eventHandlers.onReceiveResponse(t);break}else switch(this.state){case We.STATUS_TRYING:case We.STATUS_PROCEEDING:this.stateChanged(We.STATUS_COMPLETED),clearTimeout(this.F),r===408?this.eventHandlers.onRequestTimeout():this.eventHandlers.onReceiveResponse(t),this.K=setTimeout(()=>{this.timer_K()},dn.TIMER_K);break;case We.STATUS_COMPLETED:break}}}class zw extends to{constructor(t,r,l,u){super(),this.type=We.INVITE_CLIENT,this.id=`z9hG4bK${Math.floor(Math.random()*1e7)}`,this.ua=t,this.transport=r,this.request=l,this.eventHandlers=u,l.transaction=this;let s=`SIP/2.0/${r.via_transport}`;s+=` ${t.configuration.via_host};branch=${this.id}`,this.request.setHeader("via",s),this.ua.newTransaction(this)}get C(){return We}stateChanged(t){this.state=t,this.emit("stateChanged")}send(){this.stateChanged(We.STATUS_CALLING),this.B=setTimeout(()=>{this.timer_B()},dn.TIMER_B),this.transport.send(this.request)||this.onTransportError()}onTransportError(){clearTimeout(this.B),clearTimeout(this.D),clearTimeout(this.M),this.state!==We.STATUS_ACCEPTED&&(wu.debug(`transport error occurred, deleting transaction ${this.id}`),this.eventHandlers.onTransportError()),this.stateChanged(We.STATUS_TERMINATED),this.ua.destroyTransaction(this)}timer_M(){wu.debug(`Timer M expired for transaction ${this.id}`),this.state===We.STATUS_ACCEPTED&&(clearTimeout(this.B),this.stateChanged(We.STATUS_TERMINATED),this.ua.destroyTransaction(this))}timer_B(){wu.debug(`Timer B expired for transaction ${this.id}`),this.state===We.STATUS_CALLING&&(this.stateChanged(We.STATUS_TERMINATED),this.ua.destroyTransaction(this),this.eventHandlers.onRequestTimeout())}timer_D(){wu.debug(`Timer D expired for transaction ${this.id}`),clearTimeout(this.B),this.stateChanged(We.STATUS_TERMINATED),this.ua.destroyTransaction(this)}sendACK(t){const r=new R_.OutgoingRequest(ro.ACK,this.request.ruri,this.ua,{route_set:this.request.getHeaders("route"),call_id:this.request.getHeader("call-id"),cseq:this.request.cseq});r.setHeader("from",this.request.getHeader("from")),r.setHeader("via",this.request.getHeader("via")),r.setHeader("to",t.getHeader("to")),this.D=setTimeout(()=>{this.timer_D()},dn.TIMER_D),this.transport.send(r)}cancel(t){if(this.state!==We.STATUS_PROCEEDING)return;const r=new R_.OutgoingRequest(ro.CANCEL,this.request.ruri,this.ua,{route_set:this.request.getHeaders("route"),call_id:this.request.getHeader("call-id"),cseq:this.request.cseq});r.setHeader("from",this.request.getHeader("from")),r.setHeader("via",this.request.getHeader("via")),r.setHeader("to",this.request.getHeader("to")),t&&r.setHeader("reason",t),this.transport.send(r)}receiveResponse(t){const r=t.status_code;if(r>=100&&r<=199)switch(this.state){case We.STATUS_CALLING:this.stateChanged(We.STATUS_PROCEEDING),this.eventHandlers.onReceiveResponse(t);break;case We.STATUS_PROCEEDING:this.eventHandlers.onReceiveResponse(t);break}else if(r>=200&&r<=299)switch(this.state){case We.STATUS_CALLING:case We.STATUS_PROCEEDING:this.stateChanged(We.STATUS_ACCEPTED),this.M=setTimeout(()=>{this.timer_M()},dn.TIMER_M),this.eventHandlers.onReceiveResponse(t);break;case We.STATUS_ACCEPTED:this.eventHandlers.onReceiveResponse(t);break}else if(r>=300&&r<=699)switch(this.state){case We.STATUS_CALLING:case We.STATUS_PROCEEDING:this.stateChanged(We.STATUS_COMPLETED),this.sendACK(t),this.eventHandlers.onReceiveResponse(t);break;case We.STATUS_COMPLETED:this.sendACK(t);break}}}class Vw extends to{constructor(t,r,l,u){super(),this.id=`z9hG4bK${Math.floor(Math.random()*1e7)}`,this.transport=r,this.request=l,this.eventHandlers=u;let s=`SIP/2.0/${r.via_transport}`;s+=` ${t.configuration.via_host};branch=${this.id}`,this.request.setHeader("via",s)}get C(){return We}send(){this.transport.send(this.request)||this.onTransportError()}onTransportError(){Fw.debug(`transport error occurred for transaction ${this.id}`),this.eventHandlers.onTransportError()}}class qw extends to{constructor(t,r,l){super(),this.type=We.NON_INVITE_SERVER,this.id=l.via_branch,this.ua=t,this.transport=r,this.request=l,this.last_response="",l.server_transaction=this,this.state=We.STATUS_TRYING,t.newTransaction(this)}get C(){return We}stateChanged(t){this.state=t,this.emit("stateChanged")}timer_J(){x_.debug(`Timer J expired for transaction ${this.id}`),this.stateChanged(We.STATUS_TERMINATED),this.ua.destroyTransaction(this)}onTransportError(){this.transportError||(this.transportError=!0,x_.debug(`transport error occurred, deleting transaction ${this.id}`),clearTimeout(this.J),this.stateChanged(We.STATUS_TERMINATED),this.ua.destroyTransaction(this))}receiveResponse(t,r,l,u){if(t===100)switch(this.state){case We.STATUS_TRYING:this.stateChanged(We.STATUS_PROCEEDING),this.transport.send(r)||this.onTransportError();break;case We.STATUS_PROCEEDING:this.last_response=r,this.transport.send(r)?l&&l():(this.onTransportError(),u&&u());break}else if(t>=200&&t<=699)switch(this.state){case We.STATUS_TRYING:case We.STATUS_PROCEEDING:this.stateChanged(We.STATUS_COMPLETED),this.last_response=r,this.J=setTimeout(()=>{this.timer_J()},dn.TIMER_J),this.transport.send(r)?l&&l():(this.onTransportError(),u&&u());break;case We.STATUS_COMPLETED:break}}}class jw extends to{constructor(t,r,l){super(),this.type=We.INVITE_SERVER,this.id=l.via_branch,this.ua=t,this.transport=r,this.request=l,this.last_response="",l.server_transaction=this,this.state=We.STATUS_PROCEEDING,t.newTransaction(this),this.resendProvisionalTimer=null,l.reply(100)}get C(){return We}stateChanged(t){this.state=t,this.emit("stateChanged")}timer_H(){Eu.debug(`Timer H expired for transaction ${this.id}`),this.state===We.STATUS_COMPLETED&&Eu.debug("ACK not received, dialog will be terminated"),this.stateChanged(We.STATUS_TERMINATED),this.ua.destroyTransaction(this)}timer_I(){this.stateChanged(We.STATUS_TERMINATED),this.ua.destroyTransaction(this)}timer_L(){Eu.debug(`Timer L expired for transaction ${this.id}`),this.state===We.STATUS_ACCEPTED&&(this.stateChanged(We.STATUS_TERMINATED),this.ua.destroyTransaction(this))}onTransportError(){this.transportError||(this.transportError=!0,Eu.debug(`transport error occurred, deleting transaction ${this.id}`),this.resendProvisionalTimer!==null&&(clearInterval(this.resendProvisionalTimer),this.resendProvisionalTimer=null),clearTimeout(this.L),clearTimeout(this.H),clearTimeout(this.I),this.stateChanged(We.STATUS_TERMINATED),this.ua.destroyTransaction(this))}resend_provisional(){this.transport.send(this.last_response)||this.onTransportError()}receiveResponse(t,r,l,u){if(t>=100&&t<=199)switch(this.state){case We.STATUS_PROCEEDING:this.transport.send(r)||this.onTransportError(),this.last_response=r;break}if(t>100&&t<=199&&this.state===We.STATUS_PROCEEDING)this.resendProvisionalTimer===null&&(this.resendProvisionalTimer=setInterval(()=>{this.resend_provisional()},dn.PROVISIONAL_RESPONSE_INTERVAL));else if(t>=200&&t<=299)switch(this.state){case We.STATUS_PROCEEDING:this.stateChanged(We.STATUS_ACCEPTED),this.last_response=r,this.L=setTimeout(()=>{this.timer_L()},dn.TIMER_L),this.resendProvisionalTimer!==null&&(clearInterval(this.resendProvisionalTimer),this.resendProvisionalTimer=null);case We.STATUS_ACCEPTED:this.transport.send(r)?l&&l():(this.onTransportError(),u&&u());break}else if(t>=300&&t<=699)switch(this.state){case We.STATUS_PROCEEDING:this.resendProvisionalTimer!==null&&(clearInterval(this.resendProvisionalTimer),this.resendProvisionalTimer=null),this.transport.send(r)?(this.stateChanged(We.STATUS_COMPLETED),this.H=setTimeout(()=>{this.timer_H()},dn.TIMER_H),l&&l()):(this.onTransportError(),u&&u());break}}}function Gw({_transactions:f},t){let r;switch(t.method){case ro.INVITE:if(r=f.ist[t.via_branch],r){switch(r.state){case We.STATUS_PROCEEDING:r.transport.send(r.last_response);break;case We.STATUS_ACCEPTED:break}return!0}break;case ro.ACK:if(r=f.ist[t.via_branch],r){if(r.state===We.STATUS_ACCEPTED)return!1;if(r.state===We.STATUS_COMPLETED)return r.state=We.STATUS_CONFIRMED,r.I=setTimeout(()=>{r.timer_I()},dn.TIMER_I),!0}else return!1;break;case ro.CANCEL:return r=f.ist[t.via_branch],r?(t.reply_sl(200),r.state!==We.STATUS_PROCEEDING):(t.reply_sl(481),!0);default:if(r=f.nist[t.via_branch],r){switch(r.state){case We.STATUS_TRYING:break;case We.STATUS_PROCEEDING:case We.STATUS_COMPLETED:r.transport.send(r.last_response);break}return!0}break}}var hl={C:We,NonInviteClientTransaction:Bw,InviteClientTransaction:zw,AckClientTransaction:Vw,NonInviteServerTransaction:qw,InviteServerTransaction:jw,checkTransaction:Gw};const Er=Ht(hl),Ww=gs,O_=Et,Kw=A_,id=hl,Yw=new Ww("RequestSender"),ad={onRequestTimeout:()=>{},onTransportError:()=>{},onReceiveResponse:()=>{},onAuthenticated:()=>{}};var _l=class{constructor(t,r,l){this._ua=t,this._eventHandlers=l,this._method=r.method,this._request=r,this._auth=null,this._challenged=!1,this._staled=!1;for(const u in ad)Object.prototype.hasOwnProperty.call(ad,u)&&(this._eventHandlers[u]||(this._eventHandlers[u]=ad[u]));t.status===t.C.STATUS_USER_CLOSED&&(this._method!==O_.BYE||this._method!==O_.ACK)&&this._eventHandlers.onTransportError()}send(){const t={onRequestTimeout:()=>{this._eventHandlers.onRequestTimeout()},onTransportError:()=>{this._eventHandlers.onTransportError()},onReceiveResponse:r=>{this._receiveResponse(r)}};switch(this._method){case"INVITE":this.clientTransaction=new id.InviteClientTransaction(this._ua,this._ua.transport,this._request,t);break;case"ACK":this.clientTransaction=new id.AckClientTransaction(this._ua,this._ua.transport,this._request,t);break;default:this.clientTransaction=new id.NonInviteClientTransaction(this._ua,this._ua.transport,this._request,t)}this._ua._configuration.authorization_jwt&&this._request.setHeader("Authorization",this._ua._configuration.authorization_jwt),this.clientTransaction.send()}_receiveResponse(t){let r,l;const u=t.status_code;if((u===401||u===407)&&(this._ua.configuration.password!==null||this._ua.configuration.ha1!==null)){if(t.status_code===401?(r=t.parseHeader("www-authenticate"),l="authorization"):(r=t.parseHeader("proxy-authenticate"),l="proxy-authorization"),!r){Yw.debug(`${t.status_code} with wrong or missing challenge, cannot authenticate`),this._eventHandlers.onReceiveResponse(t);return}if(!this._challenged||!this._staled&&r.stale===!0){if(this._auth||(this._auth=new Kw({username:this._ua.configuration.authorization_user,password:this._ua.configuration.password,realm:this._ua.configuration.realm,ha1:this._ua.configuration.ha1})),!this._auth.authenticate(this._request,r)){this._eventHandlers.onReceiveResponse(t);return}this._challenged=!0,this._ua.set("realm",this._auth.get("realm")),this._ua.set("ha1",this._auth.get("ha1")),r.stale&&(this._staled=!0),this._request=this._request.clone(),this._request.cseq+=1,this._request.setHeader("cseq",`${this._request.cseq} ${this._method}`),this._request.setHeader(l,this._auth.toString()),this._eventHandlers.onAuthenticated(this._request),this.send()}else this._eventHandlers.onReceiveResponse(t)}else this._eventHandlers.onReceiveResponse(t)}};const no=Ht(_l),Jw=gs,ld=xs(),wa=Et,D_=Ds,k_=_l,io=new Jw("Registrator"),Cu=10;var Qw=class{constructor(t,r){this._reg_id=1,this._ua=t,this._transport=r,this._registrar=t.configuration.registrar_server,this._expires=t.configuration.register_expires,this._call_id=ld.createRandomToken(22),this._cseq=0,this._to_uri=t.configuration.uri,this._registrationTimer=null,this._registering=!1,this._registered=!1,this._contact=this._ua.contact.toString(),this._contact+=";+sip.ice",this._extraHeaders=[],this._extraContactParams="",this._sipInstance=`"<urn:uuid:${this._ua.configuration.instance_id}>"`,this._contact+=`;reg-id=${this._reg_id}`,this._contact+=`;+sip.instance=${this._sipInstance}`}get registered(){return this._registered}setExtraHeaders(t){Array.isArray(t)||(t=[]),this._extraHeaders=t.slice()}setExtraContactParams(t){t instanceof Object||(t={}),this._extraContactParams="";for(const r in t)if(Object.prototype.hasOwnProperty.call(t,r)){const l=t[r];this._extraContactParams+=`;${r}`,l&&(this._extraContactParams+=`=${l}`)}}register(){if(this._registering){io.debug("Register request in progress...");return}const t=this._extraHeaders.slice();t.push(`Contact: ${this._contact};expires=${this._expires}${this._extraContactParams}`),t.push(`Expires: ${this._expires}`);const r=new D_.OutgoingRequest(wa.REGISTER,this._registrar,this._ua,{to_uri:this._to_uri,call_id:this._call_id,cseq:this._cseq+=1},t),l=new k_(this._ua,r,{onRequestTimeout:()=>{this._registrationFailure(null,wa.causes.REQUEST_TIMEOUT)},onTransportError:()=>{this._registrationFailure(null,wa.causes.CONNECTION_ERROR)},onAuthenticated:()=>{this._cseq+=1},onReceiveResponse:u=>{if(u.cseq===this._cseq)switch(this._registrationTimer!==null&&(clearTimeout(this._registrationTimer),this._registrationTimer=null),!0){case/^1[0-9]{2}$/.test(u.status_code):break;case/^2[0-9]{2}$/.test(u.status_code):{if(this._registering=!1,!u.hasHeader("Contact")){io.debug("no Contact header in response to REGISTER, response ignored");break}const s=u.headers.Contact.reduce((v,C)=>v.concat(C.parsed),[]);let n=s.find(v=>this._sipInstance===v.getParam("+sip.instance")&&this._reg_id===parseInt(v.getParam("reg-id")));if(n||(n=s.find(v=>v.uri.user===this._ua.contact.uri.user)),!n){io.debug("no Contact header pointing to us, response ignored");break}let g=n.getParam("expires");!g&&u.hasHeader("expires")&&(g=u.getHeader("expires")),g||(g=this._expires),g=Number(g),g<Cu&&(g=Cu);const _=g>64?g*1e3/2+Math.floor((g/2-32)*1e3*Math.random()):g*1e3-5e3;this._registrationTimer=setTimeout(()=>{this._registrationTimer=null,this._ua.listeners("registrationExpiring").length===0?this.register():this._ua.emit("registrationExpiring")},_),n.hasParam("temp-gruu")&&(this._ua.contact.temp_gruu=n.getParam("temp-gruu").replace(/"/g,"")),n.hasParam("pub-gruu")&&(this._ua.contact.pub_gruu=n.getParam("pub-gruu").replace(/"/g,"")),this._registered||(this._registered=!0,this._ua.registered({response:u}));break}case/^423$/.test(u.status_code):{u.hasHeader("min-expires")?(this._expires=Number(u.getHeader("min-expires")),this._expires<Cu&&(this._expires=Cu),this.register()):(io.debug("423 response received for REGISTER without Min-Expires"),this._registrationFailure(u,wa.causes.SIP_FAILURE_CODE));break}default:{const s=ld.sipErrorCause(u.status_code);this._registrationFailure(u,s)}}}});this._registering=!0,l.send()}unregister(t={}){if(!this._registered){io.debug("already unregistered");return}this._registered=!1,this._registrationTimer!==null&&(clearTimeout(this._registrationTimer),this._registrationTimer=null);const r=this._extraHeaders.slice();t.all?r.push(`Contact: *${this._extraContactParams}`):r.push(`Contact: ${this._contact};expires=0${this._extraContactParams}`),r.push("Expires: 0");const l=new D_.OutgoingRequest(wa.REGISTER,this._registrar,this._ua,{to_uri:this._to_uri,call_id:this._call_id,cseq:this._cseq+=1},r);new k_(this._ua,l,{onRequestTimeout:()=>{this._unregistered(null,wa.causes.REQUEST_TIMEOUT)},onTransportError:()=>{this._unregistered(null,wa.causes.CONNECTION_ERROR)},onAuthenticated:()=>{this._cseq+=1},onReceiveResponse:s=>{switch(!0){case/^1[0-9]{2}$/.test(s.status_code):break;case/^2[0-9]{2}$/.test(s.status_code):this._unregistered(s);break;default:{const n=ld.sipErrorCause(s.status_code);this._unregistered(s,n)}}}}).send()}close(){this._registered&&this.unregister()}onTransportClosed(){this._registering=!1,this._registrationTimer!==null&&(clearTimeout(this._registrationTimer),this._registrationTimer=null),this._registered&&(this._registered=!1,this._ua.unregistered({}))}_registrationFailure(t,r){this._registering=!1,this._ua.registrationFailed({response:t||null,cause:r}),this._registered&&(this._registered=!1,this._ua.unregistered({response:t||null,cause:r}))}_unregistered(t,r){this._registering=!1,this._registered=!1,this._ua.unregistered({response:t||null,cause:r||null})}};class Xw extends Error{constructor(t,r){super(),this.code=1,this.name="CONFIGURATION_ERROR",this.parameter=t,this.value=r,this.message=this.value?`Invalid value ${JSON.stringify(this.value)} for parameter "${this.parameter}"`:`Missing parameter: ${this.parameter}`}}class Zw extends Error{constructor(t){super(),this.code=2,this.name="INVALID_STATE_ERROR",this.status=t,this.message=`Invalid status: ${t}`}}class eE extends Error{constructor(t){super(),this.code=3,this.name="NOT_SUPPORTED_ERROR",this.message=t}}class tE extends Error{constructor(t){super(),this.code=4,this.name="NOT_READY_ERROR",this.message=t}}var Pn={ConfigurationError:Xw,InvalidStateError:Zw,NotSupportedError:eE,NotReadyError:tE};const Ei=Ht(Pn),od=Et,Au=hl,sE=_l,ud={onRequestTimeout:()=>{},onTransportError:()=>{},onSuccessResponse:()=>{},onErrorResponse:()=>{},onAuthenticated:()=>{},onDialogError:()=>{}};var N_=class{constructor(t,r,l){this._dialog=t,this._ua=t._ua,this._request=r,this._eventHandlers=l,this._reattempt=!1,this._reattemptTimer=null;for(const u in ud)Object.prototype.hasOwnProperty.call(ud,u)&&(this._eventHandlers[u]||(this._eventHandlers[u]=ud[u]))}get request(){return this._request}send(){const t=new sE(this._ua,this._request,{onRequestTimeout:()=>{this._eventHandlers.onRequestTimeout()},onTransportError:()=>{this._eventHandlers.onTransportError()},onAuthenticated:r=>{this._eventHandlers.onAuthenticated(r)},onReceiveResponse:r=>{this._receiveResponse(r)}});if(t.send(),(this._request.method===od.INVITE||this._request.method===od.UPDATE&&this._request.body)&&t.clientTransaction.state!==Au.C.STATUS_TERMINATED){this._dialog.uac_pending_reply=!0;const r=()=>{(t.clientTransaction.state===Au.C.STATUS_ACCEPTED||t.clientTransaction.state===Au.C.STATUS_COMPLETED||t.clientTransaction.state===Au.C.STATUS_TERMINATED)&&(t.clientTransaction.removeListener("stateChanged",r),this._dialog.uac_pending_reply=!1)};t.clientTransaction.on("stateChanged",r)}}_receiveResponse(t){t.status_code===408||t.status_code===481?this._eventHandlers.onDialogError(t):t.method===od.INVITE&&t.status_code===491?this._reattempt?t.status_code>=200&&t.status_code<300?this._eventHandlers.onSuccessResponse(t):t.status_code>=300&&this._eventHandlers.onErrorResponse(t):(this._request.cseq=this._dialog.local_seqnum+=1,this._reattemptTimer=setTimeout(()=>{this._dialog.isTerminated()||(this._reattempt=!0,this.send())},1e3)):t.status_code>=200&&t.status_code<300?this._eventHandlers.onSuccessResponse(t):t.status_code>=300&&this._eventHandlers.onErrorResponse(t)}};const rE=Ht(N_),nE=gs,M_=Ds,Ci=Et,ao=hl,iE=N_,cd=xs(),dd=new nE("Dialog"),Ai={STATUS_EARLY:1,STATUS_CONFIRMED:2,STATUS_TERMINATED:3};var U_=class{static get C(){return Ai}constructor(t,r,l,u=Ai.STATUS_CONFIRMED){if(this._owner=t,this._ua=t._ua,this._uac_pending_reply=!1,this._uas_pending_reply=!1,!r.hasHeader("contact"))return{error:"unable to create a Dialog without Contact header field"};r instanceof M_.IncomingResponse&&(u=r.status_code<200?Ai.STATUS_EARLY:Ai.STATUS_CONFIRMED);const s=r.parseHeader("contact");l==="UAS"?(this._id={call_id:r.call_id,local_tag:r.to_tag,remote_tag:r.from_tag,toString(){return this.call_id+this.local_tag+this.remote_tag}},this._state=u,this._remote_seqnum=r.cseq,this._local_uri=r.parseHeader("to").uri,this._remote_uri=r.parseHeader("from").uri,this._remote_target=s.uri,this._route_set=r.getHeaders("record-route"),this._ack_seqnum=this._remote_seqnum):l==="UAC"&&(this._id={call_id:r.call_id,local_tag:r.from_tag,remote_tag:r.to_tag,toString(){return this.call_id+this.local_tag+this.remote_tag}},this._state=u,this._local_seqnum=r.cseq,this._local_uri=r.parseHeader("from").uri,this._remote_uri=r.parseHeader("to").uri,this._remote_target=s.uri,this._route_set=r.getHeaders("record-route").reverse(),this._ack_seqnum=null),this._ua.newDialog(this),dd.debug(`new ${l} dialog created with status ${this._state===Ai.STATUS_EARLY?"EARLY":"CONFIRMED"}`)}get id(){return this._id}get local_seqnum(){return this._local_seqnum}set local_seqnum(t){this._local_seqnum=t}get owner(){return this._owner}get uac_pending_reply(){return this._uac_pending_reply}set uac_pending_reply(t){this._uac_pending_reply=t}get uas_pending_reply(){return this._uas_pending_reply}isTerminated(){return this._status===Ai.STATUS_TERMINATED}update(t,r){this._state=Ai.STATUS_CONFIRMED,dd.debug(`dialog ${this._id.toString()} changed to CONFIRMED state`),r==="UAC"&&(this._route_set=t.getHeaders("record-route").reverse())}terminate(){dd.debug(`dialog ${this._id.toString()} deleted`),this._ua.destroyDialog(this),this._state=Ai.STATUS_TERMINATED}sendRequest(t,r={}){const l=cd.cloneArray(r.extraHeaders),u=cd.cloneObject(r.eventHandlers),s=r.body||null,n=this._createRequest(t,l,s);return u.onAuthenticated=()=>{this._local_seqnum+=1},new iE(this,n,u).send(),n}receiveRequest(t){this._checkInDialogRequest(t)&&(t.method===Ci.ACK&&this._ack_seqnum!==null?this._ack_seqnum=null:t.method===Ci.INVITE&&(this._ack_seqnum=t.cseq),this._owner.receiveRequest(t))}_createRequest(t,r,l){r=cd.cloneArray(r),this._local_seqnum||(this._local_seqnum=Math.floor(Math.random()*1e4));const u=t===Ci.CANCEL||t===Ci.ACK?this._local_seqnum:this._local_seqnum+=1;return new M_.OutgoingRequest(t,this._remote_target,this._ua,{cseq:u,call_id:this._id.call_id,from_uri:this._local_uri,from_tag:this._id.local_tag,to_uri:this._remote_uri,to_tag:this._id.remote_tag,route_set:this._route_set},r,l)}_checkInDialogRequest(t){if(!this._remote_seqnum)this._remote_seqnum=t.cseq;else if(t.cseq<this._remote_seqnum)if(t.method===Ci.ACK){if(this._ack_seqnum===null||t.cseq!==this._ack_seqnum)return!1}else return t.reply(500),!1;else t.cseq>this._remote_seqnum&&(this._remote_seqnum=t.cseq);if(t.method===Ci.INVITE||t.method===Ci.UPDATE&&t.body){if(this._uac_pending_reply===!0)t.reply(491);else if(this._uas_pending_reply===!0){const r=(Math.random()*10|0)+1;return t.reply(500,null,[`Retry-After:${r}`]),!1}else{this._uas_pending_reply=!0;const r=()=>{(t.server_transaction.state===ao.C.STATUS_ACCEPTED||t.server_transaction.state===ao.C.STATUS_COMPLETED||t.server_transaction.state===ao.C.STATUS_TERMINATED)&&(t.server_transaction.removeListener("stateChanged",r),this._uas_pending_reply=!1)};t.server_transaction.on("stateChanged",r)}t.hasHeader("contact")&&t.server_transaction.on("stateChanged",()=>{t.server_transaction.state===ao.C.STATUS_ACCEPTED&&(this._remote_target=t.parseHeader("contact").uri)})}else t.method===Ci.NOTIFY&&t.hasHeader("contact")&&t.server_transaction.on("stateChanged",()=>{t.server_transaction.state===ao.C.STATUS_COMPLETED&&(this._remote_target=t.parseHeader("contact").uri)});return!0}};const Iu=Ht(U_);var fd={exports:{}};const aE=ys.EventEmitter,lE=gs,oE=Et,uE=Pn,P_=xs(),cE=new lE("RTCSession:DTMF"),L_={MIN_DURATION:70,MAX_DURATION:6e3,DEFAULT_DURATION:100,MIN_INTER_TONE_GAP:50,DEFAULT_INTER_TONE_GAP:500};fd.exports=class extends aE{constructor(t){super(),this._session=t,this._direction=null,this._tone=null,this._duration=null,this._request=null}get tone(){return this._tone}get duration(){return this._duration}send(t,r={}){if(t===void 0)throw new TypeError("Not enough arguments");if(this._direction="outgoing",this._session.status!==this._session.C.STATUS_CONFIRMED&&this._session.status!==this._session.C.STATUS_WAITING_FOR_ACK)throw new uE.InvalidStateError(this._session.status);const l=P_.cloneArray(r.extraHeaders);if(this.eventHandlers=P_.cloneObject(r.eventHandlers),typeof t=="string")t=t.toUpperCase();else if(typeof t=="number")t=t.toString();else throw new TypeError(`Invalid tone: ${t}`);if(t.match(/^[0-9A-DR#*]$/))this._tone=t;else throw new TypeError(`Invalid tone: ${t}`);this._duration=r.duration,l.push("Content-Type: application/dtmf-relay");let u=`Signal=${this._tone}\r
112
+ `,this.transport.send(u)}}class Uw extends E_{constructor(){super(),this.headers={},this.status_code=null,this.reason_phrase=null}}var Ds={OutgoingRequest:bu,InitialOutgoingInviteRequest:rd,IncomingRequest:Mw,IncomingResponse:Uw};const fl=Ht(Ds),Pw=gs,Mn=xs(),kr=new Pw("DigestAuthentication");var C_=class{constructor(t){this._credentials=t,this._cnonce=null,this._nc=0,this._ncHex="00000000",this._algorithm=null,this._realm=null,this._nonce=null,this._opaque=null,this._stale=null,this._qop=null,this._method=null,this._uri=null,this._ha1=null,this._response=null}get(t){switch(t){case"realm":return this._realm;case"ha1":return this._ha1;default:kr.warn('get() | cannot get "%s" parameter',t);return}}authenticate({method:t,ruri:r,body:l},u,s=null){if(this._algorithm=u.algorithm,this._realm=u.realm,this._nonce=u.nonce,this._opaque=u.opaque,this._stale=u.stale,this._algorithm){if(this._algorithm!=="MD5")return kr.warn('authenticate() | challenge with Digest algorithm different than "MD5", authentication aborted'),!1}else this._algorithm="MD5";if(!this._nonce)return kr.warn("authenticate() | challenge without Digest nonce, authentication aborted"),!1;if(!this._realm)return kr.warn("authenticate() | challenge without Digest realm, authentication aborted"),!1;if(!this._credentials.password){if(!this._credentials.ha1)return kr.warn("authenticate() | no plain SIP password nor ha1 provided, authentication aborted"),!1;if(this._credentials.realm!==this._realm)return kr.warn('authenticate() | no plain SIP password, and stored `realm` does not match the given `realm`, cannot authenticate [stored:"%s", given:"%s"]',this._credentials.realm,this._realm),!1}if(u.qop)if(u.qop.indexOf("auth-int")>-1)this._qop="auth-int";else if(u.qop.indexOf("auth")>-1)this._qop="auth";else return kr.warn('authenticate() | challenge without Digest qop different than "auth" or "auth-int", authentication aborted'),!1;else this._qop=null;this._method=t,this._uri=r,this._cnonce=s||Mn.createRandomToken(12),this._nc+=1;const n=Number(this._nc).toString(16);this._ncHex="00000000".substr(0,8-n.length)+n,this._nc===4294967296&&(this._nc=1,this._ncHex="00000001"),this._credentials.password?this._ha1=Mn.calculateMD5(`${this._credentials.username}:${this._realm}:${this._credentials.password}`):this._ha1=this._credentials.ha1;let g,_;return this._qop==="auth"?(g=`${this._method}:${this._uri}`,_=Mn.calculateMD5(g),kr.debug('authenticate() | using qop=auth [a2:"%s"]',g),this._response=Mn.calculateMD5(`${this._ha1}:${this._nonce}:${this._ncHex}:${this._cnonce}:auth:${_}`)):this._qop==="auth-int"?(g=`${this._method}:${this._uri}:${Mn.calculateMD5(l||"")}`,_=Mn.calculateMD5(g),kr.debug('authenticate() | using qop=auth-int [a2:"%s"]',g),this._response=Mn.calculateMD5(`${this._ha1}:${this._nonce}:${this._ncHex}:${this._cnonce}:auth-int:${_}`)):this._qop===null&&(g=`${this._method}:${this._uri}`,_=Mn.calculateMD5(g),kr.debug('authenticate() | using qop=null [a2:"%s"]',g),this._response=Mn.calculateMD5(`${this._ha1}:${this._nonce}:${_}`)),kr.debug("authenticate() | response generated"),!0}toString(){const t=[];if(!this._response)throw new Error("response field does not exist, cannot generate Authorization header");return t.push(`algorithm=${this._algorithm}`),t.push(`username="${this._credentials.username}"`),t.push(`realm="${this._realm}"`),t.push(`nonce="${this._nonce}"`),t.push(`uri="${this._uri}"`),t.push(`response="${this._response}"`),this._opaque&&t.push(`opaque="${this._opaque}"`),this._qop&&(t.push(`qop=${this._qop}`),t.push(`cnonce="${this._cnonce}"`),t.push(`nc=${this._ncHex}`)),`Digest ${t.join(", ")}`}};const Lw=Ht(C_),Un=500,Hw=4e3,A_=5e3;var nd={T1:Un,T2:Hw,T4:A_,TIMER_B:64*Un,TIMER_D:0*Un,TIMER_F:64*Un,TIMER_H:64*Un,TIMER_I:0*Un,TIMER_J:0*Un,TIMER_K:0*A_,TIMER_L:64*Un,TIMER_M:64*Un,PROVISIONAL_RESPONSE_INTERVAL:6e4};const eo=Ht(nd),to=ys.EventEmitter,so=gs,ro=Et,I_=Ds,dn=nd,R_=new so("NonInviteClientTransaction"),wu=new so("InviteClientTransaction"),Fw=new so("AckClientTransaction"),$_=new so("NonInviteServerTransaction"),Eu=new so("InviteServerTransaction"),We={STATUS_TRYING:1,STATUS_PROCEEDING:2,STATUS_CALLING:3,STATUS_ACCEPTED:4,STATUS_COMPLETED:5,STATUS_TERMINATED:6,STATUS_CONFIRMED:7,NON_INVITE_CLIENT:"nict",NON_INVITE_SERVER:"nist",INVITE_CLIENT:"ict",INVITE_SERVER:"ist"};class Bw extends to{constructor(t,r,l,u){super(),this.type=We.NON_INVITE_CLIENT,this.id=`z9hG4bK${Math.floor(Math.random()*1e7)}`,this.ua=t,this.transport=r,this.request=l,this.eventHandlers=u;let s=`SIP/2.0/${r.via_transport}`;s+=` ${t.configuration.via_host};branch=${this.id}`,this.request.setHeader("via",s),this.ua.newTransaction(this)}get C(){return We}stateChanged(t){this.state=t,this.emit("stateChanged")}send(){this.stateChanged(We.STATUS_TRYING),this.F=setTimeout(()=>{this.timer_F()},dn.TIMER_F),this.transport.send(this.request)||this.onTransportError()}onTransportError(){R_.debug(`transport error occurred, deleting transaction ${this.id}`),clearTimeout(this.F),clearTimeout(this.K),this.stateChanged(We.STATUS_TERMINATED),this.ua.destroyTransaction(this),this.eventHandlers.onTransportError()}timer_F(){R_.debug(`Timer F expired for transaction ${this.id}`),this.stateChanged(We.STATUS_TERMINATED),this.ua.destroyTransaction(this),this.eventHandlers.onRequestTimeout()}timer_K(){this.stateChanged(We.STATUS_TERMINATED),this.ua.destroyTransaction(this)}receiveResponse(t){const r=t.status_code;if(r<200)switch(this.state){case We.STATUS_TRYING:case We.STATUS_PROCEEDING:this.stateChanged(We.STATUS_PROCEEDING),this.eventHandlers.onReceiveResponse(t);break}else switch(this.state){case We.STATUS_TRYING:case We.STATUS_PROCEEDING:this.stateChanged(We.STATUS_COMPLETED),clearTimeout(this.F),r===408?this.eventHandlers.onRequestTimeout():this.eventHandlers.onReceiveResponse(t),this.K=setTimeout(()=>{this.timer_K()},dn.TIMER_K);break;case We.STATUS_COMPLETED:break}}}class zw extends to{constructor(t,r,l,u){super(),this.type=We.INVITE_CLIENT,this.id=`z9hG4bK${Math.floor(Math.random()*1e7)}`,this.ua=t,this.transport=r,this.request=l,this.eventHandlers=u,l.transaction=this;let s=`SIP/2.0/${r.via_transport}`;s+=` ${t.configuration.via_host};branch=${this.id}`,this.request.setHeader("via",s),this.ua.newTransaction(this)}get C(){return We}stateChanged(t){this.state=t,this.emit("stateChanged")}send(){this.stateChanged(We.STATUS_CALLING),this.B=setTimeout(()=>{this.timer_B()},dn.TIMER_B),this.transport.send(this.request)||this.onTransportError()}onTransportError(){clearTimeout(this.B),clearTimeout(this.D),clearTimeout(this.M),this.state!==We.STATUS_ACCEPTED&&(wu.debug(`transport error occurred, deleting transaction ${this.id}`),this.eventHandlers.onTransportError()),this.stateChanged(We.STATUS_TERMINATED),this.ua.destroyTransaction(this)}timer_M(){wu.debug(`Timer M expired for transaction ${this.id}`),this.state===We.STATUS_ACCEPTED&&(clearTimeout(this.B),this.stateChanged(We.STATUS_TERMINATED),this.ua.destroyTransaction(this))}timer_B(){wu.debug(`Timer B expired for transaction ${this.id}`),this.state===We.STATUS_CALLING&&(this.stateChanged(We.STATUS_TERMINATED),this.ua.destroyTransaction(this),this.eventHandlers.onRequestTimeout())}timer_D(){wu.debug(`Timer D expired for transaction ${this.id}`),clearTimeout(this.B),this.stateChanged(We.STATUS_TERMINATED),this.ua.destroyTransaction(this)}sendACK(t){const r=new I_.OutgoingRequest(ro.ACK,this.request.ruri,this.ua,{route_set:this.request.getHeaders("route"),call_id:this.request.getHeader("call-id"),cseq:this.request.cseq});r.setHeader("from",this.request.getHeader("from")),r.setHeader("via",this.request.getHeader("via")),r.setHeader("to",t.getHeader("to")),this.D=setTimeout(()=>{this.timer_D()},dn.TIMER_D),this.transport.send(r)}cancel(t){if(this.state!==We.STATUS_PROCEEDING)return;const r=new I_.OutgoingRequest(ro.CANCEL,this.request.ruri,this.ua,{route_set:this.request.getHeaders("route"),call_id:this.request.getHeader("call-id"),cseq:this.request.cseq});r.setHeader("from",this.request.getHeader("from")),r.setHeader("via",this.request.getHeader("via")),r.setHeader("to",this.request.getHeader("to")),t&&r.setHeader("reason",t),this.transport.send(r)}receiveResponse(t){const r=t.status_code;if(r>=100&&r<=199)switch(this.state){case We.STATUS_CALLING:this.stateChanged(We.STATUS_PROCEEDING),this.eventHandlers.onReceiveResponse(t);break;case We.STATUS_PROCEEDING:this.eventHandlers.onReceiveResponse(t);break}else if(r>=200&&r<=299)switch(this.state){case We.STATUS_CALLING:case We.STATUS_PROCEEDING:this.stateChanged(We.STATUS_ACCEPTED),this.M=setTimeout(()=>{this.timer_M()},dn.TIMER_M),this.eventHandlers.onReceiveResponse(t);break;case We.STATUS_ACCEPTED:this.eventHandlers.onReceiveResponse(t);break}else if(r>=300&&r<=699)switch(this.state){case We.STATUS_CALLING:case We.STATUS_PROCEEDING:this.stateChanged(We.STATUS_COMPLETED),this.sendACK(t),this.eventHandlers.onReceiveResponse(t);break;case We.STATUS_COMPLETED:this.sendACK(t);break}}}class Vw extends to{constructor(t,r,l,u){super(),this.id=`z9hG4bK${Math.floor(Math.random()*1e7)}`,this.transport=r,this.request=l,this.eventHandlers=u;let s=`SIP/2.0/${r.via_transport}`;s+=` ${t.configuration.via_host};branch=${this.id}`,this.request.setHeader("via",s)}get C(){return We}send(){this.transport.send(this.request)||this.onTransportError()}onTransportError(){Fw.debug(`transport error occurred for transaction ${this.id}`),this.eventHandlers.onTransportError()}}class qw extends to{constructor(t,r,l){super(),this.type=We.NON_INVITE_SERVER,this.id=l.via_branch,this.ua=t,this.transport=r,this.request=l,this.last_response="",l.server_transaction=this,this.state=We.STATUS_TRYING,t.newTransaction(this)}get C(){return We}stateChanged(t){this.state=t,this.emit("stateChanged")}timer_J(){$_.debug(`Timer J expired for transaction ${this.id}`),this.stateChanged(We.STATUS_TERMINATED),this.ua.destroyTransaction(this)}onTransportError(){this.transportError||(this.transportError=!0,$_.debug(`transport error occurred, deleting transaction ${this.id}`),clearTimeout(this.J),this.stateChanged(We.STATUS_TERMINATED),this.ua.destroyTransaction(this))}receiveResponse(t,r,l,u){if(t===100)switch(this.state){case We.STATUS_TRYING:this.stateChanged(We.STATUS_PROCEEDING),this.transport.send(r)||this.onTransportError();break;case We.STATUS_PROCEEDING:this.last_response=r,this.transport.send(r)?l&&l():(this.onTransportError(),u&&u());break}else if(t>=200&&t<=699)switch(this.state){case We.STATUS_TRYING:case We.STATUS_PROCEEDING:this.stateChanged(We.STATUS_COMPLETED),this.last_response=r,this.J=setTimeout(()=>{this.timer_J()},dn.TIMER_J),this.transport.send(r)?l&&l():(this.onTransportError(),u&&u());break;case We.STATUS_COMPLETED:break}}}class jw extends to{constructor(t,r,l){super(),this.type=We.INVITE_SERVER,this.id=l.via_branch,this.ua=t,this.transport=r,this.request=l,this.last_response="",l.server_transaction=this,this.state=We.STATUS_PROCEEDING,t.newTransaction(this),this.resendProvisionalTimer=null,l.reply(100)}get C(){return We}stateChanged(t){this.state=t,this.emit("stateChanged")}timer_H(){Eu.debug(`Timer H expired for transaction ${this.id}`),this.state===We.STATUS_COMPLETED&&Eu.debug("ACK not received, dialog will be terminated"),this.stateChanged(We.STATUS_TERMINATED),this.ua.destroyTransaction(this)}timer_I(){this.stateChanged(We.STATUS_TERMINATED),this.ua.destroyTransaction(this)}timer_L(){Eu.debug(`Timer L expired for transaction ${this.id}`),this.state===We.STATUS_ACCEPTED&&(this.stateChanged(We.STATUS_TERMINATED),this.ua.destroyTransaction(this))}onTransportError(){this.transportError||(this.transportError=!0,Eu.debug(`transport error occurred, deleting transaction ${this.id}`),this.resendProvisionalTimer!==null&&(clearInterval(this.resendProvisionalTimer),this.resendProvisionalTimer=null),clearTimeout(this.L),clearTimeout(this.H),clearTimeout(this.I),this.stateChanged(We.STATUS_TERMINATED),this.ua.destroyTransaction(this))}resend_provisional(){this.transport.send(this.last_response)||this.onTransportError()}receiveResponse(t,r,l,u){if(t>=100&&t<=199)switch(this.state){case We.STATUS_PROCEEDING:this.transport.send(r)||this.onTransportError(),this.last_response=r;break}if(t>100&&t<=199&&this.state===We.STATUS_PROCEEDING)this.resendProvisionalTimer===null&&(this.resendProvisionalTimer=setInterval(()=>{this.resend_provisional()},dn.PROVISIONAL_RESPONSE_INTERVAL));else if(t>=200&&t<=299)switch(this.state){case We.STATUS_PROCEEDING:this.stateChanged(We.STATUS_ACCEPTED),this.last_response=r,this.L=setTimeout(()=>{this.timer_L()},dn.TIMER_L),this.resendProvisionalTimer!==null&&(clearInterval(this.resendProvisionalTimer),this.resendProvisionalTimer=null);case We.STATUS_ACCEPTED:this.transport.send(r)?l&&l():(this.onTransportError(),u&&u());break}else if(t>=300&&t<=699)switch(this.state){case We.STATUS_PROCEEDING:this.resendProvisionalTimer!==null&&(clearInterval(this.resendProvisionalTimer),this.resendProvisionalTimer=null),this.transport.send(r)?(this.stateChanged(We.STATUS_COMPLETED),this.H=setTimeout(()=>{this.timer_H()},dn.TIMER_H),l&&l()):(this.onTransportError(),u&&u());break}}}function Gw({_transactions:f},t){let r;switch(t.method){case ro.INVITE:if(r=f.ist[t.via_branch],r){switch(r.state){case We.STATUS_PROCEEDING:r.transport.send(r.last_response);break;case We.STATUS_ACCEPTED:break}return!0}break;case ro.ACK:if(r=f.ist[t.via_branch],r){if(r.state===We.STATUS_ACCEPTED)return!1;if(r.state===We.STATUS_COMPLETED)return r.state=We.STATUS_CONFIRMED,r.I=setTimeout(()=>{r.timer_I()},dn.TIMER_I),!0}else return!1;break;case ro.CANCEL:return r=f.ist[t.via_branch],r?(t.reply_sl(200),r.state!==We.STATUS_PROCEEDING):(t.reply_sl(481),!0);default:if(r=f.nist[t.via_branch],r){switch(r.state){case We.STATUS_TRYING:break;case We.STATUS_PROCEEDING:case We.STATUS_COMPLETED:r.transport.send(r.last_response);break}return!0}break}}var hl={C:We,NonInviteClientTransaction:Bw,InviteClientTransaction:zw,AckClientTransaction:Vw,NonInviteServerTransaction:qw,InviteServerTransaction:jw,checkTransaction:Gw};const Er=Ht(hl),Ww=gs,x_=Et,Kw=C_,id=hl,Yw=new Ww("RequestSender"),ad={onRequestTimeout:()=>{},onTransportError:()=>{},onReceiveResponse:()=>{},onAuthenticated:()=>{}};var _l=class{constructor(t,r,l){this._ua=t,this._eventHandlers=l,this._method=r.method,this._request=r,this._auth=null,this._challenged=!1,this._staled=!1;for(const u in ad)Object.prototype.hasOwnProperty.call(ad,u)&&(this._eventHandlers[u]||(this._eventHandlers[u]=ad[u]));t.status===t.C.STATUS_USER_CLOSED&&(this._method!==x_.BYE||this._method!==x_.ACK)&&this._eventHandlers.onTransportError()}send(){const t={onRequestTimeout:()=>{this._eventHandlers.onRequestTimeout()},onTransportError:()=>{this._eventHandlers.onTransportError()},onReceiveResponse:r=>{this._receiveResponse(r)}};switch(this._method){case"INVITE":this.clientTransaction=new id.InviteClientTransaction(this._ua,this._ua.transport,this._request,t);break;case"ACK":this.clientTransaction=new id.AckClientTransaction(this._ua,this._ua.transport,this._request,t);break;default:this.clientTransaction=new id.NonInviteClientTransaction(this._ua,this._ua.transport,this._request,t)}this._ua._configuration.authorization_jwt&&this._request.setHeader("Authorization",this._ua._configuration.authorization_jwt),this.clientTransaction.send()}_receiveResponse(t){let r,l;const u=t.status_code;if((u===401||u===407)&&(this._ua.configuration.password!==null||this._ua.configuration.ha1!==null)){if(t.status_code===401?(r=t.parseHeader("www-authenticate"),l="authorization"):(r=t.parseHeader("proxy-authenticate"),l="proxy-authorization"),!r){Yw.debug(`${t.status_code} with wrong or missing challenge, cannot authenticate`),this._eventHandlers.onReceiveResponse(t);return}if(!this._challenged||!this._staled&&r.stale===!0){if(this._auth||(this._auth=new Kw({username:this._ua.configuration.authorization_user,password:this._ua.configuration.password,realm:this._ua.configuration.realm,ha1:this._ua.configuration.ha1})),!this._auth.authenticate(this._request,r)){this._eventHandlers.onReceiveResponse(t);return}this._challenged=!0,this._ua.set("realm",this._auth.get("realm")),this._ua.set("ha1",this._auth.get("ha1")),r.stale&&(this._staled=!0),this._request=this._request.clone(),this._request.cseq+=1,this._request.setHeader("cseq",`${this._request.cseq} ${this._method}`),this._request.setHeader(l,this._auth.toString()),this._eventHandlers.onAuthenticated(this._request),this.send()}else this._eventHandlers.onReceiveResponse(t)}else this._eventHandlers.onReceiveResponse(t)}};const no=Ht(_l),Jw=gs,ld=xs(),wa=Et,O_=Ds,D_=_l,io=new Jw("Registrator"),Cu=10;var Qw=class{constructor(t,r){this._reg_id=1,this._ua=t,this._transport=r,this._registrar=t.configuration.registrar_server,this._expires=t.configuration.register_expires,this._call_id=ld.createRandomToken(22),this._cseq=0,this._to_uri=t.configuration.uri,this._registrationTimer=null,this._registering=!1,this._registered=!1,this._contact=this._ua.contact.toString(),this._contact+=";+sip.ice",this._extraHeaders=[],this._extraContactParams="",this._sipInstance=`"<urn:uuid:${this._ua.configuration.instance_id}>"`,this._contact+=`;reg-id=${this._reg_id}`,this._contact+=`;+sip.instance=${this._sipInstance}`}get registered(){return this._registered}setExtraHeaders(t){Array.isArray(t)||(t=[]),this._extraHeaders=t.slice()}setExtraContactParams(t){t instanceof Object||(t={}),this._extraContactParams="";for(const r in t)if(Object.prototype.hasOwnProperty.call(t,r)){const l=t[r];this._extraContactParams+=`;${r}`,l&&(this._extraContactParams+=`=${l}`)}}register(){if(this._registering){io.debug("Register request in progress...");return}const t=this._extraHeaders.slice();t.push(`Contact: ${this._contact};expires=${this._expires}${this._extraContactParams}`),t.push(`Expires: ${this._expires}`);const r=new O_.OutgoingRequest(wa.REGISTER,this._registrar,this._ua,{to_uri:this._to_uri,call_id:this._call_id,cseq:this._cseq+=1},t),l=new D_(this._ua,r,{onRequestTimeout:()=>{this._registrationFailure(null,wa.causes.REQUEST_TIMEOUT)},onTransportError:()=>{this._registrationFailure(null,wa.causes.CONNECTION_ERROR)},onAuthenticated:()=>{this._cseq+=1},onReceiveResponse:u=>{if(u.cseq===this._cseq)switch(this._registrationTimer!==null&&(clearTimeout(this._registrationTimer),this._registrationTimer=null),!0){case/^1[0-9]{2}$/.test(u.status_code):break;case/^2[0-9]{2}$/.test(u.status_code):{if(this._registering=!1,!u.hasHeader("Contact")){io.debug("no Contact header in response to REGISTER, response ignored");break}const s=u.headers.Contact.reduce((v,C)=>v.concat(C.parsed),[]);let n=s.find(v=>this._sipInstance===v.getParam("+sip.instance")&&this._reg_id===parseInt(v.getParam("reg-id")));if(n||(n=s.find(v=>v.uri.user===this._ua.contact.uri.user)),!n){io.debug("no Contact header pointing to us, response ignored");break}let g=n.getParam("expires");!g&&u.hasHeader("expires")&&(g=u.getHeader("expires")),g||(g=this._expires),g=Number(g),g<Cu&&(g=Cu);const _=g>64?g*1e3/2+Math.floor((g/2-32)*1e3*Math.random()):g*1e3-5e3;this._registrationTimer=setTimeout(()=>{this._registrationTimer=null,this._ua.listeners("registrationExpiring").length===0?this.register():this._ua.emit("registrationExpiring")},_),n.hasParam("temp-gruu")&&(this._ua.contact.temp_gruu=n.getParam("temp-gruu").replace(/"/g,"")),n.hasParam("pub-gruu")&&(this._ua.contact.pub_gruu=n.getParam("pub-gruu").replace(/"/g,"")),this._registered||(this._registered=!0,this._ua.registered({response:u}));break}case/^423$/.test(u.status_code):{u.hasHeader("min-expires")?(this._expires=Number(u.getHeader("min-expires")),this._expires<Cu&&(this._expires=Cu),this.register()):(io.debug("423 response received for REGISTER without Min-Expires"),this._registrationFailure(u,wa.causes.SIP_FAILURE_CODE));break}default:{const s=ld.sipErrorCause(u.status_code);this._registrationFailure(u,s)}}}});this._registering=!0,l.send()}unregister(t={}){if(!this._registered){io.debug("already unregistered");return}this._registered=!1,this._registrationTimer!==null&&(clearTimeout(this._registrationTimer),this._registrationTimer=null);const r=this._extraHeaders.slice();t.all?r.push(`Contact: *${this._extraContactParams}`):r.push(`Contact: ${this._contact};expires=0${this._extraContactParams}`),r.push("Expires: 0");const l=new O_.OutgoingRequest(wa.REGISTER,this._registrar,this._ua,{to_uri:this._to_uri,call_id:this._call_id,cseq:this._cseq+=1},r);new D_(this._ua,l,{onRequestTimeout:()=>{this._unregistered(null,wa.causes.REQUEST_TIMEOUT)},onTransportError:()=>{this._unregistered(null,wa.causes.CONNECTION_ERROR)},onAuthenticated:()=>{this._cseq+=1},onReceiveResponse:s=>{switch(!0){case/^1[0-9]{2}$/.test(s.status_code):break;case/^2[0-9]{2}$/.test(s.status_code):this._unregistered(s);break;default:{const n=ld.sipErrorCause(s.status_code);this._unregistered(s,n)}}}}).send()}close(){this._registered&&this.unregister()}onTransportClosed(){this._registering=!1,this._registrationTimer!==null&&(clearTimeout(this._registrationTimer),this._registrationTimer=null),this._registered&&(this._registered=!1,this._ua.unregistered({}))}_registrationFailure(t,r){this._registering=!1,this._ua.registrationFailed({response:t||null,cause:r}),this._registered&&(this._registered=!1,this._ua.unregistered({response:t||null,cause:r}))}_unregistered(t,r){this._registering=!1,this._registered=!1,this._ua.unregistered({response:t||null,cause:r||null})}};class Xw extends Error{constructor(t,r){super(),this.code=1,this.name="CONFIGURATION_ERROR",this.parameter=t,this.value=r,this.message=this.value?`Invalid value ${JSON.stringify(this.value)} for parameter "${this.parameter}"`:`Missing parameter: ${this.parameter}`}}class Zw extends Error{constructor(t){super(),this.code=2,this.name="INVALID_STATE_ERROR",this.status=t,this.message=`Invalid status: ${t}`}}class eE extends Error{constructor(t){super(),this.code=3,this.name="NOT_SUPPORTED_ERROR",this.message=t}}class tE extends Error{constructor(t){super(),this.code=4,this.name="NOT_READY_ERROR",this.message=t}}var Pn={ConfigurationError:Xw,InvalidStateError:Zw,NotSupportedError:eE,NotReadyError:tE};const Ei=Ht(Pn),od=Et,Au=hl,sE=_l,ud={onRequestTimeout:()=>{},onTransportError:()=>{},onSuccessResponse:()=>{},onErrorResponse:()=>{},onAuthenticated:()=>{},onDialogError:()=>{}};var k_=class{constructor(t,r,l){this._dialog=t,this._ua=t._ua,this._request=r,this._eventHandlers=l,this._reattempt=!1,this._reattemptTimer=null;for(const u in ud)Object.prototype.hasOwnProperty.call(ud,u)&&(this._eventHandlers[u]||(this._eventHandlers[u]=ud[u]))}get request(){return this._request}send(){const t=new sE(this._ua,this._request,{onRequestTimeout:()=>{this._eventHandlers.onRequestTimeout()},onTransportError:()=>{this._eventHandlers.onTransportError()},onAuthenticated:r=>{this._eventHandlers.onAuthenticated(r)},onReceiveResponse:r=>{this._receiveResponse(r)}});if(t.send(),(this._request.method===od.INVITE||this._request.method===od.UPDATE&&this._request.body)&&t.clientTransaction.state!==Au.C.STATUS_TERMINATED){this._dialog.uac_pending_reply=!0;const r=()=>{(t.clientTransaction.state===Au.C.STATUS_ACCEPTED||t.clientTransaction.state===Au.C.STATUS_COMPLETED||t.clientTransaction.state===Au.C.STATUS_TERMINATED)&&(t.clientTransaction.removeListener("stateChanged",r),this._dialog.uac_pending_reply=!1)};t.clientTransaction.on("stateChanged",r)}}_receiveResponse(t){t.status_code===408||t.status_code===481?this._eventHandlers.onDialogError(t):t.method===od.INVITE&&t.status_code===491?this._reattempt?t.status_code>=200&&t.status_code<300?this._eventHandlers.onSuccessResponse(t):t.status_code>=300&&this._eventHandlers.onErrorResponse(t):(this._request.cseq=this._dialog.local_seqnum+=1,this._reattemptTimer=setTimeout(()=>{this._dialog.isTerminated()||(this._reattempt=!0,this.send())},1e3)):t.status_code>=200&&t.status_code<300?this._eventHandlers.onSuccessResponse(t):t.status_code>=300&&this._eventHandlers.onErrorResponse(t)}};const rE=Ht(k_),nE=gs,N_=Ds,Ci=Et,ao=hl,iE=k_,cd=xs(),dd=new nE("Dialog"),Ai={STATUS_EARLY:1,STATUS_CONFIRMED:2,STATUS_TERMINATED:3};var M_=class{static get C(){return Ai}constructor(t,r,l,u=Ai.STATUS_CONFIRMED){if(this._owner=t,this._ua=t._ua,this._uac_pending_reply=!1,this._uas_pending_reply=!1,!r.hasHeader("contact"))return{error:"unable to create a Dialog without Contact header field"};r instanceof N_.IncomingResponse&&(u=r.status_code<200?Ai.STATUS_EARLY:Ai.STATUS_CONFIRMED);const s=r.parseHeader("contact");l==="UAS"?(this._id={call_id:r.call_id,local_tag:r.to_tag,remote_tag:r.from_tag,toString(){return this.call_id+this.local_tag+this.remote_tag}},this._state=u,this._remote_seqnum=r.cseq,this._local_uri=r.parseHeader("to").uri,this._remote_uri=r.parseHeader("from").uri,this._remote_target=s.uri,this._route_set=r.getHeaders("record-route"),this._ack_seqnum=this._remote_seqnum):l==="UAC"&&(this._id={call_id:r.call_id,local_tag:r.from_tag,remote_tag:r.to_tag,toString(){return this.call_id+this.local_tag+this.remote_tag}},this._state=u,this._local_seqnum=r.cseq,this._local_uri=r.parseHeader("from").uri,this._remote_uri=r.parseHeader("to").uri,this._remote_target=s.uri,this._route_set=r.getHeaders("record-route").reverse(),this._ack_seqnum=null),this._ua.newDialog(this),dd.debug(`new ${l} dialog created with status ${this._state===Ai.STATUS_EARLY?"EARLY":"CONFIRMED"}`)}get id(){return this._id}get local_seqnum(){return this._local_seqnum}set local_seqnum(t){this._local_seqnum=t}get owner(){return this._owner}get uac_pending_reply(){return this._uac_pending_reply}set uac_pending_reply(t){this._uac_pending_reply=t}get uas_pending_reply(){return this._uas_pending_reply}isTerminated(){return this._status===Ai.STATUS_TERMINATED}update(t,r){this._state=Ai.STATUS_CONFIRMED,dd.debug(`dialog ${this._id.toString()} changed to CONFIRMED state`),r==="UAC"&&(this._route_set=t.getHeaders("record-route").reverse())}terminate(){dd.debug(`dialog ${this._id.toString()} deleted`),this._ua.destroyDialog(this),this._state=Ai.STATUS_TERMINATED}sendRequest(t,r={}){const l=cd.cloneArray(r.extraHeaders),u=cd.cloneObject(r.eventHandlers),s=r.body||null,n=this._createRequest(t,l,s);return u.onAuthenticated=()=>{this._local_seqnum+=1},new iE(this,n,u).send(),n}receiveRequest(t){this._checkInDialogRequest(t)&&(t.method===Ci.ACK&&this._ack_seqnum!==null?this._ack_seqnum=null:t.method===Ci.INVITE&&(this._ack_seqnum=t.cseq),this._owner.receiveRequest(t))}_createRequest(t,r,l){r=cd.cloneArray(r),this._local_seqnum||(this._local_seqnum=Math.floor(Math.random()*1e4));const u=t===Ci.CANCEL||t===Ci.ACK?this._local_seqnum:this._local_seqnum+=1;return new N_.OutgoingRequest(t,this._remote_target,this._ua,{cseq:u,call_id:this._id.call_id,from_uri:this._local_uri,from_tag:this._id.local_tag,to_uri:this._remote_uri,to_tag:this._id.remote_tag,route_set:this._route_set},r,l)}_checkInDialogRequest(t){if(!this._remote_seqnum)this._remote_seqnum=t.cseq;else if(t.cseq<this._remote_seqnum)if(t.method===Ci.ACK){if(this._ack_seqnum===null||t.cseq!==this._ack_seqnum)return!1}else return t.reply(500),!1;else t.cseq>this._remote_seqnum&&(this._remote_seqnum=t.cseq);if(t.method===Ci.INVITE||t.method===Ci.UPDATE&&t.body){if(this._uac_pending_reply===!0)t.reply(491);else if(this._uas_pending_reply===!0){const r=(Math.random()*10|0)+1;return t.reply(500,null,[`Retry-After:${r}`]),!1}else{this._uas_pending_reply=!0;const r=()=>{(t.server_transaction.state===ao.C.STATUS_ACCEPTED||t.server_transaction.state===ao.C.STATUS_COMPLETED||t.server_transaction.state===ao.C.STATUS_TERMINATED)&&(t.server_transaction.removeListener("stateChanged",r),this._uas_pending_reply=!1)};t.server_transaction.on("stateChanged",r)}t.hasHeader("contact")&&t.server_transaction.on("stateChanged",()=>{t.server_transaction.state===ao.C.STATUS_ACCEPTED&&(this._remote_target=t.parseHeader("contact").uri)})}else t.method===Ci.NOTIFY&&t.hasHeader("contact")&&t.server_transaction.on("stateChanged",()=>{t.server_transaction.state===ao.C.STATUS_COMPLETED&&(this._remote_target=t.parseHeader("contact").uri)});return!0}};const Iu=Ht(M_);var fd={exports:{}};const aE=ys.EventEmitter,lE=gs,oE=Et,uE=Pn,U_=xs(),cE=new lE("RTCSession:DTMF"),P_={MIN_DURATION:70,MAX_DURATION:6e3,DEFAULT_DURATION:100,MIN_INTER_TONE_GAP:50,DEFAULT_INTER_TONE_GAP:500};fd.exports=class extends aE{constructor(t){super(),this._session=t,this._direction=null,this._tone=null,this._duration=null,this._request=null}get tone(){return this._tone}get duration(){return this._duration}send(t,r={}){if(t===void 0)throw new TypeError("Not enough arguments");if(this._direction="outgoing",this._session.status!==this._session.C.STATUS_CONFIRMED&&this._session.status!==this._session.C.STATUS_WAITING_FOR_ACK)throw new uE.InvalidStateError(this._session.status);const l=U_.cloneArray(r.extraHeaders);if(this.eventHandlers=U_.cloneObject(r.eventHandlers),typeof t=="string")t=t.toUpperCase();else if(typeof t=="number")t=t.toString();else throw new TypeError(`Invalid tone: ${t}`);if(t.match(/^[0-9A-DR#*]$/))this._tone=t;else throw new TypeError(`Invalid tone: ${t}`);this._duration=r.duration,l.push("Content-Type: application/dtmf-relay");let u=`Signal=${this._tone}\r
113
113
  `;u+=`Duration=${this._duration}`,this._session.newDTMF({originator:"local",dtmf:this,request:this._request}),this._session.sendRequest(oE.INFO,{extraHeaders:l,eventHandlers:{onSuccessResponse:s=>{this.emit("succeeded",{originator:"remote",response:s})},onErrorResponse:s=>{this.eventHandlers.onFailed&&this.eventHandlers.onFailed(),this.emit("failed",{originator:"remote",response:s})},onRequestTimeout:()=>{this._session.onRequestTimeout()},onTransportError:()=>{this._session.onTransportError()},onDialogError:()=>{this._session.onDialogError()}},body:u})}init_incoming(t){const r=/^(Signal\s*?=\s*?)([0-9A-D#*]{1})(\s)?.*/,l=/^(Duration\s?=\s?)([0-9]{1,4})(\s)?.*/;if(this._direction="incoming",this._request=t,t.reply(200),t.body){const u=t.body.split(`
114
- `);u.length>=1&&r.test(u[0])&&(this._tone=u[0].replace(r,"$2")),u.length>=2&&l.test(u[1])&&(this._duration=parseInt(u[1].replace(l,"$2"),10))}this._duration||(this._duration=L_.DEFAULT_DURATION),this._tone?this._session.newDTMF({originator:"remote",dtmf:this,request:t}):cE.debug("invalid INFO DTMF received, discarded")}},fd.exports.C=L_;var H_=fd.exports;const dE=Ht(H_),fE=ys.EventEmitter,hE=Et,_E=Pn,pE=xs();var F_=class extends fE{constructor(t){super(),this._session=t,this._direction=null,this._contentType=null,this._body=null}get contentType(){return this._contentType}get body(){return this._body}send(t,r,l={}){if(this._direction="outgoing",t===void 0)throw new TypeError("Not enough arguments");if(this._session.status!==this._session.C.STATUS_CONFIRMED&&this._session.status!==this._session.C.STATUS_WAITING_FOR_ACK)throw new _E.InvalidStateError(this._session.status);this._contentType=t,this._body=r;const u=pE.cloneArray(l.extraHeaders);u.push(`Content-Type: ${t}`),this._session.newInfo({originator:"local",info:this,request:this.request}),this._session.sendRequest(hE.INFO,{extraHeaders:u,eventHandlers:{onSuccessResponse:s=>{this.emit("succeeded",{originator:"remote",response:s})},onErrorResponse:s=>{this.emit("failed",{originator:"remote",response:s})},onTransportError:()=>{this._session.onTransportError()},onRequestTimeout:()=>{this._session.onRequestTimeout()},onDialogError:()=>{this._session.onDialogError()}},body:r})}init_incoming(t){this._direction="incoming",this.request=t,t.reply(200),this._contentType=t.hasHeader("Content-Type")?t.getHeader("Content-Type").toLowerCase():void 0,this._body=t.body,this._session.newInfo({originator:"remote",info:this,request:t})}};const hd=Ht(F_),mE=gs,B_=Et,gE=new mE("RTCSession:ReferNotifier"),_d={event_type:"refer",body_type:"message/sipfrag;version=2.0",expires:300};var z_=class{constructor(t,r,l){this._session=t,this._id=r,this._expires=l||_d.expires,this._active=!0,this.notify(100)}notify(t,r){if(gE.debug("notify()"),this._active===!1)return;r=r||B_.REASON_PHRASE[t]||"";let l;t>=200?l="terminated;reason=noresource":l=`active;expires=${this._expires}`,this._session.sendRequest(B_.NOTIFY,{extraHeaders:[`Event: ${_d.event_type};id=${this._id}`,`Subscription-State: ${l}`,`Content-Type: ${_d.body_type}`],body:`SIP/2.0 ${t} ${r}`,eventHandlers:{onErrorResponse(){this._active=!1}}})}};const vE=Ht(z_),yE=ys.EventEmitter,TE=gs,lo=Et,SE=Dr(),V_=xs(),Ea=new TE("RTCSession:ReferSubscriber");var q_=class extends yE{constructor(t){super(),this._id=null,this._session=t}get id(){return this._id}sendRefer(t,r={}){Ea.debug("sendRefer()");const l=V_.cloneArray(r.extraHeaders),u=V_.cloneObject(r.eventHandlers);for(const _ in u)Object.prototype.hasOwnProperty.call(u,_)&&this.on(_,u[_]);let s=null;r.replaces&&(s=r.replaces._request.call_id,s+=`;to-tag=${r.replaces._to_tag}`,s+=`;from-tag=${r.replaces._from_tag}`,s=encodeURIComponent(s));const n=`Refer-To: <${t}${s?`?Replaces=${s}`:""}>`;if(l.push(n),!l.some(_=>_.toLowerCase().startsWith("referred-by:"))){const _=`Referred-By: <${this._session._ua._configuration.uri._scheme}:${this._session._ua._configuration.uri._user}@${this._session._ua._configuration.uri._host}>`;l.push(_)}l.push(`Contact: ${this._session.contact}`);const g=this._session.sendRequest(lo.REFER,{extraHeaders:l,eventHandlers:{onSuccessResponse:_=>{this._requestSucceeded(_)},onErrorResponse:_=>{this._requestFailed(_,lo.causes.REJECTED)},onTransportError:()=>{this._requestFailed(null,lo.causes.CONNECTION_ERROR)},onRequestTimeout:()=>{this._requestFailed(null,lo.causes.REQUEST_TIMEOUT)},onDialogError:()=>{this._requestFailed(null,lo.causes.DIALOG_ERROR)}}});this._id=g.cseq}receiveNotify(t){if(Ea.debug("receiveNotify()"),!t.body)return;const r=SE.parse(t.body.trim().split(`\r
115
- `,1)[0],"Status_Line");if(r===-1){Ea.debug(`receiveNotify() | error parsing NOTIFY body: "${t.body}"`);return}switch(!0){case/^100$/.test(r.status_code):this.emit("trying",{request:t,status_line:r});break;case/^1[0-9]{2}$/.test(r.status_code):this.emit("progress",{request:t,status_line:r});break;case/^2[0-9]{2}$/.test(r.status_code):this.emit("accepted",{request:t,status_line:r});break;default:this.emit("failed",{request:t,status_line:r});break}}_requestSucceeded(t){Ea.debug("REFER succeeded"),Ea.debug('emit "requestSucceeded"'),this.emit("requestSucceeded",{response:t})}_requestFailed(t,r){Ea.debug("REFER failed"),Ea.debug('emit "requestFailed"'),this.emit("requestFailed",{response:t||null,cause:r})}};const bE=Ht(q_),wE=ys.EventEmitter,j_=sr,EE=gs,Ke=Et,Ca=Pn,G_=hl,Xt=xs(),oo=nd,CE=Ds,Ru=U_,AE=_l,_r=H_,W_=F_,IE=z_,RE=q_,K_=Nn(),Ce=new EE("RTCSession"),xe={STATUS_NULL:0,STATUS_INVITE_SENT:1,STATUS_1XX_RECEIVED:2,STATUS_INVITE_RECEIVED:3,STATUS_WAITING_FOR_ANSWER:4,STATUS_ANSWERED:5,STATUS_WAITING_FOR_ACK:6,STATUS_CANCELED:7,STATUS_TERMINATED:8,STATUS_CONFIRMED:9},$u=["audio","video"];var Y_=class zf extends wE{static get C(){return xe}constructor(t){Ce.debug("new"),super(),this._id=null,this._ua=t,this._status=xe.STATUS_NULL,this._dialog=null,this._earlyDialogs={},this._contact=null,this._from_tag=null,this._to_tag=null,this._connection=null,this._connectionPromiseQueue=Promise.resolve(),this._request=null,this._is_canceled=!1,this._cancel_reason="",this._is_confirmed=!1,this._late_sdp=!1,this._rtcOfferConstraints=null,this._rtcAnswerConstraints=null,this._localMediaStream=null,this._localMediaStreamLocallyGenerated=!1,this._rtcReady=!0,this._iceReady=!1,this._timers={ackTimer:null,expiresTimer:null,invite2xxTimer:null,userNoAnswerTimer:null},this._direction=null,this._local_identity=null,this._remote_identity=null,this._start_time=null,this._end_time=null,this._tones=null,this._audioMuted=!1,this._videoMuted=!1,this._localHold=!1,this._remoteHold=!1,this._sessionTimers={enabled:this._ua.configuration.session_timers,refreshMethod:this._ua.configuration.session_timers_refresh_method,defaultExpires:Ke.SESSION_EXPIRES,currentExpires:null,running:!1,refresher:!1,timer:null},this._referSubscribers={},this._data={}}get C(){return xe}get causes(){return Ke.causes}get id(){return this._id}get connection(){return this._connection}get contact(){return this._contact}get direction(){return this._direction}get local_identity(){return this._local_identity}get remote_identity(){return this._remote_identity}get start_time(){return this._start_time}get end_time(){return this._end_time}get data(){return this._data}set data(t){this._data=t}get status(){return this._status}isInProgress(){switch(this._status){case xe.STATUS_NULL:case xe.STATUS_INVITE_SENT:case xe.STATUS_1XX_RECEIVED:case xe.STATUS_INVITE_RECEIVED:case xe.STATUS_WAITING_FOR_ANSWER:return!0;default:return!1}}isEstablished(){switch(this._status){case xe.STATUS_ANSWERED:case xe.STATUS_WAITING_FOR_ACK:case xe.STATUS_CONFIRMED:return!0;default:return!1}}isEnded(){switch(this._status){case xe.STATUS_CANCELED:case xe.STATUS_TERMINATED:return!0;default:return!1}}isMuted(){return{audio:this._audioMuted,video:this._videoMuted}}isOnHold(){return{local:this._localHold,remote:this._remoteHold}}connect(t,r={},l){Ce.debug("connect()");const u=t,s=Xt.cloneObject(r.eventHandlers),n=Xt.cloneArray(r.extraHeaders),g=Xt.cloneObject(r.mediaConstraints,{audio:!0,video:!0}),_=r.mediaStream||null,v=Xt.cloneObject(r.pcConfig,{iceServers:[]}),C=r.rtcConstraints||null,R=r.rtcOfferConstraints||null;if(this._rtcOfferConstraints=R,this._rtcAnswerConstraints=r.rtcAnswerConstraints||null,this._data=r.data||this._data,t===void 0)throw new TypeError("Not enough arguments");if(this._status!==xe.STATUS_NULL)throw new Ca.InvalidStateError(this._status);if(!window.RTCPeerConnection)throw new Ca.NotSupportedError("WebRTC not supported");if(t=this._ua.normalizeTarget(t),!t)throw new TypeError(`Invalid target: ${u}`);this._sessionTimers.enabled&&Xt.isDecimal(r.sessionTimersExpires)&&(r.sessionTimersExpires>=Ke.MIN_SESSION_EXPIRES?this._sessionTimers.defaultExpires=r.sessionTimersExpires:this._sessionTimers.defaultExpires=Ke.SESSION_EXPIRES);for(const F in s)Object.prototype.hasOwnProperty.call(s,F)&&this.on(F,s[F]);this._from_tag=Xt.newTag();const D=r.anonymous||!1,H={from_tag:this._from_tag};this._contact=this._ua.contact.toString({anonymous:D,outbound:!0}),D?(H.from_display_name="Anonymous",H.from_uri=new K_("sip","anonymous","anonymous.invalid"),n.push(`P-Preferred-Identity: ${this._ua.configuration.uri.toString()}`),n.push("Privacy: id")):r.fromUserName&&(H.from_uri=new K_("sip",r.fromUserName,this._ua.configuration.uri.host),n.push(`P-Preferred-Identity: ${this._ua.configuration.uri.toString()}`)),r.fromDisplayName&&(H.from_display_name=r.fromDisplayName),n.push(`Contact: ${this._contact}`),n.push("Content-Type: application/sdp"),this._sessionTimers.enabled&&n.push(`Session-Expires: ${this._sessionTimers.defaultExpires}${this._ua.configuration.session_timers_force_refresher?";refresher=uac":""}`),this._request=new CE.InitialOutgoingInviteRequest(t,this._ua,H,n),this._id=this._request.call_id+this._from_tag,this._createRTCConnection(v,C),this._direction="outgoing",this._local_identity=this._request.from,this._remote_identity=this._request.to,l&&l(this),this._newRTCSession("local",this._request),this._sendInitialRequest(g,R,_)}init_incoming(t,r){Ce.debug("init_incoming()");let l;const u=t.hasHeader("Content-Type")?t.getHeader("Content-Type").toLowerCase():void 0;if(t.body&&u!=="application/sdp"){t.reply(415);return}if(this._status=xe.STATUS_INVITE_RECEIVED,this._from_tag=t.from_tag,this._id=t.call_id+this._from_tag,this._request=t,this._contact=this._ua.contact.toString(),t.hasHeader("expires")&&(l=t.getHeader("expires")*1e3),t.to_tag=Xt.newTag(),!this._createDialog(t,"UAS",!0)){t.reply(500,"Missing Contact header field");return}t.body?this._late_sdp=!1:this._late_sdp=!0,this._status=xe.STATUS_WAITING_FOR_ANSWER,this._timers.userNoAnswerTimer=setTimeout(()=>{t.reply(408),this._failed("local",null,Ke.causes.NO_ANSWER)},this._ua.configuration.no_answer_timeout),l&&(this._timers.expiresTimer=setTimeout(()=>{this._status===xe.STATUS_WAITING_FOR_ANSWER&&(t.reply(487),this._failed("system",null,Ke.causes.EXPIRES))},l)),this._direction="incoming",this._local_identity=t.to,this._remote_identity=t.from,r&&r(this),this._newRTCSession("remote",t),this._status!==xe.STATUS_TERMINATED&&(t.reply(180,null,[`Contact: ${this._contact}`]),this._progress("local",null))}answer(t={}){Ce.debug("answer()");const r=this._request,l=Xt.cloneArray(t.extraHeaders),u=Xt.cloneObject(t.mediaConstraints),s=t.mediaStream||null,n=Xt.cloneObject(t.pcConfig,{iceServers:[]}),g=t.rtcConstraints||null,_=t.rtcAnswerConstraints||null,v=Xt.cloneObject(t.rtcOfferConstraints);let C,R=!1,D=!1,H=!1,F=!1;if(this._rtcAnswerConstraints=_,this._rtcOfferConstraints=t.rtcOfferConstraints||null,this._data=t.data||this._data,this._direction!=="incoming")throw new Ca.NotSupportedError('"answer" not supported for outgoing RTCSession');if(this._status!==xe.STATUS_WAITING_FOR_ANSWER)throw new Ca.InvalidStateError(this._status);if(this._sessionTimers.enabled&&Xt.isDecimal(t.sessionTimersExpires)&&(t.sessionTimersExpires>=Ke.MIN_SESSION_EXPIRES?this._sessionTimers.defaultExpires=t.sessionTimersExpires:this._sessionTimers.defaultExpires=Ke.SESSION_EXPIRES),this._status=xe.STATUS_ANSWERED,!this._createDialog(r,"UAS")){r.reply(500,"Error creating dialog");return}clearTimeout(this._timers.userNoAnswerTimer),l.unshift(`Contact: ${this._contact}`);const q=r.parseSDP();Array.isArray(q.media)||(q.media=[q.media]);for(const G of q.media)G.type==="audio"&&(R=!0,(!G.direction||G.direction==="sendrecv")&&(H=!0)),G.type==="video"&&(D=!0,(!G.direction||G.direction==="sendrecv")&&(F=!0));if(s&&u.audio===!1){C=s.getAudioTracks();for(const G of C)s.removeTrack(G)}if(s&&u.video===!1){C=s.getVideoTracks();for(const G of C)s.removeTrack(G)}!s&&u.audio===void 0&&(u.audio=H),!s&&u.video===void 0&&(u.video=F),!s&&!R&&!v.offerToReceiveAudio&&(u.audio=!1),!s&&!D&&!v.offerToReceiveVideo&&(u.video=!1),this._createRTCConnection(n,g),Promise.resolve().then(()=>{if(s)return s;if(u.audio||u.video)return this._localMediaStreamLocallyGenerated=!0,navigator.mediaDevices.getUserMedia(u).catch(G=>{throw this._status===xe.STATUS_TERMINATED?new Error("terminated"):(r.reply(480),this._failed("local",null,Ke.causes.USER_DENIED_MEDIA_ACCESS),Ce.warn('emit "getusermediafailed" [error:%o]',G),this.emit("getusermediafailed",G),new Error("getUserMedia() failed"))})}).then(G=>{if(this._status===xe.STATUS_TERMINATED)throw new Error("terminated");this._localMediaStream=G,G&&G.getTracks().forEach(te=>{this._connection.addTrack(te,G)})}).then(()=>{if(this._late_sdp)return;const G={originator:"remote",type:"offer",sdp:r.body};Ce.debug('emit "sdp"'),this.emit("sdp",G);const te=new RTCSessionDescription({type:"offer",sdp:G.sdp});return this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(te)).catch(X=>{throw r.reply(488),this._failed("system",null,Ke.causes.WEBRTC_ERROR),Ce.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',X),this.emit("peerconnection:setremotedescriptionfailed",X),new Error("peerconnection.setRemoteDescription() failed")}),this._connectionPromiseQueue}).then(()=>{if(this._status===xe.STATUS_TERMINATED)throw new Error("terminated");return this._connecting(r),this._late_sdp?this._createLocalDescription("offer",this._rtcOfferConstraints).catch(()=>{throw r.reply(500),new Error("_createLocalDescription() failed")}):this._createLocalDescription("answer",_).catch(()=>{throw r.reply(500),new Error("_createLocalDescription() failed")})}).then(G=>{if(this._status===xe.STATUS_TERMINATED)throw new Error("terminated");this._handleSessionTimersInIncomingRequest(r,l),r.reply(200,null,l,G,()=>{this._status=xe.STATUS_WAITING_FOR_ACK,this._setInvite2xxTimer(r,G),this._setACKTimer(),this._accepted("local")},()=>{this._failed("system",null,Ke.causes.CONNECTION_ERROR)})}).catch(G=>{this._status!==xe.STATUS_TERMINATED&&Ce.warn(G)})}terminate(t={}){Ce.debug("terminate()");const r=t.cause||Ke.causes.BYE,l=Xt.cloneArray(t.extraHeaders),u=t.body;let s,n=t.status_code,g=t.reason_phrase;if(this._status===xe.STATUS_TERMINATED)throw new Ca.InvalidStateError(this._status);switch(this._status){case xe.STATUS_NULL:case xe.STATUS_INVITE_SENT:case xe.STATUS_1XX_RECEIVED:if(Ce.debug("canceling session"),n&&(n<200||n>=700))throw new TypeError(`Invalid status_code: ${n}`);n&&(g=g||Ke.REASON_PHRASE[n]||"",s=`SIP ;cause=${n} ;text="${g}"`),this._status===xe.STATUS_NULL||this._status===xe.STATUS_INVITE_SENT?(this._is_canceled=!0,this._cancel_reason=s):this._status===xe.STATUS_1XX_RECEIVED&&this._request.cancel(s),this._status=xe.STATUS_CANCELED,this._failed("local",null,Ke.causes.CANCELED);break;case xe.STATUS_WAITING_FOR_ANSWER:case xe.STATUS_ANSWERED:if(Ce.debug("rejecting session"),n=n||480,n<300||n>=700)throw new TypeError(`Invalid status_code: ${n}`);this._request.reply(n,g,l,u),this._failed("local",null,Ke.causes.REJECTED);break;case xe.STATUS_WAITING_FOR_ACK:case xe.STATUS_CONFIRMED:if(Ce.debug("terminating session"),g=t.reason_phrase||Ke.REASON_PHRASE[n]||"",n&&(n<200||n>=700))throw new TypeError(`Invalid status_code: ${n}`);if(n&&l.push(`Reason: SIP ;cause=${n}; text="${g}"`),this._status===xe.STATUS_WAITING_FOR_ACK&&this._direction==="incoming"&&this._request.server_transaction.state!==G_.C.STATUS_TERMINATED){const _=this._dialog;this.receiveRequest=({method:v})=>{v===Ke.ACK&&(this.sendRequest(Ke.BYE,{extraHeaders:l,body:u}),_.terminate())},this._request.server_transaction.on("stateChanged",()=>{this._request.server_transaction.state===G_.C.STATUS_TERMINATED&&(this.sendRequest(Ke.BYE,{extraHeaders:l,body:u}),_.terminate())}),this._ended("local",null,r),this._dialog=_,this._ua.newDialog(_)}else this.sendRequest(Ke.BYE,{extraHeaders:l,body:u}),this._ended("local",null,r)}}sendDTMF(t,r={}){Ce.debug("sendDTMF() | tones: %s",t);let l=0,u=r.duration||null,s=r.interToneGap||null;const n=r.transportType||Ke.DTMF_TRANSPORT.INFO;if(t===void 0)throw new TypeError("Not enough arguments");if(this._status!==xe.STATUS_CONFIRMED&&this._status!==xe.STATUS_WAITING_FOR_ACK&&this._status!==xe.STATUS_1XX_RECEIVED)throw new Ca.InvalidStateError(this._status);if(n!==Ke.DTMF_TRANSPORT.INFO&&n!==Ke.DTMF_TRANSPORT.RFC2833)throw new TypeError(`invalid transportType: ${n}`);if(typeof t=="number"&&(t=t.toString()),!t||typeof t!="string"||!t.match(/^[0-9A-DR#*,]+$/i))throw new TypeError(`Invalid tones: ${t}`);if(u&&!Xt.isDecimal(u))throw new TypeError(`Invalid tone duration: ${u}`);if(u?u<_r.C.MIN_DURATION?(Ce.debug(`"duration" value is lower than the minimum allowed, setting it to ${_r.C.MIN_DURATION} milliseconds`),u=_r.C.MIN_DURATION):u>_r.C.MAX_DURATION?(Ce.debug(`"duration" value is greater than the maximum allowed, setting it to ${_r.C.MAX_DURATION} milliseconds`),u=_r.C.MAX_DURATION):u=Math.abs(u):u=_r.C.DEFAULT_DURATION,r.duration=u,s&&!Xt.isDecimal(s))throw new TypeError(`Invalid interToneGap: ${s}`);if(s?s<_r.C.MIN_INTER_TONE_GAP?(Ce.debug(`"interToneGap" value is lower than the minimum allowed, setting it to ${_r.C.MIN_INTER_TONE_GAP} milliseconds`),s=_r.C.MIN_INTER_TONE_GAP):s=Math.abs(s):s=_r.C.DEFAULT_INTER_TONE_GAP,n===Ke.DTMF_TRANSPORT.RFC2833){const _=this._getDTMFRTPSender();_&&(t=_.toneBuffer+t,_.insertDTMF(t,u,s));return}if(this._tones){this._tones+=t;return}this._tones=t,g.call(this);function g(){let _;if(this._status===xe.STATUS_TERMINATED||!this._tones||l>=this._tones.length){this._tones=null;return}const v=this._tones[l];if(l+=1,v===",")_=2e3;else{const C=new _r(this);r.eventHandlers={onFailed:()=>{this._tones=null}},C.send(v,r),_=u+s}setTimeout(g.bind(this),_)}}sendInfo(t,r,l={}){if(Ce.debug("sendInfo()"),this._status!==xe.STATUS_CONFIRMED&&this._status!==xe.STATUS_WAITING_FOR_ACK&&this._status!==xe.STATUS_1XX_RECEIVED)throw new Ca.InvalidStateError(this._status);new W_(this).send(t,r,l)}mute(t={audio:!0,video:!1}){Ce.debug("mute()");let r=!1,l=!1;this._audioMuted===!1&&t.audio&&(r=!0,this._audioMuted=!0,this._toggleMuteAudio(!0)),this._videoMuted===!1&&t.video&&(l=!0,this._videoMuted=!0,this._toggleMuteVideo(!0)),(r===!0||l===!0)&&this._onmute({audio:r,video:l})}unmute(t={audio:!0,video:!0}){Ce.debug("unmute()");let r=!1,l=!1;this._audioMuted===!0&&t.audio&&(r=!0,this._audioMuted=!1,this._localHold===!1&&this._toggleMuteAudio(!1)),this._videoMuted===!0&&t.video&&(l=!0,this._videoMuted=!1,this._localHold===!1&&this._toggleMuteVideo(!1)),(r===!0||l===!0)&&this._onunmute({audio:r,video:l})}hold(t={},r){if(Ce.debug("hold()"),this._status!==xe.STATUS_WAITING_FOR_ACK&&this._status!==xe.STATUS_CONFIRMED||this._localHold===!0||!this._isReadyToReOffer())return!1;this._localHold=!0,this._onhold("local");const l={succeeded:()=>{r&&r()},failed:()=>{this.terminate({cause:Ke.causes.WEBRTC_ERROR,status_code:500,reason_phrase:"Hold Failed"})}};return t.useUpdate?this._sendUpdate({sdpOffer:!0,eventHandlers:l,extraHeaders:t.extraHeaders}):this._sendReinvite({eventHandlers:l,extraHeaders:t.extraHeaders}),!0}unhold(t={},r){if(Ce.debug("unhold()"),this._status!==xe.STATUS_WAITING_FOR_ACK&&this._status!==xe.STATUS_CONFIRMED||this._localHold===!1||!this._isReadyToReOffer())return!1;this._localHold=!1,this._onunhold("local");const l={succeeded:()=>{r&&r()},failed:()=>{this.terminate({cause:Ke.causes.WEBRTC_ERROR,status_code:500,reason_phrase:"Unhold Failed"})}};return t.useUpdate?this._sendUpdate({sdpOffer:!0,eventHandlers:l,extraHeaders:t.extraHeaders}):this._sendReinvite({eventHandlers:l,extraHeaders:t.extraHeaders}),!0}renegotiate(t={},r){Ce.debug("renegotiate()");const l=t.rtcOfferConstraints||null;if(this._status!==xe.STATUS_WAITING_FOR_ACK&&this._status!==xe.STATUS_CONFIRMED||!this._isReadyToReOffer())return!1;const u={succeeded:()=>{r&&r()},failed:()=>{this.terminate({cause:Ke.causes.WEBRTC_ERROR,status_code:500,reason_phrase:"Media Renegotiation Failed"})}};return this._setLocalMediaStatus(),t.useUpdate?this._sendUpdate({sdpOffer:!0,eventHandlers:u,rtcOfferConstraints:l,extraHeaders:t.extraHeaders}):this._sendReinvite({eventHandlers:u,rtcOfferConstraints:l,extraHeaders:t.extraHeaders}),!0}refer(t,r){Ce.debug("refer()");const l=t;if(this._status!==xe.STATUS_WAITING_FOR_ACK&&this._status!==xe.STATUS_CONFIRMED)return!1;if(t=this._ua.normalizeTarget(t),!t)throw new TypeError(`Invalid target: ${l}`);const u=new RE(this);u.sendRefer(t,r);const s=u.id;return this._referSubscribers[s]=u,u.on("requestFailed",()=>{delete this._referSubscribers[s]}),u.on("accepted",()=>{delete this._referSubscribers[s]}),u.on("failed",()=>{delete this._referSubscribers[s]}),u}sendRequest(t,r){return Ce.debug("sendRequest()"),this._dialog.sendRequest(t,r)}receiveRequest(t){if(Ce.debug("receiveRequest()"),t.method===Ke.CANCEL)(this._status===xe.STATUS_WAITING_FOR_ANSWER||this._status===xe.STATUS_ANSWERED)&&(this._status=xe.STATUS_CANCELED,this._request.reply(487),this._failed("remote",t,Ke.causes.CANCELED));else switch(t.method){case Ke.ACK:if(this._status!==xe.STATUS_WAITING_FOR_ACK)return;if(this._status=xe.STATUS_CONFIRMED,clearTimeout(this._timers.ackTimer),clearTimeout(this._timers.invite2xxTimer),this._late_sdp){if(!t.body){this.terminate({cause:Ke.causes.MISSING_SDP,status_code:400});break}const r={originator:"remote",type:"answer",sdp:t.body};Ce.debug('emit "sdp"'),this.emit("sdp",r);const l=new RTCSessionDescription({type:"answer",sdp:r.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(l)).then(()=>{this._is_confirmed||this._confirmed("remote",t)}).catch(u=>{this.terminate({cause:Ke.causes.BAD_MEDIA_DESCRIPTION,status_code:488}),Ce.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',u),this.emit("peerconnection:setremotedescriptionfailed",u)})}else this._is_confirmed||this._confirmed("remote",t);break;case Ke.BYE:this._status===xe.STATUS_CONFIRMED||this._status===xe.STATUS_WAITING_FOR_ACK?(t.reply(200),this._ended("remote",t,Ke.causes.BYE)):this._status===xe.STATUS_INVITE_RECEIVED||this._status===xe.STATUS_WAITING_FOR_ANSWER?(t.reply(200),this._request.reply(487,"BYE Received"),this._ended("remote",t,Ke.causes.BYE)):t.reply(403,"Wrong Status");break;case Ke.INVITE:this._status===xe.STATUS_CONFIRMED?t.hasHeader("replaces")?this._receiveReplaces(t):this._receiveReinvite(t):t.reply(403,"Wrong Status");break;case Ke.INFO:if(this._status===xe.STATUS_1XX_RECEIVED||this._status===xe.STATUS_WAITING_FOR_ANSWER||this._status===xe.STATUS_ANSWERED||this._status===xe.STATUS_WAITING_FOR_ACK||this._status===xe.STATUS_CONFIRMED){const r=t.hasHeader("Content-Type")?t.getHeader("Content-Type").toLowerCase():void 0;r&&r.match(/^application\/dtmf-relay/i)?new _r(this).init_incoming(t):r!==void 0?new W_(this).init_incoming(t):t.reply(415)}else t.reply(403,"Wrong Status");break;case Ke.UPDATE:this._status===xe.STATUS_CONFIRMED?this._receiveUpdate(t):t.reply(403,"Wrong Status");break;case Ke.REFER:this._status===xe.STATUS_CONFIRMED?this._receiveRefer(t):t.reply(403,"Wrong Status");break;case Ke.NOTIFY:this._status===xe.STATUS_CONFIRMED?this._receiveNotify(t):t.reply(403,"Wrong Status");break;default:t.reply(501)}}onTransportError(){Ce.warn("onTransportError()"),this._status!==xe.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:Ke.causes.CONNECTION_ERROR,cause:Ke.causes.CONNECTION_ERROR})}onRequestTimeout(){Ce.warn("onRequestTimeout()"),this._status!==xe.STATUS_TERMINATED&&this.terminate({status_code:408,reason_phrase:Ke.causes.REQUEST_TIMEOUT,cause:Ke.causes.REQUEST_TIMEOUT})}onDialogError(){Ce.warn("onDialogError()"),this._status!==xe.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:Ke.causes.DIALOG_ERROR,cause:Ke.causes.DIALOG_ERROR})}newDTMF(t){Ce.debug("newDTMF()"),this.emit("newDTMF",t)}newInfo(t){Ce.debug("newInfo()"),this.emit("newInfo",t)}_isReadyToReOffer(){return this._rtcReady?this._dialog?this._dialog.uac_pending_reply===!0||this._dialog.uas_pending_reply===!0?(Ce.debug("_isReadyToReOffer() | there is another INVITE/UPDATE transaction in progress"),!1):!0:(Ce.debug("_isReadyToReOffer() | session not established yet"),!1):(Ce.debug("_isReadyToReOffer() | internal WebRTC status not ready"),!1)}_close(){if(Ce.debug("close()"),this._localMediaStream&&this._localMediaStreamLocallyGenerated&&(Ce.debug("close() | closing local MediaStream"),Xt.closeMediaStream(this._localMediaStream)),this._status!==xe.STATUS_TERMINATED){if(this._status=xe.STATUS_TERMINATED,this._connection)try{this._connection.close()}catch(t){Ce.warn("close() | error closing the RTCPeerConnection: %o",t)}for(const t in this._timers)Object.prototype.hasOwnProperty.call(this._timers,t)&&clearTimeout(this._timers[t]);clearTimeout(this._sessionTimers.timer),this._dialog&&(this._dialog.terminate(),delete this._dialog);for(const t in this._earlyDialogs)Object.prototype.hasOwnProperty.call(this._earlyDialogs,t)&&(this._earlyDialogs[t].terminate(),delete this._earlyDialogs[t]);for(const t in this._referSubscribers)Object.prototype.hasOwnProperty.call(this._referSubscribers,t)&&delete this._referSubscribers[t];this._ua.destroyRTCSession(this)}}_setInvite2xxTimer(t,r){let l=oo.T1;function u(){this._status===xe.STATUS_WAITING_FOR_ACK&&(t.reply(200,null,[`Contact: ${this._contact}`],r),l<oo.T2&&(l=l*2,l>oo.T2&&(l=oo.T2)),this._timers.invite2xxTimer=setTimeout(u.bind(this),l))}this._timers.invite2xxTimer=setTimeout(u.bind(this),l)}_setACKTimer(){this._timers.ackTimer=setTimeout(()=>{this._status===xe.STATUS_WAITING_FOR_ACK&&(Ce.debug("no ACK received, terminating the session"),clearTimeout(this._timers.invite2xxTimer),this.sendRequest(Ke.BYE),this._ended("remote",null,Ke.causes.NO_ACK))},oo.TIMER_H)}_createRTCConnection(t,r){this._connection=new RTCPeerConnection(t,r),this._connection.addEventListener("iceconnectionstatechange",()=>{this._connection.iceConnectionState==="failed"&&this.terminate({cause:Ke.causes.RTP_TIMEOUT,status_code:408,reason_phrase:Ke.causes.RTP_TIMEOUT})}),Ce.debug('emit "peerconnection"'),this.emit("peerconnection",{peerconnection:this._connection})}_createLocalDescription(t,r){if(Ce.debug("createLocalDescription()"),t!=="offer"&&t!=="answer")throw new Error(`createLocalDescription() | invalid type "${t}"`);const l=this._connection;return this._rtcReady=!1,Promise.resolve().then(()=>t==="offer"?l.createOffer(r).catch(u=>(Ce.warn('emit "peerconnection:createofferfailed" [error:%o]',u),this.emit("peerconnection:createofferfailed",u),Promise.reject(u))):l.createAnswer(r).catch(u=>(Ce.warn('emit "peerconnection:createanswerfailed" [error:%o]',u),this.emit("peerconnection:createanswerfailed",u),Promise.reject(u)))).then(u=>l.setLocalDescription(u).catch(s=>(this._rtcReady=!0,Ce.warn('emit "peerconnection:setlocaldescriptionfailed" [error:%o]',s),this.emit("peerconnection:setlocaldescriptionfailed",s),Promise.reject(s)))).then(()=>{const u=r&&r.iceRestart;if(l.iceGatheringState==="complete"&&!u||l.iceGatheringState==="gathering"&&this._iceReady){this._rtcReady=!0;const s={originator:"local",type:t,sdp:l.localDescription.sdp};return Ce.debug('emit "sdp"'),this.emit("sdp",s),Promise.resolve(s.sdp)}return new Promise(s=>{let n=!1,g,_;this._iceReady=!1;const v=()=>{l.removeEventListener("icecandidate",g),l.removeEventListener("icegatheringstatechange",_),n=!0,this._rtcReady=!0,this._iceReady=!0;const C={originator:"local",type:t,sdp:l.localDescription.sdp};Ce.debug('emit "sdp"'),this.emit("sdp",C),s(C.sdp)};l.addEventListener("icecandidate",g=C=>{const R=C.candidate;R?this.emit("icecandidate",{candidate:R,ready:v}):n||v()}),l.addEventListener("icegatheringstatechange",_=()=>{l.iceGatheringState==="complete"&&!n&&v()})})})}_createDialog(t,r,l){const u=r==="UAS"?t.to_tag:t.from_tag,s=r==="UAS"?t.from_tag:t.to_tag,n=t.call_id+u+s;let g=this._earlyDialogs[n];if(l)return g?!0:(g=new Ru(this,t,r,Ru.C.STATUS_EARLY),g.error?(Ce.debug(g.error),this._failed("remote",t,Ke.causes.INTERNAL_ERROR),!1):(this._earlyDialogs[n]=g,!0));{if(this._from_tag=t.from_tag,this._to_tag=t.to_tag,g)return g.update(t,r),this._dialog=g,delete this._earlyDialogs[n],!0;const _=new Ru(this,t,r);return _.error?(Ce.debug(_.error),this._failed("remote",t,Ke.causes.INTERNAL_ERROR),!1):(this._dialog=_,!0)}}_receiveReinvite(t){Ce.debug("receiveReinvite()");const r=t.hasHeader("Content-Type")?t.getHeader("Content-Type").toLowerCase():void 0,l={request:t,callback:void 0,reject:s.bind(this)};let u=!1;function s(g={}){u=!0;const _=g.status_code||403,v=g.reason_phrase||"",C=Xt.cloneArray(g.extraHeaders);if(this._status!==xe.STATUS_CONFIRMED)return!1;if(_<300||_>=700)throw new TypeError(`Invalid status_code: ${_}`);t.reply(_,v,C)}if(this.emit("reinvite",l),u)return;if(this._late_sdp=!1,!t.body){this._late_sdp=!0,this._remoteHold&&(this._remoteHold=!1,this._onunhold("remote")),this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._createLocalDescription("offer",this._rtcOfferConstraints)).then(g=>{n.call(this,g)}).catch(()=>{t.reply(500)});return}if(r!=="application/sdp"){Ce.debug("invalid Content-Type"),t.reply(415);return}this._processInDialogSdpOffer(t).then(g=>{this._status!==xe.STATUS_TERMINATED&&n.call(this,g)}).catch(g=>{Ce.warn(g)});function n(g){const _=[`Contact: ${this._contact}`];this._handleSessionTimersInIncomingRequest(t,_),this._late_sdp&&(g=this._mangleOffer(g)),t.reply(200,null,_,g,()=>{this._status=xe.STATUS_WAITING_FOR_ACK,this._setInvite2xxTimer(t,g),this._setACKTimer()}),typeof l.callback=="function"&&l.callback()}}_receiveUpdate(t){Ce.debug("receiveUpdate()");const r=t.hasHeader("Content-Type")?t.getHeader("Content-Type").toLowerCase():void 0,l={request:t,callback:void 0,reject:s.bind(this)};let u=!1;function s(g={}){u=!0;const _=g.status_code||403,v=g.reason_phrase||"",C=Xt.cloneArray(g.extraHeaders);if(this._status!==xe.STATUS_CONFIRMED)return!1;if(_<300||_>=700)throw new TypeError(`Invalid status_code: ${_}`);t.reply(_,v,C)}if(this.emit("update",l),u)return;if(!t.body){n.call(this,null);return}if(r!=="application/sdp"){Ce.debug("invalid Content-Type"),t.reply(415);return}this._processInDialogSdpOffer(t).then(g=>{this._status!==xe.STATUS_TERMINATED&&n.call(this,g)}).catch(g=>{Ce.warn(g)});function n(g){const _=[`Contact: ${this._contact}`];this._handleSessionTimersInIncomingRequest(t,_),t.reply(200,null,_,g),typeof l.callback=="function"&&l.callback()}}_processInDialogSdpOffer(t){Ce.debug("_processInDialogSdpOffer()");const r=t.parseSDP();let l=!1;for(const n of r.media){if($u.indexOf(n.type)===-1)continue;const g=n.direction||r.direction||"sendrecv";if(g==="sendonly"||g==="inactive")l=!0;else{l=!1;break}}const u={originator:"remote",type:"offer",sdp:t.body};Ce.debug('emit "sdp"'),this.emit("sdp",u);const s=new RTCSessionDescription({type:"offer",sdp:u.sdp});return this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>{if(this._status===xe.STATUS_TERMINATED)throw new Error("terminated");return this._connection.setRemoteDescription(s).catch(n=>{throw t.reply(488),Ce.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',n),this.emit("peerconnection:setremotedescriptionfailed",n),n})}).then(()=>{if(this._status===xe.STATUS_TERMINATED)throw new Error("terminated");this._remoteHold===!0&&l===!1?(this._remoteHold=!1,this._onunhold("remote")):this._remoteHold===!1&&l===!0&&(this._remoteHold=!0,this._onhold("remote"))}).then(()=>{if(this._status===xe.STATUS_TERMINATED)throw new Error("terminated");return this._createLocalDescription("answer",this._rtcAnswerConstraints).catch(n=>{throw t.reply(500),Ce.warn('emit "peerconnection:createtelocaldescriptionfailed" [error:%o]',n),n})}).catch(n=>{Ce.warn("_processInDialogSdpOffer() failed [error: %o]",n)}),this._connectionPromiseQueue}_receiveRefer(t){if(Ce.debug("receiveRefer()"),!t.refer_to){Ce.debug("no Refer-To header field present in REFER"),t.reply(400);return}if(t.refer_to.uri.scheme!==Ke.SIP){Ce.debug("Refer-To header field points to a non-SIP URI scheme"),t.reply(416);return}t.reply(202);const r=new IE(this,t.cseq);Ce.debug('emit "refer"'),this.emit("refer",{request:t,accept:(s,n)=>{l.call(this,s,n)},reject:()=>{u.call(this)}});function l(s,n={}){if(s=typeof s=="function"?s:null,this._status!==xe.STATUS_WAITING_FOR_ACK&&this._status!==xe.STATUS_CONFIRMED)return!1;const g=new zf(this._ua);if(g.on("progress",({response:_})=>{r.notify(_.status_code,_.reason_phrase)}),g.on("accepted",({response:_})=>{r.notify(_.status_code,_.reason_phrase)}),g.on("_failed",({message:_,cause:v})=>{_?r.notify(_.status_code,_.reason_phrase):r.notify(487,v)}),t.refer_to.uri.hasHeader("replaces")){const _=decodeURIComponent(t.refer_to.uri.getHeader("replaces"));n.extraHeaders=Xt.cloneArray(n.extraHeaders),n.extraHeaders.push(`Replaces: ${_}`)}g.connect(t.refer_to.uri.toAor(),n,s)}function u(){r.notify(603)}}_receiveNotify(t){switch(Ce.debug("receiveNotify()"),t.event||t.reply(400),t.event.event){case"refer":{let r,l;if(t.event.params&&t.event.params.id)r=t.event.params.id,l=this._referSubscribers[r];else if(Object.keys(this._referSubscribers).length===1)l=this._referSubscribers[Object.keys(this._referSubscribers)[0]];else{t.reply(400,"Missing event id parameter");return}if(!l){t.reply(481,"Subscription does not exist");return}l.receiveNotify(t),t.reply(200);break}default:t.reply(489)}}_receiveReplaces(t){Ce.debug("receiveReplaces()");function r(u){if(this._status!==xe.STATUS_WAITING_FOR_ACK&&this._status!==xe.STATUS_CONFIRMED)return!1;const s=new zf(this._ua);s.on("confirmed",()=>{this.terminate()}),s.init_incoming(t,u)}function l(){Ce.debug("Replaced INVITE rejected by the user"),t.reply(486)}this.emit("replaces",{request:t,accept:u=>{r.call(this,u)},reject:()=>{l.call(this)}})}_sendInitialRequest(t,r,l){const u=new AE(this._ua,this._request,{onRequestTimeout:()=>{this.onRequestTimeout()},onTransportError:()=>{this.onTransportError()},onAuthenticated:s=>{this._request=s},onReceiveResponse:s=>{this._receiveInviteResponse(s)}});Promise.resolve().then(()=>{if(l)return l;if(t.audio||t.video)return this._localMediaStreamLocallyGenerated=!0,navigator.mediaDevices.getUserMedia(t).catch(s=>{throw this._status===xe.STATUS_TERMINATED?new Error("terminated"):(this._failed("local",null,Ke.causes.USER_DENIED_MEDIA_ACCESS),Ce.warn('emit "getusermediafailed" [error:%o]',s),this.emit("getusermediafailed",s),s)})}).then(s=>{if(this._status===xe.STATUS_TERMINATED)throw new Error("terminated");return this._localMediaStream=s,s&&s.getTracks().forEach(n=>{this._connection.addTrack(n,s)}),this._connecting(this._request),this._createLocalDescription("offer",r).catch(n=>{throw this._failed("local",null,Ke.causes.WEBRTC_ERROR),n})}).then(s=>{if(this._is_canceled||this._status===xe.STATUS_TERMINATED)throw new Error("terminated");this._request.body=s,this._status=xe.STATUS_INVITE_SENT,Ce.debug('emit "sending" [request:%o]',this._request),this.emit("sending",{request:this._request}),u.send()}).catch(s=>{this._status!==xe.STATUS_TERMINATED&&Ce.warn(s)})}_getDTMFRTPSender(){const t=this._connection.getSenders().find(r=>r.track&&r.track.kind==="audio");if(!(t&&t.dtmf)){Ce.warn("sendDTMF() | no local audio track to send DTMF with");return}return t.dtmf}_receiveInviteResponse(t){if(Ce.debug("receiveInviteResponse()"),this._dialog&&t.status_code>=200&&t.status_code<=299)if(this._dialog.id.call_id===t.call_id&&this._dialog.id.local_tag===t.from_tag&&this._dialog.id.remote_tag===t.to_tag){this.sendRequest(Ke.ACK);return}else{const r=new Ru(this,t,"UAC");if(r.error!==void 0){Ce.debug(r.error);return}this.sendRequest(Ke.ACK),this.sendRequest(Ke.BYE);return}if(this._is_canceled){t.status_code>=100&&t.status_code<200?this._request.cancel(this._cancel_reason):t.status_code>=200&&t.status_code<299&&this._acceptAndTerminate(t);return}if(!(this._status!==xe.STATUS_INVITE_SENT&&this._status!==xe.STATUS_1XX_RECEIVED))switch(!0){case/^100$/.test(t.status_code):this._status=xe.STATUS_1XX_RECEIVED;break;case/^1[0-9]{2}$/.test(t.status_code):{if(!t.to_tag){Ce.debug("1xx response received without to tag");break}if(t.hasHeader("contact")&&!this._createDialog(t,"UAC",!0))break;if(this._status=xe.STATUS_1XX_RECEIVED,!t.body){this._progress("remote",t);break}const r={originator:"remote",type:"answer",sdp:t.body};Ce.debug('emit "sdp"'),this.emit("sdp",r);const l=new RTCSessionDescription({type:"answer",sdp:r.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(l)).then(()=>this._progress("remote",t)).catch(u=>{Ce.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',u),this.emit("peerconnection:setremotedescriptionfailed",u)});break}case/^2[0-9]{2}$/.test(t.status_code):{if(this._status=xe.STATUS_CONFIRMED,!t.body){this._acceptAndTerminate(t,400,Ke.causes.MISSING_SDP),this._failed("remote",t,Ke.causes.BAD_MEDIA_DESCRIPTION);break}if(!this._createDialog(t,"UAC"))break;const r={originator:"remote",type:"answer",sdp:t.body};Ce.debug('emit "sdp"'),this.emit("sdp",r);const l=new RTCSessionDescription({type:"answer",sdp:r.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>{if(this._connection.signalingState==="stable")return this._connection.createOffer(this._rtcOfferConstraints).then(u=>this._connection.setLocalDescription(u)).catch(u=>{this._acceptAndTerminate(t,500,u.toString()),this._failed("local",t,Ke.causes.WEBRTC_ERROR)})}).then(()=>{this._connection.setRemoteDescription(l).then(()=>{this._handleSessionTimersInIncomingResponse(t),this._accepted("remote",t),this.sendRequest(Ke.ACK),this._confirmed("local",null)}).catch(u=>{this._acceptAndTerminate(t,488,"Not Acceptable Here"),this._failed("remote",t,Ke.causes.BAD_MEDIA_DESCRIPTION),Ce.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',u),this.emit("peerconnection:setremotedescriptionfailed",u)})});break}default:{const r=Xt.sipErrorCause(t.status_code);this._failed("remote",t,r)}}}_sendReinvite(t={}){Ce.debug("sendReinvite()");const r=Xt.cloneArray(t.extraHeaders),l=Xt.cloneObject(t.eventHandlers),u=t.rtcOfferConstraints||this._rtcOfferConstraints||null;let s=!1;r.push(`Contact: ${this._contact}`),r.push("Content-Type: application/sdp"),this._sessionTimers.running&&r.push(`Session-Expires: ${this._sessionTimers.currentExpires};refresher=${this._sessionTimers.refresher?"uac":"uas"}`),this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._createLocalDescription("offer",u)).then(_=>{_=this._mangleOffer(_);const v={originator:"local",type:"offer",sdp:_};Ce.debug('emit "sdp"'),this.emit("sdp",v),this.sendRequest(Ke.INVITE,{extraHeaders:r,body:_,eventHandlers:{onSuccessResponse:C=>{n.call(this,C),s=!0},onErrorResponse:C=>{g.call(this,C)},onTransportError:()=>{this.onTransportError()},onRequestTimeout:()=>{this.onRequestTimeout()},onDialogError:()=>{this.onDialogError()}}})}).catch(()=>{g()});function n(_){if(this._status===xe.STATUS_TERMINATED||(this.sendRequest(Ke.ACK),s))return;if(this._handleSessionTimersInIncomingResponse(_),_.body){if(!_.hasHeader("Content-Type")||_.getHeader("Content-Type").toLowerCase()!=="application/sdp"){g.call(this);return}}else{g.call(this);return}const v={originator:"remote",type:"answer",sdp:_.body};Ce.debug('emit "sdp"'),this.emit("sdp",v);const C=new RTCSessionDescription({type:"answer",sdp:v.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(C)).then(()=>{l.succeeded&&l.succeeded(_)}).catch(R=>{g.call(this),Ce.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',R),this.emit("peerconnection:setremotedescriptionfailed",R)})}function g(_){l.failed&&l.failed(_)}}_sendUpdate(t={}){Ce.debug("sendUpdate()");const r=Xt.cloneArray(t.extraHeaders),l=Xt.cloneObject(t.eventHandlers),u=t.rtcOfferConstraints||this._rtcOfferConstraints||null,s=t.sdpOffer||!1;let n=!1;r.push(`Contact: ${this._contact}`),this._sessionTimers.running&&r.push(`Session-Expires: ${this._sessionTimers.currentExpires};refresher=${this._sessionTimers.refresher?"uac":"uas"}`),s?(r.push("Content-Type: application/sdp"),this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._createLocalDescription("offer",u)).then(v=>{v=this._mangleOffer(v);const C={originator:"local",type:"offer",sdp:v};Ce.debug('emit "sdp"'),this.emit("sdp",C),this.sendRequest(Ke.UPDATE,{extraHeaders:r,body:v,eventHandlers:{onSuccessResponse:R=>{g.call(this,R),n=!0},onErrorResponse:R=>{_.call(this,R)},onTransportError:()=>{this.onTransportError()},onRequestTimeout:()=>{this.onRequestTimeout()},onDialogError:()=>{this.onDialogError()}}})}).catch(()=>{_.call(this)})):this.sendRequest(Ke.UPDATE,{extraHeaders:r,eventHandlers:{onSuccessResponse:v=>{g.call(this,v)},onErrorResponse:v=>{_.call(this,v)},onTransportError:()=>{this.onTransportError()},onRequestTimeout:()=>{this.onRequestTimeout()},onDialogError:()=>{this.onDialogError()}}});function g(v){if(this._status!==xe.STATUS_TERMINATED&&!n)if(this._handleSessionTimersInIncomingResponse(v),s){if(v.body){if(!v.hasHeader("Content-Type")||v.getHeader("Content-Type").toLowerCase()!=="application/sdp"){_.call(this);return}}else{_.call(this);return}const C={originator:"remote",type:"answer",sdp:v.body};Ce.debug('emit "sdp"'),this.emit("sdp",C);const R=new RTCSessionDescription({type:"answer",sdp:C.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(R)).then(()=>{l.succeeded&&l.succeeded(v)}).catch(D=>{_.call(this),Ce.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',D),this.emit("peerconnection:setremotedescriptionfailed",D)})}else l.succeeded&&l.succeeded(v)}function _(v){l.failed&&l.failed(v)}}_acceptAndTerminate(t,r,l){Ce.debug("acceptAndTerminate()");const u=[];r&&(l=l||Ke.REASON_PHRASE[r]||"",u.push(`Reason: SIP ;cause=${r}; text="${l}"`)),(this._dialog||this._createDialog(t,"UAC"))&&(this.sendRequest(Ke.ACK),this.sendRequest(Ke.BYE,{extraHeaders:u})),this._status=xe.STATUS_TERMINATED}_mangleOffer(t){if(!this._localHold&&!this._remoteHold)return t;if(t=j_.parse(t),this._localHold&&!this._remoteHold){Ce.debug("mangleOffer() | me on hold, mangling offer");for(const r of t.media)$u.indexOf(r.type)!==-1&&(r.direction?r.direction==="sendrecv"?r.direction="sendonly":r.direction==="recvonly"&&(r.direction="inactive"):r.direction="sendonly")}else if(this._localHold&&this._remoteHold){Ce.debug("mangleOffer() | both on hold, mangling offer");for(const r of t.media)$u.indexOf(r.type)!==-1&&(r.direction="inactive")}else if(this._remoteHold){Ce.debug("mangleOffer() | remote on hold, mangling offer");for(const r of t.media)$u.indexOf(r.type)!==-1&&(r.direction?r.direction==="sendrecv"?r.direction="recvonly":r.direction==="recvonly"&&(r.direction="inactive"):r.direction="recvonly")}return j_.write(t)}_setLocalMediaStatus(){let t=!0,r=!0;(this._localHold||this._remoteHold)&&(t=!1,r=!1),this._audioMuted&&(t=!1),this._videoMuted&&(r=!1),this._toggleMuteAudio(!t),this._toggleMuteVideo(!r)}_handleSessionTimersInIncomingRequest(t,r){if(!this._sessionTimers.enabled)return;let l;t.session_expires&&t.session_expires>=Ke.MIN_SESSION_EXPIRES?(this._sessionTimers.currentExpires=t.session_expires,l=t.session_expires_refresher||"uas"):(this._sessionTimers.currentExpires=this._sessionTimers.defaultExpires,l="uas"),r.push(`Session-Expires: ${this._sessionTimers.currentExpires};refresher=${l}`),this._sessionTimers.refresher=l==="uas",this._runSessionTimer()}_handleSessionTimersInIncomingResponse(t){if(!this._sessionTimers.enabled)return;let r;t.session_expires&&t.session_expires>=Ke.MIN_SESSION_EXPIRES?(this._sessionTimers.currentExpires=t.session_expires,r=t.session_expires_refresher||"uac"):(this._sessionTimers.currentExpires=this._sessionTimers.defaultExpires,r="uac"),this._sessionTimers.refresher=r==="uac",this._runSessionTimer()}_runSessionTimer(){const t=this._sessionTimers.currentExpires;this._sessionTimers.running=!0,clearTimeout(this._sessionTimers.timer),this._sessionTimers.refresher?this._sessionTimers.timer=setTimeout(()=>{this._status!==xe.STATUS_TERMINATED&&this._isReadyToReOffer()&&(Ce.debug("runSessionTimer() | sending session refresh request"),this._sessionTimers.refreshMethod===Ke.UPDATE?this._sendUpdate():this._sendReinvite())},t*500):this._sessionTimers.timer=setTimeout(()=>{this._status!==xe.STATUS_TERMINATED&&(Ce.warn("runSessionTimer() | timer expired, terminating the session"),this.terminate({cause:Ke.causes.REQUEST_TIMEOUT,status_code:408,reason_phrase:"Session Timer Expired"}))},t*1100)}_toggleMuteAudio(t){const r=this._connection.getSenders().filter(l=>l.track&&l.track.kind==="audio");for(const l of r)l.track.enabled=!t}_toggleMuteVideo(t){const r=this._connection.getSenders().filter(l=>l.track&&l.track.kind==="video");for(const l of r)l.track.enabled=!t}_newRTCSession(t,r){Ce.debug("newRTCSession()"),this._ua.newRTCSession(this,{originator:t,session:this,request:r})}_connecting(t){Ce.debug("session connecting"),Ce.debug('emit "connecting"'),this.emit("connecting",{request:t})}_progress(t,r){Ce.debug("session progress"),Ce.debug('emit "progress"'),this.emit("progress",{originator:t,response:r||null})}_accepted(t,r){Ce.debug("session accepted"),this._start_time=new Date,Ce.debug('emit "accepted"'),this.emit("accepted",{originator:t,response:r||null})}_confirmed(t,r){Ce.debug("session confirmed"),this._is_confirmed=!0,Ce.debug('emit "confirmed"'),this.emit("confirmed",{originator:t,ack:r||null})}_ended(t,r,l){Ce.debug("session ended"),this._end_time=new Date,this._close(),Ce.debug('emit "ended"'),this.emit("ended",{originator:t,message:r||null,cause:l})}_failed(t,r,l){Ce.debug("session failed"),Ce.debug('emit "_failed"'),this.emit("_failed",{originator:t,message:r||null,cause:l}),this._close(),Ce.debug('emit "failed"'),this.emit("failed",{originator:t,message:r||null,cause:l})}_onhold(t){Ce.debug("session onhold"),this._setLocalMediaStatus(),Ce.debug('emit "hold"'),this.emit("hold",{originator:t})}_onunhold(t){Ce.debug("session onunhold"),this._setLocalMediaStatus(),Ce.debug('emit "unhold"'),this.emit("unhold",{originator:t})}_onmute({audio:t,video:r}){Ce.debug("session onmute"),this._setLocalMediaStatus(),Ce.debug('emit "muted"'),this.emit("muted",{audio:t,video:r})}_onunmute({audio:t,video:r}){Ce.debug("session onunmute"),this._setLocalMediaStatus(),Ce.debug('emit "unmuted"'),this.emit("unmuted",{audio:t,video:r})}};const $E=Ht(Y_),xE=ys.EventEmitter,OE=gs,pd=Et,DE=Ds,uo=xs(),kE=_l,J_=Pn,NE=Nn(),xu=new OE("Message");var ME=class extends xE{constructor(t){super(),this._ua=t,this._request=null,this._closed=!1,this._direction=null,this._local_identity=null,this._remote_identity=null,this._is_replied=!1,this._data={}}get direction(){return this._direction}get local_identity(){return this._local_identity}get remote_identity(){return this._remote_identity}send(t,r,l={}){const u=t;if(t===void 0||r===void 0)throw new TypeError("Not enough arguments");if(t=this._ua.normalizeTarget(t),!t)throw new TypeError(`Invalid target: ${u}`);const s=uo.cloneArray(l.extraHeaders),n=uo.cloneObject(l.eventHandlers),g=l.contentType||"text/plain",_={};l.fromUserName&&(_.from_uri=new NE("sip",l.fromUserName,this._ua.configuration.uri.host),s.push(`P-Preferred-Identity: ${this._ua.configuration.uri.toString()}`)),l.fromDisplayName&&(_.from_display_name=l.fromDisplayName);for(const C in n)Object.prototype.hasOwnProperty.call(n,C)&&this.on(C,n[C]);s.push(`Content-Type: ${g}`),this._request=new DE.OutgoingRequest(pd.MESSAGE,t,this._ua,_,s),r&&(this._request.body=r);const v=new kE(this._ua,this._request,{onRequestTimeout:()=>{this._onRequestTimeout()},onTransportError:()=>{this._onTransportError()},onReceiveResponse:C=>{this._receiveResponse(C)}});this._newMessage("local",this._request),v.send()}init_incoming(t){this._request=t,this._newMessage("remote",t),this._is_replied||(this._is_replied=!0,t.reply(200)),this._close()}accept(t={}){const r=uo.cloneArray(t.extraHeaders),l=t.body;if(this._direction!=="incoming")throw new J_.NotSupportedError('"accept" not supported for outgoing Message');if(this._is_replied)throw new Error("incoming Message already replied");this._is_replied=!0,this._request.reply(200,null,r,l)}reject(t={}){const r=t.status_code||480,l=t.reason_phrase,u=uo.cloneArray(t.extraHeaders),s=t.body;if(this._direction!=="incoming")throw new J_.NotSupportedError('"reject" not supported for outgoing Message');if(this._is_replied)throw new Error("incoming Message already replied");if(r<300||r>=700)throw new TypeError(`Invalid status_code: ${r}`);this._is_replied=!0,this._request.reply(r,l,u,s)}_receiveResponse(t){if(!this._closed)switch(!0){case/^1[0-9]{2}$/.test(t.status_code):break;case/^2[0-9]{2}$/.test(t.status_code):this._succeeded("remote",t);break;default:{const r=uo.sipErrorCause(t.status_code);this._failed("remote",t,r);break}}}_onRequestTimeout(){this._closed||this._failed("system",null,pd.causes.REQUEST_TIMEOUT)}_onTransportError(){this._closed||this._failed("system",null,pd.causes.CONNECTION_ERROR)}_close(){this._closed=!0,this._ua.destroyMessage(this)}_newMessage(t,r){t==="remote"?(this._direction="incoming",this._local_identity=r.to,this._remote_identity=r.from):t==="local"&&(this._direction="outgoing",this._local_identity=r.from,this._remote_identity=r.to),this._ua.newMessage(this,{originator:t,message:this,request:r})}_failed(t,r,l){xu.debug("MESSAGE failed"),this._close(),xu.debug('emit "failed"'),this.emit("failed",{originator:t,response:r||null,cause:l})}_succeeded(t,r){xu.debug("MESSAGE succeeded"),this._close(),xu.debug('emit "succeeded"'),this.emit("succeeded",{originator:t,response:r})}};const UE=ys.EventEmitter,PE=gs,md=Et,LE=Ds,co=xs(),HE=_l,Q_=Pn,Ou=new PE("Options");var FE=class extends UE{constructor(t){super(),this._ua=t,this._request=null,this._closed=!1,this._direction=null,this._local_identity=null,this._remote_identity=null,this._is_replied=!1,this._data={}}get direction(){return this._direction}get local_identity(){return this._local_identity}get remote_identity(){return this._remote_identity}send(t,r,l={}){const u=t;if(t===void 0)throw new TypeError("A target is required for OPTIONS");if(t=this._ua.normalizeTarget(t),!t)throw new TypeError(`Invalid target: ${u}`);const s=co.cloneArray(l.extraHeaders),n=co.cloneObject(l.eventHandlers),g=l.contentType||"application/sdp";for(const v in n)Object.prototype.hasOwnProperty.call(n,v)&&this.on(v,n[v]);s.push(`Content-Type: ${g}`),this._request=new LE.OutgoingRequest(md.OPTIONS,t,this._ua,null,s),r&&(this._request.body=r);const _=new HE(this._ua,this._request,{onRequestTimeout:()=>{this._onRequestTimeout()},onTransportError:()=>{this._onTransportError()},onReceiveResponse:v=>{this._receiveResponse(v)}});this._newOptions("local",this._request),_.send()}init_incoming(t){this._request=t,this._newOptions("remote",t),this._is_replied||(this._is_replied=!0,t.reply(200)),this._close()}accept(t={}){const r=co.cloneArray(t.extraHeaders),l=t.body;if(this._direction!=="incoming")throw new Q_.NotSupportedError('"accept" not supported for outgoing Options');if(this._is_replied)throw new Error("incoming Options already replied");this._is_replied=!0,this._request.reply(200,null,r,l)}reject(t={}){const r=t.status_code||480,l=t.reason_phrase,u=co.cloneArray(t.extraHeaders),s=t.body;if(this._direction!=="incoming")throw new Q_.NotSupportedError('"reject" not supported for outgoing Options');if(this._is_replied)throw new Error("incoming Options already replied");if(r<300||r>=700)throw new TypeError(`Invalid status_code: ${r}`);this._is_replied=!0,this._request.reply(r,l,u,s)}_receiveResponse(t){if(!this._closed)switch(!0){case/^1[0-9]{2}$/.test(t.status_code):break;case/^2[0-9]{2}$/.test(t.status_code):this._succeeded("remote",t);break;default:{const r=co.sipErrorCause(t.status_code);this._failed("remote",t,r);break}}}_onRequestTimeout(){this._closed||this._failed("system",null,md.causes.REQUEST_TIMEOUT)}_onTransportError(){this._closed||this._failed("system",null,md.causes.CONNECTION_ERROR)}_close(){this._closed=!0,this._ua.destroyMessage(this)}_newOptions(t,r){t==="remote"?(this._direction="incoming",this._local_identity=r.to,this._remote_identity=r.from):t==="local"&&(this._direction="outgoing",this._local_identity=r.from,this._remote_identity=r.to),this._ua.newOptions(this,{originator:t,message:this,request:r})}_failed(t,r,l){Ou.debug("OPTIONS failed"),this._close(),Ou.debug('emit "failed"'),this.emit("failed",{originator:t,response:r||null,cause:l})}_succeeded(t,r){Ou.debug("OPTIONS succeeded"),this._close(),Ou.debug('emit "succeeded"'),this.emit("succeeded",{originator:t,response:r})}},gd={};const BE=gs,vd=xs(),zE=Dr(),fo=new BE("Socket");gd.isSocket=f=>{if(Array.isArray(f))return!1;if(typeof f>"u")return fo.warn("undefined JsSIP.Socket instance"),!1;try{if(!vd.isString(f.url))throw fo.warn("missing or invalid JsSIP.Socket url property"),new Error("Missing or invalid JsSIP.Socket url property");if(!vd.isString(f.via_transport))throw fo.warn("missing or invalid JsSIP.Socket via_transport property"),new Error("Missing or invalid JsSIP.Socket via_transport property");if(zE.parse(f.sip_uri,"SIP_URI")===-1)throw fo.warn("missing or invalid JsSIP.Socket sip_uri property"),new Error("missing or invalid JsSIP.Socket sip_uri property")}catch{return!1}try{["connect","disconnect","send"].forEach(t=>{if(!vd.isFunction(f[t]))throw fo.warn(`missing or invalid JsSIP.Socket method: ${t}`),new Error(`Missing or invalid JsSIP.Socket method: ${t}`)})}catch{return!1}return!0};const VE=gs,qE=gd,X_=Et,nr=new VE("Transport"),Cr={STATUS_CONNECTED:0,STATUS_CONNECTING:1,STATUS_DISCONNECTED:2,SOCKET_STATUS_READY:0,SOCKET_STATUS_ERROR:1,recovery_options:{min_interval:X_.CONNECTION_RECOVERY_MIN_INTERVAL,max_interval:X_.CONNECTION_RECOVERY_MAX_INTERVAL}};var Z_=class{constructor(t,r=Cr.recovery_options){nr.debug("new()"),this.status=Cr.STATUS_DISCONNECTED,this.socket=null,this.sockets=[],this.recovery_options=r,this.recover_attempts=0,this.recovery_timer=null,this.close_requested=!1;try{this.textDecoder=new TextDecoder("utf8")}catch(l){nr.warn(`cannot use TextDecoder: ${l}`)}if(typeof t>"u")throw new TypeError("Invalid argument. undefined 'sockets' argument");t instanceof Array||(t=[t]),t.forEach(function(l){if(!qE.isSocket(l.socket))throw new TypeError("Invalid argument. invalid 'JsSIP.Socket' instance");if(l.weight&&!Number(l.weight))throw new TypeError("Invalid argument. 'weight' attribute is not a number");this.sockets.push({socket:l.socket,weight:l.weight||0,status:Cr.SOCKET_STATUS_READY})},this),this._getSocket()}get via_transport(){return this.socket.via_transport}get url(){return this.socket.url}get sip_uri(){return this.socket.sip_uri}connect(){if(nr.debug("connect()"),this.isConnected()){nr.debug("Transport is already connected");return}else if(this.isConnecting()){nr.debug("Transport is connecting");return}this.close_requested=!1,this.status=Cr.STATUS_CONNECTING,this.onconnecting({socket:this.socket,attempts:this.recover_attempts}),this.close_requested||(this.socket.onconnect=this._onConnect.bind(this),this.socket.ondisconnect=this._onDisconnect.bind(this),this.socket.ondata=this._onData.bind(this),this.socket.connect())}disconnect(){nr.debug("close()"),this.close_requested=!0,this.recover_attempts=0,this.status=Cr.STATUS_DISCONNECTED,this.recovery_timer!==null&&(clearTimeout(this.recovery_timer),this.recovery_timer=null),this.socket.onconnect=()=>{},this.socket.ondisconnect=()=>{},this.socket.ondata=()=>{},this.socket.disconnect(),this.ondisconnect({socket:this.socket,error:!1})}send(t){if(nr.debug("send()"),!this.isConnected())return nr.warn("unable to send message, transport is not connected"),!1;const r=t.toString();return nr.debug(`sending message:
114
+ `);u.length>=1&&r.test(u[0])&&(this._tone=u[0].replace(r,"$2")),u.length>=2&&l.test(u[1])&&(this._duration=parseInt(u[1].replace(l,"$2"),10))}this._duration||(this._duration=P_.DEFAULT_DURATION),this._tone?this._session.newDTMF({originator:"remote",dtmf:this,request:t}):cE.debug("invalid INFO DTMF received, discarded")}},fd.exports.C=P_;var L_=fd.exports;const dE=Ht(L_),fE=ys.EventEmitter,hE=Et,_E=Pn,pE=xs();var H_=class extends fE{constructor(t){super(),this._session=t,this._direction=null,this._contentType=null,this._body=null}get contentType(){return this._contentType}get body(){return this._body}send(t,r,l={}){if(this._direction="outgoing",t===void 0)throw new TypeError("Not enough arguments");if(this._session.status!==this._session.C.STATUS_CONFIRMED&&this._session.status!==this._session.C.STATUS_WAITING_FOR_ACK)throw new _E.InvalidStateError(this._session.status);this._contentType=t,this._body=r;const u=pE.cloneArray(l.extraHeaders);u.push(`Content-Type: ${t}`),this._session.newInfo({originator:"local",info:this,request:this.request}),this._session.sendRequest(hE.INFO,{extraHeaders:u,eventHandlers:{onSuccessResponse:s=>{this.emit("succeeded",{originator:"remote",response:s})},onErrorResponse:s=>{this.emit("failed",{originator:"remote",response:s})},onTransportError:()=>{this._session.onTransportError()},onRequestTimeout:()=>{this._session.onRequestTimeout()},onDialogError:()=>{this._session.onDialogError()}},body:r})}init_incoming(t){this._direction="incoming",this.request=t,t.reply(200),this._contentType=t.hasHeader("Content-Type")?t.getHeader("Content-Type").toLowerCase():void 0,this._body=t.body,this._session.newInfo({originator:"remote",info:this,request:t})}};const hd=Ht(H_),mE=gs,F_=Et,gE=new mE("RTCSession:ReferNotifier"),_d={event_type:"refer",body_type:"message/sipfrag;version=2.0",expires:300};var B_=class{constructor(t,r,l){this._session=t,this._id=r,this._expires=l||_d.expires,this._active=!0,this.notify(100)}notify(t,r){if(gE.debug("notify()"),this._active===!1)return;r=r||F_.REASON_PHRASE[t]||"";let l;t>=200?l="terminated;reason=noresource":l=`active;expires=${this._expires}`,this._session.sendRequest(F_.NOTIFY,{extraHeaders:[`Event: ${_d.event_type};id=${this._id}`,`Subscription-State: ${l}`,`Content-Type: ${_d.body_type}`],body:`SIP/2.0 ${t} ${r}`,eventHandlers:{onErrorResponse(){this._active=!1}}})}};const vE=Ht(B_),yE=ys.EventEmitter,TE=gs,lo=Et,SE=Dr(),z_=xs(),Ea=new TE("RTCSession:ReferSubscriber");var V_=class extends yE{constructor(t){super(),this._id=null,this._session=t}get id(){return this._id}sendRefer(t,r={}){Ea.debug("sendRefer()");const l=z_.cloneArray(r.extraHeaders),u=z_.cloneObject(r.eventHandlers);for(const _ in u)Object.prototype.hasOwnProperty.call(u,_)&&this.on(_,u[_]);let s=null;r.replaces&&(s=r.replaces._request.call_id,s+=`;to-tag=${r.replaces._to_tag}`,s+=`;from-tag=${r.replaces._from_tag}`,s=encodeURIComponent(s));const n=`Refer-To: <${t}${s?`?Replaces=${s}`:""}>`;if(l.push(n),!l.some(_=>_.toLowerCase().startsWith("referred-by:"))){const _=`Referred-By: <${this._session._ua._configuration.uri._scheme}:${this._session._ua._configuration.uri._user}@${this._session._ua._configuration.uri._host}>`;l.push(_)}l.push(`Contact: ${this._session.contact}`);const g=this._session.sendRequest(lo.REFER,{extraHeaders:l,eventHandlers:{onSuccessResponse:_=>{this._requestSucceeded(_)},onErrorResponse:_=>{this._requestFailed(_,lo.causes.REJECTED)},onTransportError:()=>{this._requestFailed(null,lo.causes.CONNECTION_ERROR)},onRequestTimeout:()=>{this._requestFailed(null,lo.causes.REQUEST_TIMEOUT)},onDialogError:()=>{this._requestFailed(null,lo.causes.DIALOG_ERROR)}}});this._id=g.cseq}receiveNotify(t){if(Ea.debug("receiveNotify()"),!t.body)return;const r=SE.parse(t.body.trim().split(`\r
115
+ `,1)[0],"Status_Line");if(r===-1){Ea.debug(`receiveNotify() | error parsing NOTIFY body: "${t.body}"`);return}switch(!0){case/^100$/.test(r.status_code):this.emit("trying",{request:t,status_line:r});break;case/^1[0-9]{2}$/.test(r.status_code):this.emit("progress",{request:t,status_line:r});break;case/^2[0-9]{2}$/.test(r.status_code):this.emit("accepted",{request:t,status_line:r});break;default:this.emit("failed",{request:t,status_line:r});break}}_requestSucceeded(t){Ea.debug("REFER succeeded"),Ea.debug('emit "requestSucceeded"'),this.emit("requestSucceeded",{response:t})}_requestFailed(t,r){Ea.debug("REFER failed"),Ea.debug('emit "requestFailed"'),this.emit("requestFailed",{response:t||null,cause:r})}};const bE=Ht(V_),wE=ys.EventEmitter,q_=sr,EE=gs,Ke=Et,Ca=Pn,j_=hl,Xt=xs(),oo=nd,CE=Ds,Ru=M_,AE=_l,_r=L_,G_=H_,IE=B_,RE=V_,W_=Nn(),Ce=new EE("RTCSession"),xe={STATUS_NULL:0,STATUS_INVITE_SENT:1,STATUS_1XX_RECEIVED:2,STATUS_INVITE_RECEIVED:3,STATUS_WAITING_FOR_ANSWER:4,STATUS_ANSWERED:5,STATUS_WAITING_FOR_ACK:6,STATUS_CANCELED:7,STATUS_TERMINATED:8,STATUS_CONFIRMED:9},$u=["audio","video"];var K_=class Bf extends wE{static get C(){return xe}constructor(t){Ce.debug("new"),super(),this._id=null,this._ua=t,this._status=xe.STATUS_NULL,this._dialog=null,this._earlyDialogs={},this._contact=null,this._from_tag=null,this._to_tag=null,this._connection=null,this._connectionPromiseQueue=Promise.resolve(),this._request=null,this._is_canceled=!1,this._cancel_reason="",this._is_confirmed=!1,this._late_sdp=!1,this._rtcOfferConstraints=null,this._rtcAnswerConstraints=null,this._localMediaStream=null,this._localMediaStreamLocallyGenerated=!1,this._rtcReady=!0,this._iceReady=!1,this._timers={ackTimer:null,expiresTimer:null,invite2xxTimer:null,userNoAnswerTimer:null},this._direction=null,this._local_identity=null,this._remote_identity=null,this._start_time=null,this._end_time=null,this._tones=null,this._audioMuted=!1,this._videoMuted=!1,this._localHold=!1,this._remoteHold=!1,this._sessionTimers={enabled:this._ua.configuration.session_timers,refreshMethod:this._ua.configuration.session_timers_refresh_method,defaultExpires:Ke.SESSION_EXPIRES,currentExpires:null,running:!1,refresher:!1,timer:null},this._referSubscribers={},this._data={}}get C(){return xe}get causes(){return Ke.causes}get id(){return this._id}get connection(){return this._connection}get contact(){return this._contact}get direction(){return this._direction}get local_identity(){return this._local_identity}get remote_identity(){return this._remote_identity}get start_time(){return this._start_time}get end_time(){return this._end_time}get data(){return this._data}set data(t){this._data=t}get status(){return this._status}isInProgress(){switch(this._status){case xe.STATUS_NULL:case xe.STATUS_INVITE_SENT:case xe.STATUS_1XX_RECEIVED:case xe.STATUS_INVITE_RECEIVED:case xe.STATUS_WAITING_FOR_ANSWER:return!0;default:return!1}}isEstablished(){switch(this._status){case xe.STATUS_ANSWERED:case xe.STATUS_WAITING_FOR_ACK:case xe.STATUS_CONFIRMED:return!0;default:return!1}}isEnded(){switch(this._status){case xe.STATUS_CANCELED:case xe.STATUS_TERMINATED:return!0;default:return!1}}isMuted(){return{audio:this._audioMuted,video:this._videoMuted}}isOnHold(){return{local:this._localHold,remote:this._remoteHold}}connect(t,r={},l){Ce.debug("connect()");const u=t,s=Xt.cloneObject(r.eventHandlers),n=Xt.cloneArray(r.extraHeaders),g=Xt.cloneObject(r.mediaConstraints,{audio:!0,video:!0}),_=r.mediaStream||null,v=Xt.cloneObject(r.pcConfig,{iceServers:[]}),C=r.rtcConstraints||null,R=r.rtcOfferConstraints||null;if(this._rtcOfferConstraints=R,this._rtcAnswerConstraints=r.rtcAnswerConstraints||null,this._data=r.data||this._data,t===void 0)throw new TypeError("Not enough arguments");if(this._status!==xe.STATUS_NULL)throw new Ca.InvalidStateError(this._status);if(!window.RTCPeerConnection)throw new Ca.NotSupportedError("WebRTC not supported");if(t=this._ua.normalizeTarget(t),!t)throw new TypeError(`Invalid target: ${u}`);this._sessionTimers.enabled&&Xt.isDecimal(r.sessionTimersExpires)&&(r.sessionTimersExpires>=Ke.MIN_SESSION_EXPIRES?this._sessionTimers.defaultExpires=r.sessionTimersExpires:this._sessionTimers.defaultExpires=Ke.SESSION_EXPIRES);for(const F in s)Object.prototype.hasOwnProperty.call(s,F)&&this.on(F,s[F]);this._from_tag=Xt.newTag();const D=r.anonymous||!1,H={from_tag:this._from_tag};this._contact=this._ua.contact.toString({anonymous:D,outbound:!0}),D?(H.from_display_name="Anonymous",H.from_uri=new W_("sip","anonymous","anonymous.invalid"),n.push(`P-Preferred-Identity: ${this._ua.configuration.uri.toString()}`),n.push("Privacy: id")):r.fromUserName&&(H.from_uri=new W_("sip",r.fromUserName,this._ua.configuration.uri.host),n.push(`P-Preferred-Identity: ${this._ua.configuration.uri.toString()}`)),r.fromDisplayName&&(H.from_display_name=r.fromDisplayName),n.push(`Contact: ${this._contact}`),n.push("Content-Type: application/sdp"),this._sessionTimers.enabled&&n.push(`Session-Expires: ${this._sessionTimers.defaultExpires}${this._ua.configuration.session_timers_force_refresher?";refresher=uac":""}`),this._request=new CE.InitialOutgoingInviteRequest(t,this._ua,H,n),this._id=this._request.call_id+this._from_tag,this._createRTCConnection(v,C),this._direction="outgoing",this._local_identity=this._request.from,this._remote_identity=this._request.to,l&&l(this),this._newRTCSession("local",this._request),this._sendInitialRequest(g,R,_)}init_incoming(t,r){Ce.debug("init_incoming()");let l;const u=t.hasHeader("Content-Type")?t.getHeader("Content-Type").toLowerCase():void 0;if(t.body&&u!=="application/sdp"){t.reply(415);return}if(this._status=xe.STATUS_INVITE_RECEIVED,this._from_tag=t.from_tag,this._id=t.call_id+this._from_tag,this._request=t,this._contact=this._ua.contact.toString(),t.hasHeader("expires")&&(l=t.getHeader("expires")*1e3),t.to_tag=Xt.newTag(),!this._createDialog(t,"UAS",!0)){t.reply(500,"Missing Contact header field");return}t.body?this._late_sdp=!1:this._late_sdp=!0,this._status=xe.STATUS_WAITING_FOR_ANSWER,this._timers.userNoAnswerTimer=setTimeout(()=>{t.reply(408),this._failed("local",null,Ke.causes.NO_ANSWER)},this._ua.configuration.no_answer_timeout),l&&(this._timers.expiresTimer=setTimeout(()=>{this._status===xe.STATUS_WAITING_FOR_ANSWER&&(t.reply(487),this._failed("system",null,Ke.causes.EXPIRES))},l)),this._direction="incoming",this._local_identity=t.to,this._remote_identity=t.from,r&&r(this),this._newRTCSession("remote",t),this._status!==xe.STATUS_TERMINATED&&(t.reply(180,null,[`Contact: ${this._contact}`]),this._progress("local",null))}answer(t={}){Ce.debug("answer()");const r=this._request,l=Xt.cloneArray(t.extraHeaders),u=Xt.cloneObject(t.mediaConstraints),s=t.mediaStream||null,n=Xt.cloneObject(t.pcConfig,{iceServers:[]}),g=t.rtcConstraints||null,_=t.rtcAnswerConstraints||null,v=Xt.cloneObject(t.rtcOfferConstraints);let C,R=!1,D=!1,H=!1,F=!1;if(this._rtcAnswerConstraints=_,this._rtcOfferConstraints=t.rtcOfferConstraints||null,this._data=t.data||this._data,this._direction!=="incoming")throw new Ca.NotSupportedError('"answer" not supported for outgoing RTCSession');if(this._status!==xe.STATUS_WAITING_FOR_ANSWER)throw new Ca.InvalidStateError(this._status);if(this._sessionTimers.enabled&&Xt.isDecimal(t.sessionTimersExpires)&&(t.sessionTimersExpires>=Ke.MIN_SESSION_EXPIRES?this._sessionTimers.defaultExpires=t.sessionTimersExpires:this._sessionTimers.defaultExpires=Ke.SESSION_EXPIRES),this._status=xe.STATUS_ANSWERED,!this._createDialog(r,"UAS")){r.reply(500,"Error creating dialog");return}clearTimeout(this._timers.userNoAnswerTimer),l.unshift(`Contact: ${this._contact}`);const q=r.parseSDP();Array.isArray(q.media)||(q.media=[q.media]);for(const G of q.media)G.type==="audio"&&(R=!0,(!G.direction||G.direction==="sendrecv")&&(H=!0)),G.type==="video"&&(D=!0,(!G.direction||G.direction==="sendrecv")&&(F=!0));if(s&&u.audio===!1){C=s.getAudioTracks();for(const G of C)s.removeTrack(G)}if(s&&u.video===!1){C=s.getVideoTracks();for(const G of C)s.removeTrack(G)}!s&&u.audio===void 0&&(u.audio=H),!s&&u.video===void 0&&(u.video=F),!s&&!R&&!v.offerToReceiveAudio&&(u.audio=!1),!s&&!D&&!v.offerToReceiveVideo&&(u.video=!1),this._createRTCConnection(n,g),Promise.resolve().then(()=>{if(s)return s;if(u.audio||u.video)return this._localMediaStreamLocallyGenerated=!0,navigator.mediaDevices.getUserMedia(u).catch(G=>{throw this._status===xe.STATUS_TERMINATED?new Error("terminated"):(r.reply(480),this._failed("local",null,Ke.causes.USER_DENIED_MEDIA_ACCESS),Ce.warn('emit "getusermediafailed" [error:%o]',G),this.emit("getusermediafailed",G),new Error("getUserMedia() failed"))})}).then(G=>{if(this._status===xe.STATUS_TERMINATED)throw new Error("terminated");this._localMediaStream=G,G&&G.getTracks().forEach(te=>{this._connection.addTrack(te,G)})}).then(()=>{if(this._late_sdp)return;const G={originator:"remote",type:"offer",sdp:r.body};Ce.debug('emit "sdp"'),this.emit("sdp",G);const te=new RTCSessionDescription({type:"offer",sdp:G.sdp});return this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(te)).catch(X=>{throw r.reply(488),this._failed("system",null,Ke.causes.WEBRTC_ERROR),Ce.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',X),this.emit("peerconnection:setremotedescriptionfailed",X),new Error("peerconnection.setRemoteDescription() failed")}),this._connectionPromiseQueue}).then(()=>{if(this._status===xe.STATUS_TERMINATED)throw new Error("terminated");return this._connecting(r),this._late_sdp?this._createLocalDescription("offer",this._rtcOfferConstraints).catch(()=>{throw r.reply(500),new Error("_createLocalDescription() failed")}):this._createLocalDescription("answer",_).catch(()=>{throw r.reply(500),new Error("_createLocalDescription() failed")})}).then(G=>{if(this._status===xe.STATUS_TERMINATED)throw new Error("terminated");this._handleSessionTimersInIncomingRequest(r,l),r.reply(200,null,l,G,()=>{this._status=xe.STATUS_WAITING_FOR_ACK,this._setInvite2xxTimer(r,G),this._setACKTimer(),this._accepted("local")},()=>{this._failed("system",null,Ke.causes.CONNECTION_ERROR)})}).catch(G=>{this._status!==xe.STATUS_TERMINATED&&Ce.warn(G)})}terminate(t={}){Ce.debug("terminate()");const r=t.cause||Ke.causes.BYE,l=Xt.cloneArray(t.extraHeaders),u=t.body;let s,n=t.status_code,g=t.reason_phrase;if(this._status===xe.STATUS_TERMINATED)throw new Ca.InvalidStateError(this._status);switch(this._status){case xe.STATUS_NULL:case xe.STATUS_INVITE_SENT:case xe.STATUS_1XX_RECEIVED:if(Ce.debug("canceling session"),n&&(n<200||n>=700))throw new TypeError(`Invalid status_code: ${n}`);n&&(g=g||Ke.REASON_PHRASE[n]||"",s=`SIP ;cause=${n} ;text="${g}"`),this._status===xe.STATUS_NULL||this._status===xe.STATUS_INVITE_SENT?(this._is_canceled=!0,this._cancel_reason=s):this._status===xe.STATUS_1XX_RECEIVED&&this._request.cancel(s),this._status=xe.STATUS_CANCELED,this._failed("local",null,Ke.causes.CANCELED);break;case xe.STATUS_WAITING_FOR_ANSWER:case xe.STATUS_ANSWERED:if(Ce.debug("rejecting session"),n=n||480,n<300||n>=700)throw new TypeError(`Invalid status_code: ${n}`);this._request.reply(n,g,l,u),this._failed("local",null,Ke.causes.REJECTED);break;case xe.STATUS_WAITING_FOR_ACK:case xe.STATUS_CONFIRMED:if(Ce.debug("terminating session"),g=t.reason_phrase||Ke.REASON_PHRASE[n]||"",n&&(n<200||n>=700))throw new TypeError(`Invalid status_code: ${n}`);if(n&&l.push(`Reason: SIP ;cause=${n}; text="${g}"`),this._status===xe.STATUS_WAITING_FOR_ACK&&this._direction==="incoming"&&this._request.server_transaction.state!==j_.C.STATUS_TERMINATED){const _=this._dialog;this.receiveRequest=({method:v})=>{v===Ke.ACK&&(this.sendRequest(Ke.BYE,{extraHeaders:l,body:u}),_.terminate())},this._request.server_transaction.on("stateChanged",()=>{this._request.server_transaction.state===j_.C.STATUS_TERMINATED&&(this.sendRequest(Ke.BYE,{extraHeaders:l,body:u}),_.terminate())}),this._ended("local",null,r),this._dialog=_,this._ua.newDialog(_)}else this.sendRequest(Ke.BYE,{extraHeaders:l,body:u}),this._ended("local",null,r)}}sendDTMF(t,r={}){Ce.debug("sendDTMF() | tones: %s",t);let l=0,u=r.duration||null,s=r.interToneGap||null;const n=r.transportType||Ke.DTMF_TRANSPORT.INFO;if(t===void 0)throw new TypeError("Not enough arguments");if(this._status!==xe.STATUS_CONFIRMED&&this._status!==xe.STATUS_WAITING_FOR_ACK&&this._status!==xe.STATUS_1XX_RECEIVED)throw new Ca.InvalidStateError(this._status);if(n!==Ke.DTMF_TRANSPORT.INFO&&n!==Ke.DTMF_TRANSPORT.RFC2833)throw new TypeError(`invalid transportType: ${n}`);if(typeof t=="number"&&(t=t.toString()),!t||typeof t!="string"||!t.match(/^[0-9A-DR#*,]+$/i))throw new TypeError(`Invalid tones: ${t}`);if(u&&!Xt.isDecimal(u))throw new TypeError(`Invalid tone duration: ${u}`);if(u?u<_r.C.MIN_DURATION?(Ce.debug(`"duration" value is lower than the minimum allowed, setting it to ${_r.C.MIN_DURATION} milliseconds`),u=_r.C.MIN_DURATION):u>_r.C.MAX_DURATION?(Ce.debug(`"duration" value is greater than the maximum allowed, setting it to ${_r.C.MAX_DURATION} milliseconds`),u=_r.C.MAX_DURATION):u=Math.abs(u):u=_r.C.DEFAULT_DURATION,r.duration=u,s&&!Xt.isDecimal(s))throw new TypeError(`Invalid interToneGap: ${s}`);if(s?s<_r.C.MIN_INTER_TONE_GAP?(Ce.debug(`"interToneGap" value is lower than the minimum allowed, setting it to ${_r.C.MIN_INTER_TONE_GAP} milliseconds`),s=_r.C.MIN_INTER_TONE_GAP):s=Math.abs(s):s=_r.C.DEFAULT_INTER_TONE_GAP,n===Ke.DTMF_TRANSPORT.RFC2833){const _=this._getDTMFRTPSender();_&&(t=_.toneBuffer+t,_.insertDTMF(t,u,s));return}if(this._tones){this._tones+=t;return}this._tones=t,g.call(this);function g(){let _;if(this._status===xe.STATUS_TERMINATED||!this._tones||l>=this._tones.length){this._tones=null;return}const v=this._tones[l];if(l+=1,v===",")_=2e3;else{const C=new _r(this);r.eventHandlers={onFailed:()=>{this._tones=null}},C.send(v,r),_=u+s}setTimeout(g.bind(this),_)}}sendInfo(t,r,l={}){if(Ce.debug("sendInfo()"),this._status!==xe.STATUS_CONFIRMED&&this._status!==xe.STATUS_WAITING_FOR_ACK&&this._status!==xe.STATUS_1XX_RECEIVED)throw new Ca.InvalidStateError(this._status);new G_(this).send(t,r,l)}mute(t={audio:!0,video:!1}){Ce.debug("mute()");let r=!1,l=!1;this._audioMuted===!1&&t.audio&&(r=!0,this._audioMuted=!0,this._toggleMuteAudio(!0)),this._videoMuted===!1&&t.video&&(l=!0,this._videoMuted=!0,this._toggleMuteVideo(!0)),(r===!0||l===!0)&&this._onmute({audio:r,video:l})}unmute(t={audio:!0,video:!0}){Ce.debug("unmute()");let r=!1,l=!1;this._audioMuted===!0&&t.audio&&(r=!0,this._audioMuted=!1,this._localHold===!1&&this._toggleMuteAudio(!1)),this._videoMuted===!0&&t.video&&(l=!0,this._videoMuted=!1,this._localHold===!1&&this._toggleMuteVideo(!1)),(r===!0||l===!0)&&this._onunmute({audio:r,video:l})}hold(t={},r){if(Ce.debug("hold()"),this._status!==xe.STATUS_WAITING_FOR_ACK&&this._status!==xe.STATUS_CONFIRMED||this._localHold===!0||!this._isReadyToReOffer())return!1;this._localHold=!0,this._onhold("local");const l={succeeded:()=>{r&&r()},failed:()=>{this.terminate({cause:Ke.causes.WEBRTC_ERROR,status_code:500,reason_phrase:"Hold Failed"})}};return t.useUpdate?this._sendUpdate({sdpOffer:!0,eventHandlers:l,extraHeaders:t.extraHeaders}):this._sendReinvite({eventHandlers:l,extraHeaders:t.extraHeaders}),!0}unhold(t={},r){if(Ce.debug("unhold()"),this._status!==xe.STATUS_WAITING_FOR_ACK&&this._status!==xe.STATUS_CONFIRMED||this._localHold===!1||!this._isReadyToReOffer())return!1;this._localHold=!1,this._onunhold("local");const l={succeeded:()=>{r&&r()},failed:()=>{this.terminate({cause:Ke.causes.WEBRTC_ERROR,status_code:500,reason_phrase:"Unhold Failed"})}};return t.useUpdate?this._sendUpdate({sdpOffer:!0,eventHandlers:l,extraHeaders:t.extraHeaders}):this._sendReinvite({eventHandlers:l,extraHeaders:t.extraHeaders}),!0}renegotiate(t={},r){Ce.debug("renegotiate()");const l=t.rtcOfferConstraints||null;if(this._status!==xe.STATUS_WAITING_FOR_ACK&&this._status!==xe.STATUS_CONFIRMED||!this._isReadyToReOffer())return!1;const u={succeeded:()=>{r&&r()},failed:()=>{this.terminate({cause:Ke.causes.WEBRTC_ERROR,status_code:500,reason_phrase:"Media Renegotiation Failed"})}};return this._setLocalMediaStatus(),t.useUpdate?this._sendUpdate({sdpOffer:!0,eventHandlers:u,rtcOfferConstraints:l,extraHeaders:t.extraHeaders}):this._sendReinvite({eventHandlers:u,rtcOfferConstraints:l,extraHeaders:t.extraHeaders}),!0}refer(t,r){Ce.debug("refer()");const l=t;if(this._status!==xe.STATUS_WAITING_FOR_ACK&&this._status!==xe.STATUS_CONFIRMED)return!1;if(t=this._ua.normalizeTarget(t),!t)throw new TypeError(`Invalid target: ${l}`);const u=new RE(this);u.sendRefer(t,r);const s=u.id;return this._referSubscribers[s]=u,u.on("requestFailed",()=>{delete this._referSubscribers[s]}),u.on("accepted",()=>{delete this._referSubscribers[s]}),u.on("failed",()=>{delete this._referSubscribers[s]}),u}sendRequest(t,r){return Ce.debug("sendRequest()"),this._dialog.sendRequest(t,r)}receiveRequest(t){if(Ce.debug("receiveRequest()"),t.method===Ke.CANCEL)(this._status===xe.STATUS_WAITING_FOR_ANSWER||this._status===xe.STATUS_ANSWERED)&&(this._status=xe.STATUS_CANCELED,this._request.reply(487),this._failed("remote",t,Ke.causes.CANCELED));else switch(t.method){case Ke.ACK:if(this._status!==xe.STATUS_WAITING_FOR_ACK)return;if(this._status=xe.STATUS_CONFIRMED,clearTimeout(this._timers.ackTimer),clearTimeout(this._timers.invite2xxTimer),this._late_sdp){if(!t.body){this.terminate({cause:Ke.causes.MISSING_SDP,status_code:400});break}const r={originator:"remote",type:"answer",sdp:t.body};Ce.debug('emit "sdp"'),this.emit("sdp",r);const l=new RTCSessionDescription({type:"answer",sdp:r.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(l)).then(()=>{this._is_confirmed||this._confirmed("remote",t)}).catch(u=>{this.terminate({cause:Ke.causes.BAD_MEDIA_DESCRIPTION,status_code:488}),Ce.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',u),this.emit("peerconnection:setremotedescriptionfailed",u)})}else this._is_confirmed||this._confirmed("remote",t);break;case Ke.BYE:this._status===xe.STATUS_CONFIRMED||this._status===xe.STATUS_WAITING_FOR_ACK?(t.reply(200),this._ended("remote",t,Ke.causes.BYE)):this._status===xe.STATUS_INVITE_RECEIVED||this._status===xe.STATUS_WAITING_FOR_ANSWER?(t.reply(200),this._request.reply(487,"BYE Received"),this._ended("remote",t,Ke.causes.BYE)):t.reply(403,"Wrong Status");break;case Ke.INVITE:this._status===xe.STATUS_CONFIRMED?t.hasHeader("replaces")?this._receiveReplaces(t):this._receiveReinvite(t):t.reply(403,"Wrong Status");break;case Ke.INFO:if(this._status===xe.STATUS_1XX_RECEIVED||this._status===xe.STATUS_WAITING_FOR_ANSWER||this._status===xe.STATUS_ANSWERED||this._status===xe.STATUS_WAITING_FOR_ACK||this._status===xe.STATUS_CONFIRMED){const r=t.hasHeader("Content-Type")?t.getHeader("Content-Type").toLowerCase():void 0;r&&r.match(/^application\/dtmf-relay/i)?new _r(this).init_incoming(t):r!==void 0?new G_(this).init_incoming(t):t.reply(415)}else t.reply(403,"Wrong Status");break;case Ke.UPDATE:this._status===xe.STATUS_CONFIRMED?this._receiveUpdate(t):t.reply(403,"Wrong Status");break;case Ke.REFER:this._status===xe.STATUS_CONFIRMED?this._receiveRefer(t):t.reply(403,"Wrong Status");break;case Ke.NOTIFY:this._status===xe.STATUS_CONFIRMED?this._receiveNotify(t):t.reply(403,"Wrong Status");break;default:t.reply(501)}}onTransportError(){Ce.warn("onTransportError()"),this._status!==xe.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:Ke.causes.CONNECTION_ERROR,cause:Ke.causes.CONNECTION_ERROR})}onRequestTimeout(){Ce.warn("onRequestTimeout()"),this._status!==xe.STATUS_TERMINATED&&this.terminate({status_code:408,reason_phrase:Ke.causes.REQUEST_TIMEOUT,cause:Ke.causes.REQUEST_TIMEOUT})}onDialogError(){Ce.warn("onDialogError()"),this._status!==xe.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:Ke.causes.DIALOG_ERROR,cause:Ke.causes.DIALOG_ERROR})}newDTMF(t){Ce.debug("newDTMF()"),this.emit("newDTMF",t)}newInfo(t){Ce.debug("newInfo()"),this.emit("newInfo",t)}_isReadyToReOffer(){return this._rtcReady?this._dialog?this._dialog.uac_pending_reply===!0||this._dialog.uas_pending_reply===!0?(Ce.debug("_isReadyToReOffer() | there is another INVITE/UPDATE transaction in progress"),!1):!0:(Ce.debug("_isReadyToReOffer() | session not established yet"),!1):(Ce.debug("_isReadyToReOffer() | internal WebRTC status not ready"),!1)}_close(){if(Ce.debug("close()"),this._localMediaStream&&this._localMediaStreamLocallyGenerated&&(Ce.debug("close() | closing local MediaStream"),Xt.closeMediaStream(this._localMediaStream)),this._status!==xe.STATUS_TERMINATED){if(this._status=xe.STATUS_TERMINATED,this._connection)try{this._connection.close()}catch(t){Ce.warn("close() | error closing the RTCPeerConnection: %o",t)}for(const t in this._timers)Object.prototype.hasOwnProperty.call(this._timers,t)&&clearTimeout(this._timers[t]);clearTimeout(this._sessionTimers.timer),this._dialog&&(this._dialog.terminate(),delete this._dialog);for(const t in this._earlyDialogs)Object.prototype.hasOwnProperty.call(this._earlyDialogs,t)&&(this._earlyDialogs[t].terminate(),delete this._earlyDialogs[t]);for(const t in this._referSubscribers)Object.prototype.hasOwnProperty.call(this._referSubscribers,t)&&delete this._referSubscribers[t];this._ua.destroyRTCSession(this)}}_setInvite2xxTimer(t,r){let l=oo.T1;function u(){this._status===xe.STATUS_WAITING_FOR_ACK&&(t.reply(200,null,[`Contact: ${this._contact}`],r),l<oo.T2&&(l=l*2,l>oo.T2&&(l=oo.T2)),this._timers.invite2xxTimer=setTimeout(u.bind(this),l))}this._timers.invite2xxTimer=setTimeout(u.bind(this),l)}_setACKTimer(){this._timers.ackTimer=setTimeout(()=>{this._status===xe.STATUS_WAITING_FOR_ACK&&(Ce.debug("no ACK received, terminating the session"),clearTimeout(this._timers.invite2xxTimer),this.sendRequest(Ke.BYE),this._ended("remote",null,Ke.causes.NO_ACK))},oo.TIMER_H)}_createRTCConnection(t,r){this._connection=new RTCPeerConnection(t,r),this._connection.addEventListener("iceconnectionstatechange",()=>{this._connection.iceConnectionState==="failed"&&this.terminate({cause:Ke.causes.RTP_TIMEOUT,status_code:408,reason_phrase:Ke.causes.RTP_TIMEOUT})}),Ce.debug('emit "peerconnection"'),this.emit("peerconnection",{peerconnection:this._connection})}_createLocalDescription(t,r){if(Ce.debug("createLocalDescription()"),t!=="offer"&&t!=="answer")throw new Error(`createLocalDescription() | invalid type "${t}"`);const l=this._connection;return this._rtcReady=!1,Promise.resolve().then(()=>t==="offer"?l.createOffer(r).catch(u=>(Ce.warn('emit "peerconnection:createofferfailed" [error:%o]',u),this.emit("peerconnection:createofferfailed",u),Promise.reject(u))):l.createAnswer(r).catch(u=>(Ce.warn('emit "peerconnection:createanswerfailed" [error:%o]',u),this.emit("peerconnection:createanswerfailed",u),Promise.reject(u)))).then(u=>l.setLocalDescription(u).catch(s=>(this._rtcReady=!0,Ce.warn('emit "peerconnection:setlocaldescriptionfailed" [error:%o]',s),this.emit("peerconnection:setlocaldescriptionfailed",s),Promise.reject(s)))).then(()=>{const u=r&&r.iceRestart;if(l.iceGatheringState==="complete"&&!u||l.iceGatheringState==="gathering"&&this._iceReady){this._rtcReady=!0;const s={originator:"local",type:t,sdp:l.localDescription.sdp};return Ce.debug('emit "sdp"'),this.emit("sdp",s),Promise.resolve(s.sdp)}return new Promise(s=>{let n=!1,g,_;this._iceReady=!1;const v=()=>{l.removeEventListener("icecandidate",g),l.removeEventListener("icegatheringstatechange",_),n=!0,this._rtcReady=!0,this._iceReady=!0;const C={originator:"local",type:t,sdp:l.localDescription.sdp};Ce.debug('emit "sdp"'),this.emit("sdp",C),s(C.sdp)};l.addEventListener("icecandidate",g=C=>{const R=C.candidate;R?this.emit("icecandidate",{candidate:R,ready:v}):n||v()}),l.addEventListener("icegatheringstatechange",_=()=>{l.iceGatheringState==="complete"&&!n&&v()})})})}_createDialog(t,r,l){const u=r==="UAS"?t.to_tag:t.from_tag,s=r==="UAS"?t.from_tag:t.to_tag,n=t.call_id+u+s;let g=this._earlyDialogs[n];if(l)return g?!0:(g=new Ru(this,t,r,Ru.C.STATUS_EARLY),g.error?(Ce.debug(g.error),this._failed("remote",t,Ke.causes.INTERNAL_ERROR),!1):(this._earlyDialogs[n]=g,!0));{if(this._from_tag=t.from_tag,this._to_tag=t.to_tag,g)return g.update(t,r),this._dialog=g,delete this._earlyDialogs[n],!0;const _=new Ru(this,t,r);return _.error?(Ce.debug(_.error),this._failed("remote",t,Ke.causes.INTERNAL_ERROR),!1):(this._dialog=_,!0)}}_receiveReinvite(t){Ce.debug("receiveReinvite()");const r=t.hasHeader("Content-Type")?t.getHeader("Content-Type").toLowerCase():void 0,l={request:t,callback:void 0,reject:s.bind(this)};let u=!1;function s(g={}){u=!0;const _=g.status_code||403,v=g.reason_phrase||"",C=Xt.cloneArray(g.extraHeaders);if(this._status!==xe.STATUS_CONFIRMED)return!1;if(_<300||_>=700)throw new TypeError(`Invalid status_code: ${_}`);t.reply(_,v,C)}if(this.emit("reinvite",l),u)return;if(this._late_sdp=!1,!t.body){this._late_sdp=!0,this._remoteHold&&(this._remoteHold=!1,this._onunhold("remote")),this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._createLocalDescription("offer",this._rtcOfferConstraints)).then(g=>{n.call(this,g)}).catch(()=>{t.reply(500)});return}if(r!=="application/sdp"){Ce.debug("invalid Content-Type"),t.reply(415);return}this._processInDialogSdpOffer(t).then(g=>{this._status!==xe.STATUS_TERMINATED&&n.call(this,g)}).catch(g=>{Ce.warn(g)});function n(g){const _=[`Contact: ${this._contact}`];this._handleSessionTimersInIncomingRequest(t,_),this._late_sdp&&(g=this._mangleOffer(g)),t.reply(200,null,_,g,()=>{this._status=xe.STATUS_WAITING_FOR_ACK,this._setInvite2xxTimer(t,g),this._setACKTimer()}),typeof l.callback=="function"&&l.callback()}}_receiveUpdate(t){Ce.debug("receiveUpdate()");const r=t.hasHeader("Content-Type")?t.getHeader("Content-Type").toLowerCase():void 0,l={request:t,callback:void 0,reject:s.bind(this)};let u=!1;function s(g={}){u=!0;const _=g.status_code||403,v=g.reason_phrase||"",C=Xt.cloneArray(g.extraHeaders);if(this._status!==xe.STATUS_CONFIRMED)return!1;if(_<300||_>=700)throw new TypeError(`Invalid status_code: ${_}`);t.reply(_,v,C)}if(this.emit("update",l),u)return;if(!t.body){n.call(this,null);return}if(r!=="application/sdp"){Ce.debug("invalid Content-Type"),t.reply(415);return}this._processInDialogSdpOffer(t).then(g=>{this._status!==xe.STATUS_TERMINATED&&n.call(this,g)}).catch(g=>{Ce.warn(g)});function n(g){const _=[`Contact: ${this._contact}`];this._handleSessionTimersInIncomingRequest(t,_),t.reply(200,null,_,g),typeof l.callback=="function"&&l.callback()}}_processInDialogSdpOffer(t){Ce.debug("_processInDialogSdpOffer()");const r=t.parseSDP();let l=!1;for(const n of r.media){if($u.indexOf(n.type)===-1)continue;const g=n.direction||r.direction||"sendrecv";if(g==="sendonly"||g==="inactive")l=!0;else{l=!1;break}}const u={originator:"remote",type:"offer",sdp:t.body};Ce.debug('emit "sdp"'),this.emit("sdp",u);const s=new RTCSessionDescription({type:"offer",sdp:u.sdp});return this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>{if(this._status===xe.STATUS_TERMINATED)throw new Error("terminated");return this._connection.setRemoteDescription(s).catch(n=>{throw t.reply(488),Ce.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',n),this.emit("peerconnection:setremotedescriptionfailed",n),n})}).then(()=>{if(this._status===xe.STATUS_TERMINATED)throw new Error("terminated");this._remoteHold===!0&&l===!1?(this._remoteHold=!1,this._onunhold("remote")):this._remoteHold===!1&&l===!0&&(this._remoteHold=!0,this._onhold("remote"))}).then(()=>{if(this._status===xe.STATUS_TERMINATED)throw new Error("terminated");return this._createLocalDescription("answer",this._rtcAnswerConstraints).catch(n=>{throw t.reply(500),Ce.warn('emit "peerconnection:createtelocaldescriptionfailed" [error:%o]',n),n})}).catch(n=>{Ce.warn("_processInDialogSdpOffer() failed [error: %o]",n)}),this._connectionPromiseQueue}_receiveRefer(t){if(Ce.debug("receiveRefer()"),!t.refer_to){Ce.debug("no Refer-To header field present in REFER"),t.reply(400);return}if(t.refer_to.uri.scheme!==Ke.SIP){Ce.debug("Refer-To header field points to a non-SIP URI scheme"),t.reply(416);return}t.reply(202);const r=new IE(this,t.cseq);Ce.debug('emit "refer"'),this.emit("refer",{request:t,accept:(s,n)=>{l.call(this,s,n)},reject:()=>{u.call(this)}});function l(s,n={}){if(s=typeof s=="function"?s:null,this._status!==xe.STATUS_WAITING_FOR_ACK&&this._status!==xe.STATUS_CONFIRMED)return!1;const g=new Bf(this._ua);if(g.on("progress",({response:_})=>{r.notify(_.status_code,_.reason_phrase)}),g.on("accepted",({response:_})=>{r.notify(_.status_code,_.reason_phrase)}),g.on("_failed",({message:_,cause:v})=>{_?r.notify(_.status_code,_.reason_phrase):r.notify(487,v)}),t.refer_to.uri.hasHeader("replaces")){const _=decodeURIComponent(t.refer_to.uri.getHeader("replaces"));n.extraHeaders=Xt.cloneArray(n.extraHeaders),n.extraHeaders.push(`Replaces: ${_}`)}g.connect(t.refer_to.uri.toAor(),n,s)}function u(){r.notify(603)}}_receiveNotify(t){switch(Ce.debug("receiveNotify()"),t.event||t.reply(400),t.event.event){case"refer":{let r,l;if(t.event.params&&t.event.params.id)r=t.event.params.id,l=this._referSubscribers[r];else if(Object.keys(this._referSubscribers).length===1)l=this._referSubscribers[Object.keys(this._referSubscribers)[0]];else{t.reply(400,"Missing event id parameter");return}if(!l){t.reply(481,"Subscription does not exist");return}l.receiveNotify(t),t.reply(200);break}default:t.reply(489)}}_receiveReplaces(t){Ce.debug("receiveReplaces()");function r(u){if(this._status!==xe.STATUS_WAITING_FOR_ACK&&this._status!==xe.STATUS_CONFIRMED)return!1;const s=new Bf(this._ua);s.on("confirmed",()=>{this.terminate()}),s.init_incoming(t,u)}function l(){Ce.debug("Replaced INVITE rejected by the user"),t.reply(486)}this.emit("replaces",{request:t,accept:u=>{r.call(this,u)},reject:()=>{l.call(this)}})}_sendInitialRequest(t,r,l){const u=new AE(this._ua,this._request,{onRequestTimeout:()=>{this.onRequestTimeout()},onTransportError:()=>{this.onTransportError()},onAuthenticated:s=>{this._request=s},onReceiveResponse:s=>{this._receiveInviteResponse(s)}});Promise.resolve().then(()=>{if(l)return l;if(t.audio||t.video)return this._localMediaStreamLocallyGenerated=!0,navigator.mediaDevices.getUserMedia(t).catch(s=>{throw this._status===xe.STATUS_TERMINATED?new Error("terminated"):(this._failed("local",null,Ke.causes.USER_DENIED_MEDIA_ACCESS),Ce.warn('emit "getusermediafailed" [error:%o]',s),this.emit("getusermediafailed",s),s)})}).then(s=>{if(this._status===xe.STATUS_TERMINATED)throw new Error("terminated");return this._localMediaStream=s,s&&s.getTracks().forEach(n=>{this._connection.addTrack(n,s)}),this._connecting(this._request),this._createLocalDescription("offer",r).catch(n=>{throw this._failed("local",null,Ke.causes.WEBRTC_ERROR),n})}).then(s=>{if(this._is_canceled||this._status===xe.STATUS_TERMINATED)throw new Error("terminated");this._request.body=s,this._status=xe.STATUS_INVITE_SENT,Ce.debug('emit "sending" [request:%o]',this._request),this.emit("sending",{request:this._request}),u.send()}).catch(s=>{this._status!==xe.STATUS_TERMINATED&&Ce.warn(s)})}_getDTMFRTPSender(){const t=this._connection.getSenders().find(r=>r.track&&r.track.kind==="audio");if(!(t&&t.dtmf)){Ce.warn("sendDTMF() | no local audio track to send DTMF with");return}return t.dtmf}_receiveInviteResponse(t){if(Ce.debug("receiveInviteResponse()"),this._dialog&&t.status_code>=200&&t.status_code<=299)if(this._dialog.id.call_id===t.call_id&&this._dialog.id.local_tag===t.from_tag&&this._dialog.id.remote_tag===t.to_tag){this.sendRequest(Ke.ACK);return}else{const r=new Ru(this,t,"UAC");if(r.error!==void 0){Ce.debug(r.error);return}this.sendRequest(Ke.ACK),this.sendRequest(Ke.BYE);return}if(this._is_canceled){t.status_code>=100&&t.status_code<200?this._request.cancel(this._cancel_reason):t.status_code>=200&&t.status_code<299&&this._acceptAndTerminate(t);return}if(!(this._status!==xe.STATUS_INVITE_SENT&&this._status!==xe.STATUS_1XX_RECEIVED))switch(!0){case/^100$/.test(t.status_code):this._status=xe.STATUS_1XX_RECEIVED;break;case/^1[0-9]{2}$/.test(t.status_code):{if(!t.to_tag){Ce.debug("1xx response received without to tag");break}if(t.hasHeader("contact")&&!this._createDialog(t,"UAC",!0))break;if(this._status=xe.STATUS_1XX_RECEIVED,!t.body){this._progress("remote",t);break}const r={originator:"remote",type:"answer",sdp:t.body};Ce.debug('emit "sdp"'),this.emit("sdp",r);const l=new RTCSessionDescription({type:"answer",sdp:r.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(l)).then(()=>this._progress("remote",t)).catch(u=>{Ce.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',u),this.emit("peerconnection:setremotedescriptionfailed",u)});break}case/^2[0-9]{2}$/.test(t.status_code):{if(this._status=xe.STATUS_CONFIRMED,!t.body){this._acceptAndTerminate(t,400,Ke.causes.MISSING_SDP),this._failed("remote",t,Ke.causes.BAD_MEDIA_DESCRIPTION);break}if(!this._createDialog(t,"UAC"))break;const r={originator:"remote",type:"answer",sdp:t.body};Ce.debug('emit "sdp"'),this.emit("sdp",r);const l=new RTCSessionDescription({type:"answer",sdp:r.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>{if(this._connection.signalingState==="stable")return this._connection.createOffer(this._rtcOfferConstraints).then(u=>this._connection.setLocalDescription(u)).catch(u=>{this._acceptAndTerminate(t,500,u.toString()),this._failed("local",t,Ke.causes.WEBRTC_ERROR)})}).then(()=>{this._connection.setRemoteDescription(l).then(()=>{this._handleSessionTimersInIncomingResponse(t),this._accepted("remote",t),this.sendRequest(Ke.ACK),this._confirmed("local",null)}).catch(u=>{this._acceptAndTerminate(t,488,"Not Acceptable Here"),this._failed("remote",t,Ke.causes.BAD_MEDIA_DESCRIPTION),Ce.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',u),this.emit("peerconnection:setremotedescriptionfailed",u)})});break}default:{const r=Xt.sipErrorCause(t.status_code);this._failed("remote",t,r)}}}_sendReinvite(t={}){Ce.debug("sendReinvite()");const r=Xt.cloneArray(t.extraHeaders),l=Xt.cloneObject(t.eventHandlers),u=t.rtcOfferConstraints||this._rtcOfferConstraints||null;let s=!1;r.push(`Contact: ${this._contact}`),r.push("Content-Type: application/sdp"),this._sessionTimers.running&&r.push(`Session-Expires: ${this._sessionTimers.currentExpires};refresher=${this._sessionTimers.refresher?"uac":"uas"}`),this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._createLocalDescription("offer",u)).then(_=>{_=this._mangleOffer(_);const v={originator:"local",type:"offer",sdp:_};Ce.debug('emit "sdp"'),this.emit("sdp",v),this.sendRequest(Ke.INVITE,{extraHeaders:r,body:_,eventHandlers:{onSuccessResponse:C=>{n.call(this,C),s=!0},onErrorResponse:C=>{g.call(this,C)},onTransportError:()=>{this.onTransportError()},onRequestTimeout:()=>{this.onRequestTimeout()},onDialogError:()=>{this.onDialogError()}}})}).catch(()=>{g()});function n(_){if(this._status===xe.STATUS_TERMINATED||(this.sendRequest(Ke.ACK),s))return;if(this._handleSessionTimersInIncomingResponse(_),_.body){if(!_.hasHeader("Content-Type")||_.getHeader("Content-Type").toLowerCase()!=="application/sdp"){g.call(this);return}}else{g.call(this);return}const v={originator:"remote",type:"answer",sdp:_.body};Ce.debug('emit "sdp"'),this.emit("sdp",v);const C=new RTCSessionDescription({type:"answer",sdp:v.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(C)).then(()=>{l.succeeded&&l.succeeded(_)}).catch(R=>{g.call(this),Ce.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',R),this.emit("peerconnection:setremotedescriptionfailed",R)})}function g(_){l.failed&&l.failed(_)}}_sendUpdate(t={}){Ce.debug("sendUpdate()");const r=Xt.cloneArray(t.extraHeaders),l=Xt.cloneObject(t.eventHandlers),u=t.rtcOfferConstraints||this._rtcOfferConstraints||null,s=t.sdpOffer||!1;let n=!1;r.push(`Contact: ${this._contact}`),this._sessionTimers.running&&r.push(`Session-Expires: ${this._sessionTimers.currentExpires};refresher=${this._sessionTimers.refresher?"uac":"uas"}`),s?(r.push("Content-Type: application/sdp"),this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._createLocalDescription("offer",u)).then(v=>{v=this._mangleOffer(v);const C={originator:"local",type:"offer",sdp:v};Ce.debug('emit "sdp"'),this.emit("sdp",C),this.sendRequest(Ke.UPDATE,{extraHeaders:r,body:v,eventHandlers:{onSuccessResponse:R=>{g.call(this,R),n=!0},onErrorResponse:R=>{_.call(this,R)},onTransportError:()=>{this.onTransportError()},onRequestTimeout:()=>{this.onRequestTimeout()},onDialogError:()=>{this.onDialogError()}}})}).catch(()=>{_.call(this)})):this.sendRequest(Ke.UPDATE,{extraHeaders:r,eventHandlers:{onSuccessResponse:v=>{g.call(this,v)},onErrorResponse:v=>{_.call(this,v)},onTransportError:()=>{this.onTransportError()},onRequestTimeout:()=>{this.onRequestTimeout()},onDialogError:()=>{this.onDialogError()}}});function g(v){if(this._status!==xe.STATUS_TERMINATED&&!n)if(this._handleSessionTimersInIncomingResponse(v),s){if(v.body){if(!v.hasHeader("Content-Type")||v.getHeader("Content-Type").toLowerCase()!=="application/sdp"){_.call(this);return}}else{_.call(this);return}const C={originator:"remote",type:"answer",sdp:v.body};Ce.debug('emit "sdp"'),this.emit("sdp",C);const R=new RTCSessionDescription({type:"answer",sdp:C.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(R)).then(()=>{l.succeeded&&l.succeeded(v)}).catch(D=>{_.call(this),Ce.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',D),this.emit("peerconnection:setremotedescriptionfailed",D)})}else l.succeeded&&l.succeeded(v)}function _(v){l.failed&&l.failed(v)}}_acceptAndTerminate(t,r,l){Ce.debug("acceptAndTerminate()");const u=[];r&&(l=l||Ke.REASON_PHRASE[r]||"",u.push(`Reason: SIP ;cause=${r}; text="${l}"`)),(this._dialog||this._createDialog(t,"UAC"))&&(this.sendRequest(Ke.ACK),this.sendRequest(Ke.BYE,{extraHeaders:u})),this._status=xe.STATUS_TERMINATED}_mangleOffer(t){if(!this._localHold&&!this._remoteHold)return t;if(t=q_.parse(t),this._localHold&&!this._remoteHold){Ce.debug("mangleOffer() | me on hold, mangling offer");for(const r of t.media)$u.indexOf(r.type)!==-1&&(r.direction?r.direction==="sendrecv"?r.direction="sendonly":r.direction==="recvonly"&&(r.direction="inactive"):r.direction="sendonly")}else if(this._localHold&&this._remoteHold){Ce.debug("mangleOffer() | both on hold, mangling offer");for(const r of t.media)$u.indexOf(r.type)!==-1&&(r.direction="inactive")}else if(this._remoteHold){Ce.debug("mangleOffer() | remote on hold, mangling offer");for(const r of t.media)$u.indexOf(r.type)!==-1&&(r.direction?r.direction==="sendrecv"?r.direction="recvonly":r.direction==="recvonly"&&(r.direction="inactive"):r.direction="recvonly")}return q_.write(t)}_setLocalMediaStatus(){let t=!0,r=!0;(this._localHold||this._remoteHold)&&(t=!1,r=!1),this._audioMuted&&(t=!1),this._videoMuted&&(r=!1),this._toggleMuteAudio(!t),this._toggleMuteVideo(!r)}_handleSessionTimersInIncomingRequest(t,r){if(!this._sessionTimers.enabled)return;let l;t.session_expires&&t.session_expires>=Ke.MIN_SESSION_EXPIRES?(this._sessionTimers.currentExpires=t.session_expires,l=t.session_expires_refresher||"uas"):(this._sessionTimers.currentExpires=this._sessionTimers.defaultExpires,l="uas"),r.push(`Session-Expires: ${this._sessionTimers.currentExpires};refresher=${l}`),this._sessionTimers.refresher=l==="uas",this._runSessionTimer()}_handleSessionTimersInIncomingResponse(t){if(!this._sessionTimers.enabled)return;let r;t.session_expires&&t.session_expires>=Ke.MIN_SESSION_EXPIRES?(this._sessionTimers.currentExpires=t.session_expires,r=t.session_expires_refresher||"uac"):(this._sessionTimers.currentExpires=this._sessionTimers.defaultExpires,r="uac"),this._sessionTimers.refresher=r==="uac",this._runSessionTimer()}_runSessionTimer(){const t=this._sessionTimers.currentExpires;this._sessionTimers.running=!0,clearTimeout(this._sessionTimers.timer),this._sessionTimers.refresher?this._sessionTimers.timer=setTimeout(()=>{this._status!==xe.STATUS_TERMINATED&&this._isReadyToReOffer()&&(Ce.debug("runSessionTimer() | sending session refresh request"),this._sessionTimers.refreshMethod===Ke.UPDATE?this._sendUpdate():this._sendReinvite())},t*500):this._sessionTimers.timer=setTimeout(()=>{this._status!==xe.STATUS_TERMINATED&&(Ce.warn("runSessionTimer() | timer expired, terminating the session"),this.terminate({cause:Ke.causes.REQUEST_TIMEOUT,status_code:408,reason_phrase:"Session Timer Expired"}))},t*1100)}_toggleMuteAudio(t){const r=this._connection.getSenders().filter(l=>l.track&&l.track.kind==="audio");for(const l of r)l.track.enabled=!t}_toggleMuteVideo(t){const r=this._connection.getSenders().filter(l=>l.track&&l.track.kind==="video");for(const l of r)l.track.enabled=!t}_newRTCSession(t,r){Ce.debug("newRTCSession()"),this._ua.newRTCSession(this,{originator:t,session:this,request:r})}_connecting(t){Ce.debug("session connecting"),Ce.debug('emit "connecting"'),this.emit("connecting",{request:t})}_progress(t,r){Ce.debug("session progress"),Ce.debug('emit "progress"'),this.emit("progress",{originator:t,response:r||null})}_accepted(t,r){Ce.debug("session accepted"),this._start_time=new Date,Ce.debug('emit "accepted"'),this.emit("accepted",{originator:t,response:r||null})}_confirmed(t,r){Ce.debug("session confirmed"),this._is_confirmed=!0,Ce.debug('emit "confirmed"'),this.emit("confirmed",{originator:t,ack:r||null})}_ended(t,r,l){Ce.debug("session ended"),this._end_time=new Date,this._close(),Ce.debug('emit "ended"'),this.emit("ended",{originator:t,message:r||null,cause:l})}_failed(t,r,l){Ce.debug("session failed"),Ce.debug('emit "_failed"'),this.emit("_failed",{originator:t,message:r||null,cause:l}),this._close(),Ce.debug('emit "failed"'),this.emit("failed",{originator:t,message:r||null,cause:l})}_onhold(t){Ce.debug("session onhold"),this._setLocalMediaStatus(),Ce.debug('emit "hold"'),this.emit("hold",{originator:t})}_onunhold(t){Ce.debug("session onunhold"),this._setLocalMediaStatus(),Ce.debug('emit "unhold"'),this.emit("unhold",{originator:t})}_onmute({audio:t,video:r}){Ce.debug("session onmute"),this._setLocalMediaStatus(),Ce.debug('emit "muted"'),this.emit("muted",{audio:t,video:r})}_onunmute({audio:t,video:r}){Ce.debug("session onunmute"),this._setLocalMediaStatus(),Ce.debug('emit "unmuted"'),this.emit("unmuted",{audio:t,video:r})}};const $E=Ht(K_),xE=ys.EventEmitter,OE=gs,pd=Et,DE=Ds,uo=xs(),kE=_l,Y_=Pn,NE=Nn(),xu=new OE("Message");var ME=class extends xE{constructor(t){super(),this._ua=t,this._request=null,this._closed=!1,this._direction=null,this._local_identity=null,this._remote_identity=null,this._is_replied=!1,this._data={}}get direction(){return this._direction}get local_identity(){return this._local_identity}get remote_identity(){return this._remote_identity}send(t,r,l={}){const u=t;if(t===void 0||r===void 0)throw new TypeError("Not enough arguments");if(t=this._ua.normalizeTarget(t),!t)throw new TypeError(`Invalid target: ${u}`);const s=uo.cloneArray(l.extraHeaders),n=uo.cloneObject(l.eventHandlers),g=l.contentType||"text/plain",_={};l.fromUserName&&(_.from_uri=new NE("sip",l.fromUserName,this._ua.configuration.uri.host),s.push(`P-Preferred-Identity: ${this._ua.configuration.uri.toString()}`)),l.fromDisplayName&&(_.from_display_name=l.fromDisplayName);for(const C in n)Object.prototype.hasOwnProperty.call(n,C)&&this.on(C,n[C]);s.push(`Content-Type: ${g}`),this._request=new DE.OutgoingRequest(pd.MESSAGE,t,this._ua,_,s),r&&(this._request.body=r);const v=new kE(this._ua,this._request,{onRequestTimeout:()=>{this._onRequestTimeout()},onTransportError:()=>{this._onTransportError()},onReceiveResponse:C=>{this._receiveResponse(C)}});this._newMessage("local",this._request),v.send()}init_incoming(t){this._request=t,this._newMessage("remote",t),this._is_replied||(this._is_replied=!0,t.reply(200)),this._close()}accept(t={}){const r=uo.cloneArray(t.extraHeaders),l=t.body;if(this._direction!=="incoming")throw new Y_.NotSupportedError('"accept" not supported for outgoing Message');if(this._is_replied)throw new Error("incoming Message already replied");this._is_replied=!0,this._request.reply(200,null,r,l)}reject(t={}){const r=t.status_code||480,l=t.reason_phrase,u=uo.cloneArray(t.extraHeaders),s=t.body;if(this._direction!=="incoming")throw new Y_.NotSupportedError('"reject" not supported for outgoing Message');if(this._is_replied)throw new Error("incoming Message already replied");if(r<300||r>=700)throw new TypeError(`Invalid status_code: ${r}`);this._is_replied=!0,this._request.reply(r,l,u,s)}_receiveResponse(t){if(!this._closed)switch(!0){case/^1[0-9]{2}$/.test(t.status_code):break;case/^2[0-9]{2}$/.test(t.status_code):this._succeeded("remote",t);break;default:{const r=uo.sipErrorCause(t.status_code);this._failed("remote",t,r);break}}}_onRequestTimeout(){this._closed||this._failed("system",null,pd.causes.REQUEST_TIMEOUT)}_onTransportError(){this._closed||this._failed("system",null,pd.causes.CONNECTION_ERROR)}_close(){this._closed=!0,this._ua.destroyMessage(this)}_newMessage(t,r){t==="remote"?(this._direction="incoming",this._local_identity=r.to,this._remote_identity=r.from):t==="local"&&(this._direction="outgoing",this._local_identity=r.from,this._remote_identity=r.to),this._ua.newMessage(this,{originator:t,message:this,request:r})}_failed(t,r,l){xu.debug("MESSAGE failed"),this._close(),xu.debug('emit "failed"'),this.emit("failed",{originator:t,response:r||null,cause:l})}_succeeded(t,r){xu.debug("MESSAGE succeeded"),this._close(),xu.debug('emit "succeeded"'),this.emit("succeeded",{originator:t,response:r})}};const UE=ys.EventEmitter,PE=gs,md=Et,LE=Ds,co=xs(),HE=_l,J_=Pn,Ou=new PE("Options");var FE=class extends UE{constructor(t){super(),this._ua=t,this._request=null,this._closed=!1,this._direction=null,this._local_identity=null,this._remote_identity=null,this._is_replied=!1,this._data={}}get direction(){return this._direction}get local_identity(){return this._local_identity}get remote_identity(){return this._remote_identity}send(t,r,l={}){const u=t;if(t===void 0)throw new TypeError("A target is required for OPTIONS");if(t=this._ua.normalizeTarget(t),!t)throw new TypeError(`Invalid target: ${u}`);const s=co.cloneArray(l.extraHeaders),n=co.cloneObject(l.eventHandlers),g=l.contentType||"application/sdp";for(const v in n)Object.prototype.hasOwnProperty.call(n,v)&&this.on(v,n[v]);s.push(`Content-Type: ${g}`),this._request=new LE.OutgoingRequest(md.OPTIONS,t,this._ua,null,s),r&&(this._request.body=r);const _=new HE(this._ua,this._request,{onRequestTimeout:()=>{this._onRequestTimeout()},onTransportError:()=>{this._onTransportError()},onReceiveResponse:v=>{this._receiveResponse(v)}});this._newOptions("local",this._request),_.send()}init_incoming(t){this._request=t,this._newOptions("remote",t),this._is_replied||(this._is_replied=!0,t.reply(200)),this._close()}accept(t={}){const r=co.cloneArray(t.extraHeaders),l=t.body;if(this._direction!=="incoming")throw new J_.NotSupportedError('"accept" not supported for outgoing Options');if(this._is_replied)throw new Error("incoming Options already replied");this._is_replied=!0,this._request.reply(200,null,r,l)}reject(t={}){const r=t.status_code||480,l=t.reason_phrase,u=co.cloneArray(t.extraHeaders),s=t.body;if(this._direction!=="incoming")throw new J_.NotSupportedError('"reject" not supported for outgoing Options');if(this._is_replied)throw new Error("incoming Options already replied");if(r<300||r>=700)throw new TypeError(`Invalid status_code: ${r}`);this._is_replied=!0,this._request.reply(r,l,u,s)}_receiveResponse(t){if(!this._closed)switch(!0){case/^1[0-9]{2}$/.test(t.status_code):break;case/^2[0-9]{2}$/.test(t.status_code):this._succeeded("remote",t);break;default:{const r=co.sipErrorCause(t.status_code);this._failed("remote",t,r);break}}}_onRequestTimeout(){this._closed||this._failed("system",null,md.causes.REQUEST_TIMEOUT)}_onTransportError(){this._closed||this._failed("system",null,md.causes.CONNECTION_ERROR)}_close(){this._closed=!0,this._ua.destroyMessage(this)}_newOptions(t,r){t==="remote"?(this._direction="incoming",this._local_identity=r.to,this._remote_identity=r.from):t==="local"&&(this._direction="outgoing",this._local_identity=r.from,this._remote_identity=r.to),this._ua.newOptions(this,{originator:t,message:this,request:r})}_failed(t,r,l){Ou.debug("OPTIONS failed"),this._close(),Ou.debug('emit "failed"'),this.emit("failed",{originator:t,response:r||null,cause:l})}_succeeded(t,r){Ou.debug("OPTIONS succeeded"),this._close(),Ou.debug('emit "succeeded"'),this.emit("succeeded",{originator:t,response:r})}},gd={};const BE=gs,vd=xs(),zE=Dr(),fo=new BE("Socket");gd.isSocket=f=>{if(Array.isArray(f))return!1;if(typeof f>"u")return fo.warn("undefined JsSIP.Socket instance"),!1;try{if(!vd.isString(f.url))throw fo.warn("missing or invalid JsSIP.Socket url property"),new Error("Missing or invalid JsSIP.Socket url property");if(!vd.isString(f.via_transport))throw fo.warn("missing or invalid JsSIP.Socket via_transport property"),new Error("Missing or invalid JsSIP.Socket via_transport property");if(zE.parse(f.sip_uri,"SIP_URI")===-1)throw fo.warn("missing or invalid JsSIP.Socket sip_uri property"),new Error("missing or invalid JsSIP.Socket sip_uri property")}catch{return!1}try{["connect","disconnect","send"].forEach(t=>{if(!vd.isFunction(f[t]))throw fo.warn(`missing or invalid JsSIP.Socket method: ${t}`),new Error(`Missing or invalid JsSIP.Socket method: ${t}`)})}catch{return!1}return!0};const VE=gs,qE=gd,Q_=Et,nr=new VE("Transport"),Cr={STATUS_CONNECTED:0,STATUS_CONNECTING:1,STATUS_DISCONNECTED:2,SOCKET_STATUS_READY:0,SOCKET_STATUS_ERROR:1,recovery_options:{min_interval:Q_.CONNECTION_RECOVERY_MIN_INTERVAL,max_interval:Q_.CONNECTION_RECOVERY_MAX_INTERVAL}};var X_=class{constructor(t,r=Cr.recovery_options){nr.debug("new()"),this.status=Cr.STATUS_DISCONNECTED,this.socket=null,this.sockets=[],this.recovery_options=r,this.recover_attempts=0,this.recovery_timer=null,this.close_requested=!1;try{this.textDecoder=new TextDecoder("utf8")}catch(l){nr.warn(`cannot use TextDecoder: ${l}`)}if(typeof t>"u")throw new TypeError("Invalid argument. undefined 'sockets' argument");t instanceof Array||(t=[t]),t.forEach(function(l){if(!qE.isSocket(l.socket))throw new TypeError("Invalid argument. invalid 'JsSIP.Socket' instance");if(l.weight&&!Number(l.weight))throw new TypeError("Invalid argument. 'weight' attribute is not a number");this.sockets.push({socket:l.socket,weight:l.weight||0,status:Cr.SOCKET_STATUS_READY})},this),this._getSocket()}get via_transport(){return this.socket.via_transport}get url(){return this.socket.url}get sip_uri(){return this.socket.sip_uri}connect(){if(nr.debug("connect()"),this.isConnected()){nr.debug("Transport is already connected");return}else if(this.isConnecting()){nr.debug("Transport is connecting");return}this.close_requested=!1,this.status=Cr.STATUS_CONNECTING,this.onconnecting({socket:this.socket,attempts:this.recover_attempts}),this.close_requested||(this.socket.onconnect=this._onConnect.bind(this),this.socket.ondisconnect=this._onDisconnect.bind(this),this.socket.ondata=this._onData.bind(this),this.socket.connect())}disconnect(){nr.debug("close()"),this.close_requested=!0,this.recover_attempts=0,this.status=Cr.STATUS_DISCONNECTED,this.recovery_timer!==null&&(clearTimeout(this.recovery_timer),this.recovery_timer=null),this.socket.onconnect=()=>{},this.socket.ondisconnect=()=>{},this.socket.ondata=()=>{},this.socket.disconnect(),this.ondisconnect({socket:this.socket,error:!1})}send(t){if(nr.debug("send()"),!this.isConnected())return nr.warn("unable to send message, transport is not connected"),!1;const r=t.toString();return nr.debug(`sending message:
116
116
 
117
117
  ${r}
118
118
  `),this.socket.send(r)}isConnected(){return this.status===Cr.STATUS_CONNECTED}isConnecting(){return this.status===Cr.STATUS_CONNECTING}_reconnect(){this.recover_attempts+=1;let t=Math.floor(Math.random()*Math.pow(2,this.recover_attempts)+1);t<this.recovery_options.min_interval?t=this.recovery_options.min_interval:t>this.recovery_options.max_interval&&(t=this.recovery_options.max_interval),nr.debug(`reconnection attempt: ${this.recover_attempts}. next connection attempt in ${t} seconds`),this.recovery_timer=setTimeout(()=>{!this.close_requested&&!(this.isConnected()||this.isConnecting())&&(this._getSocket(),this.connect())},t*1e3)}_getSocket(){let t=[];if(this.sockets.forEach(l=>{l.status!==Cr.SOCKET_STATUS_ERROR&&(t.length===0?t.push(l):l.weight>t[0].weight?t=[l]:l.weight===t[0].weight&&t.push(l))}),t.length===0){this.sockets.forEach(l=>{l.status=Cr.SOCKET_STATUS_READY}),this._getSocket();return}const r=Math.floor(Math.random()*t.length);this.socket=t[r].socket}_onConnect(){this.recover_attempts=0,this.status=Cr.STATUS_CONNECTED,this.recovery_timer!==null&&(clearTimeout(this.recovery_timer),this.recovery_timer=null),this.onconnect({socket:this})}_onDisconnect(t,r,l){this.status=Cr.STATUS_DISCONNECTED,this.ondisconnect({socket:this.socket,error:t,code:r,reason:l}),!this.close_requested&&(this.sockets.forEach(function(u){this.socket===u.socket&&(u.status=Cr.SOCKET_STATUS_ERROR)},this),this._reconnect(t))}_onData(t){if(t===`\r
@@ -122,17 +122,17 @@ ${t}
122
122
  `)}else nr.debug(`received text message:
123
123
 
124
124
  ${t}
125
- `);this.ondata({transport:this,message:t})}};const jE=Ht(Z_);var ep={};const GE=gs,yd=Dr(),Td=Ds,Du=new GE("Parser");ep.parseMessage=(f,t)=>{let r,l,u=f.indexOf(`\r
125
+ `);this.ondata({transport:this,message:t})}};const jE=Ht(X_);var Z_={};const GE=gs,yd=Dr(),Td=Ds,Du=new GE("Parser");Z_.parseMessage=(f,t)=>{let r,l,u=f.indexOf(`\r
126
126
  `);if(u===-1){Du.warn("parseMessage() | no CRLF found, not a SIP message");return}const s=f.substring(0,u);let n=yd.parse(s,"Request_Response");if(n===-1){Du.warn(`parseMessage() | error parsing first line of SIP message: "${s}"`);return}else n.status_code?(r=new Td.IncomingResponse,r.status_code=n.status_code,r.reason_phrase=n.reason_phrase):(r=new Td.IncomingRequest(t),r.method=n.method,r.ruri=n.uri);r.data=f;let g=u+2;for(;;){if(u=WE(f,g),u===-2){l=g+2;break}else if(u===-1){Du.warn("parseMessage() | malformed message");return}if(n=KE(r,f,g,u),n!==!0){Du.warn("parseMessage() |",n.error);return}g=u+2}if(r.hasHeader("content-length")){const _=r.getHeader("content-length");r.body=f.substr(l,_)}else r.body=f.substring(l);return r};function WE(f,t){let r=t,l=0,u=0;if(f.substring(r,r+2).match(/(^\r\n)/))return-2;for(;l===0;){if(u=f.indexOf(`\r
127
- `,r),u===-1)return u;!f.substring(u+2,u+4).match(/(^\r\n)/)&&f.charAt(u+2).match(/(^\s+)/)?r=u+2:l=u}return l}function KE(f,t,r,l){let u;const s=t.indexOf(":",r),n=t.substring(r,s).trim(),g=t.substring(s+1,l).trim();switch(n.toLowerCase()){case"via":case"v":f.addHeader("via",g),f.getHeaders("via").length===1?(u=f.parseHeader("Via"),u&&(f.via=u,f.via_branch=u.branch)):u=0;break;case"from":case"f":f.setHeader("from",g),u=f.parseHeader("from"),u&&(f.from=u,f.from_tag=u.getParam("tag"));break;case"to":case"t":f.setHeader("to",g),u=f.parseHeader("to"),u&&(f.to=u,f.to_tag=u.getParam("tag"));break;case"record-route":if(u=yd.parse(g,"Record_Route"),u===-1)u=void 0;else for(const _ of u)f.addHeader("record-route",g.substring(_.possition,_.offset)),f.headers["Record-Route"][f.getHeaders("record-route").length-1].parsed=_.parsed;break;case"call-id":case"i":f.setHeader("call-id",g),u=f.parseHeader("call-id"),u&&(f.call_id=g);break;case"contact":case"m":if(u=yd.parse(g,"Contact"),u===-1)u=void 0;else for(const _ of u)f.addHeader("contact",g.substring(_.possition,_.offset)),f.headers.Contact[f.getHeaders("contact").length-1].parsed=_.parsed;break;case"content-length":case"l":f.setHeader("content-length",g),u=f.parseHeader("content-length");break;case"content-type":case"c":f.setHeader("content-type",g),u=f.parseHeader("content-type");break;case"cseq":f.setHeader("cseq",g),u=f.parseHeader("cseq"),u&&(f.cseq=u.value),f instanceof Td.IncomingResponse&&(f.method=u.method);break;case"max-forwards":f.setHeader("max-forwards",g),u=f.parseHeader("max-forwards");break;case"www-authenticate":f.setHeader("www-authenticate",g),u=f.parseHeader("www-authenticate");break;case"proxy-authenticate":f.setHeader("proxy-authenticate",g),u=f.parseHeader("proxy-authenticate");break;case"session-expires":case"x":f.setHeader("session-expires",g),u=f.parseHeader("session-expires"),u&&(f.session_expires=u.expires,f.session_expires_refresher=u.refresher);break;case"refer-to":case"r":f.setHeader("refer-to",g),u=f.parseHeader("refer-to"),u&&(f.refer_to=u);break;case"replaces":f.setHeader("replaces",g),u=f.parseHeader("replaces"),u&&(f.replaces=u);break;case"event":case"o":f.setHeader("event",g),u=f.parseHeader("event"),u&&(f.event=u);break;default:f.addHeader(n,g),u=0}return u===void 0?{error:`error parsing header "${n}"`}:!0}const YE=gs,tp=Et,sp=Ds,Sd=xs(),bd=new YE("sanityCheck"),JE=[iC],QE=[ZE,eC,tC,sC],XE=[rC,nC];let Kt,fn,rp;var np=(f,t,r)=>{Kt=f,fn=t,rp=r;for(const l of JE)if(l()===!1)return!1;if(Kt instanceof sp.IncomingRequest){for(const l of QE)if(l()===!1)return!1}else if(Kt instanceof sp.IncomingResponse){for(const l of XE)if(l()===!1)return!1}return!0};function ZE(){if(Kt.s("to").uri.scheme!=="sip")return ho(416),!1}function eC(){if(!Kt.to_tag&&Kt.call_id.substr(0,5)===fn.configuration.jssip_id)return ho(482),!1}function tC(){const f=Sd.str_utf8_length(Kt.body),t=Kt.getHeader("content-length");if(f<t)return ho(400),!1}function sC(){const f=Kt.from_tag,t=Kt.call_id,r=Kt.cseq;let l;if(!Kt.to_tag)if(Kt.method===tp.INVITE){if(fn._transactions.ist[Kt.via_branch])return!1;for(const u in fn._transactions.ist)if(Object.prototype.hasOwnProperty.call(fn._transactions.ist,u)&&(l=fn._transactions.ist[u],l.request.from_tag===f&&l.request.call_id===t&&l.request.cseq===r))return ho(482),!1}else{if(fn._transactions.nist[Kt.via_branch])return!1;for(const u in fn._transactions.nist)if(Object.prototype.hasOwnProperty.call(fn._transactions.nist,u)&&(l=fn._transactions.nist[u],l.request.from_tag===f&&l.request.call_id===t&&l.request.cseq===r))return ho(482),!1}}function rC(){if(Kt.getHeaders("via").length>1)return bd.debug("more than one Via header field present in the response, dropping the response"),!1}function nC(){const f=Sd.str_utf8_length(Kt.body),t=Kt.getHeader("content-length");if(f<t)return bd.debug("message body length is lower than the value in Content-Length header field, dropping the response"),!1}function iC(){const f=["from","to","call_id","cseq","via"];for(const t of f)if(!Kt.hasHeader(t))return bd.debug(`missing mandatory header field : ${t}, dropping the response`),!1}function ho(f){const t=Kt.getHeaders("via");let r,l=`SIP/2.0 ${f} ${tp.REASON_PHRASE[f]}\r
127
+ `,r),u===-1)return u;!f.substring(u+2,u+4).match(/(^\r\n)/)&&f.charAt(u+2).match(/(^\s+)/)?r=u+2:l=u}return l}function KE(f,t,r,l){let u;const s=t.indexOf(":",r),n=t.substring(r,s).trim(),g=t.substring(s+1,l).trim();switch(n.toLowerCase()){case"via":case"v":f.addHeader("via",g),f.getHeaders("via").length===1?(u=f.parseHeader("Via"),u&&(f.via=u,f.via_branch=u.branch)):u=0;break;case"from":case"f":f.setHeader("from",g),u=f.parseHeader("from"),u&&(f.from=u,f.from_tag=u.getParam("tag"));break;case"to":case"t":f.setHeader("to",g),u=f.parseHeader("to"),u&&(f.to=u,f.to_tag=u.getParam("tag"));break;case"record-route":if(u=yd.parse(g,"Record_Route"),u===-1)u=void 0;else for(const _ of u)f.addHeader("record-route",g.substring(_.possition,_.offset)),f.headers["Record-Route"][f.getHeaders("record-route").length-1].parsed=_.parsed;break;case"call-id":case"i":f.setHeader("call-id",g),u=f.parseHeader("call-id"),u&&(f.call_id=g);break;case"contact":case"m":if(u=yd.parse(g,"Contact"),u===-1)u=void 0;else for(const _ of u)f.addHeader("contact",g.substring(_.possition,_.offset)),f.headers.Contact[f.getHeaders("contact").length-1].parsed=_.parsed;break;case"content-length":case"l":f.setHeader("content-length",g),u=f.parseHeader("content-length");break;case"content-type":case"c":f.setHeader("content-type",g),u=f.parseHeader("content-type");break;case"cseq":f.setHeader("cseq",g),u=f.parseHeader("cseq"),u&&(f.cseq=u.value),f instanceof Td.IncomingResponse&&(f.method=u.method);break;case"max-forwards":f.setHeader("max-forwards",g),u=f.parseHeader("max-forwards");break;case"www-authenticate":f.setHeader("www-authenticate",g),u=f.parseHeader("www-authenticate");break;case"proxy-authenticate":f.setHeader("proxy-authenticate",g),u=f.parseHeader("proxy-authenticate");break;case"session-expires":case"x":f.setHeader("session-expires",g),u=f.parseHeader("session-expires"),u&&(f.session_expires=u.expires,f.session_expires_refresher=u.refresher);break;case"refer-to":case"r":f.setHeader("refer-to",g),u=f.parseHeader("refer-to"),u&&(f.refer_to=u);break;case"replaces":f.setHeader("replaces",g),u=f.parseHeader("replaces"),u&&(f.replaces=u);break;case"event":case"o":f.setHeader("event",g),u=f.parseHeader("event"),u&&(f.event=u);break;default:f.addHeader(n,g),u=0}return u===void 0?{error:`error parsing header "${n}"`}:!0}const YE=gs,ep=Et,tp=Ds,Sd=xs(),bd=new YE("sanityCheck"),JE=[iC],QE=[ZE,eC,tC,sC],XE=[rC,nC];let Kt,fn,sp;var rp=(f,t,r)=>{Kt=f,fn=t,sp=r;for(const l of JE)if(l()===!1)return!1;if(Kt instanceof tp.IncomingRequest){for(const l of QE)if(l()===!1)return!1}else if(Kt instanceof tp.IncomingResponse){for(const l of XE)if(l()===!1)return!1}return!0};function ZE(){if(Kt.s("to").uri.scheme!=="sip")return ho(416),!1}function eC(){if(!Kt.to_tag&&Kt.call_id.substr(0,5)===fn.configuration.jssip_id)return ho(482),!1}function tC(){const f=Sd.str_utf8_length(Kt.body),t=Kt.getHeader("content-length");if(f<t)return ho(400),!1}function sC(){const f=Kt.from_tag,t=Kt.call_id,r=Kt.cseq;let l;if(!Kt.to_tag)if(Kt.method===ep.INVITE){if(fn._transactions.ist[Kt.via_branch])return!1;for(const u in fn._transactions.ist)if(Object.prototype.hasOwnProperty.call(fn._transactions.ist,u)&&(l=fn._transactions.ist[u],l.request.from_tag===f&&l.request.call_id===t&&l.request.cseq===r))return ho(482),!1}else{if(fn._transactions.nist[Kt.via_branch])return!1;for(const u in fn._transactions.nist)if(Object.prototype.hasOwnProperty.call(fn._transactions.nist,u)&&(l=fn._transactions.nist[u],l.request.from_tag===f&&l.request.call_id===t&&l.request.cseq===r))return ho(482),!1}}function rC(){if(Kt.getHeaders("via").length>1)return bd.debug("more than one Via header field present in the response, dropping the response"),!1}function nC(){const f=Sd.str_utf8_length(Kt.body),t=Kt.getHeader("content-length");if(f<t)return bd.debug("message body length is lower than the value in Content-Length header field, dropping the response"),!1}function iC(){const f=["from","to","call_id","cseq","via"];for(const t of f)if(!Kt.hasHeader(t))return bd.debug(`missing mandatory header field : ${t}, dropping the response`),!1}function ho(f){const t=Kt.getHeaders("via");let r,l=`SIP/2.0 ${f} ${ep.REASON_PHRASE[f]}\r
128
128
  `;for(const u of t)l+=`Via: ${u}\r
129
129
  `;r=Kt.getHeader("To"),Kt.to_tag||(r+=`;tag=${Sd.newTag()}`),l+=`To: ${r}\r
130
130
  `,l+=`From: ${Kt.getHeader("From")}\r
131
131
  `,l+=`Call-ID: ${Kt.call_id}\r
132
132
  `,l+=`CSeq: ${Kt.cseq} ${Kt.method}\r
133
133
  `,l+=`\r
134
- `,rp.send(l)}const aC=Ht(np);var _o={};const pl=xs(),Aa=Et,wd=Dr(),ip=Nn(),Ed=gd,Cd=Pn;_o.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:Aa.UPDATE,session_timers_force_refresher:!1,no_answer_timeout:60,register:!0,register_expires:600,registrar_server:null,sockets:null,connection_recovery_max_interval:Aa.CONNECTION_RECOVERY_MAX_INTERVAL,connection_recovery_min_interval:Aa.CONNECTION_RECOVERY_MIN_INTERVAL,extra_headers:null,via_host:`${pl.createRandomToken(12)}.invalid`};const ku={mandatory:{sockets(f){const t=[];if(Ed.isSocket(f))t.push({socket:f});else if(Array.isArray(f)&&f.length)for(const r of f)Object.prototype.hasOwnProperty.call(r,"socket")&&Ed.isSocket(r.socket)?t.push(r):Ed.isSocket(r)&&t.push({socket:r});else return;return t},uri(f){/^sip:/i.test(f)||(f=`${Aa.SIP}:${f}`);const t=ip.parse(f);if(t)return t.user?t:void 0}},optional:{authorization_user(f){if(wd.parse(`"${f}"`,"quoted_string")!==-1)return f},authorization_jwt(f){if(typeof f=="string")return f},user_agent(f){if(typeof f=="string")return f},connection_recovery_max_interval(f){if(pl.isDecimal(f)){const t=Number(f);if(t>0)return t}},connection_recovery_min_interval(f){if(pl.isDecimal(f)){const t=Number(f);if(t>0)return t}},contact_uri(f){if(typeof f=="string"){const t=wd.parse(f,"SIP_URI");if(t!==-1)return t}},display_name(f){return f},instance_id(f){if(/^uuid:/i.test(f)&&(f=f.substr(5)),wd.parse(f,"uuid")!==-1)return f},no_answer_timeout(f){if(pl.isDecimal(f)){const t=Number(f);if(t>0)return t}},session_timers(f){if(typeof f=="boolean")return f},session_timers_refresh_method(f){if(typeof f=="string"&&(f=f.toUpperCase(),f===Aa.INVITE||f===Aa.UPDATE))return f},session_timers_force_refresher(f){if(typeof f=="boolean")return f},password(f){return String(f)},realm(f){return String(f)},ha1(f){return String(f)},register(f){if(typeof f=="boolean")return f},register_expires(f){if(pl.isDecimal(f)){const t=Number(f);if(t>0)return t}},registrar_server(f){/^sip:/i.test(f)||(f=`${Aa.SIP}:${f}`);const t=ip.parse(f);if(t)return t.user?void 0:t},use_preloaded_route(f){if(typeof f=="boolean")return f},extra_headers(f){const t=[];if(Array.isArray(f)&&f.length)for(const r of f)typeof r=="string"&&t.push(r);else return;return t}}};_o.load=(f,t)=>{for(const r in ku.mandatory)if(t.hasOwnProperty(r)){const l=t[r],u=ku.mandatory[r](l);if(u!==void 0)f[r]=u;else throw new Cd.ConfigurationError(r,l)}else throw new Cd.ConfigurationError(r);for(const r in ku.optional)if(t.hasOwnProperty(r)){const l=t[r];if(pl.isEmpty(l))continue;const u=ku.optional[r](l);if(u!==void 0)f[r]=u;else throw new Cd.ConfigurationError(r,l)}};const lC=ys.EventEmitter,oC=gs,ks=Et,uC=Qw,ap=Y_,lp=ME,op=FE,Ad=hl,cC=Z_,Nu=xs(),dC=Pn,fC=Nn(),hC=ep,Id=Ds,_C=np,Rd=_o,Jt=new oC("UA"),Ns={STATUS_INIT:0,STATUS_READY:1,STATUS_USER_CLOSED:2,STATUS_NOT_READY:3,CONFIGURATION_ERROR:1,NETWORK_ERROR:2};var up=class extends lC{static get C(){return Ns}constructor(t){if(Jt.debug("new() [configuration:%o]",t),super(),this._cache={credentials:{}},this._configuration=Object.assign({},Rd.settings),this._dynConfiguration={},this._dialogs={},this._applicants={},this._sessions={},this._transport=null,this._contact=null,this._status=Ns.STATUS_INIT,this._error=null,this._transactions={nist:{},nict:{},ist:{},ict:{}},this._data={},this._closeTimer=null,t===void 0)throw new TypeError("Not enough arguments");try{this._loadConfig(t)}catch(r){throw this._status=Ns.STATUS_NOT_READY,this._error=Ns.CONFIGURATION_ERROR,r}this._registrator=new uC(this)}get C(){return Ns}get status(){return this._status}get contact(){return this._contact}get configuration(){return this._configuration}get transport(){return this._transport}start(){Jt.debug("start()"),this._status===Ns.STATUS_INIT?this._transport.connect():this._status===Ns.STATUS_USER_CLOSED?(Jt.debug("restarting UA"),this._closeTimer!==null&&(clearTimeout(this._closeTimer),this._closeTimer=null,this._transport.disconnect()),this._status=Ns.STATUS_INIT,this._transport.connect()):this._status===Ns.STATUS_READY?Jt.debug("UA is in READY status, not restarted"):Jt.debug("ERROR: connection is down, Auto-Recovery system is trying to reconnect"),this._dynConfiguration.register=this._configuration.register}register(){Jt.debug("register()"),this._dynConfiguration.register=!0,this._registrator.register()}unregister(t){Jt.debug("unregister()"),this._dynConfiguration.register=!1,this._registrator.unregister(t)}registrator(){return this._registrator}isRegistered(){return this._registrator.registered}isConnected(){return this._transport.isConnected()}call(t,r){Jt.debug("call()");const l=new ap(this);return l.connect(t,r),l}sendMessage(t,r,l){Jt.debug("sendMessage()");const u=new lp(this);return u.send(t,r,l),u}sendOptions(t,r,l){Jt.debug("sendOptions()");const u=new op(this);return u.send(t,r,l),u}terminateSessions(t){Jt.debug("terminateSessions()");for(const r in this._sessions)this._sessions[r].isEnded()||this._sessions[r].terminate(t)}stop(){if(Jt.debug("stop()"),this._dynConfiguration={},this._status===Ns.STATUS_USER_CLOSED){Jt.debug("UA already closed");return}this._registrator.close();const t=Object.keys(this._sessions).length;for(const l in this._sessions)if(Object.prototype.hasOwnProperty.call(this._sessions,l)){Jt.debug(`closing session ${l}`);try{this._sessions[l].terminate()}catch{}}for(const l in this._applicants)if(Object.prototype.hasOwnProperty.call(this._applicants,l))try{this._applicants[l].close()}catch{}this._status=Ns.STATUS_USER_CLOSED,Object.keys(this._transactions.nict).length+Object.keys(this._transactions.nist).length+Object.keys(this._transactions.ict).length+Object.keys(this._transactions.ist).length===0&&t===0?this._transport.disconnect():this._closeTimer=setTimeout(()=>{this._closeTimer=null,this._transport.disconnect()},2e3)}normalizeTarget(t){return Nu.normalizeTarget(t,this._configuration.hostport_params)}get(t){switch(t){case"authorization_user":return this._configuration.authorization_user;case"realm":return this._configuration.realm;case"ha1":return this._configuration.ha1;case"authorization_jwt":return this._configuration.authorization_jwt;default:Jt.warn('get() | cannot get "%s" parameter in runtime',t);return}}set(t,r){switch(t){case"authorization_user":{this._configuration.authorization_user=String(r);break}case"password":{this._configuration.password=String(r);break}case"realm":{this._configuration.realm=String(r);break}case"ha1":{this._configuration.ha1=String(r),this._configuration.password=null;break}case"authorization_jwt":{this._configuration.authorization_jwt=String(r);break}case"display_name":{this._configuration.display_name=r;break}default:return Jt.warn('set() | cannot set "%s" parameter in runtime',t),!1}return!0}newTransaction(t){this._transactions[t.type][t.id]=t,this.emit("newTransaction",{transaction:t})}destroyTransaction(t){delete this._transactions[t.type][t.id],this.emit("transactionDestroyed",{transaction:t})}newDialog(t){this._dialogs[t.id]=t}destroyDialog(t){delete this._dialogs[t.id]}newMessage(t,r){this._applicants[t]=t,this.emit("newMessage",r)}newOptions(t,r){this._applicants[t]=t,this.emit("newOptions",r)}destroyMessage(t){delete this._applicants[t]}newRTCSession(t,r){this._sessions[t.id]=t,this.emit("newRTCSession",r)}destroyRTCSession(t){delete this._sessions[t.id]}registered(t){this.emit("registered",t)}unregistered(t){this.emit("unregistered",t)}registrationFailed(t){this.emit("registrationFailed",t)}receiveRequest(t){const r=t.method;if(t.ruri.user!==this._configuration.uri.user&&t.ruri.user!==this._contact.uri.user){Jt.debug("Request-URI does not point to us"),t.method!==ks.ACK&&t.reply_sl(404);return}if(t.ruri.scheme===ks.SIPS){t.reply_sl(416);return}if(Ad.checkTransaction(this,t))return;if(r===ks.INVITE?new Ad.InviteServerTransaction(this,this._transport,t):r!==ks.ACK&&r!==ks.CANCEL&&new Ad.NonInviteServerTransaction(this,this._transport,t),r===ks.OPTIONS){if(this.listeners("newOptions").length===0){t.reply(200);return}new op(this).init_incoming(t)}else if(r===ks.MESSAGE){if(this.listeners("newMessage").length===0){t.reply(405);return}new lp(this).init_incoming(t)}else if(r===ks.INVITE&&!t.to_tag&&this.listeners("newRTCSession").length===0){t.reply(405);return}let l,u;if(t.to_tag)l=this._findDialog(t.call_id,t.from_tag,t.to_tag),l?l.receiveRequest(t):r===ks.NOTIFY?(u=this._findSession(t),u?u.receiveRequest(t):(Jt.debug("received NOTIFY request for a non existent subscription"),t.reply(481,"Subscription does not exist"))):r!==ks.ACK&&t.reply(481);else switch(r){case ks.INVITE:if(window.RTCPeerConnection)if(t.hasHeader("replaces")){const s=t.replaces;l=this._findDialog(s.call_id,s.from_tag,s.to_tag),l?(u=l.owner,u.isEnded()?t.reply(603):u.receiveRequest(t)):t.reply(481)}else u=new ap(this),u.init_incoming(t);else Jt.warn("INVITE received but WebRTC is not supported"),t.reply(488);break;case ks.BYE:t.reply(481);break;case ks.CANCEL:u=this._findSession(t),u?u.receiveRequest(t):Jt.debug("received CANCEL request for a non existent session");break;case ks.ACK:break;case ks.NOTIFY:this.emit("sipEvent",{event:t.event,request:t}),t.reply(200);break;default:t.reply(405);break}}_findSession({call_id:t,from_tag:r,to_tag:l}){const u=t+r,s=this._sessions[u],n=t+l,g=this._sessions[n];return s||g||null}_findDialog(t,r,l){let u=t+r+l,s=this._dialogs[u];return s||(u=t+l+r,s=this._dialogs[u],s||null)}_loadConfig(t){try{Rd.load(this._configuration,t)}catch(u){throw u}this._configuration.display_name===0&&(this._configuration.display_name="0"),this._configuration.instance_id||(this._configuration.instance_id=Nu.newUUID()),this._configuration.jssip_id=Nu.createRandomToken(5);const r=this._configuration.uri.clone();r.user=null,this._configuration.hostport_params=r.toString().replace(/^sip:/i,"");try{this._transport=new cC(this._configuration.sockets,{max_interval:this._configuration.connection_recovery_max_interval,min_interval:this._configuration.connection_recovery_min_interval}),this._transport.onconnecting=pC.bind(this),this._transport.onconnect=mC.bind(this),this._transport.ondisconnect=gC.bind(this),this._transport.ondata=vC.bind(this)}catch(u){throw Jt.warn(u),new dC.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 u=this._configuration.uri.clone();u.user=null,u.clearParams(),u.clearHeaders(),this._configuration.registrar_server=u}this._configuration.no_answer_timeout*=1e3,this._configuration.contact_uri?this._configuration.via_host=this._configuration.contact_uri.host:this._configuration.contact_uri=new fC("sip",Nu.createRandomToken(8),this._configuration.via_host,null,{transport:"ws"}),this._contact={pub_gruu:null,temp_gruu:null,uri:this._configuration.contact_uri,toString(u={}){const s=u.anonymous||null,n=u.outbound||null;let g="<";return s?g+=this.temp_gruu||"sip:anonymous@anonymous.invalid;transport=ws":g+=this.pub_gruu||this.uri.toString(),n&&(s?!this.temp_gruu:!this.pub_gruu)&&(g+=";ob"),g+=">",g}};const l=["authorization_user","password","realm","ha1","authorization_jwt","display_name","register"];for(const u in this._configuration)Object.prototype.hasOwnProperty.call(this._configuration,u)&&(l.indexOf(u)!==-1?Object.defineProperty(this._configuration,u,{writable:!0,configurable:!1}):Object.defineProperty(this._configuration,u,{writable:!1,configurable:!1}));Jt.debug("configuration parameters after validation:");for(const u in this._configuration)if(Object.prototype.hasOwnProperty.call(Rd.settings,u))switch(u){case"uri":case"registrar_server":Jt.debug(`- ${u}: ${this._configuration[u]}`);break;case"password":case"ha1":case"authorization_jwt":Jt.debug(`- ${u}: NOT SHOWN`);break;default:Jt.debug(`- ${u}: ${JSON.stringify(this._configuration[u])}`)}}};function pC(f){this.emit("connecting",f)}function mC(f){this._status!==Ns.STATUS_USER_CLOSED&&(this._status=Ns.STATUS_READY,this._error=null,this.emit("connected",f),this._dynConfiguration.register&&this._registrator.register())}function gC(f){const t=["nict","ict","nist","ist"];for(const r of t)for(const l in this._transactions[r])Object.prototype.hasOwnProperty.call(this._transactions[r],l)&&this._transactions[r][l].onTransportError();this.emit("disconnected",f),this._registrator.onTransportClosed(),this._status!==Ns.STATUS_USER_CLOSED&&(this._status=Ns.STATUS_NOT_READY,this._error=Ns.NETWORK_ERROR)}function vC(f){const t=f.transport;let r=f.message;if(r=hC.parseMessage(r,this),!!r&&!(this._status===Ns.STATUS_USER_CLOSED&&r instanceof Id.IncomingRequest)&&_C(r,this,t)){if(r instanceof Id.IncomingRequest)r.transport=t,this.receiveRequest(r);else if(r instanceof Id.IncomingResponse){let l;switch(r.method){case ks.INVITE:l=this._transactions.ict[r.via_branch],l&&l.receiveResponse(r);break;case ks.ACK:break;default:l=this._transactions.nict[r.via_branch],l&&l.receiveResponse(r);break}}}}const yC=Ht(up);for(var Ms=[],$d=0;$d<256;++$d)Ms.push(($d+256).toString(16).slice(1));function TC(f,t=0){return(Ms[f[t+0]]+Ms[f[t+1]]+Ms[f[t+2]]+Ms[f[t+3]]+"-"+Ms[f[t+4]]+Ms[f[t+5]]+"-"+Ms[f[t+6]]+Ms[f[t+7]]+"-"+Ms[f[t+8]]+Ms[f[t+9]]+"-"+Ms[f[t+10]]+Ms[f[t+11]]+Ms[f[t+12]]+Ms[f[t+13]]+Ms[f[t+14]]+Ms[f[t+15]]).toLowerCase()}var Mu,SC=new Uint8Array(16);function bC(){if(!Mu&&(Mu=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!Mu))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Mu(SC)}var wC=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);const cp={randomUUID:wC};function dp(f,t,r){if(cp.randomUUID&&!t&&!f)return cp.randomUUID();f=f||{};var l=f.random||(f.rng||bC)();if(l[6]=l[6]&15|64,l[8]=l[8]&63|128,t){r=r||0;for(var u=0;u<16;++u)t[r+u]=l[u];return t}return TC(l)}var Nt=xs();const Ln=Ht(Nt),xd=new Su("Dialog"),Ii={STATUS_EARLY:1,STATUS_CONFIRMED:2,STATUS_TERMINATED:3};class Uu{static get C(){return Ii}constructor(t,r,l,u=Ii.STATUS_CONFIRMED){if(this._owner=t,this._ua=t._ua,this._uac_pending_reply=!1,this._uas_pending_reply=!1,r instanceof Ds.IncomingResponse&&(u=r.status_code<200?Ii.STATUS_EARLY:Ii.STATUS_CONFIRMED),l==="UAS"){this._id={call_id:r.call_id,local_tag:r.to_tag,remote_tag:r.from_tag,toString(){return this.call_id+this.local_tag+this.remote_tag}},this._state=u,this._remote_seqnum=r.cseq,this._local_uri=r.parseHeader("to").uri,this._remote_uri=r.parseHeader("from").uri;let s=r.getHeaders("to")[0].split(";")[0];s=s.match(/<([^>]*)>/)[1],this._remote_target=s,this._route_set=r.getHeaders("record-route"),this._ack_seqnum=this._remote_seqnum}else if(l==="UAC"){this._id={call_id:r.call_id,local_tag:r.from_tag,remote_tag:r.to_tag,toString(){return this.call_id+this.local_tag+this.remote_tag}},this._state=u,this._local_seqnum=r.cseq,this._local_uri=r.parseHeader("from").uri,this._remote_uri=r.parseHeader("to").uri;let s=r.getHeaders("to")[0].split(";")[0];s=s.match(/<([^>]*)>/)[1],this._remote_target=s,this._route_set=r.getHeaders("record-route").reverse(),this._ack_seqnum=null}this._ua.newDialog(this),xd.debug(`new ${l} dialog created with status ${this._state===Ii.STATUS_EARLY?"EARLY":"CONFIRMED"}`)}get id(){return this._id}get local_seqnum(){return this._local_seqnum}set local_seqnum(t){this._local_seqnum=t}get owner(){return this._owner}get uac_pending_reply(){return this._uac_pending_reply}set uac_pending_reply(t){this._uac_pending_reply=t}get uas_pending_reply(){return this._uas_pending_reply}isTerminated(){return this._status===Ii.STATUS_TERMINATED}update(t,r){this._state=Ii.STATUS_CONFIRMED,xd.debug(`dialog ${this._id.toString()} changed to CONFIRMED state`),r==="UAC"&&(this._route_set=t.getHeaders("record-route").reverse())}terminate(){xd.debug(`dialog ${this._id.toString()} deleted`),this._ua.destroyDialog(this),this._state=Ii.STATUS_TERMINATED}sendRequest(t,r={}){const l=Ln.cloneArray(r.extraHeaders),u=Ln.cloneObject(r.eventHandlers),s=r.body||null,n=this._createRequest(t,l,s);return u.onAuthenticated=()=>{this._local_seqnum+=1},new rE(this,n,u).send(),n}receiveRequest(t){this._checkInDialogRequest(t)&&(t.method===fe.ACK&&this._ack_seqnum!==null?this._ack_seqnum=null:t.method===fe.INVITE&&(this._ack_seqnum=t.cseq),this._owner.receiveRequest(t))}_createRequest(t,r,l){r=Ln.cloneArray(r),this._local_seqnum||(this._local_seqnum=Math.floor(Math.random()*1e4));const u=t===fe.CANCEL||t===fe.ACK?this._local_seqnum:this._local_seqnum+=1;return new Ds.OutgoingRequest(t,this._remote_target,this._ua,{cseq:u,call_id:this._id.call_id,from_uri:this._local_uri,from_tag:this._id.local_tag,to_uri:this._remote_uri,to_tag:this._id.remote_tag,route_set:this._route_set},r,l)}_checkInDialogRequest(t){if(!this._remote_seqnum)this._remote_seqnum=t.cseq;else if(t.cseq<this._remote_seqnum)if(t.method===fe.ACK){if(this._ack_seqnum===null||t.cseq!==this._ack_seqnum)return!1}else return t.reply(500),!1;else t.cseq>this._remote_seqnum&&(this._remote_seqnum=t.cseq);if(t.method===fe.INVITE||t.method===fe.UPDATE&&t.body){if(this._uac_pending_reply===!0)t.reply(491);else if(this._uas_pending_reply===!0){const r=(Math.random()*10|0)+1;return t.reply(500,null,[`Retry-After:${r}`]),!1}else{this._uas_pending_reply=!0;const r=()=>{(t.server_transaction.state===Er.C.STATUS_ACCEPTED||t.server_transaction.state===Er.C.STATUS_COMPLETED||t.server_transaction.state===Er.C.STATUS_TERMINATED)&&(t.server_transaction.removeListener("stateChanged",r),this._uas_pending_reply=!1)};t.server_transaction.on("stateChanged",r)}t.hasHeader("contact")&&t.server_transaction.on("stateChanged",()=>{t.server_transaction.state===Er.C.STATUS_ACCEPTED&&(this._remote_target=t.parseHeader("contact").uri)})}else t.method===fe.NOTIFY&&t.hasHeader("contact")&&t.server_transaction.on("stateChanged",()=>{t.server_transaction.state===Er.C.STATUS_COMPLETED&&(this._remote_target=t.parseHeader("contact").uri)});return!0}}class EC{constructor(t,r){ln(this,"plugin",null);ln(this,"rtcpPeer",null);ln(this,"handleId",0);ln(this,"info",null);ln(this,"joinResult",null);ln(this,"state",{});ln(this,"stream",null);ln(this,"loaded",!1);ln(this,"aTracks",[]);ln(this,"vTracks",[]);this.info=t,this.plugin=r,this.rtcpPeer=new RTCPeerConnection({iceServers:[]})}get memberInfo(){return{stream:this.stream,joinResult:this.joinResult,sender:this.handleId,type:"subscriber",name:this.info.display,state:this.state,id:this.handleId}}updateMemberState(t){var r;this.state={...this.state,...t||{}},(r=this.plugin)==null||r.session.emit("member:update",this.memberInfo)}updateMemberStateFromMessage(t){var s,n,g,_;const r=(n=(s=t==null?void 0:t.plugindata)==null?void 0:s.data)==null?void 0:n.newStatePublisher,u=((_=(g=t==null?void 0:t.plugindata)==null?void 0:g.data)==null?void 0:_.publisher_state).find(v=>v.id===r);this.updateMemberState(u==null?void 0:u.state)}hangup(){this.rtcpPeer&&(this.rtcpPeer.close(),this.rtcpPeer=null),this.stream&&this.stream.getTracks().forEach(t=>{t.stop()})}}class Nr{static canGetMediaDevices(){return!(!navigator.mediaDevices||!navigator.mediaDevices.enumerateDevices)}static async getDevices(t){return Nr.canGetMediaDevices()?(await navigator.mediaDevices.enumerateDevices()).filter(l=>l.kind===t):[]}static async getMicrophoneList(){return(await Nr.getDevices("audioinput")).map((r,l)=>({...r,deviceId:r.deviceId,label:r.label||`microphone ${l+1}`,kind:r.kind,groupId:r.groupId}))}static async getSpeakerList(){return(await Nr.getDevices("audiooutput")).map((r,l)=>({...r,deviceId:r.deviceId,label:r.label||`speaker ${l+1}`,kind:r.kind,groupId:r.groupId}))}static async getCameraList(){return(await Nr.getDevices("videoinput")).map((r,l)=>({...r,deviceId:r.deviceId,label:r.label||`camera ${l+1}`,kind:r.kind,groupId:r.groupId}))}static stopStreamTracks(t){t&&t.getTracks().forEach(r=>{r.stop()})}static async getMediaFromInputs({videoInput:t,audioInput:r}){let l,u;t==="default"?l=!0:t&&t!=="default"&&(l={deviceId:{exact:t}}),r==="default"?u=!0:r&&r!=="default"&&(u={deviceId:{exact:r}});const s={audio:u,video:l};return Nr.getUserMedia(s)}static async getUserMedia(t){return await navigator.mediaDevices.getUserMedia(t)}static async changeAudioOutput(t,r){if(!(!t||!r))if(typeof t.sinkId<"u")try{await t.setSinkId(r)}catch(l){let u=l;l.name==="SecurityError"&&(u=`You need to use HTTPS for selecting audio output device: ${l}`),console.error(u)}else console.warn("Browser does not support output device selection.")}static toggleAudioMute(t){const r=t.getAudioTracks();if(r.length!==0)return r.forEach(l=>{l.enabled=!l.enabled}),r[0].enabled}static toggleVideoMute(t){const r=t.getVideoTracks();if(r.length!==0)return r.forEach(l=>{l.enabled=!l.enabled}),r[0].enabled}static async getStream(t={video:!0,audio:!0}){try{const r=await navigator.mediaDevices.getUserMedia(t);let l=r.getTracks();return t.video?l=r.getVideoTracks():t.audio&&(l=r.getAudioTracks()),l.length===0?{stream:r,track:null}:{stream:r,track:l[0]}}catch(r){return console.warn(r),{stream:null,track:null}}}}var CC=Nn();const Ia=Ht(CC),ir={LEAVE:"Leave",DETACH:"Detach",AUDIO_CHANGE:"AudioChange",VIDEO_CHANGE:"VideoChange",STATE:"State",ICE:"Ice",CONFIGURE:"Configure",TRICKLE:"Trickle",SUBSCRIBER:"Subscriber",PUBLISHER:"Publisher"},Ie=new Su("JanusSession"),AC="/opt/recordings/",De={STATUS_NULL:0,STATUS_INVITE_SENT:1,STATUS_1XX_RECEIVED:2,STATUS_INVITE_RECEIVED:3,STATUS_WAITING_FOR_ANSWER:4,STATUS_ANSWERED:5,STATUS_WAITING_FOR_ACK:6,STATUS_CANCELED:7,STATUS_TERMINATED:8,STATUS_CONFIRMED:9},Pu=["audio","video"];class Lu extends ys.EventEmitter{static get C(){return De}constructor(t){Ie.debug("new"),super(),this._id=null,this._ua=t,this._status=De.STATUS_NULL,this._dialog=null,this._earlyDialogs={},this._contact=null,this._from_tag=null,this._to_tag=null,this.lastTransaction=0,this._connection=null,this._connectionPromiseQueue=Promise.resolve(),this._request=null,this._is_canceled=!1,this._cancel_reason="",this._is_confirmed=!1,this._late_sdp=!1,this._rtcOfferConstraints=null,this._rtcAnswerConstraints=null,this._localMediaStream=null,this._localMediaStreamLocallyGenerated=!1,this._rtcReady=!0,this._iceReady=!1,this._timers={ackTimer:null,expiresTimer:null,invite2xxTimer:null,userNoAnswerTimer:null},this._direction=null,this._local_identity=null,this._remote_identity=null,this._start_time=null,this._end_time=null,this._audioMuted=!1,this._videoMuted=!1,this._localHold=!1,this._remoteHold=!1,this._sessionTimers={enabled:this._ua.configuration.session_timers,refreshMethod:this._ua.configuration.session_timers_refresh_method,defaultExpires:fe.SESSION_EXPIRES,currentExpires:null,running:!1,refresher:!1,timer:null},this._referSubscribers={},this._candidates=[],this.publishers=[],this.private_id=null,this.memberList={},this.myFeedList=[],this.display_name="",this.stunServers=[{urls:"stun:turn.voicenter.co",credential:"kxsjahnsdjns3eds23esd",username:"turn2es21e"}],this.opaque_id=this.generateOpaqueId(),this.screen_share_opaque_id=this.generateOpaqueId(),this._data={},this.isAudioOn=!0,this.isVideoOn=!0,this.mediaConstraints={}}get C(){return De}get causes(){return fe.causes}get id(){return this._id}get connection(){return this._connection}get contact(){return this._contact}get direction(){return this._direction}get local_identity(){return this._local_identity}get remote_identity(){return this._remote_identity}get start_time(){return this._start_time}get end_time(){return this._end_time}get data(){return this._data}set data(t){this._data=t}get status(){return this._status}isInProgress(){switch(this._status){case De.STATUS_NULL:case De.STATUS_INVITE_SENT:case De.STATUS_1XX_RECEIVED:case De.STATUS_INVITE_RECEIVED:case De.STATUS_WAITING_FOR_ANSWER:return!0;default:return!1}}isEstablished(){switch(this._status){case De.STATUS_ANSWERED:case De.STATUS_WAITING_FOR_ACK:case De.STATUS_CONFIRMED:return!0;default:return!1}}isEnded(){switch(this._status){case De.STATUS_CANCELED:case De.STATUS_TERMINATED:return!0;default:return!1}}isMuted(){return{audio:this._audioMuted,video:this._videoMuted}}isOnHold(){return{local:this._localHold,remote:this._remoteHold}}getPTypeHeader(t){return`PTYPE: ${t}`}generateOpaqueId(){return`videoroomtest-${dp().replace(/-/g,"").slice(0,12)}`}connect(t,r,l={},u){Ie.debug("connect()"),this.display_name=r;const s=t,n=Nt.cloneObject(l.eventHandlers),g=Nt.cloneArray(l.extraHeaders),_=Nt.cloneObject(l.mediaConstraints,{audio:!0,video:!0});this.mediaConstraints={..._};const v=l.mediaStream||null,C=Nt.cloneObject(l.pcConfig,{iceServers:[]}),R=l.rtcConstraints||null,D=l.rtcOfferConstraints||null;if(this._rtcOfferConstraints=D,this._rtcAnswerConstraints=l.rtcAnswerConstraints||null,this._data=l.data||this._data,t===void 0)throw new TypeError("Not enough arguments");if(this._status!==De.STATUS_NULL)throw new Ei.InvalidStateError(this._status);if(!window.RTCPeerConnection)throw new Ei.NotSupportedError("WebRTC not supported");if(t=this._ua.normalizeTarget(t),this.room_id=t.user,this.target=t,!t)throw new TypeError(`Invalid target: ${s}`);this._sessionTimers.enabled&&Nt.isDecimal(l.sessionTimersExpires)&&(l.sessionTimersExpires>=fe.MIN_SESSION_EXPIRES?this._sessionTimers.defaultExpires=l.sessionTimersExpires:this._sessionTimers.defaultExpires=fe.SESSION_EXPIRES);for(const q in n)Object.prototype.hasOwnProperty.call(n,q)&&this.on(q,n[q]);this._from_tag=Nt.newTag();const H=l.anonymous||!1,F={from_tag:this._from_tag};this._contact=this._ua.contact.toString({anonymous:H,outbound:!0}),H?(F.from_display_name="Anonymous",F.from_uri=new Ia("sip","anonymous","anonymous.invalid"),g.push(`P-Preferred-Identity: ${this._ua.configuration.uri.toString()}`),g.push("Privacy: id")):l.fromUserName&&(F.from_uri=new Ia("sip",l.fromUserName,this._ua.configuration.uri.host),g.push(`P-Preferred-Identity: ${this._ua.configuration.uri.toString()}`)),l.fromDisplayName&&(F.from_display_name=l.fromDisplayName),g.push(`Contact: ${this._contact}`),g.push("Content-Type: application/json"),this._sessionTimers.enabled&&g.push(`Session-Expires: ${this._sessionTimers.defaultExpires}${this._ua.configuration.session_timers_force_refresher?";refresher=uac":""}`),this._request=new Ds.InitialOutgoingInviteRequest(t,this._ua,F,g),this._id=this._request.call_id+this._from_tag,this._createRTCConnection(C,R),this._direction="outgoing",this._local_identity=this._request.from,this._remote_identity=this._request.to,u&&u(this),this._newJanusSession("local",this._request),this._sendInitialRequest(_,D,v)}_overrideSenderTracks(t,r){t.getTracks().forEach(l=>{r.getSenders().forEach(async s=>{s.track.kind===l.kind&&(l.kind==="audio"&&!this.isAudioOn&&(l.enabled=!1),l.kind==="video"&&!this.isVideoOn&&(l.enabled=!1),await s.replaceTrack(l))})})}init_incoming(t,r){Ie.debug("init_incoming()");let l;const u=t.hasHeader("Content-Type")?t.getHeader("Content-Type").toLowerCase():void 0;if(t.body&&u!=="application/sdp"){t.reply(415);return}if(this._status=De.STATUS_INVITE_RECEIVED,this._from_tag=t.from_tag,this._id=t.call_id+this._from_tag,this._request=t,this._contact=this._ua.contact.toString(),t.hasHeader("expires")&&(l=t.getHeader("expires")*1e3),t.to_tag=Nt.newTag(),!this._createDialog(t,"UAS",!0)){t.reply(500,"Missing Contact header field");return}t.body?this._late_sdp=!1:this._late_sdp=!0,this._status=De.STATUS_WAITING_FOR_ANSWER,this._timers.userNoAnswerTimer=setTimeout(()=>{t.reply(408),this._failed("local",null,fe.causes.NO_ANSWER)},this._ua.configuration.no_answer_timeout),l&&(this._timers.expiresTimer=setTimeout(()=>{this._status===De.STATUS_WAITING_FOR_ANSWER&&(t.reply(487),this._failed("system",null,fe.causes.EXPIRES))},l)),this._direction="incoming",this._local_identity=t.to,this._remote_identity=t.from,r&&r(this),this._newJanusSession("remote",t),this._status!==De.STATUS_TERMINATED&&(t.reply(180,null,[`Contact: ${this._contact}`]),this._progress("local",null))}answer(t={}){Ie.debug("answer()");const r=this._request,l=Nt.cloneArray(t.extraHeaders),u=Nt.cloneObject(t.mediaConstraints),s=t.mediaStream||null,n=Nt.cloneObject(t.pcConfig,{iceServers:[]}),g=t.rtcConstraints||null,_=t.rtcAnswerConstraints||null,v=Nt.cloneObject(t.rtcOfferConstraints);let C,R=!1,D=!1,H=!1,F=!1;if(this._rtcAnswerConstraints=_,this._rtcOfferConstraints=t.rtcOfferConstraints||null,this._data=t.data||this._data,this._direction!=="incoming")throw new Ei.NotSupportedError('"answer" not supported for outgoing RTCSession');if(this._status!==De.STATUS_WAITING_FOR_ANSWER)throw new Ei.InvalidStateError(this._status);if(this._sessionTimers.enabled&&Nt.isDecimal(t.sessionTimersExpires)&&(t.sessionTimersExpires>=fe.MIN_SESSION_EXPIRES?this._sessionTimers.defaultExpires=t.sessionTimersExpires:this._sessionTimers.defaultExpires=fe.SESSION_EXPIRES),this._status=De.STATUS_ANSWERED,!this._createDialog(r,"UAS")){r.reply(500,"Error creating dialog");return}clearTimeout(this._timers.userNoAnswerTimer),l.unshift(`Contact: ${this._contact}`);const q=r.parseSDP();Array.isArray(q.media)||(q.media=[q.media]);for(const G of q.media)G.type==="audio"&&(R=!0,(!G.direction||G.direction==="sendrecv")&&(H=!0)),G.type==="video"&&(D=!0,(!G.direction||G.direction==="sendrecv")&&(F=!0));if(s&&u.audio===!1){C=s.getAudioTracks();for(const G of C)s.removeTrack(G)}if(s&&u.video===!1){C=s.getVideoTracks();for(const G of C)s.removeTrack(G)}!s&&u.audio===void 0&&(u.audio=H),!s&&u.video===void 0&&(u.video=F),!s&&!R&&!v.offerToReceiveAudio&&(u.audio=!1),!s&&!D&&!v.offerToReceiveVideo&&(u.video=!1),this._createRTCConnection(n,g),Promise.resolve().then(()=>{if(s)return s;if(u.audio||u.video)return this._localMediaStreamLocallyGenerated=!0,this.loadStream().catch(G=>{throw this._status===De.STATUS_TERMINATED?new Error("terminated"):(r.reply(480),this._failed("local",null,fe.causes.USER_DENIED_MEDIA_ACCESS),Ie.warn('emit "getusermediafailed" [error:%o]',G),this.emit("getusermediafailed",G),new Error("getUserMedia() failed"))})}).then(G=>{if(this._status===De.STATUS_TERMINATED)throw new Error("terminated");this._localMediaStream=G,G&&G.getTracks().forEach(te=>{this._connection.addTrack(te,G)})}).then(()=>{if(this._late_sdp)return;const G={originator:"remote",type:"offer",sdp:r.body};Ie.debug('emit "sdp"'),this.emit("sdp",G);const te=new RTCSessionDescription({type:"offer",sdp:G.sdp});return this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(te)).catch(X=>{throw r.reply(488),this._failed("system",null,fe.causes.WEBRTC_ERROR),Ie.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',X),this.emit("peerconnection:setremotedescriptionfailed",X),new Error("peerconnection.setRemoteDescription() failed")}),this._connectionPromiseQueue}).then(()=>{if(this._status===De.STATUS_TERMINATED)throw new Error("terminated");return this._connecting(r),this._late_sdp?this._createLocalDescription("offer",this._rtcOfferConstraints).catch(()=>{throw r.reply(500),new Error("_createLocalDescription() failed")}):this._createLocalDescription("answer",_).catch(()=>{throw r.reply(500),new Error("_createLocalDescription() failed")})}).then(G=>{if(this._status===De.STATUS_TERMINATED)throw new Error("terminated");this._handleSessionTimersInIncomingRequest(r,l),r.reply(200,null,l,G,()=>{this._status=De.STATUS_WAITING_FOR_ACK,this._setInvite2xxTimer(r,G),this._setACKTimer(),this._accepted("local")},()=>{this._failed("system",null,fe.causes.CONNECTION_ERROR)})}).catch(G=>{this._status!==De.STATUS_TERMINATED&&Ie.warn(G)})}terminate(t={}){Ie.debug("terminate()");const r=t.cause||fe.causes.BYE,l=Nt.cloneArray(t.extraHeaders),u=t.body;let s,n=t.status_code,g=t.reason_phrase;if(this._status===De.STATUS_TERMINATED)throw new Ei.InvalidStateError(this._status);switch(this._status){case De.STATUS_NULL:case De.STATUS_INVITE_SENT:case De.STATUS_1XX_RECEIVED:if(Ie.debug("canceling session"),n&&(n<200||n>=700))throw new TypeError(`Invalid status_code: ${n}`);n&&(g=g||fe.REASON_PHRASE[n]||"",s=`SIP ;cause=${n} ;text="${g}"`),this._status===De.STATUS_NULL||this._status===De.STATUS_INVITE_SENT?(this._is_canceled=!0,this._cancel_reason=s):this._status===De.STATUS_1XX_RECEIVED&&this._request.cancel(s),this._status=De.STATUS_CANCELED,this._failed("local",null,fe.causes.CANCELED);break;case De.STATUS_WAITING_FOR_ANSWER:case De.STATUS_ANSWERED:if(Ie.debug("rejecting session"),n=n||480,n<300||n>=700)throw new TypeError(`Invalid status_code: ${n}`);this._request.reply(n,g,l,u),this._failed("local",null,fe.causes.REJECTED);break;case De.STATUS_WAITING_FOR_ACK:case De.STATUS_CONFIRMED:if(Ie.debug("terminating session"),g=t.reason_phrase||fe.REASON_PHRASE[n]||"",n&&(n<200||n>=700))throw new TypeError(`Invalid status_code: ${n}`);if(n&&l.push(`Reason: SIP ;cause=${n}; text="${g}"`),this._status===De.STATUS_WAITING_FOR_ACK&&this._direction==="incoming"&&this._request.server_transaction.state!==Er.C.STATUS_TERMINATED){const _=this._dialog;this.receiveRequest=({method:v})=>{v===fe.ACK&&(this.sendRequest(fe.BYE,{extraHeaders:l,body:u}),_.terminate(),this.closeSession())},this._request.server_transaction.on("stateChanged",()=>{this._request.server_transaction.state===Er.C.STATUS_TERMINATED&&(this.sendRequest(fe.BYE,{extraHeaders:l,body:u}),_.terminate(),this.closeSession())}),this._ended("local",null,r),this._dialog=_,this._ua.newDialog(_)}else{const _={janus:"leave"},v=["Content-Type: application/json",this.getPTypeHeader(ir.LEAVE)];this.sendRequest(fe.BYE,{extraHeaders:v,body:JSON.stringify(_)}),this.closeSession(),this._ended("local",null,r)}}}configureMedia(t){this.isAudioOn=t.audio,this.isVideoOn=t.video}enableAudio(t){const r={janus:"message",body:{audio:t},handle_id:this.handle_id,session_id:this.session_id},l=["Content-Type: application/json",this.getPTypeHeader(ir.AUDIO_CHANGE)];this.sendRequest(fe.INFO,{extraHeaders:l,body:JSON.stringify(r),eventHandlers:{onSuccessResponse:async u=>{u.status_code===200&&(this._ua.emit("changeAudioState",t),this.sendStateMessage({audio:t}))}}})}startAudio(){Nr.toggleAudioMute(this.stream),this._toggleMuteAudio(!1),this.enableAudio(!0),this.isAudioOn=!0}stopAudio(){Nr.toggleAudioMute(this.stream),this._toggleMuteAudio(!0),this.enableAudio(!1),this.isAudioOn=!1}enableVideo(t){const r={janus:"message",body:{video:t},handle_id:this.handle_id,session_id:this.session_id},l=["Content-Type: application/json",this.getPTypeHeader(ir.VIDEO_CHANGE)];this.sendRequest(fe.INFO,{extraHeaders:l,body:JSON.stringify(r),eventHandlers:{onSuccessResponse:async u=>{u.status_code===200&&(this._ua.emit("changeVideoState",t),this.sendStateMessage({video:t}))}}})}startVideo(){Nr.toggleVideoMute(this.stream),this._toggleMuteVideo(!1),this.enableVideo(!0),this.isVideoOn=!0}stopVideo(){Nr.toggleVideoMute(this.stream),this._toggleMuteVideo(!0),this.enableVideo(!1),this.isVideoOn=!1}sendStateMessage(t){const r={janus:"message",body:{request:"state",data:t},handle_id:this.handle_id,session_id:this.session_id},l=["Content-Type: application/json",this.getPTypeHeader(ir.STATE)];this.sendRequest(fe.INFO,{extraHeaders:l,body:JSON.stringify(r)})}sendInfo(t,r,l={}){if(Ie.debug("sendInfo()"),this._status!==De.STATUS_CONFIRMED&&this._status!==De.STATUS_WAITING_FOR_ACK&&this._status!==De.STATUS_1XX_RECEIVED)throw new Ei.InvalidStateError(this._status);new hd(this).send(t,r,l)}mute(t={audio:!0,video:!1}){Ie.debug("mute()");let r=!1,l=!1;this._audioMuted===!1&&t.audio&&(r=!0,this._audioMuted=!0,this._toggleMuteAudio(!0)),this._videoMuted===!1&&t.video&&(l=!0,this._videoMuted=!0,this._toggleMuteVideo(!0)),(r===!0||l===!0)&&this._onmute({audio:r,video:l})}unmute(t={audio:!0,video:!0}){Ie.debug("unmute()");let r=!1,l=!1;this._audioMuted===!0&&t.audio&&(r=!0,this._audioMuted=!1,this._localHold===!1&&this._toggleMuteAudio(!1)),this._videoMuted===!0&&t.video&&(l=!0,this._videoMuted=!1,this._localHold===!1&&this._toggleMuteVideo(!1)),(r===!0||l===!0)&&this._onunmute({audio:r,video:l})}hold(t={},r){if(Ie.debug("hold()"),this._status!==De.STATUS_WAITING_FOR_ACK&&this._status!==De.STATUS_CONFIRMED||this._localHold===!0||!this._isReadyToReOffer())return!1;this._localHold=!0,this._onhold("local");const l={succeeded:()=>{r&&r()},failed:()=>{this.terminate({cause:fe.causes.WEBRTC_ERROR,status_code:500,reason_phrase:"Hold Failed"})}};return t.useUpdate?this._sendUpdate({sdpOffer:!0,eventHandlers:l,extraHeaders:t.extraHeaders}):this._sendReinvite({eventHandlers:l,extraHeaders:t.extraHeaders}),!0}unhold(t={},r){if(Ie.debug("unhold()"),this._status!==De.STATUS_WAITING_FOR_ACK&&this._status!==De.STATUS_CONFIRMED||this._localHold===!1||!this._isReadyToReOffer())return!1;this._localHold=!1,this._onunhold("local");const l={succeeded:()=>{r&&r()},failed:()=>{this.terminate({cause:fe.causes.WEBRTC_ERROR,status_code:500,reason_phrase:"Unhold Failed"})}};return t.useUpdate?this._sendUpdate({sdpOffer:!0,eventHandlers:l,extraHeaders:t.extraHeaders}):this._sendReinvite({eventHandlers:l,extraHeaders:t.extraHeaders}),!0}renegotiate(t={},r){Ie.debug("renegotiate()");const l=t.rtcOfferConstraints||null;if(this._status!==De.STATUS_WAITING_FOR_ACK&&this._status!==De.STATUS_CONFIRMED||!this._isReadyToReOffer())return!1;const u={succeeded:()=>{r&&r()},failed:()=>{this.terminate({cause:fe.causes.WEBRTC_ERROR,status_code:500,reason_phrase:"Media Renegotiation Failed"})}};return this._setLocalMediaStatus(),t.useUpdate?this._sendUpdate({sdpOffer:!0,eventHandlers:u,rtcOfferConstraints:l,extraHeaders:t.extraHeaders}):this._sendReinvite({eventHandlers:u,rtcOfferConstraints:l,extraHeaders:t.extraHeaders}),!0}refer(t,r){Ie.debug("refer()");const l=t;if(this._status!==De.STATUS_WAITING_FOR_ACK&&this._status!==De.STATUS_CONFIRMED)return!1;if(t=this._ua.normalizeTarget(t),!t)throw new TypeError(`Invalid target: ${l}`);const u=new bE(this);u.sendRefer(t,r);const s=u.id;return this._referSubscribers[s]=u,u.on("requestFailed",()=>{delete this._referSubscribers[s]}),u.on("accepted",()=>{delete this._referSubscribers[s]}),u.on("failed",()=>{delete this._referSubscribers[s]}),u}sendRequest(t,r){return Ie.debug("sendRequest()"),this._dialog.sendRequest(t,r)}receiveNotify(t){Ie.debug("receiveRequest()")}receiveRequest(t){if(Ie.debug("receiveRequest()"),t.method===fe.CANCEL)(this._status===De.STATUS_WAITING_FOR_ANSWER||this._status===De.STATUS_ANSWERED)&&(this._status=De.STATUS_CANCELED,this._request.reply(487),this._failed("remote",t,fe.causes.CANCELED));else switch(t.method){case fe.ACK:if(this._status!==De.STATUS_WAITING_FOR_ACK)return;if(this._status=De.STATUS_CONFIRMED,clearTimeout(this._timers.ackTimer),clearTimeout(this._timers.invite2xxTimer),this._late_sdp){if(!t.body){this.terminate({cause:fe.causes.MISSING_SDP,status_code:400});break}const r={originator:"remote",type:"answer",sdp:t.body};Ie.debug('emit "sdp"'),this.emit("sdp",r);const l=new RTCSessionDescription({type:"answer",sdp:r.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(l)).then(()=>{this._is_confirmed||this._confirmed("remote",t)}).catch(u=>{this.terminate({cause:fe.causes.BAD_MEDIA_DESCRIPTION,status_code:488}),Ie.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',u),this.emit("peerconnection:setremotedescriptionfailed",u)})}else this._is_confirmed||this._confirmed("remote",t);break;case fe.BYE:this._status===De.STATUS_CONFIRMED||this._status===De.STATUS_WAITING_FOR_ACK?(t.reply(200),this._ended("remote",t,fe.causes.BYE)):this._status===De.STATUS_INVITE_RECEIVED||this._status===De.STATUS_WAITING_FOR_ANSWER?(t.reply(200),this._request.reply(487,"BYE Received"),this._ended("remote",t,fe.causes.BYE)):t.reply(403,"Wrong Status");break;case fe.INVITE:this._status===De.STATUS_CONFIRMED?t.hasHeader("replaces")?this._receiveReplaces(t):this._receiveReinvite(t):t.reply(403,"Wrong Status");break;case fe.INFO:if(this._status===De.STATUS_1XX_RECEIVED||this._status===De.STATUS_WAITING_FOR_ANSWER||this._status===De.STATUS_ANSWERED||this._status===De.STATUS_WAITING_FOR_ACK||this._status===De.STATUS_CONFIRMED){const r=t.hasHeader("Content-Type")?t.getHeader("Content-Type").toLowerCase():void 0;r&&r.match(/^application\/dtmf-relay/i)?new dE(this).init_incoming(t):r!==void 0?new hd(this).init_incoming(t):t.reply(415)}else t.reply(403,"Wrong Status");break;case fe.UPDATE:this._status===De.STATUS_CONFIRMED?this._receiveUpdate(t):t.reply(403,"Wrong Status");break;case fe.REFER:this._status===De.STATUS_CONFIRMED?this._receiveRefer(t):t.reply(403,"Wrong Status");break;case fe.NOTIFY:this._status===De.STATUS_CONFIRMED?this._receiveNotify(t):t.reply(403,"Wrong Status");break;default:t.reply(501)}}onTransportError(){Ie.warn("onTransportError()"),this._status!==De.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:fe.causes.CONNECTION_ERROR,cause:fe.causes.CONNECTION_ERROR})}onRequestTimeout(){Ie.warn("onRequestTimeout()"),this._status!==De.STATUS_TERMINATED&&this.terminate({status_code:408,reason_phrase:fe.causes.REQUEST_TIMEOUT,cause:fe.causes.REQUEST_TIMEOUT})}onDialogError(){Ie.warn("onDialogError()"),this._status!==De.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:fe.causes.DIALOG_ERROR,cause:fe.causes.DIALOG_ERROR})}newDTMF(t){Ie.debug("newDTMF()"),this.emit("newDTMF",t)}newInfo(t){Ie.debug("newInfo()"),this.emit("newInfo",t)}_isReadyToReOffer(){return this._rtcReady?this._dialog?this._dialog.uac_pending_reply===!0||this._dialog.uas_pending_reply===!0?(Ie.debug("_isReadyToReOffer() | there is another INVITE/UPDATE transaction in progress"),!1):!0:(Ie.debug("_isReadyToReOffer() | session not established yet"),!1):(Ie.debug("_isReadyToReOffer() | internal WebRTC status not ready"),!1)}_close(){if(Ie.debug("close()"),this._localMediaStream&&this._localMediaStreamLocallyGenerated&&(Ie.debug("close() | closing local MediaStream"),Nt.closeMediaStream(this._localMediaStream)),this._status!==De.STATUS_TERMINATED){if(this._status=De.STATUS_TERMINATED,this._connection)try{this._connection.close()}catch(t){Ie.warn("close() | error closing the RTCPeerConnection: %o",t)}for(const t in this._timers)Object.prototype.hasOwnProperty.call(this._timers,t)&&clearTimeout(this._timers[t]);clearTimeout(this._sessionTimers.timer),this._dialog&&(this._dialog.terminate(),delete this._dialog);for(const t in this._earlyDialogs)Object.prototype.hasOwnProperty.call(this._earlyDialogs,t)&&(this._earlyDialogs[t].terminate(),delete this._earlyDialogs[t]);for(const t in this._referSubscribers)Object.prototype.hasOwnProperty.call(this._referSubscribers,t)&&delete this._referSubscribers[t];this._ua.destroyRTCSession(this)}}_setInvite2xxTimer(t,r){let l=eo.T1;function u(){this._status===De.STATUS_WAITING_FOR_ACK&&(t.reply(200,null,[`Contact: ${this._contact}`],r),l<eo.T2&&(l=l*2,l>eo.T2&&(l=eo.T2)),this._timers.invite2xxTimer=setTimeout(u.bind(this),l))}this._timers.invite2xxTimer=setTimeout(u.bind(this),l)}_setACKTimer(){this._timers.ackTimer=setTimeout(()=>{this._status===De.STATUS_WAITING_FOR_ACK&&(Ie.debug("no ACK received, terminating the session"),clearTimeout(this._timers.invite2xxTimer),this.sendRequest(fe.BYE),this._ended("remote",null,fe.causes.NO_ACK))},eo.TIMER_H)}_createRTCConnection(t,r){this.stunServers,this._connection=new RTCPeerConnection(t,r),this._connection.addEventListener("iceconnectionstatechange",()=>{this._connection.iceConnectionState==="failed"&&this.terminate({cause:fe.causes.RTP_TIMEOUT,status_code:408,reason_phrase:fe.causes.RTP_TIMEOUT})});let l;const u=s=>{this._connection.signalingState!=="stable"&&this._connection.signalingState!=="have-local-offer"||s.candidate&&(this._candidates.push(s.candidate),clearTimeout(l),l=setTimeout(()=>{this.lastTrickleReceived=!0,this.subscribeSent&&!this.isConfigureSent&&(this.addTracks(this.stream.getTracks()),this._ua.emit("changeMainVideoStream",{name:this.display_name,stream:this.stream}),this._sendConfigureMessage({audio:!0,video:!0}).then(()=>{}))},500))};this._connection.onicecandidate=u,Ie.debug('emit "peerconnection"'),this.emit("peerconnection",{peerconnection:this._connection})}_createLocalDescription(t,r){if(Ie.debug("createLocalDescription()"),t!=="offer"&&t!=="answer")throw new Error(`createLocalDescription() | invalid type "${t}"`);const l=this._connection;return this._rtcReady=!1,Promise.resolve().then(()=>t==="offer"?l.createOffer(r).catch(u=>(Ie.warn('emit "peerconnection:createofferfailed" [error:%o]',u),this.emit("peerconnection:createofferfailed",u),Promise.reject(u))):l.createAnswer(r).catch(u=>(Ie.warn('emit "peerconnection:createanswerfailed" [error:%o]',u),this.emit("peerconnection:createanswerfailed",u),Promise.reject(u)))).then(u=>(this.jsepOffer=u,l.setLocalDescription(u).catch(s=>(this._rtcReady=!0,Ie.warn('emit "peerconnection:setlocaldescriptionfailed" [error:%o]',s),this.emit("peerconnection:setlocaldescriptionfailed",s),Promise.reject(s))))).then(()=>{const u=r&&r.iceRestart;if(l.iceGatheringState==="complete"&&!u||l.iceGatheringState==="gathering"&&this._iceReady){this._rtcReady=!0;const s={originator:"local",type:t,sdp:l.localDescription.sdp};return Ie.debug('emit "sdp"'),this.emit("sdp",s),Promise.resolve(s.sdp)}return new Promise(s=>{let n=!1,g,_;this._iceReady=!1;const v=()=>{l.removeEventListener("icecandidate",g),l.removeEventListener("icegatheringstatechange",_),n=!0,this._rtcReady=!0,this._iceReady=!0;const C={originator:"local",type:t,sdp:l.localDescription.sdp};Ie.debug('emit "sdp"'),this.emit("sdp",C),s(C.sdp)};l.addEventListener("icecandidate",g=C=>{const R=C.candidate;R?this.emit("icecandidate",{candidate:R,ready:v}):n||v()}),l.addEventListener("icegatheringstatechange",_=()=>{l.iceGatheringState==="complete"&&!n&&v()})})})}_createDialog(t,r,l){const u=r==="UAS"?t.to_tag:t.from_tag,s=r==="UAS"?t.from_tag:t.to_tag,n=t.call_id+u+s;let g=this._earlyDialogs[n];if(l)return g?!0:(g=new Uu(this,t,r,Uu.C.STATUS_EARLY),g.error?(Ie.debug(g.error),this._failed("remote",t,fe.causes.INTERNAL_ERROR),!1):(this._earlyDialogs[n]=g,!0));{if(this._from_tag=t.from_tag,this._to_tag=t.to_tag,g)return g.update(t,r),this._dialog=g,delete this._earlyDialogs[n],!0;const _=new Uu(this,t,r);return _.error?(Ie.debug(_.error),this._failed("remote",t,fe.causes.INTERNAL_ERROR),!1):(this._dialog=_,!0)}}_receiveReinvite(t){Ie.debug("receiveReinvite()");const r=t.hasHeader("Content-Type")?t.getHeader("Content-Type").toLowerCase():void 0,l={request:t,callback:void 0,reject:s.bind(this)};let u=!1;function s(g={}){u=!0;const _=g.status_code||403,v=g.reason_phrase||"",C=Nt.cloneArray(g.extraHeaders);if(this._status!==De.STATUS_CONFIRMED)return!1;if(_<300||_>=700)throw new TypeError(`Invalid status_code: ${_}`);t.reply(_,v,C)}if(this.emit("reinvite",l),u)return;if(this._late_sdp=!1,!t.body){this._late_sdp=!0,this._remoteHold&&(this._remoteHold=!1,this._onunhold("remote")),this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._createLocalDescription("offer",this._rtcOfferConstraints)).then(g=>{n.call(this,g)}).catch(()=>{t.reply(500)});return}if(r!=="application/sdp"){Ie.debug("invalid Content-Type"),t.reply(415);return}this._processInDialogSdpOffer(t).then(g=>{this._status!==De.STATUS_TERMINATED&&n.call(this,g)}).catch(g=>{Ie.warn(g)});function n(g){const _=[`Contact: ${this._contact}`];this._handleSessionTimersInIncomingRequest(t,_),this._late_sdp&&(g=this._mangleOffer(g)),t.reply(200,null,_,g,()=>{this._status=De.STATUS_WAITING_FOR_ACK,this._setInvite2xxTimer(t,g),this._setACKTimer()}),typeof l.callback=="function"&&l.callback()}}_receiveUpdate(t){Ie.debug("receiveUpdate()");const r=t.hasHeader("Content-Type")?t.getHeader("Content-Type").toLowerCase():void 0,l={request:t,callback:void 0,reject:s.bind(this)};let u=!1;function s(g={}){u=!0;const _=g.status_code||403,v=g.reason_phrase||"",C=Nt.cloneArray(g.extraHeaders);if(this._status!==De.STATUS_CONFIRMED)return!1;if(_<300||_>=700)throw new TypeError(`Invalid status_code: ${_}`);t.reply(_,v,C)}if(this.emit("update",l),u)return;if(!t.body){n.call(this,null);return}if(r!=="application/sdp"){Ie.debug("invalid Content-Type"),t.reply(415);return}this._processInDialogSdpOffer(t).then(g=>{this._status!==De.STATUS_TERMINATED&&n.call(this,g)}).catch(g=>{Ie.warn(g)});function n(g){const _=[`Contact: ${this._contact}`];this._handleSessionTimersInIncomingRequest(t,_),t.reply(200,null,_,g),typeof l.callback=="function"&&l.callback()}}_processInDialogSdpOffer(t){Ie.debug("_processInDialogSdpOffer()");const r=t.parseSDP();let l=!1;for(const n of r.media){if(Pu.indexOf(n.type)===-1)continue;const g=n.direction||r.direction||"sendrecv";if(g==="sendonly"||g==="inactive")l=!0;else{l=!1;break}}const u={originator:"remote",type:"offer",sdp:t.body};Ie.debug('emit "sdp"'),this.emit("sdp",u);const s=new RTCSessionDescription({type:"offer",sdp:u.sdp});return this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>{if(this._status===De.STATUS_TERMINATED)throw new Error("terminated");return this._connection.setRemoteDescription(s).catch(n=>{throw t.reply(488),Ie.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',n),this.emit("peerconnection:setremotedescriptionfailed",n),n})}).then(()=>{if(this._status===De.STATUS_TERMINATED)throw new Error("terminated");this._remoteHold===!0&&l===!1?(this._remoteHold=!1,this._onunhold("remote")):this._remoteHold===!1&&l===!0&&(this._remoteHold=!0,this._onhold("remote"))}).then(()=>{if(this._status===De.STATUS_TERMINATED)throw new Error("terminated");return this._createLocalDescription("answer",this._rtcAnswerConstraints).catch(n=>{throw t.reply(500),Ie.warn('emit "peerconnection:createtelocaldescriptionfailed" [error:%o]',n),n})}).catch(n=>{Ie.warn("_processInDialogSdpOffer() failed [error: %o]",n)}),this._connectionPromiseQueue}_receiveRefer(t){if(Ie.debug("receiveRefer()"),!t.refer_to){Ie.debug("no Refer-To header field present in REFER"),t.reply(400);return}if(t.refer_to.uri.scheme!==fe.SIP){Ie.debug("Refer-To header field points to a non-SIP URI scheme"),t.reply(416);return}t.reply(202);const r=new vE(this,t.cseq);Ie.debug('emit "refer"'),this.emit("refer",{request:t,accept:(s,n)=>{l.call(this,s,n)},reject:()=>{u.call(this)}});function l(s,n={}){if(s=typeof s=="function"?s:null,this._status!==De.STATUS_WAITING_FOR_ACK&&this._status!==De.STATUS_CONFIRMED)return!1;const g=new Lu(this._ua);if(g.on("progress",({response:_})=>{r.notify(_.status_code,_.reason_phrase)}),g.on("accepted",({response:_})=>{r.notify(_.status_code,_.reason_phrase)}),g.on("_failed",({message:_,cause:v})=>{_?r.notify(_.status_code,_.reason_phrase):r.notify(487,v)}),t.refer_to.uri.hasHeader("replaces")){const _=decodeURIComponent(t.refer_to.uri.getHeader("replaces"));n.extraHeaders=Nt.cloneArray(n.extraHeaders),n.extraHeaders.push(`Replaces: ${_}`)}g.connect(t.refer_to.uri.toAor(),n,s)}function u(){r.notify(603)}}_receiveNotify(t){switch(Ie.debug("receiveNotify()"),t.event||t.reply(400),t.event.event){case"refer":{let r,l;if(t.event.params&&t.event.params.id)r=t.event.params.id,l=this._referSubscribers[r];else if(Object.keys(this._referSubscribers).length===1)l=this._referSubscribers[Object.keys(this._referSubscribers)[0]];else{t.reply(400,"Missing event id parameter");return}if(!l){t.reply(481,"Subscription does not exist");return}l.receiveNotify(t),t.reply(200);break}default:t.reply(489)}}_receiveReplaces(t){Ie.debug("receiveReplaces()");function r(u){if(this._status!==De.STATUS_WAITING_FOR_ACK&&this._status!==De.STATUS_CONFIRMED)return!1;const s=new Lu(this._ua);s.on("confirmed",()=>{this.terminate()}),s.init_incoming(t,u)}function l(){Ie.debug("Replaced INVITE rejected by the user"),t.reply(486)}this.emit("replaces",{request:t,accept:u=>{r.call(this,u)},reject:()=>{l.call(this)}})}_getNextTransactionId(){return(this.lastTransaction+1).toString()}_sendInitialRequest(t,r,l){this.ackSent=!1,this.publisherSubscribeSent=!1;const u=new no(this._ua,this._request,{onRequestTimeout:()=>{this.onRequestTimeout()},onTransportError:()=>{this.onTransportError()},onAuthenticated:s=>{this._request=s},onReceiveResponse:s=>{this._receiveInviteResponse(s)}});Promise.resolve().then(()=>{if(l)return l;if(t.audio||t.video)return this._localMediaStreamLocallyGenerated=!0,this.loadStream().catch(s=>{throw this._status===De.STATUS_TERMINATED?new Error("terminated"):(this._failed("local",null,fe.causes.USER_DENIED_MEDIA_ACCESS),Ie.warn('emit "getusermediafailed" [error:%o]',s),this.emit("getusermediafailed",s),s)})}).then(s=>{if(this._status===De.STATUS_TERMINATED)throw new Error("terminated");return this._localMediaStream=s,s&&s.getTracks().forEach(n=>{this._connection.addTrack(n,s)}),this._connecting(this._request),this._createLocalDescription("offer",r).catch(n=>{throw this._failed("local",null,fe.causes.WEBRTC_ERROR),n})}).then(s=>{if(this._is_canceled||this._status===De.STATUS_TERMINATED)throw new Error("terminated");const n={janus:"attach",plugin:"janus.plugin.videoroom",opaque_id:this.opaque_id},g=JSON.stringify(n);this._request.body=g,this._status=De.STATUS_INVITE_SENT,Ie.debug('emit "sending" [request:%o]',this._request),this.emit("sending",{request:this._request}),u.send()}).catch(s=>{this._status!==De.STATUS_TERMINATED&&Ie.warn(s)})}async requestAudioAndVideoPermissions(){this.stream=await this.loadStream()}async setupMediaStream(){await this.requestAudioAndVideoPermissions(),await this.processPlugins()}async changeMediaConstraints(t){this.mediaConstraints={...t},await this.processPlugins(),this.addTracks(this.stream.getTracks()),this._ua.emit("changeMainVideoStream",{name:this.display_name,stream:this.stream})}async loadStream(){const t={};this.isAudioOn?this.mediaConstraints.audio?t.audio=this.mediaConstraints.audio:t.audio=!0:t.audio=!1,this.isVideoOn?this.mediaConstraints.video?t.video=this.mediaConstraints.video:t.video=!0:t.video=!1;let r=null;try{r=await navigator.mediaDevices.getUserMedia(t)}catch{try{t.video=!1,r=await navigator.mediaDevices.getUserMedia(t)}catch{t.audio=!1,t.video=!1,r=await navigator.mediaDevices.getUserMedia(t)}}return r}addTracks(t){this._connection.getSenders().forEach(r=>{this._connection.removeTrack(r)}),t.forEach(r=>{this._connection.addTrack(r)})}getRecordFileName(){return AC+this.room_id+btoa(unescape(encodeURIComponent(this.displayName)))+Date.now()}async processIceCandidates(){for(let t=0;t<this.iceCandidates.length;t++)await this._connection.addIceCandidate(this.iceCandidates[t]);this.iceCandidates=[]}async _sendConfigureMessage(t){const r=this._candidates.map(n=>({janus:"trickle",candidate:n,handle_id:this.handle_id,session_id:this.session_id})),u={configure:{janus:"message",body:{request:"configure",record:!0,filename:this.getRecordFileName(),...t},jsep:this.jsepOffer,handle_id:this.handle_id,session_id:this.session_id},trickles:[...r]},s=["Content-Type: application/json",this.getPTypeHeader(ir.ICE)];this.sendRequest(fe.INFO,{extraHeaders:s,body:JSON.stringify(u),eventHandlers:{onSuccessResponse:async n=>{this.isConfigureSent=!0;const _=n.data.split(`\r
135
- `),v=_[_.length-1],C=JSON.parse(v);await this._connection.setRemoteDescription(C.jsep),this._candidates=[]}}})}_sendMemberStartMessage(t,r){const l={janus:"message",body:{request:"start",room:this.room_id},handle_id:t.handleId,session_id:this.session_id,jsep:r},u=["Content-Type: application/json",this.getPTypeHeader(ir.CONFIGURE)];this.sendRequest(fe.INFO,{extraHeaders:u,body:JSON.stringify(l),eventHandlers:{onSuccessResponse:async s=>{s.status_code===200&&await t.rtcpPeer.setLocalDescription(r)}}})}_sendTrickleMessage(t){const l={trickles:[...t.map(s=>({janus:"trickle",candidate:s,handle_id:this.handle_id,session_id:this.session_id}))]},u=[this.getPTypeHeader(ir.TRICKLE)];this.sendRequest(fe.INFO,{extraHeaders:u,body:JSON.stringify(l),eventHandlers:{onSuccessResponse:async s=>{}}})}async _answerAttachedStream(t,r){let l=null;const u=async _=>{if(!t.rtcpPeer||t.loaded)return;{t.loaded=!0;const H={audio:!0,video:!0};await new Promise(F=>{setTimeout(F,100)}),l=await t.rtcpPeer.createAnswer(H),this._sendMemberStartMessage(t,l)}const v=_.streams[0].getAudioTracks(),C=_.streams[0].getVideoTracks(),R=[];v[0]&&R.push(v[0]),C[0]&&R.push(C[0]);const D=new MediaStream(R);t.stream=D,this._ua.emit("memberJoin",t.memberInfo)};let s,n=[];const g=_=>{t.rtcpPeer.signalingState!=="stable"&&t.rtcpPeer.signalingState!=="have-local-offer"||(n.push(_.candidate||null),clearTimeout(s),s=setTimeout(()=>{this._sendTrickleMessage(n)},500))};t.rtcpPeer=new RTCPeerConnection,t.rtcpPeer.ontrack=u,t.rtcpPeer.onicecandidate=g,t.rtcpPeer.sender=r.sender,await t.rtcpPeer.setRemoteDescription(r.jsep)}_sendJoinMemberRequest(t){const r={janus:"message",body:{request:"join",room:this.room_id,feed:t.info.id,ptype:"subscriber"},handle_id:t.handleId,session_id:this.session_id},l=[this.getPTypeHeader(ir.SUBSCRIBER)];this.sendRequest(fe.SUBSCRIBE,{extraHeaders:l,body:JSON.stringify(r),eventHandlers:{onSuccessResponse:async u=>{var s,n;if(u.status_code===200){const g=JSON.parse(u.body);(n=(s=g==null?void 0:g.plugindata)==null?void 0:s.data)!=null&&n.id&&await this._answerAttachedStream(t,g)}}}})}_attachMember(t){const r={janus:"attach",opaque_id:this.opaque_id,plugin:"janus.plugin.videoroom",session_id:this.session_id},l=[this.getPTypeHeader(ir.SUBSCRIBER)];this.sendRequest(fe.INFO,{extraHeaders:l,body:JSON.stringify(r),eventHandlers:{onSuccessResponse:async u=>{if(u.status_code===200){const n=JSON.parse(u.body).data.id;t.handleId=n,this._sendJoinMemberRequest(t)}}}})}_detachMember(t){const r={janus:"detach",handle_id:t.handleId,session_id:this.session_id},l=[this.getPTypeHeader(ir.SUBSCRIBER)];this.sendRequest(fe.INFO,{extraHeaders:l,body:JSON.stringify(r)}),Nr.stopStreamTracks(t.memberInfo.stream),this._ua.emit("memberHangup",t.memberInfo)}receivePublishers(t){var l,u,s,n,g,_,v,C;const r={...this.memberList};(u=(l=t==null?void 0:t.plugindata)==null?void 0:l.data)==null||u.publishers.forEach(R=>{delete r[R.id],!this.memberList[R.id]&&!this.myFeedList.includes(R.id)&&R.clientID!==this.client_id&&(this.memberList[R.id]=new EC(R,this),this._attachMember(this.memberList[R.id]))}),((n=(s=t==null?void 0:t.plugindata)==null?void 0:s.data)==null?void 0:n.videoroom)==="synced"&&Object.keys(r).forEach(R=>{r[R].hangup(),delete this.memberList[R]}),this.publishers=(_=(g=t==null?void 0:t.plugindata)==null?void 0:g.data)==null?void 0:_.publishers,this.private_id=(C=(v=t==null?void 0:t.plugindata)==null?void 0:v.data)==null?void 0:C.private_id}receiveUnpublished(t){const r=this.memberList[t];r&&(r.hangup(),this._detachMember(r),delete this.memberList[t])}closeSession(){this.stream&&this.stream.getTracks().forEach(r=>{r.stop()}),Object.values(this.memberList).forEach(r=>{r.hangup(),this._detachMember(r)}),this._ua.emit("conferenceEnd",this.id)}async processPlugins(){const t=this._ua.processStreamPlugins;let r=await this.loadStream();for(const l of t)r=await l.process(r);this.stream.getTracks().forEach(l=>{this.stream.removeTrack(l),l.stop()}),r.getTracks().forEach(l=>{this.stream.addTrack(l)})}async resyncPlugins(t){const r=this._ua.processStreamPlugins.filter(l=>l.type===t);for(const l of r)l.running&&l.terminate();if(t==="video"){let l=await this.loadStream();for(const u of r)u.running&&(l=await u.start(l));this.stream.getTracks().forEach(u=>{this.stream.removeTrack(u),u.stop()}),l.getTracks().forEach(u=>{this.stream.addTrack(u)}),this._overrideSenderTracks(this.stream,this._connection),this._ua.emit("changeMainVideoStream",{name:this.display_name,stream:this.stream})}else{const l=this._ua.newStreamPlugins.find(g=>g.type===t);let s=l.getStream().clone();for(const g of r)g.running&&(s=await g.start(s));const n=l.getConnection();this._overrideSenderTracks(s,n),this._ua.emit("changePluginStream",{type:t,stream:s})}}stopProcessPlugins(t){const r=this._ua.processStreamPlugins.filter(l=>l.type===t);for(const l of r)l.running&&l.kill()}_receiveInviteResponse(t){if(Ie.debug("receiveInviteResponse()"),this._dialog&&t.status_code>=200&&t.status_code<=299&&!this.ackSent)if(this._dialog.id.call_id===t.call_id&&this._dialog.id.local_tag===t.from_tag&&this._dialog.id.remote_tag===t.to_tag){this.ackSent=!0,this.sendRequest(fe.ACK);return}else{const r=new Uu(this,t,"UAC");if(r.error!==void 0){Ie.debug(r.error);return}this.sendRequest(fe.ACK),this.sendRequest(fe.BYE);return}if(this.ackSent&&!this.publisherSubscribeSent){const r=JSON.parse(t.body);this.setupMediaStream().then(()=>{this.session_id=r.session_id,this.handle_id=r.data.id,this.client_id=dp();const l={janus:"message",body:{request:"join",room:this.room_id,ptype:"publisher",display:this.display_name,clientID:this.client_id,opaque_id:this.opaque_id},handle_id:this.handle_id},u=[this.getPTypeHeader(ir.PUBLISHER)];this.sendRequest(fe.SUBSCRIBE,{extraHeaders:u,body:JSON.stringify(l),eventHandlers:{onSuccessResponse:async s=>{var n,g,_,v;if(s.status_code===200){if(this.subscribeSent=!0,s.body)try{const C=JSON.parse(s.body)||{};((g=(n=C.plugindata)==null?void 0:n.data)==null?void 0:g.videoroom)==="joined"&&this.myFeedList.push(C.plugindata.data.id),(v=(_=C.plugindata)==null?void 0:_.data)!=null&&v.publishers&&this.receivePublishers(C)}catch(C){console.error(C)}this.lastTrickleReceived&&!this.isConfigureSent&&(this.addTracks(this.stream.getTracks()),this._ua.emit("changeMainVideoStream",{name:this.display_name,stream:this.stream}),this._sendConfigureMessage({audio:!0,video:!0}).then(()=>{})),this._ua.emit("conferenceStart")}}}}),this.publisherSubscribeSent=!0})}if(this._is_canceled){t.status_code>=100&&t.status_code<200?this._request.cancel(this._cancel_reason):t.status_code>=200&&t.status_code<299&&this._acceptAndTerminate(t);return}if(!(this._status!==De.STATUS_INVITE_SENT&&this._status!==De.STATUS_1XX_RECEIVED))switch(!0){case/^100$/.test(t.status_code):this._status=De.STATUS_1XX_RECEIVED;break;case/^1[0-9]{2}$/.test(t.status_code):{if(!t.to_tag){Ie.debug("1xx response received without to tag");break}if(t.hasHeader("contact")&&!this._createDialog(t,"UAC",!0))break;if(this._status=De.STATUS_1XX_RECEIVED,!t.body){this._progress("remote",t);break}const r={originator:"remote",type:"answer",sdp:t.body};Ie.debug('emit "sdp"'),this.emit("sdp",r);const l=new RTCSessionDescription({type:"answer",sdp:r.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(l)).then(()=>this._progress("remote",t)).catch(u=>{Ie.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',u),this.emit("peerconnection:setremotedescriptionfailed",u)});break}case/^2[0-9]{2}$/.test(t.status_code):{if(this._status=De.STATUS_CONFIRMED,!t.body){this._acceptAndTerminate(t,400,fe.causes.MISSING_SDP),this._failed("remote",t,fe.causes.BAD_MEDIA_DESCRIPTION);break}if(!this._createDialog(t,"UAC"))break;break}default:{const r=Nt.sipErrorCause(t.status_code);this._failed("remote",t,r)}}}_sendReinvite(t={}){Ie.debug("sendReinvite()");const r=Nt.cloneArray(t.extraHeaders),l=Nt.cloneObject(t.eventHandlers),u=t.rtcOfferConstraints||this._rtcOfferConstraints||null;let s=!1;r.push(`Contact: ${this._contact}`),r.push("Content-Type: application/sdp"),this._sessionTimers.running&&r.push(`Session-Expires: ${this._sessionTimers.currentExpires};refresher=${this._sessionTimers.refresher?"uac":"uas"}`),this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._createLocalDescription("offer",u)).then(_=>{_=this._mangleOffer(_);const v={originator:"local",type:"offer",sdp:_};Ie.debug('emit "sdp"'),this.emit("sdp",v),this.sendRequest(fe.INVITE,{extraHeaders:r,body:_,eventHandlers:{onSuccessResponse:C=>{n.call(this,C),s=!0},onErrorResponse:C=>{g.call(this,C)},onTransportError:()=>{this.onTransportError()},onRequestTimeout:()=>{this.onRequestTimeout()},onDialogError:()=>{this.onDialogError()}}})}).catch(()=>{g()});function n(_){if(this._status===De.STATUS_TERMINATED||(this.sendRequest(fe.ACK),s))return;if(this._handleSessionTimersInIncomingResponse(_),_.body){if(!_.hasHeader("Content-Type")||_.getHeader("Content-Type").toLowerCase()!=="application/sdp"){g.call(this);return}}else{g.call(this);return}const v={originator:"remote",type:"answer",sdp:_.body};Ie.debug('emit "sdp"'),this.emit("sdp",v);const C=new RTCSessionDescription({type:"answer",sdp:v.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(C)).then(()=>{l.succeeded&&l.succeeded(_)}).catch(R=>{g.call(this),Ie.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',R),this.emit("peerconnection:setremotedescriptionfailed",R)})}function g(_){l.failed&&l.failed(_)}}_sendUpdate(t={}){Ie.debug("sendUpdate()");const r=Nt.cloneArray(t.extraHeaders),l=Nt.cloneObject(t.eventHandlers),u=t.rtcOfferConstraints||this._rtcOfferConstraints||null,s=t.sdpOffer||!1;let n=!1;r.push(`Contact: ${this._contact}`),this._sessionTimers.running&&r.push(`Session-Expires: ${this._sessionTimers.currentExpires};refresher=${this._sessionTimers.refresher?"uac":"uas"}`),s?(r.push("Content-Type: application/sdp"),this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._createLocalDescription("offer",u)).then(v=>{v=this._mangleOffer(v);const C={originator:"local",type:"offer",sdp:v};Ie.debug('emit "sdp"'),this.emit("sdp",C),this.sendRequest(fe.UPDATE,{extraHeaders:r,body:v,eventHandlers:{onSuccessResponse:R=>{g.call(this,R),n=!0},onErrorResponse:R=>{_.call(this,R)},onTransportError:()=>{this.onTransportError()},onRequestTimeout:()=>{this.onRequestTimeout()},onDialogError:()=>{this.onDialogError()}}})}).catch(()=>{_.call(this)})):this.sendRequest(fe.UPDATE,{extraHeaders:r,eventHandlers:{onSuccessResponse:v=>{g.call(this,v)},onErrorResponse:v=>{_.call(this,v)},onTransportError:()=>{this.onTransportError()},onRequestTimeout:()=>{this.onRequestTimeout()},onDialogError:()=>{this.onDialogError()}}});function g(v){if(this._status!==De.STATUS_TERMINATED&&!n)if(this._handleSessionTimersInIncomingResponse(v),s){if(v.body){if(!v.hasHeader("Content-Type")||v.getHeader("Content-Type").toLowerCase()!=="application/sdp"){_.call(this);return}}else{_.call(this);return}const C={originator:"remote",type:"answer",sdp:v.body};Ie.debug('emit "sdp"'),this.emit("sdp",C);const R=new RTCSessionDescription({type:"answer",sdp:C.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(R)).then(()=>{l.succeeded&&l.succeeded(v)}).catch(D=>{_.call(this),Ie.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',D),this.emit("peerconnection:setremotedescriptionfailed",D)})}else l.succeeded&&l.succeeded(v)}function _(v){l.failed&&l.failed(v)}}_acceptAndTerminate(t,r,l){Ie.debug("acceptAndTerminate()");const u=[];r&&(l=l||fe.REASON_PHRASE[r]||"",u.push(`Reason: SIP ;cause=${r}; text="${l}"`)),(this._dialog||this._createDialog(t,"UAC"))&&(this.sendRequest(fe.ACK),this.sendRequest(fe.BYE,{extraHeaders:u})),this._status=De.STATUS_TERMINATED}_mangleOffer(t){if(!this._localHold&&!this._remoteHold)return t;if(t=sr.parse(t),this._localHold&&!this._remoteHold){Ie.debug("mangleOffer() | me on hold, mangling offer");for(const r of t.media)Pu.indexOf(r.type)!==-1&&(r.direction?r.direction==="sendrecv"?r.direction="sendonly":r.direction==="recvonly"&&(r.direction="inactive"):r.direction="sendonly")}else if(this._localHold&&this._remoteHold){Ie.debug("mangleOffer() | both on hold, mangling offer");for(const r of t.media)Pu.indexOf(r.type)!==-1&&(r.direction="inactive")}else if(this._remoteHold){Ie.debug("mangleOffer() | remote on hold, mangling offer");for(const r of t.media)Pu.indexOf(r.type)!==-1&&(r.direction?r.direction==="sendrecv"?r.direction="recvonly":r.direction==="recvonly"&&(r.direction="inactive"):r.direction="recvonly")}return sr.write(t)}_setLocalMediaStatus(){let t=!0,r=!0;(this._localHold||this._remoteHold)&&(t=!1,r=!1),this._audioMuted&&(t=!1),this._videoMuted&&(r=!1),this._toggleMuteAudio(!t),this._toggleMuteVideo(!r)}_handleSessionTimersInIncomingRequest(t,r){if(!this._sessionTimers.enabled)return;let l;t.session_expires&&t.session_expires>=fe.MIN_SESSION_EXPIRES?(this._sessionTimers.currentExpires=t.session_expires,l=t.session_expires_refresher||"uas"):(this._sessionTimers.currentExpires=this._sessionTimers.defaultExpires,l="uas"),r.push(`Session-Expires: ${this._sessionTimers.currentExpires};refresher=${l}`),this._sessionTimers.refresher=l==="uas",this._runSessionTimer()}_handleSessionTimersInIncomingResponse(t){if(!this._sessionTimers.enabled)return;let r;t.session_expires&&t.session_expires>=fe.MIN_SESSION_EXPIRES?(this._sessionTimers.currentExpires=t.session_expires,r=t.session_expires_refresher||"uac"):(this._sessionTimers.currentExpires=this._sessionTimers.defaultExpires,r="uac"),this._sessionTimers.refresher=r==="uac",this._runSessionTimer()}_runSessionTimer(){const t=this._sessionTimers.currentExpires;this._sessionTimers.running=!0,clearTimeout(this._sessionTimers.timer),this._sessionTimers.refresher?this._sessionTimers.timer=setTimeout(()=>{this._status!==De.STATUS_TERMINATED&&this._isReadyToReOffer()&&(Ie.debug("runSessionTimer() | sending session refresh request"),this._sessionTimers.refreshMethod===fe.UPDATE?this._sendUpdate():this._sendReinvite())},t*500):this._sessionTimers.timer=setTimeout(()=>{this._status!==De.STATUS_TERMINATED&&(Ie.warn("runSessionTimer() | timer expired, terminating the session"),this.terminate({cause:fe.causes.REQUEST_TIMEOUT,status_code:408,reason_phrase:"Session Timer Expired"}))},t*1100)}_toggleMuteAudio(t){const r=this._connection.getSenders().filter(l=>l.track&&l.track.kind==="audio");for(const l of r)l.track.enabled=!t}_toggleMuteVideo(t){const r=this._connection.getSenders().filter(l=>l.track&&l.track.kind==="video");for(const l of r)l.track.enabled=!t}_newJanusSession(t,r){Ie.debug("newRTCSession()"),this._ua.newJanusSession(this,{originator:t,session:this,request:r})}_connecting(t){Ie.debug("session connecting"),Ie.debug('emit "connecting"'),this.emit("connecting",{request:t})}_progress(t,r){Ie.debug("session progress"),Ie.debug('emit "progress"'),this.emit("progress",{originator:t,response:r||null})}_accepted(t,r){Ie.debug("session accepted"),this._start_time=new Date,Ie.debug('emit "accepted"'),this.emit("accepted",{originator:t,response:r||null})}_confirmed(t,r){Ie.debug("session confirmed"),this._is_confirmed=!0,Ie.debug('emit "confirmed"'),this.emit("confirmed",{originator:t,ack:r||null})}_ended(t,r,l){Ie.debug("session ended"),this._end_time=new Date,this._close(),Ie.debug('emit "ended"'),this.emit("ended",{originator:t,message:r||null,cause:l})}_failed(t,r,l){Ie.debug("session failed"),Ie.debug('emit "_failed"'),this.emit("_failed",{originator:t,message:r||null,cause:l}),this._close(),Ie.debug('emit "failed"'),this.emit("failed",{originator:t,message:r||null,cause:l})}_onhold(t){Ie.debug("session onhold"),this._setLocalMediaStatus(),Ie.debug('emit "hold"'),this.emit("hold",{originator:t})}_onunhold(t){Ie.debug("session onunhold"),this._setLocalMediaStatus(),Ie.debug('emit "unhold"'),this.emit("unhold",{originator:t})}_onmute({audio:t,video:r}){Ie.debug("session onmute"),this._setLocalMediaStatus(),Ie.debug('emit "muted"'),this.emit("muted",{audio:t,video:r})}_onunmute({audio:t,video:r}){Ie.debug("session onunmute"),this._setLocalMediaStatus(),Ie.debug('emit "unmuted"'),this.emit("unmuted",{audio:t,video:r})}}class ml{constructor(t){if(this.headers={},t.length>0){let r=!1;const l=t.split(`\r
134
+ `,sp.send(l)}const aC=Ht(rp);var _o={};const pl=xs(),Aa=Et,wd=Dr(),np=Nn(),Ed=gd,Cd=Pn;_o.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:Aa.UPDATE,session_timers_force_refresher:!1,no_answer_timeout:60,register:!0,register_expires:600,registrar_server:null,sockets:null,connection_recovery_max_interval:Aa.CONNECTION_RECOVERY_MAX_INTERVAL,connection_recovery_min_interval:Aa.CONNECTION_RECOVERY_MIN_INTERVAL,extra_headers:null,via_host:`${pl.createRandomToken(12)}.invalid`};const ku={mandatory:{sockets(f){const t=[];if(Ed.isSocket(f))t.push({socket:f});else if(Array.isArray(f)&&f.length)for(const r of f)Object.prototype.hasOwnProperty.call(r,"socket")&&Ed.isSocket(r.socket)?t.push(r):Ed.isSocket(r)&&t.push({socket:r});else return;return t},uri(f){/^sip:/i.test(f)||(f=`${Aa.SIP}:${f}`);const t=np.parse(f);if(t)return t.user?t:void 0}},optional:{authorization_user(f){if(wd.parse(`"${f}"`,"quoted_string")!==-1)return f},authorization_jwt(f){if(typeof f=="string")return f},user_agent(f){if(typeof f=="string")return f},connection_recovery_max_interval(f){if(pl.isDecimal(f)){const t=Number(f);if(t>0)return t}},connection_recovery_min_interval(f){if(pl.isDecimal(f)){const t=Number(f);if(t>0)return t}},contact_uri(f){if(typeof f=="string"){const t=wd.parse(f,"SIP_URI");if(t!==-1)return t}},display_name(f){return f},instance_id(f){if(/^uuid:/i.test(f)&&(f=f.substr(5)),wd.parse(f,"uuid")!==-1)return f},no_answer_timeout(f){if(pl.isDecimal(f)){const t=Number(f);if(t>0)return t}},session_timers(f){if(typeof f=="boolean")return f},session_timers_refresh_method(f){if(typeof f=="string"&&(f=f.toUpperCase(),f===Aa.INVITE||f===Aa.UPDATE))return f},session_timers_force_refresher(f){if(typeof f=="boolean")return f},password(f){return String(f)},realm(f){return String(f)},ha1(f){return String(f)},register(f){if(typeof f=="boolean")return f},register_expires(f){if(pl.isDecimal(f)){const t=Number(f);if(t>0)return t}},registrar_server(f){/^sip:/i.test(f)||(f=`${Aa.SIP}:${f}`);const t=np.parse(f);if(t)return t.user?void 0:t},use_preloaded_route(f){if(typeof f=="boolean")return f},extra_headers(f){const t=[];if(Array.isArray(f)&&f.length)for(const r of f)typeof r=="string"&&t.push(r);else return;return t}}};_o.load=(f,t)=>{for(const r in ku.mandatory)if(t.hasOwnProperty(r)){const l=t[r],u=ku.mandatory[r](l);if(u!==void 0)f[r]=u;else throw new Cd.ConfigurationError(r,l)}else throw new Cd.ConfigurationError(r);for(const r in ku.optional)if(t.hasOwnProperty(r)){const l=t[r];if(pl.isEmpty(l))continue;const u=ku.optional[r](l);if(u!==void 0)f[r]=u;else throw new Cd.ConfigurationError(r,l)}};const lC=ys.EventEmitter,oC=gs,ks=Et,uC=Qw,ip=K_,ap=ME,lp=FE,Ad=hl,cC=X_,Nu=xs(),dC=Pn,fC=Nn(),hC=Z_,Id=Ds,_C=rp,Rd=_o,Jt=new oC("UA"),Ns={STATUS_INIT:0,STATUS_READY:1,STATUS_USER_CLOSED:2,STATUS_NOT_READY:3,CONFIGURATION_ERROR:1,NETWORK_ERROR:2};var op=class extends lC{static get C(){return Ns}constructor(t){if(Jt.debug("new() [configuration:%o]",t),super(),this._cache={credentials:{}},this._configuration=Object.assign({},Rd.settings),this._dynConfiguration={},this._dialogs={},this._applicants={},this._sessions={},this._transport=null,this._contact=null,this._status=Ns.STATUS_INIT,this._error=null,this._transactions={nist:{},nict:{},ist:{},ict:{}},this._data={},this._closeTimer=null,t===void 0)throw new TypeError("Not enough arguments");try{this._loadConfig(t)}catch(r){throw this._status=Ns.STATUS_NOT_READY,this._error=Ns.CONFIGURATION_ERROR,r}this._registrator=new uC(this)}get C(){return Ns}get status(){return this._status}get contact(){return this._contact}get configuration(){return this._configuration}get transport(){return this._transport}start(){Jt.debug("start()"),this._status===Ns.STATUS_INIT?this._transport.connect():this._status===Ns.STATUS_USER_CLOSED?(Jt.debug("restarting UA"),this._closeTimer!==null&&(clearTimeout(this._closeTimer),this._closeTimer=null,this._transport.disconnect()),this._status=Ns.STATUS_INIT,this._transport.connect()):this._status===Ns.STATUS_READY?Jt.debug("UA is in READY status, not restarted"):Jt.debug("ERROR: connection is down, Auto-Recovery system is trying to reconnect"),this._dynConfiguration.register=this._configuration.register}register(){Jt.debug("register()"),this._dynConfiguration.register=!0,this._registrator.register()}unregister(t){Jt.debug("unregister()"),this._dynConfiguration.register=!1,this._registrator.unregister(t)}registrator(){return this._registrator}isRegistered(){return this._registrator.registered}isConnected(){return this._transport.isConnected()}call(t,r){Jt.debug("call()");const l=new ip(this);return l.connect(t,r),l}sendMessage(t,r,l){Jt.debug("sendMessage()");const u=new ap(this);return u.send(t,r,l),u}sendOptions(t,r,l){Jt.debug("sendOptions()");const u=new lp(this);return u.send(t,r,l),u}terminateSessions(t){Jt.debug("terminateSessions()");for(const r in this._sessions)this._sessions[r].isEnded()||this._sessions[r].terminate(t)}stop(){if(Jt.debug("stop()"),this._dynConfiguration={},this._status===Ns.STATUS_USER_CLOSED){Jt.debug("UA already closed");return}this._registrator.close();const t=Object.keys(this._sessions).length;for(const l in this._sessions)if(Object.prototype.hasOwnProperty.call(this._sessions,l)){Jt.debug(`closing session ${l}`);try{this._sessions[l].terminate()}catch{}}for(const l in this._applicants)if(Object.prototype.hasOwnProperty.call(this._applicants,l))try{this._applicants[l].close()}catch{}this._status=Ns.STATUS_USER_CLOSED,Object.keys(this._transactions.nict).length+Object.keys(this._transactions.nist).length+Object.keys(this._transactions.ict).length+Object.keys(this._transactions.ist).length===0&&t===0?this._transport.disconnect():this._closeTimer=setTimeout(()=>{this._closeTimer=null,this._transport.disconnect()},2e3)}normalizeTarget(t){return Nu.normalizeTarget(t,this._configuration.hostport_params)}get(t){switch(t){case"authorization_user":return this._configuration.authorization_user;case"realm":return this._configuration.realm;case"ha1":return this._configuration.ha1;case"authorization_jwt":return this._configuration.authorization_jwt;default:Jt.warn('get() | cannot get "%s" parameter in runtime',t);return}}set(t,r){switch(t){case"authorization_user":{this._configuration.authorization_user=String(r);break}case"password":{this._configuration.password=String(r);break}case"realm":{this._configuration.realm=String(r);break}case"ha1":{this._configuration.ha1=String(r),this._configuration.password=null;break}case"authorization_jwt":{this._configuration.authorization_jwt=String(r);break}case"display_name":{this._configuration.display_name=r;break}default:return Jt.warn('set() | cannot set "%s" parameter in runtime',t),!1}return!0}newTransaction(t){this._transactions[t.type][t.id]=t,this.emit("newTransaction",{transaction:t})}destroyTransaction(t){delete this._transactions[t.type][t.id],this.emit("transactionDestroyed",{transaction:t})}newDialog(t){this._dialogs[t.id]=t}destroyDialog(t){delete this._dialogs[t.id]}newMessage(t,r){this._applicants[t]=t,this.emit("newMessage",r)}newOptions(t,r){this._applicants[t]=t,this.emit("newOptions",r)}destroyMessage(t){delete this._applicants[t]}newRTCSession(t,r){this._sessions[t.id]=t,this.emit("newRTCSession",r)}destroyRTCSession(t){delete this._sessions[t.id]}registered(t){this.emit("registered",t)}unregistered(t){this.emit("unregistered",t)}registrationFailed(t){this.emit("registrationFailed",t)}receiveRequest(t){const r=t.method;if(t.ruri.user!==this._configuration.uri.user&&t.ruri.user!==this._contact.uri.user){Jt.debug("Request-URI does not point to us"),t.method!==ks.ACK&&t.reply_sl(404);return}if(t.ruri.scheme===ks.SIPS){t.reply_sl(416);return}if(Ad.checkTransaction(this,t))return;if(r===ks.INVITE?new Ad.InviteServerTransaction(this,this._transport,t):r!==ks.ACK&&r!==ks.CANCEL&&new Ad.NonInviteServerTransaction(this,this._transport,t),r===ks.OPTIONS){if(this.listeners("newOptions").length===0){t.reply(200);return}new lp(this).init_incoming(t)}else if(r===ks.MESSAGE){if(this.listeners("newMessage").length===0){t.reply(405);return}new ap(this).init_incoming(t)}else if(r===ks.INVITE&&!t.to_tag&&this.listeners("newRTCSession").length===0){t.reply(405);return}let l,u;if(t.to_tag)l=this._findDialog(t.call_id,t.from_tag,t.to_tag),l?l.receiveRequest(t):r===ks.NOTIFY?(u=this._findSession(t),u?u.receiveRequest(t):(Jt.debug("received NOTIFY request for a non existent subscription"),t.reply(481,"Subscription does not exist"))):r!==ks.ACK&&t.reply(481);else switch(r){case ks.INVITE:if(window.RTCPeerConnection)if(t.hasHeader("replaces")){const s=t.replaces;l=this._findDialog(s.call_id,s.from_tag,s.to_tag),l?(u=l.owner,u.isEnded()?t.reply(603):u.receiveRequest(t)):t.reply(481)}else u=new ip(this),u.init_incoming(t);else Jt.warn("INVITE received but WebRTC is not supported"),t.reply(488);break;case ks.BYE:t.reply(481);break;case ks.CANCEL:u=this._findSession(t),u?u.receiveRequest(t):Jt.debug("received CANCEL request for a non existent session");break;case ks.ACK:break;case ks.NOTIFY:this.emit("sipEvent",{event:t.event,request:t}),t.reply(200);break;default:t.reply(405);break}}_findSession({call_id:t,from_tag:r,to_tag:l}){const u=t+r,s=this._sessions[u],n=t+l,g=this._sessions[n];return s||g||null}_findDialog(t,r,l){let u=t+r+l,s=this._dialogs[u];return s||(u=t+l+r,s=this._dialogs[u],s||null)}_loadConfig(t){try{Rd.load(this._configuration,t)}catch(u){throw u}this._configuration.display_name===0&&(this._configuration.display_name="0"),this._configuration.instance_id||(this._configuration.instance_id=Nu.newUUID()),this._configuration.jssip_id=Nu.createRandomToken(5);const r=this._configuration.uri.clone();r.user=null,this._configuration.hostport_params=r.toString().replace(/^sip:/i,"");try{this._transport=new cC(this._configuration.sockets,{max_interval:this._configuration.connection_recovery_max_interval,min_interval:this._configuration.connection_recovery_min_interval}),this._transport.onconnecting=pC.bind(this),this._transport.onconnect=mC.bind(this),this._transport.ondisconnect=gC.bind(this),this._transport.ondata=vC.bind(this)}catch(u){throw Jt.warn(u),new dC.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 u=this._configuration.uri.clone();u.user=null,u.clearParams(),u.clearHeaders(),this._configuration.registrar_server=u}this._configuration.no_answer_timeout*=1e3,this._configuration.contact_uri?this._configuration.via_host=this._configuration.contact_uri.host:this._configuration.contact_uri=new fC("sip",Nu.createRandomToken(8),this._configuration.via_host,null,{transport:"ws"}),this._contact={pub_gruu:null,temp_gruu:null,uri:this._configuration.contact_uri,toString(u={}){const s=u.anonymous||null,n=u.outbound||null;let g="<";return s?g+=this.temp_gruu||"sip:anonymous@anonymous.invalid;transport=ws":g+=this.pub_gruu||this.uri.toString(),n&&(s?!this.temp_gruu:!this.pub_gruu)&&(g+=";ob"),g+=">",g}};const l=["authorization_user","password","realm","ha1","authorization_jwt","display_name","register"];for(const u in this._configuration)Object.prototype.hasOwnProperty.call(this._configuration,u)&&(l.indexOf(u)!==-1?Object.defineProperty(this._configuration,u,{writable:!0,configurable:!1}):Object.defineProperty(this._configuration,u,{writable:!1,configurable:!1}));Jt.debug("configuration parameters after validation:");for(const u in this._configuration)if(Object.prototype.hasOwnProperty.call(Rd.settings,u))switch(u){case"uri":case"registrar_server":Jt.debug(`- ${u}: ${this._configuration[u]}`);break;case"password":case"ha1":case"authorization_jwt":Jt.debug(`- ${u}: NOT SHOWN`);break;default:Jt.debug(`- ${u}: ${JSON.stringify(this._configuration[u])}`)}}};function pC(f){this.emit("connecting",f)}function mC(f){this._status!==Ns.STATUS_USER_CLOSED&&(this._status=Ns.STATUS_READY,this._error=null,this.emit("connected",f),this._dynConfiguration.register&&this._registrator.register())}function gC(f){const t=["nict","ict","nist","ist"];for(const r of t)for(const l in this._transactions[r])Object.prototype.hasOwnProperty.call(this._transactions[r],l)&&this._transactions[r][l].onTransportError();this.emit("disconnected",f),this._registrator.onTransportClosed(),this._status!==Ns.STATUS_USER_CLOSED&&(this._status=Ns.STATUS_NOT_READY,this._error=Ns.NETWORK_ERROR)}function vC(f){const t=f.transport;let r=f.message;if(r=hC.parseMessage(r,this),!!r&&!(this._status===Ns.STATUS_USER_CLOSED&&r instanceof Id.IncomingRequest)&&_C(r,this,t)){if(r instanceof Id.IncomingRequest)r.transport=t,this.receiveRequest(r);else if(r instanceof Id.IncomingResponse){let l;switch(r.method){case ks.INVITE:l=this._transactions.ict[r.via_branch],l&&l.receiveResponse(r);break;case ks.ACK:break;default:l=this._transactions.nict[r.via_branch],l&&l.receiveResponse(r);break}}}}const yC=Ht(op);for(var Ms=[],$d=0;$d<256;++$d)Ms.push(($d+256).toString(16).slice(1));function TC(f,t=0){return(Ms[f[t+0]]+Ms[f[t+1]]+Ms[f[t+2]]+Ms[f[t+3]]+"-"+Ms[f[t+4]]+Ms[f[t+5]]+"-"+Ms[f[t+6]]+Ms[f[t+7]]+"-"+Ms[f[t+8]]+Ms[f[t+9]]+"-"+Ms[f[t+10]]+Ms[f[t+11]]+Ms[f[t+12]]+Ms[f[t+13]]+Ms[f[t+14]]+Ms[f[t+15]]).toLowerCase()}var Mu,SC=new Uint8Array(16);function bC(){if(!Mu&&(Mu=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!Mu))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Mu(SC)}var wC=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);const up={randomUUID:wC};function cp(f,t,r){if(up.randomUUID&&!t&&!f)return up.randomUUID();f=f||{};var l=f.random||(f.rng||bC)();if(l[6]=l[6]&15|64,l[8]=l[8]&63|128,t){r=r||0;for(var u=0;u<16;++u)t[r+u]=l[u];return t}return TC(l)}var Nt=xs();const Ln=Ht(Nt),xd=new Su("Dialog"),Ii={STATUS_EARLY:1,STATUS_CONFIRMED:2,STATUS_TERMINATED:3};class Uu{static get C(){return Ii}constructor(t,r,l,u=Ii.STATUS_CONFIRMED){if(this._owner=t,this._ua=t._ua,this._uac_pending_reply=!1,this._uas_pending_reply=!1,r instanceof Ds.IncomingResponse&&(u=r.status_code<200?Ii.STATUS_EARLY:Ii.STATUS_CONFIRMED),l==="UAS"){this._id={call_id:r.call_id,local_tag:r.to_tag,remote_tag:r.from_tag,toString(){return this.call_id+this.local_tag+this.remote_tag}},this._state=u,this._remote_seqnum=r.cseq,this._local_uri=r.parseHeader("to").uri,this._remote_uri=r.parseHeader("from").uri;let s=r.getHeaders("to")[0].split(";")[0];s=s.match(/<([^>]*)>/)[1],this._remote_target=s,this._route_set=r.getHeaders("record-route"),this._ack_seqnum=this._remote_seqnum}else if(l==="UAC"){this._id={call_id:r.call_id,local_tag:r.from_tag,remote_tag:r.to_tag,toString(){return this.call_id+this.local_tag+this.remote_tag}},this._state=u,this._local_seqnum=r.cseq,this._local_uri=r.parseHeader("from").uri,this._remote_uri=r.parseHeader("to").uri;let s=r.getHeaders("to")[0].split(";")[0];s=s.match(/<([^>]*)>/)[1],this._remote_target=s,this._route_set=r.getHeaders("record-route").reverse(),this._ack_seqnum=null}this._ua.newDialog(this),xd.debug(`new ${l} dialog created with status ${this._state===Ii.STATUS_EARLY?"EARLY":"CONFIRMED"}`)}get id(){return this._id}get local_seqnum(){return this._local_seqnum}set local_seqnum(t){this._local_seqnum=t}get owner(){return this._owner}get uac_pending_reply(){return this._uac_pending_reply}set uac_pending_reply(t){this._uac_pending_reply=t}get uas_pending_reply(){return this._uas_pending_reply}isTerminated(){return this._status===Ii.STATUS_TERMINATED}update(t,r){this._state=Ii.STATUS_CONFIRMED,xd.debug(`dialog ${this._id.toString()} changed to CONFIRMED state`),r==="UAC"&&(this._route_set=t.getHeaders("record-route").reverse())}terminate(){xd.debug(`dialog ${this._id.toString()} deleted`),this._ua.destroyDialog(this),this._state=Ii.STATUS_TERMINATED}sendRequest(t,r={}){const l=Ln.cloneArray(r.extraHeaders),u=Ln.cloneObject(r.eventHandlers),s=r.body||null,n=this._createRequest(t,l,s);return u.onAuthenticated=()=>{this._local_seqnum+=1},new rE(this,n,u).send(),n}receiveRequest(t){this._checkInDialogRequest(t)&&(t.method===fe.ACK&&this._ack_seqnum!==null?this._ack_seqnum=null:t.method===fe.INVITE&&(this._ack_seqnum=t.cseq),this._owner.receiveRequest(t))}_createRequest(t,r,l){r=Ln.cloneArray(r),this._local_seqnum||(this._local_seqnum=Math.floor(Math.random()*1e4));const u=t===fe.CANCEL||t===fe.ACK?this._local_seqnum:this._local_seqnum+=1;return new Ds.OutgoingRequest(t,this._remote_target,this._ua,{cseq:u,call_id:this._id.call_id,from_uri:this._local_uri,from_tag:this._id.local_tag,to_uri:this._remote_uri,to_tag:this._id.remote_tag,route_set:this._route_set},r,l)}_checkInDialogRequest(t){if(!this._remote_seqnum)this._remote_seqnum=t.cseq;else if(t.cseq<this._remote_seqnum)if(t.method===fe.ACK){if(this._ack_seqnum===null||t.cseq!==this._ack_seqnum)return!1}else return t.reply(500),!1;else t.cseq>this._remote_seqnum&&(this._remote_seqnum=t.cseq);if(t.method===fe.INVITE||t.method===fe.UPDATE&&t.body){if(this._uac_pending_reply===!0)t.reply(491);else if(this._uas_pending_reply===!0){const r=(Math.random()*10|0)+1;return t.reply(500,null,[`Retry-After:${r}`]),!1}else{this._uas_pending_reply=!0;const r=()=>{(t.server_transaction.state===Er.C.STATUS_ACCEPTED||t.server_transaction.state===Er.C.STATUS_COMPLETED||t.server_transaction.state===Er.C.STATUS_TERMINATED)&&(t.server_transaction.removeListener("stateChanged",r),this._uas_pending_reply=!1)};t.server_transaction.on("stateChanged",r)}t.hasHeader("contact")&&t.server_transaction.on("stateChanged",()=>{t.server_transaction.state===Er.C.STATUS_ACCEPTED&&(this._remote_target=t.parseHeader("contact").uri)})}else t.method===fe.NOTIFY&&t.hasHeader("contact")&&t.server_transaction.on("stateChanged",()=>{t.server_transaction.state===Er.C.STATUS_COMPLETED&&(this._remote_target=t.parseHeader("contact").uri)});return!0}}class EC{constructor(t,r){ln(this,"plugin",null);ln(this,"rtcpPeer",null);ln(this,"handleId",0);ln(this,"info",null);ln(this,"joinResult",null);ln(this,"state",{});ln(this,"stream",null);ln(this,"loaded",!1);ln(this,"aTracks",[]);ln(this,"vTracks",[]);this.info=t,this.plugin=r,this.rtcpPeer=new RTCPeerConnection({iceServers:[]})}get memberInfo(){return{stream:this.stream,joinResult:this.joinResult,sender:this.handleId,type:"subscriber",name:this.info.display,state:this.state,id:this.handleId}}updateMemberState(t){var r;this.state={...this.state,...t||{}},(r=this.plugin)==null||r.session.emit("member:update",this.memberInfo)}updateMemberStateFromMessage(t){var s,n,g,_;const r=(n=(s=t==null?void 0:t.plugindata)==null?void 0:s.data)==null?void 0:n.newStatePublisher,u=((_=(g=t==null?void 0:t.plugindata)==null?void 0:g.data)==null?void 0:_.publisher_state).find(v=>v.id===r);this.updateMemberState(u==null?void 0:u.state)}hangup(){this.rtcpPeer&&(this.rtcpPeer.close(),this.rtcpPeer=null),this.stream&&this.stream.getTracks().forEach(t=>{t.stop()})}}class Nr{static canGetMediaDevices(){return!(!navigator.mediaDevices||!navigator.mediaDevices.enumerateDevices)}static async getDevices(t){return Nr.canGetMediaDevices()?(await navigator.mediaDevices.enumerateDevices()).filter(l=>l.kind===t):[]}static async getMicrophoneList(){return(await Nr.getDevices("audioinput")).map((r,l)=>({...r,deviceId:r.deviceId,label:r.label||`microphone ${l+1}`,kind:r.kind,groupId:r.groupId}))}static async getSpeakerList(){return(await Nr.getDevices("audiooutput")).map((r,l)=>({...r,deviceId:r.deviceId,label:r.label||`speaker ${l+1}`,kind:r.kind,groupId:r.groupId}))}static async getCameraList(){return(await Nr.getDevices("videoinput")).map((r,l)=>({...r,deviceId:r.deviceId,label:r.label||`camera ${l+1}`,kind:r.kind,groupId:r.groupId}))}static stopStreamTracks(t){t&&t.getTracks().forEach(r=>{r.stop()})}static async getMediaFromInputs({videoInput:t,audioInput:r}){let l,u;t==="default"?l=!0:t&&t!=="default"&&(l={deviceId:{exact:t}}),r==="default"?u=!0:r&&r!=="default"&&(u={deviceId:{exact:r}});const s={audio:u,video:l};return Nr.getUserMedia(s)}static async getUserMedia(t){return await navigator.mediaDevices.getUserMedia(t)}static async changeAudioOutput(t,r){if(!(!t||!r))if(typeof t.sinkId<"u")try{await t.setSinkId(r)}catch(l){let u=l;l.name==="SecurityError"&&(u=`You need to use HTTPS for selecting audio output device: ${l}`),console.error(u)}else console.warn("Browser does not support output device selection.")}static toggleAudioMute(t){const r=t.getAudioTracks();if(r.length!==0)return r.forEach(l=>{l.enabled=!l.enabled}),r[0].enabled}static toggleVideoMute(t){const r=t.getVideoTracks();if(r.length!==0)return r.forEach(l=>{l.enabled=!l.enabled}),r[0].enabled}static async getStream(t={video:!0,audio:!0}){try{const r=await navigator.mediaDevices.getUserMedia(t);let l=r.getTracks();return t.video?l=r.getVideoTracks():t.audio&&(l=r.getAudioTracks()),l.length===0?{stream:r,track:null}:{stream:r,track:l[0]}}catch(r){return console.warn(r),{stream:null,track:null}}}}var CC=Nn();const Ia=Ht(CC),ir={LEAVE:"Leave",DETACH:"Detach",AUDIO_CHANGE:"AudioChange",VIDEO_CHANGE:"VideoChange",STATE:"State",ICE:"Ice",CONFIGURE:"Configure",TRICKLE:"Trickle",SUBSCRIBER:"Subscriber",PUBLISHER:"Publisher"},Ie=new Su("JanusSession"),AC="/opt/recordings/",De={STATUS_NULL:0,STATUS_INVITE_SENT:1,STATUS_1XX_RECEIVED:2,STATUS_INVITE_RECEIVED:3,STATUS_WAITING_FOR_ANSWER:4,STATUS_ANSWERED:5,STATUS_WAITING_FOR_ACK:6,STATUS_CANCELED:7,STATUS_TERMINATED:8,STATUS_CONFIRMED:9},Pu=["audio","video"];class Lu extends ys.EventEmitter{static get C(){return De}constructor(t){Ie.debug("new"),super(),this._id=null,this._ua=t,this._status=De.STATUS_NULL,this._dialog=null,this._earlyDialogs={},this._contact=null,this._from_tag=null,this._to_tag=null,this.lastTransaction=0,this._connection=null,this._connectionPromiseQueue=Promise.resolve(),this._request=null,this._is_canceled=!1,this._cancel_reason="",this._is_confirmed=!1,this._late_sdp=!1,this._rtcOfferConstraints=null,this._rtcAnswerConstraints=null,this._localMediaStream=null,this._localMediaStreamLocallyGenerated=!1,this._rtcReady=!0,this._iceReady=!1,this._timers={ackTimer:null,expiresTimer:null,invite2xxTimer:null,userNoAnswerTimer:null},this._direction=null,this._local_identity=null,this._remote_identity=null,this._start_time=null,this._end_time=null,this._audioMuted=!1,this._videoMuted=!1,this._localHold=!1,this._remoteHold=!1,this._sessionTimers={enabled:this._ua.configuration.session_timers,refreshMethod:this._ua.configuration.session_timers_refresh_method,defaultExpires:fe.SESSION_EXPIRES,currentExpires:null,running:!1,refresher:!1,timer:null},this._referSubscribers={},this._candidates=[],this.publishers=[],this.private_id=null,this.memberList={},this.myFeedList=[],this.display_name="",this.stunServers=[{urls:"stun:turn.voicenter.co",credential:"kxsjahnsdjns3eds23esd",username:"turn2es21e"}],this.opaque_id=this.generateOpaqueId(),this.screen_share_opaque_id=this.generateOpaqueId(),this._data={},this.isAudioOn=!0,this.isVideoOn=!0,this.mediaConstraints={}}get C(){return De}get causes(){return fe.causes}get id(){return this._id}get connection(){return this._connection}get contact(){return this._contact}get direction(){return this._direction}get local_identity(){return this._local_identity}get remote_identity(){return this._remote_identity}get start_time(){return this._start_time}get end_time(){return this._end_time}get data(){return this._data}set data(t){this._data=t}get status(){return this._status}isInProgress(){switch(this._status){case De.STATUS_NULL:case De.STATUS_INVITE_SENT:case De.STATUS_1XX_RECEIVED:case De.STATUS_INVITE_RECEIVED:case De.STATUS_WAITING_FOR_ANSWER:return!0;default:return!1}}isEstablished(){switch(this._status){case De.STATUS_ANSWERED:case De.STATUS_WAITING_FOR_ACK:case De.STATUS_CONFIRMED:return!0;default:return!1}}isEnded(){switch(this._status){case De.STATUS_CANCELED:case De.STATUS_TERMINATED:return!0;default:return!1}}isMuted(){return{audio:this._audioMuted,video:this._videoMuted}}isOnHold(){return{local:this._localHold,remote:this._remoteHold}}getPTypeHeader(t){return`PTYPE: ${t}`}generateOpaqueId(){return`videoroomtest-${cp().replace(/-/g,"").slice(0,12)}`}connect(t,r,l={},u){Ie.debug("connect()"),this.display_name=r;const s=t,n=Nt.cloneObject(l.eventHandlers),g=Nt.cloneArray(l.extraHeaders),_=Nt.cloneObject(l.mediaConstraints,{audio:!0,video:!0});this.mediaConstraints={..._};const v=l.mediaStream||null,C=Nt.cloneObject(l.pcConfig,{iceServers:[]}),R=l.rtcConstraints||null,D=l.rtcOfferConstraints||null;if(this._rtcOfferConstraints=D,this._rtcAnswerConstraints=l.rtcAnswerConstraints||null,this._data=l.data||this._data,t===void 0)throw new TypeError("Not enough arguments");if(this._status!==De.STATUS_NULL)throw new Ei.InvalidStateError(this._status);if(!window.RTCPeerConnection)throw new Ei.NotSupportedError("WebRTC not supported");if(t=this._ua.normalizeTarget(t),this.room_id=t.user,this.target=t,!t)throw new TypeError(`Invalid target: ${s}`);this._sessionTimers.enabled&&Nt.isDecimal(l.sessionTimersExpires)&&(l.sessionTimersExpires>=fe.MIN_SESSION_EXPIRES?this._sessionTimers.defaultExpires=l.sessionTimersExpires:this._sessionTimers.defaultExpires=fe.SESSION_EXPIRES);for(const q in n)Object.prototype.hasOwnProperty.call(n,q)&&this.on(q,n[q]);this._from_tag=Nt.newTag();const H=l.anonymous||!1,F={from_tag:this._from_tag};this._contact=this._ua.contact.toString({anonymous:H,outbound:!0}),H?(F.from_display_name="Anonymous",F.from_uri=new Ia("sip","anonymous","anonymous.invalid"),g.push(`P-Preferred-Identity: ${this._ua.configuration.uri.toString()}`),g.push("Privacy: id")):l.fromUserName&&(F.from_uri=new Ia("sip",l.fromUserName,this._ua.configuration.uri.host),g.push(`P-Preferred-Identity: ${this._ua.configuration.uri.toString()}`)),l.fromDisplayName&&(F.from_display_name=l.fromDisplayName),g.push(`Contact: ${this._contact}`),g.push("Content-Type: application/json"),this._sessionTimers.enabled&&g.push(`Session-Expires: ${this._sessionTimers.defaultExpires}${this._ua.configuration.session_timers_force_refresher?";refresher=uac":""}`),this._request=new Ds.InitialOutgoingInviteRequest(t,this._ua,F,g),this._id=this._request.call_id+this._from_tag,this._createRTCConnection(C,R),this._direction="outgoing",this._local_identity=this._request.from,this._remote_identity=this._request.to,u&&u(this),this._newJanusSession("local",this._request),this._sendInitialRequest(_,D,v)}_overrideSenderTracks(t,r){t.getTracks().forEach(l=>{r.getSenders().forEach(async s=>{s.track.kind===l.kind&&(l.kind==="audio"&&!this.isAudioOn&&(l.enabled=!1),l.kind==="video"&&!this.isVideoOn&&(l.enabled=!1),await s.replaceTrack(l))})})}init_incoming(t,r){Ie.debug("init_incoming()");let l;const u=t.hasHeader("Content-Type")?t.getHeader("Content-Type").toLowerCase():void 0;if(t.body&&u!=="application/sdp"){t.reply(415);return}if(this._status=De.STATUS_INVITE_RECEIVED,this._from_tag=t.from_tag,this._id=t.call_id+this._from_tag,this._request=t,this._contact=this._ua.contact.toString(),t.hasHeader("expires")&&(l=t.getHeader("expires")*1e3),t.to_tag=Nt.newTag(),!this._createDialog(t,"UAS",!0)){t.reply(500,"Missing Contact header field");return}t.body?this._late_sdp=!1:this._late_sdp=!0,this._status=De.STATUS_WAITING_FOR_ANSWER,this._timers.userNoAnswerTimer=setTimeout(()=>{t.reply(408),this._failed("local",null,fe.causes.NO_ANSWER)},this._ua.configuration.no_answer_timeout),l&&(this._timers.expiresTimer=setTimeout(()=>{this._status===De.STATUS_WAITING_FOR_ANSWER&&(t.reply(487),this._failed("system",null,fe.causes.EXPIRES))},l)),this._direction="incoming",this._local_identity=t.to,this._remote_identity=t.from,r&&r(this),this._newJanusSession("remote",t),this._status!==De.STATUS_TERMINATED&&(t.reply(180,null,[`Contact: ${this._contact}`]),this._progress("local",null))}answer(t={}){Ie.debug("answer()");const r=this._request,l=Nt.cloneArray(t.extraHeaders),u=Nt.cloneObject(t.mediaConstraints),s=t.mediaStream||null,n=Nt.cloneObject(t.pcConfig,{iceServers:[]}),g=t.rtcConstraints||null,_=t.rtcAnswerConstraints||null,v=Nt.cloneObject(t.rtcOfferConstraints);let C,R=!1,D=!1,H=!1,F=!1;if(this._rtcAnswerConstraints=_,this._rtcOfferConstraints=t.rtcOfferConstraints||null,this._data=t.data||this._data,this._direction!=="incoming")throw new Ei.NotSupportedError('"answer" not supported for outgoing RTCSession');if(this._status!==De.STATUS_WAITING_FOR_ANSWER)throw new Ei.InvalidStateError(this._status);if(this._sessionTimers.enabled&&Nt.isDecimal(t.sessionTimersExpires)&&(t.sessionTimersExpires>=fe.MIN_SESSION_EXPIRES?this._sessionTimers.defaultExpires=t.sessionTimersExpires:this._sessionTimers.defaultExpires=fe.SESSION_EXPIRES),this._status=De.STATUS_ANSWERED,!this._createDialog(r,"UAS")){r.reply(500,"Error creating dialog");return}clearTimeout(this._timers.userNoAnswerTimer),l.unshift(`Contact: ${this._contact}`);const q=r.parseSDP();Array.isArray(q.media)||(q.media=[q.media]);for(const G of q.media)G.type==="audio"&&(R=!0,(!G.direction||G.direction==="sendrecv")&&(H=!0)),G.type==="video"&&(D=!0,(!G.direction||G.direction==="sendrecv")&&(F=!0));if(s&&u.audio===!1){C=s.getAudioTracks();for(const G of C)s.removeTrack(G)}if(s&&u.video===!1){C=s.getVideoTracks();for(const G of C)s.removeTrack(G)}!s&&u.audio===void 0&&(u.audio=H),!s&&u.video===void 0&&(u.video=F),!s&&!R&&!v.offerToReceiveAudio&&(u.audio=!1),!s&&!D&&!v.offerToReceiveVideo&&(u.video=!1),this._createRTCConnection(n,g),Promise.resolve().then(()=>{if(s)return s;if(u.audio||u.video)return this._localMediaStreamLocallyGenerated=!0,this.loadStream().catch(G=>{throw this._status===De.STATUS_TERMINATED?new Error("terminated"):(r.reply(480),this._failed("local",null,fe.causes.USER_DENIED_MEDIA_ACCESS),Ie.warn('emit "getusermediafailed" [error:%o]',G),this.emit("getusermediafailed",G),new Error("getUserMedia() failed"))})}).then(G=>{if(this._status===De.STATUS_TERMINATED)throw new Error("terminated");this._localMediaStream=G,G&&G.getTracks().forEach(te=>{this._connection.addTrack(te,G)})}).then(()=>{if(this._late_sdp)return;const G={originator:"remote",type:"offer",sdp:r.body};Ie.debug('emit "sdp"'),this.emit("sdp",G);const te=new RTCSessionDescription({type:"offer",sdp:G.sdp});return this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(te)).catch(X=>{throw r.reply(488),this._failed("system",null,fe.causes.WEBRTC_ERROR),Ie.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',X),this.emit("peerconnection:setremotedescriptionfailed",X),new Error("peerconnection.setRemoteDescription() failed")}),this._connectionPromiseQueue}).then(()=>{if(this._status===De.STATUS_TERMINATED)throw new Error("terminated");return this._connecting(r),this._late_sdp?this._createLocalDescription("offer",this._rtcOfferConstraints).catch(()=>{throw r.reply(500),new Error("_createLocalDescription() failed")}):this._createLocalDescription("answer",_).catch(()=>{throw r.reply(500),new Error("_createLocalDescription() failed")})}).then(G=>{if(this._status===De.STATUS_TERMINATED)throw new Error("terminated");this._handleSessionTimersInIncomingRequest(r,l),r.reply(200,null,l,G,()=>{this._status=De.STATUS_WAITING_FOR_ACK,this._setInvite2xxTimer(r,G),this._setACKTimer(),this._accepted("local")},()=>{this._failed("system",null,fe.causes.CONNECTION_ERROR)})}).catch(G=>{this._status!==De.STATUS_TERMINATED&&Ie.warn(G)})}terminate(t={}){Ie.debug("terminate()");const r=t.cause||fe.causes.BYE,l=Nt.cloneArray(t.extraHeaders),u=t.body;let s,n=t.status_code,g=t.reason_phrase;if(this._status===De.STATUS_TERMINATED)throw new Ei.InvalidStateError(this._status);switch(this._status){case De.STATUS_NULL:case De.STATUS_INVITE_SENT:case De.STATUS_1XX_RECEIVED:if(Ie.debug("canceling session"),n&&(n<200||n>=700))throw new TypeError(`Invalid status_code: ${n}`);n&&(g=g||fe.REASON_PHRASE[n]||"",s=`SIP ;cause=${n} ;text="${g}"`),this._status===De.STATUS_NULL||this._status===De.STATUS_INVITE_SENT?(this._is_canceled=!0,this._cancel_reason=s):this._status===De.STATUS_1XX_RECEIVED&&this._request.cancel(s),this._status=De.STATUS_CANCELED,this._failed("local",null,fe.causes.CANCELED);break;case De.STATUS_WAITING_FOR_ANSWER:case De.STATUS_ANSWERED:if(Ie.debug("rejecting session"),n=n||480,n<300||n>=700)throw new TypeError(`Invalid status_code: ${n}`);this._request.reply(n,g,l,u),this._failed("local",null,fe.causes.REJECTED);break;case De.STATUS_WAITING_FOR_ACK:case De.STATUS_CONFIRMED:if(Ie.debug("terminating session"),g=t.reason_phrase||fe.REASON_PHRASE[n]||"",n&&(n<200||n>=700))throw new TypeError(`Invalid status_code: ${n}`);if(n&&l.push(`Reason: SIP ;cause=${n}; text="${g}"`),this._status===De.STATUS_WAITING_FOR_ACK&&this._direction==="incoming"&&this._request.server_transaction.state!==Er.C.STATUS_TERMINATED){const _=this._dialog;this.receiveRequest=({method:v})=>{v===fe.ACK&&(this.sendRequest(fe.BYE,{extraHeaders:l,body:u}),_.terminate(),this.closeSession())},this._request.server_transaction.on("stateChanged",()=>{this._request.server_transaction.state===Er.C.STATUS_TERMINATED&&(this.sendRequest(fe.BYE,{extraHeaders:l,body:u}),_.terminate(),this.closeSession())}),this._ended("local",null,r),this._dialog=_,this._ua.newDialog(_)}else{const _={janus:"leave"},v=["Content-Type: application/json",this.getPTypeHeader(ir.LEAVE)];this.sendRequest(fe.BYE,{extraHeaders:v,body:JSON.stringify(_)}),this.closeSession(),this._ended("local",null,r)}}}configureMedia(t){this.isAudioOn=t.audio,this.isVideoOn=t.video}enableAudio(t){const r={janus:"message",body:{audio:t},handle_id:this.handle_id,session_id:this.session_id},l=["Content-Type: application/json",this.getPTypeHeader(ir.AUDIO_CHANGE)];this.sendRequest(fe.INFO,{extraHeaders:l,body:JSON.stringify(r),eventHandlers:{onSuccessResponse:async u=>{u.status_code===200&&(this._ua.emit("changeAudioState",t),this.sendStateMessage({audio:t}))}}})}startAudio(){Nr.toggleAudioMute(this.stream),this._toggleMuteAudio(!1),this.enableAudio(!0),this.isAudioOn=!0}stopAudio(){Nr.toggleAudioMute(this.stream),this._toggleMuteAudio(!0),this.enableAudio(!1),this.isAudioOn=!1}enableVideo(t){const r={janus:"message",body:{video:t},handle_id:this.handle_id,session_id:this.session_id},l=["Content-Type: application/json",this.getPTypeHeader(ir.VIDEO_CHANGE)];this.sendRequest(fe.INFO,{extraHeaders:l,body:JSON.stringify(r),eventHandlers:{onSuccessResponse:async u=>{u.status_code===200&&(this._ua.emit("changeVideoState",t),this.sendStateMessage({video:t}))}}})}startVideo(){Nr.toggleVideoMute(this.stream),this._toggleMuteVideo(!1),this.enableVideo(!0),this.isVideoOn=!0}stopVideo(){Nr.toggleVideoMute(this.stream),this._toggleMuteVideo(!0),this.enableVideo(!1),this.isVideoOn=!1}sendStateMessage(t){const r={janus:"message",body:{request:"state",data:t},handle_id:this.handle_id,session_id:this.session_id},l=["Content-Type: application/json",this.getPTypeHeader(ir.STATE)];this.sendRequest(fe.INFO,{extraHeaders:l,body:JSON.stringify(r)})}sendInfo(t,r,l={}){if(Ie.debug("sendInfo()"),this._status!==De.STATUS_CONFIRMED&&this._status!==De.STATUS_WAITING_FOR_ACK&&this._status!==De.STATUS_1XX_RECEIVED)throw new Ei.InvalidStateError(this._status);new hd(this).send(t,r,l)}mute(t={audio:!0,video:!1}){Ie.debug("mute()");let r=!1,l=!1;this._audioMuted===!1&&t.audio&&(r=!0,this._audioMuted=!0,this._toggleMuteAudio(!0)),this._videoMuted===!1&&t.video&&(l=!0,this._videoMuted=!0,this._toggleMuteVideo(!0)),(r===!0||l===!0)&&this._onmute({audio:r,video:l})}unmute(t={audio:!0,video:!0}){Ie.debug("unmute()");let r=!1,l=!1;this._audioMuted===!0&&t.audio&&(r=!0,this._audioMuted=!1,this._localHold===!1&&this._toggleMuteAudio(!1)),this._videoMuted===!0&&t.video&&(l=!0,this._videoMuted=!1,this._localHold===!1&&this._toggleMuteVideo(!1)),(r===!0||l===!0)&&this._onunmute({audio:r,video:l})}hold(t={},r){if(Ie.debug("hold()"),this._status!==De.STATUS_WAITING_FOR_ACK&&this._status!==De.STATUS_CONFIRMED||this._localHold===!0||!this._isReadyToReOffer())return!1;this._localHold=!0,this._onhold("local");const l={succeeded:()=>{r&&r()},failed:()=>{this.terminate({cause:fe.causes.WEBRTC_ERROR,status_code:500,reason_phrase:"Hold Failed"})}};return t.useUpdate?this._sendUpdate({sdpOffer:!0,eventHandlers:l,extraHeaders:t.extraHeaders}):this._sendReinvite({eventHandlers:l,extraHeaders:t.extraHeaders}),!0}unhold(t={},r){if(Ie.debug("unhold()"),this._status!==De.STATUS_WAITING_FOR_ACK&&this._status!==De.STATUS_CONFIRMED||this._localHold===!1||!this._isReadyToReOffer())return!1;this._localHold=!1,this._onunhold("local");const l={succeeded:()=>{r&&r()},failed:()=>{this.terminate({cause:fe.causes.WEBRTC_ERROR,status_code:500,reason_phrase:"Unhold Failed"})}};return t.useUpdate?this._sendUpdate({sdpOffer:!0,eventHandlers:l,extraHeaders:t.extraHeaders}):this._sendReinvite({eventHandlers:l,extraHeaders:t.extraHeaders}),!0}renegotiate(t={},r){Ie.debug("renegotiate()");const l=t.rtcOfferConstraints||null;if(this._status!==De.STATUS_WAITING_FOR_ACK&&this._status!==De.STATUS_CONFIRMED||!this._isReadyToReOffer())return!1;const u={succeeded:()=>{r&&r()},failed:()=>{this.terminate({cause:fe.causes.WEBRTC_ERROR,status_code:500,reason_phrase:"Media Renegotiation Failed"})}};return this._setLocalMediaStatus(),t.useUpdate?this._sendUpdate({sdpOffer:!0,eventHandlers:u,rtcOfferConstraints:l,extraHeaders:t.extraHeaders}):this._sendReinvite({eventHandlers:u,rtcOfferConstraints:l,extraHeaders:t.extraHeaders}),!0}refer(t,r){Ie.debug("refer()");const l=t;if(this._status!==De.STATUS_WAITING_FOR_ACK&&this._status!==De.STATUS_CONFIRMED)return!1;if(t=this._ua.normalizeTarget(t),!t)throw new TypeError(`Invalid target: ${l}`);const u=new bE(this);u.sendRefer(t,r);const s=u.id;return this._referSubscribers[s]=u,u.on("requestFailed",()=>{delete this._referSubscribers[s]}),u.on("accepted",()=>{delete this._referSubscribers[s]}),u.on("failed",()=>{delete this._referSubscribers[s]}),u}sendRequest(t,r){return Ie.debug("sendRequest()"),this._dialog.sendRequest(t,r)}receiveNotify(t){Ie.debug("receiveRequest()")}receiveRequest(t){if(Ie.debug("receiveRequest()"),t.method===fe.CANCEL)(this._status===De.STATUS_WAITING_FOR_ANSWER||this._status===De.STATUS_ANSWERED)&&(this._status=De.STATUS_CANCELED,this._request.reply(487),this._failed("remote",t,fe.causes.CANCELED));else switch(t.method){case fe.ACK:if(this._status!==De.STATUS_WAITING_FOR_ACK)return;if(this._status=De.STATUS_CONFIRMED,clearTimeout(this._timers.ackTimer),clearTimeout(this._timers.invite2xxTimer),this._late_sdp){if(!t.body){this.terminate({cause:fe.causes.MISSING_SDP,status_code:400});break}const r={originator:"remote",type:"answer",sdp:t.body};Ie.debug('emit "sdp"'),this.emit("sdp",r);const l=new RTCSessionDescription({type:"answer",sdp:r.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(l)).then(()=>{this._is_confirmed||this._confirmed("remote",t)}).catch(u=>{this.terminate({cause:fe.causes.BAD_MEDIA_DESCRIPTION,status_code:488}),Ie.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',u),this.emit("peerconnection:setremotedescriptionfailed",u)})}else this._is_confirmed||this._confirmed("remote",t);break;case fe.BYE:this._status===De.STATUS_CONFIRMED||this._status===De.STATUS_WAITING_FOR_ACK?(t.reply(200),this._ended("remote",t,fe.causes.BYE)):this._status===De.STATUS_INVITE_RECEIVED||this._status===De.STATUS_WAITING_FOR_ANSWER?(t.reply(200),this._request.reply(487,"BYE Received"),this._ended("remote",t,fe.causes.BYE)):t.reply(403,"Wrong Status");break;case fe.INVITE:this._status===De.STATUS_CONFIRMED?t.hasHeader("replaces")?this._receiveReplaces(t):this._receiveReinvite(t):t.reply(403,"Wrong Status");break;case fe.INFO:if(this._status===De.STATUS_1XX_RECEIVED||this._status===De.STATUS_WAITING_FOR_ANSWER||this._status===De.STATUS_ANSWERED||this._status===De.STATUS_WAITING_FOR_ACK||this._status===De.STATUS_CONFIRMED){const r=t.hasHeader("Content-Type")?t.getHeader("Content-Type").toLowerCase():void 0;r&&r.match(/^application\/dtmf-relay/i)?new dE(this).init_incoming(t):r!==void 0?new hd(this).init_incoming(t):t.reply(415)}else t.reply(403,"Wrong Status");break;case fe.UPDATE:this._status===De.STATUS_CONFIRMED?this._receiveUpdate(t):t.reply(403,"Wrong Status");break;case fe.REFER:this._status===De.STATUS_CONFIRMED?this._receiveRefer(t):t.reply(403,"Wrong Status");break;case fe.NOTIFY:this._status===De.STATUS_CONFIRMED?this._receiveNotify(t):t.reply(403,"Wrong Status");break;default:t.reply(501)}}onTransportError(){Ie.warn("onTransportError()"),this._status!==De.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:fe.causes.CONNECTION_ERROR,cause:fe.causes.CONNECTION_ERROR})}onRequestTimeout(){Ie.warn("onRequestTimeout()"),this._status!==De.STATUS_TERMINATED&&this.terminate({status_code:408,reason_phrase:fe.causes.REQUEST_TIMEOUT,cause:fe.causes.REQUEST_TIMEOUT})}onDialogError(){Ie.warn("onDialogError()"),this._status!==De.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:fe.causes.DIALOG_ERROR,cause:fe.causes.DIALOG_ERROR})}newDTMF(t){Ie.debug("newDTMF()"),this.emit("newDTMF",t)}newInfo(t){Ie.debug("newInfo()"),this.emit("newInfo",t)}_isReadyToReOffer(){return this._rtcReady?this._dialog?this._dialog.uac_pending_reply===!0||this._dialog.uas_pending_reply===!0?(Ie.debug("_isReadyToReOffer() | there is another INVITE/UPDATE transaction in progress"),!1):!0:(Ie.debug("_isReadyToReOffer() | session not established yet"),!1):(Ie.debug("_isReadyToReOffer() | internal WebRTC status not ready"),!1)}_close(){if(Ie.debug("close()"),this._localMediaStream&&this._localMediaStreamLocallyGenerated&&(Ie.debug("close() | closing local MediaStream"),Nt.closeMediaStream(this._localMediaStream)),this._status!==De.STATUS_TERMINATED){if(this._status=De.STATUS_TERMINATED,this._connection)try{this._connection.close()}catch(t){Ie.warn("close() | error closing the RTCPeerConnection: %o",t)}for(const t in this._timers)Object.prototype.hasOwnProperty.call(this._timers,t)&&clearTimeout(this._timers[t]);clearTimeout(this._sessionTimers.timer),this._dialog&&(this._dialog.terminate(),delete this._dialog);for(const t in this._earlyDialogs)Object.prototype.hasOwnProperty.call(this._earlyDialogs,t)&&(this._earlyDialogs[t].terminate(),delete this._earlyDialogs[t]);for(const t in this._referSubscribers)Object.prototype.hasOwnProperty.call(this._referSubscribers,t)&&delete this._referSubscribers[t];this._ua.destroyRTCSession(this)}}_setInvite2xxTimer(t,r){let l=eo.T1;function u(){this._status===De.STATUS_WAITING_FOR_ACK&&(t.reply(200,null,[`Contact: ${this._contact}`],r),l<eo.T2&&(l=l*2,l>eo.T2&&(l=eo.T2)),this._timers.invite2xxTimer=setTimeout(u.bind(this),l))}this._timers.invite2xxTimer=setTimeout(u.bind(this),l)}_setACKTimer(){this._timers.ackTimer=setTimeout(()=>{this._status===De.STATUS_WAITING_FOR_ACK&&(Ie.debug("no ACK received, terminating the session"),clearTimeout(this._timers.invite2xxTimer),this.sendRequest(fe.BYE),this._ended("remote",null,fe.causes.NO_ACK))},eo.TIMER_H)}_createRTCConnection(t,r){this.stunServers,this._connection=new RTCPeerConnection(t,r),this._connection.addEventListener("iceconnectionstatechange",()=>{this._connection.iceConnectionState==="failed"&&this.terminate({cause:fe.causes.RTP_TIMEOUT,status_code:408,reason_phrase:fe.causes.RTP_TIMEOUT})});let l;const u=s=>{this._connection.signalingState!=="stable"&&this._connection.signalingState!=="have-local-offer"||s.candidate&&(this._candidates.push(s.candidate),clearTimeout(l),l=setTimeout(()=>{this.lastTrickleReceived=!0,this.subscribeSent&&!this.isConfigureSent&&(this.addTracks(this.stream.getTracks()),this._ua.emit("changeMainVideoStream",{name:this.display_name,stream:this.stream}),this._sendConfigureMessage({audio:!0,video:!0}).then(()=>{}))},500))};this._connection.onicecandidate=u,Ie.debug('emit "peerconnection"'),this.emit("peerconnection",{peerconnection:this._connection})}_createLocalDescription(t,r){if(Ie.debug("createLocalDescription()"),t!=="offer"&&t!=="answer")throw new Error(`createLocalDescription() | invalid type "${t}"`);const l=this._connection;return this._rtcReady=!1,Promise.resolve().then(()=>t==="offer"?l.createOffer(r).catch(u=>(Ie.warn('emit "peerconnection:createofferfailed" [error:%o]',u),this.emit("peerconnection:createofferfailed",u),Promise.reject(u))):l.createAnswer(r).catch(u=>(Ie.warn('emit "peerconnection:createanswerfailed" [error:%o]',u),this.emit("peerconnection:createanswerfailed",u),Promise.reject(u)))).then(u=>(this.jsepOffer=u,l.setLocalDescription(u).catch(s=>(this._rtcReady=!0,Ie.warn('emit "peerconnection:setlocaldescriptionfailed" [error:%o]',s),this.emit("peerconnection:setlocaldescriptionfailed",s),Promise.reject(s))))).then(()=>{const u=r&&r.iceRestart;if(l.iceGatheringState==="complete"&&!u||l.iceGatheringState==="gathering"&&this._iceReady){this._rtcReady=!0;const s={originator:"local",type:t,sdp:l.localDescription.sdp};return Ie.debug('emit "sdp"'),this.emit("sdp",s),Promise.resolve(s.sdp)}return new Promise(s=>{let n=!1,g,_;this._iceReady=!1;const v=()=>{l.removeEventListener("icecandidate",g),l.removeEventListener("icegatheringstatechange",_),n=!0,this._rtcReady=!0,this._iceReady=!0;const C={originator:"local",type:t,sdp:l.localDescription.sdp};Ie.debug('emit "sdp"'),this.emit("sdp",C),s(C.sdp)};l.addEventListener("icecandidate",g=C=>{const R=C.candidate;R?this.emit("icecandidate",{candidate:R,ready:v}):n||v()}),l.addEventListener("icegatheringstatechange",_=()=>{l.iceGatheringState==="complete"&&!n&&v()})})})}_createDialog(t,r,l){const u=r==="UAS"?t.to_tag:t.from_tag,s=r==="UAS"?t.from_tag:t.to_tag,n=t.call_id+u+s;let g=this._earlyDialogs[n];if(l)return g?!0:(g=new Uu(this,t,r,Uu.C.STATUS_EARLY),g.error?(Ie.debug(g.error),this._failed("remote",t,fe.causes.INTERNAL_ERROR),!1):(this._earlyDialogs[n]=g,!0));{if(this._from_tag=t.from_tag,this._to_tag=t.to_tag,g)return g.update(t,r),this._dialog=g,delete this._earlyDialogs[n],!0;const _=new Uu(this,t,r);return _.error?(Ie.debug(_.error),this._failed("remote",t,fe.causes.INTERNAL_ERROR),!1):(this._dialog=_,!0)}}_receiveReinvite(t){Ie.debug("receiveReinvite()");const r=t.hasHeader("Content-Type")?t.getHeader("Content-Type").toLowerCase():void 0,l={request:t,callback:void 0,reject:s.bind(this)};let u=!1;function s(g={}){u=!0;const _=g.status_code||403,v=g.reason_phrase||"",C=Nt.cloneArray(g.extraHeaders);if(this._status!==De.STATUS_CONFIRMED)return!1;if(_<300||_>=700)throw new TypeError(`Invalid status_code: ${_}`);t.reply(_,v,C)}if(this.emit("reinvite",l),u)return;if(this._late_sdp=!1,!t.body){this._late_sdp=!0,this._remoteHold&&(this._remoteHold=!1,this._onunhold("remote")),this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._createLocalDescription("offer",this._rtcOfferConstraints)).then(g=>{n.call(this,g)}).catch(()=>{t.reply(500)});return}if(r!=="application/sdp"){Ie.debug("invalid Content-Type"),t.reply(415);return}this._processInDialogSdpOffer(t).then(g=>{this._status!==De.STATUS_TERMINATED&&n.call(this,g)}).catch(g=>{Ie.warn(g)});function n(g){const _=[`Contact: ${this._contact}`];this._handleSessionTimersInIncomingRequest(t,_),this._late_sdp&&(g=this._mangleOffer(g)),t.reply(200,null,_,g,()=>{this._status=De.STATUS_WAITING_FOR_ACK,this._setInvite2xxTimer(t,g),this._setACKTimer()}),typeof l.callback=="function"&&l.callback()}}_receiveUpdate(t){Ie.debug("receiveUpdate()");const r=t.hasHeader("Content-Type")?t.getHeader("Content-Type").toLowerCase():void 0,l={request:t,callback:void 0,reject:s.bind(this)};let u=!1;function s(g={}){u=!0;const _=g.status_code||403,v=g.reason_phrase||"",C=Nt.cloneArray(g.extraHeaders);if(this._status!==De.STATUS_CONFIRMED)return!1;if(_<300||_>=700)throw new TypeError(`Invalid status_code: ${_}`);t.reply(_,v,C)}if(this.emit("update",l),u)return;if(!t.body){n.call(this,null);return}if(r!=="application/sdp"){Ie.debug("invalid Content-Type"),t.reply(415);return}this._processInDialogSdpOffer(t).then(g=>{this._status!==De.STATUS_TERMINATED&&n.call(this,g)}).catch(g=>{Ie.warn(g)});function n(g){const _=[`Contact: ${this._contact}`];this._handleSessionTimersInIncomingRequest(t,_),t.reply(200,null,_,g),typeof l.callback=="function"&&l.callback()}}_processInDialogSdpOffer(t){Ie.debug("_processInDialogSdpOffer()");const r=t.parseSDP();let l=!1;for(const n of r.media){if(Pu.indexOf(n.type)===-1)continue;const g=n.direction||r.direction||"sendrecv";if(g==="sendonly"||g==="inactive")l=!0;else{l=!1;break}}const u={originator:"remote",type:"offer",sdp:t.body};Ie.debug('emit "sdp"'),this.emit("sdp",u);const s=new RTCSessionDescription({type:"offer",sdp:u.sdp});return this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>{if(this._status===De.STATUS_TERMINATED)throw new Error("terminated");return this._connection.setRemoteDescription(s).catch(n=>{throw t.reply(488),Ie.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',n),this.emit("peerconnection:setremotedescriptionfailed",n),n})}).then(()=>{if(this._status===De.STATUS_TERMINATED)throw new Error("terminated");this._remoteHold===!0&&l===!1?(this._remoteHold=!1,this._onunhold("remote")):this._remoteHold===!1&&l===!0&&(this._remoteHold=!0,this._onhold("remote"))}).then(()=>{if(this._status===De.STATUS_TERMINATED)throw new Error("terminated");return this._createLocalDescription("answer",this._rtcAnswerConstraints).catch(n=>{throw t.reply(500),Ie.warn('emit "peerconnection:createtelocaldescriptionfailed" [error:%o]',n),n})}).catch(n=>{Ie.warn("_processInDialogSdpOffer() failed [error: %o]",n)}),this._connectionPromiseQueue}_receiveRefer(t){if(Ie.debug("receiveRefer()"),!t.refer_to){Ie.debug("no Refer-To header field present in REFER"),t.reply(400);return}if(t.refer_to.uri.scheme!==fe.SIP){Ie.debug("Refer-To header field points to a non-SIP URI scheme"),t.reply(416);return}t.reply(202);const r=new vE(this,t.cseq);Ie.debug('emit "refer"'),this.emit("refer",{request:t,accept:(s,n)=>{l.call(this,s,n)},reject:()=>{u.call(this)}});function l(s,n={}){if(s=typeof s=="function"?s:null,this._status!==De.STATUS_WAITING_FOR_ACK&&this._status!==De.STATUS_CONFIRMED)return!1;const g=new Lu(this._ua);if(g.on("progress",({response:_})=>{r.notify(_.status_code,_.reason_phrase)}),g.on("accepted",({response:_})=>{r.notify(_.status_code,_.reason_phrase)}),g.on("_failed",({message:_,cause:v})=>{_?r.notify(_.status_code,_.reason_phrase):r.notify(487,v)}),t.refer_to.uri.hasHeader("replaces")){const _=decodeURIComponent(t.refer_to.uri.getHeader("replaces"));n.extraHeaders=Nt.cloneArray(n.extraHeaders),n.extraHeaders.push(`Replaces: ${_}`)}g.connect(t.refer_to.uri.toAor(),n,s)}function u(){r.notify(603)}}_receiveNotify(t){switch(Ie.debug("receiveNotify()"),t.event||t.reply(400),t.event.event){case"refer":{let r,l;if(t.event.params&&t.event.params.id)r=t.event.params.id,l=this._referSubscribers[r];else if(Object.keys(this._referSubscribers).length===1)l=this._referSubscribers[Object.keys(this._referSubscribers)[0]];else{t.reply(400,"Missing event id parameter");return}if(!l){t.reply(481,"Subscription does not exist");return}l.receiveNotify(t),t.reply(200);break}default:t.reply(489)}}_receiveReplaces(t){Ie.debug("receiveReplaces()");function r(u){if(this._status!==De.STATUS_WAITING_FOR_ACK&&this._status!==De.STATUS_CONFIRMED)return!1;const s=new Lu(this._ua);s.on("confirmed",()=>{this.terminate()}),s.init_incoming(t,u)}function l(){Ie.debug("Replaced INVITE rejected by the user"),t.reply(486)}this.emit("replaces",{request:t,accept:u=>{r.call(this,u)},reject:()=>{l.call(this)}})}_getNextTransactionId(){return(this.lastTransaction+1).toString()}_sendInitialRequest(t,r,l){this.ackSent=!1,this.publisherSubscribeSent=!1;const u=new no(this._ua,this._request,{onRequestTimeout:()=>{this.onRequestTimeout()},onTransportError:()=>{this.onTransportError()},onAuthenticated:s=>{this._request=s},onReceiveResponse:s=>{this._receiveInviteResponse(s)}});Promise.resolve().then(()=>{if(l)return l;if(t.audio||t.video)return this._localMediaStreamLocallyGenerated=!0,this.loadStream().catch(s=>{throw this._status===De.STATUS_TERMINATED?new Error("terminated"):(this._failed("local",null,fe.causes.USER_DENIED_MEDIA_ACCESS),Ie.warn('emit "getusermediafailed" [error:%o]',s),this.emit("getusermediafailed",s),s)})}).then(s=>{if(this._status===De.STATUS_TERMINATED)throw new Error("terminated");return this._localMediaStream=s,s&&s.getTracks().forEach(n=>{this._connection.addTrack(n,s)}),this._connecting(this._request),this._createLocalDescription("offer",r).catch(n=>{throw this._failed("local",null,fe.causes.WEBRTC_ERROR),n})}).then(s=>{if(this._is_canceled||this._status===De.STATUS_TERMINATED)throw new Error("terminated");const n={janus:"attach",plugin:"janus.plugin.videoroom",opaque_id:this.opaque_id},g=JSON.stringify(n);this._request.body=g,this._status=De.STATUS_INVITE_SENT,Ie.debug('emit "sending" [request:%o]',this._request),this.emit("sending",{request:this._request}),u.send()}).catch(s=>{this._status!==De.STATUS_TERMINATED&&Ie.warn(s)})}async requestAudioAndVideoPermissions(){this.stream=await this.loadStream()}async setupMediaStream(){await this.requestAudioAndVideoPermissions(),await this.processPlugins()}async changeMediaConstraints(t){this.mediaConstraints={...t},await this.processPlugins(),this.addTracks(this.stream.getTracks()),this._ua.emit("changeMainVideoStream",{name:this.display_name,stream:this.stream})}async loadStream(){const t={};this.isAudioOn?this.mediaConstraints.audio?t.audio=this.mediaConstraints.audio:t.audio=!0:t.audio=!1,this.isVideoOn?this.mediaConstraints.video?t.video=this.mediaConstraints.video:t.video=!0:t.video=!1;let r=null;try{r=await navigator.mediaDevices.getUserMedia(t)}catch{try{t.video=!1,r=await navigator.mediaDevices.getUserMedia(t)}catch{t.audio=!1,t.video=!1,r=await navigator.mediaDevices.getUserMedia(t)}}return r}addTracks(t){this._connection.getSenders().forEach(r=>{this._connection.removeTrack(r)}),t.forEach(r=>{this._connection.addTrack(r)})}getRecordFileName(){return AC+this.room_id+btoa(unescape(encodeURIComponent(this.displayName)))+Date.now()}async processIceCandidates(){for(let t=0;t<this.iceCandidates.length;t++)await this._connection.addIceCandidate(this.iceCandidates[t]);this.iceCandidates=[]}async _sendConfigureMessage(t){const r=this._candidates.map(n=>({janus:"trickle",candidate:n,handle_id:this.handle_id,session_id:this.session_id})),u={configure:{janus:"message",body:{request:"configure",record:!0,filename:this.getRecordFileName(),...t},jsep:this.jsepOffer,handle_id:this.handle_id,session_id:this.session_id},trickles:[...r]},s=["Content-Type: application/json",this.getPTypeHeader(ir.ICE)];this.sendRequest(fe.INFO,{extraHeaders:s,body:JSON.stringify(u),eventHandlers:{onSuccessResponse:async n=>{this.isConfigureSent=!0;const _=n.data.split(`\r
135
+ `),v=_[_.length-1],C=JSON.parse(v);await this._connection.setRemoteDescription(C.jsep),this._candidates=[]}}})}_sendMemberStartMessage(t,r){const l={janus:"message",body:{request:"start",room:this.room_id},handle_id:t.handleId,session_id:this.session_id,jsep:r},u=["Content-Type: application/json",this.getPTypeHeader(ir.CONFIGURE)];this.sendRequest(fe.INFO,{extraHeaders:u,body:JSON.stringify(l),eventHandlers:{onSuccessResponse:async s=>{s.status_code===200&&await t.rtcpPeer.setLocalDescription(r)}}})}_sendTrickleMessage(t){const l={trickles:[...t.map(s=>({janus:"trickle",candidate:s,handle_id:this.handle_id,session_id:this.session_id}))]},u=[this.getPTypeHeader(ir.TRICKLE)];this.sendRequest(fe.INFO,{extraHeaders:u,body:JSON.stringify(l),eventHandlers:{onSuccessResponse:async s=>{}}})}async _answerAttachedStream(t,r){let l=null;const u=async _=>{if(!t.rtcpPeer||t.loaded)return;{t.loaded=!0;const H={audio:!0,video:!0};await new Promise(F=>{setTimeout(F,100)}),l=await t.rtcpPeer.createAnswer(H),this._sendMemberStartMessage(t,l)}const v=_.streams[0].getAudioTracks(),C=_.streams[0].getVideoTracks(),R=[];v[0]&&R.push(v[0]),C[0]&&R.push(C[0]);const D=new MediaStream(R);t.stream=D,this._ua.emit("memberJoin",t.memberInfo)};let s,n=[];const g=_=>{t.rtcpPeer.signalingState!=="stable"&&t.rtcpPeer.signalingState!=="have-local-offer"||(n.push(_.candidate||null),clearTimeout(s),s=setTimeout(()=>{this._sendTrickleMessage(n)},500))};t.rtcpPeer=new RTCPeerConnection,t.rtcpPeer.ontrack=u,t.rtcpPeer.onicecandidate=g,t.rtcpPeer.sender=r.sender,await t.rtcpPeer.setRemoteDescription(r.jsep)}_sendJoinMemberRequest(t){const r={janus:"message",body:{request:"join",room:this.room_id,feed:t.info.id,ptype:"subscriber"},handle_id:t.handleId,session_id:this.session_id},l=[this.getPTypeHeader(ir.SUBSCRIBER)];this.sendRequest(fe.SUBSCRIBE,{extraHeaders:l,body:JSON.stringify(r),eventHandlers:{onSuccessResponse:async u=>{var s,n;if(u.status_code===200){const g=JSON.parse(u.body);(n=(s=g==null?void 0:g.plugindata)==null?void 0:s.data)!=null&&n.id&&await this._answerAttachedStream(t,g)}}}})}_attachMember(t){const r={janus:"attach",opaque_id:this.opaque_id,plugin:"janus.plugin.videoroom",session_id:this.session_id},l=[this.getPTypeHeader(ir.SUBSCRIBER)];this.sendRequest(fe.INFO,{extraHeaders:l,body:JSON.stringify(r),eventHandlers:{onSuccessResponse:async u=>{if(u.status_code===200){const n=JSON.parse(u.body).data.id;t.handleId=n,this._sendJoinMemberRequest(t)}}}})}_detachMember(t){const r={janus:"detach",handle_id:t.handleId,session_id:this.session_id},l=[this.getPTypeHeader(ir.SUBSCRIBER)];this.sendRequest(fe.INFO,{extraHeaders:l,body:JSON.stringify(r)}),Nr.stopStreamTracks(t.memberInfo.stream),this._ua.emit("memberHangup",t.memberInfo)}receivePublishers(t){var l,u,s,n,g,_,v,C;const r={...this.memberList};(u=(l=t==null?void 0:t.plugindata)==null?void 0:l.data)==null||u.publishers.forEach(R=>{delete r[R.id],!this.memberList[R.id]&&!this.myFeedList.includes(R.id)&&R.clientID!==this.client_id&&(this.memberList[R.id]=new EC(R,this),this._attachMember(this.memberList[R.id]))}),((n=(s=t==null?void 0:t.plugindata)==null?void 0:s.data)==null?void 0:n.videoroom)==="synced"&&Object.keys(r).forEach(R=>{r[R].hangup(),delete this.memberList[R]}),this.publishers=(_=(g=t==null?void 0:t.plugindata)==null?void 0:g.data)==null?void 0:_.publishers,this.private_id=(C=(v=t==null?void 0:t.plugindata)==null?void 0:v.data)==null?void 0:C.private_id}receiveUnpublished(t){const r=this.memberList[t];r&&(r.hangup(),this._detachMember(r),delete this.memberList[t])}closeSession(){this.stream&&this.stream.getTracks().forEach(r=>{r.stop()}),Object.values(this.memberList).forEach(r=>{r.hangup(),this._detachMember(r)}),this._ua.emit("conferenceEnd",this.id)}async processPlugins(){const t=this._ua.processStreamPlugins;let r=await this.loadStream();for(const l of t)r=await l.process(r);this.stream.getTracks().forEach(l=>{this.stream.removeTrack(l),l.stop()}),r.getTracks().forEach(l=>{this.stream.addTrack(l)})}async resyncPlugins(t){const r=this._ua.processStreamPlugins.filter(l=>l.type===t);for(const l of r)l.running&&l.terminate();if(t==="video"){let l=await this.loadStream();for(const u of r)u.running&&(l=await u.start(l));this.stream.getTracks().forEach(u=>{this.stream.removeTrack(u),u.stop()}),l.getTracks().forEach(u=>{this.stream.addTrack(u)}),this._overrideSenderTracks(this.stream,this._connection),this._ua.emit("changeMainVideoStream",{name:this.display_name,stream:this.stream})}else{const l=this._ua.newStreamPlugins.find(g=>g.type===t);let s=l.getStream().clone();for(const g of r)g.running&&(s=await g.start(s));const n=l.getConnection();this._overrideSenderTracks(s,n),this._ua.emit("changePluginStream",{type:t,stream:s})}}stopProcessPlugins(t){const r=this._ua.processStreamPlugins.filter(l=>l.type===t);for(const l of r)l.running&&l.kill()}_receiveInviteResponse(t){if(Ie.debug("receiveInviteResponse()"),this._dialog&&t.status_code>=200&&t.status_code<=299&&!this.ackSent)if(this._dialog.id.call_id===t.call_id&&this._dialog.id.local_tag===t.from_tag&&this._dialog.id.remote_tag===t.to_tag){this.ackSent=!0,this.sendRequest(fe.ACK);return}else{const r=new Uu(this,t,"UAC");if(r.error!==void 0){Ie.debug(r.error);return}this.sendRequest(fe.ACK),this.sendRequest(fe.BYE);return}if(this.ackSent&&!this.publisherSubscribeSent){const r=JSON.parse(t.body);this.setupMediaStream().then(()=>{this.session_id=r.session_id,this.handle_id=r.data.id,this.client_id=cp();const l={janus:"message",body:{request:"join",room:this.room_id,ptype:"publisher",display:this.display_name,clientID:this.client_id,opaque_id:this.opaque_id},handle_id:this.handle_id},u=[this.getPTypeHeader(ir.PUBLISHER)];this.sendRequest(fe.SUBSCRIBE,{extraHeaders:u,body:JSON.stringify(l),eventHandlers:{onSuccessResponse:async s=>{var n,g,_,v;if(s.status_code===200){if(this.subscribeSent=!0,s.body)try{const C=JSON.parse(s.body)||{};((g=(n=C.plugindata)==null?void 0:n.data)==null?void 0:g.videoroom)==="joined"&&this.myFeedList.push(C.plugindata.data.id),(v=(_=C.plugindata)==null?void 0:_.data)!=null&&v.publishers&&this.receivePublishers(C)}catch(C){console.error(C)}this.lastTrickleReceived&&!this.isConfigureSent&&(this.addTracks(this.stream.getTracks()),this._ua.emit("changeMainVideoStream",{name:this.display_name,stream:this.stream}),this._sendConfigureMessage({audio:!0,video:!0}).then(()=>{})),this._ua.emit("conferenceStart")}}}}),this.publisherSubscribeSent=!0})}if(this._is_canceled){t.status_code>=100&&t.status_code<200?this._request.cancel(this._cancel_reason):t.status_code>=200&&t.status_code<299&&this._acceptAndTerminate(t);return}if(!(this._status!==De.STATUS_INVITE_SENT&&this._status!==De.STATUS_1XX_RECEIVED))switch(!0){case/^100$/.test(t.status_code):this._status=De.STATUS_1XX_RECEIVED;break;case/^1[0-9]{2}$/.test(t.status_code):{if(!t.to_tag){Ie.debug("1xx response received without to tag");break}if(t.hasHeader("contact")&&!this._createDialog(t,"UAC",!0))break;if(this._status=De.STATUS_1XX_RECEIVED,!t.body){this._progress("remote",t);break}const r={originator:"remote",type:"answer",sdp:t.body};Ie.debug('emit "sdp"'),this.emit("sdp",r);const l=new RTCSessionDescription({type:"answer",sdp:r.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(l)).then(()=>this._progress("remote",t)).catch(u=>{Ie.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',u),this.emit("peerconnection:setremotedescriptionfailed",u)});break}case/^2[0-9]{2}$/.test(t.status_code):{if(this._status=De.STATUS_CONFIRMED,!t.body){this._acceptAndTerminate(t,400,fe.causes.MISSING_SDP),this._failed("remote",t,fe.causes.BAD_MEDIA_DESCRIPTION);break}if(!this._createDialog(t,"UAC"))break;break}default:{const r=Nt.sipErrorCause(t.status_code);this._failed("remote",t,r)}}}_sendReinvite(t={}){Ie.debug("sendReinvite()");const r=Nt.cloneArray(t.extraHeaders),l=Nt.cloneObject(t.eventHandlers),u=t.rtcOfferConstraints||this._rtcOfferConstraints||null;let s=!1;r.push(`Contact: ${this._contact}`),r.push("Content-Type: application/sdp"),this._sessionTimers.running&&r.push(`Session-Expires: ${this._sessionTimers.currentExpires};refresher=${this._sessionTimers.refresher?"uac":"uas"}`),this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._createLocalDescription("offer",u)).then(_=>{_=this._mangleOffer(_);const v={originator:"local",type:"offer",sdp:_};Ie.debug('emit "sdp"'),this.emit("sdp",v),this.sendRequest(fe.INVITE,{extraHeaders:r,body:_,eventHandlers:{onSuccessResponse:C=>{n.call(this,C),s=!0},onErrorResponse:C=>{g.call(this,C)},onTransportError:()=>{this.onTransportError()},onRequestTimeout:()=>{this.onRequestTimeout()},onDialogError:()=>{this.onDialogError()}}})}).catch(()=>{g()});function n(_){if(this._status===De.STATUS_TERMINATED||(this.sendRequest(fe.ACK),s))return;if(this._handleSessionTimersInIncomingResponse(_),_.body){if(!_.hasHeader("Content-Type")||_.getHeader("Content-Type").toLowerCase()!=="application/sdp"){g.call(this);return}}else{g.call(this);return}const v={originator:"remote",type:"answer",sdp:_.body};Ie.debug('emit "sdp"'),this.emit("sdp",v);const C=new RTCSessionDescription({type:"answer",sdp:v.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(C)).then(()=>{l.succeeded&&l.succeeded(_)}).catch(R=>{g.call(this),Ie.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',R),this.emit("peerconnection:setremotedescriptionfailed",R)})}function g(_){l.failed&&l.failed(_)}}_sendUpdate(t={}){Ie.debug("sendUpdate()");const r=Nt.cloneArray(t.extraHeaders),l=Nt.cloneObject(t.eventHandlers),u=t.rtcOfferConstraints||this._rtcOfferConstraints||null,s=t.sdpOffer||!1;let n=!1;r.push(`Contact: ${this._contact}`),this._sessionTimers.running&&r.push(`Session-Expires: ${this._sessionTimers.currentExpires};refresher=${this._sessionTimers.refresher?"uac":"uas"}`),s?(r.push("Content-Type: application/sdp"),this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._createLocalDescription("offer",u)).then(v=>{v=this._mangleOffer(v);const C={originator:"local",type:"offer",sdp:v};Ie.debug('emit "sdp"'),this.emit("sdp",C),this.sendRequest(fe.UPDATE,{extraHeaders:r,body:v,eventHandlers:{onSuccessResponse:R=>{g.call(this,R),n=!0},onErrorResponse:R=>{_.call(this,R)},onTransportError:()=>{this.onTransportError()},onRequestTimeout:()=>{this.onRequestTimeout()},onDialogError:()=>{this.onDialogError()}}})}).catch(()=>{_.call(this)})):this.sendRequest(fe.UPDATE,{extraHeaders:r,eventHandlers:{onSuccessResponse:v=>{g.call(this,v)},onErrorResponse:v=>{_.call(this,v)},onTransportError:()=>{this.onTransportError()},onRequestTimeout:()=>{this.onRequestTimeout()},onDialogError:()=>{this.onDialogError()}}});function g(v){if(this._status!==De.STATUS_TERMINATED&&!n)if(this._handleSessionTimersInIncomingResponse(v),s){if(v.body){if(!v.hasHeader("Content-Type")||v.getHeader("Content-Type").toLowerCase()!=="application/sdp"){_.call(this);return}}else{_.call(this);return}const C={originator:"remote",type:"answer",sdp:v.body};Ie.debug('emit "sdp"'),this.emit("sdp",C);const R=new RTCSessionDescription({type:"answer",sdp:C.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(R)).then(()=>{l.succeeded&&l.succeeded(v)}).catch(D=>{_.call(this),Ie.warn('emit "peerconnection:setremotedescriptionfailed" [error:%o]',D),this.emit("peerconnection:setremotedescriptionfailed",D)})}else l.succeeded&&l.succeeded(v)}function _(v){l.failed&&l.failed(v)}}_acceptAndTerminate(t,r,l){Ie.debug("acceptAndTerminate()");const u=[];r&&(l=l||fe.REASON_PHRASE[r]||"",u.push(`Reason: SIP ;cause=${r}; text="${l}"`)),(this._dialog||this._createDialog(t,"UAC"))&&(this.sendRequest(fe.ACK),this.sendRequest(fe.BYE,{extraHeaders:u})),this._status=De.STATUS_TERMINATED}_mangleOffer(t){if(!this._localHold&&!this._remoteHold)return t;if(t=sr.parse(t),this._localHold&&!this._remoteHold){Ie.debug("mangleOffer() | me on hold, mangling offer");for(const r of t.media)Pu.indexOf(r.type)!==-1&&(r.direction?r.direction==="sendrecv"?r.direction="sendonly":r.direction==="recvonly"&&(r.direction="inactive"):r.direction="sendonly")}else if(this._localHold&&this._remoteHold){Ie.debug("mangleOffer() | both on hold, mangling offer");for(const r of t.media)Pu.indexOf(r.type)!==-1&&(r.direction="inactive")}else if(this._remoteHold){Ie.debug("mangleOffer() | remote on hold, mangling offer");for(const r of t.media)Pu.indexOf(r.type)!==-1&&(r.direction?r.direction==="sendrecv"?r.direction="recvonly":r.direction==="recvonly"&&(r.direction="inactive"):r.direction="recvonly")}return sr.write(t)}_setLocalMediaStatus(){let t=!0,r=!0;(this._localHold||this._remoteHold)&&(t=!1,r=!1),this._audioMuted&&(t=!1),this._videoMuted&&(r=!1),this._toggleMuteAudio(!t),this._toggleMuteVideo(!r)}_handleSessionTimersInIncomingRequest(t,r){if(!this._sessionTimers.enabled)return;let l;t.session_expires&&t.session_expires>=fe.MIN_SESSION_EXPIRES?(this._sessionTimers.currentExpires=t.session_expires,l=t.session_expires_refresher||"uas"):(this._sessionTimers.currentExpires=this._sessionTimers.defaultExpires,l="uas"),r.push(`Session-Expires: ${this._sessionTimers.currentExpires};refresher=${l}`),this._sessionTimers.refresher=l==="uas",this._runSessionTimer()}_handleSessionTimersInIncomingResponse(t){if(!this._sessionTimers.enabled)return;let r;t.session_expires&&t.session_expires>=fe.MIN_SESSION_EXPIRES?(this._sessionTimers.currentExpires=t.session_expires,r=t.session_expires_refresher||"uac"):(this._sessionTimers.currentExpires=this._sessionTimers.defaultExpires,r="uac"),this._sessionTimers.refresher=r==="uac",this._runSessionTimer()}_runSessionTimer(){const t=this._sessionTimers.currentExpires;this._sessionTimers.running=!0,clearTimeout(this._sessionTimers.timer),this._sessionTimers.refresher?this._sessionTimers.timer=setTimeout(()=>{this._status!==De.STATUS_TERMINATED&&this._isReadyToReOffer()&&(Ie.debug("runSessionTimer() | sending session refresh request"),this._sessionTimers.refreshMethod===fe.UPDATE?this._sendUpdate():this._sendReinvite())},t*500):this._sessionTimers.timer=setTimeout(()=>{this._status!==De.STATUS_TERMINATED&&(Ie.warn("runSessionTimer() | timer expired, terminating the session"),this.terminate({cause:fe.causes.REQUEST_TIMEOUT,status_code:408,reason_phrase:"Session Timer Expired"}))},t*1100)}_toggleMuteAudio(t){const r=this._connection.getSenders().filter(l=>l.track&&l.track.kind==="audio");for(const l of r)l.track.enabled=!t}_toggleMuteVideo(t){const r=this._connection.getSenders().filter(l=>l.track&&l.track.kind==="video");for(const l of r)l.track.enabled=!t}_newJanusSession(t,r){Ie.debug("newRTCSession()"),this._ua.newJanusSession(this,{originator:t,session:this,request:r})}_connecting(t){Ie.debug("session connecting"),Ie.debug('emit "connecting"'),this.emit("connecting",{request:t})}_progress(t,r){Ie.debug("session progress"),Ie.debug('emit "progress"'),this.emit("progress",{originator:t,response:r||null})}_accepted(t,r){Ie.debug("session accepted"),this._start_time=new Date,Ie.debug('emit "accepted"'),this.emit("accepted",{originator:t,response:r||null})}_confirmed(t,r){Ie.debug("session confirmed"),this._is_confirmed=!0,Ie.debug('emit "confirmed"'),this.emit("confirmed",{originator:t,ack:r||null})}_ended(t,r,l){Ie.debug("session ended"),this._end_time=new Date,this._close(),Ie.debug('emit "ended"'),this.emit("ended",{originator:t,message:r||null,cause:l})}_failed(t,r,l){Ie.debug("session failed"),Ie.debug('emit "_failed"'),this.emit("_failed",{originator:t,message:r||null,cause:l}),this._close(),Ie.debug('emit "failed"'),this.emit("failed",{originator:t,message:r||null,cause:l})}_onhold(t){Ie.debug("session onhold"),this._setLocalMediaStatus(),Ie.debug('emit "hold"'),this.emit("hold",{originator:t})}_onunhold(t){Ie.debug("session onunhold"),this._setLocalMediaStatus(),Ie.debug('emit "unhold"'),this.emit("unhold",{originator:t})}_onmute({audio:t,video:r}){Ie.debug("session onmute"),this._setLocalMediaStatus(),Ie.debug('emit "muted"'),this.emit("muted",{audio:t,video:r})}_onunmute({audio:t,video:r}){Ie.debug("session onunmute"),this._setLocalMediaStatus(),Ie.debug('emit "unmuted"'),this.emit("unmuted",{audio:t,video:r})}}class ml{constructor(t){if(this.headers={},t.length>0){let r=!1;const l=t.split(`\r
136
136
  `),u=l.shift().split(/\s/);this.protocol=u[0],this.ident=u[1],this.code=u.length>3?parseInt(u[2]):0,this.method=u.length>3?u[3]:u[2],this.body="";for(const s of l){if(s==`-------${this.ident}$`)break;if(s===""){r=!0;continue}if(s&&r)this.body+=`${s}\r
137
137
  `;else{const n=s.split(": ");this.addHeader(n[0],n[1].trim())}}}else this.ident=Nt.createRandomToken(12),this.protocol="MSRP"}addHeader(t,r){this.headers[t]=r}getHeader(t){return this.headers[t]}toString(){let t=`${this.protocol} ${this.ident} ${this.code} ${this.method}`.replaceAll(/null\s|undefined\s/ig,"")+`\r
138
138
  `;for(const r in this.headers)t+=`${r}: ${this.headers[r]}\r
@@ -155,11 +155,11 @@ a=accept-types:text/plain text/html
155
155
  a=path:${t.getHeader("Use-Path")} msrp://${this._ua._configuration.authorization_user}.${this._ua._configuration.realm}:2856/${this.auth_id};ws
156
156
  `),this._newMSRPSession("local",this._request),this._id=this._request.call_id+this._from_tag,new no(this._ua,this._request,{onRequestTimeout:()=>{this.onRequestTimeout(),console.log("to")},onTransportError:s=>{this.onTransportError(),console.log(s)},onAuthenticated:s=>{this._request=s},onReceiveResponse:s=>{this._receiveInviteResponse(s),s.status_code===200&&(s.parseSDP(!0),this._status=mt.STATUS_CONFIRMED,this.target_addr=s.sdp.media[0].invalid[1].value.replaceAll("path:","").split(" ").reverse(),this.status="active",this.emit("active"),this.emit("confirmed"))}}).send(),this._status=mt.STATUS_INVITE_SENT}terminate(t={}){const r=t.cause||fe.causes.BYE,l=Nt.cloneArray(t.extraHeaders),u=t.body;let s,n=t.status_code,g=t.reason_phrase;if(this._status===mt.STATUS_TERMINATED)throw new Ei.InvalidStateError(this._status);switch(this.status="terminated",this._status){case mt.STATUS_NULL:case mt.STATUS_INVITE_SENT:case mt.STATUS_1XX_RECEIVED:if(n&&(n<200||n>=700))throw new TypeError(`Invalid status_code: ${n}`);n&&(g=g||fe.REASON_PHRASE[n]||"",s=`SIP ;cause=${n} ;text="${g}"`),this._status===mt.STATUS_NULL||this._status===mt.STATUS_INVITE_SENT?(this._is_canceled=!0,this._cancel_reason=s):this._status===mt.STATUS_1XX_RECEIVED&&this._request.cancel(s),this._status=mt.STATUS_CANCELED,this._failed("local",null,fe.causes.CANCELED);break;case mt.STATUS_WAITING_FOR_ANSWER:case mt.STATUS_ANSWERED:if(n=n||480,n<300||n>=700)throw new TypeError(`Invalid status_code: ${n}`);this._request.reply(n,g,l,u),this._failed("local",null,fe.causes.REJECTED);break;case mt.STATUS_WAITING_FOR_ACK:case mt.STATUS_CONFIRMED:if(g=t.reason_phrase||fe.REASON_PHRASE[n]||"",n&&(n<200||n>=700))throw new TypeError(`Invalid status_code: ${n}`);if(n&&l.push(`Reason: SIP ;cause=${n}; text="${g}"`),this._status===mt.STATUS_WAITING_FOR_ACK&&this._direction==="incoming"&&this._request.server_transaction.state!==Er.C.STATUS_TERMINATED){const _=this._dialog;this.receiveRequest=({method:v})=>{v===fe.ACK&&(this.sendRequest(fe.BYE,{extraHeaders:l,body:u}),_.terminate())},this._request.server_transaction.on("stateChanged",()=>{this._request.server_transaction.state===Er.C.STATUS_TERMINATED&&(this.sendRequest(fe.BYE,{extraHeaders:l,body:u}),_.terminate())}),this._ended("local",null,r),this._dialog=_,this._ua.newDialog(_)}else this.sendRequest(fe.BYE,{extraHeaders:l,body:u}),this._ended("local",null,r)}}sendRequest(t,r){return this._dialog.sendRequest(t,r)}authenticate(t){this.status="auth";let r=new ml("");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`),t&&r.addHeader("Authorization",t.toString());let l=r.toString(),u=[];for(var s=0;s<l.length;s++)u.push(l.charCodeAt(s).toString(16));this._connection.send(r.toString())}onmessage(t){const r=new ml(t.data);if(this.status==="auth"&&r.code===401){const l=this.parseAuth(r.getHeader("WWW-Authenticate")),u=new Lw(this.credentials);u.authenticate({method:"AUTH",ruri:`msrp://${this._ua._configuration.realm}:2856;ws`,body:null},l,Nt.createRandomToken(12)),this.authenticate(u)}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 t=new RTCPeerConnection({iceServers:[]});t.createDataChannel(""),t.createOffer().then(t.setLocalDescription.bind(t)),t.onicecandidate=r=>{if(!r||!r.candidate||!r.candidate.candidate)return;const l=/([0-9]{1,3}(\.[0-9]{1,3}){3})/,u=r.candidate.candidate.match(l);this.my_ip=u&&u[1],t.onicecandidate=()=>{},this.authenticate(null)}}onerror(t){console.log(t)}_receiveInviteResponse(t){if(console.log("resp0000000000000",t),this._dialog&&t.status_code>=200&&t.status_code<=299)if(console.log("200000000000000"),this._dialog.id.call_id===t.call_id&&this._dialog.id.local_tag===t.from_tag&&this._dialog.id.remote_tag===t.to_tag){this.sendRequest(fe.ACK);return}else{const r=new Iu(this,t,"UAC");if(r.error!==void 0){console.log(r.error);return}this.sendRequest(fe.ACK),this.sendRequest(fe.BYE);return}if(this._is_canceled){t.status_code>=100&&t.status_code<200?this._request.cancel(this._cancel_reason):t.status_code>=200&&t.status_code<299&&this._acceptAndTerminate(t);return}if(!(this._status!==mt.STATUS_INVITE_SENT&&this._status!==mt.STATUS_1XX_RECEIVED))switch(console.log("start Switch"),!0){case/^100$/.test(t.status_code):this._status=mt.STATUS_1XX_RECEIVED;break;case/^1[0-9]{2}$/.test(t.status_code):{if(!t.to_tag){console.log("1xx response received without to tag");break}if(t.hasHeader("contact")&&!this._createDialog(t,"UAC",!0))break;if(this._status=mt.STATUS_1XX_RECEIVED,!t.body){this._progress("remote",t);break}const r={originator:"remote",type:"answer",sdp:t.body};console.log('emit "sdp"'),this.emit("sdp",r);const l=new RTCSessionDescription({type:"answer",sdp:r.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(l)).then(()=>this._progress("remote",t)).catch(u=>{console.log('emit "peerconnection:setremotedescriptionfailed" [error:%o]',u),this.emit("peerconnection:setremotedescriptionfailed",u)});break}case/^2[0-9]{2}$/.test(t.status_code):{if(console.log("maybe here???"),this._status=mt.STATUS_CONFIRMED,!t.body){this._acceptAndTerminate(t,400,fe.causes.MISSING_SDP),console.log("failed 3"),this._failed("remote",t,fe.causes.BAD_MEDIA_DESCRIPTION);break}if(!this._createDialog(t,"UAC"))break;const r={originator:"remote",type:"answer",sdp:t.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(l=>this._connection.setLocalDescription(l)).catch(l=>{this._acceptAndTerminate(t,500,l.toString()),console.log("failed 4"),this._failed("local",t,fe.causes.WEBRTC_ERROR)})}).then(()=>{this._handleSessionTimersInIncomingResponse(t),this._accepted("remote",t),this.sendRequest(fe.ACK),this._confirmed("local",null)});break}default:{const r=Nt.sipErrorCause(t.status_code);console.log("failed 5"),this._failed("remote",t,r)}}}sendMSRP(t){const r=new ml("");r.method="SEND",r.addHeader("To-Path",`${this.my_addr[1]} ${this.target_addr[1]} ${this.target_addr[0]}`),r.addHeader("From-Path",`${this.my_addr[0]}`),r.addHeader("Message-ID",Nt.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=t;let l=r.toString();console.log(l);let u=[];for(var s=0;s<l.length;s++)u.push(l.charCodeAt(s).toString(16));console.log(u),this._connection.send(r.toString()),r.direction="outgoing",this.emit("newMessage",r),this._msgHistory.push(r),this.emit("msgHistoryUpdate",this._msgHistory)}_sendOk(t){let r=t.ident,l=t.getHeader("Message-ID"),u=new ml("");u.method="200 OK",u.addHeader("To-Path",`${this.my_addr[1]}`),u.addHeader("From-Path",`${this.my_addr[0]}`),u.addHeader("Message-ID",l),u.ident=r;let s=u.toString();console.log(s);let n=[];for(var g=0;g<s.length;g++)n.push(s.charCodeAt(g).toString(16));console.log(n),this._connection.send(u.toString())}_sendReport(t){let r=t.ident,l=t.getHeader("Message-ID"),u=new ml("");u.method="REPORT",u.addHeader("To-Path",`${t.getHeader("From-Path")}`),u.addHeader("From-Path",`${this.my_addr[0]}`),u.addHeader("Message-ID",l),u.addHeader("Byte-Range","1-25/25"),u.addHeader("Status","000 200 OK"),u.ident=r;let s=u.toString();console.log(s);let n=[];for(var g=0;g<s.length;g++)n.push(s.charCodeAt(g).toString(16));console.log(n),this._connection.send(u.toString())}parseAuth(t){const r={},l=t.replace("Digest","").split(",");for(const u of l){const s=u.trim().split("=");r[s[0]]=s[1].match('^"(.+)"$')[1]}return r}init_incoming(t,r){let l;const u=t.hasHeader("Content-Type")?t.getHeader("Content-Type").toLowerCase():void 0;if(t.body&&u!=="application/sdp"){t.reply(415);return}if(this._status=mt.STATUS_INVITE_RECEIVED,this._from_tag=t.from_tag,this._id=t.call_id+this._from_tag,this._request=t,this._contact=this._ua.contact.toString(),t.hasHeader("expires")&&(l=t.getHeader("expires")*1e3),t.to_tag=Nt.newTag(),!this._createDialog(t,"UAS",!0)){t.reply(500,"Missing Contact header field");return}t.body?this._late_sdp=!1:this._late_sdp=!0,this._status=mt.STATUS_WAITING_FOR_ANSWER,this._timers.userNoAnswerTimer=setTimeout(()=>{t.reply(408),console.log("failed 6"),this._failed("local",null,fe.causes.NO_ANSWER)},this._ua.configuration.no_answer_timeout),l&&(this._timers.expiresTimer=setTimeout(()=>{this._status===mt.STATUS_WAITING_FOR_ANSWER&&(t.reply(487),console.log("failed 7"),this._failed("system",null,fe.causes.EXPIRES))},l)),this._direction="incoming",this._local_identity=t.to,this._remote_identity=t.from,r&&r(this),t.parseSDP(!0),this.target_addr=t.sdp.media[0].invalid[1].value.replaceAll("path:","").split(" ").reverse(),this._newMSRPSession("remote",t),this._status!==mt.STATUS_TERMINATED&&(t.reply(180,null,[`Contact: ${this._ua._contact}`]),this._progress("local",null))}_failed(t,r,l){this.emit("_failed",{originator:t,message:r||null,cause:l}),this._close(),this.emit("failed",{originator:t,message:r||null,cause:l})}_close(){if(console.log("CLOSE SESSION"),this._status!==mt.STATUS_TERMINATED){if(this._status=mt.STATUS_TERMINATED,this._connection)try{this._connection.close()}catch(t){console.log("close() | error closing the RTCPeerConnection: %o",t)}for(const t in this._timers)Object.prototype.hasOwnProperty.call(this._timers,t)&&clearTimeout(this._timers[t]);clearTimeout(this._sessionTimers.timer),this._dialog&&(this._dialog.terminate(),delete this._dialog);for(const t in this._earlyDialogs)Object.prototype.hasOwnProperty.call(this._earlyDialogs,t)&&(this._earlyDialogs[t].terminate(),delete this._earlyDialogs[t]);for(const t in this._referSubscribers)Object.prototype.hasOwnProperty.call(this._referSubscribers,t)&&delete this._referSubscribers[t];this._ua.destroyMSRPSession(this)}}_createDialog(t,r,l){const u=r==="UAS"?t.to_tag:t.from_tag,s=r==="UAS"?t.from_tag:t.to_tag,n=t.call_id+u+s;let g=this._earlyDialogs[n];if(l)return g?!0:(g=new Iu(this,t,r,Iu.C.STATUS_EARLY),g.error?(console.log("failed 8"),this._failed("remote",t,fe.causes.INTERNAL_ERROR),!1):(this._earlyDialogs[n]=g,!0));{if(this._from_tag=t.from_tag,this._to_tag=t.to_tag,g)return g.update(t,r),this._dialog=g,delete this._earlyDialogs[n],!0;const _=new Iu(this,t,r);return _.error?(console.log("failed 9"),this._failed("remote",t,fe.causes.INTERNAL_ERROR),!1):(this._dialog=_,!0)}}_newMSRPSession(t,r){this._ua.newMSRPSession(this,{originator:t,session:this,request:r})}_progress(t,r){this.emit("progress",{originator:t,response:r||null})}isEnded(){switch(this._status){case mt.STATUS_CANCELED:case mt.STATUS_TERMINATED:return!0;default:return!1}}_accepted(t,r){console.log("session accepted"),this._start_time=new Date,console.log('emit "accepted"'),this.emit("accepted",{originator:t,response:r||null})}_confirmed(t,r){console.log("session confirmed"),this._is_confirmed=!0,console.log('emit "confirmed"'),this.emit("confirmed",{originator:t,ack:r||null})}_ended(t,r,l){console.log("session ended"),this._end_time=new Date,this._close(),console.log('emit "ended"'),this.emit("ended",{originator:t,message:r||null,cause:l})}_handleSessionTimersInIncomingResponse(t){if(!this._sessionTimers.enabled)return;let r;t.session_expires&&t.session_expires>=fe.MIN_SESSION_EXPIRES?(this._sessionTimers.currentExpires=t.session_expires,r=t.session_expires_refresher||"uac"):(this._sessionTimers.currentExpires=this._sessionTimers.defaultExpires,r="uac"),this._sessionTimers.refresher=r==="uac",this._runSessionTimer()}receiveRequest(t){if(console.log("receiveRequest()"),t.method===fe.CANCEL)(this._status===mt.STATUS_WAITING_FOR_ANSWER||this._status===mt.STATUS_ANSWERED)&&(this._status=mt.STATUS_CANCELED,this._request.reply(487),console.log("failed 10"),this._failed("remote",t,fe.causes.CANCELED));else switch(t.method){case fe.ACK:if(this._status!==mt.STATUS_WAITING_FOR_ACK)return;if(this._status=mt.STATUS_CONFIRMED,clearTimeout(this._timers.ackTimer),clearTimeout(this._timers.invite2xxTimer),this._late_sdp){if(!t.body){this.terminate({cause:fe.causes.MISSING_SDP,status_code:400});break}const r={originator:"remote",type:"answer",sdp:t.body};console.log('emit "sdp"'),this.emit("sdp",r);const l=new RTCSessionDescription({type:"answer",sdp:r.sdp});this._connectionPromiseQueue=this._connectionPromiseQueue.then(()=>this._connection.setRemoteDescription(l)).then(()=>{this._is_confirmed||this._confirmed("remote",t)}).catch(u=>{this.terminate({cause:fe.causes.BAD_MEDIA_DESCRIPTION,status_code:488}),console.log('emit "peerconnection:setremotedescriptionfailed" [error:%o]',u),this.emit("peerconnection:setremotedescriptionfailed",u)})}else this._is_confirmed||this._confirmed("remote",t);break;case fe.BYE:this._status===mt.STATUS_CONFIRMED||this._status===mt.STATUS_WAITING_FOR_ACK?(t.reply(200),this._ended("remote",t,fe.causes.BYE)):this._status===mt.STATUS_INVITE_RECEIVED||this._status===mt.STATUS_WAITING_FOR_ANSWER?(t.reply(200),this._request.reply(487,"BYE Received"),this._ended("remote",t,fe.causes.BYE)):t.reply(403,"Wrong Status");break;case fe.INVITE:this._status===mt.STATUS_CONFIRMED?t.hasHeader("replaces")?this._receiveReplaces(t):this._receiveReinvite(t):t.reply(403,"Wrong Status");break;case fe.INFO:this._status===mt.STATUS_1XX_RECEIVED||this._status===mt.STATUS_WAITING_FOR_ANSWER||this._status===mt.STATUS_ANSWERED||this._status===mt.STATUS_WAITING_FOR_ACK||this._status===mt.STATUS_CONFIRMED?(t.hasHeader("Content-Type")?t.getHeader("Content-Type").toLowerCase():void 0)!==void 0?new hd(this).init_incoming(t):t.reply(415):t.reply(403,"Wrong Status");break;case fe.UPDATE:this._status===mt.STATUS_CONFIRMED?this._receiveUpdate(t):t.reply(403,"Wrong Status");break;case fe.REFER:this._status===mt.STATUS_CONFIRMED?this._receiveRefer(t):t.reply(403,"Wrong Status");break;case fe.NOTIFY:this._status===mt.STATUS_CONFIRMED?this._receiveNotify(t):t.reply(403,"Wrong Status");break;default:t.reply(501)}}onTransportError(){console.log("onTransportError()"),this._status!==mt.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:fe.causes.CONNECTION_ERROR,cause:fe.causes.CONNECTION_ERROR})}onRequestTimeout(){console.log("onRequestTimeout()"),this._status!==mt.STATUS_TERMINATED&&this.terminate({status_code:408,reason_phrase:fe.causes.REQUEST_TIMEOUT,cause:fe.causes.REQUEST_TIMEOUT})}onDialogError(){console.log("onDialogError()"),this._status!==mt.STATUS_TERMINATED&&this.terminate({status_code:500,reason_phrase:fe.causes.DIALOG_ERROR,cause:fe.causes.DIALOG_ERROR})}}var IC=Dr();const Dd=Ht(IC),Hu=new Su("Parser"),RC=(f,t)=>{let r,l,u=f.indexOf(`\r
157
157
  `);if(u===-1){Hu.warn("parseMessage() | no CRLF found, not a SIP message");return}const s=f.substring(0,u);let n=Dd.parse(s,"Request_Response");if(n===-1){Hu.warn(`parseMessage() | error parsing first line of SIP message: "${s}"`);return}else n.status_code?(r=new fl.IncomingResponse,r.status_code=n.status_code,r.reason_phrase=n.reason_phrase):(r=new fl.IncomingRequest(t),r.method=n.method,r.ruri=n.uri);r.data=f;let g=u+2;for(;;){if(u=$C(f,g),u===-2){l=g+2;break}else if(u===-1){Hu.warn("parseMessage() | malformed message");return}if(n=xC(r,f,g,u),n!==!0){Hu.warn("parseMessage() |",n.error);return}g=u+2}if(r.hasHeader("content-length")){const _=r.getHeader("content-length");r.body=f.substr(l,_)}else r.body=f.substring(l);return r};function $C(f,t){let r=t,l=0,u=0;if(f.substring(r,r+2).match(/(^\r\n)/))return-2;for(;l===0;){if(u=f.indexOf(`\r
158
- `,r),u===-1)return u;!f.substring(u+2,u+4).match(/(^\r\n)/)&&f.charAt(u+2).match(/(^\s+)/)?r=u+2:l=u}return l}function xC(f,t,r,l){let u;const s=t.indexOf(":",r),n=t.substring(r,s).trim(),g=t.substring(s+1,l).trim();switch(n.toLowerCase()){case"via":case"v":f.addHeader("via",g),f.getHeaders("via").length===1?(u=f.parseHeader("Via"),u&&(f.via=u,f.via_branch=u.branch)):u=0;break;case"from":case"f":f.setHeader("from",g),u=f.parseHeader("from"),u&&(f.from=u,f.from_tag=u.getParam("tag"));break;case"to":case"t":f.setHeader("to",g),u=f.parseHeader("to"),u&&(f.to=u,f.to_tag=u.getParam("tag"));break;case"record-route":if(u=Dd.parse(g,"Record_Route"),u===-1)u=void 0;else for(const _ of u)f.addHeader("record-route",g.substring(_.possition,_.offset)),f.headers["Record-Route"][f.getHeaders("record-route").length-1].parsed=_.parsed;break;case"call-id":case"i":f.setHeader("call-id",g),u=f.parseHeader("call-id"),u&&(f.call_id=g);break;case"contact":case"m":if(u=Dd.parse(g,"Contact"),u===-1)u=void 0;else for(const _ of u)f.addHeader("contact",g.substring(_.possition,_.offset)),f.headers.Contact[f.getHeaders("contact").length-1].parsed=_.parsed;break;case"content-length":case"l":f.setHeader("content-length",g),u=f.parseHeader("content-length");break;case"content-type":case"c":f.setHeader("content-type",g),u=f.parseHeader("content-type");break;case"cseq":f.setHeader("cseq",g),u=f.parseHeader("cseq"),u&&(f.cseq=u.value),f instanceof fl.IncomingResponse&&(f.method=u.method);break;case"max-forwards":f.setHeader("max-forwards",g),u=f.parseHeader("max-forwards");break;case"www-authenticate":f.setHeader("www-authenticate",g),u=f.parseHeader("www-authenticate");break;case"proxy-authenticate":f.setHeader("proxy-authenticate",g),u=f.parseHeader("proxy-authenticate");break;case"session-expires":case"x":f.setHeader("session-expires",g),u=f.parseHeader("session-expires"),u&&(f.session_expires=u.expires,f.session_expires_refresher=u.refresher);break;case"refer-to":case"r":f.setHeader("refer-to",g),u=f.parseHeader("refer-to"),u&&(f.refer_to=u);break;case"replaces":f.setHeader("replaces",g),u=f.parseHeader("replaces"),u&&(f.replaces=u);break;case"event":case"o":f.setHeader("event",g),u=f.parseHeader("event"),u&&(f.event=u);break;default:f.addHeader(n,g),u=0}return u===void 0?{error:`error parsing header "${n}"`}:!0}const OC={parseMessage:RC},po=new Su("Registrator"),Fu=10;class DC{constructor(t,r){this._reg_id=1,this._ua=t,this._transport=r,this._registrar=t.configuration.registrar_server,this._expires=t.configuration.register_expires,this._call_id=Ln.createRandomToken(22),this._cseq=0,this._to_uri=t.configuration.uri,this._registrationTimer=null,this._registering=!1,this._registered=!1,this._contact=this._ua.contact.toString();const l=this._contact.indexOf(">");if(l!==-1){const u=this._contact.slice(0,l)+this._contact.slice(l+1,this._contact.length);this._contact=u}this._extra_contact="",this._extraContactParams="",this._extra_contact+=";+sip.ice",this._extraHeaders=[],this._sipInstance=`"<urn:uuid:${this._ua.configuration.instance_id}>"`,this._extra_contact+=`;reg-id=${this._reg_id}`,this._extra_contact+=`;+sip.instance=${this._sipInstance}`}get registered(){return this._registered}setExtraHeaders(t){Array.isArray(t)||(t=[]),this._extraHeaders=t.slice()}setExtraContactParams(t){t instanceof Object||(t={}),this._extraContactParams="";for(const r in t)if(Object.prototype.hasOwnProperty.call(t,r)){const l=t[r];this._extraContactParams+=`;${r}`,l&&(this._extraContactParams+=`=${l}`)}}setExtraContactUriParams(t){t instanceof Object||(t={}),this._extraContactParams="";for(const r in t)if(Object.prototype.hasOwnProperty.call(t,r)){const l=t[r];this._extraContactParams+=`;${r}`,l&&(this._extraContactParams+=`=${l}`)}}register(){if(this._registering){po.debug("Register request in progress...");return}const t=this._extraHeaders.slice();t.push(`Contact: ${this._contact}${this._extraContactParams}>${this._extra_contact};expires=${this._expires}`),t.push(`Expires: ${this._expires}`);const r=new Ds.OutgoingRequest(fe.REGISTER,this._registrar,this._ua,{to_uri:this._to_uri,call_id:this._call_id,cseq:this._cseq+=1},t),l=new no(this._ua,r,{onRequestTimeout:()=>{this._registrationFailure(null,fe.causes.REQUEST_TIMEOUT)},onTransportError:()=>{this._registrationFailure(null,fe.causes.CONNECTION_ERROR)},onAuthenticated:()=>{this._cseq+=1},onReceiveResponse:u=>{if(u.cseq===this._cseq)switch(this._registrationTimer!==null&&(clearTimeout(this._registrationTimer),this._registrationTimer=null),!0){case/^1[0-9]{2}$/.test(u.status_code):break;case/^2[0-9]{2}$/.test(u.status_code):{if(this._registering=!1,!u.hasHeader("Contact")){po.debug("no Contact header in response to REGISTER, response ignored");break}const s=u.headers.Contact.reduce((v,C)=>v.concat(C.parsed),[]);let n=s.find(v=>this._sipInstance===v.getParam("+sip.instance")&&this._reg_id===parseInt(v.getParam("reg-id")));if(n||(n=s.find(v=>v.uri.user===this._ua.contact.uri.user)),!n){po.debug("no Contact header pointing to us, response ignored");break}this._ua.clearKeepAliveInterval(),this._ua.setLastRegisterTimestamp();let g=n.getParam("expires");!g&&u.hasHeader("expires")&&(g=u.getHeader("expires")),g||(g=this._expires),g=Number(g),g<Fu&&(g=Fu);const _=g>64?g*1e3/2+Math.floor((g/2-32)*1e3*Math.random()):g*1e3-5e3;this._registrationTimer=setTimeout(()=>{this._registrationTimer=null,this._ua.listeners("registrationExpiring").length===0?this.register():this._ua.emit("registrationExpiring")},_),n.hasParam("temp-gruu")&&(this._ua.contact.temp_gruu=n.getParam("temp-gruu").replace(/"/g,"")),n.hasParam("pub-gruu")&&(this._ua.contact.pub_gruu=n.getParam("pub-gruu").replace(/"/g,"")),this._registered||(this._registered=!0,this._ua.registered({response:u}));break}case/^423$/.test(u.status_code):{u.hasHeader("min-expires")?(this._expires=Number(u.getHeader("min-expires")),this._expires<Fu&&(this._expires=Fu),this.register()):(po.debug("423 response received for REGISTER without Min-Expires"),this._registrationFailure(u,fe.causes.SIP_FAILURE_CODE));break}default:{const s=Ln.sipErrorCause(u.status_code);this._registrationFailure(u,s)}}}});this._registering=!0,l.send()}unregister(t={}){if(!this._registered){po.debug("already unregistered");return}this._registered=!1,this._registrationTimer!==null&&(clearTimeout(this._registrationTimer),this._registrationTimer=null);const r=this._extraHeaders.slice();t.all?r.push(`Contact: *${this._extraContactParams}`):r.push(`Contact: ${this._contact}${this._extraContactParams}>${this._extra_contact};expires=0`),r.push("Expires: 0");const l=new Ds.OutgoingRequest(fe.REGISTER,this._registrar,this._ua,{to_uri:this._to_uri,call_id:this._call_id,cseq:this._cseq+=1},r);new no(this._ua,l,{onRequestTimeout:()=>{this._unregistered(null,fe.causes.REQUEST_TIMEOUT)},onTransportError:()=>{this._unregistered(null,fe.causes.CONNECTION_ERROR)},onAuthenticated:()=>{this._cseq+=1},onReceiveResponse:s=>{switch(!0){case/^1[0-9]{2}$/.test(s.status_code):break;case/^2[0-9]{2}$/.test(s.status_code):this._unregistered(s);break;default:{const n=Ln.sipErrorCause(s.status_code);this._unregistered(s,n)}}}}).send()}close(){this._registered&&this.unregister()}onTransportClosed(){this._registering=!1,this._registrationTimer!==null&&(clearTimeout(this._registrationTimer),this._registrationTimer=null),this._registered&&(this._registered=!1,this._ua.unregistered({}))}_registrationFailure(t,r){this._registering=!1,this._ua.registrationFailed({response:t||null,cause:r}),this._registered&&(this._registered=!1,this._ua.unregistered({response:t||null,cause:r}))}_unregistered(t,r){this._registering=!1,this._registered=!1,this._ua.unregistered({response:t||null,cause:r||null})}}const ds=console,Ri={STATUS_INIT:0,STATUS_READY:1,STATUS_USER_CLOSED:2,STATUS_NOT_READY:3,CONFIGURATION_ERROR:1,NETWORK_ERROR:2},kC=yC;class NC extends kC{constructor(t){super(t),this._msrp_sessions=[],this._transactions={nist:{},nict:{},ist:{},ict:{}},this._janus_sessions=[],this.newStreamPlugins=[],this.processStreamPlugins=[],this.optionsInterval=null,this.lastOptionsTimestamp=null,this.lastRegisterTimestamp=null,this._registrator=new DC(this)}setLastRegisterTimestamp(){this.lastRegisterTimestamp=Date.now()}call(t,r){return super.call(t,r)}joinVideoCall(t,r,l){ds.debug("call()");const u=new Lu(this);return u.configureMedia({audio:!0,video:!0}),u.connect(t,r,l),u}startScreenShare(){ds.debug("startScreenShare()");for(const t in this._janus_sessions)this._janus_sessions[t].connectScreenShare()}changeMediaConstraints(t){for(const r in this._janus_sessions)this._janus_sessions[r].changeMediaConstraints(t)}startBlur(){for(const t in this._janus_sessions)this._janus_sessions[t].connectBlur()}stopBlur(){for(const t in this._janus_sessions)this._janus_sessions[t].stopBlur()}_loadConfig(t){try{_o.load(this._configuration,t)}catch(s){throw s}this._configuration.display_name===0&&(this._configuration.display_name="0"),this._configuration.instance_id||(this._configuration.instance_id=Ln.newUUID());let r;typeof window<"u"&&typeof window.document<"u"?r=window==null?void 0:window.navigator.userAgent:typeof self<"u"&&self.navigator&&(r=self.navigator.userAgent),r+=" "+Et.USER_AGENT,this._configuration.user_agent=t.overrideUserAgent&&typeof t.overrideUserAgent=="function"?t.overrideUserAgent(r):r,t.onTransportCallback&&typeof t.onTransportCallback=="function"&&(this.onTransportCallback=t.onTransportCallback),this._configuration.jssip_id=Ln.createRandomToken(5);const l=this._configuration.uri.clone();l.user=null,this._configuration.hostport_params=l.toString().replace(/^sip:/i,"");try{this._transport=new jE(this._configuration.sockets,{max_interval:this._configuration.connection_recovery_max_interval,min_interval:this._configuration.connection_recovery_min_interval}),this._transport.onconnecting=MC.bind(this),this._transport.onconnect=UC.bind(this),this._transport.ondisconnect=PC.bind(this),this._transport.ondata=LC.bind(this)}catch(s){throw ds.warn(s),new Ei.ConfigurationError("sockets",this._configuration.sockets)}if(delete this._configuration.sockets,this._configuration.authorization_user||(this._configuration.authorization_user=this._configuration.uri.user),!this._configuration.registrar_server){const s=this._configuration.uri.clone();s.user=null,s.clearParams(),s.clearHeaders(),this._configuration.registrar_server=s}this._configuration.no_answer_timeout*=1e3,this._configuration.contact_uri?this._configuration.via_host=this._configuration.contact_uri.host:this._configuration.contact_uri=new Ia("sip",Ln.createRandomToken(8),this._configuration.via_host,null,{transport:"ws"}),this._contact={pub_gruu:null,temp_gruu:null,uri:this._configuration.contact_uri,toString(s={}){const n=s.anonymous||null,g=s.outbound||null;let _="<";return n?_+=this.temp_gruu||"sip:anonymous@anonymous.invalid;transport=ws":_+=this.pub_gruu||this.uri.toString(),g&&(n?!this.temp_gruu:!this.pub_gruu)&&(_+=";ob"),_+=">",_}};const u=["authorization_user","password","realm","ha1","authorization_jwt","display_name","register"];for(const s in this._configuration)Object.prototype.hasOwnProperty.call(this._configuration,s)&&(u.indexOf(s)!==-1?Object.defineProperty(this._configuration,s,{writable:!0,configurable:!1}):Object.defineProperty(this._configuration,s,{writable:!1,configurable:!1}));ds.debug("configuration parameters after validation:");for(const s in this._configuration)if(Object.prototype.hasOwnProperty.call(_o.settings,s))switch(s){case"uri":case"registrar_server":ds.debug(`- ${s}: ${this._configuration[s]}`);break;case"password":case"ha1":case"authorization_jwt":ds.debug(`- ${s}: NOT SHOWN`);break;default:ds.debug(`- ${s}: ${JSON.stringify(this._configuration[s])}`)}}newMSRPSession(t,r){t.on("msgHistoryUpdate",l=>{console.log(l)}),this._msrp_sessions[t.id]=t,this.emit("newMSRPSession",r)}newJanusSession(t,r){this._janus_sessions[t.id]=t,this.newStreamPlugins.forEach(l=>{l.setSession(t)}),this.processStreamPlugins.forEach(l=>{l.setSession(t)}),this.emit("newJanusSession",r)}kill(){}destroyMSRPSession(t){delete this._msrp_sessions[t.id]}destroyJanusSession(t){delete this._janus_sessions[t.id]}clearKeepAliveInterval(){clearInterval(this.optionsInterval),this.optionsInterval=null}receiveRequest(t){var s,n,g,_;const r=t.method;if(t.ruri.user!==this._configuration.uri.user&&t.ruri.user!==this._contact.uri.user){ds.debug("Request-URI does not point to us"),t.method!==Et.ACK&&t.reply_sl(404);return}if(t.ruri.scheme===Et.SIPS){t.reply_sl(416);return}if(Er.checkTransaction(this,t))return;if(r===Et.INVITE?new Er.InviteServerTransaction(this,this._transport,t):r!==Et.ACK&&r!==Et.CANCEL&&new Er.NonInviteServerTransaction(this,this._transport,t),r===Et.OPTIONS){if(this.lastOptionsTimestamp=Date.now(),this.optionsInterval||(this.emit("initKeepAliveInterval"),this.optionsInterval=setInterval(()=>{const C=Date.now(),R=this.lastOptionsTimestamp>C-35e3,D=this.lastRegisterTimestamp+this._configuration.register_expires*1e3>C;R&&D&&this.emit("keepAliveInterval")},35e3)),this.listeners("newOptions").length===0){t.reply(200);return}new g_.Options(this).init_incoming(t)}else if(r===Et.MESSAGE){if(this.listeners("newMessage").length===0){t.reply(405);return}new g_.Message(this).init_incoming(t)}else if(r===Et.INVITE&&!t.to_tag&&this.listeners("newRTCSession").length===0){t.reply(405);return}let l,u;if(t.to_tag)if(l=this._findDialog(t.call_id,t.from_tag,t.to_tag),l)l.receiveRequest(t);else if(r===Et.NOTIFY)if(u=this._findSession(t),u)u.receiveRequest(t);else{if(t.body)try{const v=JSON.parse(t.body)||{};(n=(s=v.plugindata)==null?void 0:s.data)!=null&&n.publishers&&Object.values(this._janus_sessions)[0].receivePublishers(v),(_=(g=v.plugindata)==null?void 0:g.data)!=null&&_.unpublished&&Object.values(this._janus_sessions)[0].receiveUnpublished(v.plugindata.data.unpublished)}catch(v){console.error(v)}t.reply(200)}else r!==Et.ACK&&t.reply(481);else switch(r){case Et.INVITE:if(window.RTCPeerConnection)if(t.hasHeader("replaces")){const v=t.replaces;l=this._findDialog(v.call_id,v.from_tag,v.to_tag),l?(u=l.owner,u.isEnded()?t.reply(603):u.receiveRequest(t)):t.reply(481)}else t.body.search(/MSRP/ig)>-1?(u=new Od(this),u.init_incoming(t)):t.body.search(/JANUS/ig)>-1||(u=new $E(this),u.init_incoming(t));else ds.warn("INVITE received but WebRTC is not supported"),t.reply(488);break;case Et.BYE:t.reply(481);break;case Et.CANCEL:u=this._findSession(t),u?u.receiveRequest(t):ds.debug("received CANCEL request for a non existent session");break;case Et.ACK:break;case Et.NOTIFY:this.emit("sipEvent",{event:t.event,request:t}),t.reply(200);break;default:t.reply(405);break}}startMSRP(t,r){ds.debug("startMSRP()",r);const l=new Od(this);return l.connect(t),l}startJanus(t,r){ds.debug("startJanus()",r);const l=new Od(this);return l.connect(t),l}terminateMSRPSessions(t){ds.debug("terminateSessions()");for(const r in this._msrp_sessions)this._msrp_sessions[r].isEnded()||this._msrp_sessions[r].terminate(t)}terminateJanusSessions(t){ds.debug("terminateSessions()");for(const r in this._janus_sessions)this._janus_sessions[r].isEnded()||this._janus_sessions[r].terminate(t)}enableJanusAudio(t){ds.debug("enableJanusAudio()");for(const r in this._janus_sessions)this._janus_sessions[r].isEnded()||(t?this._janus_sessions[r].startAudio():this._janus_sessions[r].stopAudio())}enableJanusVideo(t){ds.debug("enableJanusVideo()");for(const r in this._janus_sessions)this._janus_sessions[r].isEnded()||(t?this._janus_sessions[r].startVideo():this._janus_sessions[r].stopVideo())}terminateAllSessions(){for(const t in this._sessions)if(Object.prototype.hasOwnProperty.call(this._sessions,t)){ds.debug(`closing session ${t}`);try{this._sessions[t].terminate()}catch(r){console.error(r)}}}stop(t=!0){if(ds.debug("stop()"),this._dynConfiguration={},this._status===Ri.STATUS_USER_CLOSED){ds.debug("UA already closed");return}this._registrator.close();const r=Object.keys(this._sessions).length;t&&this.terminateAllSessions();for(const u in this._msrp_sessions)if(Object.prototype.hasOwnProperty.call(this._msrp_sessions,u)){ds.debug(`closing session ${u}`);try{this._msrp_sessions[u].terminate()}catch(s){console.error(s)}}for(const u in this._janus_sessions)if(Object.prototype.hasOwnProperty.call(this._janus_sessions,u)){ds.debug(`closing session ${u}`);try{this._janus_sessions[u].terminate()}catch(s){console.error(s)}}for(const u in this._applicants)if(Object.prototype.hasOwnProperty.call(this._applicants,u))try{this._applicants[u].close()}catch(s){console.error(s)}this._status=Ri.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 MC(f){this.emit("connecting",f)}function UC(f){this._status!==Ri.STATUS_USER_CLOSED&&(this._status=Ri.STATUS_READY,this._error=null,this.emit("connected",f),this._dynConfiguration.register&&this._registrator.register())}function PC(f){const t=["nict","ict","nist","ist"];for(const r of t)for(const l in this._transactions[r])Object.prototype.hasOwnProperty.call(this._transactions[r],l)&&this._transactions[r][l].onTransportError();this.emit("disconnected",f),this._registrator.onTransportClosed(),this._status!==Ri.STATUS_USER_CLOSED&&(this._status=Ri.STATUS_NOT_READY,this._error=Ri.NETWORK_ERROR)}function LC(f){const t=f.transport;let r=f.message;const l=r;if(r=OC.parseMessage(r,this),this.onTransportCallback&&typeof this.onTransportCallback=="function"&&this.onTransportCallback(r,l),!!r&&!(this._status===Ri.STATUS_USER_CLOSED&&r instanceof fl.IncomingRequest)&&aC(r,this,t)){if(r instanceof fl.IncomingRequest)r.transport=t,this.receiveRequest(r);else if(r instanceof fl.IncomingResponse){let u;switch(r.method){case Et.INVITE:u=this._transactions.ict[r.via_branch],u&&u.receiveResponse(r);break;case Et.ACK:break;default:u=this._transactions.nict[r.via_branch],u&&u.receiveResponse(r);break}}}}const HC=["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"],FC=["_cancel_reason","_contact","direction","_end_time","_eventsCount","_from_tag","_id","_is_canceled","_is_confirmed","_late_sdp","status","start_time","_remote_identity","target_addr"];function fp(f){const t={};return HC.forEach(r=>{f[r]!==void 0&&(t[r]=f[r])}),t.localHold=f._localHold,t}function hp(f){const t={};return FC.forEach(r=>{f[r]!==void 0&&(t[r]=f[r])}),t}async function kd(f,t,r){const l=f.createMediaStreamSource(t),u=f.createMediaStreamDestination(),s=f.createGain();return l.connect(s),s.connect(u),s.gain.value=r,u.stream}function BC(f,t,r,l){if(_p())return;const u=document.createElement("audio");u.id=t._id,u.className="audioTag",u.srcObject=f,u.setSinkId(r),u.volume=l,u.play(),t.audioTag=u}function zC(f){if(f&&typeof f.log=="function"&&typeof f.warn=="function"&&typeof f.error=="function")return!0}function _p(){return/Mobi|react-native|Android|iPhone/i.test(navigator.userAgent)}const VC=gs,qC=Dr(),Ks=new VC("WebSocketInterface");var jC=class{constructor(t){Ks.debug('new() [url:"%s"]',t),this._url=t,this._sip_uri=null,this._via_transport=null,this._ws=null;const r=qC.parse(t,"absoluteURI");if(r===-1)throw Ks.warn(`invalid WebSocket URI: ${t}`),new TypeError(`Invalid argument: ${t}`);if(r.scheme!=="wss"&&r.scheme!=="ws")throw Ks.warn(`invalid WebSocket URI scheme: ${r.scheme}`),new TypeError(`Invalid argument: ${t}`);this._sip_uri=`sip:${r.host}${r.port?`:${r.port}`:""};transport=ws`,this._via_transport=r.scheme.toUpperCase()}get via_transport(){return this._via_transport}set via_transport(t){this._via_transport=t.toUpperCase()}get sip_uri(){return this._sip_uri}get url(){return this._url}connect(){if(Ks.debug("connect()"),this.isConnected()){Ks.debug(`WebSocket ${this._url} is already connected`);return}else if(this.isConnecting()){Ks.debug(`WebSocket ${this._url} is connecting`);return}this._ws&&this.disconnect(),Ks.debug(`connecting to WebSocket ${this._url}`);try{this._ws=new WebSocket(this._url,"sip"),this._ws.binaryType="arraybuffer",this._ws.onopen=this._onOpen.bind(this),this._ws.onclose=this._onClose.bind(this),this._ws.onmessage=this._onMessage.bind(this),this._ws.onerror=this._onError.bind(this)}catch(t){this._onError(t)}}disconnect(){Ks.debug("disconnect()"),this._ws&&(this._ws.onopen=()=>{},this._ws.onclose=()=>{},this._ws.onmessage=()=>{},this._ws.onerror=()=>{},this._ws.close(),this._ws=null)}send(t){return Ks.debug("send()"),this.isConnected()?(this._ws.send(t),!0):(Ks.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(){Ks.debug(`WebSocket ${this._url} connected`),this.onconnect()}_onClose({wasClean:t,code:r,reason:l}){Ks.debug(`WebSocket ${this._url} closed`),t===!1&&Ks.debug("WebSocket abrupt disconnection"),this.ondisconnect(!t,r,l)}_onMessage({data:t}){Ks.debug("received WebSocket message"),this.ondata(t)}_onError(t){Ks.warn(`WebSocket ${this._url} error: `,t)}};const Nd=Uo,GC=Et,WC=Pn,KC=xs(),YC=up,JC=Nn(),QC=Zc(),XC=Dr(),ZC=jC;al("JsSIP")("version %s",Nd.version);var eA={C:GC,Exceptions:WC,Utils:KC,UA:YC,URI:JC,NameAddrHeader:QC,WebSocketInterface:ZC,Grammar:XC,debug:al,get name(){return Nd.title},get version(){return Nd.version}};const tA=Ht(eA);function Md(f){return f<10?`0${f}`:`${f}`}function sA(f){let t=f.hours||0,r=f.minutes||0,l=f.seconds||0;l++,l===60&&(l=0,r++,r===60&&(r=0,t++));const u=`${Md(t)}:${Md(r)}:${Md(l)}`;return{seconds:l,minutes:r,hours:t,formatted:u}}function rA(f){let t=0;for(let r=0;r<f.length;r++)t+=f[r]*f[r];return Math.sqrt(t/f.length)}async function nA(f,t,r=150){const l=t.createMediaStreamSource(f),u=t.createDelay();u.delayTime.value=r/1e3;const s=t.createGain();s.gain.value=0;const n=t.createMediaStreamDestination();return l.connect(u).connect(s).connect(n),{stream:n.stream,setSpeaking:g=>{s.gain.value=g?1:0}}}var Us={};Us.forEach=async(f,t,r)=>{const l=[];for(let u=0;u<f.length;u++)if(u in f){const s=Promise.resolve(f[u]).then(n=>t.call(r||globalThis,n,u,f));l.push(s)}await Promise.all(l)},Us.forEachSeries=async(f,t,r)=>{for(let l=0;l<f.length;l++)l in f&&await t.call(r||globalThis,await f[l],l,f)},Us.map=async(f,t,r)=>{const l=[];for(let u=0;u<f.length;u++)u in f&&(l[u]=Promise.resolve(f[u]).then(s=>t.call(r||globalThis,s,u,f)));return Promise.all(l)},Us.mapSeries=async(f,t,r)=>{const l=[];for(let u=0;u<f.length;u++)u in f&&(l[u]=await t.call(r||globalThis,await f[u],u,f));return l},Us.find=(f,t,r)=>new Promise((l,u)=>{if(f.length===0)return l();let s=1;for(let n=0;n<f.length;n++){const g=_=>{_?l(f[n]):s===f.length&&l(),s++};Promise.resolve(f[n]).then(_=>t.call(r||globalThis,_,n,f)).then(g).catch(u)}}),Us.findSeries=async(f,t,r)=>{for(let l=0;l<f.length;l++)if(await t.call(r||globalThis,await f[l],l,f))return f[l]},Us.findIndex=(f,t,r)=>new Promise((l,u)=>{if(f.length===0)return l(-1);let s=1;for(let n=0;n<f.length;n++){const g=_=>{_?l(n):s===f.length&&l(-1),s++};Promise.resolve(f[n]).then(_=>t.call(r||globalThis,_,n,f)).then(g).catch(u)}}),Us.findIndexSeries=async(f,t,r)=>{for(let l=0;l<f.length;l++)if(await t.call(r||globalThis,await f[l],l,f))return l},Us.some=(f,t,r)=>new Promise((l,u)=>{if(f.length===0)return l(!1);let s=1;for(let n=0;n<f.length;n++){if(!(n in f)){s++;continue}const g=_=>{_?l(!0):s===f.length&&l(!1),s++};Promise.resolve(f[n]).then(_=>t.call(r||globalThis,_,n,f)).then(g).catch(u)}}),Us.someSeries=async(f,t,r)=>{for(let l=0;l<f.length;l++)if(l in f&&await t.call(r||globalThis,await f[l],l,f))return!0;return!1},Us.every=(f,t,r)=>new Promise((l,u)=>{if(f.length===0)return l(!0);let s=1;for(let n=0;n<f.length;n++){if(!(n in f)){s++;continue}const g=_=>{_?s===f.length&&l(!0):l(!1),s++};Promise.resolve(f[n]).then(_=>t.call(r||globalThis,_,n,f)).then(g).catch(u)}}),Us.everySeries=async(f,t,r)=>{for(let l=0;l<f.length;l++)if(l in f&&!await t.call(r||globalThis,await f[l],l,f))return!1;return!0},Us.filter=(f,t,r)=>new Promise(async(l,u)=>{const s=[];for(let g=0;g<f.length;g++)g in f&&(s[g]=Promise.resolve(f[g]).then(_=>t.call(r||globalThis,_,g,f)).catch(u));const n=[];for(let g=0;g<s.length;g++)await s[g]&&n.push(await f[g]);l(n)}),Us.filterSeries=async(f,t,r)=>{const l=[];for(let u=0;u<f.length;u++)u in f&&await t.call(r||globalThis,await f[u],u,f)&&l.push(await f[u]);return l},Us.reduce=async(f,t,r)=>{if(f.length===0&&r===void 0)throw TypeError("Reduce of empty array with no initial value");let l,u;for(r!==void 0?(u=r,l=0):(u=f[0],l=1),l;l<f.length;l++)l in f&&(u=await t(await u,await f[l],l,f));return u};var pp={};(function(f){const t=Us;Object.keys(t).forEach(r=>{const l=r.charAt(0).toUpperCase()+r.slice(1);f[`async${l}`]=async function(...u){return t[r](this,...u)}})})(pp);var iA=Object.assign(Us,{instanceMethods:pp}),mp={},mo={};Object.defineProperty(mo,"__esModule",{value:!0}),mo.baseAssetPath=void 0;const gp=typeof window<"u"&&typeof window.document<"u"?window.document.currentScript:null;let vp="/";gp&&(vp=gp.src.replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/")),mo.baseAssetPath=vp;var gl={};Object.defineProperty(gl,"__esModule",{value:!0}),gl.defaultModelFetcher=void 0;const aA=f=>fetch(f).then(t=>t.arrayBuffer());gl.defaultModelFetcher=aA;var hn={},vl={};(function(f){Object.defineProperty(f,"__esModule",{value:!0}),f.log=f.LOG_PREFIX=void 0,f.LOG_PREFIX="[VAD]";const t=["error","debug","warn"];function r(u){return(...s)=>{console[u](f.LOG_PREFIX,...s)}}const l=t.reduce((u,s)=>(u[s]=r(s),u),{});f.log=l})(vl);var Ra={};Object.defineProperty(Ra,"__esModule",{value:!0}),Ra.Message=void 0;var yp;(function(f){f.AudioFrame="AUDIO_FRAME",f.SpeechStart="SPEECH_START",f.VADMisfire="VAD_MISFIRE",f.SpeechEnd="SPEECH_END",f.SpeechStop="SPEECH_STOP",f.SpeechRealStart="SPEECH_REAL_START",f.FrameProcessed="FRAME_PROCESSED"})(yp||(Ra.Message=yp={})),Object.defineProperty(hn,"__esModule",{value:!0}),hn.FrameProcessor=hn.validateOptions=hn.defaultFrameProcessorOptions=void 0;const go=vl,$a=Ra;hn.defaultFrameProcessorOptions={positiveSpeechThreshold:.3,negativeSpeechThreshold:.25,preSpeechPadMs:800,redemptionMs:1400,minSpeechMs:400,submitUserSpeechOnPause:!1};function lA(f){(f.positiveSpeechThreshold<0||f.positiveSpeechThreshold>1)&&go.log.error("positiveSpeechThreshold should be a number between 0 and 1"),(f.negativeSpeechThreshold<0||f.negativeSpeechThreshold>f.positiveSpeechThreshold)&&go.log.error("negativeSpeechThreshold should be between 0 and positiveSpeechThreshold"),f.preSpeechPadMs<0&&go.log.error("preSpeechPadMs should be positive"),f.redemptionMs<0&&go.log.error("redemptionMs should be positive"),f.minSpeechMs<0&&go.log.error("minSpeechMs should be positive")}hn.validateOptions=lA;const Tp=f=>{const t=f.reduce((l,u)=>(l.push(l.at(-1)+u.length),l),[0]),r=new Float32Array(t.at(-1));return f.forEach((l,u)=>{const s=t[u];r.set(l,s)}),r};class oA{constructor(t,r,l,u){this.modelProcessFunc=t,this.modelResetFunc=r,this.options=l,this.msPerFrame=u,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=s=>{this.active=!1,this.options.submitUserSpeechOnPause?this.endSegment(s):this.reset()},this.resume=()=>{this.active=!0},this.endSegment=s=>{const n=this.audioBuffer;this.audioBuffer=[];const g=this.speaking;if(this.reset(),g)if(n.reduce((v,C)=>C.isSpeech?v+1:v,0)>=this.minSpeechFrames){const v=Tp(n.map(C=>C.frame));s({msg:$a.Message.SpeechEnd,audio:v})}else s({msg:$a.Message.VADMisfire});return{}},this.process=async(s,n)=>{if(!this.active)return;const g=await this.modelProcessFunc(s),_=g.isSpeech>=this.options.positiveSpeechThreshold;if(n({probs:g,msg:$a.Message.FrameProcessed,frame:s}),this.audioBuffer.push({frame:s,isSpeech:_}),_&&(this.speechFrameCount++,this.redemptionCounter=0),_&&!this.speaking&&(this.speaking=!0,n({msg:$a.Message.SpeechStart})),this.speaking&&this.speechFrameCount===this.minSpeechFrames&&!this.speechRealStartFired&&(this.speechRealStartFired=!0,n({msg:$a.Message.SpeechRealStart})),g.isSpeech<this.options.negativeSpeechThreshold&&this.speaking&&++this.redemptionCounter>=this.redemptionFrames){this.redemptionCounter=0,this.speechFrameCount=0,this.speaking=!1,this.speechRealStartFired=!1;const v=this.audioBuffer;if(this.audioBuffer=[],v.reduce((R,D)=>D.isSpeech?R+1:R,0)>=this.minSpeechFrames){const R=Tp(v.map(D=>D.frame));n({msg:$a.Message.SpeechEnd,audio:R})}else n({msg:$a.Message.VADMisfire})}if(!this.speaking){for(;this.audioBuffer.length>this.preSpeechPadFrames;)this.audioBuffer.shift();this.speechFrameCount=0}},this.audioBuffer=[],this.redemptionFrames=Math.floor(l.redemptionMs/this.msPerFrame),this.preSpeechPadFrames=Math.floor(l.preSpeechPadMs/this.msPerFrame),this.minSpeechFrames=Math.floor(l.minSpeechMs/this.msPerFrame),this.reset()}}hn.FrameProcessor=oA;var Sp={};function yl(f){throw new Error('Could not dynamically require "'+f+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var bp={exports:{}};/*!
158
+ `,r),u===-1)return u;!f.substring(u+2,u+4).match(/(^\r\n)/)&&f.charAt(u+2).match(/(^\s+)/)?r=u+2:l=u}return l}function xC(f,t,r,l){let u;const s=t.indexOf(":",r),n=t.substring(r,s).trim(),g=t.substring(s+1,l).trim();switch(n.toLowerCase()){case"via":case"v":f.addHeader("via",g),f.getHeaders("via").length===1?(u=f.parseHeader("Via"),u&&(f.via=u,f.via_branch=u.branch)):u=0;break;case"from":case"f":f.setHeader("from",g),u=f.parseHeader("from"),u&&(f.from=u,f.from_tag=u.getParam("tag"));break;case"to":case"t":f.setHeader("to",g),u=f.parseHeader("to"),u&&(f.to=u,f.to_tag=u.getParam("tag"));break;case"record-route":if(u=Dd.parse(g,"Record_Route"),u===-1)u=void 0;else for(const _ of u)f.addHeader("record-route",g.substring(_.possition,_.offset)),f.headers["Record-Route"][f.getHeaders("record-route").length-1].parsed=_.parsed;break;case"call-id":case"i":f.setHeader("call-id",g),u=f.parseHeader("call-id"),u&&(f.call_id=g);break;case"contact":case"m":if(u=Dd.parse(g,"Contact"),u===-1)u=void 0;else for(const _ of u)f.addHeader("contact",g.substring(_.possition,_.offset)),f.headers.Contact[f.getHeaders("contact").length-1].parsed=_.parsed;break;case"content-length":case"l":f.setHeader("content-length",g),u=f.parseHeader("content-length");break;case"content-type":case"c":f.setHeader("content-type",g),u=f.parseHeader("content-type");break;case"cseq":f.setHeader("cseq",g),u=f.parseHeader("cseq"),u&&(f.cseq=u.value),f instanceof fl.IncomingResponse&&(f.method=u.method);break;case"max-forwards":f.setHeader("max-forwards",g),u=f.parseHeader("max-forwards");break;case"www-authenticate":f.setHeader("www-authenticate",g),u=f.parseHeader("www-authenticate");break;case"proxy-authenticate":f.setHeader("proxy-authenticate",g),u=f.parseHeader("proxy-authenticate");break;case"session-expires":case"x":f.setHeader("session-expires",g),u=f.parseHeader("session-expires"),u&&(f.session_expires=u.expires,f.session_expires_refresher=u.refresher);break;case"refer-to":case"r":f.setHeader("refer-to",g),u=f.parseHeader("refer-to"),u&&(f.refer_to=u);break;case"replaces":f.setHeader("replaces",g),u=f.parseHeader("replaces"),u&&(f.replaces=u);break;case"event":case"o":f.setHeader("event",g),u=f.parseHeader("event"),u&&(f.event=u);break;default:f.addHeader(n,g),u=0}return u===void 0?{error:`error parsing header "${n}"`}:!0}const OC={parseMessage:RC},po=new Su("Registrator"),Fu=10;class DC{constructor(t,r){this._reg_id=1,this._ua=t,this._transport=r,this._registrar=t.configuration.registrar_server,this._expires=t.configuration.register_expires,this._call_id=Ln.createRandomToken(22),this._cseq=0,this._to_uri=t.configuration.uri,this._registrationTimer=null,this._registering=!1,this._registered=!1,this._contact=this._ua.contact.toString();const l=this._contact.indexOf(">");if(l!==-1){const u=this._contact.slice(0,l)+this._contact.slice(l+1,this._contact.length);this._contact=u}this._extra_contact="",this._extraContactParams="",this._extra_contact+=";+sip.ice",this._extraHeaders=[],this._sipInstance=`"<urn:uuid:${this._ua.configuration.instance_id}>"`,this._extra_contact+=`;reg-id=${this._reg_id}`,this._extra_contact+=`;+sip.instance=${this._sipInstance}`}get registered(){return this._registered}setExtraHeaders(t){Array.isArray(t)||(t=[]),this._extraHeaders=t.slice()}setExtraContactParams(t){t instanceof Object||(t={}),this._extraContactParams="";for(const r in t)if(Object.prototype.hasOwnProperty.call(t,r)){const l=t[r];this._extraContactParams+=`;${r}`,l&&(this._extraContactParams+=`=${l}`)}}setExtraContactUriParams(t){t instanceof Object||(t={}),this._extraContactParams="";for(const r in t)if(Object.prototype.hasOwnProperty.call(t,r)){const l=t[r];this._extraContactParams+=`;${r}`,l&&(this._extraContactParams+=`=${l}`)}}register(){if(this._registering){po.debug("Register request in progress...");return}const t=this._extraHeaders.slice();t.push(`Contact: ${this._contact}${this._extraContactParams}>${this._extra_contact};expires=${this._expires}`),t.push(`Expires: ${this._expires}`);const r=new Ds.OutgoingRequest(fe.REGISTER,this._registrar,this._ua,{to_uri:this._to_uri,call_id:this._call_id,cseq:this._cseq+=1},t),l=new no(this._ua,r,{onRequestTimeout:()=>{this._registrationFailure(null,fe.causes.REQUEST_TIMEOUT)},onTransportError:()=>{this._registrationFailure(null,fe.causes.CONNECTION_ERROR)},onAuthenticated:()=>{this._cseq+=1},onReceiveResponse:u=>{if(u.cseq===this._cseq)switch(this._registrationTimer!==null&&(clearTimeout(this._registrationTimer),this._registrationTimer=null),!0){case/^1[0-9]{2}$/.test(u.status_code):break;case/^2[0-9]{2}$/.test(u.status_code):{if(this._registering=!1,!u.hasHeader("Contact")){po.debug("no Contact header in response to REGISTER, response ignored");break}const s=u.headers.Contact.reduce((v,C)=>v.concat(C.parsed),[]);let n=s.find(v=>this._sipInstance===v.getParam("+sip.instance")&&this._reg_id===parseInt(v.getParam("reg-id")));if(n||(n=s.find(v=>v.uri.user===this._ua.contact.uri.user)),!n){po.debug("no Contact header pointing to us, response ignored");break}this._ua.clearKeepAliveInterval(),this._ua.setLastRegisterTimestamp();let g=n.getParam("expires");!g&&u.hasHeader("expires")&&(g=u.getHeader("expires")),g||(g=this._expires),g=Number(g),g<Fu&&(g=Fu);const _=g>64?g*1e3/2+Math.floor((g/2-32)*1e3*Math.random()):g*1e3-5e3;this._registrationTimer=setTimeout(()=>{this._registrationTimer=null,this._ua.listeners("registrationExpiring").length===0?this.register():this._ua.emit("registrationExpiring")},_),n.hasParam("temp-gruu")&&(this._ua.contact.temp_gruu=n.getParam("temp-gruu").replace(/"/g,"")),n.hasParam("pub-gruu")&&(this._ua.contact.pub_gruu=n.getParam("pub-gruu").replace(/"/g,"")),this._registered||(this._registered=!0,this._ua.registered({response:u}));break}case/^423$/.test(u.status_code):{u.hasHeader("min-expires")?(this._expires=Number(u.getHeader("min-expires")),this._expires<Fu&&(this._expires=Fu),this.register()):(po.debug("423 response received for REGISTER without Min-Expires"),this._registrationFailure(u,fe.causes.SIP_FAILURE_CODE));break}default:{const s=Ln.sipErrorCause(u.status_code);this._registrationFailure(u,s)}}}});this._registering=!0,l.send()}unregister(t={}){if(!this._registered){po.debug("already unregistered");return}this._registered=!1,this._registrationTimer!==null&&(clearTimeout(this._registrationTimer),this._registrationTimer=null);const r=this._extraHeaders.slice();t.all?r.push(`Contact: *${this._extraContactParams}`):r.push(`Contact: ${this._contact}${this._extraContactParams}>${this._extra_contact};expires=0`),r.push("Expires: 0");const l=new Ds.OutgoingRequest(fe.REGISTER,this._registrar,this._ua,{to_uri:this._to_uri,call_id:this._call_id,cseq:this._cseq+=1},r);new no(this._ua,l,{onRequestTimeout:()=>{this._unregistered(null,fe.causes.REQUEST_TIMEOUT)},onTransportError:()=>{this._unregistered(null,fe.causes.CONNECTION_ERROR)},onAuthenticated:()=>{this._cseq+=1},onReceiveResponse:s=>{switch(!0){case/^1[0-9]{2}$/.test(s.status_code):break;case/^2[0-9]{2}$/.test(s.status_code):this._unregistered(s);break;default:{const n=Ln.sipErrorCause(s.status_code);this._unregistered(s,n)}}}}).send()}close(){this._registered&&this.unregister()}onTransportClosed(){this._registering=!1,this._registrationTimer!==null&&(clearTimeout(this._registrationTimer),this._registrationTimer=null),this._registered&&(this._registered=!1,this._ua.unregistered({}))}_registrationFailure(t,r){this._registering=!1,this._ua.registrationFailed({response:t||null,cause:r}),this._registered&&(this._registered=!1,this._ua.unregistered({response:t||null,cause:r}))}_unregistered(t,r){this._registering=!1,this._registered=!1,this._ua.unregistered({response:t||null,cause:r||null})}}const ds=console,Ri={STATUS_INIT:0,STATUS_READY:1,STATUS_USER_CLOSED:2,STATUS_NOT_READY:3,CONFIGURATION_ERROR:1,NETWORK_ERROR:2},kC=yC;class NC extends kC{constructor(t){super(t),this._msrp_sessions=[],this._transactions={nist:{},nict:{},ist:{},ict:{}},this._janus_sessions=[],this.newStreamPlugins=[],this.processStreamPlugins=[],this.optionsInterval=null,this.lastOptionsTimestamp=null,this.lastRegisterTimestamp=null,this._registrator=new DC(this)}setLastRegisterTimestamp(){this.lastRegisterTimestamp=Date.now()}call(t,r){return super.call(t,r)}joinVideoCall(t,r,l){ds.debug("call()");const u=new Lu(this);return u.configureMedia({audio:!0,video:!0}),u.connect(t,r,l),u}startScreenShare(){ds.debug("startScreenShare()");for(const t in this._janus_sessions)this._janus_sessions[t].connectScreenShare()}changeMediaConstraints(t){for(const r in this._janus_sessions)this._janus_sessions[r].changeMediaConstraints(t)}startBlur(){for(const t in this._janus_sessions)this._janus_sessions[t].connectBlur()}stopBlur(){for(const t in this._janus_sessions)this._janus_sessions[t].stopBlur()}_loadConfig(t){try{_o.load(this._configuration,t)}catch(s){throw s}this._configuration.display_name===0&&(this._configuration.display_name="0"),this._configuration.instance_id||(this._configuration.instance_id=Ln.newUUID());let r;typeof window<"u"&&typeof window.document<"u"?r=window==null?void 0:window.navigator.userAgent:typeof self<"u"&&self.navigator&&(r=self.navigator.userAgent),r+=" "+Et.USER_AGENT,this._configuration.user_agent=t.overrideUserAgent&&typeof t.overrideUserAgent=="function"?t.overrideUserAgent(r):r,t.onTransportCallback&&typeof t.onTransportCallback=="function"&&(this.onTransportCallback=t.onTransportCallback),this._configuration.jssip_id=Ln.createRandomToken(5);const l=this._configuration.uri.clone();l.user=null,this._configuration.hostport_params=l.toString().replace(/^sip:/i,"");try{this._transport=new jE(this._configuration.sockets,{max_interval:this._configuration.connection_recovery_max_interval,min_interval:this._configuration.connection_recovery_min_interval}),this._transport.onconnecting=MC.bind(this),this._transport.onconnect=UC.bind(this),this._transport.ondisconnect=PC.bind(this),this._transport.ondata=LC.bind(this)}catch(s){throw ds.warn(s),new Ei.ConfigurationError("sockets",this._configuration.sockets)}if(delete this._configuration.sockets,this._configuration.authorization_user||(this._configuration.authorization_user=this._configuration.uri.user),!this._configuration.registrar_server){const s=this._configuration.uri.clone();s.user=null,s.clearParams(),s.clearHeaders(),this._configuration.registrar_server=s}this._configuration.no_answer_timeout*=1e3,this._configuration.contact_uri?this._configuration.via_host=this._configuration.contact_uri.host:this._configuration.contact_uri=new Ia("sip",Ln.createRandomToken(8),this._configuration.via_host,null,{transport:"ws"}),this._contact={pub_gruu:null,temp_gruu:null,uri:this._configuration.contact_uri,toString(s={}){const n=s.anonymous||null,g=s.outbound||null;let _="<";return n?_+=this.temp_gruu||"sip:anonymous@anonymous.invalid;transport=ws":_+=this.pub_gruu||this.uri.toString(),g&&(n?!this.temp_gruu:!this.pub_gruu)&&(_+=";ob"),_+=">",_}};const u=["authorization_user","password","realm","ha1","authorization_jwt","display_name","register"];for(const s in this._configuration)Object.prototype.hasOwnProperty.call(this._configuration,s)&&(u.indexOf(s)!==-1?Object.defineProperty(this._configuration,s,{writable:!0,configurable:!1}):Object.defineProperty(this._configuration,s,{writable:!1,configurable:!1}));ds.debug("configuration parameters after validation:");for(const s in this._configuration)if(Object.prototype.hasOwnProperty.call(_o.settings,s))switch(s){case"uri":case"registrar_server":ds.debug(`- ${s}: ${this._configuration[s]}`);break;case"password":case"ha1":case"authorization_jwt":ds.debug(`- ${s}: NOT SHOWN`);break;default:ds.debug(`- ${s}: ${JSON.stringify(this._configuration[s])}`)}}newMSRPSession(t,r){t.on("msgHistoryUpdate",l=>{console.log(l)}),this._msrp_sessions[t.id]=t,this.emit("newMSRPSession",r)}newJanusSession(t,r){this._janus_sessions[t.id]=t,this.newStreamPlugins.forEach(l=>{l.setSession(t)}),this.processStreamPlugins.forEach(l=>{l.setSession(t)}),this.emit("newJanusSession",r)}kill(){}destroyMSRPSession(t){delete this._msrp_sessions[t.id]}destroyJanusSession(t){delete this._janus_sessions[t.id]}clearKeepAliveInterval(){clearInterval(this.optionsInterval),this.optionsInterval=null}receiveRequest(t){var s,n,g,_;const r=t.method;if(t.ruri.user!==this._configuration.uri.user&&t.ruri.user!==this._contact.uri.user){ds.debug("Request-URI does not point to us"),t.method!==Et.ACK&&t.reply_sl(404);return}if(t.ruri.scheme===Et.SIPS){t.reply_sl(416);return}if(Er.checkTransaction(this,t))return;if(r===Et.INVITE?new Er.InviteServerTransaction(this,this._transport,t):r!==Et.ACK&&r!==Et.CANCEL&&new Er.NonInviteServerTransaction(this,this._transport,t),r===Et.OPTIONS){if(this.lastOptionsTimestamp=Date.now(),this.optionsInterval||(this.emit("initKeepAliveInterval"),this.optionsInterval=setInterval(()=>{const C=Date.now(),R=this.lastOptionsTimestamp>C-35e3,D=this.lastRegisterTimestamp+this._configuration.register_expires*1e3>C;R&&D&&this.emit("keepAliveInterval")},35e3)),this.listeners("newOptions").length===0){t.reply(200);return}new m_.Options(this).init_incoming(t)}else if(r===Et.MESSAGE){if(this.listeners("newMessage").length===0){t.reply(405);return}new m_.Message(this).init_incoming(t)}else if(r===Et.INVITE&&!t.to_tag&&this.listeners("newRTCSession").length===0){t.reply(405);return}let l,u;if(t.to_tag)if(l=this._findDialog(t.call_id,t.from_tag,t.to_tag),l)l.receiveRequest(t);else if(r===Et.NOTIFY)if(u=this._findSession(t),u)u.receiveRequest(t);else{if(t.body)try{const v=JSON.parse(t.body)||{};(n=(s=v.plugindata)==null?void 0:s.data)!=null&&n.publishers&&Object.values(this._janus_sessions)[0].receivePublishers(v),(_=(g=v.plugindata)==null?void 0:g.data)!=null&&_.unpublished&&Object.values(this._janus_sessions)[0].receiveUnpublished(v.plugindata.data.unpublished)}catch(v){console.error(v)}t.reply(200)}else r!==Et.ACK&&t.reply(481);else switch(r){case Et.INVITE:if(window.RTCPeerConnection)if(t.hasHeader("replaces")){const v=t.replaces;l=this._findDialog(v.call_id,v.from_tag,v.to_tag),l?(u=l.owner,u.isEnded()?t.reply(603):u.receiveRequest(t)):t.reply(481)}else t.body.search(/MSRP/ig)>-1?(u=new Od(this),u.init_incoming(t)):t.body.search(/JANUS/ig)>-1||(u=new $E(this),u.init_incoming(t));else ds.warn("INVITE received but WebRTC is not supported"),t.reply(488);break;case Et.BYE:t.reply(481);break;case Et.CANCEL:u=this._findSession(t),u?u.receiveRequest(t):ds.debug("received CANCEL request for a non existent session");break;case Et.ACK:break;case Et.NOTIFY:this.emit("sipEvent",{event:t.event,request:t}),t.reply(200);break;default:t.reply(405);break}}startMSRP(t,r){ds.debug("startMSRP()",r);const l=new Od(this);return l.connect(t),l}startJanus(t,r){ds.debug("startJanus()",r);const l=new Od(this);return l.connect(t),l}terminateMSRPSessions(t){ds.debug("terminateSessions()");for(const r in this._msrp_sessions)this._msrp_sessions[r].isEnded()||this._msrp_sessions[r].terminate(t)}terminateJanusSessions(t){ds.debug("terminateSessions()");for(const r in this._janus_sessions)this._janus_sessions[r].isEnded()||this._janus_sessions[r].terminate(t)}enableJanusAudio(t){ds.debug("enableJanusAudio()");for(const r in this._janus_sessions)this._janus_sessions[r].isEnded()||(t?this._janus_sessions[r].startAudio():this._janus_sessions[r].stopAudio())}enableJanusVideo(t){ds.debug("enableJanusVideo()");for(const r in this._janus_sessions)this._janus_sessions[r].isEnded()||(t?this._janus_sessions[r].startVideo():this._janus_sessions[r].stopVideo())}terminateAllSessions(){for(const t in this._sessions)if(Object.prototype.hasOwnProperty.call(this._sessions,t)){ds.debug(`closing session ${t}`);try{this._sessions[t].terminate()}catch(r){console.error(r)}}}stop(t=!0){if(ds.debug("stop()"),this._dynConfiguration={},this._status===Ri.STATUS_USER_CLOSED){ds.debug("UA already closed");return}this._registrator.close();const r=Object.keys(this._sessions).length;t&&this.terminateAllSessions();for(const u in this._msrp_sessions)if(Object.prototype.hasOwnProperty.call(this._msrp_sessions,u)){ds.debug(`closing session ${u}`);try{this._msrp_sessions[u].terminate()}catch(s){console.error(s)}}for(const u in this._janus_sessions)if(Object.prototype.hasOwnProperty.call(this._janus_sessions,u)){ds.debug(`closing session ${u}`);try{this._janus_sessions[u].terminate()}catch(s){console.error(s)}}for(const u in this._applicants)if(Object.prototype.hasOwnProperty.call(this._applicants,u))try{this._applicants[u].close()}catch(s){console.error(s)}this._status=Ri.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 MC(f){this.emit("connecting",f)}function UC(f){this._status!==Ri.STATUS_USER_CLOSED&&(this._status=Ri.STATUS_READY,this._error=null,this.emit("connected",f),this._dynConfiguration.register&&this._registrator.register())}function PC(f){const t=["nict","ict","nist","ist"];for(const r of t)for(const l in this._transactions[r])Object.prototype.hasOwnProperty.call(this._transactions[r],l)&&this._transactions[r][l].onTransportError();this.emit("disconnected",f),this._registrator.onTransportClosed(),this._status!==Ri.STATUS_USER_CLOSED&&(this._status=Ri.STATUS_NOT_READY,this._error=Ri.NETWORK_ERROR)}function LC(f){const t=f.transport;let r=f.message;const l=r;if(r=OC.parseMessage(r,this),this.onTransportCallback&&typeof this.onTransportCallback=="function"&&this.onTransportCallback(r,l),!!r&&!(this._status===Ri.STATUS_USER_CLOSED&&r instanceof fl.IncomingRequest)&&aC(r,this,t)){if(r instanceof fl.IncomingRequest)r.transport=t,this.receiveRequest(r);else if(r instanceof fl.IncomingResponse){let u;switch(r.method){case Et.INVITE:u=this._transactions.ict[r.via_branch],u&&u.receiveResponse(r);break;case Et.ACK:break;default:u=this._transactions.nict[r.via_branch],u&&u.receiveResponse(r);break}}}}const HC=["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"],FC=["_cancel_reason","_contact","direction","_end_time","_eventsCount","_from_tag","_id","_is_canceled","_is_confirmed","_late_sdp","status","start_time","_remote_identity","target_addr"];function dp(f){const t={};return HC.forEach(r=>{f[r]!==void 0&&(t[r]=f[r])}),t.localHold=f._localHold,t}function fp(f){const t={};return FC.forEach(r=>{f[r]!==void 0&&(t[r]=f[r])}),t}async function kd(f,t,r){const l=f.createMediaStreamSource(t),u=f.createMediaStreamDestination(),s=f.createGain();return l.connect(s),s.connect(u),s.gain.value=r,u.stream}function BC(f,t,r,l){if(hp())return;const u=document.createElement("audio");u.id=t._id,u.className="audioTag",u.srcObject=f,u.setSinkId(r),u.volume=l,u.play(),t.audioTag=u}function zC(f){if(f&&typeof f.log=="function"&&typeof f.warn=="function"&&typeof f.error=="function")return!0}function hp(){return/Mobi|react-native|Android|iPhone/i.test(navigator.userAgent)}const VC=gs,qC=Dr(),Ks=new VC("WebSocketInterface");var jC=class{constructor(t){Ks.debug('new() [url:"%s"]',t),this._url=t,this._sip_uri=null,this._via_transport=null,this._ws=null;const r=qC.parse(t,"absoluteURI");if(r===-1)throw Ks.warn(`invalid WebSocket URI: ${t}`),new TypeError(`Invalid argument: ${t}`);if(r.scheme!=="wss"&&r.scheme!=="ws")throw Ks.warn(`invalid WebSocket URI scheme: ${r.scheme}`),new TypeError(`Invalid argument: ${t}`);this._sip_uri=`sip:${r.host}${r.port?`:${r.port}`:""};transport=ws`,this._via_transport=r.scheme.toUpperCase()}get via_transport(){return this._via_transport}set via_transport(t){this._via_transport=t.toUpperCase()}get sip_uri(){return this._sip_uri}get url(){return this._url}connect(){if(Ks.debug("connect()"),this.isConnected()){Ks.debug(`WebSocket ${this._url} is already connected`);return}else if(this.isConnecting()){Ks.debug(`WebSocket ${this._url} is connecting`);return}this._ws&&this.disconnect(),Ks.debug(`connecting to WebSocket ${this._url}`);try{this._ws=new WebSocket(this._url,"sip"),this._ws.binaryType="arraybuffer",this._ws.onopen=this._onOpen.bind(this),this._ws.onclose=this._onClose.bind(this),this._ws.onmessage=this._onMessage.bind(this),this._ws.onerror=this._onError.bind(this)}catch(t){this._onError(t)}}disconnect(){Ks.debug("disconnect()"),this._ws&&(this._ws.onopen=()=>{},this._ws.onclose=()=>{},this._ws.onmessage=()=>{},this._ws.onerror=()=>{},this._ws.close(),this._ws=null)}send(t){return Ks.debug("send()"),this.isConnected()?(this._ws.send(t),!0):(Ks.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(){Ks.debug(`WebSocket ${this._url} connected`),this.onconnect()}_onClose({wasClean:t,code:r,reason:l}){Ks.debug(`WebSocket ${this._url} closed`),t===!1&&Ks.debug("WebSocket abrupt disconnection"),this.ondisconnect(!t,r,l)}_onMessage({data:t}){Ks.debug("received WebSocket message"),this.ondata(t)}_onError(t){Ks.warn(`WebSocket ${this._url} error: `,t)}};const Nd=Uo,GC=Et,WC=Pn,KC=xs(),YC=op,JC=Nn(),QC=Zc(),XC=Dr(),ZC=jC;al("JsSIP")("version %s",Nd.version);var eA={C:GC,Exceptions:WC,Utils:KC,UA:YC,URI:JC,NameAddrHeader:QC,WebSocketInterface:ZC,Grammar:XC,debug:al,get name(){return Nd.title},get version(){return Nd.version}};const tA=Ht(eA);function Md(f){return f<10?`0${f}`:`${f}`}function sA(f){let t=f.hours||0,r=f.minutes||0,l=f.seconds||0;l++,l===60&&(l=0,r++,r===60&&(r=0,t++));const u=`${Md(t)}:${Md(r)}:${Md(l)}`;return{seconds:l,minutes:r,hours:t,formatted:u}}function rA(f){let t=0;for(let r=0;r<f.length;r++)t+=f[r]*f[r];return Math.sqrt(t/f.length)}async function nA(f,t,r=150){const l=t.createMediaStreamSource(f),u=t.createDelay();u.delayTime.value=r/1e3;const s=t.createGain();s.gain.value=0;const n=t.createMediaStreamDestination();return l.connect(u).connect(s).connect(n),{stream:n.stream,setSpeaking:g=>{s.gain.value=g?1:0}}}var Us={};Us.forEach=async(f,t,r)=>{const l=[];for(let u=0;u<f.length;u++)if(u in f){const s=Promise.resolve(f[u]).then(n=>t.call(r||globalThis,n,u,f));l.push(s)}await Promise.all(l)},Us.forEachSeries=async(f,t,r)=>{for(let l=0;l<f.length;l++)l in f&&await t.call(r||globalThis,await f[l],l,f)},Us.map=async(f,t,r)=>{const l=[];for(let u=0;u<f.length;u++)u in f&&(l[u]=Promise.resolve(f[u]).then(s=>t.call(r||globalThis,s,u,f)));return Promise.all(l)},Us.mapSeries=async(f,t,r)=>{const l=[];for(let u=0;u<f.length;u++)u in f&&(l[u]=await t.call(r||globalThis,await f[u],u,f));return l},Us.find=(f,t,r)=>new Promise((l,u)=>{if(f.length===0)return l();let s=1;for(let n=0;n<f.length;n++){const g=_=>{_?l(f[n]):s===f.length&&l(),s++};Promise.resolve(f[n]).then(_=>t.call(r||globalThis,_,n,f)).then(g).catch(u)}}),Us.findSeries=async(f,t,r)=>{for(let l=0;l<f.length;l++)if(await t.call(r||globalThis,await f[l],l,f))return f[l]},Us.findIndex=(f,t,r)=>new Promise((l,u)=>{if(f.length===0)return l(-1);let s=1;for(let n=0;n<f.length;n++){const g=_=>{_?l(n):s===f.length&&l(-1),s++};Promise.resolve(f[n]).then(_=>t.call(r||globalThis,_,n,f)).then(g).catch(u)}}),Us.findIndexSeries=async(f,t,r)=>{for(let l=0;l<f.length;l++)if(await t.call(r||globalThis,await f[l],l,f))return l},Us.some=(f,t,r)=>new Promise((l,u)=>{if(f.length===0)return l(!1);let s=1;for(let n=0;n<f.length;n++){if(!(n in f)){s++;continue}const g=_=>{_?l(!0):s===f.length&&l(!1),s++};Promise.resolve(f[n]).then(_=>t.call(r||globalThis,_,n,f)).then(g).catch(u)}}),Us.someSeries=async(f,t,r)=>{for(let l=0;l<f.length;l++)if(l in f&&await t.call(r||globalThis,await f[l],l,f))return!0;return!1},Us.every=(f,t,r)=>new Promise((l,u)=>{if(f.length===0)return l(!0);let s=1;for(let n=0;n<f.length;n++){if(!(n in f)){s++;continue}const g=_=>{_?s===f.length&&l(!0):l(!1),s++};Promise.resolve(f[n]).then(_=>t.call(r||globalThis,_,n,f)).then(g).catch(u)}}),Us.everySeries=async(f,t,r)=>{for(let l=0;l<f.length;l++)if(l in f&&!await t.call(r||globalThis,await f[l],l,f))return!1;return!0},Us.filter=(f,t,r)=>new Promise(async(l,u)=>{const s=[];for(let g=0;g<f.length;g++)g in f&&(s[g]=Promise.resolve(f[g]).then(_=>t.call(r||globalThis,_,g,f)).catch(u));const n=[];for(let g=0;g<s.length;g++)await s[g]&&n.push(await f[g]);l(n)}),Us.filterSeries=async(f,t,r)=>{const l=[];for(let u=0;u<f.length;u++)u in f&&await t.call(r||globalThis,await f[u],u,f)&&l.push(await f[u]);return l},Us.reduce=async(f,t,r)=>{if(f.length===0&&r===void 0)throw TypeError("Reduce of empty array with no initial value");let l,u;for(r!==void 0?(u=r,l=0):(u=f[0],l=1),l;l<f.length;l++)l in f&&(u=await t(await u,await f[l],l,f));return u};var _p={};(function(f){const t=Us;Object.keys(t).forEach(r=>{const l=r.charAt(0).toUpperCase()+r.slice(1);f[`async${l}`]=async function(...u){return t[r](this,...u)}})})(_p);var iA=Object.assign(Us,{instanceMethods:_p}),pp={},mo={};Object.defineProperty(mo,"__esModule",{value:!0}),mo.baseAssetPath=void 0;const mp=typeof window<"u"&&typeof window.document<"u"?window.document.currentScript:null;let gp="/";mp&&(gp=mp.src.replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/")),mo.baseAssetPath=gp;var gl={};Object.defineProperty(gl,"__esModule",{value:!0}),gl.defaultModelFetcher=void 0;const aA=f=>fetch(f).then(t=>t.arrayBuffer());gl.defaultModelFetcher=aA;var hn={},vl={};(function(f){Object.defineProperty(f,"__esModule",{value:!0}),f.log=f.LOG_PREFIX=void 0,f.LOG_PREFIX="[VAD]";const t=["error","debug","warn"];function r(u){return(...s)=>{console[u](f.LOG_PREFIX,...s)}}const l=t.reduce((u,s)=>(u[s]=r(s),u),{});f.log=l})(vl);var Ra={};Object.defineProperty(Ra,"__esModule",{value:!0}),Ra.Message=void 0;var vp;(function(f){f.AudioFrame="AUDIO_FRAME",f.SpeechStart="SPEECH_START",f.VADMisfire="VAD_MISFIRE",f.SpeechEnd="SPEECH_END",f.SpeechStop="SPEECH_STOP",f.SpeechRealStart="SPEECH_REAL_START",f.FrameProcessed="FRAME_PROCESSED"})(vp||(Ra.Message=vp={})),Object.defineProperty(hn,"__esModule",{value:!0}),hn.FrameProcessor=hn.validateOptions=hn.defaultFrameProcessorOptions=void 0;const go=vl,$a=Ra;hn.defaultFrameProcessorOptions={positiveSpeechThreshold:.3,negativeSpeechThreshold:.25,preSpeechPadMs:800,redemptionMs:1400,minSpeechMs:400,submitUserSpeechOnPause:!1};function lA(f){(f.positiveSpeechThreshold<0||f.positiveSpeechThreshold>1)&&go.log.error("positiveSpeechThreshold should be a number between 0 and 1"),(f.negativeSpeechThreshold<0||f.negativeSpeechThreshold>f.positiveSpeechThreshold)&&go.log.error("negativeSpeechThreshold should be between 0 and positiveSpeechThreshold"),f.preSpeechPadMs<0&&go.log.error("preSpeechPadMs should be positive"),f.redemptionMs<0&&go.log.error("redemptionMs should be positive"),f.minSpeechMs<0&&go.log.error("minSpeechMs should be positive")}hn.validateOptions=lA;const yp=f=>{const t=f.reduce((l,u)=>(l.push(l.at(-1)+u.length),l),[0]),r=new Float32Array(t.at(-1));return f.forEach((l,u)=>{const s=t[u];r.set(l,s)}),r};class oA{constructor(t,r,l,u){this.modelProcessFunc=t,this.modelResetFunc=r,this.options=l,this.msPerFrame=u,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=s=>{this.active=!1,this.options.submitUserSpeechOnPause?this.endSegment(s):this.reset()},this.resume=()=>{this.active=!0},this.endSegment=s=>{const n=this.audioBuffer;this.audioBuffer=[];const g=this.speaking;if(this.reset(),g)if(n.reduce((v,C)=>C.isSpeech?v+1:v,0)>=this.minSpeechFrames){const v=yp(n.map(C=>C.frame));s({msg:$a.Message.SpeechEnd,audio:v})}else s({msg:$a.Message.VADMisfire});return{}},this.process=async(s,n)=>{if(!this.active)return;const g=await this.modelProcessFunc(s),_=g.isSpeech>=this.options.positiveSpeechThreshold;if(n({probs:g,msg:$a.Message.FrameProcessed,frame:s}),this.audioBuffer.push({frame:s,isSpeech:_}),_&&(this.speechFrameCount++,this.redemptionCounter=0),_&&!this.speaking&&(this.speaking=!0,n({msg:$a.Message.SpeechStart})),this.speaking&&this.speechFrameCount===this.minSpeechFrames&&!this.speechRealStartFired&&(this.speechRealStartFired=!0,n({msg:$a.Message.SpeechRealStart})),g.isSpeech<this.options.negativeSpeechThreshold&&this.speaking&&++this.redemptionCounter>=this.redemptionFrames){this.redemptionCounter=0,this.speechFrameCount=0,this.speaking=!1,this.speechRealStartFired=!1;const v=this.audioBuffer;if(this.audioBuffer=[],v.reduce((R,D)=>D.isSpeech?R+1:R,0)>=this.minSpeechFrames){const R=yp(v.map(D=>D.frame));n({msg:$a.Message.SpeechEnd,audio:R})}else n({msg:$a.Message.VADMisfire})}if(!this.speaking){for(;this.audioBuffer.length>this.preSpeechPadFrames;)this.audioBuffer.shift();this.speechFrameCount=0}},this.audioBuffer=[],this.redemptionFrames=Math.floor(l.redemptionMs/this.msPerFrame),this.preSpeechPadFrames=Math.floor(l.preSpeechPadMs/this.msPerFrame),this.minSpeechFrames=Math.floor(l.minSpeechMs/this.msPerFrame),this.reset()}}hn.FrameProcessor=oA;var Tp={};function yl(f){throw new Error('Could not dynamically require "'+f+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var Sp={exports:{}};/*!
159
159
  * ONNX Runtime Web v1.23.0
160
160
  * Copyright (c) Microsoft Corporation. All rights reserved.
161
161
  * Licensed under the MIT License.
162
- */(function(f,t){var r=(()=>{var l=Object.defineProperty,u=Object.getOwnPropertyDescriptor,s=Object.getOwnPropertyNames,n=Object.prototype.hasOwnProperty,g=(i=>typeof yl<"u"?yl:typeof Proxy<"u"?new Proxy(i,{get:(c,h)=>(typeof yl<"u"?yl:c)[h]}):i)(function(i){if(typeof yl<"u")return yl.apply(this,arguments);throw Error('Dynamic require of "'+i+'" is not supported')}),_=(i,c)=>()=>(i&&(c=i(i=0)),c),v=(i,c)=>{for(var h in c)l(i,h,{get:c[h],enumerable:!0})},C=(i,c,h,m)=>{if(c&&typeof c=="object"||typeof c=="function")for(let y of s(c))!n.call(i,y)&&y!==h&&l(i,y,{get:()=>c[y],enumerable:!(m=u(c,y))||m.enumerable});return i},R=i=>C(l({},"__esModule",{value:!0}),i),D,H,F,q,G,te=_(()=>{D=new Map,H=[],F=(i,c,h)=>{if(c&&typeof c.init=="function"&&typeof c.createInferenceSessionHandler=="function"){let m=D.get(i);if(m===void 0)D.set(i,{backend:c,priority:h});else{if(m.priority>h)return;if(m.priority===h&&m.backend!==c)throw new Error(`cannot register backend "${i}" using priority ${h}`)}if(h>=0){let y=H.indexOf(i);y!==-1&&H.splice(y,1);for(let S=0;S<H.length;S++)if(D.get(H[S]).priority<=h){H.splice(S,0,i);return}H.push(i)}return}throw new TypeError("not a valid backend")},q=async i=>{let c=D.get(i);if(!c)return"backend not found.";if(c.initialized)return c.backend;if(c.aborted)return c.error;{let h=!!c.initPromise;try{return h||(c.initPromise=c.backend.init(i)),await c.initPromise,c.initialized=!0,c.backend}catch(m){return h||(c.error=`${m}`,c.aborted=!0),c.error}finally{delete c.initPromise}}},G=async i=>{let c=i.executionProviders||[],h=c.map(A=>typeof A=="string"?A:A.name),m=h.length===0?H:h,y,S=[],b=new Set;for(let A of m){let I=await q(A);typeof I=="string"?S.push({name:A,err:I}):(y||(y=I),y===I&&b.add(A))}if(!y)throw new Error(`no available backend found. ERR: ${S.map(A=>`[${A.name}] ${A.err}`).join(", ")}`);for(let{name:A,err:I}of S)h.includes(A)&&console.warn(`removing requested execution provider "${A}" from session options because it is not available: ${I}`);let E=c.filter(A=>b.has(typeof A=="string"?A:A.name));return[y,new Proxy(i,{get:(A,I)=>I==="executionProviders"?E:Reflect.get(A,I)})]}}),X=_(()=>{te()}),we,Q=_(()=>{we="1.23.0"}),re,ke,Ne=_(()=>{Q(),re="warning",ke={wasm:{},webgl:{},webgpu:{},versions:{common:we},set logLevel(i){if(i!==void 0){if(typeof i!="string"||["verbose","info","warning","error","fatal"].indexOf(i)===-1)throw new Error(`Unsupported logging level: ${i}`);re=i}},get logLevel(){return re}},Object.defineProperty(ke,"logLevel",{enumerable:!0})}),Z,se=_(()=>{Ne(),Z=ke}),pe,me,be=_(()=>{pe=(i,c)=>{let h=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);h.width=i.dims[3],h.height=i.dims[2];let m=h.getContext("2d");if(m!=null){let y,S;(c==null?void 0:c.tensorLayout)!==void 0&&c.tensorLayout==="NHWC"?(y=i.dims[2],S=i.dims[3]):(y=i.dims[3],S=i.dims[2]);let b=(c==null?void 0:c.format)!==void 0?c.format:"RGB",E=c==null?void 0:c.norm,A,I;E===void 0||E.mean===void 0?A=[255,255,255,255]:typeof E.mean=="number"?A=[E.mean,E.mean,E.mean,E.mean]:(A=[E.mean[0],E.mean[1],E.mean[2],0],E.mean[3]!==void 0&&(A[3]=E.mean[3])),E===void 0||E.bias===void 0?I=[0,0,0,0]:typeof E.bias=="number"?I=[E.bias,E.bias,E.bias,E.bias]:(I=[E.bias[0],E.bias[1],E.bias[2],0],E.bias[3]!==void 0&&(I[3]=E.bias[3]));let $=S*y,x=0,k=$,N=$*2,M=-1;b==="RGBA"?(x=0,k=$,N=$*2,M=$*3):b==="RGB"?(x=0,k=$,N=$*2):b==="RBG"&&(x=0,N=$,k=$*2);for(let U=0;U<S;U++)for(let z=0;z<y;z++){let L=(i.data[x++]-I[0])*A[0],P=(i.data[k++]-I[1])*A[1],j=(i.data[N++]-I[2])*A[2],V=M===-1?255:(i.data[M++]-I[3])*A[3];m.fillStyle="rgba("+L+","+P+","+j+","+V+")",m.fillRect(z,U,1,1)}if("toDataURL"in h)return h.toDataURL();throw new Error("toDataURL is not supported")}else throw new Error("Can not access image data")},me=(i,c)=>{let h=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),m;if(h!=null){let y,S,b;(c==null?void 0:c.tensorLayout)!==void 0&&c.tensorLayout==="NHWC"?(y=i.dims[2],S=i.dims[1],b=i.dims[3]):(y=i.dims[3],S=i.dims[2],b=i.dims[1]);let E=c!==void 0&&c.format!==void 0?c.format:"RGB",A=c==null?void 0:c.norm,I,$;A===void 0||A.mean===void 0?I=[255,255,255,255]:typeof A.mean=="number"?I=[A.mean,A.mean,A.mean,A.mean]:(I=[A.mean[0],A.mean[1],A.mean[2],255],A.mean[3]!==void 0&&(I[3]=A.mean[3])),A===void 0||A.bias===void 0?$=[0,0,0,0]:typeof A.bias=="number"?$=[A.bias,A.bias,A.bias,A.bias]:($=[A.bias[0],A.bias[1],A.bias[2],0],A.bias[3]!==void 0&&($[3]=A.bias[3]));let x=S*y;if(c!==void 0&&(c.format!==void 0&&b===4&&c.format!=="RGBA"||b===3&&c.format!=="RGB"&&c.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let k=4,N=0,M=1,U=2,z=3,L=0,P=x,j=x*2,V=-1;E==="RGBA"?(L=0,P=x,j=x*2,V=x*3):E==="RGB"?(L=0,P=x,j=x*2):E==="RBG"&&(L=0,j=x,P=x*2),m=h.createImageData(y,S);for(let Y=0;Y<S*y;N+=k,M+=k,U+=k,z+=k,Y++)m.data[N]=(i.data[L++]-$[0])*I[0],m.data[M]=(i.data[P++]-$[1])*I[1],m.data[U]=(i.data[j++]-$[2])*I[2],m.data[z]=V===-1?255:(i.data[V++]-$[3])*I[3]}else throw new Error("Can not access image data");return m}}),_e,Ae,le,oe,Oe,rs,Re=_(()=>{Zt(),_e=(i,c)=>{if(i===void 0)throw new Error("Image buffer must be defined");if(c.height===void 0||c.width===void 0)throw new Error("Image height and width must be defined");if(c.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:h,width:m}=c,y=c.norm??{mean:255,bias:0},S,b;typeof y.mean=="number"?S=[y.mean,y.mean,y.mean,y.mean]:S=[y.mean[0],y.mean[1],y.mean[2],y.mean[3]??255],typeof y.bias=="number"?b=[y.bias,y.bias,y.bias,y.bias]:b=[y.bias[0],y.bias[1],y.bias[2],y.bias[3]??0];let E=c.format!==void 0?c.format:"RGBA",A=c.tensorFormat!==void 0&&c.tensorFormat!==void 0?c.tensorFormat:"RGB",I=h*m,$=A==="RGBA"?new Float32Array(I*4):new Float32Array(I*3),x=4,k=0,N=1,M=2,U=3,z=0,L=I,P=I*2,j=-1;E==="RGB"&&(x=3,k=0,N=1,M=2,U=-1),A==="RGBA"?j=I*3:A==="RBG"?(z=0,P=I,L=I*2):A==="BGR"&&(P=0,L=I,z=I*2);for(let V=0;V<I;V++,k+=x,M+=x,N+=x,U+=x)$[z++]=(i[k]+b[0])/S[0],$[L++]=(i[N]+b[1])/S[1],$[P++]=(i[M]+b[2])/S[2],j!==-1&&U!==-1&&($[j++]=(i[U]+b[3])/S[3]);return A==="RGBA"?new Ye("float32",$,[1,4,h,m]):new Ye("float32",$,[1,3,h,m])},Ae=async(i,c)=>{let h=typeof HTMLImageElement<"u"&&i instanceof HTMLImageElement,m=typeof ImageData<"u"&&i instanceof ImageData,y=typeof ImageBitmap<"u"&&i instanceof ImageBitmap,S=typeof i=="string",b,E=c??{},A=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},I=$=>typeof HTMLCanvasElement<"u"&&$ instanceof HTMLCanvasElement||$ instanceof OffscreenCanvas?$.getContext("2d"):null;if(h){let $=A();$.width=i.width,$.height=i.height;let x=I($);if(x!=null){let k=i.height,N=i.width;if(c!==void 0&&c.resizedHeight!==void 0&&c.resizedWidth!==void 0&&(k=c.resizedHeight,N=c.resizedWidth),c!==void 0){if(E=c,c.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");E.tensorFormat="RGBA",E.height=k,E.width=N}else E.tensorFormat="RGBA",E.height=k,E.width=N;x.drawImage(i,0,0),b=x.getImageData(0,0,N,k).data}else throw new Error("Can not access image data")}else if(m){let $,x;if(c!==void 0&&c.resizedWidth!==void 0&&c.resizedHeight!==void 0?($=c.resizedHeight,x=c.resizedWidth):($=i.height,x=i.width),c!==void 0&&(E=c),E.format="RGBA",E.height=$,E.width=x,c!==void 0){let k=A();k.width=x,k.height=$;let N=I(k);if(N!=null)N.putImageData(i,0,0),b=N.getImageData(0,0,x,$).data;else throw new Error("Can not access image data")}else b=i.data}else if(y){if(c===void 0)throw new Error("Please provide image config with format for Imagebitmap");let $=A();$.width=i.width,$.height=i.height;let x=I($);if(x!=null){let k=i.height,N=i.width;return x.drawImage(i,0,0,N,k),b=x.getImageData(0,0,N,k).data,E.height=k,E.width=N,_e(b,E)}else throw new Error("Can not access image data")}else{if(S)return new Promise(($,x)=>{let k=A(),N=I(k);if(!i||!N)return x();let M=new Image;M.crossOrigin="Anonymous",M.src=i,M.onload=()=>{k.width=M.width,k.height=M.height,N.drawImage(M,0,0,k.width,k.height);let U=N.getImageData(0,0,k.width,k.height);E.height=k.height,E.width=k.width,$(_e(U.data,E))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(b!==void 0)return _e(b,E);throw new Error("Input data provided is not supported - aborted tensor creation")},le=(i,c)=>{let{width:h,height:m,download:y,dispose:S}=c,b=[1,m,h,4];return new Ye({location:"texture",type:"float32",texture:i,dims:b,download:y,dispose:S})},oe=(i,c)=>{let{dataType:h,dims:m,download:y,dispose:S}=c;return new Ye({location:"gpu-buffer",type:h??"float32",gpuBuffer:i,dims:m,download:y,dispose:S})},Oe=(i,c)=>{let{dataType:h,dims:m,download:y,dispose:S}=c;return new Ye({location:"ml-tensor",type:h??"float32",mlTensor:i,dims:m,download:y,dispose:S})},rs=(i,c,h)=>new Ye({location:"cpu-pinned",type:i,data:c,dims:h??[c.length]})}),ye,ge,Le,et,vt=_(()=>{ye=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),ge=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),Le=!1,et=()=>{if(!Le){Le=!0;let i=typeof BigInt64Array<"u"&&BigInt64Array.from,c=typeof BigUint64Array<"u"&&BigUint64Array.from,h=globalThis.Float16Array,m=typeof h<"u"&&h.from;i&&(ye.set("int64",BigInt64Array),ge.set(BigInt64Array,"int64")),c&&(ye.set("uint64",BigUint64Array),ge.set(BigUint64Array,"uint64")),m?(ye.set("float16",h),ge.set(h,"float16")):ye.set("float16",Uint16Array)}}}),xt,dt,ze=_(()=>{Zt(),xt=i=>{let c=1;for(let h=0;h<i.length;h++){let m=i[h];if(typeof m!="number"||!Number.isSafeInteger(m))throw new TypeError(`dims[${h}] must be an integer, got: ${m}`);if(m<0)throw new RangeError(`dims[${h}] must be a non-negative integer, got: ${m}`);c*=m}return c},dt=(i,c)=>{switch(i.location){case"cpu":return new Ye(i.type,i.data,c);case"cpu-pinned":return new Ye({location:"cpu-pinned",data:i.data,type:i.type,dims:c});case"texture":return new Ye({location:"texture",texture:i.texture,type:i.type,dims:c});case"gpu-buffer":return new Ye({location:"gpu-buffer",gpuBuffer:i.gpuBuffer,type:i.type,dims:c});case"ml-tensor":return new Ye({location:"ml-tensor",mlTensor:i.mlTensor,type:i.type,dims:c});default:throw new Error(`tensorReshape: tensor location ${i.location} is not supported`)}}}),Ye,Zt=_(()=>{be(),Re(),vt(),ze(),Ye=class{constructor(i,c,h){et();let m,y;if(typeof i=="object"&&"location"in i)switch(this.dataLocation=i.location,m=i.type,y=i.dims,i.location){case"cpu-pinned":{let b=ye.get(m);if(!b)throw new TypeError(`unsupported type "${m}" to create tensor from pinned buffer`);if(!(i.data instanceof b))throw new TypeError(`buffer should be of type ${b.name}`);this.cpuData=i.data;break}case"texture":{if(m!=="float32")throw new TypeError(`unsupported type "${m}" to create tensor from texture`);this.gpuTextureData=i.texture,this.downloader=i.download,this.disposer=i.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=i.gpuBuffer,this.downloader=i.download,this.disposer=i.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=i.mlTensor,this.downloader=i.download,this.disposer=i.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let b,E;if(typeof i=="string")if(m=i,E=h,i==="string"){if(!Array.isArray(c))throw new TypeError("A string tensor's data must be a string array.");b=c}else{let A=ye.get(i);if(A===void 0)throw new TypeError(`Unsupported tensor type: ${i}.`);if(Array.isArray(c)){if(i==="float16"&&A===Uint16Array||i==="uint4"||i==="int4")throw new TypeError(`Creating a ${i} tensor from number array is not supported. Please use ${A.name} as data.`);i==="uint64"||i==="int64"?b=A.from(c,BigInt):b=A.from(c)}else if(c instanceof A)b=c;else if(c instanceof Uint8ClampedArray)if(i==="uint8")b=Uint8Array.from(c);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(i==="float16"&&c instanceof Uint16Array&&A!==Uint16Array)b=new globalThis.Float16Array(c.buffer,c.byteOffset,c.length);else throw new TypeError(`A ${m} tensor's data must be type of ${A}`)}else if(E=c,Array.isArray(i)){if(i.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let A=typeof i[0];if(A==="string")m="string",b=i;else if(A==="boolean")m="bool",b=Uint8Array.from(i);else throw new TypeError(`Invalid element type of data array: ${A}.`)}else if(i instanceof Uint8ClampedArray)m="uint8",b=Uint8Array.from(i);else{let A=ge.get(i.constructor);if(A===void 0)throw new TypeError(`Unsupported type for tensor data: ${i.constructor}.`);m=A,b=i}if(E===void 0)E=[b.length];else if(!Array.isArray(E))throw new TypeError("A tensor's dims must be a number array");y=E,this.cpuData=b,this.dataLocation="cpu"}let S=xt(y);if(this.cpuData&&S!==this.cpuData.length&&!((m==="uint4"||m==="int4")&&Math.ceil(S/2)===this.cpuData.length))throw new Error(`Tensor's size(${S}) does not match data length(${this.cpuData.length}).`);this.type=m,this.dims=y,this.size=S}static async fromImage(i,c){return Ae(i,c)}static fromTexture(i,c){return le(i,c)}static fromGpuBuffer(i,c){return oe(i,c)}static fromMLTensor(i,c){return Oe(i,c)}static fromPinnedBuffer(i,c,h){return rs(i,c,h)}toDataURL(i){return pe(this,i)}toImageData(i){return me(this,i)}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(i){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 c=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=c,i&&this.disposer&&(this.disposer(),this.disposer=void 0),c}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(i){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return dt(this,i)}}}),Mt,nt=_(()=>{Zt(),Mt=Ye}),rt,gt,ft,Fe,He,qe,yt=_(()=>{Ne(),rt=(i,c)=>{(typeof ke.trace>"u"?!ke.wasm.trace:!ke.trace)||console.timeStamp(`${i}::ORT::${c}`)},gt=(i,c)=>{var y;let h=((y=new Error().stack)==null?void 0:y.split(/\r\n|\r|\n/g))||[],m=!1;for(let S=0;S<h.length;S++){if(m&&!h[S].includes("TRACE_FUNC")){let b=`FUNC_${i}::${h[S].trim().split(" ")[1]}`;c&&(b+=`::${c}`),rt("CPU",b);return}h[S].includes("TRACE_FUNC")&&(m=!0)}},ft=i=>{(typeof ke.trace>"u"?!ke.wasm.trace:!ke.trace)||gt("BEGIN",i)},Fe=i=>{(typeof ke.trace>"u"?!ke.wasm.trace:!ke.trace)||gt("END",i)},He=i=>{(typeof ke.trace>"u"?!ke.wasm.trace:!ke.trace)||console.time(`ORT::${i}`)},qe=i=>{(typeof ke.trace>"u"?!ke.wasm.trace:!ke.trace)||console.timeEnd(`ORT::${i}`)}}),Ct,ns=_(()=>{te(),nt(),yt(),Ct=class GT{constructor(c){this.handler=c}async run(c,h,m){ft(),He("InferenceSession.run");let y={},S={};if(typeof c!="object"||c===null||c instanceof Mt||Array.isArray(c))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let b=!0;if(typeof h=="object"){if(h===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(h instanceof Mt)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(h)){if(h.length===0)throw new TypeError("'fetches' cannot be an empty array.");b=!1;for(let I of h){if(typeof I!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(I)===-1)throw new RangeError(`'fetches' contains invalid output name: ${I}.`);y[I]=null}if(typeof m=="object"&&m!==null)S=m;else if(typeof m<"u")throw new TypeError("'options' must be an object.")}else{let I=!1,$=Object.getOwnPropertyNames(h);for(let x of this.outputNames)if($.indexOf(x)!==-1){let k=h[x];(k===null||k instanceof Mt)&&(I=!0,b=!1,y[x]=k)}if(I){if(typeof m=="object"&&m!==null)S=m;else if(typeof m<"u")throw new TypeError("'options' must be an object.")}else S=h}}else if(typeof h<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let I of this.inputNames)if(typeof c[I]>"u")throw new Error(`input '${I}' is missing in 'feeds'.`);if(b)for(let I of this.outputNames)y[I]=null;let E=await this.handler.run(c,y,S),A={};for(let I in E)if(Object.hasOwnProperty.call(E,I)){let $=E[I];$ instanceof Mt?A[I]=$:A[I]=new Mt($.type,$.data,$.dims)}return qe("InferenceSession.run"),Fe(),A}async release(){return this.handler.dispose()}static async create(c,h,m,y){ft(),He("InferenceSession.create");let S,b={};if(typeof c=="string"){if(S=c,typeof h=="object"&&h!==null)b=h;else if(typeof h<"u")throw new TypeError("'options' must be an object.")}else if(c instanceof Uint8Array){if(S=c,typeof h=="object"&&h!==null)b=h;else if(typeof h<"u")throw new TypeError("'options' must be an object.")}else if(c instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&c instanceof SharedArrayBuffer){let $=c,x=0,k=c.byteLength;if(typeof h=="object"&&h!==null)b=h;else if(typeof h=="number"){if(x=h,!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(k=c.byteLength-x,typeof m=="number"){if(k=m,!Number.isSafeInteger(k))throw new RangeError("'byteLength' must be an integer.");if(k<=0||x+k>$.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${$.byteLength-x}].`);if(typeof y=="object"&&y!==null)b=y;else if(typeof y<"u")throw new TypeError("'options' must be an object.")}else if(typeof m<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof h<"u")throw new TypeError("'options' must be an object.");S=new Uint8Array($,x,k)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[E,A]=await G(b),I=await E.createInferenceSessionHandler(S,A);return qe("InferenceSession.create"),Fe(),new GT(I)}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}}}),Ut,ar=_(()=>{ns(),Ut=Ct}),vs=_(()=>{}),Oi=_(()=>{}),Di=_(()=>{}),zn=_(()=>{}),pr={};v(pr,{InferenceSession:()=>Ut,TRACE:()=>rt,TRACE_EVENT_BEGIN:()=>He,TRACE_EVENT_END:()=>qe,TRACE_FUNC_BEGIN:()=>ft,TRACE_FUNC_END:()=>Fe,Tensor:()=>Mt,env:()=>Z,registerBackend:()=>F});var as=_(()=>{X(),se(),ar(),nt(),vs(),Oi(),yt(),Di(),zn()}),Pr=_(()=>{}),Vn={};v(Vn,{default:()=>Qe});var pn,Lr,Qe,Ve=_(()=>{var i;RT(),gr(),Yn(),pn="ort-wasm-proxy-worker",Lr=((i=globalThis.self)==null?void 0:i.name)===pn,Lr&&(self.onmessage=c=>{let{type:h,in:m}=c.data;try{switch(h){case"init-wasm":Vr(m.wasm).then(()=>{$f(m).then(()=>{postMessage({type:h})},y=>{postMessage({type:h,err:y})})},y=>{postMessage({type:h,err:y})});break;case"init-ep":{let{epName:y,env:S}=m;xf(S,y).then(()=>{postMessage({type:h})},b=>{postMessage({type:h,err:b})});break}case"copy-from":{let{buffer:y}=m,S=rc(y);postMessage({type:h,out:S});break}case"create":{let{model:y,options:S}=m;Df(y,S).then(b=>{postMessage({type:h,out:b})},b=>{postMessage({type:h,err:b})});break}case"release":kf(m),postMessage({type:h});break;case"run":{let{sessionId:y,inputIndices:S,inputs:b,outputIndices:E,options:A}=m;Mf(y,S,b,E,new Array(E.length).fill(null),A).then(I=>{I.some($=>$[3]!=="cpu")?postMessage({type:h,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:h,out:I},Pf([...b,...I]))},I=>{postMessage({type:h,err:I})});break}case"end-profiling":Uf(m),postMessage({type:h});break;default:}}catch(y){postMessage({type:h,err:y})}}),Qe=Lr?null:c=>new Worker(c??os,{type:"classic",name:pn})}),ls,lr,os,qn,Hr,jn,ki,Gn,Ni,Wn,Mi,Kn,Ui,Yn=_(()=>{Pr(),ls=typeof location>"u"?void 0:location.origin,lr=()=>{var i,c;return typeof document<"u"?(i=document.currentScript)==null?void 0:i.src:typeof self<"u"?(c=self.location)==null?void 0:c.href:void 0},os=lr(),qn=()=>{if(os&&!os.startsWith("blob:"))return os.substring(0,os.lastIndexOf("/")+1)},Hr=(i,c)=>{try{let h=c??os;return(h?new URL(i,h):new URL(i)).origin===ls}catch{return!1}},jn=(i,c)=>{let h=c??os;try{return(h?new URL(i,h):new URL(i)).href}catch{return}},ki=(i,c)=>`${c??"./"}${i}`,Gn=async i=>{let c=await(await fetch(i,{credentials:"same-origin"})).blob();return URL.createObjectURL(c)},Ni=async i=>(await import(i)).default,Wn=(Ve(),R(Vn)).default,Mi=async()=>{if(!os)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(Hr(os))return[void 0,Wn()];let i=await Gn(os);return[i,Wn(i)]},Kn=void 0,Ui=async(i,c,h,m)=>{let y=Kn&&!(i||c);if(y)if(os)y=Hr(os);else if(m&&!h)y=!0;else throw new Error("cannot determine the script source URL.");if(y)return[void 0,Kn];{let S="ort-wasm-simd-threaded.jsep.mjs",b=i??jn(S,c),E=h&&b&&!Hr(b,c),A=E?await Gn(b):b??ki(S,c);return[E?A:void 0,await Ni(A)]}}}),Ar,mr,Fr,Br,mn,Pi,zr,Vr,kt,gr=_(()=>{Yn(),mr=!1,Fr=!1,Br=!1,mn=()=>{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}},Pi=()=>{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}},zr=()=>{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}},Vr=async i=>{if(mr)return Promise.resolve();if(Fr)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(Br)throw new Error("previous call to 'initializeWebAssembly()' failed.");Fr=!0;let c=i.initTimeout,h=i.numThreads;if(i.simd!==!1){if(i.simd==="relaxed"){if(!zr())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!Pi())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let m=mn();h>1&&!m&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+h+", 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."),i.numThreads=h=1);let y=i.wasmPaths,S=typeof y=="string"?y:void 0,b=y==null?void 0:y.mjs,E=(b==null?void 0:b.href)??b,A=y==null?void 0:y.wasm,I=(A==null?void 0:A.href)??A,$=i.wasmBinary,[x,k]=await Ui(E,S,h>1,!!$||!!I),N=!1,M=[];if(c>0&&M.push(new Promise(U=>{setTimeout(()=>{N=!0,U()},c)})),M.push(new Promise((U,z)=>{let L={numThreads:h};if($)L.wasmBinary=$;else if(I||S)L.locateFile=P=>I??S+P;else if(E&&E.indexOf("blob:")!==0)L.locateFile=P=>new URL(P,E).href;else if(x){let P=qn();P&&(L.locateFile=j=>P+j)}k(L).then(P=>{Fr=!1,mr=!0,Ar=P,U(),x&&URL.revokeObjectURL(x)},P=>{Fr=!1,Br=!0,z(P)})})),await Promise.race(M),N)throw new Error(`WebAssembly backend initializing failed due to timeout: ${c}ms`)},kt=()=>{if(mr&&Ar)return Ar;throw new Error("WebAssembly is not initialized yet.")}}),bs,qr,It,jr=_(()=>{gr(),bs=(i,c)=>{let h=kt(),m=h.lengthBytesUTF8(i)+1,y=h._malloc(m);return h.stringToUTF8(i,y,m),c.push(y),y},qr=(i,c,h,m)=>{if(typeof i=="object"&&i!==null){if(h.has(i))throw new Error("Circular reference in options");h.add(i)}Object.entries(i).forEach(([y,S])=>{let b=c?c+y:y;if(typeof S=="object")qr(S,b+".",h,m);else if(typeof S=="string"||typeof S=="number")m(b,S.toString());else if(typeof S=="boolean")m(b,S?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof S}`)})},It=i=>{let c=kt(),h=c.stackSave();try{let m=c.PTR_SIZE,y=c.stackAlloc(2*m);c._OrtGetLastError(y,y+m);let S=Number(c.getValue(y,m===4?"i32":"i64")),b=c.getValue(y+m,"*"),E=b?c.UTF8ToString(b):"";throw new Error(`${i} ERROR_CODE: ${S}, ERROR_MESSAGE: ${E}`)}finally{c.stackRestore(h)}}}),gn,vn=_(()=>{gr(),jr(),gn=i=>{let c=kt(),h=0,m=[],y=i||{};try{if((i==null?void 0:i.logSeverityLevel)===void 0)y.logSeverityLevel=2;else if(typeof i.logSeverityLevel!="number"||!Number.isInteger(i.logSeverityLevel)||i.logSeverityLevel<0||i.logSeverityLevel>4)throw new Error(`log severity level is not valid: ${i.logSeverityLevel}`);if((i==null?void 0:i.logVerbosityLevel)===void 0)y.logVerbosityLevel=0;else if(typeof i.logVerbosityLevel!="number"||!Number.isInteger(i.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${i.logVerbosityLevel}`);(i==null?void 0:i.terminate)===void 0&&(y.terminate=!1);let S=0;return(i==null?void 0:i.tag)!==void 0&&(S=bs(i.tag,m)),h=c._OrtCreateRunOptions(y.logSeverityLevel,y.logVerbosityLevel,!!y.terminate,S),h===0&&It("Can't create run options."),(i==null?void 0:i.extra)!==void 0&&qr(i.extra,"",new WeakSet,(b,E)=>{let A=bs(b,m),I=bs(E,m);c._OrtAddRunConfigEntry(h,A,I)!==0&&It(`Can't set a run config entry: ${b} - ${E}.`)}),[h,m]}catch(S){throw h!==0&&c._OrtReleaseRunOptions(h),m.forEach(b=>c._free(b)),S}}}),Gr,Li,yn,or,Ir,Wr,Da=_(()=>{gr(),jr(),Gr=i=>{switch(i){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: ${i}`)}},Li=i=>{switch(i){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${i}`)}},yn=i=>{i.extra||(i.extra={}),i.extra.session||(i.extra.session={});let c=i.extra.session;c.use_ort_model_bytes_directly||(c.use_ort_model_bytes_directly="1"),i.executionProviders&&i.executionProviders.some(h=>(typeof h=="string"?h:h.name)==="webgpu")&&(i.enableMemPattern=!1)},or=(i,c,h,m)=>{let y=bs(c,m),S=bs(h,m);kt()._OrtAddSessionConfigEntry(i,y,S)!==0&&It(`Can't set a session config entry: ${c} - ${h}.`)},Ir=async(i,c,h)=>{for(let m of c){let y=typeof m=="string"?m:m.name,S=[];switch(y){case"webnn":if(y="WEBNN",typeof m!="string"){let $=m==null?void 0:m.deviceType;$&&or(i,"deviceType",$,h)}break;case"webgpu":if(y="JS",typeof m!="string"){let $=m;if($!=null&&$.preferredLayout){if($.preferredLayout!=="NCHW"&&$.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${$.preferredLayout}`);or(i,"preferredLayout",$.preferredLayout,h)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${y}`)}let b=bs(y,h),E=S.length,A=0,I=0;if(E>0){A=kt()._malloc(E*kt().PTR_SIZE),h.push(A),I=kt()._malloc(E*kt().PTR_SIZE),h.push(I);for(let $=0;$<E;$++)kt().setValue(A+$*kt().PTR_SIZE,S[$][0],"*"),kt().setValue(I+$*kt().PTR_SIZE,S[$][1],"*")}await kt()._OrtAppendExecutionProvider(i,b,A,I,E)!==0&&It(`Can't append execution provider: ${y}.`)}},Wr=async i=>{let c=kt(),h=0,m=[],y=i||{};yn(y);try{let S=Gr(y.graphOptimizationLevel??"all"),b=Li(y.executionMode??"sequential"),E=typeof y.logId=="string"?bs(y.logId,m):0,A=y.logSeverityLevel??2;if(!Number.isInteger(A)||A<0||A>4)throw new Error(`log severity level is not valid: ${A}`);let I=y.logVerbosityLevel??0;if(!Number.isInteger(I)||I<0||I>4)throw new Error(`log verbosity level is not valid: ${I}`);let $=typeof y.optimizedModelFilePath=="string"?bs(y.optimizedModelFilePath,m):0;if(h=c._OrtCreateSessionOptions(S,!!y.enableCpuMemArena,!!y.enableMemPattern,b,!!y.enableProfiling,0,E,A,I,$),h===0&&It("Can't create session options."),y.executionProviders&&await Ir(h,y.executionProviders,m),y.enableGraphCapture!==void 0){if(typeof y.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${y.enableGraphCapture}`);or(h,"enableGraphCapture",y.enableGraphCapture.toString(),m)}if(y.freeDimensionOverrides)for(let[x,k]of Object.entries(y.freeDimensionOverrides)){if(typeof x!="string")throw new Error(`free dimension override name must be a string: ${x}`);if(typeof k!="number"||!Number.isInteger(k)||k<0)throw new Error(`free dimension override value must be a non-negative integer: ${k}`);let N=bs(x,m);c._OrtAddFreeDimensionOverride(h,N,k)!==0&&It(`Can't set a free dimension override: ${x} - ${k}.`)}return y.extra!==void 0&&qr(y.extra,"",new WeakSet,(x,k)=>{or(h,x,k,m)}),[h,m]}catch(S){throw h!==0&&c._OrtReleaseSessionOptions(h)!==0&&It("Can't release session options."),m.forEach(b=>c._free(b)),S}}}),vr,Ys,yr,Kr,Yr,Jn,Qn,Xn,ot=_(()=>{vr=i=>{switch(i){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: ${i}`)}},Ys=i=>{switch(i){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: ${i}`)}},yr=(i,c)=>{let h=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][i],m=typeof c=="number"?c:c.reduce((y,S)=>y*S,1);return h>0?Math.ceil(m*h):void 0},Kr=i=>{switch(i){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: ${i}`)}},Yr=i=>{switch(i){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: ${i}`)}},Jn=i=>i==="float32"||i==="float16"||i==="int32"||i==="int64"||i==="uint32"||i==="uint8"||i==="bool"||i==="uint4"||i==="int4",Qn=i=>i==="float32"||i==="float16"||i==="int32"||i==="int64"||i==="uint32"||i==="uint64"||i==="int8"||i==="uint8"||i==="bool"||i==="uint4"||i==="int4",Xn=i=>{switch(i){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: ${i}`)}}}),Zn,Hi=_(()=>{Pr(),Zn=async i=>{if(typeof i=="string"){let c=await fetch(i);if(!c.ok)throw new Error(`failed to load external data file: ${i}`);let h=c.headers.get("Content-Length"),m=h?parseInt(h,10):0;if(m<1073741824)return new Uint8Array(await c.arrayBuffer());{if(!c.body)throw new Error(`failed to load external data file: ${i}, no response body.`);let y=c.body.getReader(),S;try{S=new ArrayBuffer(m)}catch(E){if(E instanceof RangeError){let A=Math.ceil(m/65536);S=new WebAssembly.Memory({initial:A,maximum:A}).buffer}else throw E}let b=0;for(;;){let{done:E,value:A}=await y.read();if(E)break;let I=A.byteLength;new Uint8Array(S,b,I).set(A),b+=I}return new Uint8Array(S,0,m)}}else return i instanceof Blob?new Uint8Array(await i.arrayBuffer()):i instanceof Uint8Array?i:new Uint8Array(i)}}),Fi,Bi,Tn,Sn,ei,zi,bt,ur=_(()=>{ot(),Fi=["V","I","W","E","F"],Bi=(i,c)=>{console.log(`[${Fi[i]},${new Date().toISOString()}]${c}`)},ei=(i,c)=>{Tn=i,Sn=c},zi=(i,c)=>{let h=Yr(i),m=Yr(Tn);h>=m&&Bi(h,typeof c=="function"?c():c)},bt=(...i)=>{Sn&&zi(...i)}}),Sl,bn,ie,Ls,Js,Jr,ti,ht=_(()=>{Sl=class{static calcMatMulShape(i,c){return i[1]!==c[0]?void 0:[i[0],c[1]]}},bn=class{static calcShape(i,c,h=!1){let m=i.length,y=c.length;if(m===0)return c;if(y===0)return i;let S=Math.max(i.length,c.length),b=new Array(S);if(h){if(m<2||y<2)return;let E=Sl.calcMatMulShape([i[m-2],i[m-1]],[c[y-2],c[y-1]]);if(E===void 0)return;[b[S-2],b[S-1]]=E}for(let E=h?3:1;E<=S;E++){let A=m-E<0?1:i[m-E],I=y-E<0?1:c[y-E];if(A!==I&&A>1&&I>1)return;let $=Math.max(A,I);if(A&&I)b[S-E]=Math.max(A,I);else{if($>1)return;b[S-E]=0}}return b}static isValidBroadcast(i,c){let h=i.length,m=c.length;if(h>m)return!1;for(let y=1;y<=h;y++)if(i[h-y]!==1&&i[h-y]!==c[m-y])return!1;return!0}},ie=class ac{static size(c){return ac.getSizeFromDimensionRange(c,0,c.length)}static convertShape(c,h=4){let m=c.length;if(m===0)return[];let y=new Array(m),S=m-1;for(;S>=0;){if(c[S]%h===0){y[S]=c[S]/h;break}if(h%c[S]!==0)throw new Error("cannot convert shape");y[S]=1,h/=c[S],S--}for(S--;S>=0;S--)y[S]=c[S];return y}static sizeFromDimension(c,h){if(h<0||h>c.length)throw new Error(`invalid dimension of ${h} for sizeFromDimension as Tensor has ${c.length} dimensions.`);return ac.getSizeFromDimensionRange(c,h,c.length)}static sizeToDimension(c,h){if(h<0||h>c.length)throw new Error(`invalid dimension of ${h} for sizeToDimension as Tensor has ${c.length} dimensions.`);return ac.getSizeFromDimensionRange(c,0,h)}static getSizeFromDimensionRange(c,h,m){let y=1;for(let S=h;S<m;S++){if(c[S]<0)throw new Error("cannot get valid size from specified dimension range. Most likely the range contains negative values in them.");y*=Number(c[S])}return y}static computeStrides(c){let h=c.length;if(h===0)return[];if(h===1)return[1];let m=new Array(h);m[h-1]=1,m[h-2]=c[h-1];for(let y=h-3;y>=0;--y)m[y]=m[y+1]*c[y+1];return m}static normalizeAxis(c,h){if(c<-h&&c>=h)throw new Error("unsupported axis for this operation.");return c<0?c+h:c}static normalizeAxes(c,h){return c.map(m=>this.normalizeAxis(m,h??c.length))}static sortBasedOnPerm(c,h){return h?h.map(m=>c[m]):c.slice().reverse()}static padShape(c,h){let m=c.length;return c.map((y,S)=>y+h[S]+h[S+m])}static areEqual(c,h){return c.length!==h.length?!1:c.every((m,y)=>m===h[y])}},Ls=class Mo{static adjustPoolAttributes(c,h,m,y,S,b){if(!c&&m.length!==h.length-2)throw new Error("length of specified kernel shapes should be 2 less than length of input dimensions");if(c)for(let E=0;E<h.length-2;E++)E>=m.length?m.push(h[E+2]):m[E]=h[E+2];for(let E=0;E<m.length;E++)if(E<y.length){if(y[E]<0)throw new Error("strides should be greater than or equal to 1")}else y.push(1);for(let E=0;E<m.length;E++)if(E<S.length){if(S[E]<0)throw new Error("dilations should be greater than or equal to 1")}else S.push(1);for(let E=0;E<m.length*2;E++)if(E<b.length){if(b[E]<0)throw new Error("pad should be greater than or equal to 1")}else b.push(0);for(let E=0;E<m.length;E++){if(m[E]<=0)throw new Error("kernel shapes need to be greater than 0");if(b[E]>=m[E]||b[E+m.length]>=m[E])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(c,h,m,y,S,b,E){if(E){if(S.length!==2*(c.length-2))throw new Error("length of pads should be twice the length of data dimensions");if(h.length!==c.length-2)throw new Error("length of strides should be the length of data dimensions");if(y.length!==c.length-2)throw new Error("length of kernel shapes should be the length of data dimensions");for(let A=0;A<c.length-2;A++)Mo.adjustPadAndReturnShape(c[A+(b?1:2)],h[A],m[A],y[A],S,A,A+c.length-2,E)}}static computePoolOutputShape(c,h,m,y,S,b,E){if(h.length<=0)throw new Error("input shape must be of size greater than 0");let A=[h[0],h[1]];return Mo.computeShapeHelper(c,h,A,m,y,S,b,E),A}static computeConvOutputShape(c,h,m,y,S,b,E){if(c.length<=0||h.length<=0)throw new Error("invalid input tensor dims or invalid filter tensor dims");let A=[c[0],h[0]];return Mo.computeShapeHelper(!1,c,A,m,y,S,b,E),A}static computeShapeHelper(c,h,m,y,S,b,E,A){if(c)for(let I=0;I<h.length-2;I++)m.push(1);else for(let I=0;I<h.length-2;I++)m.push(Mo.adjustPadAndReturnShape(h[I+2],y[I],S[I],b[I],E,I,I+h.length-2,A))}static adjustPadAndReturnShape(c,h,m,y,S,b,E,A){let I=m*(y-1)+1;if(A&&A!=="NOTSET")switch(A){case"VALID":return S[b]=0,S[E]=0,Math.floor((c-I)/h+1);case"SAME_LOWER":case"SAME_UPPER":if(m!==1)throw new Error("Dilation not supported for SAME_UPPER or SAME_LOWER");{let $=((c+h-1)/h-1)*h+y-c;return S[b]=Math.floor(A==="SAME_LOWER"?($+1)/2:$/2),S[E]=$-S[b],Math.floor((c+$-y)/h+1)}default:throw new Error("Unsupported AutoPad type")}else return Math.floor((c+S[b]+S[E]-I)/h+1)}},Js=class{static getShapeOfGemmResult(i,c,h,m,y){if(i.length!==2||h.length!==2)throw new Error("shape need to be of size 2");let S,b,E;c?(S=i[1],b=i[0]):(S=i[0],b=i[1]);let A=-1;if(m?(E=h[0],A=1):(E=h[1],A=0),h[A]!==b)throw new Error("dimension mismatch");if(S<=0||E<=0||b<=0)throw new Error("invalid shape specified");if(y&&!bn.isValidBroadcast(y,[S,E]))throw new Error("gemm: invalid bias shape for broadcast");return[S,E,b]}},Jr=-34028234663852886e22,ti=34028234663852886e22}),cr,Tr=_(()=>{ot(),cr=(i,c)=>new(Kr(c))(i)}),Vt,qt,Vi,ka,wn,si,qi,Na,Ma,Ua,ji,Pa=_(()=>{ot(),ur(),Vt=new Map([["float32",32],["float16",16],["int32",32],["uint32",32],["int64",64],["uint64",64],["int8",8],["uint8",8],["int4",4],["uint4",4]]),qt=(i,c)=>{if(c==="int32")return i;let h=Vt.get(c);if(!h)throw new Error(`WebNN backend does not support data type: ${c}`);let m=h/8;if(i.byteLength%m!==0)throw new Error(`Invalid Uint8Array length - must be a multiple of ${m}.`);let y=i.byteLength/m,S=new(Kr(c))(i.buffer,i.byteOffset,y);switch(c){case"int64":case"uint64":{let b=new Int32Array(y);for(let E=0;E<y;E++){let A=S[E];if(A>2147483647n||A<-2147483648n)throw new Error("Can not convert int64 data to int32 - value out of range.");b[E]=Number(A)}return new Uint8Array(b.buffer)}case"int8":case"uint8":case"uint32":{if(c==="uint32"&&S.some(E=>E>2147483647))throw new Error("Can not convert uint32 data to int32 - value out of range.");let b=Int32Array.from(S,Number);return new Uint8Array(b.buffer)}default:throw new Error(`Unsupported data conversion from ${c} to 'int32'`)}},Vi=(i,c)=>{if(c==="int32")return i;if(i.byteLength%4!==0)throw new Error("Invalid Uint8Array length - must be a multiple of 4 (int32).");let h=i.byteLength/4,m=new Int32Array(i.buffer,i.byteOffset,h);switch(c){case"int64":{let y=BigInt64Array.from(m,BigInt);return new Uint8Array(y.buffer)}case"uint64":{if(m.some(S=>S<0))throw new Error("Can not convert int32 data to uin64 - negative value found.");let y=BigUint64Array.from(m,BigInt);return new Uint8Array(y.buffer)}case"int8":{if(m.some(S=>S<-128||S>127))throw new Error("Can not convert int32 data to int8 - value out of range.");let y=Int8Array.from(m,Number);return new Uint8Array(y.buffer)}case"uint8":{if(m.some(y=>y<0||y>255))throw new Error("Can not convert int32 data to uint8 - value out of range.");return Uint8Array.from(m,Number)}case"uint32":{if(m.some(S=>S<0))throw new Error("Can not convert int32 data to uint32 - negative value found.");let y=Uint32Array.from(m,Number);return new Uint8Array(y.buffer)}default:throw new Error(`Unsupported data conversion from 'int32' to ${c}`)}},ka=1,wn=()=>ka++,si=new Map([["int8","int32"],["uint8","int32"],["uint32","int32"],["int64","int32"]]),qi=(i,c)=>{let h=Vt.get(i);if(!h)throw new Error(`WebNN backend does not support data type: ${i}`);return c.length>0?Math.ceil(c.reduce((m,y)=>m*y)*h/8):0},Na=class{constructor(i){this.isDataConverted=!1;let{sessionId:c,context:h,tensor:m,dataType:y,shape:S,fallbackDataType:b}=i;this.sessionId=c,this.mlContext=h,this.mlTensor=m,this.dataType=y,this.tensorShape=S,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 qi(this.dataType,this.tensorShape)}destroy(){bt("verbose",()=>"[WebNN] TensorWrapper.destroy"),this.mlTensor.destroy()}write(i){this.mlContext.writeTensor(this.mlTensor,i)}async read(i){if(this.fallbackDataType){let c=await this.mlContext.readTensor(this.mlTensor),h=Vi(new Uint8Array(c),this.dataType);if(i){(i instanceof ArrayBuffer?new Uint8Array(i):new Uint8Array(i.buffer,i.byteOffset,i.byteLength)).set(h);return}else return h.buffer}else return i?this.mlContext.readTensor(this.mlTensor,i):this.mlContext.readTensor(this.mlTensor)}canReuseTensor(i,c,h){return this.mlContext===i&&this.dataType===c&&this.tensorShape.length===h.length&&this.tensorShape.every((m,y)=>m===h[y])}setIsDataConverted(i){this.isDataConverted=i}},Ma=class{constructor(i,c){this.tensorManager=i,this.wrapper=c}get tensorWrapper(){return this.wrapper}releaseTensor(){this.tensorWrapper&&(this.tensorManager.releaseTensor(this.tensorWrapper),this.wrapper=void 0)}async ensureTensor(i,c,h,m){let y=this.tensorManager.getMLContext(i),S;if(!y.opSupportLimits().input.dataTypes.includes(c)){if(S=si.get(c),!S||!y.opSupportLimits().input.dataTypes.includes(S))throw new Error(`WebNN backend does not support data type: ${c}`);bt("verbose",()=>`[WebNN] TensorIdTracker.ensureTensor: fallback dataType from ${c} to ${S}`)}if(this.wrapper){if(this.wrapper.canReuseTensor(y,c,h))return this.wrapper.tensor;if(m){if(this.wrapper.byteLength!==qi(c,h))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(i,c,h,b,!0,!0,S),m&&this.activeUpload&&(this.wrapper.write(this.activeUpload),this.activeUpload=void 0),this.wrapper.tensor}upload(i){let c=i;if(this.wrapper){if(this.wrapper.fallbackType)if(this.wrapper.fallbackType==="int32")c=qt(i,this.wrapper.type),this.wrapper.setIsDataConverted(!0);else throw new Error(`Unsupported fallback data type: ${this.wrapper.fallbackType}`);if(i.byteLength===this.wrapper.byteLength){this.wrapper.write(c);return}else bt("verbose",()=>"Data size does not match tensor size. Releasing tensor."),this.releaseTensor()}this.activeUpload?this.activeUpload.set(c):this.activeUpload=new Uint8Array(c)}async download(i){var c,h;if(this.activeUpload){let m=(c=this.wrapper)!=null&&c.isDataConverted?Vi(this.activeUpload,(h=this.wrapper)==null?void 0:h.type):this.activeUpload;if(i){i instanceof ArrayBuffer?new Uint8Array(i).set(m):new Uint8Array(i.buffer,i.byteOffset,i.byteLength).set(m);return}else return m.buffer}if(!this.wrapper)throw new Error("Tensor has not been created.");return i?this.wrapper.read(i):this.wrapper.read()}},Ua=class{constructor(i){this.backend=i,this.tensorTrackersById=new Map,this.freeTensors=[],this.externalTensors=new Set}getMLContext(i){let c=this.backend.getMLContext(i);if(!c)throw new Error("MLContext not found for session.");return c}reserveTensorId(){let i=wn();return this.tensorTrackersById.set(i,new Ma(this)),i}releaseTensorId(i){let c=this.tensorTrackersById.get(i);c&&(this.tensorTrackersById.delete(i),c.tensorWrapper&&this.releaseTensor(c.tensorWrapper))}async ensureTensor(i,c,h,m,y){bt("verbose",()=>`[WebNN] TensorManager.ensureTensor {tensorId: ${c}, dataType: ${h}, shape: ${m}, copyOld: ${y}}`);let S=this.tensorTrackersById.get(c);if(!S)throw new Error("Tensor not found.");return S.ensureTensor(i,h,m,y)}upload(i,c){let h=this.tensorTrackersById.get(i);if(!h)throw new Error("Tensor not found.");h.upload(c)}async download(i,c){bt("verbose",()=>`[WebNN] TensorManager.download {tensorId: ${i}, dstBuffer: ${c==null?void 0:c.byteLength}}`);let h=this.tensorTrackersById.get(i);if(!h)throw new Error("Tensor not found.");return h.download(c)}releaseTensorsForSession(i){for(let c of this.freeTensors)c.sessionId===i&&c.destroy();this.freeTensors=this.freeTensors.filter(c=>c.sessionId!==i)}registerTensor(i,c,h,m){let y=this.getMLContext(i),S=wn(),b=new Na({sessionId:i,context:y,tensor:c,dataType:h,shape:m});return this.tensorTrackersById.set(S,new Ma(this,b)),this.externalTensors.add(b),S}async getCachedTensor(i,c,h,m,y,S,b){let E=this.getMLContext(i);for(let[I,$]of this.freeTensors.entries())if($.canReuseTensor(E,c,h)){bt("verbose",()=>`[WebNN] Reusing tensor {dataType: ${c}, ${b?`fallbackDataType: ${b},`:""} shape: ${h}`);let x=this.freeTensors.splice(I,1)[0];return x.sessionId=i,x}bt("verbose",()=>`[WebNN] MLContext.createTensor {dataType: ${c}, ${b?`fallbackDataType: ${b},`:""} shape: ${h}}`);let A=await E.createTensor({dataType:b??c,shape:h,dimensions:h,usage:m,writable:y,readable:S});return new Na({sessionId:i,context:E,tensor:A,dataType:c,shape:h,fallbackDataType:b})}releaseTensor(i){this.externalTensors.has(i)&&this.externalTensors.delete(i),this.freeTensors.push(i)}},ji=(...i)=>new Ua(...i)}),Qr,En,Cn,La=_(()=>{ot(),gr(),Tr(),Pa(),ur(),Qr=new Map([[1,"float32"],[10,"float16"],[6,"int32"],[12,"uint32"],[7,"int64"],[13,"uint64"],[22,"int4"],[21,"uint4"],[3,"int8"],[2,"uint8"],[9,"uint8"]]),En=(i,c)=>{if(i===c)return!0;if(i===void 0||c===void 0)return!1;let h=Object.keys(i).sort(),m=Object.keys(c).sort();return h.length===m.length&&h.every((y,S)=>y===m[S]&&i[y]===c[y])},Cn=class{constructor(i){this.tensorManager=ji(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,ei(i.logLevel,!!i.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw new Error("No active session");return this.activeSessionId}onRunStart(i){bt("verbose",()=>`[WebNN] onRunStart {sessionId: ${i}}`),this.activeSessionId=i}onRunEnd(i){bt("verbose",()=>`[WebNN] onRunEnd {sessionId: ${i}}`);let c=this.temporarySessionTensorIds.get(i);if(c){for(let h of c)bt("verbose",()=>`[WebNN] releasing temporary tensor {tensorId: ${h}}`),this.tensorManager.releaseTensorId(h);this.temporarySessionTensorIds.delete(i),this.activeSessionId=void 0}}async createMLContext(i){if(i instanceof GPUDevice){let h=this.mlContextCache.findIndex(m=>m.gpuDevice===i);if(h!==-1)return this.mlContextCache[h].mlContext;{let m=await navigator.ml.createContext(i);return this.mlContextCache.push({gpuDevice:i,mlContext:m}),m}}else if(i===void 0){let h=this.mlContextCache.findIndex(m=>m.options===void 0&&m.gpuDevice===void 0);if(h!==-1)return this.mlContextCache[h].mlContext;{let m=await navigator.ml.createContext();return this.mlContextCache.push({mlContext:m}),m}}let c=this.mlContextCache.findIndex(h=>En(h.options,i));if(c!==-1)return this.mlContextCache[c].mlContext;{let h=await navigator.ml.createContext(i);return this.mlContextCache.push({options:i,mlContext:h}),h}}registerMLContext(i,c){this.mlContextBySessionId.set(i,c);let h=this.sessionIdsByMLContext.get(c);h||(h=new Set,this.sessionIdsByMLContext.set(c,h)),h.add(i),this.temporaryGraphInputs.length>0&&(this.sessionGraphInputs.set(i,this.temporaryGraphInputs),this.temporaryGraphInputs=[]),this.temporaryGraphOutputs.length>0&&(this.sessionGraphOutputs.set(i,this.temporaryGraphOutputs),this.temporaryGraphOutputs=[])}onReleaseSession(i){this.sessionGraphInputs.delete(i),this.sessionGraphOutputs.delete(i);let c=this.mlContextBySessionId.get(i);if(!c)return;this.tensorManager.releaseTensorsForSession(i),this.mlContextBySessionId.delete(i);let h=this.sessionIdsByMLContext.get(c);if(h.delete(i),h.size===0){this.sessionIdsByMLContext.delete(c);let m=this.mlContextCache.findIndex(y=>y.mlContext===c);m!==-1&&this.mlContextCache.splice(m,1)}}getMLContext(i){return this.mlContextBySessionId.get(i)}reserveTensorId(){return this.tensorManager.reserveTensorId()}releaseTensorId(i){bt("verbose",()=>`[WebNN] releaseTensorId {tensorId: ${i}}`),this.tensorManager.releaseTensorId(i)}async ensureTensor(i,c,h,m,y){let S=Qr.get(h);if(!S)throw new Error(`Unsupported ONNX data type: ${h}`);return this.tensorManager.ensureTensor(i??this.currentSessionId,c,S,m,y)}async createTemporaryTensor(i,c,h){bt("verbose",()=>`[WebNN] createTemporaryTensor {onnxDataType: ${c}, shape: ${h}}`);let m=Qr.get(c);if(!m)throw new Error(`Unsupported ONNX data type: ${c}`);let y=this.tensorManager.reserveTensorId();await this.tensorManager.ensureTensor(i,y,m,h,!1);let S=this.temporarySessionTensorIds.get(i);return S?S.push(y):this.temporarySessionTensorIds.set(i,[y]),y}uploadTensor(i,c){if(!kt().shouldTransferToMLTensor)throw new Error("Trying to upload to a MLTensor while shouldTransferToMLTensor is false");bt("verbose",()=>`[WebNN] uploadTensor {tensorId: ${i}, data: ${c.byteLength}}`),this.tensorManager.upload(i,c)}async downloadTensor(i,c){return this.tensorManager.download(i,c)}createMLTensorDownloader(i,c){return async()=>{let h=await this.tensorManager.download(i);return cr(h,c)}}registerMLTensor(i,c,h,m){let y=Qr.get(h);if(!y)throw new Error(`Unsupported ONNX data type: ${h}`);let S=this.tensorManager.registerTensor(i,c,y,m);return bt("verbose",()=>`[WebNN] registerMLTensor {tensor: ${c}, dataType: ${y}, dimensions: ${m}} -> {tensorId: ${S}}`),S}registerMLConstant(i,c,h,m,y,S,b=!1){if(!S)throw new Error("External mounted files are not available.");let E=i;i.startsWith("./")&&(E=i.substring(2));let A=S.get(E);if(!A)throw new Error(`File with name ${E} not found in preloaded files.`);if(c+h>A.byteLength)throw new Error("Out of bounds: data offset and length exceed the external file data size.");let I=A.slice(c,c+h).buffer,$;switch(y.dataType){case"float32":$=new Float32Array(I);break;case"float16":$=typeof Float16Array<"u"&&Float16Array.from?new Float16Array(I):new Uint16Array(I);break;case"int32":$=new Int32Array(I);break;case"uint32":$=new Uint32Array(I);break;case"int64":if(b){let x=qt(new Uint8Array(I),"int64");$=new Int32Array(x.buffer),y.dataType="int32"}else $=new BigInt64Array(I);break;case"uint64":$=new BigUint64Array(I);break;case"int8":$=new Int8Array(I);break;case"int4":case"uint4":case"uint8":$=new Uint8Array(I);break;default:throw new Error(`Unsupported data type: ${y.dataType} in creating WebNN Constant from external data.`)}return bt("verbose",()=>`[WebNN] registerMLConstant {dataType: ${y.dataType}, shape: ${y.shape}}} ${b?"(Note: it was int64 data type and registered to int32 as workaround)":""}`),m.constant(y,$)}registerGraphInput(i){this.temporaryGraphInputs.push(i)}registerGraphOutput(i){this.temporaryGraphOutputs.push(i)}isGraphInput(i,c){let h=this.sessionGraphInputs.get(i);return h?h.includes(c):!1}isGraphOutput(i,c){let h=this.sessionGraphOutputs.get(i);return h?h.includes(c):!1}isGraphInputOutputTypeSupported(i,c,h=!0){let m=this.mlContextBySessionId.get(i),y=Qr.get(vr(c));return typeof y>"u"?!1:h?!!(m!=null&&m.opSupportLimits().input.dataTypes.includes(y)):!!(m!=null&&m.opSupportLimits().output.dataTypes.includes(y))}flush(){}}}),An=_(()=>{}),In,ri,ni,Ha,bl,Xr,Zr,Gi,Rn,Fa=_(()=>{ur(),An(),In=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]]),ri=[],ni=i=>Math.ceil(Number(i)/16)*16,Ha=i=>{for(let c=0;c<ri.length;c++){let h=ri[c];if(i<=h)return h}return Math.ceil(i/16)*16},bl=1,Xr=()=>bl++,Zr=async(i,c,h,m)=>{let y=ni(h),S=i.device.createBuffer({size:y,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});try{let b=i.getCommandEncoder();i.endComputePass(),b.copyBufferToBuffer(c,0,S,0,y),i.flush(),await S.mapAsync(GPUMapMode.READ);let E=S.getMappedRange();if(m){let A=m();return A.set(new Uint8Array(E,0,h)),A}else return new Uint8Array(E.slice(0,h))}finally{S.destroy()}},Gi=class{constructor(i){this.backend=i,this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.buffersPending=[],this.capturedPendingBuffers=new Map;for(let[c]of In)ri.push(c),this.freeBuffers.set(c,[]),this.freeUniformBuffers.set(c,[]);this.sessionCount=0}upload(i,c){let h=c.buffer,m=c.byteOffset,y=c.byteLength,S=ni(y),b=this.storageCache.get(i);if(!b)throw new Error("gpu data for uploading does not exist");if(Number(b.originalSize)!==y)throw new Error(`inconsistent data size. gpu data size=${b.originalSize}, data size=${y}`);let E=this.backend.device.createBuffer({mappedAtCreation:!0,size:S,usage:GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC}),A=E.getMappedRange();new Uint8Array(A).set(new Uint8Array(h,m,y)),E.unmap();let I=this.backend.device.createCommandEncoder();I.copyBufferToBuffer(E,0,b.gpuData.buffer,0,S),this.backend.device.queue.submit([I.finish()]),E.destroy(),bt("verbose",()=>`[WebGPU] GpuDataManager.upload(id=${i})`)}memcpy(i,c){let h=this.storageCache.get(i);if(!h)throw new Error("source gpu data for memcpy does not exist");let m=this.storageCache.get(c);if(!m)throw new Error("destination gpu data for memcpy does not exist");if(h.originalSize!==m.originalSize)throw new Error("inconsistent source and destination gpu data size");let y=ni(h.originalSize),S=this.backend.getCommandEncoder();this.backend.endComputePass(),S.copyBufferToBuffer(h.gpuData.buffer,0,m.gpuData.buffer,0,y)}registerExternalBuffer(i,c,h){let m;if(h){if(m=h[0],i===h[1])return bt("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${c}) => 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.
162
+ */(function(f,t){var r=(()=>{var l=Object.defineProperty,u=Object.getOwnPropertyDescriptor,s=Object.getOwnPropertyNames,n=Object.prototype.hasOwnProperty,g=(i=>typeof yl<"u"?yl:typeof Proxy<"u"?new Proxy(i,{get:(c,h)=>(typeof yl<"u"?yl:c)[h]}):i)(function(i){if(typeof yl<"u")return yl.apply(this,arguments);throw Error('Dynamic require of "'+i+'" is not supported')}),_=(i,c)=>()=>(i&&(c=i(i=0)),c),v=(i,c)=>{for(var h in c)l(i,h,{get:c[h],enumerable:!0})},C=(i,c,h,m)=>{if(c&&typeof c=="object"||typeof c=="function")for(let y of s(c))!n.call(i,y)&&y!==h&&l(i,y,{get:()=>c[y],enumerable:!(m=u(c,y))||m.enumerable});return i},R=i=>C(l({},"__esModule",{value:!0}),i),D,H,F,q,G,te=_(()=>{D=new Map,H=[],F=(i,c,h)=>{if(c&&typeof c.init=="function"&&typeof c.createInferenceSessionHandler=="function"){let m=D.get(i);if(m===void 0)D.set(i,{backend:c,priority:h});else{if(m.priority>h)return;if(m.priority===h&&m.backend!==c)throw new Error(`cannot register backend "${i}" using priority ${h}`)}if(h>=0){let y=H.indexOf(i);y!==-1&&H.splice(y,1);for(let S=0;S<H.length;S++)if(D.get(H[S]).priority<=h){H.splice(S,0,i);return}H.push(i)}return}throw new TypeError("not a valid backend")},q=async i=>{let c=D.get(i);if(!c)return"backend not found.";if(c.initialized)return c.backend;if(c.aborted)return c.error;{let h=!!c.initPromise;try{return h||(c.initPromise=c.backend.init(i)),await c.initPromise,c.initialized=!0,c.backend}catch(m){return h||(c.error=`${m}`,c.aborted=!0),c.error}finally{delete c.initPromise}}},G=async i=>{let c=i.executionProviders||[],h=c.map(A=>typeof A=="string"?A:A.name),m=h.length===0?H:h,y,S=[],b=new Set;for(let A of m){let I=await q(A);typeof I=="string"?S.push({name:A,err:I}):(y||(y=I),y===I&&b.add(A))}if(!y)throw new Error(`no available backend found. ERR: ${S.map(A=>`[${A.name}] ${A.err}`).join(", ")}`);for(let{name:A,err:I}of S)h.includes(A)&&console.warn(`removing requested execution provider "${A}" from session options because it is not available: ${I}`);let E=c.filter(A=>b.has(typeof A=="string"?A:A.name));return[y,new Proxy(i,{get:(A,I)=>I==="executionProviders"?E:Reflect.get(A,I)})]}}),X=_(()=>{te()}),we,Q=_(()=>{we="1.23.0"}),re,ke,Ne=_(()=>{Q(),re="warning",ke={wasm:{},webgl:{},webgpu:{},versions:{common:we},set logLevel(i){if(i!==void 0){if(typeof i!="string"||["verbose","info","warning","error","fatal"].indexOf(i)===-1)throw new Error(`Unsupported logging level: ${i}`);re=i}},get logLevel(){return re}},Object.defineProperty(ke,"logLevel",{enumerable:!0})}),Z,se=_(()=>{Ne(),Z=ke}),pe,me,be=_(()=>{pe=(i,c)=>{let h=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);h.width=i.dims[3],h.height=i.dims[2];let m=h.getContext("2d");if(m!=null){let y,S;(c==null?void 0:c.tensorLayout)!==void 0&&c.tensorLayout==="NHWC"?(y=i.dims[2],S=i.dims[3]):(y=i.dims[3],S=i.dims[2]);let b=(c==null?void 0:c.format)!==void 0?c.format:"RGB",E=c==null?void 0:c.norm,A,I;E===void 0||E.mean===void 0?A=[255,255,255,255]:typeof E.mean=="number"?A=[E.mean,E.mean,E.mean,E.mean]:(A=[E.mean[0],E.mean[1],E.mean[2],0],E.mean[3]!==void 0&&(A[3]=E.mean[3])),E===void 0||E.bias===void 0?I=[0,0,0,0]:typeof E.bias=="number"?I=[E.bias,E.bias,E.bias,E.bias]:(I=[E.bias[0],E.bias[1],E.bias[2],0],E.bias[3]!==void 0&&(I[3]=E.bias[3]));let $=S*y,x=0,k=$,N=$*2,M=-1;b==="RGBA"?(x=0,k=$,N=$*2,M=$*3):b==="RGB"?(x=0,k=$,N=$*2):b==="RBG"&&(x=0,N=$,k=$*2);for(let U=0;U<S;U++)for(let z=0;z<y;z++){let L=(i.data[x++]-I[0])*A[0],P=(i.data[k++]-I[1])*A[1],j=(i.data[N++]-I[2])*A[2],V=M===-1?255:(i.data[M++]-I[3])*A[3];m.fillStyle="rgba("+L+","+P+","+j+","+V+")",m.fillRect(z,U,1,1)}if("toDataURL"in h)return h.toDataURL();throw new Error("toDataURL is not supported")}else throw new Error("Can not access image data")},me=(i,c)=>{let h=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),m;if(h!=null){let y,S,b;(c==null?void 0:c.tensorLayout)!==void 0&&c.tensorLayout==="NHWC"?(y=i.dims[2],S=i.dims[1],b=i.dims[3]):(y=i.dims[3],S=i.dims[2],b=i.dims[1]);let E=c!==void 0&&c.format!==void 0?c.format:"RGB",A=c==null?void 0:c.norm,I,$;A===void 0||A.mean===void 0?I=[255,255,255,255]:typeof A.mean=="number"?I=[A.mean,A.mean,A.mean,A.mean]:(I=[A.mean[0],A.mean[1],A.mean[2],255],A.mean[3]!==void 0&&(I[3]=A.mean[3])),A===void 0||A.bias===void 0?$=[0,0,0,0]:typeof A.bias=="number"?$=[A.bias,A.bias,A.bias,A.bias]:($=[A.bias[0],A.bias[1],A.bias[2],0],A.bias[3]!==void 0&&($[3]=A.bias[3]));let x=S*y;if(c!==void 0&&(c.format!==void 0&&b===4&&c.format!=="RGBA"||b===3&&c.format!=="RGB"&&c.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let k=4,N=0,M=1,U=2,z=3,L=0,P=x,j=x*2,V=-1;E==="RGBA"?(L=0,P=x,j=x*2,V=x*3):E==="RGB"?(L=0,P=x,j=x*2):E==="RBG"&&(L=0,j=x,P=x*2),m=h.createImageData(y,S);for(let Y=0;Y<S*y;N+=k,M+=k,U+=k,z+=k,Y++)m.data[N]=(i.data[L++]-$[0])*I[0],m.data[M]=(i.data[P++]-$[1])*I[1],m.data[U]=(i.data[j++]-$[2])*I[2],m.data[z]=V===-1?255:(i.data[V++]-$[3])*I[3]}else throw new Error("Can not access image data");return m}}),_e,Ae,le,oe,Oe,rs,Re=_(()=>{Zt(),_e=(i,c)=>{if(i===void 0)throw new Error("Image buffer must be defined");if(c.height===void 0||c.width===void 0)throw new Error("Image height and width must be defined");if(c.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:h,width:m}=c,y=c.norm??{mean:255,bias:0},S,b;typeof y.mean=="number"?S=[y.mean,y.mean,y.mean,y.mean]:S=[y.mean[0],y.mean[1],y.mean[2],y.mean[3]??255],typeof y.bias=="number"?b=[y.bias,y.bias,y.bias,y.bias]:b=[y.bias[0],y.bias[1],y.bias[2],y.bias[3]??0];let E=c.format!==void 0?c.format:"RGBA",A=c.tensorFormat!==void 0&&c.tensorFormat!==void 0?c.tensorFormat:"RGB",I=h*m,$=A==="RGBA"?new Float32Array(I*4):new Float32Array(I*3),x=4,k=0,N=1,M=2,U=3,z=0,L=I,P=I*2,j=-1;E==="RGB"&&(x=3,k=0,N=1,M=2,U=-1),A==="RGBA"?j=I*3:A==="RBG"?(z=0,P=I,L=I*2):A==="BGR"&&(P=0,L=I,z=I*2);for(let V=0;V<I;V++,k+=x,M+=x,N+=x,U+=x)$[z++]=(i[k]+b[0])/S[0],$[L++]=(i[N]+b[1])/S[1],$[P++]=(i[M]+b[2])/S[2],j!==-1&&U!==-1&&($[j++]=(i[U]+b[3])/S[3]);return A==="RGBA"?new Ye("float32",$,[1,4,h,m]):new Ye("float32",$,[1,3,h,m])},Ae=async(i,c)=>{let h=typeof HTMLImageElement<"u"&&i instanceof HTMLImageElement,m=typeof ImageData<"u"&&i instanceof ImageData,y=typeof ImageBitmap<"u"&&i instanceof ImageBitmap,S=typeof i=="string",b,E=c??{},A=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},I=$=>typeof HTMLCanvasElement<"u"&&$ instanceof HTMLCanvasElement||$ instanceof OffscreenCanvas?$.getContext("2d"):null;if(h){let $=A();$.width=i.width,$.height=i.height;let x=I($);if(x!=null){let k=i.height,N=i.width;if(c!==void 0&&c.resizedHeight!==void 0&&c.resizedWidth!==void 0&&(k=c.resizedHeight,N=c.resizedWidth),c!==void 0){if(E=c,c.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");E.tensorFormat="RGBA",E.height=k,E.width=N}else E.tensorFormat="RGBA",E.height=k,E.width=N;x.drawImage(i,0,0),b=x.getImageData(0,0,N,k).data}else throw new Error("Can not access image data")}else if(m){let $,x;if(c!==void 0&&c.resizedWidth!==void 0&&c.resizedHeight!==void 0?($=c.resizedHeight,x=c.resizedWidth):($=i.height,x=i.width),c!==void 0&&(E=c),E.format="RGBA",E.height=$,E.width=x,c!==void 0){let k=A();k.width=x,k.height=$;let N=I(k);if(N!=null)N.putImageData(i,0,0),b=N.getImageData(0,0,x,$).data;else throw new Error("Can not access image data")}else b=i.data}else if(y){if(c===void 0)throw new Error("Please provide image config with format for Imagebitmap");let $=A();$.width=i.width,$.height=i.height;let x=I($);if(x!=null){let k=i.height,N=i.width;return x.drawImage(i,0,0,N,k),b=x.getImageData(0,0,N,k).data,E.height=k,E.width=N,_e(b,E)}else throw new Error("Can not access image data")}else{if(S)return new Promise(($,x)=>{let k=A(),N=I(k);if(!i||!N)return x();let M=new Image;M.crossOrigin="Anonymous",M.src=i,M.onload=()=>{k.width=M.width,k.height=M.height,N.drawImage(M,0,0,k.width,k.height);let U=N.getImageData(0,0,k.width,k.height);E.height=k.height,E.width=k.width,$(_e(U.data,E))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(b!==void 0)return _e(b,E);throw new Error("Input data provided is not supported - aborted tensor creation")},le=(i,c)=>{let{width:h,height:m,download:y,dispose:S}=c,b=[1,m,h,4];return new Ye({location:"texture",type:"float32",texture:i,dims:b,download:y,dispose:S})},oe=(i,c)=>{let{dataType:h,dims:m,download:y,dispose:S}=c;return new Ye({location:"gpu-buffer",type:h??"float32",gpuBuffer:i,dims:m,download:y,dispose:S})},Oe=(i,c)=>{let{dataType:h,dims:m,download:y,dispose:S}=c;return new Ye({location:"ml-tensor",type:h??"float32",mlTensor:i,dims:m,download:y,dispose:S})},rs=(i,c,h)=>new Ye({location:"cpu-pinned",type:i,data:c,dims:h??[c.length]})}),ye,ge,Le,et,vt=_(()=>{ye=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),ge=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),Le=!1,et=()=>{if(!Le){Le=!0;let i=typeof BigInt64Array<"u"&&BigInt64Array.from,c=typeof BigUint64Array<"u"&&BigUint64Array.from,h=globalThis.Float16Array,m=typeof h<"u"&&h.from;i&&(ye.set("int64",BigInt64Array),ge.set(BigInt64Array,"int64")),c&&(ye.set("uint64",BigUint64Array),ge.set(BigUint64Array,"uint64")),m?(ye.set("float16",h),ge.set(h,"float16")):ye.set("float16",Uint16Array)}}}),xt,dt,ze=_(()=>{Zt(),xt=i=>{let c=1;for(let h=0;h<i.length;h++){let m=i[h];if(typeof m!="number"||!Number.isSafeInteger(m))throw new TypeError(`dims[${h}] must be an integer, got: ${m}`);if(m<0)throw new RangeError(`dims[${h}] must be a non-negative integer, got: ${m}`);c*=m}return c},dt=(i,c)=>{switch(i.location){case"cpu":return new Ye(i.type,i.data,c);case"cpu-pinned":return new Ye({location:"cpu-pinned",data:i.data,type:i.type,dims:c});case"texture":return new Ye({location:"texture",texture:i.texture,type:i.type,dims:c});case"gpu-buffer":return new Ye({location:"gpu-buffer",gpuBuffer:i.gpuBuffer,type:i.type,dims:c});case"ml-tensor":return new Ye({location:"ml-tensor",mlTensor:i.mlTensor,type:i.type,dims:c});default:throw new Error(`tensorReshape: tensor location ${i.location} is not supported`)}}}),Ye,Zt=_(()=>{be(),Re(),vt(),ze(),Ye=class{constructor(i,c,h){et();let m,y;if(typeof i=="object"&&"location"in i)switch(this.dataLocation=i.location,m=i.type,y=i.dims,i.location){case"cpu-pinned":{let b=ye.get(m);if(!b)throw new TypeError(`unsupported type "${m}" to create tensor from pinned buffer`);if(!(i.data instanceof b))throw new TypeError(`buffer should be of type ${b.name}`);this.cpuData=i.data;break}case"texture":{if(m!=="float32")throw new TypeError(`unsupported type "${m}" to create tensor from texture`);this.gpuTextureData=i.texture,this.downloader=i.download,this.disposer=i.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=i.gpuBuffer,this.downloader=i.download,this.disposer=i.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=i.mlTensor,this.downloader=i.download,this.disposer=i.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let b,E;if(typeof i=="string")if(m=i,E=h,i==="string"){if(!Array.isArray(c))throw new TypeError("A string tensor's data must be a string array.");b=c}else{let A=ye.get(i);if(A===void 0)throw new TypeError(`Unsupported tensor type: ${i}.`);if(Array.isArray(c)){if(i==="float16"&&A===Uint16Array||i==="uint4"||i==="int4")throw new TypeError(`Creating a ${i} tensor from number array is not supported. Please use ${A.name} as data.`);i==="uint64"||i==="int64"?b=A.from(c,BigInt):b=A.from(c)}else if(c instanceof A)b=c;else if(c instanceof Uint8ClampedArray)if(i==="uint8")b=Uint8Array.from(c);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(i==="float16"&&c instanceof Uint16Array&&A!==Uint16Array)b=new globalThis.Float16Array(c.buffer,c.byteOffset,c.length);else throw new TypeError(`A ${m} tensor's data must be type of ${A}`)}else if(E=c,Array.isArray(i)){if(i.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let A=typeof i[0];if(A==="string")m="string",b=i;else if(A==="boolean")m="bool",b=Uint8Array.from(i);else throw new TypeError(`Invalid element type of data array: ${A}.`)}else if(i instanceof Uint8ClampedArray)m="uint8",b=Uint8Array.from(i);else{let A=ge.get(i.constructor);if(A===void 0)throw new TypeError(`Unsupported type for tensor data: ${i.constructor}.`);m=A,b=i}if(E===void 0)E=[b.length];else if(!Array.isArray(E))throw new TypeError("A tensor's dims must be a number array");y=E,this.cpuData=b,this.dataLocation="cpu"}let S=xt(y);if(this.cpuData&&S!==this.cpuData.length&&!((m==="uint4"||m==="int4")&&Math.ceil(S/2)===this.cpuData.length))throw new Error(`Tensor's size(${S}) does not match data length(${this.cpuData.length}).`);this.type=m,this.dims=y,this.size=S}static async fromImage(i,c){return Ae(i,c)}static fromTexture(i,c){return le(i,c)}static fromGpuBuffer(i,c){return oe(i,c)}static fromMLTensor(i,c){return Oe(i,c)}static fromPinnedBuffer(i,c,h){return rs(i,c,h)}toDataURL(i){return pe(this,i)}toImageData(i){return me(this,i)}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(i){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 c=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=c,i&&this.disposer&&(this.disposer(),this.disposer=void 0),c}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(i){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return dt(this,i)}}}),Mt,nt=_(()=>{Zt(),Mt=Ye}),rt,gt,ft,Fe,He,qe,yt=_(()=>{Ne(),rt=(i,c)=>{(typeof ke.trace>"u"?!ke.wasm.trace:!ke.trace)||console.timeStamp(`${i}::ORT::${c}`)},gt=(i,c)=>{var y;let h=((y=new Error().stack)==null?void 0:y.split(/\r\n|\r|\n/g))||[],m=!1;for(let S=0;S<h.length;S++){if(m&&!h[S].includes("TRACE_FUNC")){let b=`FUNC_${i}::${h[S].trim().split(" ")[1]}`;c&&(b+=`::${c}`),rt("CPU",b);return}h[S].includes("TRACE_FUNC")&&(m=!0)}},ft=i=>{(typeof ke.trace>"u"?!ke.wasm.trace:!ke.trace)||gt("BEGIN",i)},Fe=i=>{(typeof ke.trace>"u"?!ke.wasm.trace:!ke.trace)||gt("END",i)},He=i=>{(typeof ke.trace>"u"?!ke.wasm.trace:!ke.trace)||console.time(`ORT::${i}`)},qe=i=>{(typeof ke.trace>"u"?!ke.wasm.trace:!ke.trace)||console.timeEnd(`ORT::${i}`)}}),Ct,ns=_(()=>{te(),nt(),yt(),Ct=class GT{constructor(c){this.handler=c}async run(c,h,m){ft(),He("InferenceSession.run");let y={},S={};if(typeof c!="object"||c===null||c instanceof Mt||Array.isArray(c))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let b=!0;if(typeof h=="object"){if(h===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(h instanceof Mt)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(h)){if(h.length===0)throw new TypeError("'fetches' cannot be an empty array.");b=!1;for(let I of h){if(typeof I!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(I)===-1)throw new RangeError(`'fetches' contains invalid output name: ${I}.`);y[I]=null}if(typeof m=="object"&&m!==null)S=m;else if(typeof m<"u")throw new TypeError("'options' must be an object.")}else{let I=!1,$=Object.getOwnPropertyNames(h);for(let x of this.outputNames)if($.indexOf(x)!==-1){let k=h[x];(k===null||k instanceof Mt)&&(I=!0,b=!1,y[x]=k)}if(I){if(typeof m=="object"&&m!==null)S=m;else if(typeof m<"u")throw new TypeError("'options' must be an object.")}else S=h}}else if(typeof h<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let I of this.inputNames)if(typeof c[I]>"u")throw new Error(`input '${I}' is missing in 'feeds'.`);if(b)for(let I of this.outputNames)y[I]=null;let E=await this.handler.run(c,y,S),A={};for(let I in E)if(Object.hasOwnProperty.call(E,I)){let $=E[I];$ instanceof Mt?A[I]=$:A[I]=new Mt($.type,$.data,$.dims)}return qe("InferenceSession.run"),Fe(),A}async release(){return this.handler.dispose()}static async create(c,h,m,y){ft(),He("InferenceSession.create");let S,b={};if(typeof c=="string"){if(S=c,typeof h=="object"&&h!==null)b=h;else if(typeof h<"u")throw new TypeError("'options' must be an object.")}else if(c instanceof Uint8Array){if(S=c,typeof h=="object"&&h!==null)b=h;else if(typeof h<"u")throw new TypeError("'options' must be an object.")}else if(c instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&c instanceof SharedArrayBuffer){let $=c,x=0,k=c.byteLength;if(typeof h=="object"&&h!==null)b=h;else if(typeof h=="number"){if(x=h,!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(k=c.byteLength-x,typeof m=="number"){if(k=m,!Number.isSafeInteger(k))throw new RangeError("'byteLength' must be an integer.");if(k<=0||x+k>$.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${$.byteLength-x}].`);if(typeof y=="object"&&y!==null)b=y;else if(typeof y<"u")throw new TypeError("'options' must be an object.")}else if(typeof m<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof h<"u")throw new TypeError("'options' must be an object.");S=new Uint8Array($,x,k)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[E,A]=await G(b),I=await E.createInferenceSessionHandler(S,A);return qe("InferenceSession.create"),Fe(),new GT(I)}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}}}),Ut,ar=_(()=>{ns(),Ut=Ct}),vs=_(()=>{}),Oi=_(()=>{}),Di=_(()=>{}),zn=_(()=>{}),pr={};v(pr,{InferenceSession:()=>Ut,TRACE:()=>rt,TRACE_EVENT_BEGIN:()=>He,TRACE_EVENT_END:()=>qe,TRACE_FUNC_BEGIN:()=>ft,TRACE_FUNC_END:()=>Fe,Tensor:()=>Mt,env:()=>Z,registerBackend:()=>F});var as=_(()=>{X(),se(),ar(),nt(),vs(),Oi(),yt(),Di(),zn()}),Pr=_(()=>{}),Vn={};v(Vn,{default:()=>Qe});var pn,Lr,Qe,Ve=_(()=>{var i;RT(),gr(),Yn(),pn="ort-wasm-proxy-worker",Lr=((i=globalThis.self)==null?void 0:i.name)===pn,Lr&&(self.onmessage=c=>{let{type:h,in:m}=c.data;try{switch(h){case"init-wasm":Vr(m.wasm).then(()=>{Rf(m).then(()=>{postMessage({type:h})},y=>{postMessage({type:h,err:y})})},y=>{postMessage({type:h,err:y})});break;case"init-ep":{let{epName:y,env:S}=m;$f(S,y).then(()=>{postMessage({type:h})},b=>{postMessage({type:h,err:b})});break}case"copy-from":{let{buffer:y}=m,S=rc(y);postMessage({type:h,out:S});break}case"create":{let{model:y,options:S}=m;Of(y,S).then(b=>{postMessage({type:h,out:b})},b=>{postMessage({type:h,err:b})});break}case"release":Df(m),postMessage({type:h});break;case"run":{let{sessionId:y,inputIndices:S,inputs:b,outputIndices:E,options:A}=m;Nf(y,S,b,E,new Array(E.length).fill(null),A).then(I=>{I.some($=>$[3]!=="cpu")?postMessage({type:h,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:h,out:I},Uf([...b,...I]))},I=>{postMessage({type:h,err:I})});break}case"end-profiling":Mf(m),postMessage({type:h});break;default:}}catch(y){postMessage({type:h,err:y})}}),Qe=Lr?null:c=>new Worker(c??os,{type:"classic",name:pn})}),ls,lr,os,qn,Hr,jn,ki,Gn,Ni,Wn,Mi,Kn,Ui,Yn=_(()=>{Pr(),ls=typeof location>"u"?void 0:location.origin,lr=()=>{var i,c;return typeof document<"u"?(i=document.currentScript)==null?void 0:i.src:typeof self<"u"?(c=self.location)==null?void 0:c.href:void 0},os=lr(),qn=()=>{if(os&&!os.startsWith("blob:"))return os.substring(0,os.lastIndexOf("/")+1)},Hr=(i,c)=>{try{let h=c??os;return(h?new URL(i,h):new URL(i)).origin===ls}catch{return!1}},jn=(i,c)=>{let h=c??os;try{return(h?new URL(i,h):new URL(i)).href}catch{return}},ki=(i,c)=>`${c??"./"}${i}`,Gn=async i=>{let c=await(await fetch(i,{credentials:"same-origin"})).blob();return URL.createObjectURL(c)},Ni=async i=>(await import(i)).default,Wn=(Ve(),R(Vn)).default,Mi=async()=>{if(!os)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(Hr(os))return[void 0,Wn()];let i=await Gn(os);return[i,Wn(i)]},Kn=void 0,Ui=async(i,c,h,m)=>{let y=Kn&&!(i||c);if(y)if(os)y=Hr(os);else if(m&&!h)y=!0;else throw new Error("cannot determine the script source URL.");if(y)return[void 0,Kn];{let S="ort-wasm-simd-threaded.jsep.mjs",b=i??jn(S,c),E=h&&b&&!Hr(b,c),A=E?await Gn(b):b??ki(S,c);return[E?A:void 0,await Ni(A)]}}}),Ar,mr,Fr,Br,mn,Pi,zr,Vr,kt,gr=_(()=>{Yn(),mr=!1,Fr=!1,Br=!1,mn=()=>{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}},Pi=()=>{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}},zr=()=>{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}},Vr=async i=>{if(mr)return Promise.resolve();if(Fr)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(Br)throw new Error("previous call to 'initializeWebAssembly()' failed.");Fr=!0;let c=i.initTimeout,h=i.numThreads;if(i.simd!==!1){if(i.simd==="relaxed"){if(!zr())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!Pi())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let m=mn();h>1&&!m&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+h+", 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."),i.numThreads=h=1);let y=i.wasmPaths,S=typeof y=="string"?y:void 0,b=y==null?void 0:y.mjs,E=(b==null?void 0:b.href)??b,A=y==null?void 0:y.wasm,I=(A==null?void 0:A.href)??A,$=i.wasmBinary,[x,k]=await Ui(E,S,h>1,!!$||!!I),N=!1,M=[];if(c>0&&M.push(new Promise(U=>{setTimeout(()=>{N=!0,U()},c)})),M.push(new Promise((U,z)=>{let L={numThreads:h};if($)L.wasmBinary=$;else if(I||S)L.locateFile=P=>I??S+P;else if(E&&E.indexOf("blob:")!==0)L.locateFile=P=>new URL(P,E).href;else if(x){let P=qn();P&&(L.locateFile=j=>P+j)}k(L).then(P=>{Fr=!1,mr=!0,Ar=P,U(),x&&URL.revokeObjectURL(x)},P=>{Fr=!1,Br=!0,z(P)})})),await Promise.race(M),N)throw new Error(`WebAssembly backend initializing failed due to timeout: ${c}ms`)},kt=()=>{if(mr&&Ar)return Ar;throw new Error("WebAssembly is not initialized yet.")}}),bs,qr,It,jr=_(()=>{gr(),bs=(i,c)=>{let h=kt(),m=h.lengthBytesUTF8(i)+1,y=h._malloc(m);return h.stringToUTF8(i,y,m),c.push(y),y},qr=(i,c,h,m)=>{if(typeof i=="object"&&i!==null){if(h.has(i))throw new Error("Circular reference in options");h.add(i)}Object.entries(i).forEach(([y,S])=>{let b=c?c+y:y;if(typeof S=="object")qr(S,b+".",h,m);else if(typeof S=="string"||typeof S=="number")m(b,S.toString());else if(typeof S=="boolean")m(b,S?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof S}`)})},It=i=>{let c=kt(),h=c.stackSave();try{let m=c.PTR_SIZE,y=c.stackAlloc(2*m);c._OrtGetLastError(y,y+m);let S=Number(c.getValue(y,m===4?"i32":"i64")),b=c.getValue(y+m,"*"),E=b?c.UTF8ToString(b):"";throw new Error(`${i} ERROR_CODE: ${S}, ERROR_MESSAGE: ${E}`)}finally{c.stackRestore(h)}}}),gn,vn=_(()=>{gr(),jr(),gn=i=>{let c=kt(),h=0,m=[],y=i||{};try{if((i==null?void 0:i.logSeverityLevel)===void 0)y.logSeverityLevel=2;else if(typeof i.logSeverityLevel!="number"||!Number.isInteger(i.logSeverityLevel)||i.logSeverityLevel<0||i.logSeverityLevel>4)throw new Error(`log severity level is not valid: ${i.logSeverityLevel}`);if((i==null?void 0:i.logVerbosityLevel)===void 0)y.logVerbosityLevel=0;else if(typeof i.logVerbosityLevel!="number"||!Number.isInteger(i.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${i.logVerbosityLevel}`);(i==null?void 0:i.terminate)===void 0&&(y.terminate=!1);let S=0;return(i==null?void 0:i.tag)!==void 0&&(S=bs(i.tag,m)),h=c._OrtCreateRunOptions(y.logSeverityLevel,y.logVerbosityLevel,!!y.terminate,S),h===0&&It("Can't create run options."),(i==null?void 0:i.extra)!==void 0&&qr(i.extra,"",new WeakSet,(b,E)=>{let A=bs(b,m),I=bs(E,m);c._OrtAddRunConfigEntry(h,A,I)!==0&&It(`Can't set a run config entry: ${b} - ${E}.`)}),[h,m]}catch(S){throw h!==0&&c._OrtReleaseRunOptions(h),m.forEach(b=>c._free(b)),S}}}),Gr,Li,yn,or,Ir,Wr,Da=_(()=>{gr(),jr(),Gr=i=>{switch(i){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: ${i}`)}},Li=i=>{switch(i){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${i}`)}},yn=i=>{i.extra||(i.extra={}),i.extra.session||(i.extra.session={});let c=i.extra.session;c.use_ort_model_bytes_directly||(c.use_ort_model_bytes_directly="1"),i.executionProviders&&i.executionProviders.some(h=>(typeof h=="string"?h:h.name)==="webgpu")&&(i.enableMemPattern=!1)},or=(i,c,h,m)=>{let y=bs(c,m),S=bs(h,m);kt()._OrtAddSessionConfigEntry(i,y,S)!==0&&It(`Can't set a session config entry: ${c} - ${h}.`)},Ir=async(i,c,h)=>{for(let m of c){let y=typeof m=="string"?m:m.name,S=[];switch(y){case"webnn":if(y="WEBNN",typeof m!="string"){let $=m==null?void 0:m.deviceType;$&&or(i,"deviceType",$,h)}break;case"webgpu":if(y="JS",typeof m!="string"){let $=m;if($!=null&&$.preferredLayout){if($.preferredLayout!=="NCHW"&&$.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${$.preferredLayout}`);or(i,"preferredLayout",$.preferredLayout,h)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${y}`)}let b=bs(y,h),E=S.length,A=0,I=0;if(E>0){A=kt()._malloc(E*kt().PTR_SIZE),h.push(A),I=kt()._malloc(E*kt().PTR_SIZE),h.push(I);for(let $=0;$<E;$++)kt().setValue(A+$*kt().PTR_SIZE,S[$][0],"*"),kt().setValue(I+$*kt().PTR_SIZE,S[$][1],"*")}await kt()._OrtAppendExecutionProvider(i,b,A,I,E)!==0&&It(`Can't append execution provider: ${y}.`)}},Wr=async i=>{let c=kt(),h=0,m=[],y=i||{};yn(y);try{let S=Gr(y.graphOptimizationLevel??"all"),b=Li(y.executionMode??"sequential"),E=typeof y.logId=="string"?bs(y.logId,m):0,A=y.logSeverityLevel??2;if(!Number.isInteger(A)||A<0||A>4)throw new Error(`log severity level is not valid: ${A}`);let I=y.logVerbosityLevel??0;if(!Number.isInteger(I)||I<0||I>4)throw new Error(`log verbosity level is not valid: ${I}`);let $=typeof y.optimizedModelFilePath=="string"?bs(y.optimizedModelFilePath,m):0;if(h=c._OrtCreateSessionOptions(S,!!y.enableCpuMemArena,!!y.enableMemPattern,b,!!y.enableProfiling,0,E,A,I,$),h===0&&It("Can't create session options."),y.executionProviders&&await Ir(h,y.executionProviders,m),y.enableGraphCapture!==void 0){if(typeof y.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${y.enableGraphCapture}`);or(h,"enableGraphCapture",y.enableGraphCapture.toString(),m)}if(y.freeDimensionOverrides)for(let[x,k]of Object.entries(y.freeDimensionOverrides)){if(typeof x!="string")throw new Error(`free dimension override name must be a string: ${x}`);if(typeof k!="number"||!Number.isInteger(k)||k<0)throw new Error(`free dimension override value must be a non-negative integer: ${k}`);let N=bs(x,m);c._OrtAddFreeDimensionOverride(h,N,k)!==0&&It(`Can't set a free dimension override: ${x} - ${k}.`)}return y.extra!==void 0&&qr(y.extra,"",new WeakSet,(x,k)=>{or(h,x,k,m)}),[h,m]}catch(S){throw h!==0&&c._OrtReleaseSessionOptions(h)!==0&&It("Can't release session options."),m.forEach(b=>c._free(b)),S}}}),vr,Ys,yr,Kr,Yr,Jn,Qn,Xn,ot=_(()=>{vr=i=>{switch(i){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: ${i}`)}},Ys=i=>{switch(i){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: ${i}`)}},yr=(i,c)=>{let h=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][i],m=typeof c=="number"?c:c.reduce((y,S)=>y*S,1);return h>0?Math.ceil(m*h):void 0},Kr=i=>{switch(i){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: ${i}`)}},Yr=i=>{switch(i){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: ${i}`)}},Jn=i=>i==="float32"||i==="float16"||i==="int32"||i==="int64"||i==="uint32"||i==="uint8"||i==="bool"||i==="uint4"||i==="int4",Qn=i=>i==="float32"||i==="float16"||i==="int32"||i==="int64"||i==="uint32"||i==="uint64"||i==="int8"||i==="uint8"||i==="bool"||i==="uint4"||i==="int4",Xn=i=>{switch(i){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: ${i}`)}}}),Zn,Hi=_(()=>{Pr(),Zn=async i=>{if(typeof i=="string"){let c=await fetch(i);if(!c.ok)throw new Error(`failed to load external data file: ${i}`);let h=c.headers.get("Content-Length"),m=h?parseInt(h,10):0;if(m<1073741824)return new Uint8Array(await c.arrayBuffer());{if(!c.body)throw new Error(`failed to load external data file: ${i}, no response body.`);let y=c.body.getReader(),S;try{S=new ArrayBuffer(m)}catch(E){if(E instanceof RangeError){let A=Math.ceil(m/65536);S=new WebAssembly.Memory({initial:A,maximum:A}).buffer}else throw E}let b=0;for(;;){let{done:E,value:A}=await y.read();if(E)break;let I=A.byteLength;new Uint8Array(S,b,I).set(A),b+=I}return new Uint8Array(S,0,m)}}else return i instanceof Blob?new Uint8Array(await i.arrayBuffer()):i instanceof Uint8Array?i:new Uint8Array(i)}}),Fi,Bi,Tn,Sn,ei,zi,bt,ur=_(()=>{ot(),Fi=["V","I","W","E","F"],Bi=(i,c)=>{console.log(`[${Fi[i]},${new Date().toISOString()}]${c}`)},ei=(i,c)=>{Tn=i,Sn=c},zi=(i,c)=>{let h=Yr(i),m=Yr(Tn);h>=m&&Bi(h,typeof c=="function"?c():c)},bt=(...i)=>{Sn&&zi(...i)}}),Sl,bn,ie,Ls,Js,Jr,ti,ht=_(()=>{Sl=class{static calcMatMulShape(i,c){return i[1]!==c[0]?void 0:[i[0],c[1]]}},bn=class{static calcShape(i,c,h=!1){let m=i.length,y=c.length;if(m===0)return c;if(y===0)return i;let S=Math.max(i.length,c.length),b=new Array(S);if(h){if(m<2||y<2)return;let E=Sl.calcMatMulShape([i[m-2],i[m-1]],[c[y-2],c[y-1]]);if(E===void 0)return;[b[S-2],b[S-1]]=E}for(let E=h?3:1;E<=S;E++){let A=m-E<0?1:i[m-E],I=y-E<0?1:c[y-E];if(A!==I&&A>1&&I>1)return;let $=Math.max(A,I);if(A&&I)b[S-E]=Math.max(A,I);else{if($>1)return;b[S-E]=0}}return b}static isValidBroadcast(i,c){let h=i.length,m=c.length;if(h>m)return!1;for(let y=1;y<=h;y++)if(i[h-y]!==1&&i[h-y]!==c[m-y])return!1;return!0}},ie=class ac{static size(c){return ac.getSizeFromDimensionRange(c,0,c.length)}static convertShape(c,h=4){let m=c.length;if(m===0)return[];let y=new Array(m),S=m-1;for(;S>=0;){if(c[S]%h===0){y[S]=c[S]/h;break}if(h%c[S]!==0)throw new Error("cannot convert shape");y[S]=1,h/=c[S],S--}for(S--;S>=0;S--)y[S]=c[S];return y}static sizeFromDimension(c,h){if(h<0||h>c.length)throw new Error(`invalid dimension of ${h} for sizeFromDimension as Tensor has ${c.length} dimensions.`);return ac.getSizeFromDimensionRange(c,h,c.length)}static sizeToDimension(c,h){if(h<0||h>c.length)throw new Error(`invalid dimension of ${h} for sizeToDimension as Tensor has ${c.length} dimensions.`);return ac.getSizeFromDimensionRange(c,0,h)}static getSizeFromDimensionRange(c,h,m){let y=1;for(let S=h;S<m;S++){if(c[S]<0)throw new Error("cannot get valid size from specified dimension range. Most likely the range contains negative values in them.");y*=Number(c[S])}return y}static computeStrides(c){let h=c.length;if(h===0)return[];if(h===1)return[1];let m=new Array(h);m[h-1]=1,m[h-2]=c[h-1];for(let y=h-3;y>=0;--y)m[y]=m[y+1]*c[y+1];return m}static normalizeAxis(c,h){if(c<-h&&c>=h)throw new Error("unsupported axis for this operation.");return c<0?c+h:c}static normalizeAxes(c,h){return c.map(m=>this.normalizeAxis(m,h??c.length))}static sortBasedOnPerm(c,h){return h?h.map(m=>c[m]):c.slice().reverse()}static padShape(c,h){let m=c.length;return c.map((y,S)=>y+h[S]+h[S+m])}static areEqual(c,h){return c.length!==h.length?!1:c.every((m,y)=>m===h[y])}},Ls=class Mo{static adjustPoolAttributes(c,h,m,y,S,b){if(!c&&m.length!==h.length-2)throw new Error("length of specified kernel shapes should be 2 less than length of input dimensions");if(c)for(let E=0;E<h.length-2;E++)E>=m.length?m.push(h[E+2]):m[E]=h[E+2];for(let E=0;E<m.length;E++)if(E<y.length){if(y[E]<0)throw new Error("strides should be greater than or equal to 1")}else y.push(1);for(let E=0;E<m.length;E++)if(E<S.length){if(S[E]<0)throw new Error("dilations should be greater than or equal to 1")}else S.push(1);for(let E=0;E<m.length*2;E++)if(E<b.length){if(b[E]<0)throw new Error("pad should be greater than or equal to 1")}else b.push(0);for(let E=0;E<m.length;E++){if(m[E]<=0)throw new Error("kernel shapes need to be greater than 0");if(b[E]>=m[E]||b[E+m.length]>=m[E])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(c,h,m,y,S,b,E){if(E){if(S.length!==2*(c.length-2))throw new Error("length of pads should be twice the length of data dimensions");if(h.length!==c.length-2)throw new Error("length of strides should be the length of data dimensions");if(y.length!==c.length-2)throw new Error("length of kernel shapes should be the length of data dimensions");for(let A=0;A<c.length-2;A++)Mo.adjustPadAndReturnShape(c[A+(b?1:2)],h[A],m[A],y[A],S,A,A+c.length-2,E)}}static computePoolOutputShape(c,h,m,y,S,b,E){if(h.length<=0)throw new Error("input shape must be of size greater than 0");let A=[h[0],h[1]];return Mo.computeShapeHelper(c,h,A,m,y,S,b,E),A}static computeConvOutputShape(c,h,m,y,S,b,E){if(c.length<=0||h.length<=0)throw new Error("invalid input tensor dims or invalid filter tensor dims");let A=[c[0],h[0]];return Mo.computeShapeHelper(!1,c,A,m,y,S,b,E),A}static computeShapeHelper(c,h,m,y,S,b,E,A){if(c)for(let I=0;I<h.length-2;I++)m.push(1);else for(let I=0;I<h.length-2;I++)m.push(Mo.adjustPadAndReturnShape(h[I+2],y[I],S[I],b[I],E,I,I+h.length-2,A))}static adjustPadAndReturnShape(c,h,m,y,S,b,E,A){let I=m*(y-1)+1;if(A&&A!=="NOTSET")switch(A){case"VALID":return S[b]=0,S[E]=0,Math.floor((c-I)/h+1);case"SAME_LOWER":case"SAME_UPPER":if(m!==1)throw new Error("Dilation not supported for SAME_UPPER or SAME_LOWER");{let $=((c+h-1)/h-1)*h+y-c;return S[b]=Math.floor(A==="SAME_LOWER"?($+1)/2:$/2),S[E]=$-S[b],Math.floor((c+$-y)/h+1)}default:throw new Error("Unsupported AutoPad type")}else return Math.floor((c+S[b]+S[E]-I)/h+1)}},Js=class{static getShapeOfGemmResult(i,c,h,m,y){if(i.length!==2||h.length!==2)throw new Error("shape need to be of size 2");let S,b,E;c?(S=i[1],b=i[0]):(S=i[0],b=i[1]);let A=-1;if(m?(E=h[0],A=1):(E=h[1],A=0),h[A]!==b)throw new Error("dimension mismatch");if(S<=0||E<=0||b<=0)throw new Error("invalid shape specified");if(y&&!bn.isValidBroadcast(y,[S,E]))throw new Error("gemm: invalid bias shape for broadcast");return[S,E,b]}},Jr=-34028234663852886e22,ti=34028234663852886e22}),cr,Tr=_(()=>{ot(),cr=(i,c)=>new(Kr(c))(i)}),Vt,qt,Vi,ka,wn,si,qi,Na,Ma,Ua,ji,Pa=_(()=>{ot(),ur(),Vt=new Map([["float32",32],["float16",16],["int32",32],["uint32",32],["int64",64],["uint64",64],["int8",8],["uint8",8],["int4",4],["uint4",4]]),qt=(i,c)=>{if(c==="int32")return i;let h=Vt.get(c);if(!h)throw new Error(`WebNN backend does not support data type: ${c}`);let m=h/8;if(i.byteLength%m!==0)throw new Error(`Invalid Uint8Array length - must be a multiple of ${m}.`);let y=i.byteLength/m,S=new(Kr(c))(i.buffer,i.byteOffset,y);switch(c){case"int64":case"uint64":{let b=new Int32Array(y);for(let E=0;E<y;E++){let A=S[E];if(A>2147483647n||A<-2147483648n)throw new Error("Can not convert int64 data to int32 - value out of range.");b[E]=Number(A)}return new Uint8Array(b.buffer)}case"int8":case"uint8":case"uint32":{if(c==="uint32"&&S.some(E=>E>2147483647))throw new Error("Can not convert uint32 data to int32 - value out of range.");let b=Int32Array.from(S,Number);return new Uint8Array(b.buffer)}default:throw new Error(`Unsupported data conversion from ${c} to 'int32'`)}},Vi=(i,c)=>{if(c==="int32")return i;if(i.byteLength%4!==0)throw new Error("Invalid Uint8Array length - must be a multiple of 4 (int32).");let h=i.byteLength/4,m=new Int32Array(i.buffer,i.byteOffset,h);switch(c){case"int64":{let y=BigInt64Array.from(m,BigInt);return new Uint8Array(y.buffer)}case"uint64":{if(m.some(S=>S<0))throw new Error("Can not convert int32 data to uin64 - negative value found.");let y=BigUint64Array.from(m,BigInt);return new Uint8Array(y.buffer)}case"int8":{if(m.some(S=>S<-128||S>127))throw new Error("Can not convert int32 data to int8 - value out of range.");let y=Int8Array.from(m,Number);return new Uint8Array(y.buffer)}case"uint8":{if(m.some(y=>y<0||y>255))throw new Error("Can not convert int32 data to uint8 - value out of range.");return Uint8Array.from(m,Number)}case"uint32":{if(m.some(S=>S<0))throw new Error("Can not convert int32 data to uint32 - negative value found.");let y=Uint32Array.from(m,Number);return new Uint8Array(y.buffer)}default:throw new Error(`Unsupported data conversion from 'int32' to ${c}`)}},ka=1,wn=()=>ka++,si=new Map([["int8","int32"],["uint8","int32"],["uint32","int32"],["int64","int32"]]),qi=(i,c)=>{let h=Vt.get(i);if(!h)throw new Error(`WebNN backend does not support data type: ${i}`);return c.length>0?Math.ceil(c.reduce((m,y)=>m*y)*h/8):0},Na=class{constructor(i){this.isDataConverted=!1;let{sessionId:c,context:h,tensor:m,dataType:y,shape:S,fallbackDataType:b}=i;this.sessionId=c,this.mlContext=h,this.mlTensor=m,this.dataType=y,this.tensorShape=S,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 qi(this.dataType,this.tensorShape)}destroy(){bt("verbose",()=>"[WebNN] TensorWrapper.destroy"),this.mlTensor.destroy()}write(i){this.mlContext.writeTensor(this.mlTensor,i)}async read(i){if(this.fallbackDataType){let c=await this.mlContext.readTensor(this.mlTensor),h=Vi(new Uint8Array(c),this.dataType);if(i){(i instanceof ArrayBuffer?new Uint8Array(i):new Uint8Array(i.buffer,i.byteOffset,i.byteLength)).set(h);return}else return h.buffer}else return i?this.mlContext.readTensor(this.mlTensor,i):this.mlContext.readTensor(this.mlTensor)}canReuseTensor(i,c,h){return this.mlContext===i&&this.dataType===c&&this.tensorShape.length===h.length&&this.tensorShape.every((m,y)=>m===h[y])}setIsDataConverted(i){this.isDataConverted=i}},Ma=class{constructor(i,c){this.tensorManager=i,this.wrapper=c}get tensorWrapper(){return this.wrapper}releaseTensor(){this.tensorWrapper&&(this.tensorManager.releaseTensor(this.tensorWrapper),this.wrapper=void 0)}async ensureTensor(i,c,h,m){let y=this.tensorManager.getMLContext(i),S;if(!y.opSupportLimits().input.dataTypes.includes(c)){if(S=si.get(c),!S||!y.opSupportLimits().input.dataTypes.includes(S))throw new Error(`WebNN backend does not support data type: ${c}`);bt("verbose",()=>`[WebNN] TensorIdTracker.ensureTensor: fallback dataType from ${c} to ${S}`)}if(this.wrapper){if(this.wrapper.canReuseTensor(y,c,h))return this.wrapper.tensor;if(m){if(this.wrapper.byteLength!==qi(c,h))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(i,c,h,b,!0,!0,S),m&&this.activeUpload&&(this.wrapper.write(this.activeUpload),this.activeUpload=void 0),this.wrapper.tensor}upload(i){let c=i;if(this.wrapper){if(this.wrapper.fallbackType)if(this.wrapper.fallbackType==="int32")c=qt(i,this.wrapper.type),this.wrapper.setIsDataConverted(!0);else throw new Error(`Unsupported fallback data type: ${this.wrapper.fallbackType}`);if(i.byteLength===this.wrapper.byteLength){this.wrapper.write(c);return}else bt("verbose",()=>"Data size does not match tensor size. Releasing tensor."),this.releaseTensor()}this.activeUpload?this.activeUpload.set(c):this.activeUpload=new Uint8Array(c)}async download(i){var c,h;if(this.activeUpload){let m=(c=this.wrapper)!=null&&c.isDataConverted?Vi(this.activeUpload,(h=this.wrapper)==null?void 0:h.type):this.activeUpload;if(i){i instanceof ArrayBuffer?new Uint8Array(i).set(m):new Uint8Array(i.buffer,i.byteOffset,i.byteLength).set(m);return}else return m.buffer}if(!this.wrapper)throw new Error("Tensor has not been created.");return i?this.wrapper.read(i):this.wrapper.read()}},Ua=class{constructor(i){this.backend=i,this.tensorTrackersById=new Map,this.freeTensors=[],this.externalTensors=new Set}getMLContext(i){let c=this.backend.getMLContext(i);if(!c)throw new Error("MLContext not found for session.");return c}reserveTensorId(){let i=wn();return this.tensorTrackersById.set(i,new Ma(this)),i}releaseTensorId(i){let c=this.tensorTrackersById.get(i);c&&(this.tensorTrackersById.delete(i),c.tensorWrapper&&this.releaseTensor(c.tensorWrapper))}async ensureTensor(i,c,h,m,y){bt("verbose",()=>`[WebNN] TensorManager.ensureTensor {tensorId: ${c}, dataType: ${h}, shape: ${m}, copyOld: ${y}}`);let S=this.tensorTrackersById.get(c);if(!S)throw new Error("Tensor not found.");return S.ensureTensor(i,h,m,y)}upload(i,c){let h=this.tensorTrackersById.get(i);if(!h)throw new Error("Tensor not found.");h.upload(c)}async download(i,c){bt("verbose",()=>`[WebNN] TensorManager.download {tensorId: ${i}, dstBuffer: ${c==null?void 0:c.byteLength}}`);let h=this.tensorTrackersById.get(i);if(!h)throw new Error("Tensor not found.");return h.download(c)}releaseTensorsForSession(i){for(let c of this.freeTensors)c.sessionId===i&&c.destroy();this.freeTensors=this.freeTensors.filter(c=>c.sessionId!==i)}registerTensor(i,c,h,m){let y=this.getMLContext(i),S=wn(),b=new Na({sessionId:i,context:y,tensor:c,dataType:h,shape:m});return this.tensorTrackersById.set(S,new Ma(this,b)),this.externalTensors.add(b),S}async getCachedTensor(i,c,h,m,y,S,b){let E=this.getMLContext(i);for(let[I,$]of this.freeTensors.entries())if($.canReuseTensor(E,c,h)){bt("verbose",()=>`[WebNN] Reusing tensor {dataType: ${c}, ${b?`fallbackDataType: ${b},`:""} shape: ${h}`);let x=this.freeTensors.splice(I,1)[0];return x.sessionId=i,x}bt("verbose",()=>`[WebNN] MLContext.createTensor {dataType: ${c}, ${b?`fallbackDataType: ${b},`:""} shape: ${h}}`);let A=await E.createTensor({dataType:b??c,shape:h,dimensions:h,usage:m,writable:y,readable:S});return new Na({sessionId:i,context:E,tensor:A,dataType:c,shape:h,fallbackDataType:b})}releaseTensor(i){this.externalTensors.has(i)&&this.externalTensors.delete(i),this.freeTensors.push(i)}},ji=(...i)=>new Ua(...i)}),Qr,En,Cn,La=_(()=>{ot(),gr(),Tr(),Pa(),ur(),Qr=new Map([[1,"float32"],[10,"float16"],[6,"int32"],[12,"uint32"],[7,"int64"],[13,"uint64"],[22,"int4"],[21,"uint4"],[3,"int8"],[2,"uint8"],[9,"uint8"]]),En=(i,c)=>{if(i===c)return!0;if(i===void 0||c===void 0)return!1;let h=Object.keys(i).sort(),m=Object.keys(c).sort();return h.length===m.length&&h.every((y,S)=>y===m[S]&&i[y]===c[y])},Cn=class{constructor(i){this.tensorManager=ji(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,ei(i.logLevel,!!i.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw new Error("No active session");return this.activeSessionId}onRunStart(i){bt("verbose",()=>`[WebNN] onRunStart {sessionId: ${i}}`),this.activeSessionId=i}onRunEnd(i){bt("verbose",()=>`[WebNN] onRunEnd {sessionId: ${i}}`);let c=this.temporarySessionTensorIds.get(i);if(c){for(let h of c)bt("verbose",()=>`[WebNN] releasing temporary tensor {tensorId: ${h}}`),this.tensorManager.releaseTensorId(h);this.temporarySessionTensorIds.delete(i),this.activeSessionId=void 0}}async createMLContext(i){if(i instanceof GPUDevice){let h=this.mlContextCache.findIndex(m=>m.gpuDevice===i);if(h!==-1)return this.mlContextCache[h].mlContext;{let m=await navigator.ml.createContext(i);return this.mlContextCache.push({gpuDevice:i,mlContext:m}),m}}else if(i===void 0){let h=this.mlContextCache.findIndex(m=>m.options===void 0&&m.gpuDevice===void 0);if(h!==-1)return this.mlContextCache[h].mlContext;{let m=await navigator.ml.createContext();return this.mlContextCache.push({mlContext:m}),m}}let c=this.mlContextCache.findIndex(h=>En(h.options,i));if(c!==-1)return this.mlContextCache[c].mlContext;{let h=await navigator.ml.createContext(i);return this.mlContextCache.push({options:i,mlContext:h}),h}}registerMLContext(i,c){this.mlContextBySessionId.set(i,c);let h=this.sessionIdsByMLContext.get(c);h||(h=new Set,this.sessionIdsByMLContext.set(c,h)),h.add(i),this.temporaryGraphInputs.length>0&&(this.sessionGraphInputs.set(i,this.temporaryGraphInputs),this.temporaryGraphInputs=[]),this.temporaryGraphOutputs.length>0&&(this.sessionGraphOutputs.set(i,this.temporaryGraphOutputs),this.temporaryGraphOutputs=[])}onReleaseSession(i){this.sessionGraphInputs.delete(i),this.sessionGraphOutputs.delete(i);let c=this.mlContextBySessionId.get(i);if(!c)return;this.tensorManager.releaseTensorsForSession(i),this.mlContextBySessionId.delete(i);let h=this.sessionIdsByMLContext.get(c);if(h.delete(i),h.size===0){this.sessionIdsByMLContext.delete(c);let m=this.mlContextCache.findIndex(y=>y.mlContext===c);m!==-1&&this.mlContextCache.splice(m,1)}}getMLContext(i){return this.mlContextBySessionId.get(i)}reserveTensorId(){return this.tensorManager.reserveTensorId()}releaseTensorId(i){bt("verbose",()=>`[WebNN] releaseTensorId {tensorId: ${i}}`),this.tensorManager.releaseTensorId(i)}async ensureTensor(i,c,h,m,y){let S=Qr.get(h);if(!S)throw new Error(`Unsupported ONNX data type: ${h}`);return this.tensorManager.ensureTensor(i??this.currentSessionId,c,S,m,y)}async createTemporaryTensor(i,c,h){bt("verbose",()=>`[WebNN] createTemporaryTensor {onnxDataType: ${c}, shape: ${h}}`);let m=Qr.get(c);if(!m)throw new Error(`Unsupported ONNX data type: ${c}`);let y=this.tensorManager.reserveTensorId();await this.tensorManager.ensureTensor(i,y,m,h,!1);let S=this.temporarySessionTensorIds.get(i);return S?S.push(y):this.temporarySessionTensorIds.set(i,[y]),y}uploadTensor(i,c){if(!kt().shouldTransferToMLTensor)throw new Error("Trying to upload to a MLTensor while shouldTransferToMLTensor is false");bt("verbose",()=>`[WebNN] uploadTensor {tensorId: ${i}, data: ${c.byteLength}}`),this.tensorManager.upload(i,c)}async downloadTensor(i,c){return this.tensorManager.download(i,c)}createMLTensorDownloader(i,c){return async()=>{let h=await this.tensorManager.download(i);return cr(h,c)}}registerMLTensor(i,c,h,m){let y=Qr.get(h);if(!y)throw new Error(`Unsupported ONNX data type: ${h}`);let S=this.tensorManager.registerTensor(i,c,y,m);return bt("verbose",()=>`[WebNN] registerMLTensor {tensor: ${c}, dataType: ${y}, dimensions: ${m}} -> {tensorId: ${S}}`),S}registerMLConstant(i,c,h,m,y,S,b=!1){if(!S)throw new Error("External mounted files are not available.");let E=i;i.startsWith("./")&&(E=i.substring(2));let A=S.get(E);if(!A)throw new Error(`File with name ${E} not found in preloaded files.`);if(c+h>A.byteLength)throw new Error("Out of bounds: data offset and length exceed the external file data size.");let I=A.slice(c,c+h).buffer,$;switch(y.dataType){case"float32":$=new Float32Array(I);break;case"float16":$=typeof Float16Array<"u"&&Float16Array.from?new Float16Array(I):new Uint16Array(I);break;case"int32":$=new Int32Array(I);break;case"uint32":$=new Uint32Array(I);break;case"int64":if(b){let x=qt(new Uint8Array(I),"int64");$=new Int32Array(x.buffer),y.dataType="int32"}else $=new BigInt64Array(I);break;case"uint64":$=new BigUint64Array(I);break;case"int8":$=new Int8Array(I);break;case"int4":case"uint4":case"uint8":$=new Uint8Array(I);break;default:throw new Error(`Unsupported data type: ${y.dataType} in creating WebNN Constant from external data.`)}return bt("verbose",()=>`[WebNN] registerMLConstant {dataType: ${y.dataType}, shape: ${y.shape}}} ${b?"(Note: it was int64 data type and registered to int32 as workaround)":""}`),m.constant(y,$)}registerGraphInput(i){this.temporaryGraphInputs.push(i)}registerGraphOutput(i){this.temporaryGraphOutputs.push(i)}isGraphInput(i,c){let h=this.sessionGraphInputs.get(i);return h?h.includes(c):!1}isGraphOutput(i,c){let h=this.sessionGraphOutputs.get(i);return h?h.includes(c):!1}isGraphInputOutputTypeSupported(i,c,h=!0){let m=this.mlContextBySessionId.get(i),y=Qr.get(vr(c));return typeof y>"u"?!1:h?!!(m!=null&&m.opSupportLimits().input.dataTypes.includes(y)):!!(m!=null&&m.opSupportLimits().output.dataTypes.includes(y))}flush(){}}}),An=_(()=>{}),In,ri,ni,Ha,bl,Xr,Zr,Gi,Rn,Fa=_(()=>{ur(),An(),In=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]]),ri=[],ni=i=>Math.ceil(Number(i)/16)*16,Ha=i=>{for(let c=0;c<ri.length;c++){let h=ri[c];if(i<=h)return h}return Math.ceil(i/16)*16},bl=1,Xr=()=>bl++,Zr=async(i,c,h,m)=>{let y=ni(h),S=i.device.createBuffer({size:y,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});try{let b=i.getCommandEncoder();i.endComputePass(),b.copyBufferToBuffer(c,0,S,0,y),i.flush(),await S.mapAsync(GPUMapMode.READ);let E=S.getMappedRange();if(m){let A=m();return A.set(new Uint8Array(E,0,h)),A}else return new Uint8Array(E.slice(0,h))}finally{S.destroy()}},Gi=class{constructor(i){this.backend=i,this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.buffersPending=[],this.capturedPendingBuffers=new Map;for(let[c]of In)ri.push(c),this.freeBuffers.set(c,[]),this.freeUniformBuffers.set(c,[]);this.sessionCount=0}upload(i,c){let h=c.buffer,m=c.byteOffset,y=c.byteLength,S=ni(y),b=this.storageCache.get(i);if(!b)throw new Error("gpu data for uploading does not exist");if(Number(b.originalSize)!==y)throw new Error(`inconsistent data size. gpu data size=${b.originalSize}, data size=${y}`);let E=this.backend.device.createBuffer({mappedAtCreation:!0,size:S,usage:GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC}),A=E.getMappedRange();new Uint8Array(A).set(new Uint8Array(h,m,y)),E.unmap();let I=this.backend.device.createCommandEncoder();I.copyBufferToBuffer(E,0,b.gpuData.buffer,0,S),this.backend.device.queue.submit([I.finish()]),E.destroy(),bt("verbose",()=>`[WebGPU] GpuDataManager.upload(id=${i})`)}memcpy(i,c){let h=this.storageCache.get(i);if(!h)throw new Error("source gpu data for memcpy does not exist");let m=this.storageCache.get(c);if(!m)throw new Error("destination gpu data for memcpy does not exist");if(h.originalSize!==m.originalSize)throw new Error("inconsistent source and destination gpu data size");let y=ni(h.originalSize),S=this.backend.getCommandEncoder();this.backend.endComputePass(),S.copyBufferToBuffer(h.gpuData.buffer,0,m.gpuData.buffer,0,y)}registerExternalBuffer(i,c,h){let m;if(h){if(m=h[0],i===h[1])return bt("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${c}) => id=${m}, buffer is the same, skip.`),m;if(this.backend.capturedCommandList.has(this.backend.currentSessionId))throw new Error(`Registering a different external buffer under graph capture mode is not supported yet.
163
163
  Please use the previous external buffer!`)}else m=Xr();return this.storageCache.set(m,{gpuData:{id:m,type:0,buffer:i},originalSize:c}),bt("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${c}) => id=${m}, registered.`),m}unregisterExternalBuffer(i){i!==void 0&&(this.storageCache.delete(i),bt("verbose",()=>`[WebGPU] GpuDataManager.unregisterExternalBuffer() => id=${i}`))}create(i,c=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST){let h=Ha(i),m,y=(c&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE,S=(c&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM;if(y||S){let E=(y?this.freeBuffers:this.freeUniformBuffers).get(h);E?E.length>0?m=E.pop():m=this.backend.device.createBuffer({size:h,usage:c}):m=this.backend.device.createBuffer({size:h,usage:c})}else m=this.backend.device.createBuffer({size:h,usage:c});let b={id:Xr(),type:0,buffer:m};return this.storageCache.set(b.id,{gpuData:b,originalSize:Number(i)}),bt("verbose",()=>`[WebGPU] GpuDataManager.create(size=${i}) => id=${b.id}`),b}get(i){var c;return(c=this.storageCache.get(i))==null?void 0:c.gpuData}release(i){let c=typeof i=="bigint"?Number(i):i,h=this.storageCache.get(c);if(!h){if(this.storageCache.size===0)return 0;throw new Error("releasing data does not exist")}return bt("verbose",()=>`[WebGPU] GpuDataManager.release(id=${c}), gpuDataId=${h.gpuData.id}`),this.storageCache.delete(c),this.buffersPending.push(h.gpuData.buffer),h.originalSize}async download(i,c){let h=this.storageCache.get(Number(i));if(!h)throw new Error("data does not exist");await Zr(this.backend,h.gpuData.buffer,h.originalSize,c)}refreshPendingBuffers(){if(this.buffersPending.length!==0)if(this.backend.sessionStatus==="default"){for(let i of this.buffersPending){let c=In.get(i.size);if((i.usage&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE){let h=this.freeBuffers.get(i.size)||[];c===void 0||h.length>=c?i.destroy():h.push(i)}else if((i.usage&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM){let h=this.freeUniformBuffers.get(i.size)||[];c===void 0||h.length>=c?i.destroy():h.push(i)}else i.destroy()}this.buffersPending=[]}else{let i=this.capturedPendingBuffers.get(this.backend.currentSessionId);i||(i=[],this.capturedPendingBuffers.set(this.backend.currentSessionId,i));for(let c of this.buffersPending)i.push(c);this.buffersPending=[]}}dispose(){this.freeBuffers.forEach(i=>{i.forEach(c=>{c.destroy()})}),this.freeUniformBuffers.forEach(i=>{i.forEach(c=>{c.destroy()})}),this.storageCache.forEach(i=>{i.gpuData.buffer.destroy()}),this.capturedPendingBuffers.forEach(i=>{i.forEach(c=>{c.destroy()})}),this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.capturedPendingBuffers=new Map}onCreateSession(){this.sessionCount+=1}onReleaseSession(i){let c=this.capturedPendingBuffers.get(i);c&&(c.forEach(h=>{h.destroy()}),this.capturedPendingBuffers.delete(i)),this.sessionCount-=1,this.sessionCount===0&&(bt("warning",()=>"[WebGPU] Clearing webgpu buffer cache"),this.storageCache.forEach(h=>{h.gpuData.buffer.destroy()}),this.storageCache=new Map)}},Rn=(...i)=>new Gi(...i)}),wl,Rt,jt=_(()=>{wl=class{constructor(i){Object.assign(this,i)}get cacheKey(){return this.key||(this.key=Object.getOwnPropertyNames(this).sort().map(i=>`${this[i]}`).join(";")),this.key}},Rt=i=>new wl(i)}),Rr,en,Bt,Gt,Xe,Pt,ii,dr,qs,Ze,tn,he,Je,Wi,sn,ai,El,_t=_(()=>{ot(),ht(),Rr=64,en=(i,c)=>{if(c===3)throw new Error("vec3 has same alignment as vec4, use vec4 instead");switch(Number(i)){case 10:return c>1?`vec${c}<f16>`:"f16";case 1:return c>1?`vec${c}<f32>`:"f32";case 6:return c>1?`vec${c}<i32>`:"i32";case 12:return c>1?`vec${c}<u32>`:"u32";case 7:if(c>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2<u32>","i32"];case 13:if(c>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2<u32>","u32"];case 9:if(c!==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: ${i}`)}},Bt=(i,c=1)=>{let h=en(i,c);return typeof h=="string"?h:h[0]},Gt=(i,c=1)=>{let h=en(i,c);return typeof h=="string"?h:h[1]},Xe=(...i)=>{let c=[];return i.forEach(h=>{h.length!==0&&c.push({type:12,data:h},{type:12,data:ie.computeStrides(h)})}),c},Pt=i=>i%4===0?4:i%2===0?2:1,ii=(i="f32",c,h="0")=>!c||c===1?`${i}(${h})`:`vec${c}<${i}>(${h})`,dr=(i,c,h)=>i==="f32"?h:c===1?`f32(${h})`:`vec${c}<f32>(${h})`,qs=(i,c)=>c===4?`(${i}.x + ${i}.y + ${i}.z + ${i}.w)`:c===2?`(${i}.x + ${i}.y)`:c===3?`(${i}.x + ${i}.y + ${i}.z)`:i,Ze=(i,c,h,m)=>i.startsWith("uniforms.")&&h>4?typeof c=="string"?m==="f16"?`${i}[(${c}) / 8][(${c}) % 8 / 4][(${c}) % 8 % 4]`:`${i}[(${c}) / 4][(${c}) % 4]`:m==="f16"?`${i}[${Math.floor(c/8)}][${Math.floor(c%8/4)}][${c%8%4}]`:`${i}[${Math.floor(c/4)}][${c%4}]`:h>1?`${i}[${c}]`:i,tn=(i,c,h,m,y)=>{let S=typeof h=="number",b=S?h:h.length,E=[...new Array(b).keys()],A=b<2?"u32":b<=4?`vec${b}<u32>`:`array<u32, ${b}>`,I=en(c,y),$=typeof I=="string"?I:I[1],x=typeof I=="string"?I:I[0],k={indices:A,value:$,storage:x,tensor:c},N=Se=>typeof Se=="string"?Se:`${Se}u`,M={offsetToIndices:!1,indicesToOffset:!1,broadcastedIndicesToOffset:!1,set:!1,setByIndices:!1,get:!1,getByIndices:!1},U=S?"uniforms.":"",z=`${U}${i}_shape`,L=`${U}${i}_strides`,P="";for(let Se=0;Se<b-1;Se++)P+=`
164
164
  let dim${Se} = current / ${Ze(L,Se,b)};
165
165
  let rest${Se} = current % ${Ze(L,Se,b)};
@@ -572,7 +572,7 @@ var best_index : i32 = 0;`,`if (${m.getByIndices("input_indices")} ${c.selectLas
572
572
  let value = ${S.getByOffset("global_idx")}
573
573
  + ${b.getByOffset("global_idx % channels")} + ${E.getByOffset("global_idx")};
574
574
  ${A.setByOffset("global_idx","value")}
575
- }`}},Kp=i=>{Gp(i.inputs),i.compute(Wp(i.inputs))}}),Yp,Dt,Jp,Qp,Xp,Zp,em,tm,sm,rm,nm,im,am,lm,om,um,Co,cm,Ju,dm,fm,hm,_m,pm,mm,gm,vm,ym,Tm,Sm,bm,wm,Em,Cm,Am,qd,Im,jd,Gd,Rm,$m,xm,Om,Dm,km,Wd=_(()=>{ot(),ht(),jt(),_t(),Yp=(i,c,h,m,y,S,b)=>{let E=Math.ceil(c/4),A="";typeof y=="string"?A=`${y}(a)`:A=y("a");let I=he("inputData",h,[E],4),$=Je("outputData",m,[E],4),x=[{name:"vec_size",type:"u32"}];return b&&x.push(...b),`
575
+ }`}},Kp=i=>{Gp(i.inputs),i.compute(Wp(i.inputs))}}),Yp,Dt,Jp,Qp,Xp,Zp,em,tm,sm,rm,nm,im,am,lm,om,um,Co,cm,Ju,dm,fm,hm,_m,pm,mm,gm,vm,ym,Tm,Sm,bm,wm,Em,Cm,Am,Vd,Im,qd,jd,Rm,$m,xm,Om,Dm,km,Gd=_(()=>{ot(),ht(),jt(),_t(),Yp=(i,c,h,m,y,S,b)=>{let E=Math.ceil(c/4),A="";typeof y=="string"?A=`${y}(a)`:A=y("a");let I=he("inputData",h,[E],4),$=Je("outputData",m,[E],4),x=[{name:"vec_size",type:"u32"}];return b&&x.push(...b),`
576
576
  ${i.registerUniforms(x).declareVariables(I,$)}
577
577
 
578
578
  ${S??""}
@@ -603,15 +603,15 @@ fn erf_vf32(v: vec4<${i}>) -> vec4<${i}> {
603
603
  let absv = abs(v);
604
604
  let x = 1.0 / (1.0 + r0 * absv);
605
605
  return sign(v) * (1.0 - ((((r5 * x + r4) * x + r3) * x + r2) * x + r1) * x * exp(-absv * absv));
606
- }`,dm=i=>{let c=Gt(i.inputs[0].dataType);i.compute(Dt(i.inputs[0],"Erf",h=>`erf_vf32(${h})`,Ju(c)))},fm=i=>{i.compute(Dt(i.inputs[0],"Exp","exp"))},hm=i=>{i.compute(Dt(i.inputs[0],"Floor","floor"))},_m=i=>{let c=Gt(i.inputs[0].dataType);i.compute(Dt(i.inputs[0],"Gelu",h=>`0.5 * ${h} * (1.0 + erf_vf32(${h} * 0.7071067811865475))`,Ju(c)))},pm=(i,c)=>{let h=Gt(i.inputs[0].dataType);i.compute(Dt(i.inputs[0],"LeakyRelu",m=>`select(leaky_relu_alpha_ * ${m}, ${m}, ${m} >= vec4<${h}>(0.0))`,`const leaky_relu_alpha_ = ${h}(${c.alpha});`,c.cacheKey))},mm=i=>{i.compute(Dt(i.inputs[0],"Not",c=>`!${c}`))},gm=i=>{i.compute(Dt(i.inputs[0],"Neg",c=>`-${c}`))},vm=i=>{i.compute(Dt(i.inputs[0],"Reciprocal",c=>`1.0/${c}`))},ym=i=>{let c=Gt(i.inputs[0].dataType);i.compute(Dt(i.inputs[0],"Relu",h=>`select(vec4<${c}>(0.0), ${h}, ${h} > vec4<${c}>(0.0))`))},Tm=i=>{i.compute(Dt(i.inputs[0],"Sigmoid",c=>`(1.0 / (1.0 + exp(-${c})))`))},Sm=i=>Rt(i),bm=(i,c)=>{let h=Gt(i.inputs[0].dataType);i.compute(Dt(i.inputs[0],"HardSigmoid",m=>`max(vec4<${h}>(0.0), min(vec4<${h}>(1.0), ${c.alpha} * ${m} + vec4<${h}>(${c.beta})))`,void 0,c.cacheKey))},wm=i=>{i.compute(Dt(i.inputs[0],"Sin","sin"))},Em=i=>{i.compute(Dt(i.inputs[0],"Sinh","sinh"))},Cm=i=>{i.compute(Dt(i.inputs[0],"Sqrt","sqrt"))},Am=i=>{i.compute(Dt(i.inputs[0],"Tan","tan"))},qd=i=>`sign(${i}) * (1 - exp(-2 * abs(${i}))) / (1 + exp(-2 * abs(${i})))`,Im=i=>{i.compute(Dt(i.inputs[0],"Tanh",qd))},jd=(i="f32")=>`
606
+ }`,dm=i=>{let c=Gt(i.inputs[0].dataType);i.compute(Dt(i.inputs[0],"Erf",h=>`erf_vf32(${h})`,Ju(c)))},fm=i=>{i.compute(Dt(i.inputs[0],"Exp","exp"))},hm=i=>{i.compute(Dt(i.inputs[0],"Floor","floor"))},_m=i=>{let c=Gt(i.inputs[0].dataType);i.compute(Dt(i.inputs[0],"Gelu",h=>`0.5 * ${h} * (1.0 + erf_vf32(${h} * 0.7071067811865475))`,Ju(c)))},pm=(i,c)=>{let h=Gt(i.inputs[0].dataType);i.compute(Dt(i.inputs[0],"LeakyRelu",m=>`select(leaky_relu_alpha_ * ${m}, ${m}, ${m} >= vec4<${h}>(0.0))`,`const leaky_relu_alpha_ = ${h}(${c.alpha});`,c.cacheKey))},mm=i=>{i.compute(Dt(i.inputs[0],"Not",c=>`!${c}`))},gm=i=>{i.compute(Dt(i.inputs[0],"Neg",c=>`-${c}`))},vm=i=>{i.compute(Dt(i.inputs[0],"Reciprocal",c=>`1.0/${c}`))},ym=i=>{let c=Gt(i.inputs[0].dataType);i.compute(Dt(i.inputs[0],"Relu",h=>`select(vec4<${c}>(0.0), ${h}, ${h} > vec4<${c}>(0.0))`))},Tm=i=>{i.compute(Dt(i.inputs[0],"Sigmoid",c=>`(1.0 / (1.0 + exp(-${c})))`))},Sm=i=>Rt(i),bm=(i,c)=>{let h=Gt(i.inputs[0].dataType);i.compute(Dt(i.inputs[0],"HardSigmoid",m=>`max(vec4<${h}>(0.0), min(vec4<${h}>(1.0), ${c.alpha} * ${m} + vec4<${h}>(${c.beta})))`,void 0,c.cacheKey))},wm=i=>{i.compute(Dt(i.inputs[0],"Sin","sin"))},Em=i=>{i.compute(Dt(i.inputs[0],"Sinh","sinh"))},Cm=i=>{i.compute(Dt(i.inputs[0],"Sqrt","sqrt"))},Am=i=>{i.compute(Dt(i.inputs[0],"Tan","tan"))},Vd=i=>`sign(${i}) * (1 - exp(-2 * abs(${i}))) / (1 + exp(-2 * abs(${i})))`,Im=i=>{i.compute(Dt(i.inputs[0],"Tanh",Vd))},qd=(i="f32")=>`
607
607
  const fast_gelu_a: ${i} = 0.5;
608
608
  const fast_gelu_b: ${i} = 0.7978845608028654;
609
609
  const fast_gelu_c: ${i} = 0.035677408136300125;
610
610
 
611
611
  fn tanh_v(v: vec4<${i}>) -> vec4<${i}> {
612
- return ${qd("v")};
612
+ return ${Vd("v")};
613
613
  }
614
- `,Gd=i=>`(fast_gelu_a + fast_gelu_a * tanh_v(${i} * (fast_gelu_c * ${i} * ${i} + fast_gelu_b))) * ${i}`,Rm=i=>{let c=Gt(i.inputs[0].dataType);i.compute(Dt(i.inputs[0],"FastGelu",Gd,jd(c),void 0,i.inputs[0].dataType))},$m=(i,c)=>{let h=Gt(i.inputs[0].dataType);return i.compute(Dt(i.inputs[0],"ThresholdedRelu",m=>`select(vec4<${h}>(0.0), ${m}, ${m} > thresholded_relu_alpha_)`,`const thresholded_relu_alpha_ = vec4<${h}>(${c.alpha});`,c.cacheKey)),0},xm=i=>{i.compute(Dt(i.inputs[0],"Log","log"))},Om=(i,c)=>`
614
+ `,jd=i=>`(fast_gelu_a + fast_gelu_a * tanh_v(${i} * (fast_gelu_c * ${i} * ${i} + fast_gelu_b))) * ${i}`,Rm=i=>{let c=Gt(i.inputs[0].dataType);i.compute(Dt(i.inputs[0],"FastGelu",jd,qd(c),void 0,i.inputs[0].dataType))},$m=(i,c)=>{let h=Gt(i.inputs[0].dataType);return i.compute(Dt(i.inputs[0],"ThresholdedRelu",m=>`select(vec4<${h}>(0.0), ${m}, ${m} > thresholded_relu_alpha_)`,`const thresholded_relu_alpha_ = vec4<${h}>(${c.alpha});`,c.cacheKey)),0},xm=i=>{i.compute(Dt(i.inputs[0],"Log","log"))},Om=(i,c)=>`
615
615
  const alpha = vec4<${i}>(${c});
616
616
  const one = ${i}(1.0);
617
617
  const zero = ${i}(0.0);
@@ -628,7 +628,7 @@ fn quick_gelu_impl(x: vec4<${i}>) -> vec4<${i}> {
628
628
  }
629
629
  return x * x1;
630
630
  }
631
- `,Dm=i=>`quick_gelu_impl(${i})`,km=(i,c)=>{let h=Gt(i.inputs[0].dataType);i.compute(Dt(i.inputs[0],"QuickGelu",Dm,Om(h,c.alpha),c.cacheKey,i.inputs[0].dataType))}}),Nm,Mm,Um,yI=_(()=>{ht(),_t(),Wd(),Nm=i=>{if(i[0].dims.length!==3)throw new Error("input should have 3 dimensions");if(![2560,5120,10240].includes(i[0].dims[2]))throw new Error("hidden state should be 2560, 5120 or 10240");if(i[1].dims.length!==1)throw new Error("bias is expected to have 1 dimensions");if(i[0].dims[2]!==i[1].dims[0])throw new Error("last dimension of input and bias are not the same")},Mm=i=>{let c=i[0].dims.slice();c[2]=c[2]/2;let h=he("input",i[0].dataType,i[0].dims,4),m=he("bias",i[0].dataType,[i[0].dims[2]],4),y=Je("output",i[0].dataType,c,4),S=ie.size(c)/4,b=Bt(i[0].dataType);return{name:"BiasSplitGelu",getRunData:()=>({outputs:[{dims:c,dataType:i[0].dataType}],dispatchGroup:{x:Math.ceil(S/64)}}),getShaderSource:E=>`
631
+ `,Dm=i=>`quick_gelu_impl(${i})`,km=(i,c)=>{let h=Gt(i.inputs[0].dataType);i.compute(Dt(i.inputs[0],"QuickGelu",Dm,Om(h,c.alpha),c.cacheKey,i.inputs[0].dataType))}}),Nm,Mm,Um,yI=_(()=>{ht(),_t(),Gd(),Nm=i=>{if(i[0].dims.length!==3)throw new Error("input should have 3 dimensions");if(![2560,5120,10240].includes(i[0].dims[2]))throw new Error("hidden state should be 2560, 5120 or 10240");if(i[1].dims.length!==1)throw new Error("bias is expected to have 1 dimensions");if(i[0].dims[2]!==i[1].dims[0])throw new Error("last dimension of input and bias are not the same")},Mm=i=>{let c=i[0].dims.slice();c[2]=c[2]/2;let h=he("input",i[0].dataType,i[0].dims,4),m=he("bias",i[0].dataType,[i[0].dims[2]],4),y=Je("output",i[0].dataType,c,4),S=ie.size(c)/4,b=Bt(i[0].dataType);return{name:"BiasSplitGelu",getRunData:()=>({outputs:[{dims:c,dataType:i[0].dataType}],dispatchGroup:{x:Math.ceil(S/64)}}),getShaderSource:E=>`
632
632
  const M_SQRT2 = sqrt(2.0);
633
633
  const halfChannels = ${i[0].dims[2]/4/2}u;
634
634
 
@@ -720,9 +720,9 @@ fn quick_gelu_impl(x: vec4<${i}>) -> vec4<${i}> {
720
720
  }
721
721
 
722
722
  ${Qm(b,x)}
723
- }`;return{name:"Concat",shaderCache:{hint:`${c}`,inputDependencies:A},getRunData:()=>({outputs:[{dims:h,dataType:m}],dispatchGroup:{x:Math.ceil(y/64)},programUniforms:$}),getShaderSource:M}},Zm=(i,c)=>{let h=i.inputs,m=h[0].dims,y=ie.normalizeAxis(c.axis,m.length);Ym(h,y);let S=m.slice();S[y]=h.reduce((E,A)=>E+(A.dims.length>y?A.dims[y]:0),0);let b=h.filter(E=>ie.size(E.dims)>0);i.compute(Xm(b,y,S,h[0].dataType),{inputs:b})},eg=i=>Rt({axis:i.axis})}),Ja,Qa,Xa,Kd,Za=_(()=>{ot(),ht(),Ja=(i,c,h="f32")=>{switch(i.activation){case"Relu":return`value = max(value, ${c}(0.0));`;case"Sigmoid":return`value = (${c}(1.0) / (${c}(1.0) + exp(-value)));`;case"Clip":return`value = clamp(value, ${c}(${h}(uniforms.clip_min)), ${c}(${h}(uniforms.clip_max)));`;case"HardSigmoid":return`value = max(${c}(0.0), min(${c}(1.0), ${h}(uniforms.alpha) * value + ${h}(uniforms.beta)));`;case"LeakyRelu":return`value = select(${h}(uniforms.alpha) * value, value, value >= ${c}(0.0));`;case"Tanh":return`let e2x = exp(-2.0 * abs(value));
723
+ }`;return{name:"Concat",shaderCache:{hint:`${c}`,inputDependencies:A},getRunData:()=>({outputs:[{dims:h,dataType:m}],dispatchGroup:{x:Math.ceil(y/64)},programUniforms:$}),getShaderSource:M}},Zm=(i,c)=>{let h=i.inputs,m=h[0].dims,y=ie.normalizeAxis(c.axis,m.length);Ym(h,y);let S=m.slice();S[y]=h.reduce((E,A)=>E+(A.dims.length>y?A.dims[y]:0),0);let b=h.filter(E=>ie.size(E.dims)>0);i.compute(Xm(b,y,S,h[0].dataType),{inputs:b})},eg=i=>Rt({axis:i.axis})}),Ja,Qa,Xa,Wd,Za=_(()=>{ot(),ht(),Ja=(i,c,h="f32")=>{switch(i.activation){case"Relu":return`value = max(value, ${c}(0.0));`;case"Sigmoid":return`value = (${c}(1.0) / (${c}(1.0) + exp(-value)));`;case"Clip":return`value = clamp(value, ${c}(${h}(uniforms.clip_min)), ${c}(${h}(uniforms.clip_max)));`;case"HardSigmoid":return`value = max(${c}(0.0), min(${c}(1.0), ${h}(uniforms.alpha) * value + ${h}(uniforms.beta)));`;case"LeakyRelu":return`value = select(${h}(uniforms.alpha) * value, value, value >= ${c}(0.0));`;case"Tanh":return`let e2x = exp(-2.0 * abs(value));
724
724
  value = sign(value) * (1.0 - e2x) / (1.0 + e2x);
725
- `;case"":return"";default:throw new Error(`Unsupported activation ${i.activation}`)}},Qa=(i,c)=>{i.activation==="Clip"?c.push({type:1,data:i.clipMax},{type:1,data:i.clipMin}):i.activation==="HardSigmoid"?c.push({type:1,data:i.alpha},{type:1,data:i.beta}):i.activation==="LeakyRelu"&&c.push({type:1,data:i.alpha})},Xa=(i,c)=>{i.activation==="Clip"?c.push({name:"clip_max",type:"f32"},{name:"clip_min",type:"f32"}):i.activation==="HardSigmoid"?c.push({name:"alpha",type:"f32"},{name:"beta",type:"f32"}):i.activation==="LeakyRelu"&&c.push({name:"alpha",type:"f32"})},Kd=i=>{let c=(i==null?void 0:i.activation)||"";if(c==="HardSigmoid"){let[h,m]=(i==null?void 0:i.activation_params)||[.2,.5];return{activation:c,alpha:h,beta:m}}else if(c==="Clip"){let[h,m]=(i==null?void 0:i.activation_params)||[Jr,ti];return{activation:c,clipMax:m,clipMin:h}}else if(c==="LeakyRelu"){let[h]=(i==null?void 0:i.activation_params)||[.01];return{activation:c,alpha:h}}return{activation:c}}}),Cs,tg,Yd=_(()=>{Cs=(i,c)=>{switch(i){case 1:return c;case 2:return`vec2<${c}>`;case 3:return`vec3<${c}>`;case 4:return`vec4<${c}>`;default:throw new Error(`${i}-component is not supported.`)}},tg=i=>`
725
+ `;case"":return"";default:throw new Error(`Unsupported activation ${i.activation}`)}},Qa=(i,c)=>{i.activation==="Clip"?c.push({type:1,data:i.clipMax},{type:1,data:i.clipMin}):i.activation==="HardSigmoid"?c.push({type:1,data:i.alpha},{type:1,data:i.beta}):i.activation==="LeakyRelu"&&c.push({type:1,data:i.alpha})},Xa=(i,c)=>{i.activation==="Clip"?c.push({name:"clip_max",type:"f32"},{name:"clip_min",type:"f32"}):i.activation==="HardSigmoid"?c.push({name:"alpha",type:"f32"},{name:"beta",type:"f32"}):i.activation==="LeakyRelu"&&c.push({name:"alpha",type:"f32"})},Wd=i=>{let c=(i==null?void 0:i.activation)||"";if(c==="HardSigmoid"){let[h,m]=(i==null?void 0:i.activation_params)||[.2,.5];return{activation:c,alpha:h,beta:m}}else if(c==="Clip"){let[h,m]=(i==null?void 0:i.activation_params)||[Jr,ti];return{activation:c,clipMax:m,clipMin:h}}else if(c==="LeakyRelu"){let[h]=(i==null?void 0:i.activation_params)||[.01];return{activation:c,alpha:h}}return{activation:c}}}),Cs,tg,Kd=_(()=>{Cs=(i,c)=>{switch(i){case 1:return c;case 2:return`vec2<${c}>`;case 3:return`vec3<${c}>`;case 4:return`vec4<${c}>`;default:throw new Error(`${i}-component is not supported.`)}},tg=i=>`
726
726
  ${i?"value = value + getBiasByOutputCoords(coords);":""}
727
727
  `}),sg,bI=_(()=>{sg=i=>`
728
728
  fn getIndexFromCoords4D(coords : vec4<i32>, shape : vec4<i32>) -> i32 {
@@ -733,14 +733,14 @@ fn getOutputIndexFromCoords(coords : vec4<i32>) -> i32 {
733
733
  return dot(coords, vec4<i32>(
734
734
  i32(${i}.x), i32(${i}.y), i32(${i}.z), 1));
735
735
  }
736
- `}),Ao,Jd,Qd=_(()=>{ot(),ht(),_t(),Za(),Ao=(i,c,h,m,y)=>{let S=m-h;return`
736
+ `}),Ao,Yd,Jd=_(()=>{ot(),ht(),_t(),Za(),Ao=(i,c,h,m,y)=>{let S=m-h;return`
737
737
  ${Array.from({length:h}).map((b,E)=>`
738
738
  if (${Ze(c.shape,E,c.rank)} != 1) {
739
739
  ${c.indicesSet(i,E,Ze(y,E+S,m))}
740
740
  } else {
741
741
  ${c.indicesSet(i,E,0)}
742
742
  }`).join("")}
743
- `},Jd=(i,c,h,m,y=!1,S)=>{let b=i[0].dims,E=i[1].dims,A=b[b.length-2],I=E[E.length-1],$=b[b.length-1],x=Pt(I),k=Pt($),N=Pt(A),M=ie.size(h)/x/N,U=i.length>2,z=m?m.slice(0,-2):h.slice(0,-2),L=[ie.size(z),A,I],P=[{type:12,data:M},{type:12,data:A},{type:12,data:I},{type:12,data:$}];Qa(c,P),P.push(...Xe(z,b,E)),U&&P.push(...Xe(i[2].dims)),P.push(...Xe(L));let j=V=>{let Y=sn("batch_dims",i[0].dataType,z.length),ae=he("a",i[0].dataType,b.length,k),ne=he("b",i[1].dataType,E.length,x),de=Je("output",i[0].dataType,L.length,x),ve=Bt(de.type.tensor),Ue=Ja(c,de.type.value,ve),ct=[ae,ne],st="";if(U){let Tt=y?x:1;ct.push(he("bias",i[2].dataType,i[2].dims.length,Tt)),st=`${y?`value += bias[col / ${Tt}];`:`value += ${de.type.value}(bias[row + i]);`}`}let ut=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"}];Xa(c,ut);let $t=()=>{let Tt=`var a_data: ${ae.type.value};`;for(let at=0;at<k;at++)Tt+=`
743
+ `},Yd=(i,c,h,m,y=!1,S)=>{let b=i[0].dims,E=i[1].dims,A=b[b.length-2],I=E[E.length-1],$=b[b.length-1],x=Pt(I),k=Pt($),N=Pt(A),M=ie.size(h)/x/N,U=i.length>2,z=m?m.slice(0,-2):h.slice(0,-2),L=[ie.size(z),A,I],P=[{type:12,data:M},{type:12,data:A},{type:12,data:I},{type:12,data:$}];Qa(c,P),P.push(...Xe(z,b,E)),U&&P.push(...Xe(i[2].dims)),P.push(...Xe(L));let j=V=>{let Y=sn("batch_dims",i[0].dataType,z.length),ae=he("a",i[0].dataType,b.length,k),ne=he("b",i[1].dataType,E.length,x),de=Je("output",i[0].dataType,L.length,x),ve=Bt(de.type.tensor),Ue=Ja(c,de.type.value,ve),ct=[ae,ne],st="";if(U){let Tt=y?x:1;ct.push(he("bias",i[2].dataType,i[2].dims.length,Tt)),st=`${y?`value += bias[col / ${Tt}];`:`value += ${de.type.value}(bias[row + i]);`}`}let ut=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"}];Xa(c,ut);let $t=()=>{let Tt=`var a_data: ${ae.type.value};`;for(let at=0;at<k;at++)Tt+=`
744
744
  let b_data${at} = b[(b_offset + (k + ${at}) * uniforms.N + col) / ${x}];`;for(let at=0;at<N;at++){Tt+=`a_data = a[(a_offset + (row + ${at}) * uniforms.K + k) / ${k}];`;for(let St=0;St<k;St++)Tt+=`
745
745
  values[${at}] = fma(${ne.type.value}(a_data${k===1?"":`[${St}]`}), b_data${St}, values[${at}]);
746
746
  `}return Tt};return`
@@ -779,7 +779,7 @@ fn getOutputIndexFromCoords(coords : vec4<i32>) -> i32 {
779
779
  ${de.setByOffset(`offset / ${x}`,"value")};
780
780
  }
781
781
  }
782
- `};return{name:"MatMulNaive",shaderCache:{hint:`${c.activation};${x};${k};${N};${y}`,inputDependencies:U?["rank","rank","rank"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:S?S(h):h,dataType:i[0].dataType}],dispatchGroup:{x:Math.ceil(M/64)},programUniforms:P}),getShaderSource:j}}}),rg,ng,Xd,Zd,ig,ef,ag,Qu,tf=_(()=>{ot(),ht(),_t(),Za(),Qd(),Yd(),rg=(i,c)=>i?`
782
+ `};return{name:"MatMulNaive",shaderCache:{hint:`${c.activation};${x};${k};${N};${y}`,inputDependencies:U?["rank","rank","rank"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:S?S(h):h,dataType:i[0].dataType}],dispatchGroup:{x:Math.ceil(M/64)},programUniforms:P}),getShaderSource:j}}}),rg,ng,Qd,Xd,ig,Zd,ag,Qu,ef=_(()=>{ot(),ht(),_t(),Za(),Jd(),Kd(),rg=(i,c)=>i?`
783
783
  mm_Asub[inputRow][inputCol] = mm_readA(batch,
784
784
  kStart + inputRow,
785
785
  globalRowStart / innerElementSize + inputCol${c?", batchIndices":""});
@@ -804,7 +804,7 @@ fn getOutputIndexFromCoords(coords : vec4<i32>) -> i32 {
804
804
  acc[i] = BCached1 * ACached.y + acc[i];
805
805
  acc[i] = BCached2 * ACached.z + acc[i];
806
806
  ${c===3?"":"acc[i] = BCached3 * ACached.w + acc[i];"}
807
- }`,Xd=(i,c,h="f32",m,y=!1,S=32,b=!1,E=32)=>{let A=c[1]*i[1],I=c[0]*i[0],$=y?A:S,x=y?S:A,k=$/c[0],N=S/c[1];if(!((y&&k===4&&i[1]===4||!y&&(k===3||k===4))&&$%c[0]===0&&S%c[1]===0&&i[0]===4))throw new Error(`If transposeA ${y} is true, innerElementSize ${k} and workPerThread[1] ${i[1]} must be 4.
807
+ }`,Qd=(i,c,h="f32",m,y=!1,S=32,b=!1,E=32)=>{let A=c[1]*i[1],I=c[0]*i[0],$=y?A:S,x=y?S:A,k=$/c[0],N=S/c[1];if(!((y&&k===4&&i[1]===4||!y&&(k===3||k===4))&&$%c[0]===0&&S%c[1]===0&&i[0]===4))throw new Error(`If transposeA ${y} is true, innerElementSize ${k} and workPerThread[1] ${i[1]} must be 4.
808
808
  Otherwise, innerElementSize ${k} must be 3 or 4.
809
809
  tileAWidth ${$} must be divisible by workgroupSize[0]${c[0]}. tileInner ${S} must be divisible by workgroupSize[1] ${c[1]}. colPerThread ${i[0]} must be 4.`);return`
810
810
  var<workgroup> mm_Asub: array<array<vec${k}<${h}>, ${$/k}>, ${x}>;
@@ -869,7 +869,7 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
869
869
  for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) {
870
870
  mm_write(batch, globalRow + innerRow, globalCol, acc[innerRow]);
871
871
  }
872
- }`},Zd=(i,c)=>i?`
872
+ }`},Xd=(i,c)=>i?`
873
873
  mm_Asub[inputRow][inputCol] = mm_readA(batch,
874
874
  kStart + inputRow,
875
875
  globalRowStart + inputCol${c?", batchIndices":""});
@@ -877,7 +877,7 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
877
877
  mm_Asub[inputRow][inputCol] = mm_readA(batch,
878
878
  globalRowStart + inputRow,
879
879
  kStart + inputCol${c?", batchIndices":""});
880
- `,ig=i=>i?"let ACached = mm_Asub[k][tileRow + innerRow];":"let ACached = mm_Asub[tileRow + innerRow][k];",ef=(i,c,h="f32",m,y=!1,S=32,b=!1,E=32,A=!1)=>{let I=i[1]*c[1],$=i[0]*c[0],x=y?I:S,k=y?S:I;if(!(k%c[1]===0&&x%c[0]===0&&S%c[1]===0))throw new Error(`tileAHight ${k} must be divisible by workgroupSize[1]${c[1]}, tileAWidth ${x} must be divisible by workgroupSize[0]${c[0]}, tileInner ${S} must be divisible by workgroupSize[1]${c[1]}`);let N=k/c[1],M=x/c[0],U=S/c[1],z=A?`
880
+ `,ig=i=>i?"let ACached = mm_Asub[k][tileRow + innerRow];":"let ACached = mm_Asub[tileRow + innerRow][k];",Zd=(i,c,h="f32",m,y=!1,S=32,b=!1,E=32,A=!1)=>{let I=i[1]*c[1],$=i[0]*c[0],x=y?I:S,k=y?S:I;if(!(k%c[1]===0&&x%c[0]===0&&S%c[1]===0))throw new Error(`tileAHight ${k} must be divisible by workgroupSize[1]${c[1]}, tileAWidth ${x} must be divisible by workgroupSize[0]${c[0]}, tileInner ${S} must be divisible by workgroupSize[1]${c[1]}`);let N=k/c[1],M=x/c[0],U=S/c[1],z=A?`
881
881
  let localRow = i32(localId.y);
882
882
  let localCol = i32(localId.x);
883
883
  let globalRowStart = i32(workgroupId.y) * ${I};
@@ -888,7 +888,7 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
888
888
  // Load one tile of A into local memory.
889
889
  for (var inputRow = localRow; inputRow < ${k}; inputRow = inputRow + ${c[1]}) {
890
890
  for (var inputCol = localCol; inputCol < ${x}; inputCol = inputCol + ${c[0]}) {
891
- ${Zd(y,m)}
891
+ ${Xd(y,m)}
892
892
  }
893
893
  }
894
894
  // Load one tile of B into local memory.
@@ -943,7 +943,7 @@ for (var t = 0; t < num_tiles; t = t + 1) {
943
943
  for (var innerCol = 0; innerCol < ${M}; innerCol = innerCol + 1) {
944
944
  let inputRow = tileRowA + innerRow;
945
945
  let inputCol = tileColA + innerCol;
946
- ${Zd(y,m)}
946
+ ${Xd(y,m)}
947
947
  }
948
948
  }
949
949
 
@@ -1045,8 +1045,8 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
1045
1045
  `},Qu=(i,c,h,m,y=!1,S)=>{let b=i[0].dims,E=i[1].dims,A=b.slice(0,-2),I=E.slice(0,-2),$=m?m.slice(0,-2):h.slice(0,-2),x=ie.size($),k=b[b.length-2],N=b[b.length-1],M=E[E.length-1],U=N%4===0&&M%4===0,z=k<=8?[4,1,1]:[4,4,1],L=[8,8,1],P=[Math.ceil(M/L[0]/z[0]),Math.ceil(k/L[1]/z[1]),Math.ceil(x/L[2]/z[2])],j=U?4:1,V=[...A,k,N/j],Y=V.length,ae=[...I,N,M/j],ne=ae.length,de=[x,k,M/j],ve=[{type:6,data:k},{type:6,data:M},{type:6,data:N}];Qa(c,ve),ve.push(...Xe($,V,ae));let Ue=["rank","rank"],ct=i.length>2;ct&&(ve.push(...Xe(i[2].dims)),Ue.push("rank")),ve.push(...Xe(de));let st=ut=>{let $t=$.length,Tt=sn("batchDims",i[0].dataType,$t,1),at=Bt(i[0].dataType),St=he("a",i[0].dataType,Y,j),it=he("b",i[1].dataType,ne,j),pt=Je("result",i[0].dataType,de.length,j),Fs=[St,it];if(ct){let Sr=y?j:1;Fs.push(he("bias",i[2].dataType,i[2].dims.length,Sr))}let Se=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"}];Xa(c,Se);let Be=Bt(pt.type.tensor),lt=Ja(c,pt.type.value,Be),wt=ag(j,ct,lt,[Tt,St,it,pt],y);return`
1046
1046
  ${ut.registerUniforms(Se).registerInternalVariables(Tt).declareVariables(...Fs,pt)}
1047
1047
  ${wt}
1048
- ${U?Xd(z,L,at,Tt):ef(z,L,at,Tt)}
1049
- `};return{name:"MatMul",shaderCache:{hint:`${z};${c.activation};${U};${y}`,inputDependencies:Ue},getRunData:()=>({outputs:[{dims:S?S(h):h,dataType:i[0].dataType}],dispatchGroup:{x:P[0],y:P[1],z:P[2]},programUniforms:ve}),getShaderSource:st}}}),lg,og,wI=_(()=>{ot(),ur(),_t(),Za(),Yd(),bI(),tf(),lg=(i,c,h,m,y=!1,S,b=4,E=4,A=4,I="f32")=>{let $=ve=>{switch(ve){case 1:return"resData = x[xIndex];";case 3:return`resData = vec3<${I}>(x[xIndex], x[xIndex + 1], x[xIndex + 2]);`;case 4:return"resData = x[xIndex / 4];";default:throw new Error(`innerElementSize ${ve} is not supported.`)}},x=ve=>{switch(ve){case 1:return"return w[row * i32(uniforms.w_shape[3]) + colIn];";case 4:return"return w[row * i32(uniforms.w_shape[3]) / 4 + colIn];";default:throw new Error(`innerElementSize ${ve} is not supported.`)}},k=i?`
1048
+ ${U?Qd(z,L,at,Tt):Zd(z,L,at,Tt)}
1049
+ `};return{name:"MatMul",shaderCache:{hint:`${z};${c.activation};${U};${y}`,inputDependencies:Ue},getRunData:()=>({outputs:[{dims:S?S(h):h,dataType:i[0].dataType}],dispatchGroup:{x:P[0],y:P[1],z:P[2]},programUniforms:ve}),getShaderSource:st}}}),lg,og,wI=_(()=>{ot(),ur(),_t(),Za(),Kd(),bI(),ef(),lg=(i,c,h,m,y=!1,S,b=4,E=4,A=4,I="f32")=>{let $=ve=>{switch(ve){case 1:return"resData = x[xIndex];";case 3:return`resData = vec3<${I}>(x[xIndex], x[xIndex + 1], x[xIndex + 2]);`;case 4:return"resData = x[xIndex / 4];";default:throw new Error(`innerElementSize ${ve} is not supported.`)}},x=ve=>{switch(ve){case 1:return"return w[row * i32(uniforms.w_shape[3]) + colIn];";case 4:return"return w[row * i32(uniforms.w_shape[3]) / 4 + colIn];";default:throw new Error(`innerElementSize ${ve} is not supported.`)}},k=i?`
1050
1050
  let coord = vec4<i32>(batch, xRow, xCol, xCh);
1051
1051
  `:`
1052
1052
  let coord = vec4<i32>(batch, xCh, xRow, xCol);
@@ -1143,7 +1143,7 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
1143
1143
  ${at.registerUniforms(St).declareVariables(...lt,wt)}
1144
1144
  ${Fs}
1145
1145
  ${lg(I,ve,Ue,ct,b,c,st[0],st[1],st[2],pt)}
1146
- ${U?Xd(j,P,pt,void 0,!I,de):ef(j,P,pt,void 0,!I,de,!1,void 0,E)}`};return{name:"Conv2DMatMul",shaderCache:{hint:`${c.cacheKey};${Y};${U};${ve};${Ue};${ct};${ae};${ne};${de}`,inputDependencies:$t},getRunData:()=>({outputs:[{dims:A?A(h):h,dataType:i[0].dataType}],dispatchGroup:{x:V[0],y:V[1],z:V[2]},programUniforms:ut}),getShaderSource:Tt}}}),ug,sf,Io,cg,rf,dg,fg,hg,EI=_(()=>{ot(),ur(),ht(),_t(),Za(),Yd(),ug=i=>{let c=1;for(let h=0;h<i.length;h++)c*=i[h];return c},sf=i=>typeof i=="number"?[i,i,i]:i,Io=(i,c)=>c<=1?i:i+(i-1)*(c-1),cg=(i,c,h,m=1)=>{let y=Io(c,m);return Math.floor((i[0]*(h-1)-h+y)/2)},rf=(i,c,h,m,y)=>{y==null&&(y=cg(i,c[0],m[0]));let S=[0,0,0,h];for(let b=0;b<3;b++)i[b]+2*y>=c[b]&&(S[b]=Math.trunc((i[b]-c[b]+2*y)/m[b]+1));return S},dg=(i,c,h,m,y,S,b,E,A,I)=>{let $,x,k,N;if(i==="VALID"&&(i=0),typeof i=="number"){$={top:i,bottom:i,left:i,right:i,front:i,back:i};let M=rf([c,h,m,1],[E,A,I],1,[y,S,b],i);x=M[0],k=M[1],N=M[2]}else if(Array.isArray(i)){if(!i.every((U,z,L)=>U===L[0]))throw Error(`Unsupported padding parameter: ${i}`);$={top:i[0],bottom:i[1],left:i[2],right:i[3],front:i[4],back:i[5]};let M=rf([c,h,m,1],[E,A,I],1,[y,S,b],i[0]);x=M[0],k=M[1],N=M[2]}else if(i==="SAME_UPPER"){x=Math.ceil(c/y),k=Math.ceil(h/S),N=Math.ceil(m/b);let M=(x-1)*y+E-c,U=(k-1)*S+A-h,z=(N-1)*b+I-m,L=Math.floor(M/2),P=M-L,j=Math.floor(U/2),V=U-j,Y=Math.floor(z/2),ae=z-Y;$={top:j,bottom:V,left:Y,right:ae,front:L,back:P}}else throw Error(`Unknown padding parameter: ${i}`);return{padInfo:$,outDepth:x,outHeight:k,outWidth:N}},fg=(i,c,h,m,y,S=!1,b="channelsLast")=>{let E,A,I,$,x;if(b==="channelsLast")[E,A,I,$,x]=i;else if(b==="channelsFirst")[E,x,A,I,$]=i;else throw new Error(`Unknown dataFormat ${b}`);let[k,,N,M,U]=c,[z,L,P]=sf(h),[j,V,Y]=sf(m),ae=Io(N,j),ne=Io(M,V),de=Io(U,Y),{padInfo:ve,outDepth:Ue,outHeight:ct,outWidth:st}=dg(y,A,I,$,z,L,P,ae,ne,de),ut=S?k*x:k,$t=[0,0,0,0,0];return b==="channelsFirst"?$t=[E,ut,Ue,ct,st]:b==="channelsLast"&&($t=[E,Ue,ct,st,ut]),{batchSize:E,dataFormat:b,inDepth:A,inHeight:I,inWidth:$,inChannels:x,outDepth:Ue,outHeight:ct,outWidth:st,outChannels:ut,padInfo:ve,strideDepth:z,strideHeight:L,strideWidth:P,filterDepth:N,filterHeight:M,filterWidth:U,effectiveFilterDepth:ae,effectiveFilterHeight:ne,effectiveFilterWidth:de,dilationDepth:j,dilationHeight:V,dilationWidth:Y,inShape:i,outShape:$t,filterShape:c}},hg=(i,c,h,m,y,S)=>{let b=S==="channelsLast";b?i[0].dims[3]:i[0].dims[1];let E=[64,1,1],A={x:h.map((z,L)=>L)},I=[Math.ceil(ug(A.x.map(z=>h[z]))/E[0]),1,1];bt("verbose",()=>`[conv3d_naive_webgpu] dispatch = ${I}`);let $=1,x=ie.size(h),k=[{type:12,data:x},{type:12,data:m},{type:12,data:y},{type:12,data:c.strides},{type:12,data:c.dilations}];Qa(c,k),k.push(...Xe(i[0].dims,i[1].dims));let N=["rank","rank"],M=i.length===3;M&&(k.push(...Xe(i[2].dims)),N.push("rank")),k.push(...Xe(h));let U=z=>{let L=[{name:"output_size",type:"u32"},{name:"filter_dims",type:"u32",length:m.length},{name:"pads",type:"u32",length:y.length},{name:"strides",type:"u32",length:c.strides.length},{name:"dilations",type:"u32",length:c.dilations.length}];Xa(c,L);let P=1,j=Bt(i[0].dataType),V=he("x",i[0].dataType,i[0].dims.length,$),Y=he("W",i[1].dataType,i[1].dims.length,P),ae=[V,Y],ne=Je("result",i[0].dataType,h.length,P),de="";if(M){let ct=he("bias",i[2].dataType,i[2].dims.length,P);ae.push(ct),de+=`
1146
+ ${U?Qd(j,P,pt,void 0,!I,de):Zd(j,P,pt,void 0,!I,de,!1,void 0,E)}`};return{name:"Conv2DMatMul",shaderCache:{hint:`${c.cacheKey};${Y};${U};${ve};${Ue};${ct};${ae};${ne};${de}`,inputDependencies:$t},getRunData:()=>({outputs:[{dims:A?A(h):h,dataType:i[0].dataType}],dispatchGroup:{x:V[0],y:V[1],z:V[2]},programUniforms:ut}),getShaderSource:Tt}}}),ug,tf,Io,cg,sf,dg,fg,hg,EI=_(()=>{ot(),ur(),ht(),_t(),Za(),Kd(),ug=i=>{let c=1;for(let h=0;h<i.length;h++)c*=i[h];return c},tf=i=>typeof i=="number"?[i,i,i]:i,Io=(i,c)=>c<=1?i:i+(i-1)*(c-1),cg=(i,c,h,m=1)=>{let y=Io(c,m);return Math.floor((i[0]*(h-1)-h+y)/2)},sf=(i,c,h,m,y)=>{y==null&&(y=cg(i,c[0],m[0]));let S=[0,0,0,h];for(let b=0;b<3;b++)i[b]+2*y>=c[b]&&(S[b]=Math.trunc((i[b]-c[b]+2*y)/m[b]+1));return S},dg=(i,c,h,m,y,S,b,E,A,I)=>{let $,x,k,N;if(i==="VALID"&&(i=0),typeof i=="number"){$={top:i,bottom:i,left:i,right:i,front:i,back:i};let M=sf([c,h,m,1],[E,A,I],1,[y,S,b],i);x=M[0],k=M[1],N=M[2]}else if(Array.isArray(i)){if(!i.every((U,z,L)=>U===L[0]))throw Error(`Unsupported padding parameter: ${i}`);$={top:i[0],bottom:i[1],left:i[2],right:i[3],front:i[4],back:i[5]};let M=sf([c,h,m,1],[E,A,I],1,[y,S,b],i[0]);x=M[0],k=M[1],N=M[2]}else if(i==="SAME_UPPER"){x=Math.ceil(c/y),k=Math.ceil(h/S),N=Math.ceil(m/b);let M=(x-1)*y+E-c,U=(k-1)*S+A-h,z=(N-1)*b+I-m,L=Math.floor(M/2),P=M-L,j=Math.floor(U/2),V=U-j,Y=Math.floor(z/2),ae=z-Y;$={top:j,bottom:V,left:Y,right:ae,front:L,back:P}}else throw Error(`Unknown padding parameter: ${i}`);return{padInfo:$,outDepth:x,outHeight:k,outWidth:N}},fg=(i,c,h,m,y,S=!1,b="channelsLast")=>{let E,A,I,$,x;if(b==="channelsLast")[E,A,I,$,x]=i;else if(b==="channelsFirst")[E,x,A,I,$]=i;else throw new Error(`Unknown dataFormat ${b}`);let[k,,N,M,U]=c,[z,L,P]=tf(h),[j,V,Y]=tf(m),ae=Io(N,j),ne=Io(M,V),de=Io(U,Y),{padInfo:ve,outDepth:Ue,outHeight:ct,outWidth:st}=dg(y,A,I,$,z,L,P,ae,ne,de),ut=S?k*x:k,$t=[0,0,0,0,0];return b==="channelsFirst"?$t=[E,ut,Ue,ct,st]:b==="channelsLast"&&($t=[E,Ue,ct,st,ut]),{batchSize:E,dataFormat:b,inDepth:A,inHeight:I,inWidth:$,inChannels:x,outDepth:Ue,outHeight:ct,outWidth:st,outChannels:ut,padInfo:ve,strideDepth:z,strideHeight:L,strideWidth:P,filterDepth:N,filterHeight:M,filterWidth:U,effectiveFilterDepth:ae,effectiveFilterHeight:ne,effectiveFilterWidth:de,dilationDepth:j,dilationHeight:V,dilationWidth:Y,inShape:i,outShape:$t,filterShape:c}},hg=(i,c,h,m,y,S)=>{let b=S==="channelsLast";b?i[0].dims[3]:i[0].dims[1];let E=[64,1,1],A={x:h.map((z,L)=>L)},I=[Math.ceil(ug(A.x.map(z=>h[z]))/E[0]),1,1];bt("verbose",()=>`[conv3d_naive_webgpu] dispatch = ${I}`);let $=1,x=ie.size(h),k=[{type:12,data:x},{type:12,data:m},{type:12,data:y},{type:12,data:c.strides},{type:12,data:c.dilations}];Qa(c,k),k.push(...Xe(i[0].dims,i[1].dims));let N=["rank","rank"],M=i.length===3;M&&(k.push(...Xe(i[2].dims)),N.push("rank")),k.push(...Xe(h));let U=z=>{let L=[{name:"output_size",type:"u32"},{name:"filter_dims",type:"u32",length:m.length},{name:"pads",type:"u32",length:y.length},{name:"strides",type:"u32",length:c.strides.length},{name:"dilations",type:"u32",length:c.dilations.length}];Xa(c,L);let P=1,j=Bt(i[0].dataType),V=he("x",i[0].dataType,i[0].dims.length,$),Y=he("W",i[1].dataType,i[1].dims.length,P),ae=[V,Y],ne=Je("result",i[0].dataType,h.length,P),de="";if(M){let ct=he("bias",i[2].dataType,i[2].dims.length,P);ae.push(ct),de+=`
1147
1147
  fn getBiasByOutputCoords(coords : array<u32, 5>) -> ${j} {
1148
1148
  return bias[${b?Ze("coords",4,5):Ze("coords",1,5)}];
1149
1149
  }`}let ve=Cs($,j),Ue=Ja(c,ve,j);return`
@@ -1358,7 +1358,7 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
1358
1358
  ${L}
1359
1359
  ${U.set("batch","row","col + i","output_channel","value")};
1360
1360
  }
1361
- }`};return{name:"GroupedConv-Vectorize",shaderCache:{hint:`${c.cacheKey};${S};${b};${k};${I[0]};${I[1]}`,inputDependencies:y?["rank","rank","type"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:m?m(h):h,dataType:i[0].dataType}],dispatchGroup:{x:Math.ceil(E/64)},programUniforms:x}),getShaderSource:N}}}),mg,Xu,gg,Zu,nf,af,vg,yg,lf,AI=_(()=>{ht(),wI(),EI(),tf(),CI(),Za(),Qd(),Qs(),mg=(i,c,h,m,y,S)=>{let b=i[0],E=i.slice(S?1:2,S?3:4),A=E.length,I=c[0],$=c.slice(2).map((k,N)=>k+(k-1)*(h[N]-1)),x=E.map((k,N)=>k+m[N]+m[N+A]).map((k,N)=>Math.floor((k-$[N]+y[N])/y[N]));return x.splice(0,0,b),x.splice(S?3:1,0,I),x},Xu=[2,3,1,0],gg=(i,c)=>{if(!i||i.length!==2&&i.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(i[0].dims.length>5)throw new Error("greater than 5D is not supported");if(i[0].dims.length!==i[1].dims.length)throw new Error("filter does not have same dimension as input");let h=i[0].dims[c.format==="NHWC"?i[0].dims.length-1:1],m=i[1].dims[1]*c.group;if(h!==m)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");if(i.length===3&&(i[2].dims.length!==1||i[1].dims[0]!==i[2].dims[0]))throw new Error("invalid bias");let y=i[0].dims.length-2;if(c.dilations.length!==y)throw new Error(`dilations should be ${y}D`);if(c.strides.length!==y)throw new Error(`strides should be ${y}D`);if(c.pads.length!==y*2)throw new Error(`pads should be ${y*2}D`);if(c.kernelShape.length!==0&&c.kernelShape.length!==i[1].dims.length-2)throw new Error("invalid kernel shape")},Zu=(i,c)=>{let h=i.kernelShape.slice();h.length<c[1].dims.length-2&&h.push(...Array(c[1].dims.length-2-h.length).fill(0));for(let S=2;S<c[1].dims.length;++S)h[S-2]===0&&(h[S-2]=c[1].dims[S]);let m=i.pads.slice();Ls.adjustPadsBasedOnAutoPad(c[0].dims,i.strides,i.dilations,h,m,i.format==="NHWC",i.autoPad);let y=Object.assign({},i);return Object.assign(y,{kernelShape:h,pads:m}),y},nf=i=>{let c=Kd(i),h=i.format,m=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][i.auto_pad],y=i.dilations,S=i.group,b=i.kernel_shape,E=i.pads,A=i.strides,I=i.w_is_const();return{autoPad:m,format:h,dilations:y,group:S,kernelShape:b,pads:E,strides:A,wIsConst:I,...c,cacheKey:`${i.format};${c.activation};`}},af=(i,c,h,m)=>{let y=h.format==="NHWC",S=mg(c[0].dims,c[1].dims,h.dilations,h.pads,h.strides,y);if(h.group!==1){let ae=[c[0]];if(y){let ne=i.kernelCustomData.wT??i.compute(ms(c[1],Xu),{inputs:[1],outputs:[h.wIsConst?-2:-1]})[0];h.wIsConst&&!i.kernelCustomData.wT&&(i.kernelCustomData.wT=ne),ae.push(ne)}else ae.push(c[1]);c.length===3&&ae.push(c[2]),!i.adapterInfo.isArchitecture("ampere")&&y&&c[1].dims[0]===h.group&&c[1].dims[1]===1&&h.dilations[0]===1&&h.dilations[1]===1?i.compute(pg(ae,h,S,m),{inputs:ae}):i.compute(_g(ae,h,S,m),{inputs:ae});return}let b=c.length===3,E=c[0].dims[y?1:2],A=c[0].dims[y?2:3],I=c[0].dims[y?3:1],$=c[1].dims[2],x=c[1].dims[3],k=S[y?1:2],N=S[y?2:3],M=S[y?3:1],U=y&&$===E&&x===A&&h.pads[0]===0&&h.pads[1]===0;if(U||$===1&&x===1&&h.dilations[0]===1&&h.dilations[1]===1&&h.strides[0]===1&&h.strides[1]===1&&h.pads[0]===0&&h.pads[1]===0){let ae=S[0],ne,de,ve,Ue=[];if(y){let ut=i.kernelCustomData.wT??i.compute(ms(c[1],Xu),{inputs:[1],outputs:[h.wIsConst?-2:-1]})[0];if(h.wIsConst&&!i.kernelCustomData.wT&&(i.kernelCustomData.wT=ut),U){let $t=E*A*I;ne=c[0].reshape([1,ae,$t]),de=ut.reshape([1,$t,M]),ve=[1,ae,M]}else ne=c[0].reshape([ae,E*A,I]),de=ut.reshape([1,I,M]),ve=[ae,k*N,M];Ue.push(ne),Ue.push(de)}else ne=c[0].reshape([ae,I,E*A]),de=c[1].reshape([1,M,I]),ve=[ae,M,k*N],Ue.push(de),Ue.push(ne);b&&Ue.push(c[2]);let ct=ve[2],st=Ue[0].dims[Ue[0].dims.length-1];ct<8&&st<8?i.compute(Jd(Ue,h,S,ve,y,m),{inputs:Ue}):i.compute(Qu(Ue,h,S,ve,y,m),{inputs:Ue});return}let z=!0,L=i.kernelCustomData.wT??i.compute(ms(c[1],Xu),{inputs:[1],outputs:[h.wIsConst?-2:-1]})[0];h.wIsConst&&!i.kernelCustomData.wT&&(i.kernelCustomData.wT=L);let P=[c[0],L];b&&P.push(c[2]);let j=y?k*N:M,V=y?M:k*N,Y=$*x*I;i.compute(og(P,h,S,j,V,Y,b,z,m),{inputs:P})},vg=(i,c)=>{let h=c.format==="NHWC",m=[i.inputs[0].reshape(h?[i.inputs[0].dims[0],1,i.inputs[0].dims[1],i.inputs[0].dims[2]]:[i.inputs[0].dims[0],i.inputs[0].dims[1],1,i.inputs[0].dims[2]]),i.inputs[1].reshape([i.inputs[1].dims[0],i.inputs[1].dims[1],1,i.inputs[1].dims[2]])];i.inputs.length===3&&m.push(i.inputs[2]);let y=[0,c.pads[0],0,c.pads[1]],S=[1].concat(c.strides),b=[1].concat(c.dilations),E=[1].concat(c.kernelShape),A=Zu({...c,pads:y,strides:S,dilations:b,kernelShape:E},m);af(i,m,A,I=>h?[I[0],I[2],I[3]]:[I[0],I[1],I[3]])},yg=(i,c,h)=>{let m=h.format==="NHWC"?"channelsLast":"channelsFirst",y=Zu(h,c),S=h.autoPad==="NOTSET"?h.pads:h.autoPad,b=fg(c[0].dims,c[1].dims,h.strides,h.dilations,S,!1,m);i.compute(hg(c,y,b.outShape,[b.filterDepth,b.filterHeight,b.filterWidth],[b.padInfo.front,b.padInfo.top,b.padInfo.left],m))},lf=(i,c)=>{if(gg(i.inputs,c),i.inputs[0].dims.length===3)vg(i,c);else if(i.inputs[0].dims.length===5)yg(i,i.inputs,c);else{let h=Zu(c,i.inputs);af(i,i.inputs,h)}}}),Tg,II=_(()=>{ot(),ur(),ht(),_t(),Tg=(i,c,h)=>{let m=i.length>2,y=c.outputShape,S=c.format==="NHWC",b=c.group,E=i[1].dims,A=E[2]/b,I=E[3],$=S?Pt(A):1,x=S&&I===1&&A>=4,k=x?Math.floor(A/4)*4:Math.floor(A/$)*$,N=A-k,M=S?Pt(I):1,U=S?I===1?$:M:1,z=ie.size(y)/M,L=[Math.ceil(z/64),1,1];bt("verbose",()=>`[conv2d_backprop_webgpu] dispatch = ${L}`);let P=["rank","rank"],j=[c.strides[0],c.strides[1]],V=[c.kernelShape[S?1:2],c.kernelShape[S?2:3]],Y=[c.dilations[0],c.dilations[1]],ae=[V[0]+(c.dilations[0]<=1?0:(c.kernelShape[S?1:2]-1)*(c.dilations[0]-1)),V[1]+(c.dilations[1]<=1?0:(c.kernelShape[S?2:3]-1)*(c.dilations[1]-1))],ne=[ae[0]-1-Math.floor((c.pads[0]+c.pads[2])/2),ae[1]-1-Math.floor((c.pads[1]+c.pads[3])/2)],de=[{type:12,data:z},{type:12,data:j},{type:12,data:V},{type:12,data:Y},{type:12,data:ae},{type:6,data:ne},{type:12,data:k},{type:12,data:A},{type:12,data:I},...Xe(i[0].dims,i[1].dims)];m&&(de.push(...Xe(i[2].dims)),P.push("rank")),de.push(...Xe(y));let ve=Ue=>{let ct=[{name:"output_size",type:"u32"},{name:"strides",type:"u32",length:j.length},{name:"filter_dims",type:"u32",length:V.length},{name:"dilations",type:"u32",length:V.length},{name:"effective_filter_dims",type:"u32",length:ae.length},{name:"pads",type:"i32",length:ne.length},{name:"input_channels_per_group_int",type:"u32"},{name:"input_channels_per_group",type:"u32"},{name:"output_channels_per_group",type:"u32"}],st=Bt(i[0].dataType),ut=S?1:2,$t=S?2:3,Tt=S?3:1,at=he("W",i[1].dataType,i[1].dims.length,U),St=he("Dy",i[0].dataType,i[0].dims.length,$),it=[St,at];m&&it.push(he("bias",i[2].dataType,[y[Tt]].length,M));let pt=Je("result",i[0].dataType,y.length,M),Fs=()=>{let lt="";if(x)$===4?lt+=`
1361
+ }`};return{name:"GroupedConv-Vectorize",shaderCache:{hint:`${c.cacheKey};${S};${b};${k};${I[0]};${I[1]}`,inputDependencies:y?["rank","rank","type"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:m?m(h):h,dataType:i[0].dataType}],dispatchGroup:{x:Math.ceil(E/64)},programUniforms:x}),getShaderSource:N}}}),mg,Xu,gg,Zu,rf,nf,vg,yg,af,AI=_(()=>{ht(),wI(),EI(),ef(),CI(),Za(),Jd(),Qs(),mg=(i,c,h,m,y,S)=>{let b=i[0],E=i.slice(S?1:2,S?3:4),A=E.length,I=c[0],$=c.slice(2).map((k,N)=>k+(k-1)*(h[N]-1)),x=E.map((k,N)=>k+m[N]+m[N+A]).map((k,N)=>Math.floor((k-$[N]+y[N])/y[N]));return x.splice(0,0,b),x.splice(S?3:1,0,I),x},Xu=[2,3,1,0],gg=(i,c)=>{if(!i||i.length!==2&&i.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(i[0].dims.length>5)throw new Error("greater than 5D is not supported");if(i[0].dims.length!==i[1].dims.length)throw new Error("filter does not have same dimension as input");let h=i[0].dims[c.format==="NHWC"?i[0].dims.length-1:1],m=i[1].dims[1]*c.group;if(h!==m)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");if(i.length===3&&(i[2].dims.length!==1||i[1].dims[0]!==i[2].dims[0]))throw new Error("invalid bias");let y=i[0].dims.length-2;if(c.dilations.length!==y)throw new Error(`dilations should be ${y}D`);if(c.strides.length!==y)throw new Error(`strides should be ${y}D`);if(c.pads.length!==y*2)throw new Error(`pads should be ${y*2}D`);if(c.kernelShape.length!==0&&c.kernelShape.length!==i[1].dims.length-2)throw new Error("invalid kernel shape")},Zu=(i,c)=>{let h=i.kernelShape.slice();h.length<c[1].dims.length-2&&h.push(...Array(c[1].dims.length-2-h.length).fill(0));for(let S=2;S<c[1].dims.length;++S)h[S-2]===0&&(h[S-2]=c[1].dims[S]);let m=i.pads.slice();Ls.adjustPadsBasedOnAutoPad(c[0].dims,i.strides,i.dilations,h,m,i.format==="NHWC",i.autoPad);let y=Object.assign({},i);return Object.assign(y,{kernelShape:h,pads:m}),y},rf=i=>{let c=Wd(i),h=i.format,m=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][i.auto_pad],y=i.dilations,S=i.group,b=i.kernel_shape,E=i.pads,A=i.strides,I=i.w_is_const();return{autoPad:m,format:h,dilations:y,group:S,kernelShape:b,pads:E,strides:A,wIsConst:I,...c,cacheKey:`${i.format};${c.activation};`}},nf=(i,c,h,m)=>{let y=h.format==="NHWC",S=mg(c[0].dims,c[1].dims,h.dilations,h.pads,h.strides,y);if(h.group!==1){let ae=[c[0]];if(y){let ne=i.kernelCustomData.wT??i.compute(ms(c[1],Xu),{inputs:[1],outputs:[h.wIsConst?-2:-1]})[0];h.wIsConst&&!i.kernelCustomData.wT&&(i.kernelCustomData.wT=ne),ae.push(ne)}else ae.push(c[1]);c.length===3&&ae.push(c[2]),!i.adapterInfo.isArchitecture("ampere")&&y&&c[1].dims[0]===h.group&&c[1].dims[1]===1&&h.dilations[0]===1&&h.dilations[1]===1?i.compute(pg(ae,h,S,m),{inputs:ae}):i.compute(_g(ae,h,S,m),{inputs:ae});return}let b=c.length===3,E=c[0].dims[y?1:2],A=c[0].dims[y?2:3],I=c[0].dims[y?3:1],$=c[1].dims[2],x=c[1].dims[3],k=S[y?1:2],N=S[y?2:3],M=S[y?3:1],U=y&&$===E&&x===A&&h.pads[0]===0&&h.pads[1]===0;if(U||$===1&&x===1&&h.dilations[0]===1&&h.dilations[1]===1&&h.strides[0]===1&&h.strides[1]===1&&h.pads[0]===0&&h.pads[1]===0){let ae=S[0],ne,de,ve,Ue=[];if(y){let ut=i.kernelCustomData.wT??i.compute(ms(c[1],Xu),{inputs:[1],outputs:[h.wIsConst?-2:-1]})[0];if(h.wIsConst&&!i.kernelCustomData.wT&&(i.kernelCustomData.wT=ut),U){let $t=E*A*I;ne=c[0].reshape([1,ae,$t]),de=ut.reshape([1,$t,M]),ve=[1,ae,M]}else ne=c[0].reshape([ae,E*A,I]),de=ut.reshape([1,I,M]),ve=[ae,k*N,M];Ue.push(ne),Ue.push(de)}else ne=c[0].reshape([ae,I,E*A]),de=c[1].reshape([1,M,I]),ve=[ae,M,k*N],Ue.push(de),Ue.push(ne);b&&Ue.push(c[2]);let ct=ve[2],st=Ue[0].dims[Ue[0].dims.length-1];ct<8&&st<8?i.compute(Yd(Ue,h,S,ve,y,m),{inputs:Ue}):i.compute(Qu(Ue,h,S,ve,y,m),{inputs:Ue});return}let z=!0,L=i.kernelCustomData.wT??i.compute(ms(c[1],Xu),{inputs:[1],outputs:[h.wIsConst?-2:-1]})[0];h.wIsConst&&!i.kernelCustomData.wT&&(i.kernelCustomData.wT=L);let P=[c[0],L];b&&P.push(c[2]);let j=y?k*N:M,V=y?M:k*N,Y=$*x*I;i.compute(og(P,h,S,j,V,Y,b,z,m),{inputs:P})},vg=(i,c)=>{let h=c.format==="NHWC",m=[i.inputs[0].reshape(h?[i.inputs[0].dims[0],1,i.inputs[0].dims[1],i.inputs[0].dims[2]]:[i.inputs[0].dims[0],i.inputs[0].dims[1],1,i.inputs[0].dims[2]]),i.inputs[1].reshape([i.inputs[1].dims[0],i.inputs[1].dims[1],1,i.inputs[1].dims[2]])];i.inputs.length===3&&m.push(i.inputs[2]);let y=[0,c.pads[0],0,c.pads[1]],S=[1].concat(c.strides),b=[1].concat(c.dilations),E=[1].concat(c.kernelShape),A=Zu({...c,pads:y,strides:S,dilations:b,kernelShape:E},m);nf(i,m,A,I=>h?[I[0],I[2],I[3]]:[I[0],I[1],I[3]])},yg=(i,c,h)=>{let m=h.format==="NHWC"?"channelsLast":"channelsFirst",y=Zu(h,c),S=h.autoPad==="NOTSET"?h.pads:h.autoPad,b=fg(c[0].dims,c[1].dims,h.strides,h.dilations,S,!1,m);i.compute(hg(c,y,b.outShape,[b.filterDepth,b.filterHeight,b.filterWidth],[b.padInfo.front,b.padInfo.top,b.padInfo.left],m))},af=(i,c)=>{if(gg(i.inputs,c),i.inputs[0].dims.length===3)vg(i,c);else if(i.inputs[0].dims.length===5)yg(i,i.inputs,c);else{let h=Zu(c,i.inputs);nf(i,i.inputs,h)}}}),Tg,II=_(()=>{ot(),ur(),ht(),_t(),Tg=(i,c,h)=>{let m=i.length>2,y=c.outputShape,S=c.format==="NHWC",b=c.group,E=i[1].dims,A=E[2]/b,I=E[3],$=S?Pt(A):1,x=S&&I===1&&A>=4,k=x?Math.floor(A/4)*4:Math.floor(A/$)*$,N=A-k,M=S?Pt(I):1,U=S?I===1?$:M:1,z=ie.size(y)/M,L=[Math.ceil(z/64),1,1];bt("verbose",()=>`[conv2d_backprop_webgpu] dispatch = ${L}`);let P=["rank","rank"],j=[c.strides[0],c.strides[1]],V=[c.kernelShape[S?1:2],c.kernelShape[S?2:3]],Y=[c.dilations[0],c.dilations[1]],ae=[V[0]+(c.dilations[0]<=1?0:(c.kernelShape[S?1:2]-1)*(c.dilations[0]-1)),V[1]+(c.dilations[1]<=1?0:(c.kernelShape[S?2:3]-1)*(c.dilations[1]-1))],ne=[ae[0]-1-Math.floor((c.pads[0]+c.pads[2])/2),ae[1]-1-Math.floor((c.pads[1]+c.pads[3])/2)],de=[{type:12,data:z},{type:12,data:j},{type:12,data:V},{type:12,data:Y},{type:12,data:ae},{type:6,data:ne},{type:12,data:k},{type:12,data:A},{type:12,data:I},...Xe(i[0].dims,i[1].dims)];m&&(de.push(...Xe(i[2].dims)),P.push("rank")),de.push(...Xe(y));let ve=Ue=>{let ct=[{name:"output_size",type:"u32"},{name:"strides",type:"u32",length:j.length},{name:"filter_dims",type:"u32",length:V.length},{name:"dilations",type:"u32",length:V.length},{name:"effective_filter_dims",type:"u32",length:ae.length},{name:"pads",type:"i32",length:ne.length},{name:"input_channels_per_group_int",type:"u32"},{name:"input_channels_per_group",type:"u32"},{name:"output_channels_per_group",type:"u32"}],st=Bt(i[0].dataType),ut=S?1:2,$t=S?2:3,Tt=S?3:1,at=he("W",i[1].dataType,i[1].dims.length,U),St=he("Dy",i[0].dataType,i[0].dims.length,$),it=[St,at];m&&it.push(he("bias",i[2].dataType,[y[Tt]].length,M));let pt=Je("result",i[0].dataType,y.length,M),Fs=()=>{let lt="";if(x)$===4?lt+=`
1362
1362
  let xValue = ${St.getByOffset("x_offset")};
1363
1363
  let wValue = ${at.getByOffset("w_offset")};
1364
1364
  dotProd = dotProd + dot(xValue, wValue);
@@ -1446,7 +1446,7 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
1446
1446
  ${Ue.registerUniforms(ct).declareVariables(...it,pt)}
1447
1447
  ${Ue.mainStart()}
1448
1448
  ${Ue.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")};
1449
- ${Be}}`};return{name:"ConvTranspose2D",shaderCache:{hint:`${c.cacheKey};${$}${U}${M}${x}${N}`,inputDependencies:P},getRunData:()=>({dispatchGroup:{x:L[0],y:L[1],z:L[2]},outputs:[{dims:h?h(y):y,dataType:i[0].dataType}],programUniforms:de}),getShaderSource:ve}}}),Sg,bg,wg,of,Eg,Cg,uf,Ag,Ig,RI=_(()=>{II(),Za(),Qs(),Sg=(i,c,h,m,y,S)=>(i-1)*c+h+(m-1)*y+1-S,bg=(i,c,h,m,y)=>{let S=Math.floor(i/2);c==="SAME_UPPER"?(h[m]=S,h[y]=i-S):c==="SAME_LOWER"&&(h[m]=i-S,h[y]=S)},wg=(i,c,h,m,y,S,b,E,A,I)=>{let $=i.length-2,x=I.length===0;A.length<$&&A.push(...Array($-A.length).fill(0));let k=i[0],N=c[E?3:1]*y;for(let M=0,U=i.length-$-(E?1:0);M<$;++M,++U){let z=i[U],L=x?z*b[M]:I[M],P=Sg(z,b[M],S[M],c[U],h[M],L);bg(P,m,S,M,M+$),x&&I.push(b[M]*(z-1)+A[M]+(c[U]-1)*h[M]+1-S[M]-S[M+$])}I.splice(0,0,k),I.splice(E?3:1,0,N)},of=(i,c)=>{let h=i.kernelShape.slice();if(i.kernelShape.length===0||i.kernelShape.reduce((x,k)=>x*k,1)===0){h.length=0;for(let x=2;x<c[1].dims.length;++x)h.push(c[1].dims[x])}let m=i.format==="NHWC";h.splice(0,0,c[1].dims[0]),h.splice(m?3:1,0,c[1].dims[1]);let y=i.pads.slice(),S=i.outputShape.slice(),b=i.outputPadding.slice(),E=c[0].dims,A=i.dilations.slice();if(A.reduce((x,k)=>x+k,0)===0){let x=c[0].dims.length-2;A=new Array(x).fill(1)}let I=i.strides.slice();if(I.reduce((x,k)=>x+k,0)===0){let x=c[0].dims.length-2;I=new Array(x).fill(1)}wg(E,h,A,i.autoPad,i.group,y,I,m,b,S);let $=Object.assign({},i);return Object.assign($,{kernelShape:h,pads:y,outputPadding:b,outputShape:S,dilations:A,strides:I}),$},Eg=i=>{let c=Kd(i),h=i.format,m=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][typeof i.autoPad>"u"?0:i.autoPad],y=i.dilations,S=i.group,b=i.kernelShape,E=i.pads,A=i.strides,I=i.wIsConst(),$=i.outputPadding,x=i.outputShape;return{autoPad:m,format:h,dilations:y,group:S,kernelShape:b,outputPadding:$,outputShape:x,pads:E,strides:A,wIsConst:I,...c,cacheKey:`${i.format};${c.activation};`}},Cg=(i,c)=>{if(!i||i.length!==2&&i.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(i[0].dims.length!==4&&i[0].dims.length!==3)throw new Error("currently only support 2-dimensional conv");if(i[0].dims.length!==i[1].dims.length)throw new Error("filter does not have same dimension as input");let h=i[0].dims[c.format==="NHWC"?i[0].dims.length-1:1],m=i[1].dims[0];if(h!==m)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");let y=i[1].dims[1]*c.group;if(i.length===3&&(i[2].dims.length!==1||i[2].dims[0]!==y))throw new Error("invalid bias");let S=i[0].dims.length-2;if(c.dilations.reduce((b,E)=>b+E,0)>0&&c.dilations.length!==S)throw new Error(`dilations should be ${S}D`);if(c.strides.reduce((b,E)=>b+E,0)>0&&c.strides.length!==S)throw new Error(`strides should be ${S}D`);if(c.pads.reduce((b,E)=>b+E,0)>0&&c.pads.length!==S*2)throw new Error(`pads should be ${S*2}D`);if(c.outputPadding.length!==S&&c.outputPadding.length!==0)throw new Error(`output_padding should be ${S}D`);if(c.kernelShape.reduce((b,E)=>b+E,0)>0&&c.kernelShape.length!==0&&c.kernelShape.length!==i[1].dims.length-2)throw new Error("invalid kernel shape");if(c.outputShape.length!==0&&c.outputShape.length!==i[0].dims.length-2)throw new Error("invalid output shape")},uf=(i,c,h,m)=>{let y=i.kernelCustomData.wT??i.compute(ms(c[1],[2,3,0,1]),{inputs:[1],outputs:[h.wIsConst?-2:-1]})[0];h.wIsConst&&!i.kernelCustomData.wT&&(i.kernelCustomData.wT=y);let S=[c[0],y];c.length===3&&S.push(c[2]),i.compute(Tg(S,h,m),{inputs:S})},Ag=(i,c)=>{let h=c.format==="NHWC",m=[i.inputs[0].reshape(h?[i.inputs[0].dims[0],1,i.inputs[0].dims[1],i.inputs[0].dims[2]]:[i.inputs[0].dims[0],i.inputs[0].dims[1],1,i.inputs[0].dims[2]]),i.inputs[1].reshape([i.inputs[1].dims[0],i.inputs[1].dims[1],1,i.inputs[1].dims[2]])];i.inputs.length===3&&m.push(i.inputs[2]);let y=c.kernelShape;(y.length===0||y[0]===0)&&(y=[i.inputs[1].dims[2]]);let S=c.dilations;(S.length===0||S[0]===0)&&(S=[1]);let b=c.strides;(b.length===0||b[0]===0)&&(b=[1]);let E=c.pads;E.length===0&&(E=[0,0]),E=[0,E[0],0,E[1]],b=[1].concat(b),S=[1].concat(S),y=[1].concat(y);let A=c.outputPadding;A=[0].concat(A);let I=of({...c,pads:E,strides:b,dilations:S,kernelShape:y,outputPadding:A},m);uf(i,m,I,$=>h?[$[0],$[2],$[3]]:[$[0],$[1],$[3]])},Ig=(i,c)=>{if(Cg(i.inputs,c),i.inputs[0].dims.length===3)Ag(i,c);else{let h=of(c,i.inputs);uf(i,i.inputs,h)}}}),Rg,$g,xg,$I=_(()=>{ot(),ht(),jt(),_t(),Rg=(i,c,h,m)=>{let y=ie.size(c),S=c.length,b=he("input",i,S),E=Je("output",i,S),A=h.dataType===6?h.getInt32Array()[0]:Number(h.getBigInt64Array()[0]),I=ie.normalizeAxis(A,S),$=x=>{let k=` i32(${b.indicesGet("inputIndices","uniforms.axis")}) `,N=Ze("uniforms.input_shape","uniforms.axis",S),M=m.reverse?k+(m.exclusive?" + 1":""):"0",U=m.reverse?N:k+(m.exclusive?"":" + 1");return`
1449
+ ${Be}}`};return{name:"ConvTranspose2D",shaderCache:{hint:`${c.cacheKey};${$}${U}${M}${x}${N}`,inputDependencies:P},getRunData:()=>({dispatchGroup:{x:L[0],y:L[1],z:L[2]},outputs:[{dims:h?h(y):y,dataType:i[0].dataType}],programUniforms:de}),getShaderSource:ve}}}),Sg,bg,wg,lf,Eg,Cg,of,Ag,Ig,RI=_(()=>{II(),Za(),Qs(),Sg=(i,c,h,m,y,S)=>(i-1)*c+h+(m-1)*y+1-S,bg=(i,c,h,m,y)=>{let S=Math.floor(i/2);c==="SAME_UPPER"?(h[m]=S,h[y]=i-S):c==="SAME_LOWER"&&(h[m]=i-S,h[y]=S)},wg=(i,c,h,m,y,S,b,E,A,I)=>{let $=i.length-2,x=I.length===0;A.length<$&&A.push(...Array($-A.length).fill(0));let k=i[0],N=c[E?3:1]*y;for(let M=0,U=i.length-$-(E?1:0);M<$;++M,++U){let z=i[U],L=x?z*b[M]:I[M],P=Sg(z,b[M],S[M],c[U],h[M],L);bg(P,m,S,M,M+$),x&&I.push(b[M]*(z-1)+A[M]+(c[U]-1)*h[M]+1-S[M]-S[M+$])}I.splice(0,0,k),I.splice(E?3:1,0,N)},lf=(i,c)=>{let h=i.kernelShape.slice();if(i.kernelShape.length===0||i.kernelShape.reduce((x,k)=>x*k,1)===0){h.length=0;for(let x=2;x<c[1].dims.length;++x)h.push(c[1].dims[x])}let m=i.format==="NHWC";h.splice(0,0,c[1].dims[0]),h.splice(m?3:1,0,c[1].dims[1]);let y=i.pads.slice(),S=i.outputShape.slice(),b=i.outputPadding.slice(),E=c[0].dims,A=i.dilations.slice();if(A.reduce((x,k)=>x+k,0)===0){let x=c[0].dims.length-2;A=new Array(x).fill(1)}let I=i.strides.slice();if(I.reduce((x,k)=>x+k,0)===0){let x=c[0].dims.length-2;I=new Array(x).fill(1)}wg(E,h,A,i.autoPad,i.group,y,I,m,b,S);let $=Object.assign({},i);return Object.assign($,{kernelShape:h,pads:y,outputPadding:b,outputShape:S,dilations:A,strides:I}),$},Eg=i=>{let c=Wd(i),h=i.format,m=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][typeof i.autoPad>"u"?0:i.autoPad],y=i.dilations,S=i.group,b=i.kernelShape,E=i.pads,A=i.strides,I=i.wIsConst(),$=i.outputPadding,x=i.outputShape;return{autoPad:m,format:h,dilations:y,group:S,kernelShape:b,outputPadding:$,outputShape:x,pads:E,strides:A,wIsConst:I,...c,cacheKey:`${i.format};${c.activation};`}},Cg=(i,c)=>{if(!i||i.length!==2&&i.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(i[0].dims.length!==4&&i[0].dims.length!==3)throw new Error("currently only support 2-dimensional conv");if(i[0].dims.length!==i[1].dims.length)throw new Error("filter does not have same dimension as input");let h=i[0].dims[c.format==="NHWC"?i[0].dims.length-1:1],m=i[1].dims[0];if(h!==m)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");let y=i[1].dims[1]*c.group;if(i.length===3&&(i[2].dims.length!==1||i[2].dims[0]!==y))throw new Error("invalid bias");let S=i[0].dims.length-2;if(c.dilations.reduce((b,E)=>b+E,0)>0&&c.dilations.length!==S)throw new Error(`dilations should be ${S}D`);if(c.strides.reduce((b,E)=>b+E,0)>0&&c.strides.length!==S)throw new Error(`strides should be ${S}D`);if(c.pads.reduce((b,E)=>b+E,0)>0&&c.pads.length!==S*2)throw new Error(`pads should be ${S*2}D`);if(c.outputPadding.length!==S&&c.outputPadding.length!==0)throw new Error(`output_padding should be ${S}D`);if(c.kernelShape.reduce((b,E)=>b+E,0)>0&&c.kernelShape.length!==0&&c.kernelShape.length!==i[1].dims.length-2)throw new Error("invalid kernel shape");if(c.outputShape.length!==0&&c.outputShape.length!==i[0].dims.length-2)throw new Error("invalid output shape")},of=(i,c,h,m)=>{let y=i.kernelCustomData.wT??i.compute(ms(c[1],[2,3,0,1]),{inputs:[1],outputs:[h.wIsConst?-2:-1]})[0];h.wIsConst&&!i.kernelCustomData.wT&&(i.kernelCustomData.wT=y);let S=[c[0],y];c.length===3&&S.push(c[2]),i.compute(Tg(S,h,m),{inputs:S})},Ag=(i,c)=>{let h=c.format==="NHWC",m=[i.inputs[0].reshape(h?[i.inputs[0].dims[0],1,i.inputs[0].dims[1],i.inputs[0].dims[2]]:[i.inputs[0].dims[0],i.inputs[0].dims[1],1,i.inputs[0].dims[2]]),i.inputs[1].reshape([i.inputs[1].dims[0],i.inputs[1].dims[1],1,i.inputs[1].dims[2]])];i.inputs.length===3&&m.push(i.inputs[2]);let y=c.kernelShape;(y.length===0||y[0]===0)&&(y=[i.inputs[1].dims[2]]);let S=c.dilations;(S.length===0||S[0]===0)&&(S=[1]);let b=c.strides;(b.length===0||b[0]===0)&&(b=[1]);let E=c.pads;E.length===0&&(E=[0,0]),E=[0,E[0],0,E[1]],b=[1].concat(b),S=[1].concat(S),y=[1].concat(y);let A=c.outputPadding;A=[0].concat(A);let I=lf({...c,pads:E,strides:b,dilations:S,kernelShape:y,outputPadding:A},m);of(i,m,I,$=>h?[$[0],$[2],$[3]]:[$[0],$[1],$[3]])},Ig=(i,c)=>{if(Cg(i.inputs,c),i.inputs[0].dims.length===3)Ag(i,c);else{let h=lf(c,i.inputs);of(i,i.inputs,h)}}}),Rg,$g,xg,$I=_(()=>{ot(),ht(),jt(),_t(),Rg=(i,c,h,m)=>{let y=ie.size(c),S=c.length,b=he("input",i,S),E=Je("output",i,S),A=h.dataType===6?h.getInt32Array()[0]:Number(h.getBigInt64Array()[0]),I=ie.normalizeAxis(A,S),$=x=>{let k=` i32(${b.indicesGet("inputIndices","uniforms.axis")}) `,N=Ze("uniforms.input_shape","uniforms.axis",S),M=m.reverse?k+(m.exclusive?" + 1":""):"0",U=m.reverse?N:k+(m.exclusive?"":" + 1");return`
1450
1450
  ${x.registerUniform("outputSize","u32").registerUniform("axis","u32").declareVariables(b,E)}
1451
1451
  ${x.mainStart()}
1452
1452
  ${x.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}
@@ -1473,8 +1473,8 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
1473
1473
  let aIndices = perm(indices);
1474
1474
 
1475
1475
  ${U.setByOffset("global_idx",M.getByIndices("aIndices"))}
1476
- }`;return{name:"DepthToSpace",shaderCache:{hint:`${i.dims};${c.blocksize};${c.mode}`,inputDependencies:["rank"]},getRunData:L=>{let P=A?[h,m*I,y*I,S/I**2]:[h,S/I**2,m*I,y*I],j=ie.size(P),V=x.dims,Y=ie.sortBasedOnPerm(V,E);return{outputs:[{dims:P,dataType:L[0].dataType}],dispatchGroup:{x:Math.ceil(j/64)},programUniforms:[{type:12,data:j},...Xe(V,Y)]}},getShaderSource:z}},Ng=(i,c)=>{Og(i.inputs),i.compute(kg(i.inputs[0],c))},Mg=i=>Rt({blocksize:i.blocksize,mode:i.mode,format:i.format})}),ec,Ro,cf,Ug,Pg,Lg,Hg,df,Fg,Bg,zg,OI=_(()=>{ot(),ht(),jt(),_t(),ec="[a-zA-Z]|\\.\\.\\.",Ro="("+ec+")+",cf="^"+Ro+"$",Ug="("+Ro+",)*"+Ro,Pg="^"+Ug+"$",Lg=class{constructor(i=-1){this.symbolToIndices=new Map,this.inputIndex=i}addSymbol(i,c){let h=this.symbolToIndices.get(i);h===void 0?h=[c]:h.push(c),this.symbolToIndices.set(i,h)}},Hg=class{constructor(i,c){var y;this.equation=c,this.hasEllipsis=!1,this.symbolToInfo=new Map,this.lhs=new Array,this.outputDims=[];let[h,m]=c.includes("->")?c.split("->",2):[c,""];if(!h.match(RegExp(Pg)))throw new Error("Invalid LHS term");if(h.split(",").forEach((S,b)=>{let E=i[b].dims.slice();if(!S.match(RegExp(cf)))throw new Error("Invalid LHS term");let A=this.processTerm(S,!0,E,b);this.lhs.push(A)}),m==="")m+=[...this.symbolToInfo.entries()].filter(([S,b])=>b.count===1||S==="...").map(([S])=>S).join("");else if(!m.match(RegExp(Ro)))throw new Error("Invalid RHS");(y=m.match(RegExp(ec,"g")))==null||y.forEach(S=>{if(S==="...")this.outputDims=this.outputDims.concat(this.ellipsisDims);else{let b=this.symbolToInfo.get(S);if(b===void 0)throw new Error("Invalid RHS symbol");this.outputDims.push(b.dimValue)}}),this.rhs=this.processTerm(m,!1,this.outputDims)}addSymbol(i,c,h){let m=this.symbolToInfo.get(i);if(m!==void 0){if(m.dimValue!==c&&m.count!==1)throw new Error("Dimension mismatch");m.count++,m.inputIndices.push(h)}else m={count:1,dimValue:c,inputIndices:[h]};this.symbolToInfo.set(i,m)}processTerm(i,c,h,m=-1){let y=h.length,S=!1,b=[],E=0;if(!i.match(RegExp(cf))&&!c&&i!=="")throw new Error("Invalid LHS term");let A=i.match(RegExp(ec,"g")),I=new Lg(m);return A==null||A.forEach(($,x)=>{if($==="..."){if(S)throw new Error("Only one ellipsis is allowed per input term");S=!0;let k=y-A.length+1;if(k<0)throw new Error("Ellipsis out of bounds");if(b=h.slice(E,E+k),this.hasEllipsis){if(this.ellipsisDims.length!==b.length||this.ellipsisDims.toString()!==b.toString())throw new Error("Ellipsis dimensions mismatch")}else if(c)this.hasEllipsis=!0,this.ellipsisDims=b;else throw new Error("Ellipsis must be specified in the LHS");for(let N=0;N<b.length;N++){let M=String.fromCharCode(48+N);I.addSymbol(M,x+N),this.addSymbol(M,h[E++],m)}}else I.addSymbol($,x+(this.hasEllipsis?this.ellipsisDims.length-1:0)),this.addSymbol($,h[E++],m)}),I}},df=i=>i+"_max",Fg=(i,c,h,m)=>{let y=i.map(I=>I.length).map((I,$)=>he(`input${$}`,c,I)),S=ie.size(m),b=Je("output",c,m.length),E=[...h.symbolToInfo.keys()].filter(I=>!h.rhs.symbolToIndices.has(I)),A=I=>{let $=[],x="var prod = 1.0;",k="var sum = 0.0;",N="sum += prod;",M=[],U=[],z=[],L=[],P=h.symbolToInfo.size===h.rhs.symbolToIndices.size;h.symbolToInfo.forEach((V,Y)=>{var ae;if(h.rhs.symbolToIndices.has(Y)){let ne=(ae=h.rhs.symbolToIndices.get(Y))==null?void 0:ae[0];ne!==void 0&&h.lhs.forEach((de,ve)=>{if(V.inputIndices.includes(ve)){let Ue=de.symbolToIndices.get(Y);if(Ue===void 0)throw new Error("Invalid symbol error");Ue.forEach(ct=>{$.push(`${y[ve].indicesSet(`input${ve}Indices`,ct,b.indicesGet("outputIndices",ne))}`)})}})}else h.lhs.forEach((ne,de)=>{if(V.inputIndices.includes(de)){let ve=ne.symbolToIndices.get(Y);if(ve===void 0)throw new Error("Invalid symbol error");ve.forEach(Ue=>{M.push(`${y[de].indicesSet(`input${de}Indices`,Ue,`${Y}`)}`)}),L.push(`prod *= ${y[de].getByIndices(`input${de}Indices`)};`)}}),U.push(`for(var ${Y}: u32 = 0; ${Y} < uniforms.${df(Y)}; ${Y}++) {`),z.push("}")});let j=P?[...$,`let sum = ${y.map((V,Y)=>V.getByIndices(`input${Y}Indices`)).join(" * ")};`]:[...$,k,...U,...M,x,...L,N,...z];return`
1477
- ${I.registerUniforms(E.map(V=>({name:`${df(V)}`,type:"u32"}))).registerUniform("outputSize","u32").declareVariables(...y,b)}
1476
+ }`;return{name:"DepthToSpace",shaderCache:{hint:`${i.dims};${c.blocksize};${c.mode}`,inputDependencies:["rank"]},getRunData:L=>{let P=A?[h,m*I,y*I,S/I**2]:[h,S/I**2,m*I,y*I],j=ie.size(P),V=x.dims,Y=ie.sortBasedOnPerm(V,E);return{outputs:[{dims:P,dataType:L[0].dataType}],dispatchGroup:{x:Math.ceil(j/64)},programUniforms:[{type:12,data:j},...Xe(V,Y)]}},getShaderSource:z}},Ng=(i,c)=>{Og(i.inputs),i.compute(kg(i.inputs[0],c))},Mg=i=>Rt({blocksize:i.blocksize,mode:i.mode,format:i.format})}),ec,Ro,uf,Ug,Pg,Lg,Hg,cf,Fg,Bg,zg,OI=_(()=>{ot(),ht(),jt(),_t(),ec="[a-zA-Z]|\\.\\.\\.",Ro="("+ec+")+",uf="^"+Ro+"$",Ug="("+Ro+",)*"+Ro,Pg="^"+Ug+"$",Lg=class{constructor(i=-1){this.symbolToIndices=new Map,this.inputIndex=i}addSymbol(i,c){let h=this.symbolToIndices.get(i);h===void 0?h=[c]:h.push(c),this.symbolToIndices.set(i,h)}},Hg=class{constructor(i,c){var y;this.equation=c,this.hasEllipsis=!1,this.symbolToInfo=new Map,this.lhs=new Array,this.outputDims=[];let[h,m]=c.includes("->")?c.split("->",2):[c,""];if(!h.match(RegExp(Pg)))throw new Error("Invalid LHS term");if(h.split(",").forEach((S,b)=>{let E=i[b].dims.slice();if(!S.match(RegExp(uf)))throw new Error("Invalid LHS term");let A=this.processTerm(S,!0,E,b);this.lhs.push(A)}),m==="")m+=[...this.symbolToInfo.entries()].filter(([S,b])=>b.count===1||S==="...").map(([S])=>S).join("");else if(!m.match(RegExp(Ro)))throw new Error("Invalid RHS");(y=m.match(RegExp(ec,"g")))==null||y.forEach(S=>{if(S==="...")this.outputDims=this.outputDims.concat(this.ellipsisDims);else{let b=this.symbolToInfo.get(S);if(b===void 0)throw new Error("Invalid RHS symbol");this.outputDims.push(b.dimValue)}}),this.rhs=this.processTerm(m,!1,this.outputDims)}addSymbol(i,c,h){let m=this.symbolToInfo.get(i);if(m!==void 0){if(m.dimValue!==c&&m.count!==1)throw new Error("Dimension mismatch");m.count++,m.inputIndices.push(h)}else m={count:1,dimValue:c,inputIndices:[h]};this.symbolToInfo.set(i,m)}processTerm(i,c,h,m=-1){let y=h.length,S=!1,b=[],E=0;if(!i.match(RegExp(uf))&&!c&&i!=="")throw new Error("Invalid LHS term");let A=i.match(RegExp(ec,"g")),I=new Lg(m);return A==null||A.forEach(($,x)=>{if($==="..."){if(S)throw new Error("Only one ellipsis is allowed per input term");S=!0;let k=y-A.length+1;if(k<0)throw new Error("Ellipsis out of bounds");if(b=h.slice(E,E+k),this.hasEllipsis){if(this.ellipsisDims.length!==b.length||this.ellipsisDims.toString()!==b.toString())throw new Error("Ellipsis dimensions mismatch")}else if(c)this.hasEllipsis=!0,this.ellipsisDims=b;else throw new Error("Ellipsis must be specified in the LHS");for(let N=0;N<b.length;N++){let M=String.fromCharCode(48+N);I.addSymbol(M,x+N),this.addSymbol(M,h[E++],m)}}else I.addSymbol($,x+(this.hasEllipsis?this.ellipsisDims.length-1:0)),this.addSymbol($,h[E++],m)}),I}},cf=i=>i+"_max",Fg=(i,c,h,m)=>{let y=i.map(I=>I.length).map((I,$)=>he(`input${$}`,c,I)),S=ie.size(m),b=Je("output",c,m.length),E=[...h.symbolToInfo.keys()].filter(I=>!h.rhs.symbolToIndices.has(I)),A=I=>{let $=[],x="var prod = 1.0;",k="var sum = 0.0;",N="sum += prod;",M=[],U=[],z=[],L=[],P=h.symbolToInfo.size===h.rhs.symbolToIndices.size;h.symbolToInfo.forEach((V,Y)=>{var ae;if(h.rhs.symbolToIndices.has(Y)){let ne=(ae=h.rhs.symbolToIndices.get(Y))==null?void 0:ae[0];ne!==void 0&&h.lhs.forEach((de,ve)=>{if(V.inputIndices.includes(ve)){let Ue=de.symbolToIndices.get(Y);if(Ue===void 0)throw new Error("Invalid symbol error");Ue.forEach(ct=>{$.push(`${y[ve].indicesSet(`input${ve}Indices`,ct,b.indicesGet("outputIndices",ne))}`)})}})}else h.lhs.forEach((ne,de)=>{if(V.inputIndices.includes(de)){let ve=ne.symbolToIndices.get(Y);if(ve===void 0)throw new Error("Invalid symbol error");ve.forEach(Ue=>{M.push(`${y[de].indicesSet(`input${de}Indices`,Ue,`${Y}`)}`)}),L.push(`prod *= ${y[de].getByIndices(`input${de}Indices`)};`)}}),U.push(`for(var ${Y}: u32 = 0; ${Y} < uniforms.${cf(Y)}; ${Y}++) {`),z.push("}")});let j=P?[...$,`let sum = ${y.map((V,Y)=>V.getByIndices(`input${Y}Indices`)).join(" * ")};`]:[...$,k,...U,...M,x,...L,N,...z];return`
1477
+ ${I.registerUniforms(E.map(V=>({name:`${cf(V)}`,type:"u32"}))).registerUniform("outputSize","u32").declareVariables(...y,b)}
1478
1478
 
1479
1479
  ${I.mainStart()}
1480
1480
  ${I.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}
@@ -1484,7 +1484,7 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
1484
1484
  ${j.join(`
1485
1485
  `)};
1486
1486
  ${b.setByOffset("global_idx","sum")};
1487
- }`};return{name:"Einsum",shaderCache:{hint:h.equation,inputDependencies:i.map(()=>"rank")},getRunData:()=>{let I=E.filter(x=>h.symbolToInfo.has(x)).map(x=>{var k;return{type:12,data:((k=h.symbolToInfo.get(x))==null?void 0:k.dimValue)||0}});I.push({type:12,data:S});let $=i.map((x,k)=>[...Xe(x)]).reduce((x,k)=>x.concat(k),I);return $.push(...Xe(m)),{outputs:[{dims:m,dataType:c}],dispatchGroup:{x:Math.ceil(S/64)},programUniforms:$}},getShaderSource:A}},Bg=(i,c)=>{let h=new Hg(i.inputs,c.equation),m=h.outputDims,y=i.inputs.map((S,b)=>S.dims);i.compute(Fg(y,i.inputs[0].dataType,h,m))},zg=i=>{let c=i.equation.replace(/\s+/g,"");return Rt({equation:c})}}),Vg,ff,qg,jg,Gg,DI=_(()=>{ot(),ht(),_t(),Vg=i=>{if(!i||i.length!==2)throw new Error("Expand requires 2 input.");let c=i[0].dims,h=Array.from(i[1].getBigInt64Array(),Number),m=h.length<c.length?0:h.length-c.length,y=c.length<h.length?0:c.length-h.length;for(;m<h.length&&y<c.length;++m,++y)if(h[m]!==c[y]&&h[m]!==1&&c[y]!==1)throw new Error("Expand requires shape to be broadcastable to input")},ff=(i,c)=>{let h=i.length-c.length,m=[];for(let y=0;y<h;++y)m.push(i[y]);for(let y=0;y<c.length;++y)m.push(c[y]===1?i[y+h]:c[y]);return m},qg=(i,c)=>i.length>c.length?ff(i,c):ff(c,i),jg=i=>{let c=i[0].dims,h=Array.from(i[1].getBigInt64Array(),Number),m=qg(c,h),y=i[0].dataType,S=y===9||ie.size(c)===1,b=y===9||c.length>0&&c[c.length-1]%4===0?4:1,E=S||m.length>0&&m[m.length-1]%4===0?4:1,A=Math.ceil(ie.size(m)/E),I=x=>{let k=he("input",y,c.length,b),N=Je("output",y,m.length,E),M;if(y===9){let U=(z,L,P="")=>`
1487
+ }`};return{name:"Einsum",shaderCache:{hint:h.equation,inputDependencies:i.map(()=>"rank")},getRunData:()=>{let I=E.filter(x=>h.symbolToInfo.has(x)).map(x=>{var k;return{type:12,data:((k=h.symbolToInfo.get(x))==null?void 0:k.dimValue)||0}});I.push({type:12,data:S});let $=i.map((x,k)=>[...Xe(x)]).reduce((x,k)=>x.concat(k),I);return $.push(...Xe(m)),{outputs:[{dims:m,dataType:c}],dispatchGroup:{x:Math.ceil(S/64)},programUniforms:$}},getShaderSource:A}},Bg=(i,c)=>{let h=new Hg(i.inputs,c.equation),m=h.outputDims,y=i.inputs.map((S,b)=>S.dims);i.compute(Fg(y,i.inputs[0].dataType,h,m))},zg=i=>{let c=i.equation.replace(/\s+/g,"");return Rt({equation:c})}}),Vg,df,qg,jg,Gg,DI=_(()=>{ot(),ht(),_t(),Vg=i=>{if(!i||i.length!==2)throw new Error("Expand requires 2 input.");let c=i[0].dims,h=Array.from(i[1].getBigInt64Array(),Number),m=h.length<c.length?0:h.length-c.length,y=c.length<h.length?0:c.length-h.length;for(;m<h.length&&y<c.length;++m,++y)if(h[m]!==c[y]&&h[m]!==1&&c[y]!==1)throw new Error("Expand requires shape to be broadcastable to input")},df=(i,c)=>{let h=i.length-c.length,m=[];for(let y=0;y<h;++y)m.push(i[y]);for(let y=0;y<c.length;++y)m.push(c[y]===1?i[y+h]:c[y]);return m},qg=(i,c)=>i.length>c.length?df(i,c):df(c,i),jg=i=>{let c=i[0].dims,h=Array.from(i[1].getBigInt64Array(),Number),m=qg(c,h),y=i[0].dataType,S=y===9||ie.size(c)===1,b=y===9||c.length>0&&c[c.length-1]%4===0?4:1,E=S||m.length>0&&m[m.length-1]%4===0?4:1,A=Math.ceil(ie.size(m)/E),I=x=>{let k=he("input",y,c.length,b),N=Je("output",y,m.length,E),M;if(y===9){let U=(z,L,P="")=>`
1488
1488
  let outputIndices${L} = ${N.offsetToIndices(`outputOffset + ${L}u`)};
1489
1489
  let offset${L} = ${k.broadcastedIndicesToOffset(`outputIndices${L}`,N)};
1490
1490
  let index${L} = offset${L} / 4u;
@@ -1507,13 +1507,13 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
1507
1507
  ${x.registerUniform("vec_size","u32").declareVariables(k,N)}
1508
1508
  ${x.mainStart()}
1509
1509
  ${x.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")}
1510
- ${M}`},$=[{type:12,data:A},...Xe(c,m)];return{name:"Expand",shaderCache:{hint:`${m.length};${b}${E}`,inputDependencies:["rank"]},getShaderSource:I,getRunData:()=>({outputs:[{dims:m,dataType:i[0].dataType}],dispatchGroup:{x:Math.ceil(A/64)},programUniforms:$})}},Gg=i=>{Vg(i.inputs),i.compute(jg(i.inputs),{inputs:[0]})}}),Wg,Kg,kI=_(()=>{ot(),ht(),_t(),Wd(),Wg=i=>{let c=i[0].dataType,h=ie.size(i[0].dims),m=ie.size(i[1].dims),y=m%4===0,S=b=>{let E=he("x",c,[1],4),A=he("bias",c,[1],4),I=Je("y",c,[1],4),$=[{name:"output_vec_size",type:"u32"},{name:"bias_size",type:"u32"}],x=N=>`
1510
+ ${M}`},$=[{type:12,data:A},...Xe(c,m)];return{name:"Expand",shaderCache:{hint:`${m.length};${b}${E}`,inputDependencies:["rank"]},getShaderSource:I,getRunData:()=>({outputs:[{dims:m,dataType:i[0].dataType}],dispatchGroup:{x:Math.ceil(A/64)},programUniforms:$})}},Gg=i=>{Vg(i.inputs),i.compute(jg(i.inputs),{inputs:[0]})}}),Wg,Kg,kI=_(()=>{ot(),ht(),_t(),Gd(),Wg=i=>{let c=i[0].dataType,h=ie.size(i[0].dims),m=ie.size(i[1].dims),y=m%4===0,S=b=>{let E=he("x",c,[1],4),A=he("bias",c,[1],4),I=Je("y",c,[1],4),$=[{name:"output_vec_size",type:"u32"},{name:"bias_size",type:"u32"}],x=N=>`
1511
1511
  let bias${N}_offset: u32 = (global_idx * 4 + ${N}) % uniforms.bias_size;
1512
1512
  let bias${N} = ${A.getByOffset(`bias${N}_offset / 4`)}[bias${N}_offset % 4];`,k=y?`
1513
1513
  let bias = ${A.getByOffset("global_idx % (uniforms.bias_size / 4)")};`:`${x(0)}${x(1)}${x(2)}${x(3)}
1514
1514
  let bias = ${E.type.value}(bias0, bias1, bias2, bias3);`;return`${b.registerUniforms($).declareVariables(E,A,I)}
1515
1515
 
1516
- ${jd(Gt(c))}
1516
+ ${qd(Gt(c))}
1517
1517
 
1518
1518
  ${b.mainStart(Rr)}
1519
1519
  ${b.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_vec_size")}
@@ -1521,7 +1521,7 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
1521
1521
  let x = ${E.getByOffset("global_idx")};
1522
1522
  ${k}
1523
1523
  let x_in = x + bias;
1524
- ${I.setByOffset("global_idx",Gd("x_in"))}
1524
+ ${I.setByOffset("global_idx",jd("x_in"))}
1525
1525
  }`};return{name:"FastGeluWithBias",shaderCache:{hint:`${y}`,inputDependencies:["type","type"]},getShaderSource:S,getRunData:b=>({outputs:[{dims:b[0].dims,dataType:b[0].dataType}],programUniforms:[{type:12,data:Math.ceil(h/4)},{type:12,data:m}],dispatchGroup:{x:Math.ceil(h/Rr/4)}})}},Kg=i=>{i.inputs.length<2||ie.size(i.inputs[1].dims)===0?Rm(i):i.compute(Wg(i.inputs))}}),Yg,Jg,Qg,Xg,NI=_(()=>{ot(),ht(),jt(),_t(),Yg=i=>{if(!i||i.length!==2)throw new Error("Gather requires 2 inputs.")},Jg=(i,c)=>{let h=i[0].dims,m=i[1].dims,y=h.length,S=ie.normalizeAxis(c.axis,y),b=h.slice(0);b.splice(S,1,...m);let E=h[S],A=i[0].dataType===9?4:1,I=Math.ceil(ie.size(b)/A),$=[{type:12,data:I},{type:6,data:E},{type:12,data:S},...Xe(i[0].dims,i[1].dims,b)],x=k=>{let N=he("data",i[0].dataType,i[0].dims.length,A),M=he("inputIndices",i[1].dataType,i[1].dims.length),U=Je("output",i[0].dataType,b.length,A),z=P=>{let j=m.length,V=`var indicesIndices${P} = ${M.type.indices}(0);`;for(let Y=0;Y<j;Y++)V+=`${j>1?`indicesIndices${P}[${Y}]`:`indicesIndices${P}`} = ${b.length>1?`outputIndices${P}[uniforms.axis + ${Y}]`:`outputIndices${P}`};`;V+=`
1526
1526
  var idx${P} = ${M.getByIndices(`indicesIndices${P}`)};
1527
1527
  if (idx${P} < 0) {
@@ -1893,14 +1893,14 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
1893
1893
  var y = gs_denormalize(f32(nxy[1]), H_in);
1894
1894
 
1895
1895
  ${Tv(b,E,c)}
1896
- }`;return{name:"GridSample",shaderCache:{hint:`${c.cacheKey}`,inputDependencies:["type","type"]},getRunData:x=>{let k=ie.size(S);return{outputs:[{dims:S,dataType:x[0].dataType}],dispatchGroup:{x:Math.ceil(k/64)},programUniforms:I}},getShaderSource:$}},bv=(i,c)=>{_v(i.inputs),i.compute(Sv(i.inputs,c))},wv=i=>Rt({alignCorners:i.align_corners,mode:i.mode,paddingMode:i.padding_mode,format:i.format})}),er,Ev,Cv,hf,Av,$o,Iv,Rv=_(()=>{ot(),ht(),jt(),An(),xr(),_t(),Qs(),er=(i,c)=>i.length>c&&i[c].dims.length>0?i[c]:void 0,Ev=(i,c)=>{let h=i[0],m=er(i,1),y=er(i,2),S=er(i,3),b=er(i,4),E=er(i,5),A=er(i,6),I=er(i,7);if(h.dims.length!==3&&h.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let $=h.dims[0],x=h.dims[1],k=h.dims.length===3?h.dims[2]:c.numHeads*h.dims[4],N=x,M=0,U=0,z=Math.floor(k/c.numHeads);if(A&&I&&ie.size(A.dims)&&ie.size(I.dims)){if(A.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(A.dims[0]!==$||A.dims[1]!==c.numHeads||A.dims[3]!==z)throw new Error('Input "past_key" shape (batch_size, num_heads, past_sequence_length, head_size)');if(I.dims[0]!==$||I.dims[1]!==c.numHeads||I.dims[3]!==z)throw new Error('Input "past_value" shape (batch_size, num_heads, past_sequence_length, head_size)');if(A.dims[2]!==I.dims[2])throw new Error('Input "past_key" and "past_value" shall have same dim 2 (past_sequence_length)');if(I.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');M=A.dims[2],U=A.dims[2]}else if(A&&ie.size(A.dims)||I&&ie.size(I.dims))throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let L;if(m&&ie.size(m.dims)>0){if(h.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(h.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]!==h.dims[2])throw new Error('Input "query" and "key" shall have same dim 2 (hidden_size)');L=2,N=m.dims[1]}else if(m.dims.length===5){if(m.dims[2]!==c.numHeads||m.dims[3]!==2||m.dims[4]!==z)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(y)throw new Error('Expect "value" be none when "key" has packed kv format.');L=5,N=m.dims[1]}else{if(m.dims[1]!==c.numHeads||m.dims[3]!==z)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');L=0,N=m.dims[2]}}else{if(h.dims.length!==5)throw new Error('Input "query" is expected to have 5 dimensions when key is empty');if(h.dims[2]!==c.numHeads||h.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(S&&ie.size(S.dims)>0){if(S.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 P=M+N,j=0;if(b&&ie.size(b.dims)>0){j=8;let ne=b.dims;throw ne.length===1?ne[0]===$?j=1:ne[0]===3*$+2&&(j=3):ne.length===2&&ne[0]===$&&ne[1]===P&&(j=5),j===8?new Error('Input "key_padding_mask" shape shall be (batch_size) or (batch_size, total_sequence_length)'):new Error("Mask not supported")}let V=!1,Y=k;if(y&&ie.size(y.dims)>0){if(y.dims.length!==3&&y.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(h.dims[0]!==y.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(y.dims.length===3){if(N!==y.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');Y=y.dims[2]}else{if(N!==y.dims[2])throw new Error('Input "key" and "value" shall have the same dim 2 (kv_sequence_length)');Y=y.dims[1]*y.dims[3],V=!0}}let ae=!1;if(b&&ie.size(b.dims)>0)throw new Error("Key padding mask is not supported");if(E&&ie.size(E.dims)>0){if(E.dims.length!==4)throw new Error('Input "attention_bias" is expected to have 4 dimensions');if(E.dims[0]!==$||E.dims[1]!==c.numHeads||E.dims[2]!==x||E.dims[3]!==P)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:$,sequenceLength:x,pastSequenceLength:M,kvSequenceLength:N,totalSequenceLength:P,maxSequenceLength:U,inputHiddenSize:0,hiddenSize:k,vHiddenSize:Y,headSize:z,vHeadSize:Math.floor(Y/c.numHeads),numHeads:c.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:c.maskFilterValue,maskType:j,scale:c.scale,broadcastResPosBias:ae,passPastInKv:V,qkvFormat:L}},Cv=i=>Rt({...i}),hf=Rt({perm:[0,2,1,3]}),Av=(i,c,h,m,y,S,b)=>{let E=[m,y,S],A=ie.size(E),I=[{type:12,data:A},{type:12,data:b},{type:12,data:S}],$=x=>{let k=Je("qkv_with_bias",c.dataType,E),N=he("qkv",c.dataType,E),M=he("bias",h.dataType,E),U=[{name:"output_size",type:"u32"},{name:"bias_offset",type:"u32"},{name:"hidden_size",type:"u32"}];return`
1896
+ }`;return{name:"GridSample",shaderCache:{hint:`${c.cacheKey}`,inputDependencies:["type","type"]},getRunData:x=>{let k=ie.size(S);return{outputs:[{dims:S,dataType:x[0].dataType}],dispatchGroup:{x:Math.ceil(k/64)},programUniforms:I}},getShaderSource:$}},bv=(i,c)=>{_v(i.inputs),i.compute(Sv(i.inputs,c))},wv=i=>Rt({alignCorners:i.align_corners,mode:i.mode,paddingMode:i.padding_mode,format:i.format})}),er,Ev,Cv,ff,Av,$o,Iv,Rv=_(()=>{ot(),ht(),jt(),An(),xr(),_t(),Qs(),er=(i,c)=>i.length>c&&i[c].dims.length>0?i[c]:void 0,Ev=(i,c)=>{let h=i[0],m=er(i,1),y=er(i,2),S=er(i,3),b=er(i,4),E=er(i,5),A=er(i,6),I=er(i,7);if(h.dims.length!==3&&h.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let $=h.dims[0],x=h.dims[1],k=h.dims.length===3?h.dims[2]:c.numHeads*h.dims[4],N=x,M=0,U=0,z=Math.floor(k/c.numHeads);if(A&&I&&ie.size(A.dims)&&ie.size(I.dims)){if(A.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(A.dims[0]!==$||A.dims[1]!==c.numHeads||A.dims[3]!==z)throw new Error('Input "past_key" shape (batch_size, num_heads, past_sequence_length, head_size)');if(I.dims[0]!==$||I.dims[1]!==c.numHeads||I.dims[3]!==z)throw new Error('Input "past_value" shape (batch_size, num_heads, past_sequence_length, head_size)');if(A.dims[2]!==I.dims[2])throw new Error('Input "past_key" and "past_value" shall have same dim 2 (past_sequence_length)');if(I.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');M=A.dims[2],U=A.dims[2]}else if(A&&ie.size(A.dims)||I&&ie.size(I.dims))throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let L;if(m&&ie.size(m.dims)>0){if(h.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(h.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]!==h.dims[2])throw new Error('Input "query" and "key" shall have same dim 2 (hidden_size)');L=2,N=m.dims[1]}else if(m.dims.length===5){if(m.dims[2]!==c.numHeads||m.dims[3]!==2||m.dims[4]!==z)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(y)throw new Error('Expect "value" be none when "key" has packed kv format.');L=5,N=m.dims[1]}else{if(m.dims[1]!==c.numHeads||m.dims[3]!==z)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');L=0,N=m.dims[2]}}else{if(h.dims.length!==5)throw new Error('Input "query" is expected to have 5 dimensions when key is empty');if(h.dims[2]!==c.numHeads||h.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(S&&ie.size(S.dims)>0){if(S.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 P=M+N,j=0;if(b&&ie.size(b.dims)>0){j=8;let ne=b.dims;throw ne.length===1?ne[0]===$?j=1:ne[0]===3*$+2&&(j=3):ne.length===2&&ne[0]===$&&ne[1]===P&&(j=5),j===8?new Error('Input "key_padding_mask" shape shall be (batch_size) or (batch_size, total_sequence_length)'):new Error("Mask not supported")}let V=!1,Y=k;if(y&&ie.size(y.dims)>0){if(y.dims.length!==3&&y.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(h.dims[0]!==y.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(y.dims.length===3){if(N!==y.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');Y=y.dims[2]}else{if(N!==y.dims[2])throw new Error('Input "key" and "value" shall have the same dim 2 (kv_sequence_length)');Y=y.dims[1]*y.dims[3],V=!0}}let ae=!1;if(b&&ie.size(b.dims)>0)throw new Error("Key padding mask is not supported");if(E&&ie.size(E.dims)>0){if(E.dims.length!==4)throw new Error('Input "attention_bias" is expected to have 4 dimensions');if(E.dims[0]!==$||E.dims[1]!==c.numHeads||E.dims[2]!==x||E.dims[3]!==P)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:$,sequenceLength:x,pastSequenceLength:M,kvSequenceLength:N,totalSequenceLength:P,maxSequenceLength:U,inputHiddenSize:0,hiddenSize:k,vHiddenSize:Y,headSize:z,vHeadSize:Math.floor(Y/c.numHeads),numHeads:c.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:c.maskFilterValue,maskType:j,scale:c.scale,broadcastResPosBias:ae,passPastInKv:V,qkvFormat:L}},Cv=i=>Rt({...i}),ff=Rt({perm:[0,2,1,3]}),Av=(i,c,h,m,y,S,b)=>{let E=[m,y,S],A=ie.size(E),I=[{type:12,data:A},{type:12,data:b},{type:12,data:S}],$=x=>{let k=Je("qkv_with_bias",c.dataType,E),N=he("qkv",c.dataType,E),M=he("bias",h.dataType,E),U=[{name:"output_size",type:"u32"},{name:"bias_offset",type:"u32"},{name:"hidden_size",type:"u32"}];return`
1897
1897
  ${x.registerUniforms(U).declareVariables(N,M,k)}
1898
1898
  ${x.mainStart()}
1899
1899
  ${x.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
1900
1900
  let bias_offset_idx = (global_idx % uniforms.hidden_size) + uniforms.bias_offset;
1901
1901
 
1902
1902
  qkv_with_bias[global_idx] = qkv[global_idx] + bias[bias_offset_idx];
1903
- }`};return i.compute({name:"MultiHeadAttentionAddBias",shaderCache:{inputDependencies:["type","type"]},getRunData:()=>({outputs:[{dims:E,dataType:c.dataType,gpuDataType:0}],dispatchGroup:{x:Math.ceil(A/64)},programUniforms:I}),getShaderSource:$},{inputs:[c,h],outputs:[-1]})[0]},$o=(i,c,h,m,y,S,b,E)=>{let A=S;if(b&&ie.size(b.dims)>0){if(m===1)throw new Error("AddBiasReshape is not implemented. Please export your model with packed QKV or KV");return A=Av(i,S,b,c,m,h*y,E),A=A.reshape([c,m,h,y]),h===1||m===1?A:i.compute(ms(A,hf.perm),{inputs:[A],outputs:[-1]})[0]}else return S.dims.length===3&&(A=S.reshape([c,m,h,y])),h===1||m===1?A:i.compute(ms(A,hf.perm),{inputs:[A],outputs:[-1]})[0]},Iv=(i,c)=>{let h=Ev(i.inputs,c),m=i.inputs[0],y=er(i.inputs,1),S=er(i.inputs,2),b=er(i.inputs,3),E=er(i.inputs,4),A=er(i.inputs,5),I=er(i.inputs,6),$=er(i.inputs,7);if(m.dims.length===5)throw new Error("Packed QKV is not implemented");if((y==null?void 0:y.dims.length)===5)throw new Error("Packed KV is not implemented");let x=y&&S&&y.dims.length===4&&S.dims.length===4,k=$o(i,h.batchSize,h.numHeads,h.sequenceLength,h.headSize,m,b,0);if(x)return Pe(i,k,y,S,E,void 0,I,$,A,h);if(!y||!S)throw new Error("key and value must be provided");let N=$o(i,h.batchSize,h.numHeads,h.kvSequenceLength,h.headSize,y,b,h.hiddenSize),M=$o(i,h.batchSize,h.numHeads,h.kvSequenceLength,h.vHeadSize,S,b,2*h.hiddenSize);Pe(i,k,N,M,E,void 0,I,$,A,h)}}),$v,xv,Ov,Dv,_f,kv,Nv,Mv=_(()=>{ot(),ht(),jt(),_t(),$v=i=>{if(!i||i.length<1)throw new Error("too few inputs")},xv=(i,c)=>{let h=[],m=c.numOutputs;return i[1].dims[0]>0&&(i[1].getBigInt64Array().forEach(y=>h.push(Number(y))),m=h.length),Rt({numOutputs:m,axis:c.axis,splitSizes:h})},Ov=i=>`
1903
+ }`};return i.compute({name:"MultiHeadAttentionAddBias",shaderCache:{inputDependencies:["type","type"]},getRunData:()=>({outputs:[{dims:E,dataType:c.dataType,gpuDataType:0}],dispatchGroup:{x:Math.ceil(A/64)},programUniforms:I}),getShaderSource:$},{inputs:[c,h],outputs:[-1]})[0]},$o=(i,c,h,m,y,S,b,E)=>{let A=S;if(b&&ie.size(b.dims)>0){if(m===1)throw new Error("AddBiasReshape is not implemented. Please export your model with packed QKV or KV");return A=Av(i,S,b,c,m,h*y,E),A=A.reshape([c,m,h,y]),h===1||m===1?A:i.compute(ms(A,ff.perm),{inputs:[A],outputs:[-1]})[0]}else return S.dims.length===3&&(A=S.reshape([c,m,h,y])),h===1||m===1?A:i.compute(ms(A,ff.perm),{inputs:[A],outputs:[-1]})[0]},Iv=(i,c)=>{let h=Ev(i.inputs,c),m=i.inputs[0],y=er(i.inputs,1),S=er(i.inputs,2),b=er(i.inputs,3),E=er(i.inputs,4),A=er(i.inputs,5),I=er(i.inputs,6),$=er(i.inputs,7);if(m.dims.length===5)throw new Error("Packed QKV is not implemented");if((y==null?void 0:y.dims.length)===5)throw new Error("Packed KV is not implemented");let x=y&&S&&y.dims.length===4&&S.dims.length===4,k=$o(i,h.batchSize,h.numHeads,h.sequenceLength,h.headSize,m,b,0);if(x)return Pe(i,k,y,S,E,void 0,I,$,A,h);if(!y||!S)throw new Error("key and value must be provided");let N=$o(i,h.batchSize,h.numHeads,h.kvSequenceLength,h.headSize,y,b,h.hiddenSize),M=$o(i,h.batchSize,h.numHeads,h.kvSequenceLength,h.vHeadSize,S,b,2*h.hiddenSize);Pe(i,k,N,M,E,void 0,I,$,A,h)}}),$v,xv,Ov,Dv,hf,kv,Nv,Mv=_(()=>{ot(),ht(),jt(),_t(),$v=i=>{if(!i||i.length<1)throw new Error("too few inputs")},xv=(i,c)=>{let h=[],m=c.numOutputs;return i[1].dims[0]>0&&(i[1].getBigInt64Array().forEach(y=>h.push(Number(y))),m=h.length),Rt({numOutputs:m,axis:c.axis,splitSizes:h})},Ov=i=>`
1904
1904
  fn calculateOutputIndex(index: u32) -> u32 {
1905
1905
  for (var i: u32 = 0u; i < ${i}u; i += 1u ) {
1906
1906
  if (index < ${Ze("uniforms.size_in_split_axis","i",i)}) {
@@ -1912,7 +1912,7 @@ fn calculateOutputIndex(index: u32) -> u32 {
1912
1912
  fn writeBufferData(output_number: u32, indices: ${i[0].type.indices}, global_idx: u32) {
1913
1913
  ${h.join(`
1914
1914
  `)}
1915
- }`},_f=(i,c)=>{let h=i[0].dims,m=ie.size(h),y=i[0].dataType,S=ie.normalizeAxis(c.axis,h.length),b=new Array(c.numOutputs),E=he("input",y,h.length),A=new Array(c.numOutputs),I=[],$=[],x=0,k=[{type:12,data:m}];for(let M=0;M<c.numOutputs;M++){x+=c.splitSizes[M],A[M]=x;let U=h.slice();U[S]=c.splitSizes[M],$.push(U),b[M]=Je(`output${M}`,y,U.length),I.push({dims:$[M],dataType:i[0].dataType})}k.push({type:12,data:A},...Xe(h,...$));let N=M=>`
1915
+ }`},hf=(i,c)=>{let h=i[0].dims,m=ie.size(h),y=i[0].dataType,S=ie.normalizeAxis(c.axis,h.length),b=new Array(c.numOutputs),E=he("input",y,h.length),A=new Array(c.numOutputs),I=[],$=[],x=0,k=[{type:12,data:m}];for(let M=0;M<c.numOutputs;M++){x+=c.splitSizes[M],A[M]=x;let U=h.slice();U[S]=c.splitSizes[M],$.push(U),b[M]=Je(`output${M}`,y,U.length),I.push({dims:$[M],dataType:i[0].dataType})}k.push({type:12,data:A},...Xe(h,...$));let N=M=>`
1916
1916
  ${M.registerUniform("input_size","u32").registerUniform("size_in_split_axis","u32",A.length).declareVariables(E,...b)}
1917
1917
  ${Ov(A.length)}
1918
1918
  ${Dv(b)}
@@ -1928,7 +1928,7 @@ fn calculateOutputIndex(index: u32) -> u32 {
1928
1928
  ${E.indicesSet("indices",S,"index")};
1929
1929
  }
1930
1930
  writeBufferData(output_number, indices, global_idx);
1931
- }`;return{name:"Split",shaderCache:{hint:c.cacheKey,inputDependencies:["rank"]},getShaderSource:N,getRunData:()=>({outputs:I,dispatchGroup:{x:Math.ceil(m/64)},programUniforms:k})}},kv=(i,c)=>{$v(i.inputs);let h=i.inputs.length===1?c:xv(i.inputs,c);i.compute(_f(i.inputs,h),{inputs:[0]})},Nv=i=>{let c=i.axis,h=i.splitSizes,m=i.numOutputs<0?h.length:i.numOutputs;if(m!==h.length)throw new Error("numOutputs and splitSizes length must be equal");return Rt({axis:c,numOutputs:m,splitSizes:h})}}),Uv,tc,Pv,Lv=_(()=>{ot(),ht(),jt(),_t(),Uv=(i,c)=>{let[h,m,y,S]=i,{numHeads:b,rotaryEmbeddingDim:E}=c;if(h.dims.length!==3&&h.dims.length!==4)throw new Error(`Input 'x' is expected to have 3 or 4 dimensions, got ${h.dims.length}`);if(!ie.areEqual(m.dims,[])&&!ie.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(y.dims.length!==2)throw new Error(`Input 'cos_cache' is expected to have 2 dimensions, got ${y.dims.length}`);if(S.dims.length!==2)throw new Error(`Input 'sin_cache' is expected to have 2 dimensions, got ${S.dims.length}`);if(!ie.areEqual(y.dims,S.dims))throw new Error("Inputs 'cos_cache' and 'sin_cache' are expected to have the same shape");if(E>0&&b===0)throw new Error("num_heads must be provided if rotary_embedding_dim is specified");let A=h.dims[0],I=h.dims[h.dims.length-2],$=y.dims[0],x=ie.sizeFromDimension(h.dims,1)/I,k=E===0?y.dims[1]*2:x/b;if(E>k)throw new Error("rotary_embedding_dim must be less than or equal to head_size");if(m.dims.length===2){if(A!==m.dims[0])throw new Error(`Input 'position_ids' dimension 0 should be of size batch_size, got ${m.dims[0]}`);if(I!==m.dims[1])throw new Error(`Input 'position_ids' dimension 1 should be of size sequence_length, got ${m.dims[1]}`)}if(k/2!==y.dims[1]&&E/2!==y.dims[1])throw new Error(`Input 'cos_cache' dimension 1 should be same as head_size / 2 or rotary_embedding_dim / 2, got ${y.dims[1]}`);if(I>$)throw new Error("Updating cos_cache and sin_cache in RotaryEmbedding is not currently supported")},tc=(i,c)=>{let{interleaved:h,numHeads:m,rotaryEmbeddingDim:y,scale:S}=c,b=i[0].dims[0],E=ie.sizeFromDimension(i[0].dims,1),A=i[0].dims[i[0].dims.length-2],I=E/A,$=i[2].dims[1],x=y===0?$*2:I/m,k=new Array(b,A,I/x,x-$),N=ie.computeStrides(k),M=[{type:1,data:S},{type:12,data:k},{type:12,data:N},...i[0].dims.length===3?new Array({type:12,data:[E,I,x,1]}):[],...i[0].dims.length===4?new Array({type:12,data:[E,x,A*x,1]}):[],...Xe(i[0].dims,i[1].dims,i[2].dims,i[3].dims,i[0].dims)],U=z=>{let L=he("input",i[0].dataType,i[0].dims.length),P=he("position_ids",i[1].dataType,i[1].dims.length),j=he("cos_cache",i[2].dataType,i[2].dims.length),V=he("sin_cache",i[3].dataType,i[3].dims.length),Y=Je("output",i[0].dataType,i[0].dims.length);return z.registerUniforms([{name:"scale",type:"f32"},{name:"global_shape",type:"u32",length:k.length},{name:"global_strides",type:"u32",length:N.length},{name:"input_output_strides",type:"u32",length:N.length}]),`
1931
+ }`;return{name:"Split",shaderCache:{hint:c.cacheKey,inputDependencies:["rank"]},getShaderSource:N,getRunData:()=>({outputs:I,dispatchGroup:{x:Math.ceil(m/64)},programUniforms:k})}},kv=(i,c)=>{$v(i.inputs);let h=i.inputs.length===1?c:xv(i.inputs,c);i.compute(hf(i.inputs,h),{inputs:[0]})},Nv=i=>{let c=i.axis,h=i.splitSizes,m=i.numOutputs<0?h.length:i.numOutputs;if(m!==h.length)throw new Error("numOutputs and splitSizes length must be equal");return Rt({axis:c,numOutputs:m,splitSizes:h})}}),Uv,tc,Pv,Lv=_(()=>{ot(),ht(),jt(),_t(),Uv=(i,c)=>{let[h,m,y,S]=i,{numHeads:b,rotaryEmbeddingDim:E}=c;if(h.dims.length!==3&&h.dims.length!==4)throw new Error(`Input 'x' is expected to have 3 or 4 dimensions, got ${h.dims.length}`);if(!ie.areEqual(m.dims,[])&&!ie.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(y.dims.length!==2)throw new Error(`Input 'cos_cache' is expected to have 2 dimensions, got ${y.dims.length}`);if(S.dims.length!==2)throw new Error(`Input 'sin_cache' is expected to have 2 dimensions, got ${S.dims.length}`);if(!ie.areEqual(y.dims,S.dims))throw new Error("Inputs 'cos_cache' and 'sin_cache' are expected to have the same shape");if(E>0&&b===0)throw new Error("num_heads must be provided if rotary_embedding_dim is specified");let A=h.dims[0],I=h.dims[h.dims.length-2],$=y.dims[0],x=ie.sizeFromDimension(h.dims,1)/I,k=E===0?y.dims[1]*2:x/b;if(E>k)throw new Error("rotary_embedding_dim must be less than or equal to head_size");if(m.dims.length===2){if(A!==m.dims[0])throw new Error(`Input 'position_ids' dimension 0 should be of size batch_size, got ${m.dims[0]}`);if(I!==m.dims[1])throw new Error(`Input 'position_ids' dimension 1 should be of size sequence_length, got ${m.dims[1]}`)}if(k/2!==y.dims[1]&&E/2!==y.dims[1])throw new Error(`Input 'cos_cache' dimension 1 should be same as head_size / 2 or rotary_embedding_dim / 2, got ${y.dims[1]}`);if(I>$)throw new Error("Updating cos_cache and sin_cache in RotaryEmbedding is not currently supported")},tc=(i,c)=>{let{interleaved:h,numHeads:m,rotaryEmbeddingDim:y,scale:S}=c,b=i[0].dims[0],E=ie.sizeFromDimension(i[0].dims,1),A=i[0].dims[i[0].dims.length-2],I=E/A,$=i[2].dims[1],x=y===0?$*2:I/m,k=new Array(b,A,I/x,x-$),N=ie.computeStrides(k),M=[{type:1,data:S},{type:12,data:k},{type:12,data:N},...i[0].dims.length===3?new Array({type:12,data:[E,I,x,1]}):[],...i[0].dims.length===4?new Array({type:12,data:[E,x,A*x,1]}):[],...Xe(i[0].dims,i[1].dims,i[2].dims,i[3].dims,i[0].dims)],U=z=>{let L=he("input",i[0].dataType,i[0].dims.length),P=he("position_ids",i[1].dataType,i[1].dims.length),j=he("cos_cache",i[2].dataType,i[2].dims.length),V=he("sin_cache",i[3].dataType,i[3].dims.length),Y=Je("output",i[0].dataType,i[0].dims.length);return z.registerUniforms([{name:"scale",type:"f32"},{name:"global_shape",type:"u32",length:k.length},{name:"global_strides",type:"u32",length:N.length},{name:"input_output_strides",type:"u32",length:N.length}]),`
1932
1932
  ${z.declareVariables(L,P,j,V,Y)}
1933
1933
 
1934
1934
  ${z.mainStart(Rr)}
@@ -1954,7 +1954,7 @@ fn calculateOutputIndex(index: u32) -> u32 {
1954
1954
  let k = dot(bsnh, uniforms.input_output_strides) + half_rotary_emb_dim;
1955
1955
  ${Y.setByOffset("k",L.getByOffset("k"))}
1956
1956
  }
1957
- }`};return{name:"RotaryEmbedding",shaderCache:{hint:Rt({interleaved:h}).cacheKey,inputDependencies:["rank","rank","rank","rank"]},getShaderSource:U,getRunData:()=>({outputs:[{dims:i[0].dims,dataType:i[0].dataType}],dispatchGroup:{x:Math.ceil(ie.size(k)/Rr)},programUniforms:M})}},Pv=(i,c)=>{Uv(i.inputs,c),i.compute(tc(i.inputs,c))}}),Hv,Fv,pf,Bv,zv,FI=_(()=>{jt(),ot(),xr(),Rv(),Mv(),Qs(),Lv(),_t(),Hv=(i,c)=>{if(c.doRotary&&i.length<=7)throw new Error("cos_cache and sin_cache inputs are required if do_rotary is specified");let h=i[0],m=i[1],y=i[2],S=i[3],b=i[4];if(c.doRotary!==0&&i.length<=7)throw new Error("cos_cast and sin_cache are expected if do_rotary attribute is non-zero");if(c.localWindowSize!==-1)throw new Error("Local attention is not supported");if(c.softcap!==0)throw new Error("Softcap is not supported");if(c.rotaryInterleaved!==0)throw new Error("Rotary interleaved is not supported");if(c.smoothSoftmax)throw new Error("Smooth softmax is not supported");if(h.dims.length!==3&&h.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let E=!1,A=h.dims[0],I=h.dims[1],$=h.dims.length===3?E?h.dims[2]/3:h.dims[2]:c.numHeads*h.dims[4],x=I,k=0,N=!m||m.dims.length===0,M=Math.floor(N?$/(c.numHeads+2*c.kvNumHeads):$/c.numHeads);N&&($=M*c.numHeads);let U=S&&S.dims.length!==0,z=b&&b.dims.length!==0;if(U&&S.dims.length===4&&S.dims[0]===A&&S.dims[1]!==c.kvNumHeads&&S.dims[2]===c.kvNumHeads&&S.dims[3]===M)throw new Error("BSNH pastKey/pastValue is not supported");if(U&&z){if(S.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');k=S.dims[2]}else if(U||z)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(h.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(h.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(h.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]!==c.numHeads||m.dims[3]!==2||m.dims[4]!==M)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(y)throw new Error('Expect "value" be none when "key" has packed kv format.');x=m.dims[1]}else{if(m.dims[1]!==c.numHeads||m.dims[3]!==M)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');x=m.dims[2]}}else{if(h.dims.length!==3&&h.dims.length!==5)throw new Error('Input "query" is expected to have 3 or 5 dimensions when key is empty');if(h.dims.length===5&&(h.dims[2]!==c.numHeads||h.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 P=0,j=!1,V=c.kvNumHeads?M*c.kvNumHeads:$;if(y&&y.dims.length>0){if(y.dims.length!==3&&y.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(h.dims[0]!==y.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(y.dims.length===3){if(x!==y.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');V=y.dims[2]}else{if(x!==y.dims[2])throw new Error('Input "past_key" and "past_value" shall have the same dim 2 (kv_sequence_length)');V=y.dims[1]*y.dims[3],j=!0}}let Y=i.length>4?i[5]:void 0;if(Y&&Y.dims.length!==1&&Y.dims[0]!==A)throw new Error('Input "seqlens" is expected to have 1 dimension and the same dim 0 as batch_size');return{batchSize:A,sequenceLength:I,pastSequenceLength:k,kvSequenceLength:x,totalSequenceLength:-1,maxSequenceLength:-1,inputHiddenSize:0,hiddenSize:$,vHiddenSize:V,headSize:M,vHeadSize:Math.floor(V/c.kvNumHeads),numHeads:c.numHeads,kvNumHeads:c.kvNumHeads,nReps:c.numHeads/c.kvNumHeads,pastPresentShareBuffer:!1,maskType:P,scale:c.scale,broadcastResPosBias:!1,passPastInKv:j,qkvFormat:L}},Fv=Rt({perm:[0,2,1,3]}),pf=(i,c,h)=>{let m=c,y=h.kvNumHeads;return c.dims.length===3&&h.kvSequenceLength!==0&&(m=c.reshape([h.batchSize,h.kvSequenceLength,y,h.headSize]),m=i.compute(ms(m,Fv.perm),{inputs:[m],outputs:[-1]})[0]),m},Bv=(i,c,h,m)=>{let y=7,S=["type","type"],b=[i*c],E=i*c,A=[{type:12,data:E},{type:12,data:c},{type:12,data:i}],I=$=>{let x=he("seq_lens",h.dataType,h.dims),k=he("total_seq_lens",m.dataType,m.dims),N=Je("pos_ids",y,b),M=[{name:"output_size",type:"u32"},{name:"sequence_length",type:"u32"},{name:"batch_size",type:"u32"}];return`
1957
+ }`};return{name:"RotaryEmbedding",shaderCache:{hint:Rt({interleaved:h}).cacheKey,inputDependencies:["rank","rank","rank","rank"]},getShaderSource:U,getRunData:()=>({outputs:[{dims:i[0].dims,dataType:i[0].dataType}],dispatchGroup:{x:Math.ceil(ie.size(k)/Rr)},programUniforms:M})}},Pv=(i,c)=>{Uv(i.inputs,c),i.compute(tc(i.inputs,c))}}),Hv,Fv,_f,Bv,zv,FI=_(()=>{jt(),ot(),xr(),Rv(),Mv(),Qs(),Lv(),_t(),Hv=(i,c)=>{if(c.doRotary&&i.length<=7)throw new Error("cos_cache and sin_cache inputs are required if do_rotary is specified");let h=i[0],m=i[1],y=i[2],S=i[3],b=i[4];if(c.doRotary!==0&&i.length<=7)throw new Error("cos_cast and sin_cache are expected if do_rotary attribute is non-zero");if(c.localWindowSize!==-1)throw new Error("Local attention is not supported");if(c.softcap!==0)throw new Error("Softcap is not supported");if(c.rotaryInterleaved!==0)throw new Error("Rotary interleaved is not supported");if(c.smoothSoftmax)throw new Error("Smooth softmax is not supported");if(h.dims.length!==3&&h.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let E=!1,A=h.dims[0],I=h.dims[1],$=h.dims.length===3?E?h.dims[2]/3:h.dims[2]:c.numHeads*h.dims[4],x=I,k=0,N=!m||m.dims.length===0,M=Math.floor(N?$/(c.numHeads+2*c.kvNumHeads):$/c.numHeads);N&&($=M*c.numHeads);let U=S&&S.dims.length!==0,z=b&&b.dims.length!==0;if(U&&S.dims.length===4&&S.dims[0]===A&&S.dims[1]!==c.kvNumHeads&&S.dims[2]===c.kvNumHeads&&S.dims[3]===M)throw new Error("BSNH pastKey/pastValue is not supported");if(U&&z){if(S.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');k=S.dims[2]}else if(U||z)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(h.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(h.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(h.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]!==c.numHeads||m.dims[3]!==2||m.dims[4]!==M)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(y)throw new Error('Expect "value" be none when "key" has packed kv format.');x=m.dims[1]}else{if(m.dims[1]!==c.numHeads||m.dims[3]!==M)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');x=m.dims[2]}}else{if(h.dims.length!==3&&h.dims.length!==5)throw new Error('Input "query" is expected to have 3 or 5 dimensions when key is empty');if(h.dims.length===5&&(h.dims[2]!==c.numHeads||h.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 P=0,j=!1,V=c.kvNumHeads?M*c.kvNumHeads:$;if(y&&y.dims.length>0){if(y.dims.length!==3&&y.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(h.dims[0]!==y.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(y.dims.length===3){if(x!==y.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');V=y.dims[2]}else{if(x!==y.dims[2])throw new Error('Input "past_key" and "past_value" shall have the same dim 2 (kv_sequence_length)');V=y.dims[1]*y.dims[3],j=!0}}let Y=i.length>4?i[5]:void 0;if(Y&&Y.dims.length!==1&&Y.dims[0]!==A)throw new Error('Input "seqlens" is expected to have 1 dimension and the same dim 0 as batch_size');return{batchSize:A,sequenceLength:I,pastSequenceLength:k,kvSequenceLength:x,totalSequenceLength:-1,maxSequenceLength:-1,inputHiddenSize:0,hiddenSize:$,vHiddenSize:V,headSize:M,vHeadSize:Math.floor(V/c.kvNumHeads),numHeads:c.numHeads,kvNumHeads:c.kvNumHeads,nReps:c.numHeads/c.kvNumHeads,pastPresentShareBuffer:!1,maskType:P,scale:c.scale,broadcastResPosBias:!1,passPastInKv:j,qkvFormat:L}},Fv=Rt({perm:[0,2,1,3]}),_f=(i,c,h)=>{let m=c,y=h.kvNumHeads;return c.dims.length===3&&h.kvSequenceLength!==0&&(m=c.reshape([h.batchSize,h.kvSequenceLength,y,h.headSize]),m=i.compute(ms(m,Fv.perm),{inputs:[m],outputs:[-1]})[0]),m},Bv=(i,c,h,m)=>{let y=7,S=["type","type"],b=[i*c],E=i*c,A=[{type:12,data:E},{type:12,data:c},{type:12,data:i}],I=$=>{let x=he("seq_lens",h.dataType,h.dims),k=he("total_seq_lens",m.dataType,m.dims),N=Je("pos_ids",y,b),M=[{name:"output_size",type:"u32"},{name:"sequence_length",type:"u32"},{name:"batch_size",type:"u32"}];return`
1958
1958
  ${$.registerUniforms(M).declareVariables(x,k,N)}
1959
1959
  ${$.mainStart()}
1960
1960
  ${$.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
@@ -1985,7 +1985,7 @@ fn calculateOutputIndex(index: u32) -> u32 {
1985
1985
  ${N.setByOffset("global_idx","seqlen")}
1986
1986
  };
1987
1987
  }
1988
- `};return{name:"GeneratePositionIds",shaderCache:{hint:`${i};${c}`,inputDependencies:S},getRunData:()=>({outputs:[{dims:b,dataType:y}],dispatchGroup:{x:Math.ceil(E/64)},programUniforms:A}),getShaderSource:I}},zv=(i,c)=>{var V;let h=Hv(i.inputs,c);if(i.inputs[0].dims.length===5)throw new Error("Packed QKV is not implemented");if(((V=i.inputs[1])==null?void 0:V.dims.length)===5)throw new Error("Packed KV is not implemented");let m=i.inputs[0],y=i.inputs[1]&&i.inputs[1].dims.length>0?i.inputs[1]:void 0,S=i.inputs[2]&&i.inputs[2].dims.length>0?i.inputs[2]:void 0,b=i.inputs[3]&&i.inputs[3].dims.length!==0?i.inputs[3]:void 0,E=i.inputs[4]&&i.inputs[4].dims.length!==0?i.inputs[4]:void 0,A=i.inputs.length>4?i.inputs[5]:void 0,I=i.inputs.length>5?i.inputs[6]:void 0,$=h.kvNumHeads?h.kvNumHeads:h.numHeads,x=Rt({axis:2,numOutputs:3,splitSizes:[h.numHeads*h.headSize,$*h.headSize,$*h.headSize]}),[k,N,M]=!y&&!S?i.compute(_f([m],x),{inputs:[m],outputs:[-1,-1,-1]}):[m,y,S],U,z;if(c.doRotary){let Y=i.compute(Bv(h.batchSize,h.sequenceLength,A,I),{inputs:[A,I],outputs:[-1]})[0],ae=i.inputs[7],ne=i.inputs[8],de=Rt({interleaved:c.rotaryInterleaved!==0,numHeads:h.numHeads,rotaryEmbeddingDim:0,scale:c.scale}),ve=[k,Y,ae,ne],Ue=[-1];U=i.compute(tc(ve,de),{inputs:ve,outputs:Ue})[0],ve.splice(0,1,N);let ct=Rt({interleaved:c.rotaryInterleaved!==0,numHeads:h.kvNumHeads,rotaryEmbeddingDim:0,scale:c.scale});z=i.compute(tc(ve,ct),{inputs:ve,outputs:Ue})[0]}let L=$o(i,h.batchSize,h.numHeads,h.sequenceLength,h.headSize,c.doRotary?U:k,void 0,0),P=pf(i,c.doRotary?z:N,h),j=pf(i,M,h);Pe(i,L,P,j,void 0,void 0,b,E,void 0,h,A,I)}}),mf,Vv,qv,jv,BI=_(()=>{ot(),ht(),Qs(),_t(),mf=(i,c,h,m,y,S,b,E)=>{let A=Pt(S),I=A===1?"f32":`vec${A}f`,$=A===1?"vec2f":`mat2x${A}f`,x=y*b,k=64;x===1&&(k=256);let N=[y,b,S/A],M=[y,b,2],U=["rank","type","type"],z=[];z.push(...Xe(N,M));let L=P=>{let j=he("x",c.dataType,3,A),V=he("scale",h.dataType,h.dims),Y=he("bias",m.dataType,m.dims),ae=Je("output",1,3,2),ne=[j,V,Y,ae];return`
1988
+ `};return{name:"GeneratePositionIds",shaderCache:{hint:`${i};${c}`,inputDependencies:S},getRunData:()=>({outputs:[{dims:b,dataType:y}],dispatchGroup:{x:Math.ceil(E/64)},programUniforms:A}),getShaderSource:I}},zv=(i,c)=>{var V;let h=Hv(i.inputs,c);if(i.inputs[0].dims.length===5)throw new Error("Packed QKV is not implemented");if(((V=i.inputs[1])==null?void 0:V.dims.length)===5)throw new Error("Packed KV is not implemented");let m=i.inputs[0],y=i.inputs[1]&&i.inputs[1].dims.length>0?i.inputs[1]:void 0,S=i.inputs[2]&&i.inputs[2].dims.length>0?i.inputs[2]:void 0,b=i.inputs[3]&&i.inputs[3].dims.length!==0?i.inputs[3]:void 0,E=i.inputs[4]&&i.inputs[4].dims.length!==0?i.inputs[4]:void 0,A=i.inputs.length>4?i.inputs[5]:void 0,I=i.inputs.length>5?i.inputs[6]:void 0,$=h.kvNumHeads?h.kvNumHeads:h.numHeads,x=Rt({axis:2,numOutputs:3,splitSizes:[h.numHeads*h.headSize,$*h.headSize,$*h.headSize]}),[k,N,M]=!y&&!S?i.compute(hf([m],x),{inputs:[m],outputs:[-1,-1,-1]}):[m,y,S],U,z;if(c.doRotary){let Y=i.compute(Bv(h.batchSize,h.sequenceLength,A,I),{inputs:[A,I],outputs:[-1]})[0],ae=i.inputs[7],ne=i.inputs[8],de=Rt({interleaved:c.rotaryInterleaved!==0,numHeads:h.numHeads,rotaryEmbeddingDim:0,scale:c.scale}),ve=[k,Y,ae,ne],Ue=[-1];U=i.compute(tc(ve,de),{inputs:ve,outputs:Ue})[0],ve.splice(0,1,N);let ct=Rt({interleaved:c.rotaryInterleaved!==0,numHeads:h.kvNumHeads,rotaryEmbeddingDim:0,scale:c.scale});z=i.compute(tc(ve,ct),{inputs:ve,outputs:Ue})[0]}let L=$o(i,h.batchSize,h.numHeads,h.sequenceLength,h.headSize,c.doRotary?U:k,void 0,0),P=_f(i,c.doRotary?z:N,h),j=_f(i,M,h);Pe(i,L,P,j,void 0,void 0,b,E,void 0,h,A,I)}}),pf,Vv,qv,jv,BI=_(()=>{ot(),ht(),Qs(),_t(),pf=(i,c,h,m,y,S,b,E)=>{let A=Pt(S),I=A===1?"f32":`vec${A}f`,$=A===1?"vec2f":`mat2x${A}f`,x=y*b,k=64;x===1&&(k=256);let N=[y,b,S/A],M=[y,b,2],U=["rank","type","type"],z=[];z.push(...Xe(N,M));let L=P=>{let j=he("x",c.dataType,3,A),V=he("scale",h.dataType,h.dims),Y=he("bias",m.dataType,m.dims),ae=Je("output",1,3,2),ne=[j,V,Y,ae];return`
1989
1989
  var<workgroup> workgroup_shared : array<${$}, ${k}>;
1990
1990
  const workgroup_size = ${k}u;
1991
1991
  ${P.declareVariables(...ne)}
@@ -2019,7 +2019,7 @@ fn calculateOutputIndex(index: u32) -> u32 {
2019
2019
  let channel_shift = f32(bias[channel]) - sum_final * channel_scale;
2020
2020
  output[workgroup_index] = vec2f(channel_scale, channel_shift);
2021
2021
  }
2022
- }`};return i.compute({name:"InstanceNormComputeChannelScaleShift",shaderCache:{hint:`${A};${E};${k}`,inputDependencies:U},getRunData:()=>({outputs:[{dims:M,dataType:1}],dispatchGroup:{x},programUniforms:z}),getShaderSource:L},{inputs:[c,h,m],outputs:[-1]})[0]},Vv=(i,c,h)=>{let m=c[0].dims,y=m,S=2,b=m[0],E=m[1],A=ie.sizeFromDimension(m,S),I=Pt(A),$=ie.size(y)/I,x=mf(i,c[0],c[1],c[2],b,A,E,h.epsilon),k=[b,E,A/I],N=[b,E],M=["type","none"],U=z=>{let L=he("x",c[0].dataType,k.length,I),P=he("scale_shift",1,N.length,2),j=Je("output",c[0].dataType,k.length,I),V=[L,P,j];return`
2022
+ }`};return i.compute({name:"InstanceNormComputeChannelScaleShift",shaderCache:{hint:`${A};${E};${k}`,inputDependencies:U},getRunData:()=>({outputs:[{dims:M,dataType:1}],dispatchGroup:{x},programUniforms:z}),getShaderSource:L},{inputs:[c,h,m],outputs:[-1]})[0]},Vv=(i,c,h)=>{let m=c[0].dims,y=m,S=2,b=m[0],E=m[1],A=ie.sizeFromDimension(m,S),I=Pt(A),$=ie.size(y)/I,x=pf(i,c[0],c[1],c[2],b,A,E,h.epsilon),k=[b,E,A/I],N=[b,E],M=["type","none"],U=z=>{let L=he("x",c[0].dataType,k.length,I),P=he("scale_shift",1,N.length,2),j=Je("output",c[0].dataType,k.length,I),V=[L,P,j];return`
2023
2023
  ${z.registerUniform("output_size","u32").declareVariables(...V)}
2024
2024
  ${z.mainStart()}
2025
2025
  ${z.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
@@ -2029,7 +2029,7 @@ fn calculateOutputIndex(index: u32) -> u32 {
2029
2029
  let scale_shift = ${P.getByIndices("vec2<u32>(batch, channel)")};
2030
2030
  let value = ${L.getByOffset("global_idx")} * ${j.type.value}(scale_shift.x) + ${j.type.value}(scale_shift.y);
2031
2031
  ${j.setByOffset("global_idx","value")};
2032
- }`};i.compute({name:"InstanceNormalization",shaderCache:{hint:`${I}`,inputDependencies:M},getRunData:()=>({outputs:[{dims:y,dataType:c[0].dataType}],dispatchGroup:{x:Math.ceil($/64)},programUniforms:[{type:12,data:$},...Xe(k,N,k)]}),getShaderSource:U},{inputs:[c[0],x]})},qv=(i,c,h)=>{let m=c[0].dims,y=m,S=m[0],b=m[m.length-1],E=ie.sizeFromDimension(m,1)/b,A=Pt(b),I=ie.size(y)/A,$=[{type:12,data:E},{type:12,data:Math.floor(b/A)}],x=["type","type"],k=!1,N=[0,m.length-1];for(let L=0;L<m.length-2;L++)k=k||m[L+1]!==1,N.push(L+1);k=k&&m[m.length-1]!==1;let M=k?i.compute(ms(i.inputs[0],N),{inputs:[i.inputs[0]],outputs:[-1]})[0]:i.inputs[0].reshape(Array.from({length:m.length},(L,P)=>m[N[P]])),U=mf(i,M,c[1],c[2],S,E,b,h.epsilon),z=L=>{let P=Bt(c[0].dataType),j=A===1?"vec2f":`mat${A}x2f`,V=ne=>{let de=ne===0?"x":"y",ve=A===1?"f32":`vec${A}f`;switch(A){case 1:return`${P}(${ve}(scale.${de}))`;case 2:return`vec2<${P}>(${ve}(scale[0].${de}, scale[1].${de}))`;case 4:return`vec4<${P}>(${ve}(scale[0].${de}, scale[1].${de}, scale[2].${de}, scale[3].${de}))`;default:throw new Error(`Not supported compoents ${A}`)}},Y=he("input",c[0].dataType,c[0].dims,A),ae=Je("output",c[0].dataType,y,A);return`
2032
+ }`};i.compute({name:"InstanceNormalization",shaderCache:{hint:`${I}`,inputDependencies:M},getRunData:()=>({outputs:[{dims:y,dataType:c[0].dataType}],dispatchGroup:{x:Math.ceil($/64)},programUniforms:[{type:12,data:$},...Xe(k,N,k)]}),getShaderSource:U},{inputs:[c[0],x]})},qv=(i,c,h)=>{let m=c[0].dims,y=m,S=m[0],b=m[m.length-1],E=ie.sizeFromDimension(m,1)/b,A=Pt(b),I=ie.size(y)/A,$=[{type:12,data:E},{type:12,data:Math.floor(b/A)}],x=["type","type"],k=!1,N=[0,m.length-1];for(let L=0;L<m.length-2;L++)k=k||m[L+1]!==1,N.push(L+1);k=k&&m[m.length-1]!==1;let M=k?i.compute(ms(i.inputs[0],N),{inputs:[i.inputs[0]],outputs:[-1]})[0]:i.inputs[0].reshape(Array.from({length:m.length},(L,P)=>m[N[P]])),U=pf(i,M,c[1],c[2],S,E,b,h.epsilon),z=L=>{let P=Bt(c[0].dataType),j=A===1?"vec2f":`mat${A}x2f`,V=ne=>{let de=ne===0?"x":"y",ve=A===1?"f32":`vec${A}f`;switch(A){case 1:return`${P}(${ve}(scale.${de}))`;case 2:return`vec2<${P}>(${ve}(scale[0].${de}, scale[1].${de}))`;case 4:return`vec4<${P}>(${ve}(scale[0].${de}, scale[1].${de}, scale[2].${de}, scale[3].${de}))`;default:throw new Error(`Not supported compoents ${A}`)}},Y=he("input",c[0].dataType,c[0].dims,A),ae=Je("output",c[0].dataType,y,A);return`
2033
2033
  @group(0) @binding(0) var<storage, read> input : array<${Y.type.storage}>;
2034
2034
  @group(0) @binding(1) var<storage, read> scale_input : array<${j}>;
2035
2035
  @group(0) @binding(2) var<storage, read_write> output : array<${ae.type.storage}>;
@@ -2071,7 +2071,7 @@ fn calculateOutputIndex(index: u32) -> u32 {
2071
2071
 
2072
2072
  ${L?"mean_data_output[global_idx] = mean":""};
2073
2073
  ${P?"inv_std_output[global_idx] = inv_std_dev":""};
2074
- }`},V=[{dims:E,dataType:i[0].dataType}];return L&&V.push({dims:N,dataType:1}),P&&V.push({dims:N,dataType:1}),{name:"LayerNormalization",shaderCache:{hint:`${M};${h};${m}`,inputDependencies:U},getRunData:()=>({outputs:V,dispatchGroup:{x:Math.ceil(I/64)},programUniforms:z}),getShaderSource:j}},Kv=(i,c)=>{Gv(i.inputs),i.compute(Wv(i.inputs,c,i.outputCount))}}),Yv,Jv,VI=_(()=>{ht(),Qd(),tf(),Yv=i=>{if(!i||i.length!==2)throw new Error("MatMul requires 2 inputs.");if(i[0].dims[i[0].dims.length-1]!==i[1].dims[i[1].dims.length-2])throw new Error("shared dimension does not match.")},Jv=i=>{Yv(i.inputs);let c=bn.calcShape(i.inputs[0].dims,i.inputs[1].dims,!0);if(!c)throw new Error("Can't use matmul on the given tensors");let h=c[c.length-1],m=i.inputs[0].dims[i.inputs[0].dims.length-1];if(h<8&&m<8)i.compute(Jd(i.inputs,{activation:""},c));else{let y=c[c.length-2],S=ie.size(i.inputs[0].dims.slice(0,-2)),b=ie.size(i.inputs[1].dims.slice(0,-2));if(S!==1&&y===1&&b===1){let E=i.inputs[0].reshape([1,S,m]),A=i.inputs[1].reshape([1,m,h]),I=[1,S,h],$=[E,A];i.compute(Qu($,{activation:""},c,I),{inputs:$})}else i.compute(Qu(i.inputs,{activation:""},c))}}}),Qv,Xv,Zv,ey,ty,qI=_(()=>{ot(),ht(),jt(),_t(),Qv=(i,c)=>{if(i.length<3||i.length>4)throw new Error("MatMulNBits requires 3 or 4 inputs");let h=i[0],m=h.dims.length;if(h.dims[m-1]!==c.k)throw new Error("The last dim of input shape does not match the k value");let y=Math.floor((c.k+c.blockSize-1)/c.blockSize),S=c.blockSize/8*c.bits,b=i[1];if(!ie.areEqual(b.dims,[c.n,y,S]))throw new Error("The second inputs must be 3D tensor with shape N X nBlocksPerCol X blobSize");let E=i[2].dims;if(ie.size(E)!==c.n*y)throw new Error("scales input size error.");if(i.length===4){let A=i[3].dims,I=c.n*(c.bits===8?y:Math.floor((y*c.bits+7)/8));if(ie.size(A)!==I)throw new Error("zeroPoints input size error.")}},Xv=(i,c)=>{let h=i[0].dims,m=h.length,y=h[m-2],S=c.k,b=c.n,E=h.slice(0,m-2),A=ie.size(E),I=i[1].dims[2]/4,$=i[0].dataType,x=Pt(c.k),k=Pt(I),N=Pt(b),M=E.concat([y,b]),U=y>1&&b/N%2===0?2:1,z=ie.size(M)/N/U,L=64,P=[],j=[A,y,S/x],V=ie.convertShape(i[1].dims).slice();V.splice(-1,1,I/k),P.push(...Xe(j)),P.push(...Xe(V)),P.push(...Xe(i[2].dims)),i.length===4&&P.push(...Xe(ie.convertShape(i[3].dims)));let Y=[A,y,b/N];P.push(...Xe(Y));let ae=ne=>{let de=j.length,ve=he("a",i[0].dataType,de,x),Ue=he("b",12,V.length,k),ct=he("scales",i[2].dataType,i[2].dims.length),st=[ve,Ue,ct],ut=i.length===4?he("zero_points",12,i[3].dims.length):void 0;ut&&st.push(ut);let $t=Y.length,Tt=Je("output",i[0].dataType,$t,N),at=Bt(i[0].dataType),St=(()=>{switch(x){case 1:return`array<${at}, 8>`;case 2:return`mat4x2<${at}>`;case 4:return`mat2x4<${at}>`;default:throw new Error(`${x}-component is not supported.`)}})(),it=()=>{let Se=`
2074
+ }`},V=[{dims:E,dataType:i[0].dataType}];return L&&V.push({dims:N,dataType:1}),P&&V.push({dims:N,dataType:1}),{name:"LayerNormalization",shaderCache:{hint:`${M};${h};${m}`,inputDependencies:U},getRunData:()=>({outputs:V,dispatchGroup:{x:Math.ceil(I/64)},programUniforms:z}),getShaderSource:j}},Kv=(i,c)=>{Gv(i.inputs),i.compute(Wv(i.inputs,c,i.outputCount))}}),Yv,Jv,VI=_(()=>{ht(),Jd(),ef(),Yv=i=>{if(!i||i.length!==2)throw new Error("MatMul requires 2 inputs.");if(i[0].dims[i[0].dims.length-1]!==i[1].dims[i[1].dims.length-2])throw new Error("shared dimension does not match.")},Jv=i=>{Yv(i.inputs);let c=bn.calcShape(i.inputs[0].dims,i.inputs[1].dims,!0);if(!c)throw new Error("Can't use matmul on the given tensors");let h=c[c.length-1],m=i.inputs[0].dims[i.inputs[0].dims.length-1];if(h<8&&m<8)i.compute(Yd(i.inputs,{activation:""},c));else{let y=c[c.length-2],S=ie.size(i.inputs[0].dims.slice(0,-2)),b=ie.size(i.inputs[1].dims.slice(0,-2));if(S!==1&&y===1&&b===1){let E=i.inputs[0].reshape([1,S,m]),A=i.inputs[1].reshape([1,m,h]),I=[1,S,h],$=[E,A];i.compute(Qu($,{activation:""},c,I),{inputs:$})}else i.compute(Qu(i.inputs,{activation:""},c))}}}),Qv,Xv,Zv,ey,ty,qI=_(()=>{ot(),ht(),jt(),_t(),Qv=(i,c)=>{if(i.length<3||i.length>4)throw new Error("MatMulNBits requires 3 or 4 inputs");let h=i[0],m=h.dims.length;if(h.dims[m-1]!==c.k)throw new Error("The last dim of input shape does not match the k value");let y=Math.floor((c.k+c.blockSize-1)/c.blockSize),S=c.blockSize/8*c.bits,b=i[1];if(!ie.areEqual(b.dims,[c.n,y,S]))throw new Error("The second inputs must be 3D tensor with shape N X nBlocksPerCol X blobSize");let E=i[2].dims;if(ie.size(E)!==c.n*y)throw new Error("scales input size error.");if(i.length===4){let A=i[3].dims,I=c.n*(c.bits===8?y:Math.floor((y*c.bits+7)/8));if(ie.size(A)!==I)throw new Error("zeroPoints input size error.")}},Xv=(i,c)=>{let h=i[0].dims,m=h.length,y=h[m-2],S=c.k,b=c.n,E=h.slice(0,m-2),A=ie.size(E),I=i[1].dims[2]/4,$=i[0].dataType,x=Pt(c.k),k=Pt(I),N=Pt(b),M=E.concat([y,b]),U=y>1&&b/N%2===0?2:1,z=ie.size(M)/N/U,L=64,P=[],j=[A,y,S/x],V=ie.convertShape(i[1].dims).slice();V.splice(-1,1,I/k),P.push(...Xe(j)),P.push(...Xe(V)),P.push(...Xe(i[2].dims)),i.length===4&&P.push(...Xe(ie.convertShape(i[3].dims)));let Y=[A,y,b/N];P.push(...Xe(Y));let ae=ne=>{let de=j.length,ve=he("a",i[0].dataType,de,x),Ue=he("b",12,V.length,k),ct=he("scales",i[2].dataType,i[2].dims.length),st=[ve,Ue,ct],ut=i.length===4?he("zero_points",12,i[3].dims.length):void 0;ut&&st.push(ut);let $t=Y.length,Tt=Je("output",i[0].dataType,$t,N),at=Bt(i[0].dataType),St=(()=>{switch(x){case 1:return`array<${at}, 8>`;case 2:return`mat4x2<${at}>`;case 4:return`mat2x4<${at}>`;default:throw new Error(`${x}-component is not supported.`)}})(),it=()=>{let Se=`
2075
2075
  // reuse a data
2076
2076
  var input_offset = ${ve.indicesToOffset(`${ve.type.indices}(batch, row, word_offset)`)};
2077
2077
  var a_data: ${St};
@@ -2295,7 +2295,7 @@ fn calculateOutputIndex(index: u32) -> u32 {
2295
2295
  var value = ${k}(0);
2296
2296
  ${N}
2297
2297
  output[global_idx] = value;
2298
- }`};return{name:"Pad",shaderCache:{hint:`${c.mode}${b}`,inputDependencies:E},getRunData:()=>({outputs:[{dims:h,dataType:i[0].dataType}],dispatchGroup:{x:Math.ceil(ie.size(h)/64)},programUniforms:S}),getShaderSource:A}},uy=(i,c)=>{if(i.length>1){let h=i[1].getBigInt64Array(),m=i.length>=3&&i[2].data?i[2].dataType===10?i[2].getUint16Array()[0]:i[2].getFloat32Array()[0]:0,y=i[0].dims.length,S=new Int32Array(2*y).fill(0);if(i.length>=4){let E=i[3].getBigInt64Array();for(let A=0;A<E.length;A++)S[Number(E[A])]=Number(h[A]),S[Number(E[A])+y]=Number(h[A+E.length])}else h.forEach((E,A)=>S[Number(A)]=Number(E));let b=[];return S.forEach(E=>b.push(E)),{mode:c.mode,value:m,pads:b}}else return c},cy=(i,c)=>{sy(i.inputs);let h=uy(i.inputs,c);i.compute(oy(i.inputs,h),{inputs:[0]})}}),xo,gf,vf,yf,Tf,dy,fy,Sf,bf,hy,_y,wf,py,my,Ef,gy,vy,yy,Ty,GI=_(()=>{as(),ot(),ht(),_t(),xo=i=>{if(Z.webgpu.validateInputContent&&(!i||i.length!==1))throw new Error("Pool ops requires 1 input.")},gf=(i,c,h)=>{let m=c.format==="NHWC",y=i.dims.slice();m&&y.splice(1,0,y.pop());let S=Object.hasOwnProperty.call(c,"dilations"),b=c.kernelShape.slice(),E=c.strides.slice(),A=S?c.dilations.slice():[],I=c.pads.slice();Ls.adjustPoolAttributes(h,y,b,E,A,I);let $=Ls.computePoolOutputShape(h,y,E,A,b,I,c.autoPad),x=Object.assign({},c);S?Object.assign(x,{kernelShape:b,strides:E,pads:I,dilations:A,cacheKey:c.cacheKey}):Object.assign(x,{kernelShape:b,strides:E,pads:I,cacheKey:c.cacheKey});let k=$.slice();return k.push(k.splice(1,1)[0]),[x,m?k:$]},vf=(i,c)=>{let h=c.format==="NHWC",m=ie.size(i),y=ie.size(c.kernelShape),S=[{type:12,data:m},{type:12,data:y}],b=[{name:"outputSize",type:"u32"},{name:"kernelSize",type:"u32"}];if(c.kernelShape.length<=2){let E=c.kernelShape[c.kernelShape.length-1],A=c.strides[c.strides.length-1],I=c.pads[c.pads.length/2-1],$=c.pads[c.pads.length-1],x=!!(I+$);S.push({type:12,data:E},{type:12,data:A},{type:12,data:I},{type:12,data:$}),b.push({name:"kw",type:"u32"},{name:"sw",type:"u32"},{name:"pwStart",type:"u32"},{name:"pwEnd",type:"u32"});let k=!1;if(c.kernelShape.length===2){let N=c.kernelShape[c.kernelShape.length-2],M=c.strides[c.strides.length-2],U=c.pads[c.pads.length/2-2],z=c.pads[c.pads.length-2];k=!!(U+z),S.push({type:12,data:N},{type:12,data:M},{type:12,data:U},{type:12,data:z}),b.push({name:"kh",type:"u32"},{name:"sh",type:"u32"},{name:"phStart",type:"u32"},{name:"phEnd",type:"u32"})}return[S,b,!0,x,k]}else{if(h)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let E=ie.computeStrides(c.kernelShape);S.push({type:12,data:E},{type:12,data:c.pads},{type:12,data:c.strides}),b.push({name:"kernelStrides",type:"u32",length:E.length},{name:"pads",type:"u32",length:c.pads.length},{name:"strides",type:"u32",length:c.strides.length});let A=c.pads.reduce((I,$)=>I+$);return[S,b,!!A,!1,!1]}},yf=(i,c,h,m,y,S,b,E,A,I,$,x)=>{let k=y.format==="NHWC",N=c.type.value,M=Je("output",c.type.tensor,m);if(y.kernelShape.length<=2){let U="",z="",L="",P=h-(k?2:1);if($?U=`
2298
+ }`};return{name:"Pad",shaderCache:{hint:`${c.mode}${b}`,inputDependencies:E},getRunData:()=>({outputs:[{dims:h,dataType:i[0].dataType}],dispatchGroup:{x:Math.ceil(ie.size(h)/64)},programUniforms:S}),getShaderSource:A}},uy=(i,c)=>{if(i.length>1){let h=i[1].getBigInt64Array(),m=i.length>=3&&i[2].data?i[2].dataType===10?i[2].getUint16Array()[0]:i[2].getFloat32Array()[0]:0,y=i[0].dims.length,S=new Int32Array(2*y).fill(0);if(i.length>=4){let E=i[3].getBigInt64Array();for(let A=0;A<E.length;A++)S[Number(E[A])]=Number(h[A]),S[Number(E[A])+y]=Number(h[A+E.length])}else h.forEach((E,A)=>S[Number(A)]=Number(E));let b=[];return S.forEach(E=>b.push(E)),{mode:c.mode,value:m,pads:b}}else return c},cy=(i,c)=>{sy(i.inputs);let h=uy(i.inputs,c);i.compute(oy(i.inputs,h),{inputs:[0]})}}),xo,mf,gf,vf,yf,dy,fy,Tf,Sf,hy,_y,bf,py,my,wf,gy,vy,yy,Ty,GI=_(()=>{as(),ot(),ht(),_t(),xo=i=>{if(Z.webgpu.validateInputContent&&(!i||i.length!==1))throw new Error("Pool ops requires 1 input.")},mf=(i,c,h)=>{let m=c.format==="NHWC",y=i.dims.slice();m&&y.splice(1,0,y.pop());let S=Object.hasOwnProperty.call(c,"dilations"),b=c.kernelShape.slice(),E=c.strides.slice(),A=S?c.dilations.slice():[],I=c.pads.slice();Ls.adjustPoolAttributes(h,y,b,E,A,I);let $=Ls.computePoolOutputShape(h,y,E,A,b,I,c.autoPad),x=Object.assign({},c);S?Object.assign(x,{kernelShape:b,strides:E,pads:I,dilations:A,cacheKey:c.cacheKey}):Object.assign(x,{kernelShape:b,strides:E,pads:I,cacheKey:c.cacheKey});let k=$.slice();return k.push(k.splice(1,1)[0]),[x,m?k:$]},gf=(i,c)=>{let h=c.format==="NHWC",m=ie.size(i),y=ie.size(c.kernelShape),S=[{type:12,data:m},{type:12,data:y}],b=[{name:"outputSize",type:"u32"},{name:"kernelSize",type:"u32"}];if(c.kernelShape.length<=2){let E=c.kernelShape[c.kernelShape.length-1],A=c.strides[c.strides.length-1],I=c.pads[c.pads.length/2-1],$=c.pads[c.pads.length-1],x=!!(I+$);S.push({type:12,data:E},{type:12,data:A},{type:12,data:I},{type:12,data:$}),b.push({name:"kw",type:"u32"},{name:"sw",type:"u32"},{name:"pwStart",type:"u32"},{name:"pwEnd",type:"u32"});let k=!1;if(c.kernelShape.length===2){let N=c.kernelShape[c.kernelShape.length-2],M=c.strides[c.strides.length-2],U=c.pads[c.pads.length/2-2],z=c.pads[c.pads.length-2];k=!!(U+z),S.push({type:12,data:N},{type:12,data:M},{type:12,data:U},{type:12,data:z}),b.push({name:"kh",type:"u32"},{name:"sh",type:"u32"},{name:"phStart",type:"u32"},{name:"phEnd",type:"u32"})}return[S,b,!0,x,k]}else{if(h)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let E=ie.computeStrides(c.kernelShape);S.push({type:12,data:E},{type:12,data:c.pads},{type:12,data:c.strides}),b.push({name:"kernelStrides",type:"u32",length:E.length},{name:"pads",type:"u32",length:c.pads.length},{name:"strides",type:"u32",length:c.strides.length});let A=c.pads.reduce((I,$)=>I+$);return[S,b,!!A,!1,!1]}},vf=(i,c,h,m,y,S,b,E,A,I,$,x)=>{let k=y.format==="NHWC",N=c.type.value,M=Je("output",c.type.tensor,m);if(y.kernelShape.length<=2){let U="",z="",L="",P=h-(k?2:1);if($?U=`
2299
2299
  for (var i: u32 = 0u; i < uniforms.kw; i++) {
2300
2300
  xIndices[${P}] = indices[${P}] * uniforms.sw - uniforms.pwStart + i;
2301
2301
  if (xIndices[${P}] < 0 || xIndices[${P}]
@@ -2384,9 +2384,9 @@ fn calculateOutputIndex(index: u32) -> u32 {
2384
2384
  ${b}
2385
2385
 
2386
2386
  output[global_idx] = value;
2387
- }`}},Tf=i=>`${i.format};${i.ceilMode};${i.autoPad};${i.kernelShape.length}`,dy=i=>`${Tf(i)};${i.countIncludePad}`,fy=i=>`${Tf(i)};${i.storageOrder};${i.dilations}`,Sf=i=>({format:i.format,autoPad:["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][i.auto_pad],ceilMode:i.ceil_mode,kernelShape:i.kernel_shape,strides:i.strides,pads:i.pads}),bf=(i,c,h,m)=>{let[y,S]=gf(c,m,h),b=he("x",c.dataType,c.dims.length),E=b.type.value,A="value += x_val;",I="";y.countIncludePad?I+=`value /= ${E}(uniforms.kernelSize);`:I+=`value /= ${E}(i32(uniforms.kernelSize) - pad);`;let[$,x,k,N,M]=vf(S,y);$.push(...Xe(c.dims,S));let U=["rank"];return{name:i,shaderCache:{hint:`${m.cacheKey};${k};${N};${M}`,inputDependencies:U},getRunData:()=>({outputs:[{dims:S,dataType:c.dataType}],dispatchGroup:{x:Math.ceil(ie.size(S)/64)},programUniforms:$}),getShaderSource:z=>yf(z,b,c.dims.length,S.length,y,A,I,0,x,k,N,M)}},hy=i=>{let c=i.count_include_pad!==0,h=Sf(i);if(h.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for AveragePool");let m={countIncludePad:c,...h,cacheKey:""};return{...m,cacheKey:dy(m)}},_y=(i,c)=>{xo(i.inputs),i.compute(bf("AveragePool",i.inputs[0],!1,c))},wf={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[]},py=i=>{let c=i.format;return{format:c,...wf,cacheKey:c}},my=(i,c)=>{xo(i.inputs),i.compute(bf("GlobalAveragePool",i.inputs[0],!0,c))},Ef=(i,c,h,m)=>{let[y,S]=gf(c,m,h),b=`
2387
+ }`}},yf=i=>`${i.format};${i.ceilMode};${i.autoPad};${i.kernelShape.length}`,dy=i=>`${yf(i)};${i.countIncludePad}`,fy=i=>`${yf(i)};${i.storageOrder};${i.dilations}`,Tf=i=>({format:i.format,autoPad:["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][i.auto_pad],ceilMode:i.ceil_mode,kernelShape:i.kernel_shape,strides:i.strides,pads:i.pads}),Sf=(i,c,h,m)=>{let[y,S]=mf(c,m,h),b=he("x",c.dataType,c.dims.length),E=b.type.value,A="value += x_val;",I="";y.countIncludePad?I+=`value /= ${E}(uniforms.kernelSize);`:I+=`value /= ${E}(i32(uniforms.kernelSize) - pad);`;let[$,x,k,N,M]=gf(S,y);$.push(...Xe(c.dims,S));let U=["rank"];return{name:i,shaderCache:{hint:`${m.cacheKey};${k};${N};${M}`,inputDependencies:U},getRunData:()=>({outputs:[{dims:S,dataType:c.dataType}],dispatchGroup:{x:Math.ceil(ie.size(S)/64)},programUniforms:$}),getShaderSource:z=>vf(z,b,c.dims.length,S.length,y,A,I,0,x,k,N,M)}},hy=i=>{let c=i.count_include_pad!==0,h=Tf(i);if(h.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for AveragePool");let m={countIncludePad:c,...h,cacheKey:""};return{...m,cacheKey:dy(m)}},_y=(i,c)=>{xo(i.inputs),i.compute(Sf("AveragePool",i.inputs[0],!1,c))},bf={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[]},py=i=>{let c=i.format;return{format:c,...bf,cacheKey:c}},my=(i,c)=>{xo(i.inputs),i.compute(Sf("GlobalAveragePool",i.inputs[0],!0,c))},wf=(i,c,h,m)=>{let[y,S]=mf(c,m,h),b=`
2388
2388
  value = max(x_val, value);
2389
- `,E="",A=he("x",c.dataType,c.dims.length),I=["rank"],[$,x,k,N,M]=vf(S,y);return $.push(...Xe(c.dims,S)),{name:i,shaderCache:{hint:`${m.cacheKey};${k};${N};${M}`,inputDependencies:I},getRunData:()=>({outputs:[{dims:S,dataType:c.dataType}],dispatchGroup:{x:Math.ceil(ie.size(S)/64)},programUniforms:$}),getShaderSource:U=>yf(U,A,c.dims.length,S.length,y,b,E,c.dataType===10?-65504:-1e5,x,k,N,M)}},gy=(i,c)=>{xo(i.inputs),i.compute(Ef("MaxPool",i.inputs[0],!1,c))},vy=i=>{let c=i.storage_order,h=i.dilations,m=Sf(i);if(c!==0)throw new Error("column major storage order is not yet supported for MaxPool");if(m.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for MaxPool");let y={storageOrder:c,dilations:h,...m,cacheKey:""};return{...y,cacheKey:fy(y)}},yy=i=>{let c=i.format;return{format:c,...wf,cacheKey:c}},Ty=(i,c)=>{xo(i.inputs),i.compute(Ef("GlobalMaxPool",i.inputs[0],!0,c))}}),Sy,by,wy,Ey,WI=_(()=>{ot(),ht(),jt(),_t(),Sy=(i,c)=>{if(i.length<2||i.length>3)throw new Error("DequantizeLinear requires 2 or 3 inputs.");if(i.length===3&&i[1].dims===i[2].dims)throw new Error("x-scale and x-zero-point must have the same shape.");if(i.length===3&&i[0].dataType!==i[2].dataType)throw new Error("x and x-zero-point must have the same data type.");if(i[0].dataType===6&&i.length>2)throw new Error("In the case of dequantizing int32 there is no zero point.");if(i[1].dims.length!==0&&i[1].dims.length!==1&&i[1].dims.length!==i[0].dims.length)throw new Error("scale input must be a scalar, a 1D tensor, or have the same rank as the input tensor.");if(i.length>2){if(i[0].dataType!==i[2].dataType)throw new Error("x and x-zero-point must have the same data type.");if(i[1].dims.length!==i[2].dims.length)throw new Error("scale and zero-point inputs must have the same rank.");if(!i[1].dims.map((h,m)=>h===i[2].dims[m]).reduce((h,m)=>h&&m,!0))throw new Error("scale and zero-point inputs must have the same shape.")}if(c.blockSize>0){if(i[1].dims.length===0||i[1].dims.length===1&&i[1].dims[0]===1)throw new Error("blockSize must be set only for block quantization.");if(!i[1].dims.map((y,S)=>S===c.axis||y===i[0].dims[S]).reduce((y,S)=>y&&S,!0))throw new Error("For block qunatization, scale input shape to match the input shape except for the axis");if(i[1].dims.length!==i[0].dims.length)throw new Error("For block qunatization the scale input rank must be the same as the x rank.");let h=i[0].dims[c.axis],m=i[1].dims[c.axis];if(c.blockSize<Math.ceil(h/m)||c.blockSize>Math.ceil(h/(m-1)-1))throw new Error("blockSize must be with in the range [ceil(dI / Si), ceil(dI / (Si - 1) - 1)].")}},by=(i,c)=>{let h=ie.normalizeAxis(c.axis,i[0].dims.length),m=i[0].dataType,y=m===3,S=i[0].dims,b=i[1].dataType,E=ie.size(S),A=m===3||m===2,I=A?[Math.ceil(ie.size(i[0].dims)/4)]:i[0].dims,$=i[1].dims,x=i.length>2?i[2]:void 0,k=x?A?[Math.ceil(ie.size(x.dims)/4)]:x.dims:void 0,N=$.length===0||$.length===1&&$[0]===1,M=N===!1&&$.length===1,U=Pt(E),z=N&&(!A||U===4),L=z?U:1,P=z&&!A?U:1,j=he("input",A?12:m,I.length,P),V=he("scale",b,$.length),Y=x?he("zero_point",A?12:m,k.length):void 0,ae=Je("output",b,S.length,L),ne=[j,V];Y&&ne.push(Y);let de=[I,$];x&&de.push(k);let ve=[{type:12,data:E/L},{type:12,data:h},{type:12,data:c.blockSize},...Xe(...de,S)],Ue=ct=>{let st=[{name:"output_size",type:"u32"},{name:"axis",type:"u32"},{name:"block_size",type:"u32"}];return`
2389
+ `,E="",A=he("x",c.dataType,c.dims.length),I=["rank"],[$,x,k,N,M]=gf(S,y);return $.push(...Xe(c.dims,S)),{name:i,shaderCache:{hint:`${m.cacheKey};${k};${N};${M}`,inputDependencies:I},getRunData:()=>({outputs:[{dims:S,dataType:c.dataType}],dispatchGroup:{x:Math.ceil(ie.size(S)/64)},programUniforms:$}),getShaderSource:U=>vf(U,A,c.dims.length,S.length,y,b,E,c.dataType===10?-65504:-1e5,x,k,N,M)}},gy=(i,c)=>{xo(i.inputs),i.compute(wf("MaxPool",i.inputs[0],!1,c))},vy=i=>{let c=i.storage_order,h=i.dilations,m=Tf(i);if(c!==0)throw new Error("column major storage order is not yet supported for MaxPool");if(m.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for MaxPool");let y={storageOrder:c,dilations:h,...m,cacheKey:""};return{...y,cacheKey:fy(y)}},yy=i=>{let c=i.format;return{format:c,...bf,cacheKey:c}},Ty=(i,c)=>{xo(i.inputs),i.compute(wf("GlobalMaxPool",i.inputs[0],!0,c))}}),Sy,by,wy,Ey,WI=_(()=>{ot(),ht(),jt(),_t(),Sy=(i,c)=>{if(i.length<2||i.length>3)throw new Error("DequantizeLinear requires 2 or 3 inputs.");if(i.length===3&&i[1].dims===i[2].dims)throw new Error("x-scale and x-zero-point must have the same shape.");if(i.length===3&&i[0].dataType!==i[2].dataType)throw new Error("x and x-zero-point must have the same data type.");if(i[0].dataType===6&&i.length>2)throw new Error("In the case of dequantizing int32 there is no zero point.");if(i[1].dims.length!==0&&i[1].dims.length!==1&&i[1].dims.length!==i[0].dims.length)throw new Error("scale input must be a scalar, a 1D tensor, or have the same rank as the input tensor.");if(i.length>2){if(i[0].dataType!==i[2].dataType)throw new Error("x and x-zero-point must have the same data type.");if(i[1].dims.length!==i[2].dims.length)throw new Error("scale and zero-point inputs must have the same rank.");if(!i[1].dims.map((h,m)=>h===i[2].dims[m]).reduce((h,m)=>h&&m,!0))throw new Error("scale and zero-point inputs must have the same shape.")}if(c.blockSize>0){if(i[1].dims.length===0||i[1].dims.length===1&&i[1].dims[0]===1)throw new Error("blockSize must be set only for block quantization.");if(!i[1].dims.map((y,S)=>S===c.axis||y===i[0].dims[S]).reduce((y,S)=>y&&S,!0))throw new Error("For block qunatization, scale input shape to match the input shape except for the axis");if(i[1].dims.length!==i[0].dims.length)throw new Error("For block qunatization the scale input rank must be the same as the x rank.");let h=i[0].dims[c.axis],m=i[1].dims[c.axis];if(c.blockSize<Math.ceil(h/m)||c.blockSize>Math.ceil(h/(m-1)-1))throw new Error("blockSize must be with in the range [ceil(dI / Si), ceil(dI / (Si - 1) - 1)].")}},by=(i,c)=>{let h=ie.normalizeAxis(c.axis,i[0].dims.length),m=i[0].dataType,y=m===3,S=i[0].dims,b=i[1].dataType,E=ie.size(S),A=m===3||m===2,I=A?[Math.ceil(ie.size(i[0].dims)/4)]:i[0].dims,$=i[1].dims,x=i.length>2?i[2]:void 0,k=x?A?[Math.ceil(ie.size(x.dims)/4)]:x.dims:void 0,N=$.length===0||$.length===1&&$[0]===1,M=N===!1&&$.length===1,U=Pt(E),z=N&&(!A||U===4),L=z?U:1,P=z&&!A?U:1,j=he("input",A?12:m,I.length,P),V=he("scale",b,$.length),Y=x?he("zero_point",A?12:m,k.length):void 0,ae=Je("output",b,S.length,L),ne=[j,V];Y&&ne.push(Y);let de=[I,$];x&&de.push(k);let ve=[{type:12,data:E/L},{type:12,data:h},{type:12,data:c.blockSize},...Xe(...de,S)],Ue=ct=>{let st=[{name:"output_size",type:"u32"},{name:"axis",type:"u32"},{name:"block_size",type:"u32"}];return`
2390
2390
  ${ct.registerUniforms(st).declareVariables(...ne,ae)}
2391
2391
  ${ct.mainStart()}
2392
2392
  ${ct.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
@@ -2475,8 +2475,8 @@ fn calculateOutputIndex(index: u32) -> u32 {
2475
2475
  ${Ry(c.reduction,"output[data_offset + i]","value",M.type.value)}
2476
2476
  }
2477
2477
 
2478
- }`};return{name:"ScatterND",shaderCache:{hint:`${c.cacheKey}_${c.reduction}`,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:y,dataType:i[0].dataType}],dispatchGroup:{x:Math.ceil(b/64)},programUniforms:I}),getShaderSource:$}},xy=i=>Rt({reduction:i.reduction}),Oy=(i,c)=>{i.compute($y(i.inputs,c),{inputs:[i.inputs[1],i.inputs[2]],outputs:[]})}}),Dy,ky,Ny,Cf,My,Uy,Py,Ly,Hy,Fy,By,zy,Af,Vy,qy,jy,Gy,Wy,Ky,Yy,JI=_(()=>{ot(),ht(),jt(),_t(),Dy=(i,c)=>{if(i.every(h=>h>0||(()=>{throw new Error("Resize requires scales input values to be positive")})),i.length>0){if(c.mode==="linear"){if(!(i.length===2||i.length===3||i.length===4&&i[0]===1&&i[1]===1||i.length===4&&i[0]===1&&i[3]===1||i.length===5&&i[0]===1&&i[1]===1))throw new Error(`For linear mode, Resize requires scales to be 2D, 3D, 4D with either two outermost or one innermost and
2479
- one outermost scale values equal to 1, or 5D with two outermost scale values equal to 1`)}else if(c.mode==="cubic"&&!(i.length===2||i.length===4&&i[0]===1&&i[1]===1||i.length===4&&i[0]===1&&i[3]===1))throw new Error("Resize requires scales input size to be 2 or 4 for cubic mode")}},ky=(i,c,h)=>{c.every(y=>y>=0&&y<h||(()=>{throw new Error("Resize requires axes input values to be positive and less than rank")}));let m=new Array(h).fill(1);return c.forEach((y,S)=>m[y]=i[S]),m},Ny=(i,c,h,m,y,S)=>{let[b,E,A]=h>10?[1,2,3]:[-1,i.length>1?1:-1,-1],I=i[0].dims.length;if(b>0&&i.length>b&&i[b].dims.length>0)i[b].getFloat32Array().forEach($=>S.push($));else if(c.coordinateTransformMode==="tf_crop_and_resize")throw new Error("Resize requires RoI input to be specified when coordinateTransformMode is tfCropAndResize");if(E>0&&i.length>E&&i[E].dims.length===1&&i[E].dims[0]>0){if(i[E].getFloat32Array().forEach($=>m.push($)),m.length!==0&&m.length!==I&&h>=18&&m.length!==c.axes.length)throw new Error("Resize requires scales input size to be same as input rank or axes size for opset 18 and up");Dy(m,c),c.axes.length>0&&ky(m,c.axes,I).forEach(($,x)=>m[x]=$)}if(A>0&&i.length>A&&i[A].dims.length===1&&i[A].dims[0]>0&&(i[A].getBigInt64Array().forEach($=>y.push(Number($))),y.length!==0&&y.length!==I&&h>=18&&y.length!==c.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(c.axes.length>0){if(m.length!==0&&m.length!==c.axes.length)throw new Error('Resize requires "scales" input size to be of axes rank when axes attributes is specified');if(y.length!==0&&y.length!==c.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 y<"u"&&m.length>0&&y.length>I)throw new Error("Resize requires only of scales or sizes to be specified")},Cf=(i,c,h,m)=>`
2478
+ }`};return{name:"ScatterND",shaderCache:{hint:`${c.cacheKey}_${c.reduction}`,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:y,dataType:i[0].dataType}],dispatchGroup:{x:Math.ceil(b/64)},programUniforms:I}),getShaderSource:$}},xy=i=>Rt({reduction:i.reduction}),Oy=(i,c)=>{i.compute($y(i.inputs,c),{inputs:[i.inputs[1],i.inputs[2]],outputs:[]})}}),Dy,ky,Ny,Ef,My,Uy,Py,Ly,Hy,Fy,By,zy,Cf,Vy,qy,jy,Gy,Wy,Ky,Yy,JI=_(()=>{ot(),ht(),jt(),_t(),Dy=(i,c)=>{if(i.every(h=>h>0||(()=>{throw new Error("Resize requires scales input values to be positive")})),i.length>0){if(c.mode==="linear"){if(!(i.length===2||i.length===3||i.length===4&&i[0]===1&&i[1]===1||i.length===4&&i[0]===1&&i[3]===1||i.length===5&&i[0]===1&&i[1]===1))throw new Error(`For linear mode, Resize requires scales to be 2D, 3D, 4D with either two outermost or one innermost and
2479
+ one outermost scale values equal to 1, or 5D with two outermost scale values equal to 1`)}else if(c.mode==="cubic"&&!(i.length===2||i.length===4&&i[0]===1&&i[1]===1||i.length===4&&i[0]===1&&i[3]===1))throw new Error("Resize requires scales input size to be 2 or 4 for cubic mode")}},ky=(i,c,h)=>{c.every(y=>y>=0&&y<h||(()=>{throw new Error("Resize requires axes input values to be positive and less than rank")}));let m=new Array(h).fill(1);return c.forEach((y,S)=>m[y]=i[S]),m},Ny=(i,c,h,m,y,S)=>{let[b,E,A]=h>10?[1,2,3]:[-1,i.length>1?1:-1,-1],I=i[0].dims.length;if(b>0&&i.length>b&&i[b].dims.length>0)i[b].getFloat32Array().forEach($=>S.push($));else if(c.coordinateTransformMode==="tf_crop_and_resize")throw new Error("Resize requires RoI input to be specified when coordinateTransformMode is tfCropAndResize");if(E>0&&i.length>E&&i[E].dims.length===1&&i[E].dims[0]>0){if(i[E].getFloat32Array().forEach($=>m.push($)),m.length!==0&&m.length!==I&&h>=18&&m.length!==c.axes.length)throw new Error("Resize requires scales input size to be same as input rank or axes size for opset 18 and up");Dy(m,c),c.axes.length>0&&ky(m,c.axes,I).forEach(($,x)=>m[x]=$)}if(A>0&&i.length>A&&i[A].dims.length===1&&i[A].dims[0]>0&&(i[A].getBigInt64Array().forEach($=>y.push(Number($))),y.length!==0&&y.length!==I&&h>=18&&y.length!==c.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(c.axes.length>0){if(m.length!==0&&m.length!==c.axes.length)throw new Error('Resize requires "scales" input size to be of axes rank when axes attributes is specified');if(y.length!==0&&y.length!==c.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 y<"u"&&m.length>0&&y.length>I)throw new Error("Resize requires only of scales or sizes to be specified")},Ef=(i,c,h,m)=>`
2480
2480
  // The whole part and the fractional part are calculated separately due to inaccuracy of floating
2481
2481
  // point division. As an example, f32(21) / f32(7) may evaluate to 2.99... instead of 3, causing an
2482
2482
  // offset-by-one error later in floor().
@@ -2489,7 +2489,7 @@ fn calculateOutputIndex(index: u32) -> u32 {
2489
2489
  if (xScale < 1.0 || floor(xScale) != xScale) {
2490
2490
  return ${c}(xResized) / ${c}(xScale);
2491
2491
  } else {
2492
- ${Cf("xResized","lengthOriginal","lengthResized",c)}
2492
+ ${Ef("xResized","lengthOriginal","lengthResized",c)}
2493
2493
  }
2494
2494
  `;case"pytorch_half_pixel":return`if (lengthResized > 1) {
2495
2495
  return (${c}(xResized) + 0.5) / ${c}(xScale) - 0.5;
@@ -2498,7 +2498,7 @@ fn calculateOutputIndex(index: u32) -> u32 {
2498
2498
  }`;case"tf_half_pixel_for_nn":return`return (${c}(xResized) + 0.5) / ${c}(xScale);`;case"align_corners":return`if (lengthResized == 1) {
2499
2499
  return 0.0;
2500
2500
  } else {
2501
- ${Cf("xResized","lengthOriginal - 1","lengthResized - 1",c)}
2501
+ ${Ef("xResized","lengthOriginal - 1","lengthResized - 1",c)}
2502
2502
  }`;case"tf_crop_and_resize":return`if (lengthResized > 1) {
2503
2503
  return ${c}(roiStart) * ${c}(lengthOriginal - 1) +
2504
2504
  (${c}(xResized) * ${c}(roiEnd - roiStart) * ${c}(lengthOriginal - 1)) /
@@ -2567,7 +2567,7 @@ fn calculateOutputIndex(index: u32) -> u32 {
2567
2567
  }
2568
2568
  }
2569
2569
  return true;
2570
- }`,Af=(i,c,h,m)=>i.rank>m?`
2570
+ }`,Cf=(i,c,h,m)=>i.rank>m?`
2571
2571
  ${i.indicesSet("input_indices",c,"channel")};
2572
2572
  ${i.indicesSet("input_indices",h,"batch")};
2573
2573
  `:"",Vy=(i,c,h,m,y)=>{let[S,b,E,A]=h.length===2?[-1,0,1,-1]:[0,2,3,1],I=i.type.value;return`
@@ -2575,7 +2575,7 @@ fn calculateOutputIndex(index: u32) -> u32 {
2575
2575
  var input_indices: ${i.type.indices};
2576
2576
  ${i.indicesSet("input_indices",b,`max(0, min(row, ${h[b]} - 1))`)};
2577
2577
  ${i.indicesSet("input_indices",E,`max(0, min(col, ${h[E]} - 1))`)};
2578
- ${Af(i,A,S,2)}
2578
+ ${Cf(i,A,S,2)}
2579
2579
  return ${i.getByIndices("input_indices")};
2580
2580
  }
2581
2581
 
@@ -2665,7 +2665,7 @@ fn calculateOutputIndex(index: u32) -> u32 {
2665
2665
  ${i.indicesSet("input_indices",b,`max(0, min(depth, ${h[b]} - 1))`)};
2666
2666
  ${i.indicesSet("input_indices",E,`max(0, min(height, ${h[E]} - 1))`)};
2667
2667
  ${i.indicesSet("input_indices",A,`max(0, min(width, ${h[A]} - 1))`)};
2668
- ${Af(i,I,S,3)}
2668
+ ${Cf(i,I,S,3)}
2669
2669
  return ${i.getByIndices("input_indices")};
2670
2670
  }
2671
2671
 
@@ -2797,7 +2797,7 @@ fn calculateOutputIndex(index: u32) -> u32 {
2797
2797
  ${de}(inv_std_dev) * gamma[offset1d + i]
2798
2798
  ${x?"+ beta[offset1d + i]":""};
2799
2799
  }
2800
- }`},V=[{dims:E,dataType:i[0].dataType}];return h>1&&V.push({dims:$,dataType:1}),h>2&&V.push({dims:$,dataType:1}),h>3&&V.push({dims:S,dataType:i[0].dataType}),{name:"SkipLayerNormalization",shaderCache:{hint:`${L};${N};${M};${U}`,inputDependencies:i.map((Y,ae)=>"type")},getShaderSource:j,getRunData:()=>({outputs:V,dispatchGroup:{x:Math.ceil(A/I)},programUniforms:P})}},Xy=(i,c)=>{Jy(i.inputs);let h=[0];i.outputCount>1&&h.push(-3),i.outputCount>2&&h.push(-3),i.outputCount>3&&h.push(3),i.compute(Qy(i.inputs,c,i.outputCount,!1),{outputs:h})}}),Zy,Oo,eT,If,tT,sT,rT,nT,XI=_(()=>{ot(),ht(),jt(),_t(),Zy=(i,c)=>{if(!i||i.length<1)throw new Error("too few inputs");if(c.axes.length!==0){if(c.axes.length!==c.starts.length||c.axes.length!==c.ends.length)throw new Error("axes, starts and ends must have the same length")}else if(c.starts.length!==c.ends.length)throw new Error("starts and ends must have the same length");i.slice(1).forEach((h,m)=>{if(i[m+1].dataType!==6&&i[m+1].dataType!==7)throw new Error(`Input ${m} must be an array of int32 or int64`)})},Oo=(i,c)=>{let h=[];if(i.length>c)if(i[c].dataType===7)i[c].getBigInt64Array().forEach(m=>h.push(Number(m)));else if(i[c].dataType===6)i[c].getInt32Array().forEach(m=>h.push(Number(m)));else throw new Error(`Input ${c} must be an array of int32 or int64`);return h},eT=(i,c)=>{if(i.length>1){let h=Oo(i,1),m=Oo(i,2),y=Oo(i,3);return y.length===0&&(y=[...Array(i[0].dims.length).keys()]),Rt({starts:h,ends:m,axes:y})}else return c},If=(i,c,h,m,y)=>{let S=i;return i<0&&(S+=h[m[c]]),y[c]<0?Math.max(0,Math.min(S,h[m[c]]-1)):Math.max(0,Math.min(S,h[m[c]]))},tT=(i,c,h)=>`fn calculateInputIndices(output_indices: ${c.type.indices}) -> ${i.type.indices} {
2800
+ }`},V=[{dims:E,dataType:i[0].dataType}];return h>1&&V.push({dims:$,dataType:1}),h>2&&V.push({dims:$,dataType:1}),h>3&&V.push({dims:S,dataType:i[0].dataType}),{name:"SkipLayerNormalization",shaderCache:{hint:`${L};${N};${M};${U}`,inputDependencies:i.map((Y,ae)=>"type")},getShaderSource:j,getRunData:()=>({outputs:V,dispatchGroup:{x:Math.ceil(A/I)},programUniforms:P})}},Xy=(i,c)=>{Jy(i.inputs);let h=[0];i.outputCount>1&&h.push(-3),i.outputCount>2&&h.push(-3),i.outputCount>3&&h.push(3),i.compute(Qy(i.inputs,c,i.outputCount,!1),{outputs:h})}}),Zy,Oo,eT,Af,tT,sT,rT,nT,XI=_(()=>{ot(),ht(),jt(),_t(),Zy=(i,c)=>{if(!i||i.length<1)throw new Error("too few inputs");if(c.axes.length!==0){if(c.axes.length!==c.starts.length||c.axes.length!==c.ends.length)throw new Error("axes, starts and ends must have the same length")}else if(c.starts.length!==c.ends.length)throw new Error("starts and ends must have the same length");i.slice(1).forEach((h,m)=>{if(i[m+1].dataType!==6&&i[m+1].dataType!==7)throw new Error(`Input ${m} must be an array of int32 or int64`)})},Oo=(i,c)=>{let h=[];if(i.length>c)if(i[c].dataType===7)i[c].getBigInt64Array().forEach(m=>h.push(Number(m)));else if(i[c].dataType===6)i[c].getInt32Array().forEach(m=>h.push(Number(m)));else throw new Error(`Input ${c} must be an array of int32 or int64`);return h},eT=(i,c)=>{if(i.length>1){let h=Oo(i,1),m=Oo(i,2),y=Oo(i,3);return y.length===0&&(y=[...Array(i[0].dims.length).keys()]),Rt({starts:h,ends:m,axes:y})}else return c},Af=(i,c,h,m,y)=>{let S=i;return i<0&&(S+=h[m[c]]),y[c]<0?Math.max(0,Math.min(S,h[m[c]]-1)):Math.max(0,Math.min(S,h[m[c]]))},tT=(i,c,h)=>`fn calculateInputIndices(output_indices: ${c.type.indices}) -> ${i.type.indices} {
2801
2801
  var input_indices: ${i.type.indices};
2802
2802
  var carry = 0u;
2803
2803
  for (var i = ${h.length-1}; i >= 0; i--) {
@@ -2815,7 +2815,7 @@ fn calculateOutputIndex(index: u32) -> u32 {
2815
2815
  ${i.indicesSet("input_indices","i","input_index")};
2816
2816
  }
2817
2817
  return input_indices;
2818
- }`,sT=(i,c)=>{let h=i[0].dims,m=ie.size(h),y=c.axes.length>0?ie.normalizeAxes(c.axes,h.length):[...Array(h.length).keys()],S=Oo(i,4);S.forEach(L=>L!==0||(()=>{throw new Error("step cannot be 0")})),S.length===0&&(S=Array(y.length).fill(1));let b=c.starts.map((L,P)=>If(L,P,h,y,S)),E=c.ends.map((L,P)=>If(L,P,h,y,S));if(y.length!==b.length||y.length!==E.length)throw new Error("start, ends and axes should have the same number of elements");if(y.length!==h.length)for(let L=0;L<h.length;++L)y.includes(L)||(b.splice(L,0,0),E.splice(L,0,h[L]),S.splice(L,0,1));let A=S.map(L=>Math.sign(L));S.forEach((L,P,j)=>{if(L<0){let V=(E[P]-b[P])/L,Y=b[P],ae=Y+V*S[P];b[P]=ae,E[P]=Y,j[P]=-L}});let I=h.slice(0);y.forEach((L,P)=>{I[L]=Math.ceil((E[L]-b[L])/S[L])});let $={dims:I,dataType:i[0].dataType},x=Je("output",i[0].dataType,I.length),k=he("input",i[0].dataType,i[0].dims.length),N=ie.size(I),M=[{name:"outputSize",type:"u32"},{name:"starts",type:"u32",length:b.length},{name:"signs",type:"i32",length:A.length},{name:"steps",type:"u32",length:S.length}],U=[{type:12,data:N},{type:12,data:b},{type:6,data:A},{type:12,data:S},...Xe(i[0].dims,I)],z=L=>`
2818
+ }`,sT=(i,c)=>{let h=i[0].dims,m=ie.size(h),y=c.axes.length>0?ie.normalizeAxes(c.axes,h.length):[...Array(h.length).keys()],S=Oo(i,4);S.forEach(L=>L!==0||(()=>{throw new Error("step cannot be 0")})),S.length===0&&(S=Array(y.length).fill(1));let b=c.starts.map((L,P)=>Af(L,P,h,y,S)),E=c.ends.map((L,P)=>Af(L,P,h,y,S));if(y.length!==b.length||y.length!==E.length)throw new Error("start, ends and axes should have the same number of elements");if(y.length!==h.length)for(let L=0;L<h.length;++L)y.includes(L)||(b.splice(L,0,0),E.splice(L,0,h[L]),S.splice(L,0,1));let A=S.map(L=>Math.sign(L));S.forEach((L,P,j)=>{if(L<0){let V=(E[P]-b[P])/L,Y=b[P],ae=Y+V*S[P];b[P]=ae,E[P]=Y,j[P]=-L}});let I=h.slice(0);y.forEach((L,P)=>{I[L]=Math.ceil((E[L]-b[L])/S[L])});let $={dims:I,dataType:i[0].dataType},x=Je("output",i[0].dataType,I.length),k=he("input",i[0].dataType,i[0].dims.length),N=ie.size(I),M=[{name:"outputSize",type:"u32"},{name:"starts",type:"u32",length:b.length},{name:"signs",type:"i32",length:A.length},{name:"steps",type:"u32",length:S.length}],U=[{type:12,data:N},{type:12,data:b},{type:6,data:A},{type:12,data:S},...Xe(i[0].dims,I)],z=L=>`
2819
2819
  ${L.registerUniforms(M).declareVariables(k,x)}
2820
2820
  ${tT(k,x,h)}
2821
2821
  ${L.mainStart()}
@@ -2897,7 +2897,7 @@ fn calculateOutputIndex(index: u32) -> u32 {
2897
2897
  value = max(value, ${j}(0.0));
2898
2898
  setValue(row, col, row_stride, value);
2899
2899
  }
2900
- }`,ae=i.compute({name:"Softmax",shaderCache:{hint:`${N};${U}`,inputDependencies:["type"]},getRunData:()=>({outputs:[{dims:$,dataType:A.dataType}],dispatchGroup:{x:k},programUniforms:[{type:6,data:M}]}),getShaderSource:Y},{inputs:[A],outputs:[E?-1:0]})[0];E&&i.compute(ms(ae,I),{inputs:[ae]})},lT=(i,c)=>{iT(i.inputs),aT(i,c)},oT=i=>Rt({axis:i.axis})}),Rf,uT,cT,dT,fT,e1=_(()=>{ot(),ht(),_t(),Rf=i=>Array.from(i.getBigInt64Array(),Number),uT=i=>{if(!i||i.length!==2)throw new Error("Tile requires 2 inputs.");if(i[0].dataType!==1&&i[0].dataType!==10&&i[0].dataType!==6&&i[0].dataType!==12)throw new Error("Tile only support float, float16, int32, and uint32 data types");if(i[1].dataType!==7)throw new Error("Tile `repeats` input should be of int64 data type");if(i[1].dims.length!==1)throw new Error("Tile `repeats` input should be 1-D");if(Rf(i[1]).length!==i[0].dims.length)throw new Error("Tile `repeats` input should have same number of elements as rank of input data tensor")},cT=(i,c)=>{let h=[];for(let m=0;m<i.length;++m)h.push(i[m]*c[m]);return h},dT=(i,c)=>{let h=i[0].dims,m=c??Rf(i[1]),y=cT(h,m),S=ie.size(y),b=i[0].dataType,E=he("input",b,h.length),A=Je("output",b,y.length),I=$=>`
2900
+ }`,ae=i.compute({name:"Softmax",shaderCache:{hint:`${N};${U}`,inputDependencies:["type"]},getRunData:()=>({outputs:[{dims:$,dataType:A.dataType}],dispatchGroup:{x:k},programUniforms:[{type:6,data:M}]}),getShaderSource:Y},{inputs:[A],outputs:[E?-1:0]})[0];E&&i.compute(ms(ae,I),{inputs:[ae]})},lT=(i,c)=>{iT(i.inputs),aT(i,c)},oT=i=>Rt({axis:i.axis})}),If,uT,cT,dT,fT,e1=_(()=>{ot(),ht(),_t(),If=i=>Array.from(i.getBigInt64Array(),Number),uT=i=>{if(!i||i.length!==2)throw new Error("Tile requires 2 inputs.");if(i[0].dataType!==1&&i[0].dataType!==10&&i[0].dataType!==6&&i[0].dataType!==12)throw new Error("Tile only support float, float16, int32, and uint32 data types");if(i[1].dataType!==7)throw new Error("Tile `repeats` input should be of int64 data type");if(i[1].dims.length!==1)throw new Error("Tile `repeats` input should be 1-D");if(If(i[1]).length!==i[0].dims.length)throw new Error("Tile `repeats` input should have same number of elements as rank of input data tensor")},cT=(i,c)=>{let h=[];for(let m=0;m<i.length;++m)h.push(i[m]*c[m]);return h},dT=(i,c)=>{let h=i[0].dims,m=c??If(i[1]),y=cT(h,m),S=ie.size(y),b=i[0].dataType,E=he("input",b,h.length),A=Je("output",b,y.length),I=$=>`
2901
2901
  const inputShape = ${E.indices(...h)};
2902
2902
  ${$.registerUniform("output_size","u32").declareVariables(E,A)}
2903
2903
  ${$.mainStart()}
@@ -2939,10 +2939,10 @@ fn calculateOutputIndex(index: u32) -> u32 {
2939
2939
  ${i.mainStart()}
2940
2940
  ${i.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")}
2941
2941
  ${I}
2942
- }`},_T=i=>{let c=i[1].dims,h=i[2].dims,m=i[0].dims,y=i[1].dataType,S=!(ie.areEqual(c,h)&&ie.areEqual(h,m)),b=c,E=ie.size(c);if(S){let I=bn.calcShape(bn.calcShape(c,h,!1),m,!1);if(!I)throw new Error("Can't perform where op on the given tensors");b=I,E=ie.size(b)}let A=Math.ceil(E/4);return{name:"Where",shaderCache:{inputDependencies:["rank","rank","rank"]},getShaderSource:I=>hT(I,i,b,S,y),getRunData:()=>({outputs:[{dims:b,dataType:y}],dispatchGroup:{x:Math.ceil(E/64/4)},programUniforms:[{type:12,data:A},...Xe(m,c,h,b)]})}},pT=i=>{i.compute(_T(i.inputs))}}),mT,s1=_(()=>{p(),xr(),gI(),vI(),yI(),TI(),SI(),AI(),RI(),$I(),xI(),OI(),DI(),kI(),NI(),MI(),UI(),PI(),LI(),HI(),FI(),BI(),zI(),VI(),qI(),Rv(),jI(),GI(),WI(),KI(),YI(),ha(),JI(),Lv(),QI(),XI(),ZI(),Mv(),e1(),Qs(),Wd(),t1(),mT=new Map([["Abs",[Jp]],["Acos",[Qp]],["Acosh",[Xp]],["Add",[Hm]],["ArgMax",[o,d]],["ArgMin",[e,d]],["Asin",[Zp]],["Asinh",[em]],["Atan",[tm]],["Atanh",[sm]],["Attention",[Es]],["AveragePool",[_y,hy]],["BatchNormalization",[Yu]],["BiasAdd",[Kp]],["BiasSplitGelu",[Um]],["Cast",[nm,rm]],["Ceil",[lm]],["Clip",[am]],["Concat",[Zm,eg]],["Conv",[lf,nf]],["ConvTranspose",[Ig,Eg]],["Cos",[om]],["Cosh",[um]],["CumSum",[$g,xg]],["DepthToSpace",[Ng,Mg]],["DequantizeLinear",[wy,Ey]],["Div",[Fm]],["Einsum",[Bg,zg]],["Elu",[cm,Co]],["Equal",[Bm]],["Erf",[dm]],["Exp",[fm]],["Expand",[Gg]],["FastGelu",[Kg]],["Floor",[hm]],["FusedConv",[lf,nf]],["Gather",[Xg,Qg]],["GatherElements",[uv,ov]],["GatherBlockQuantized",[nv,iv]],["GatherND",[ev,tv]],["Gelu",[_m]],["Gemm",[hv,fv]],["GlobalAveragePool",[my,py]],["GlobalMaxPool",[Ty,yy]],["Greater",[jm]],["GreaterOrEqual",[Wm]],["GridSample",[bv,wv]],["GroupQueryAttention",[zv]],["HardSigmoid",[bm,Sm]],["InstanceNormalization",[jv]],["LayerNormalization",[Kv]],["LeakyRelu",[pm,Co]],["Less",[Gm]],["LessOrEqual",[Km]],["Log",[xm]],["MatMul",[Jv]],["MatMulNBits",[ey,ty]],["MaxPool",[gy,vy]],["Mul",[zm]],["MultiHeadAttention",[Iv,Cv]],["Neg",[gm]],["Not",[mm]],["Pad",[cy]],["Pow",[Vm]],["QuickGelu",[km,Co]],["Range",[Iy]],["Reciprocal",[vm]],["ReduceMin",[$r]],["ReduceMean",[ua]],["ReduceMax",[Ya]],["ReduceSum",[J]],["ReduceProd",[K]],["ReduceL1",[ca]],["ReduceL2",[Ka]],["ReduceLogSum",[fa]],["ReduceLogSumExp",[xl]],["ReduceSumSquare",[da]],["Relu",[ym]],["Resize",[Ky,Yy]],["RotaryEmbedding",[Pv]],["ScatterND",[Oy,xy]],["Sigmoid",[Tm]],["Sin",[wm]],["Sinh",[Em]],["Slice",[rT,nT]],["SkipLayerNormalization",[Xy]],["Split",[kv,Nv]],["Sqrt",[Cm]],["Softmax",[lT,oT]],["Sub",[qm]],["Tan",[Am]],["Tanh",[Im]],["ThresholdedRelu",[$m,Co]],["Tile",[fT]],["Transpose",[za,di]],["Where",[pT]]])}),gT,r1=_(()=>{as(),ur(),_t(),gT=class{constructor(i){this.backend=i,this.repo=new Map,this.attributesBound=!1}getArtifact(i){return this.repo.get(i)}setArtifact(i,c){this.repo.set(i,c)}run(i,c,h,m,y){ft(i.programInfo.name);let S=this.backend.device,b=this.backend.getComputePassEncoder();this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2);let E=[];for(let I of c)E.push({binding:E.length,resource:{buffer:I.buffer}});for(let I of h)E.push({binding:E.length,resource:{buffer:I.buffer}});y&&E.push({binding:E.length,resource:y});let A=S.createBindGroup({layout:i.computePipeline.getBindGroupLayout(0),entries:E,label:i.programInfo.name});if(this.backend.sessionStatus==="capturing"){let I={kernelId:this.backend.currentKernelId,computePipeline:i.computePipeline,bindGroup:A,dispatchGroup:m};this.backend.capturedCommandList.get(this.backend.currentSessionId).push(I)}b.setPipeline(i.computePipeline),b.setBindGroup(0,A),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(),Fe(i.programInfo.name)}dispose(){}build(i,c){ft(i.name);let h=this.backend.device,m=[];[{feature:"shader-f16",extension:"f16"},{feature:"subgroups",extension:"subgroups"}].forEach(I=>{h.features.has(I.feature)&&m.push(`enable ${I.extension};`)});let y=El(c,this.backend.device.limits),S=i.getShaderSource(y),b=`${m.join(`
2942
+ }`},_T=i=>{let c=i[1].dims,h=i[2].dims,m=i[0].dims,y=i[1].dataType,S=!(ie.areEqual(c,h)&&ie.areEqual(h,m)),b=c,E=ie.size(c);if(S){let I=bn.calcShape(bn.calcShape(c,h,!1),m,!1);if(!I)throw new Error("Can't perform where op on the given tensors");b=I,E=ie.size(b)}let A=Math.ceil(E/4);return{name:"Where",shaderCache:{inputDependencies:["rank","rank","rank"]},getShaderSource:I=>hT(I,i,b,S,y),getRunData:()=>({outputs:[{dims:b,dataType:y}],dispatchGroup:{x:Math.ceil(E/64/4)},programUniforms:[{type:12,data:A},...Xe(m,c,h,b)]})}},pT=i=>{i.compute(_T(i.inputs))}}),mT,s1=_(()=>{p(),xr(),gI(),vI(),yI(),TI(),SI(),AI(),RI(),$I(),xI(),OI(),DI(),kI(),NI(),MI(),UI(),PI(),LI(),HI(),FI(),BI(),zI(),VI(),qI(),Rv(),jI(),GI(),WI(),KI(),YI(),ha(),JI(),Lv(),QI(),XI(),ZI(),Mv(),e1(),Qs(),Gd(),t1(),mT=new Map([["Abs",[Jp]],["Acos",[Qp]],["Acosh",[Xp]],["Add",[Hm]],["ArgMax",[o,d]],["ArgMin",[e,d]],["Asin",[Zp]],["Asinh",[em]],["Atan",[tm]],["Atanh",[sm]],["Attention",[Es]],["AveragePool",[_y,hy]],["BatchNormalization",[Yu]],["BiasAdd",[Kp]],["BiasSplitGelu",[Um]],["Cast",[nm,rm]],["Ceil",[lm]],["Clip",[am]],["Concat",[Zm,eg]],["Conv",[af,rf]],["ConvTranspose",[Ig,Eg]],["Cos",[om]],["Cosh",[um]],["CumSum",[$g,xg]],["DepthToSpace",[Ng,Mg]],["DequantizeLinear",[wy,Ey]],["Div",[Fm]],["Einsum",[Bg,zg]],["Elu",[cm,Co]],["Equal",[Bm]],["Erf",[dm]],["Exp",[fm]],["Expand",[Gg]],["FastGelu",[Kg]],["Floor",[hm]],["FusedConv",[af,rf]],["Gather",[Xg,Qg]],["GatherElements",[uv,ov]],["GatherBlockQuantized",[nv,iv]],["GatherND",[ev,tv]],["Gelu",[_m]],["Gemm",[hv,fv]],["GlobalAveragePool",[my,py]],["GlobalMaxPool",[Ty,yy]],["Greater",[jm]],["GreaterOrEqual",[Wm]],["GridSample",[bv,wv]],["GroupQueryAttention",[zv]],["HardSigmoid",[bm,Sm]],["InstanceNormalization",[jv]],["LayerNormalization",[Kv]],["LeakyRelu",[pm,Co]],["Less",[Gm]],["LessOrEqual",[Km]],["Log",[xm]],["MatMul",[Jv]],["MatMulNBits",[ey,ty]],["MaxPool",[gy,vy]],["Mul",[zm]],["MultiHeadAttention",[Iv,Cv]],["Neg",[gm]],["Not",[mm]],["Pad",[cy]],["Pow",[Vm]],["QuickGelu",[km,Co]],["Range",[Iy]],["Reciprocal",[vm]],["ReduceMin",[$r]],["ReduceMean",[ua]],["ReduceMax",[Ya]],["ReduceSum",[J]],["ReduceProd",[K]],["ReduceL1",[ca]],["ReduceL2",[Ka]],["ReduceLogSum",[fa]],["ReduceLogSumExp",[xl]],["ReduceSumSquare",[da]],["Relu",[ym]],["Resize",[Ky,Yy]],["RotaryEmbedding",[Pv]],["ScatterND",[Oy,xy]],["Sigmoid",[Tm]],["Sin",[wm]],["Sinh",[Em]],["Slice",[rT,nT]],["SkipLayerNormalization",[Xy]],["Split",[kv,Nv]],["Sqrt",[Cm]],["Softmax",[lT,oT]],["Sub",[qm]],["Tan",[Am]],["Tanh",[Im]],["ThresholdedRelu",[$m,Co]],["Tile",[fT]],["Transpose",[za,di]],["Where",[pT]]])}),gT,r1=_(()=>{as(),ur(),_t(),gT=class{constructor(i){this.backend=i,this.repo=new Map,this.attributesBound=!1}getArtifact(i){return this.repo.get(i)}setArtifact(i,c){this.repo.set(i,c)}run(i,c,h,m,y){ft(i.programInfo.name);let S=this.backend.device,b=this.backend.getComputePassEncoder();this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2);let E=[];for(let I of c)E.push({binding:E.length,resource:{buffer:I.buffer}});for(let I of h)E.push({binding:E.length,resource:{buffer:I.buffer}});y&&E.push({binding:E.length,resource:y});let A=S.createBindGroup({layout:i.computePipeline.getBindGroupLayout(0),entries:E,label:i.programInfo.name});if(this.backend.sessionStatus==="capturing"){let I={kernelId:this.backend.currentKernelId,computePipeline:i.computePipeline,bindGroup:A,dispatchGroup:m};this.backend.capturedCommandList.get(this.backend.currentSessionId).push(I)}b.setPipeline(i.computePipeline),b.setBindGroup(0,A),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(),Fe(i.programInfo.name)}dispose(){}build(i,c){ft(i.name);let h=this.backend.device,m=[];[{feature:"shader-f16",extension:"f16"},{feature:"subgroups",extension:"subgroups"}].forEach(I=>{h.features.has(I.feature)&&m.push(`enable ${I.extension};`)});let y=El(c,this.backend.device.limits),S=i.getShaderSource(y),b=`${m.join(`
2943
2943
  `)}
2944
2944
  ${y.additionalImplementations}
2945
- ${S}`,E=h.createShaderModule({code:b,label:i.name});bt("verbose",()=>`[WebGPU] ${i.name} shader code: ${b}`);let A=h.createComputePipeline({compute:{module:E,entryPoint:"main"},layout:"auto",label:i.name});return Fe(i.name),{programInfo:i,computePipeline:A,uniformVariablesInfo:y.variablesInfo}}normalizeDispatchGroupSize(i){let c=typeof i=="number"?i:i.x,h=typeof i=="number"?1:i.y||1,m=typeof i=="number"?1:i.z||1,y=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(c<=y&&h<=y&&m<=y)return[c,h,m];let S=c*h*m,b=Math.ceil(Math.sqrt(S));if(b>y){if(b=Math.ceil(Math.cbrt(S)),b>y)throw new Error("Total dispatch size exceeds WebGPU maximum.");return[b,b,b]}else return[b,b,1]}}}),vT={};v(vT,{WebGpuBackend:()=>bT});var yT,TT,ST,bT,n1=_(()=>{as(),ot(),ur(),Tr(),Fa(),s1(),r1(),yT=(i,c)=>{if(c.length!==i.length)throw new Error(`inputDependencies length ${c.length} is not equal to inputTensors length ${i.length}.`);let h=[];for(let m=0;m<i.length;++m){let y=i[m].dataType;switch(c[m]){case"none":{h.push("");break}case"type":{h.push(`${y}`);break}case"rank":{let S=i[m].dims.length;h.push(`${y};${S}`);break}case"dims":{let S=i[m].dims.join(",");h.push(`${y};${S}`);break}default:throw new Error(`unsupported input dependency: ${c[m]}`)}}return h.join("|")},TT=(i,c,h)=>{var y,S;let m=i.name;return(y=i.shaderCache)!=null&&y.hint&&(m+="["+i.shaderCache.hint+"]"),m+=":"+h+`:${yT(c,((S=i.shaderCache)==null?void 0:S.inputDependencies)??new Array(c.length).fill("dims"))}`,m},ST=class{constructor(i){i&&(this.architecture=i.architecture,this.vendor=i.vendor)}isArchitecture(i){return this.architecture===i}isVendor(i){return this.vendor===i}},bT=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 i=this.kernelCustomData.get(this.currentKernelId);return i||(i={},this.kernelCustomData.set(this.currentKernelId,i)),i}async initialize(i,c){this.env=i;let h=[],m={requiredLimits:{maxComputeWorkgroupStorageSize:c.limits.maxComputeWorkgroupStorageSize,maxComputeWorkgroupsPerDimension:c.limits.maxComputeWorkgroupsPerDimension,maxStorageBufferBindingSize:c.limits.maxStorageBufferBindingSize,maxBufferSize:c.limits.maxBufferSize,maxComputeInvocationsPerWorkgroup:c.limits.maxComputeInvocationsPerWorkgroup,maxComputeWorkgroupSizeX:c.limits.maxComputeWorkgroupSizeX,maxComputeWorkgroupSizeY:c.limits.maxComputeWorkgroupSizeY,maxComputeWorkgroupSizeZ:c.limits.maxComputeWorkgroupSizeZ},requiredFeatures:h},y=S=>c.features.has(S)&&h.push(S)&&!0;y("chromium-experimental-timestamp-query-inside-passes")||y("timestamp-query"),y("shader-f16"),y("subgroups"),this.device=await c.requestDevice(m),this.adapterInfo=new ST(c.info||await c.requestAdapterInfo()),this.gpuDataManager=Rn(this),this.programManager=new gT(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,ei(i.logLevel,!!i.debug),this.device.onuncapturederror=S=>{S.error instanceof GPUValidationError&&console.error(`An uncaught WebGPU validation error was raised: ${S.error.message}`)},Object.defineProperty(this.env.webgpu,"device",{value:this.device,writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(this.env.webgpu,"adapter",{value:c,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 i=this.getCommandEncoder(),c={};this.queryType==="at-passes"&&(c.timestampWrites={querySet:this.querySet,beginningOfPassWriteIndex:this.pendingDispatchNumber*2,endOfPassWriteIndex:this.pendingDispatchNumber*2+1}),this.computePassEncoder=i.beginComputePass(c)}return this.computePassEncoder}endComputePass(){this.computePassEncoder&&(this.computePassEncoder.end(),this.computePassEncoder=null)}flush(){if(!this.commandEncoder)return;ft(),this.endComputePass();let i;this.queryType!=="none"&&(this.commandEncoder.resolveQuerySet(this.querySet,0,this.pendingDispatchNumber*2,this.queryResolveBuffer,0),i=this.device.createBuffer({size:this.pendingDispatchNumber*2*8,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),this.pendingQueries.set(i,this.pendingKernels),this.pendingKernels=[],this.commandEncoder.copyBufferToBuffer(this.queryResolveBuffer,0,i,0,this.pendingDispatchNumber*2*8)),this.device.queue.submit([this.commandEncoder.finish()]),this.gpuDataManager.refreshPendingBuffers(),this.commandEncoder=null,this.pendingDispatchNumber=0,this.queryType!=="none"&&i.mapAsync(GPUMapMode.READ).then(()=>{var m;let c=new BigUint64Array(i.getMappedRange()),h=this.pendingQueries.get(i);for(let y=0;y<c.length/2;y++){let S=h[y],b=S.kernelId,E=this.kernels.get(b),A=E.kernelType,I=E.kernelName,$=S.programName,x=S.inputTensorViews,k=S.outputTensorViews,N=c[y*2],M=c[y*2+1];typeof this.queryTimeBase>"u"&&(this.queryTimeBase=N);let U=Number(N-this.queryTimeBase),z=Number(M-this.queryTimeBase);if(!Number.isSafeInteger(U)||!Number.isSafeInteger(z))throw new RangeError("incorrect timestamp range");if((m=this.env.webgpu.profiling)!=null&&m.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:x.map(L=>({dims:L.dims,dataType:Ys(L.dataType)})),outputsMetadata:k.map(L=>({dims:L.dims,dataType:Ys(L.dataType)})),kernelId:b,kernelType:A,kernelName:I,programName:$,startTime:U,endTime:z});else{let L="";x.forEach((j,V)=>{L+=`input[${V}]: [${j.dims}] | ${Ys(j.dataType)}, `});let P="";k.forEach((j,V)=>{P+=`output[${V}]: [${j.dims}] | ${Ys(j.dataType)}, `}),console.log(`[profiling] kernel "${b}|${A}|${I}|${$}" ${L}${P}start time: ${U} ns, execution time: ${z-U} ns`)}rt("GPU",`${$}::${N}::${M}`)}i.unmap(),this.pendingQueries.delete(i)}),Fe()}run(i,c,h,m,y,S){ft(i.name);let b=[];for(let P=0;P<c.length;++P){let j=c[P].data;if(j===0)continue;let V=this.gpuDataManager.get(j);if(!V)throw new Error(`no GPU data for input: ${j}`);b.push(V)}let{outputs:E,dispatchGroup:A,programUniforms:I}=i.getRunData(c),$=h.length===0?E.map((P,j)=>j):h;if($.length!==E.length)throw new Error(`Output size ${$.length} must be equal to ${E.length}.`);let x=[],k=[];for(let P=0;P<E.length;++P){if(!Number.isInteger($[P])||$[P]<-3||$[P]>=S)throw new Error(`Invalid output index: ${$[P]}`);if($[P]===-3)continue;let j=$[P]===-1,V=$[P]===-2,Y=j||V?y(E[P].dataType,E[P].dims):m($[P],E[P].dataType,E[P].dims);if(x.push(Y),Y.data===0)continue;let ae=this.gpuDataManager.get(Y.data);if(!ae)throw new Error(`no GPU data for output: ${Y.data}`);if(j&&this.temporaryData.push(ae),V){let ne=this.kernelPersistentData.get(this.currentKernelId);ne||(ne=[],this.kernelPersistentData.set(this.currentKernelId,ne)),ne.push(ae)}k.push(ae)}if(b.length!==c.length||k.length!==x.length){if(k.length===0)return Fe(i.name),x;throw new Error(`Program ${i.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`)}let N;if(I){let P=0,j=[];I.forEach(ne=>{let de=typeof ne.data=="number"?[ne.data]:ne.data;if(de.length===0)return;let ve=ne.type===10?2:4,Ue,ct;ne.type===10?(ct=de.length>4?16:de.length>2?8:de.length*ve,Ue=de.length>4?16:ve*de.length):(ct=de.length<=2?de.length*ve:16,Ue=16),P=Math.ceil(P/ct)*ct,j.push(P);let st=ne.type===10?8:4;P+=de.length>4?Math.ceil(de.length/st)*Ue:de.length*ve});let V=16;P=Math.ceil(P/V)*V;let Y=new ArrayBuffer(P);I.forEach((ne,de)=>{let ve=j[de],Ue=typeof ne.data=="number"?[ne.data]:ne.data;if(ne.type===6)new Int32Array(Y,ve,Ue.length).set(Ue);else if(ne.type===12)new Uint32Array(Y,ve,Ue.length).set(Ue);else if(ne.type===10)new Uint16Array(Y,ve,Ue.length).set(Ue);else if(ne.type===1)new Float32Array(Y,ve,Ue.length).set(Ue);else throw new Error(`Unsupported uniform type: ${Ys(ne.type)}`)});let ae=this.gpuDataManager.create(P,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(ae.buffer,0,Y,0,P),this.gpuDataManager.release(ae.id),N={offset:0,size:P,buffer:ae.buffer}}let M=this.programManager.normalizeDispatchGroupSize(A),U=M[1]===1&&M[2]===1,z=TT(i,c,U),L=this.programManager.getArtifact(z);if(L||(L=this.programManager.build(i,M),this.programManager.setArtifact(z,L),bt("info",()=>`[artifact] key: ${z}, programName: ${i.name}`)),I&&L.uniformVariablesInfo){if(I.length!==L.uniformVariablesInfo.length)throw new Error(`Uniform variables count mismatch: expect ${L.uniformVariablesInfo.length}, got ${I.length} in program "${L.programInfo.name}".`);for(let P=0;P<I.length;P++){let j=I[P],V=j.type,Y=typeof j.data=="number"?1:j.data.length,[ae,ne]=L.uniformVariablesInfo[P];if(V!==ae||Y!==ne)throw new Error(`Uniform variable ${P} mismatch: expect type ${ae} with size ${ne}, got type ${V} with size ${Y} in program "${L.programInfo.name}".`)}}if(bt("info",()=>`[ProgramManager] run "${i.name}" (key=${z}) with ${M[0]}x${M[1]}x${M[2]}`),this.queryType!=="none"||this.sessionStatus==="capturing"){let P={kernelId:this.currentKernelId,programName:L.programInfo.name,inputTensorViews:c,outputTensorViews:x};this.pendingKernels.push(P),this.sessionStatus==="capturing"&&this.capturedPendingKernels.get(this.currentSessionId).push(P)}return this.programManager.run(L,b,k,M,N),Fe(i.name),x}upload(i,c){this.gpuDataManager.upload(i,c)}memcpy(i,c){this.gpuDataManager.memcpy(i,c)}async download(i,c){await this.gpuDataManager.download(i,c)}alloc(i){return this.gpuDataManager.create(i).id}free(i){return this.gpuDataManager.release(i)}createKernel(i,c,h,m){let y=mT.get(i);if(!y)throw new Error(`kernel not implemented: ${i}`);let S={kernelType:i,kernelName:m,kernelEntry:y[0],attributes:[y[1],h]};this.kernels.set(c,S)}releaseKernel(i){let c=this.kernelPersistentData.get(i);if(c){for(let h of c)this.gpuDataManager.release(h.id);this.kernelPersistentData.delete(i)}this.kernelCustomData.delete(i),this.kernels.delete(i)}computeKernel(i,c,h){let m=this.kernels.get(i);if(!m)throw new Error(`kernel not created: ${i}`);let y=m.kernelType,S=m.kernelName,b=m.kernelEntry,E=m.attributes;if(this.currentKernelId!==null)throw new Error(`kernel "[${y}] ${S}" is not allowed to be called recursively`);this.currentKernelId=i,E[0]&&(E[1]=E[0](E[1]),E[0]=void 0),bt("info",()=>`[WebGPU] Start to run kernel "[${y}] ${S}"...`);let A=this.env.debug;this.temporaryData=[];try{return A&&this.device.pushErrorScope("validation"),b(c,E[1]),0}catch(I){return h.push(Promise.resolve(`[WebGPU] Kernel "[${y}] ${S}" failed. ${I}`)),1}finally{A&&h.push(this.device.popErrorScope().then(I=>I?`GPU validation error for kernel "[${y}] ${S}": ${I.message}`:null));for(let I of this.temporaryData)this.gpuDataManager.release(I.id);this.temporaryData=[],this.currentKernelId=null}}registerBuffer(i,c,h,m){let y=this.sessionExternalDataMapping.get(i);y||(y=new Map,this.sessionExternalDataMapping.set(i,y));let S=y.get(c),b=this.gpuDataManager.registerExternalBuffer(h,m,S);return y.set(c,[b,h]),b}unregisterBuffers(i){let c=this.sessionExternalDataMapping.get(i);c&&(c.forEach(h=>this.gpuDataManager.unregisterExternalBuffer(h[0])),this.sessionExternalDataMapping.delete(i))}getBuffer(i){let c=this.gpuDataManager.get(i);if(!c)throw new Error(`no GPU data for buffer: ${i}`);return c.buffer}createDownloader(i,c,h){return async()=>{let m=await Zr(this,i,c);return cr(m.buffer,h)}}writeTimestamp(i){this.queryType==="inside-passes"&&this.computePassEncoder.writeTimestamp(this.querySet,i)}setQueryType(){var i;this.queryType="none",(((i=this.env.webgpu.profiling)==null?void 0:i.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(){bt("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(){bt("info","captureEnd"),this.flush(),this.sessionStatus="default"}replay(){bt("info","replay"),this.sessionStatus="replaying";let i=this.capturedCommandList.get(this.currentSessionId),c=this.capturedPendingKernels.get(this.currentSessionId),h=i.length;this.pendingKernels=[];for(let m=0;m<h;m++){let y=this.getComputePassEncoder(),S=i[m];this.writeTimestamp(this.pendingDispatchNumber*2),y.setPipeline(S.computePipeline),y.setBindGroup(0,S.bindGroup),y.dispatchWorkgroups(...S.dispatchGroup),this.writeTimestamp(this.pendingDispatchNumber*2+1),this.pendingDispatchNumber++,this.queryType!=="none"&&this.pendingKernels.push(c[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(i){this.unregisterBuffers(i),this.capturedCommandList.has(i)&&this.capturedCommandList.delete(i),this.capturedPendingKernels.has(i)&&this.capturedPendingKernels.delete(i),this.gpuDataManager.onReleaseSession(i)}onRunStart(i){this.currentSessionId=i,this.setQueryType()}}}),wT={};v(wT,{init:()=>CT});var sc,ET,CT,i1=_(()=>{ot(),ur(),ht(),La(),sc=class WT{constructor(c,h,m,y){this.module=c,this.dataType=h,this.data=m,this.dims=y}getFloat32Array(){if(this.dataType!==1)throw new Error("Invalid data type");let c=ie.size(this.dims);return c===0?new Float32Array:new Float32Array(this.module.HEAP8.buffer,this.data,c)}getBigInt64Array(){if(this.dataType!==7)throw new Error("Invalid data type");let c=ie.size(this.dims);return c===0?new BigInt64Array:new BigInt64Array(this.module.HEAP8.buffer,this.data,c)}getInt32Array(){if(this.dataType!==6)throw new Error("Invalid data type");let c=ie.size(this.dims);return c===0?new Int32Array:new Int32Array(this.module.HEAP8.buffer,this.data,c)}getUint16Array(){if(this.dataType!==10&&this.dataType!==4)throw new Error("Invalid data type");let c=ie.size(this.dims);return c===0?new Uint16Array:new Uint16Array(this.module.HEAP8.buffer,this.data,c)}reshape(c){if(ie.size(c)!==ie.size(this.dims))throw new Error("Invalid new shape");return new WT(this.module,this.dataType,this.data,c)}},ET=class{constructor(i,c,h){this.module=i,this.backend=c,this.customDataOffset=0,this.customDataSize=0,this.adapterInfo=c.adapterInfo;let m=i.PTR_SIZE,y=h/i.PTR_SIZE,S=m===4?"i32":"i64";this.opKernelContext=Number(i.getValue(m*y++,S));let b=Number(i.getValue(m*y++,S));this.outputCount=Number(i.getValue(m*y++,S)),this.customDataOffset=Number(i.getValue(m*y++,"*")),this.customDataSize=Number(i.getValue(m*y++,S));let E=[];for(let A=0;A<b;A++){let I=Number(i.getValue(m*y++,S)),$=Number(i.getValue(m*y++,"*")),x=Number(i.getValue(m*y++,S)),k=[];for(let N=0;N<x;N++)k.push(Number(i.getValue(m*y++,S)));E.push(new sc(i,I,$,k))}this.inputs=E}get kernelCustomData(){return this.backend.currentKernelCustomData}get customDataBuffer(){return this.module.HEAPU8.subarray(this.customDataOffset,this.customDataOffset+this.customDataSize)}compute(i,c){var b;let h=((b=c==null?void 0:c.inputs)==null?void 0:b.map(E=>typeof E=="number"?this.inputs[E]:E))??this.inputs,m=(c==null?void 0:c.outputs)??[],y=(E,A,I)=>new sc(this.module,A,this.output(E,I),I),S=(E,A)=>{let I=yr(E,A);if(!I)throw new Error(`Unsupported data type: ${E}`);let $=I>0?this.backend.gpuDataManager.create(I).id:0;return new sc(this.module,E,$,A)};return this.backend.run(i,h,m,y,S,this.outputCount)}output(i,c){let h=this.module.stackSave();try{let m=this.module.PTR_SIZE,y=m===4?"i32":"i64",S=this.module.stackAlloc((1+c.length)*m);this.module.setValue(S,c.length,y);for(let b=0;b<c.length;b++)this.module.setValue(S+m*(b+1),c[b],y);return this.module._JsepOutput(this.opKernelContext,i,S)}catch(m){throw new Error(`Failed to generate kernel's output[${i}] with dims [${c}]. If you are running with pre-allocated output, please make sure the output type/dims are correct. Error: ${m}`)}finally{this.module.stackRestore(h)}}},CT=async(i,c,h,m)=>{let y=c.jsepInit;if(!y)throw new Error("Failed to initialize JSEP. The WebAssembly module is not built with JSEP support.");if(i==="webgpu"){let S=(n1(),R(vT)).WebGpuBackend,b=new S;await b.initialize(h,m),y("webgpu",[b,E=>b.alloc(Number(E)),E=>b.free(E),(E,A,I,$=!1)=>{if($)bt("verbose",()=>`[WebGPU] jsepCopyGpuToGpu: src=${Number(E)}, dst=${Number(A)}, size=${Number(I)}`),b.memcpy(Number(E),Number(A));else{bt("verbose",()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${Number(E)}, gpuDataId=${Number(A)}, size=${Number(I)}`);let x=c.HEAPU8.subarray(Number(E>>>0),Number(E>>>0)+Number(I));b.upload(Number(A),x)}},async(E,A,I)=>{bt("verbose",()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${E}, dataOffset=${A}, size=${I}`),await b.download(Number(E),()=>c.HEAPU8.subarray(Number(A)>>>0,Number(A+I)>>>0))},(E,A,I)=>b.createKernel(E,Number(A),I,c.UTF8ToString(c._JsepGetNodeName(Number(A)))),E=>b.releaseKernel(E),(E,A,I,$)=>{bt("verbose",()=>`[WebGPU] jsepRun: sessionHandle=${I}, kernel=${E}, contextDataOffset=${A}`);let x=new ET(c,b,Number(A));return b.computeKernel(Number(E),x,$)},()=>b.captureBegin(),()=>b.captureEnd(),()=>b.replay()])}else{let S=new Cn(h);y("webnn",[S,()=>S.reserveTensorId(),b=>S.releaseTensorId(b),async(b,E,A,I,$)=>S.ensureTensor(b,E,A,I,$),(b,E)=>{S.uploadTensor(b,E)},async(b,E)=>S.downloadTensor(b,E),(b,E)=>S.registerMLContext(b,E),!!h.trace])}}}),AT,$f,xf,_a,IT,Of,rc,Df,kf,Nf,Mf,Uf,Pf,RT=_(()=>{as(),vn(),Da(),ot(),gr(),jr(),Hi(),AT=(i,c)=>{kt()._OrtInit(i,c)!==0&&It("Can't initialize onnxruntime.")},$f=async i=>{AT(i.wasm.numThreads,Yr(i.logLevel))},xf=async(i,c)=>{var m,y;(y=(m=kt()).asyncInit)==null||y.call(m);let h=i.webgpu.adapter;if(c==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");if(h){if(typeof h.limits!="object"||typeof h.features!="object"||typeof h.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let S=i.webgpu.powerPreference;if(S!==void 0&&S!=="low-power"&&S!=="high-performance")throw new Error(`Invalid powerPreference setting: "${S}"`);let b=i.webgpu.forceFallbackAdapter;if(b!==void 0&&typeof b!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${b}"`);if(h=await navigator.gpu.requestAdapter({powerPreference:S,forceFallbackAdapter:b}),!h)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}}if(c==="webnn"&&(typeof navigator>"u"||!navigator.ml))throw new Error("WebNN is not supported in current environment");{let S=(i1(),R(wT)).init;c==="webgpu"&&await S("webgpu",kt(),i,h),c==="webnn"&&await S("webnn",kt(),i)}},_a=new Map,IT=i=>{let c=kt(),h=c.stackSave();try{let m=c.PTR_SIZE,y=c.stackAlloc(2*m);c._OrtGetInputOutputCount(i,y,y+m)!==0&&It("Can't get session input/output count.");let S=m===4?"i32":"i64";return[Number(c.getValue(y,S)),Number(c.getValue(y+m,S))]}finally{c.stackRestore(h)}},Of=(i,c)=>{let h=kt(),m=h.stackSave(),y=0;try{let S=h.PTR_SIZE,b=h.stackAlloc(2*S);h._OrtGetInputOutputMetadata(i,c,b,b+S)!==0&&It("Can't get session input/output metadata.");let E=Number(h.getValue(b,"*"));y=Number(h.getValue(b+S,"*"));let A=h.HEAP32[y/4];if(A===0)return[E,0];let I=h.HEAPU32[y/4+1],$=[];for(let x=0;x<I;x++){let k=Number(h.getValue(y+8+x*S,"*"));$.push(k!==0?h.UTF8ToString(k):Number(h.getValue(y+8+(x+I)*S,"*")))}return[E,A,$]}finally{h.stackRestore(m),y!==0&&h._OrtFree(y)}},rc=i=>{let c=kt(),h=c._malloc(i.byteLength);if(h===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${i.byteLength}.`);return c.HEAPU8.set(i,h),[h,i.byteLength]},Df=async(i,c)=>{var x,k,N,M;let h,m,y=kt();Array.isArray(i)?[h,m]=i:i.buffer===y.HEAPU8.buffer?[h,m]=[i.byteOffset,i.byteLength]:[h,m]=rc(i);let S=0,b=0,E=0,A=[],I=[],$=[];try{if([b,A]=await Wr(c),(c==null?void 0:c.externalData)&&y.mountExternalData){let de=[];for(let ve of c.externalData){let Ue=typeof ve=="string"?ve:ve.path;de.push(Zn(typeof ve=="string"?ve:ve.data).then(ct=>{y.mountExternalData(Ue,ct)}))}await Promise.all(de)}for(let de of(c==null?void 0:c.executionProviders)??[])if((typeof de=="string"?de:de.name)==="webnn"){if(y.shouldTransferToMLTensor=!1,typeof de!="string"){let ve=de,Ue=ve==null?void 0:ve.context,ct=ve==null?void 0:ve.gpuDevice,st=ve==null?void 0:ve.deviceType,ut=ve==null?void 0:ve.powerPreference;Ue?y.currentContext=Ue:ct?y.currentContext=await y.webnnCreateMLContext(ct):y.currentContext=await y.webnnCreateMLContext({deviceType:st,powerPreference:ut})}else y.currentContext=await y.webnnCreateMLContext();break}S=await y._OrtCreateSession(h,m,b),(x=y.webgpuOnCreateSession)==null||x.call(y,S),S===0&&It("Can't create a session."),(k=y.jsepOnCreateSession)==null||k.call(y),y.currentContext&&(y.webnnRegisterMLContext(S,y.currentContext),y.currentContext=void 0,y.shouldTransferToMLTensor=!0);let[U,z]=IT(S),L=!!(c!=null&&c.enableGraphCapture),P=[],j=[],V=[],Y=[],ae=[];for(let de=0;de<U;de++){let[ve,Ue,ct]=Of(S,de);ve===0&&It("Can't get an input name."),I.push(ve);let st=y.UTF8ToString(ve);P.push(st),V.push(Ue===0?{name:st,isTensor:!1}:{name:st,isTensor:!0,type:Ys(Ue),shape:ct})}for(let de=0;de<z;de++){let[ve,Ue,ct]=Of(S,de+U);ve===0&&It("Can't get an output name."),$.push(ve);let st=y.UTF8ToString(ve);j.push(st),Y.push(Ue===0?{name:st,isTensor:!1}:{name:st,isTensor:!0,type:Ys(Ue),shape:ct});{if(L&&(c==null?void 0:c.preferredOutputLocation)===void 0){ae.push("gpu-buffer");continue}let ut=typeof(c==null?void 0:c.preferredOutputLocation)=="string"?c.preferredOutputLocation:((N=c==null?void 0:c.preferredOutputLocation)==null?void 0:N[st])??"cpu",$t=y.webnnIsGraphOutput;if(ut==="cpu"&&$t&&$t(S,st)){ae.push("ml-tensor-cpu-output");continue}if(ut!=="cpu"&&ut!=="cpu-pinned"&&ut!=="gpu-buffer"&&ut!=="ml-tensor")throw new Error(`Not supported preferred output location: ${ut}.`);if(L&&ut!=="gpu-buffer")throw new Error(`Not supported preferred output location: ${ut}. Only 'gpu-buffer' location is supported when enableGraphCapture is true.`);ae.push(ut)}}let ne=null;return ae.some(de=>de==="gpu-buffer"||de==="ml-tensor"||de==="ml-tensor-cpu-output")&&(E=y._OrtCreateBinding(S),E===0&&It("Can't create IO binding."),ne={handle:E,outputPreferredLocations:ae,outputPreferredLocationsEncoded:ae.map(de=>de==="ml-tensor-cpu-output"?"ml-tensor":de).map(de=>Xn(de))}),_a.set(S,[S,I,$,ne,L,!1]),[S,P,j,V,Y]}catch(U){throw I.forEach(z=>y._OrtFree(z)),$.forEach(z=>y._OrtFree(z)),E!==0&&y._OrtReleaseBinding(E)!==0&&It("Can't release IO binding."),S!==0&&y._OrtReleaseSession(S)!==0&&It("Can't release session."),U}finally{y._free(h),b!==0&&y._OrtReleaseSessionOptions(b)!==0&&It("Can't release session options."),A.forEach(U=>y._free(U)),(M=y.unmountExternalData)==null||M.call(y)}},kf=i=>{var A,I,$;let c=kt(),h=_a.get(i);if(!h)throw new Error(`cannot release session. invalid session id: ${i}`);let[m,y,S,b,E]=h;b&&(E&&c._OrtClearBoundOutputs(b.handle)!==0&&It("Can't clear bound outputs."),c._OrtReleaseBinding(b.handle)!==0&&It("Can't release IO binding.")),(A=c.jsepOnReleaseSession)==null||A.call(c,i),(I=c.webnnOnReleaseSession)==null||I.call(c,i),($=c.webgpuOnReleaseSession)==null||$.call(c,i),y.forEach(x=>c._OrtFree(x)),S.forEach(x=>c._OrtFree(x)),c._OrtReleaseSession(m)!==0&&It("Can't release session."),_a.delete(i)},Nf=async(i,c,h,m,y,S,b=!1)=>{if(!i){c.push(0);return}let E=kt(),A=E.PTR_SIZE,I=i[0],$=i[1],x=i[3],k=x,N,M;if(I==="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 ${S} when enableGraphCapture is true.`);if(x==="gpu-buffer"){let L=i[2].gpuBuffer;M=yr(vr(I),$);{let P=E.jsepRegisterBuffer;if(!P)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');N=P(m,S,L,M)}}else if(x==="ml-tensor"){let L=i[2].mlTensor;M=yr(vr(I),$);let P=E.webnnRegisterMLTensor;if(!P)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');N=P(m,L,vr(I),$)}else{let L=i[2];if(Array.isArray(L)){M=A*L.length,N=E._malloc(M),h.push(N);for(let P=0;P<L.length;P++){if(typeof L[P]!="string")throw new TypeError(`tensor data at index ${P} is not a string`);E.setValue(N+P*A,bs(L[P],h),"*")}}else{let P=E.webnnIsGraphInput,j=E.webnnIsGraphOutput;if(I!=="string"&&P&&j){let V=E.UTF8ToString(y);if(P(m,V)||j(m,V)){let Y=vr(I);M=yr(Y,$),k="ml-tensor";let ae=E.webnnCreateTemporaryTensor,ne=E.webnnUploadTensor;if(!ae||!ne)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');let de=await ae(m,Y,$);ne(de,new Uint8Array(L.buffer,L.byteOffset,L.byteLength)),N=de}else M=L.byteLength,N=E._malloc(M),h.push(N),E.HEAPU8.set(new Uint8Array(L.buffer,L.byteOffset,M),N)}else M=L.byteLength,N=E._malloc(M),h.push(N),E.HEAPU8.set(new Uint8Array(L.buffer,L.byteOffset,M),N)}}let U=E.stackSave(),z=E.stackAlloc(4*$.length);try{$.forEach((P,j)=>E.setValue(z+j*A,P,A===4?"i32":"i64"));let L=E._OrtCreateTensor(vr(I),N,M,z,$.length,Xn(k));L===0&&It(`Can't create tensor for input/output. session=${m}, index=${S}.`),c.push(L)}finally{E.stackRestore(U)}},Mf=async(i,c,h,m,y,S)=>{var ct,st,ut,$t;let b=kt(),E=b.PTR_SIZE,A=_a.get(i);if(!A)throw new Error(`cannot run inference. invalid session id: ${i}`);let I=A[0],$=A[1],x=A[2],k=A[3],N=A[4],M=A[5],U=c.length,z=m.length,L=0,P=[],j=[],V=[],Y=[],ae=b.stackSave(),ne=b.stackAlloc(U*E),de=b.stackAlloc(U*E),ve=b.stackAlloc(z*E),Ue=b.stackAlloc(z*E);try{[L,P]=gn(S),He("wasm prepareInputOutputTensor");for(let it=0;it<U;it++)await Nf(h[it],j,Y,i,$[c[it]],c[it],N);for(let it=0;it<z;it++)await Nf(y[it],V,Y,i,x[m[it]],U+m[it],N);qe("wasm prepareInputOutputTensor");for(let it=0;it<U;it++)b.setValue(ne+it*E,j[it],"*"),b.setValue(de+it*E,$[c[it]],"*");for(let it=0;it<z;it++)b.setValue(ve+it*E,V[it],"*"),b.setValue(Ue+it*E,x[m[it]],"*");if(k&&!M){let{handle:it,outputPreferredLocations:pt,outputPreferredLocationsEncoded:Fs}=k;if($.length!==U)throw new Error(`input count from feeds (${U}) is expected to be always equal to model's input count (${$.length}).`);He("wasm bindInputsOutputs");for(let Se=0;Se<U;Se++){let Be=c[Se];await b._OrtBindInput(it,$[Be],j[Se])!==0&&It(`Can't bind input[${Se}] for session=${i}.`)}for(let Se=0;Se<z;Se++){let Be=m[Se];(ct=y[Se])!=null&&ct[3]?b._OrtBindOutput(it,x[Be],V[Se],0)!==0&&It(`Can't bind pre-allocated output[${Se}] for session=${i}.`):b._OrtBindOutput(it,x[Be],0,Fs[Be])!==0&&It(`Can't bind output[${Se}] to ${pt[Se]} for session=${i}.`)}qe("wasm bindInputsOutputs"),_a.set(i,[I,$,x,k,N,!0])}(st=b.jsepOnRunStart)==null||st.call(b,I),(ut=b.webnnOnRunStart)==null||ut.call(b,I);let Tt;k?Tt=await b._OrtRunWithBinding(I,k.handle,z,ve,L):Tt=await b._OrtRun(I,de,ne,U,Ue,z,ve,L),Tt!==0&&It("failed to call OrtRun().");let at=[],St=[];He("wasm ProcessOutputTensor");for(let it=0;it<z;it++){let pt=Number(b.getValue(ve+it*E,"*"));if(pt===V[it]){at.push(y[it]);continue}let Fs=b.stackSave(),Se=b.stackAlloc(4*E),Be=!1,lt,wt=0;try{b._OrtGetTensorData(pt,Se,Se+E,Se+2*E,Se+3*E)!==0&&It(`Can't access output tensor data on index ${it}.`);let Sr=E===4?"i32":"i64",Dl=Number(b.getValue(Se,Sr));wt=b.getValue(Se+E,"*");let VT=b.getValue(Se+E*2,"*"),c1=Number(b.getValue(Se+E*3,Sr)),ma=[];for(let As=0;As<c1;As++)ma.push(Number(b.getValue(VT+As*E,Sr)));b._OrtFree(VT)!==0&&It("Can't free memory for tensor dims.");let ga=ma.reduce((As,fs)=>As*fs,1);lt=Ys(Dl);let No=k==null?void 0:k.outputPreferredLocations[m[it]];if(lt==="string"){if(No==="gpu-buffer"||No==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let As=[];for(let fs=0;fs<ga;fs++){let vi=b.getValue(wt+fs*E,"*"),d1=b.getValue(wt+(fs+1)*E,"*"),f1=fs===ga-1?void 0:d1-vi;As.push(b.UTF8ToString(vi,f1))}at.push([lt,ma,As,"cpu"])}else if(No==="gpu-buffer"&&ga>0){let As=b.jsepGetBuffer;if(!As)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let fs=As(wt),vi=yr(Dl,ga);if(vi===void 0||!Jn(lt))throw new Error(`Unsupported data type: ${lt}`);Be=!0,at.push([lt,ma,{gpuBuffer:fs,download:b.jsepCreateDownloader(fs,vi,lt),dispose:()=>{b._OrtReleaseTensor(pt)!==0&&It("Can't release tensor.")}},"gpu-buffer"])}else if(No==="ml-tensor"&&ga>0){let As=b.webnnEnsureTensor,fs=b.webnnIsGraphInputOutputTypeSupported;if(!As||!fs)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(yr(Dl,ga)===void 0||!Qn(lt))throw new Error(`Unsupported data type: ${lt}`);if(!fs(i,lt,!1))throw new Error(`preferredLocation "ml-tensor" for ${lt} output is not supported by current WebNN Context.`);let vi=await As(i,wt,Dl,ma,!1);Be=!0,at.push([lt,ma,{mlTensor:vi,download:b.webnnCreateMLTensorDownloader(wt,lt),dispose:()=>{b.webnnReleaseTensorId(wt),b._OrtReleaseTensor(pt)}},"ml-tensor"])}else if(No==="ml-tensor-cpu-output"&&ga>0){let As=b.webnnCreateMLTensorDownloader(wt,lt)(),fs=at.length;Be=!0,St.push((async()=>{let vi=[fs,await As];return b.webnnReleaseTensorId(wt),b._OrtReleaseTensor(pt),vi})()),at.push([lt,ma,[],"cpu"])}else{let As=Kr(lt),fs=new As(ga);new Uint8Array(fs.buffer,fs.byteOffset,fs.byteLength).set(b.HEAPU8.subarray(wt,wt+fs.byteLength)),at.push([lt,ma,fs,"cpu"])}}finally{b.stackRestore(Fs),lt==="string"&&wt&&b._free(wt),Be||b._OrtReleaseTensor(pt)}}k&&!N&&(b._OrtClearBoundOutputs(k.handle)!==0&&It("Can't clear bound outputs."),_a.set(i,[I,$,x,k,N,!1]));for(let[it,pt]of await Promise.all(St))at[it][2]=pt;return qe("wasm ProcessOutputTensor"),at}finally{($t=b.webnnOnRunEnd)==null||$t.call(b,I),b.stackRestore(ae),j.forEach(Tt=>b._OrtReleaseTensor(Tt)),V.forEach(Tt=>b._OrtReleaseTensor(Tt)),Y.forEach(Tt=>b._free(Tt)),L!==0&&b._OrtReleaseRunOptions(L),P.forEach(Tt=>b._free(Tt))}},Uf=i=>{let c=kt(),h=_a.get(i);if(!h)throw new Error("invalid session id");let m=h[0],y=c._OrtEndProfiling(m);y===0&&It("Can't get an profile file name."),c._OrtFree(y)},Pf=i=>{let c=[];for(let h of i){let m=h[2];!Array.isArray(m)&&"buffer"in m&&c.push(m.buffer)}return c}}),pa,fr,Ol,Do,ko,nc,Lf,ic,sl,rl,$T,xT,OT,DT,kT,NT,MT,UT,PT=_(()=>{as(),RT(),gr(),Yn(),pa=()=>!!Z.wasm.proxy&&typeof document<"u",Ol=!1,Do=!1,ko=!1,ic=new Map,sl=(i,c)=>{let h=ic.get(i);h?h.push(c):ic.set(i,[c])},rl=()=>{if(Ol||!Do||ko||!fr)throw new Error("worker not ready")},$T=i=>{switch(i.data.type){case"init-wasm":Ol=!1,i.data.err?(ko=!0,Lf[1](i.data.err)):(Do=!0,Lf[0]()),nc&&(URL.revokeObjectURL(nc),nc=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let c=ic.get(i.data.type);i.data.err?c.shift()[1](i.data.err):c.shift()[0](i.data.out);break}}},xT=async()=>{if(!Do){if(Ol)throw new Error("multiple calls to 'initWasm()' detected.");if(ko)throw new Error("previous call to 'initWasm()' failed.");if(Ol=!0,pa())return new Promise((i,c)=>{fr==null||fr.terminate(),Mi().then(([h,m])=>{try{fr=m,fr.onerror=S=>c(S),fr.onmessage=$T,Lf=[i,c];let y={type:"init-wasm",in:Z};if(!y.in.wasm.wasmPaths&&h){let S=qn();S&&(y.in.wasm.wasmPaths=S)}fr.postMessage(y),nc=h}catch(y){c(y)}},c)});try{await Vr(Z.wasm),await $f(Z),Do=!0}catch(i){throw ko=!0,i}finally{Ol=!1}}},OT=async i=>{if(pa())return rl(),new Promise((c,h)=>{sl("init-ep",[c,h]);let m={type:"init-ep",in:{epName:i,env:Z}};fr.postMessage(m)});await xf(Z,i)},DT=async i=>pa()?(rl(),new Promise((c,h)=>{sl("copy-from",[c,h]);let m={type:"copy-from",in:{buffer:i}};fr.postMessage(m,[i.buffer])})):rc(i),kT=async(i,c)=>{if(pa()){if(c!=null&&c.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return rl(),new Promise((h,m)=>{sl("create",[h,m]);let y={type:"create",in:{model:i,options:{...c}}},S=[];i instanceof Uint8Array&&S.push(i.buffer),fr.postMessage(y,S)})}else return Df(i,c)},NT=async i=>{if(pa())return rl(),new Promise((c,h)=>{sl("release",[c,h]);let m={type:"release",in:i};fr.postMessage(m)});kf(i)},MT=async(i,c,h,m,y,S)=>{if(pa()){if(h.some(b=>b[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(y.some(b=>b))throw new Error("pre-allocated output tensor is not supported for proxy.");return rl(),new Promise((b,E)=>{sl("run",[b,E]);let A=h,I={type:"run",in:{sessionId:i,inputIndices:c,inputs:A,outputIndices:m,options:S}};fr.postMessage(I,Pf(A))})}else return Mf(i,c,h,m,y,S)},UT=async i=>{if(pa())return rl(),new Promise((c,h)=>{sl("end-profiling",[c,h]);let m={type:"end-profiling",in:i};fr.postMessage(m)});Uf(i)}}),Hf,LT,HT,a1=_(()=>{as(),PT(),ot(),Pr(),Hi(),Hf=(i,c)=>{switch(i.location){case"cpu":return[i.type,i.dims,i.data,"cpu"];case"gpu-buffer":return[i.type,i.dims,{gpuBuffer:i.gpuBuffer},"gpu-buffer"];case"ml-tensor":return[i.type,i.dims,{mlTensor:i.mlTensor},"ml-tensor"];default:throw new Error(`invalid data location: ${i.location} for ${c()}`)}},LT=i=>{switch(i[3]){case"cpu":return new Mt(i[0],i[2],i[1]);case"gpu-buffer":{let c=i[0];if(!Jn(c))throw new Error(`not supported data type: ${c} for deserializing GPU tensor`);let{gpuBuffer:h,download:m,dispose:y}=i[2];return Mt.fromGpuBuffer(h,{dataType:c,dims:i[1],download:m,dispose:y})}case"ml-tensor":{let c=i[0];if(!Qn(c))throw new Error(`not supported data type: ${c} for deserializing MLTensor tensor`);let{mlTensor:h,download:m,dispose:y}=i[2];return Mt.fromMLTensor(h,{dataType:c,dims:i[1],download:m,dispose:y})}default:throw new Error(`invalid data location: ${i[3]}`)}},HT=class{async fetchModelAndCopyToWasmMemory(i){return DT(await Zn(i))}async loadModel(i,c){ft();let h;typeof i=="string"?h=await this.fetchModelAndCopyToWasmMemory(i):h=i,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await kT(h,c),Fe()}async dispose(){return NT(this.sessionId)}async run(i,c,h){ft();let m=[],y=[];Object.entries(i).forEach(x=>{let k=x[0],N=x[1],M=this.inputNames.indexOf(k);if(M===-1)throw new Error(`invalid input '${k}'`);m.push(N),y.push(M)});let S=[],b=[];Object.entries(c).forEach(x=>{let k=x[0],N=x[1],M=this.outputNames.indexOf(k);if(M===-1)throw new Error(`invalid output '${k}'`);S.push(N),b.push(M)});let E=m.map((x,k)=>Hf(x,()=>`input "${this.inputNames[y[k]]}"`)),A=S.map((x,k)=>x?Hf(x,()=>`output "${this.outputNames[b[k]]}"`):null),I=await MT(this.sessionId,y,E,b,A,h),$={};for(let x=0;x<I.length;x++)$[this.outputNames[b[x]]]=S[x]??LT(I[x]);return Fe(),$}startProfiling(){}endProfiling(){UT(this.sessionId)}}}),FT={};v(FT,{OnnxruntimeWebAssemblyBackend:()=>Bf,initializeFlags:()=>Ff,wasmBackend:()=>BT});var Ff,Bf,BT,l1=_(()=>{as(),PT(),a1(),Ff=()=>{(typeof Z.wasm.initTimeout!="number"||Z.wasm.initTimeout<0)&&(Z.wasm.initTimeout=0);let i=Z.wasm.simd;if(typeof i!="boolean"&&i!==void 0&&i!=="fixed"&&i!=="relaxed"&&(console.warn(`Property "env.wasm.simd" is set to unknown value "${i}". Reset it to \`false\` and ignore SIMD feature checking.`),Z.wasm.simd=!1),typeof Z.wasm.proxy!="boolean"&&(Z.wasm.proxy=!1),typeof Z.wasm.trace!="boolean"&&(Z.wasm.trace=!1),typeof Z.wasm.numThreads!="number"||!Number.isInteger(Z.wasm.numThreads)||Z.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)Z.wasm.numThreads=1;else{let c=typeof navigator>"u"?g("node:os").cpus().length:navigator.hardwareConcurrency;Z.wasm.numThreads=Math.min(4,Math.ceil((c||1)/2))}},Bf=class{async init(i){Ff(),await xT(),await OT(i)}async createInferenceSessionHandler(i,c){let h=new HT;return await h.loadModel(i,c),h}},BT=new Bf}),zT={};v(zT,{InferenceSession:()=>Ut,TRACE:()=>rt,TRACE_EVENT_BEGIN:()=>He,TRACE_EVENT_END:()=>qe,TRACE_FUNC_BEGIN:()=>ft,TRACE_FUNC_END:()=>Fe,Tensor:()=>Mt,default:()=>u1,env:()=>Z,registerBackend:()=>F}),as(),as(),as();var o1="1.23.0",u1=pr;{let i=(l1(),R(FT)).wasmBackend;F("webgpu",i,5),F("webnn",i,5),F("cpu",i,10),F("wasm",i,10)}return Object.defineProperty(Z.versions,"web",{value:o1,enumerable:!0}),R(zT)})();/**
2945
+ ${S}`,E=h.createShaderModule({code:b,label:i.name});bt("verbose",()=>`[WebGPU] ${i.name} shader code: ${b}`);let A=h.createComputePipeline({compute:{module:E,entryPoint:"main"},layout:"auto",label:i.name});return Fe(i.name),{programInfo:i,computePipeline:A,uniformVariablesInfo:y.variablesInfo}}normalizeDispatchGroupSize(i){let c=typeof i=="number"?i:i.x,h=typeof i=="number"?1:i.y||1,m=typeof i=="number"?1:i.z||1,y=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(c<=y&&h<=y&&m<=y)return[c,h,m];let S=c*h*m,b=Math.ceil(Math.sqrt(S));if(b>y){if(b=Math.ceil(Math.cbrt(S)),b>y)throw new Error("Total dispatch size exceeds WebGPU maximum.");return[b,b,b]}else return[b,b,1]}}}),vT={};v(vT,{WebGpuBackend:()=>bT});var yT,TT,ST,bT,n1=_(()=>{as(),ot(),ur(),Tr(),Fa(),s1(),r1(),yT=(i,c)=>{if(c.length!==i.length)throw new Error(`inputDependencies length ${c.length} is not equal to inputTensors length ${i.length}.`);let h=[];for(let m=0;m<i.length;++m){let y=i[m].dataType;switch(c[m]){case"none":{h.push("");break}case"type":{h.push(`${y}`);break}case"rank":{let S=i[m].dims.length;h.push(`${y};${S}`);break}case"dims":{let S=i[m].dims.join(",");h.push(`${y};${S}`);break}default:throw new Error(`unsupported input dependency: ${c[m]}`)}}return h.join("|")},TT=(i,c,h)=>{var y,S;let m=i.name;return(y=i.shaderCache)!=null&&y.hint&&(m+="["+i.shaderCache.hint+"]"),m+=":"+h+`:${yT(c,((S=i.shaderCache)==null?void 0:S.inputDependencies)??new Array(c.length).fill("dims"))}`,m},ST=class{constructor(i){i&&(this.architecture=i.architecture,this.vendor=i.vendor)}isArchitecture(i){return this.architecture===i}isVendor(i){return this.vendor===i}},bT=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 i=this.kernelCustomData.get(this.currentKernelId);return i||(i={},this.kernelCustomData.set(this.currentKernelId,i)),i}async initialize(i,c){this.env=i;let h=[],m={requiredLimits:{maxComputeWorkgroupStorageSize:c.limits.maxComputeWorkgroupStorageSize,maxComputeWorkgroupsPerDimension:c.limits.maxComputeWorkgroupsPerDimension,maxStorageBufferBindingSize:c.limits.maxStorageBufferBindingSize,maxBufferSize:c.limits.maxBufferSize,maxComputeInvocationsPerWorkgroup:c.limits.maxComputeInvocationsPerWorkgroup,maxComputeWorkgroupSizeX:c.limits.maxComputeWorkgroupSizeX,maxComputeWorkgroupSizeY:c.limits.maxComputeWorkgroupSizeY,maxComputeWorkgroupSizeZ:c.limits.maxComputeWorkgroupSizeZ},requiredFeatures:h},y=S=>c.features.has(S)&&h.push(S)&&!0;y("chromium-experimental-timestamp-query-inside-passes")||y("timestamp-query"),y("shader-f16"),y("subgroups"),this.device=await c.requestDevice(m),this.adapterInfo=new ST(c.info||await c.requestAdapterInfo()),this.gpuDataManager=Rn(this),this.programManager=new gT(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,ei(i.logLevel,!!i.debug),this.device.onuncapturederror=S=>{S.error instanceof GPUValidationError&&console.error(`An uncaught WebGPU validation error was raised: ${S.error.message}`)},Object.defineProperty(this.env.webgpu,"device",{value:this.device,writable:!1,enumerable:!0,configurable:!1}),Object.defineProperty(this.env.webgpu,"adapter",{value:c,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 i=this.getCommandEncoder(),c={};this.queryType==="at-passes"&&(c.timestampWrites={querySet:this.querySet,beginningOfPassWriteIndex:this.pendingDispatchNumber*2,endOfPassWriteIndex:this.pendingDispatchNumber*2+1}),this.computePassEncoder=i.beginComputePass(c)}return this.computePassEncoder}endComputePass(){this.computePassEncoder&&(this.computePassEncoder.end(),this.computePassEncoder=null)}flush(){if(!this.commandEncoder)return;ft(),this.endComputePass();let i;this.queryType!=="none"&&(this.commandEncoder.resolveQuerySet(this.querySet,0,this.pendingDispatchNumber*2,this.queryResolveBuffer,0),i=this.device.createBuffer({size:this.pendingDispatchNumber*2*8,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),this.pendingQueries.set(i,this.pendingKernels),this.pendingKernels=[],this.commandEncoder.copyBufferToBuffer(this.queryResolveBuffer,0,i,0,this.pendingDispatchNumber*2*8)),this.device.queue.submit([this.commandEncoder.finish()]),this.gpuDataManager.refreshPendingBuffers(),this.commandEncoder=null,this.pendingDispatchNumber=0,this.queryType!=="none"&&i.mapAsync(GPUMapMode.READ).then(()=>{var m;let c=new BigUint64Array(i.getMappedRange()),h=this.pendingQueries.get(i);for(let y=0;y<c.length/2;y++){let S=h[y],b=S.kernelId,E=this.kernels.get(b),A=E.kernelType,I=E.kernelName,$=S.programName,x=S.inputTensorViews,k=S.outputTensorViews,N=c[y*2],M=c[y*2+1];typeof this.queryTimeBase>"u"&&(this.queryTimeBase=N);let U=Number(N-this.queryTimeBase),z=Number(M-this.queryTimeBase);if(!Number.isSafeInteger(U)||!Number.isSafeInteger(z))throw new RangeError("incorrect timestamp range");if((m=this.env.webgpu.profiling)!=null&&m.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:x.map(L=>({dims:L.dims,dataType:Ys(L.dataType)})),outputsMetadata:k.map(L=>({dims:L.dims,dataType:Ys(L.dataType)})),kernelId:b,kernelType:A,kernelName:I,programName:$,startTime:U,endTime:z});else{let L="";x.forEach((j,V)=>{L+=`input[${V}]: [${j.dims}] | ${Ys(j.dataType)}, `});let P="";k.forEach((j,V)=>{P+=`output[${V}]: [${j.dims}] | ${Ys(j.dataType)}, `}),console.log(`[profiling] kernel "${b}|${A}|${I}|${$}" ${L}${P}start time: ${U} ns, execution time: ${z-U} ns`)}rt("GPU",`${$}::${N}::${M}`)}i.unmap(),this.pendingQueries.delete(i)}),Fe()}run(i,c,h,m,y,S){ft(i.name);let b=[];for(let P=0;P<c.length;++P){let j=c[P].data;if(j===0)continue;let V=this.gpuDataManager.get(j);if(!V)throw new Error(`no GPU data for input: ${j}`);b.push(V)}let{outputs:E,dispatchGroup:A,programUniforms:I}=i.getRunData(c),$=h.length===0?E.map((P,j)=>j):h;if($.length!==E.length)throw new Error(`Output size ${$.length} must be equal to ${E.length}.`);let x=[],k=[];for(let P=0;P<E.length;++P){if(!Number.isInteger($[P])||$[P]<-3||$[P]>=S)throw new Error(`Invalid output index: ${$[P]}`);if($[P]===-3)continue;let j=$[P]===-1,V=$[P]===-2,Y=j||V?y(E[P].dataType,E[P].dims):m($[P],E[P].dataType,E[P].dims);if(x.push(Y),Y.data===0)continue;let ae=this.gpuDataManager.get(Y.data);if(!ae)throw new Error(`no GPU data for output: ${Y.data}`);if(j&&this.temporaryData.push(ae),V){let ne=this.kernelPersistentData.get(this.currentKernelId);ne||(ne=[],this.kernelPersistentData.set(this.currentKernelId,ne)),ne.push(ae)}k.push(ae)}if(b.length!==c.length||k.length!==x.length){if(k.length===0)return Fe(i.name),x;throw new Error(`Program ${i.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`)}let N;if(I){let P=0,j=[];I.forEach(ne=>{let de=typeof ne.data=="number"?[ne.data]:ne.data;if(de.length===0)return;let ve=ne.type===10?2:4,Ue,ct;ne.type===10?(ct=de.length>4?16:de.length>2?8:de.length*ve,Ue=de.length>4?16:ve*de.length):(ct=de.length<=2?de.length*ve:16,Ue=16),P=Math.ceil(P/ct)*ct,j.push(P);let st=ne.type===10?8:4;P+=de.length>4?Math.ceil(de.length/st)*Ue:de.length*ve});let V=16;P=Math.ceil(P/V)*V;let Y=new ArrayBuffer(P);I.forEach((ne,de)=>{let ve=j[de],Ue=typeof ne.data=="number"?[ne.data]:ne.data;if(ne.type===6)new Int32Array(Y,ve,Ue.length).set(Ue);else if(ne.type===12)new Uint32Array(Y,ve,Ue.length).set(Ue);else if(ne.type===10)new Uint16Array(Y,ve,Ue.length).set(Ue);else if(ne.type===1)new Float32Array(Y,ve,Ue.length).set(Ue);else throw new Error(`Unsupported uniform type: ${Ys(ne.type)}`)});let ae=this.gpuDataManager.create(P,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(ae.buffer,0,Y,0,P),this.gpuDataManager.release(ae.id),N={offset:0,size:P,buffer:ae.buffer}}let M=this.programManager.normalizeDispatchGroupSize(A),U=M[1]===1&&M[2]===1,z=TT(i,c,U),L=this.programManager.getArtifact(z);if(L||(L=this.programManager.build(i,M),this.programManager.setArtifact(z,L),bt("info",()=>`[artifact] key: ${z}, programName: ${i.name}`)),I&&L.uniformVariablesInfo){if(I.length!==L.uniformVariablesInfo.length)throw new Error(`Uniform variables count mismatch: expect ${L.uniformVariablesInfo.length}, got ${I.length} in program "${L.programInfo.name}".`);for(let P=0;P<I.length;P++){let j=I[P],V=j.type,Y=typeof j.data=="number"?1:j.data.length,[ae,ne]=L.uniformVariablesInfo[P];if(V!==ae||Y!==ne)throw new Error(`Uniform variable ${P} mismatch: expect type ${ae} with size ${ne}, got type ${V} with size ${Y} in program "${L.programInfo.name}".`)}}if(bt("info",()=>`[ProgramManager] run "${i.name}" (key=${z}) with ${M[0]}x${M[1]}x${M[2]}`),this.queryType!=="none"||this.sessionStatus==="capturing"){let P={kernelId:this.currentKernelId,programName:L.programInfo.name,inputTensorViews:c,outputTensorViews:x};this.pendingKernels.push(P),this.sessionStatus==="capturing"&&this.capturedPendingKernels.get(this.currentSessionId).push(P)}return this.programManager.run(L,b,k,M,N),Fe(i.name),x}upload(i,c){this.gpuDataManager.upload(i,c)}memcpy(i,c){this.gpuDataManager.memcpy(i,c)}async download(i,c){await this.gpuDataManager.download(i,c)}alloc(i){return this.gpuDataManager.create(i).id}free(i){return this.gpuDataManager.release(i)}createKernel(i,c,h,m){let y=mT.get(i);if(!y)throw new Error(`kernel not implemented: ${i}`);let S={kernelType:i,kernelName:m,kernelEntry:y[0],attributes:[y[1],h]};this.kernels.set(c,S)}releaseKernel(i){let c=this.kernelPersistentData.get(i);if(c){for(let h of c)this.gpuDataManager.release(h.id);this.kernelPersistentData.delete(i)}this.kernelCustomData.delete(i),this.kernels.delete(i)}computeKernel(i,c,h){let m=this.kernels.get(i);if(!m)throw new Error(`kernel not created: ${i}`);let y=m.kernelType,S=m.kernelName,b=m.kernelEntry,E=m.attributes;if(this.currentKernelId!==null)throw new Error(`kernel "[${y}] ${S}" is not allowed to be called recursively`);this.currentKernelId=i,E[0]&&(E[1]=E[0](E[1]),E[0]=void 0),bt("info",()=>`[WebGPU] Start to run kernel "[${y}] ${S}"...`);let A=this.env.debug;this.temporaryData=[];try{return A&&this.device.pushErrorScope("validation"),b(c,E[1]),0}catch(I){return h.push(Promise.resolve(`[WebGPU] Kernel "[${y}] ${S}" failed. ${I}`)),1}finally{A&&h.push(this.device.popErrorScope().then(I=>I?`GPU validation error for kernel "[${y}] ${S}": ${I.message}`:null));for(let I of this.temporaryData)this.gpuDataManager.release(I.id);this.temporaryData=[],this.currentKernelId=null}}registerBuffer(i,c,h,m){let y=this.sessionExternalDataMapping.get(i);y||(y=new Map,this.sessionExternalDataMapping.set(i,y));let S=y.get(c),b=this.gpuDataManager.registerExternalBuffer(h,m,S);return y.set(c,[b,h]),b}unregisterBuffers(i){let c=this.sessionExternalDataMapping.get(i);c&&(c.forEach(h=>this.gpuDataManager.unregisterExternalBuffer(h[0])),this.sessionExternalDataMapping.delete(i))}getBuffer(i){let c=this.gpuDataManager.get(i);if(!c)throw new Error(`no GPU data for buffer: ${i}`);return c.buffer}createDownloader(i,c,h){return async()=>{let m=await Zr(this,i,c);return cr(m.buffer,h)}}writeTimestamp(i){this.queryType==="inside-passes"&&this.computePassEncoder.writeTimestamp(this.querySet,i)}setQueryType(){var i;this.queryType="none",(((i=this.env.webgpu.profiling)==null?void 0:i.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(){bt("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(){bt("info","captureEnd"),this.flush(),this.sessionStatus="default"}replay(){bt("info","replay"),this.sessionStatus="replaying";let i=this.capturedCommandList.get(this.currentSessionId),c=this.capturedPendingKernels.get(this.currentSessionId),h=i.length;this.pendingKernels=[];for(let m=0;m<h;m++){let y=this.getComputePassEncoder(),S=i[m];this.writeTimestamp(this.pendingDispatchNumber*2),y.setPipeline(S.computePipeline),y.setBindGroup(0,S.bindGroup),y.dispatchWorkgroups(...S.dispatchGroup),this.writeTimestamp(this.pendingDispatchNumber*2+1),this.pendingDispatchNumber++,this.queryType!=="none"&&this.pendingKernels.push(c[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(i){this.unregisterBuffers(i),this.capturedCommandList.has(i)&&this.capturedCommandList.delete(i),this.capturedPendingKernels.has(i)&&this.capturedPendingKernels.delete(i),this.gpuDataManager.onReleaseSession(i)}onRunStart(i){this.currentSessionId=i,this.setQueryType()}}}),wT={};v(wT,{init:()=>CT});var sc,ET,CT,i1=_(()=>{ot(),ur(),ht(),La(),sc=class WT{constructor(c,h,m,y){this.module=c,this.dataType=h,this.data=m,this.dims=y}getFloat32Array(){if(this.dataType!==1)throw new Error("Invalid data type");let c=ie.size(this.dims);return c===0?new Float32Array:new Float32Array(this.module.HEAP8.buffer,this.data,c)}getBigInt64Array(){if(this.dataType!==7)throw new Error("Invalid data type");let c=ie.size(this.dims);return c===0?new BigInt64Array:new BigInt64Array(this.module.HEAP8.buffer,this.data,c)}getInt32Array(){if(this.dataType!==6)throw new Error("Invalid data type");let c=ie.size(this.dims);return c===0?new Int32Array:new Int32Array(this.module.HEAP8.buffer,this.data,c)}getUint16Array(){if(this.dataType!==10&&this.dataType!==4)throw new Error("Invalid data type");let c=ie.size(this.dims);return c===0?new Uint16Array:new Uint16Array(this.module.HEAP8.buffer,this.data,c)}reshape(c){if(ie.size(c)!==ie.size(this.dims))throw new Error("Invalid new shape");return new WT(this.module,this.dataType,this.data,c)}},ET=class{constructor(i,c,h){this.module=i,this.backend=c,this.customDataOffset=0,this.customDataSize=0,this.adapterInfo=c.adapterInfo;let m=i.PTR_SIZE,y=h/i.PTR_SIZE,S=m===4?"i32":"i64";this.opKernelContext=Number(i.getValue(m*y++,S));let b=Number(i.getValue(m*y++,S));this.outputCount=Number(i.getValue(m*y++,S)),this.customDataOffset=Number(i.getValue(m*y++,"*")),this.customDataSize=Number(i.getValue(m*y++,S));let E=[];for(let A=0;A<b;A++){let I=Number(i.getValue(m*y++,S)),$=Number(i.getValue(m*y++,"*")),x=Number(i.getValue(m*y++,S)),k=[];for(let N=0;N<x;N++)k.push(Number(i.getValue(m*y++,S)));E.push(new sc(i,I,$,k))}this.inputs=E}get kernelCustomData(){return this.backend.currentKernelCustomData}get customDataBuffer(){return this.module.HEAPU8.subarray(this.customDataOffset,this.customDataOffset+this.customDataSize)}compute(i,c){var b;let h=((b=c==null?void 0:c.inputs)==null?void 0:b.map(E=>typeof E=="number"?this.inputs[E]:E))??this.inputs,m=(c==null?void 0:c.outputs)??[],y=(E,A,I)=>new sc(this.module,A,this.output(E,I),I),S=(E,A)=>{let I=yr(E,A);if(!I)throw new Error(`Unsupported data type: ${E}`);let $=I>0?this.backend.gpuDataManager.create(I).id:0;return new sc(this.module,E,$,A)};return this.backend.run(i,h,m,y,S,this.outputCount)}output(i,c){let h=this.module.stackSave();try{let m=this.module.PTR_SIZE,y=m===4?"i32":"i64",S=this.module.stackAlloc((1+c.length)*m);this.module.setValue(S,c.length,y);for(let b=0;b<c.length;b++)this.module.setValue(S+m*(b+1),c[b],y);return this.module._JsepOutput(this.opKernelContext,i,S)}catch(m){throw new Error(`Failed to generate kernel's output[${i}] with dims [${c}]. If you are running with pre-allocated output, please make sure the output type/dims are correct. Error: ${m}`)}finally{this.module.stackRestore(h)}}},CT=async(i,c,h,m)=>{let y=c.jsepInit;if(!y)throw new Error("Failed to initialize JSEP. The WebAssembly module is not built with JSEP support.");if(i==="webgpu"){let S=(n1(),R(vT)).WebGpuBackend,b=new S;await b.initialize(h,m),y("webgpu",[b,E=>b.alloc(Number(E)),E=>b.free(E),(E,A,I,$=!1)=>{if($)bt("verbose",()=>`[WebGPU] jsepCopyGpuToGpu: src=${Number(E)}, dst=${Number(A)}, size=${Number(I)}`),b.memcpy(Number(E),Number(A));else{bt("verbose",()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${Number(E)}, gpuDataId=${Number(A)}, size=${Number(I)}`);let x=c.HEAPU8.subarray(Number(E>>>0),Number(E>>>0)+Number(I));b.upload(Number(A),x)}},async(E,A,I)=>{bt("verbose",()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${E}, dataOffset=${A}, size=${I}`),await b.download(Number(E),()=>c.HEAPU8.subarray(Number(A)>>>0,Number(A+I)>>>0))},(E,A,I)=>b.createKernel(E,Number(A),I,c.UTF8ToString(c._JsepGetNodeName(Number(A)))),E=>b.releaseKernel(E),(E,A,I,$)=>{bt("verbose",()=>`[WebGPU] jsepRun: sessionHandle=${I}, kernel=${E}, contextDataOffset=${A}`);let x=new ET(c,b,Number(A));return b.computeKernel(Number(E),x,$)},()=>b.captureBegin(),()=>b.captureEnd(),()=>b.replay()])}else{let S=new Cn(h);y("webnn",[S,()=>S.reserveTensorId(),b=>S.releaseTensorId(b),async(b,E,A,I,$)=>S.ensureTensor(b,E,A,I,$),(b,E)=>{S.uploadTensor(b,E)},async(b,E)=>S.downloadTensor(b,E),(b,E)=>S.registerMLContext(b,E),!!h.trace])}}}),AT,Rf,$f,_a,IT,xf,rc,Of,Df,kf,Nf,Mf,Uf,RT=_(()=>{as(),vn(),Da(),ot(),gr(),jr(),Hi(),AT=(i,c)=>{kt()._OrtInit(i,c)!==0&&It("Can't initialize onnxruntime.")},Rf=async i=>{AT(i.wasm.numThreads,Yr(i.logLevel))},$f=async(i,c)=>{var m,y;(y=(m=kt()).asyncInit)==null||y.call(m);let h=i.webgpu.adapter;if(c==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");if(h){if(typeof h.limits!="object"||typeof h.features!="object"||typeof h.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let S=i.webgpu.powerPreference;if(S!==void 0&&S!=="low-power"&&S!=="high-performance")throw new Error(`Invalid powerPreference setting: "${S}"`);let b=i.webgpu.forceFallbackAdapter;if(b!==void 0&&typeof b!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${b}"`);if(h=await navigator.gpu.requestAdapter({powerPreference:S,forceFallbackAdapter:b}),!h)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}}if(c==="webnn"&&(typeof navigator>"u"||!navigator.ml))throw new Error("WebNN is not supported in current environment");{let S=(i1(),R(wT)).init;c==="webgpu"&&await S("webgpu",kt(),i,h),c==="webnn"&&await S("webnn",kt(),i)}},_a=new Map,IT=i=>{let c=kt(),h=c.stackSave();try{let m=c.PTR_SIZE,y=c.stackAlloc(2*m);c._OrtGetInputOutputCount(i,y,y+m)!==0&&It("Can't get session input/output count.");let S=m===4?"i32":"i64";return[Number(c.getValue(y,S)),Number(c.getValue(y+m,S))]}finally{c.stackRestore(h)}},xf=(i,c)=>{let h=kt(),m=h.stackSave(),y=0;try{let S=h.PTR_SIZE,b=h.stackAlloc(2*S);h._OrtGetInputOutputMetadata(i,c,b,b+S)!==0&&It("Can't get session input/output metadata.");let E=Number(h.getValue(b,"*"));y=Number(h.getValue(b+S,"*"));let A=h.HEAP32[y/4];if(A===0)return[E,0];let I=h.HEAPU32[y/4+1],$=[];for(let x=0;x<I;x++){let k=Number(h.getValue(y+8+x*S,"*"));$.push(k!==0?h.UTF8ToString(k):Number(h.getValue(y+8+(x+I)*S,"*")))}return[E,A,$]}finally{h.stackRestore(m),y!==0&&h._OrtFree(y)}},rc=i=>{let c=kt(),h=c._malloc(i.byteLength);if(h===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${i.byteLength}.`);return c.HEAPU8.set(i,h),[h,i.byteLength]},Of=async(i,c)=>{var x,k,N,M;let h,m,y=kt();Array.isArray(i)?[h,m]=i:i.buffer===y.HEAPU8.buffer?[h,m]=[i.byteOffset,i.byteLength]:[h,m]=rc(i);let S=0,b=0,E=0,A=[],I=[],$=[];try{if([b,A]=await Wr(c),(c==null?void 0:c.externalData)&&y.mountExternalData){let de=[];for(let ve of c.externalData){let Ue=typeof ve=="string"?ve:ve.path;de.push(Zn(typeof ve=="string"?ve:ve.data).then(ct=>{y.mountExternalData(Ue,ct)}))}await Promise.all(de)}for(let de of(c==null?void 0:c.executionProviders)??[])if((typeof de=="string"?de:de.name)==="webnn"){if(y.shouldTransferToMLTensor=!1,typeof de!="string"){let ve=de,Ue=ve==null?void 0:ve.context,ct=ve==null?void 0:ve.gpuDevice,st=ve==null?void 0:ve.deviceType,ut=ve==null?void 0:ve.powerPreference;Ue?y.currentContext=Ue:ct?y.currentContext=await y.webnnCreateMLContext(ct):y.currentContext=await y.webnnCreateMLContext({deviceType:st,powerPreference:ut})}else y.currentContext=await y.webnnCreateMLContext();break}S=await y._OrtCreateSession(h,m,b),(x=y.webgpuOnCreateSession)==null||x.call(y,S),S===0&&It("Can't create a session."),(k=y.jsepOnCreateSession)==null||k.call(y),y.currentContext&&(y.webnnRegisterMLContext(S,y.currentContext),y.currentContext=void 0,y.shouldTransferToMLTensor=!0);let[U,z]=IT(S),L=!!(c!=null&&c.enableGraphCapture),P=[],j=[],V=[],Y=[],ae=[];for(let de=0;de<U;de++){let[ve,Ue,ct]=xf(S,de);ve===0&&It("Can't get an input name."),I.push(ve);let st=y.UTF8ToString(ve);P.push(st),V.push(Ue===0?{name:st,isTensor:!1}:{name:st,isTensor:!0,type:Ys(Ue),shape:ct})}for(let de=0;de<z;de++){let[ve,Ue,ct]=xf(S,de+U);ve===0&&It("Can't get an output name."),$.push(ve);let st=y.UTF8ToString(ve);j.push(st),Y.push(Ue===0?{name:st,isTensor:!1}:{name:st,isTensor:!0,type:Ys(Ue),shape:ct});{if(L&&(c==null?void 0:c.preferredOutputLocation)===void 0){ae.push("gpu-buffer");continue}let ut=typeof(c==null?void 0:c.preferredOutputLocation)=="string"?c.preferredOutputLocation:((N=c==null?void 0:c.preferredOutputLocation)==null?void 0:N[st])??"cpu",$t=y.webnnIsGraphOutput;if(ut==="cpu"&&$t&&$t(S,st)){ae.push("ml-tensor-cpu-output");continue}if(ut!=="cpu"&&ut!=="cpu-pinned"&&ut!=="gpu-buffer"&&ut!=="ml-tensor")throw new Error(`Not supported preferred output location: ${ut}.`);if(L&&ut!=="gpu-buffer")throw new Error(`Not supported preferred output location: ${ut}. Only 'gpu-buffer' location is supported when enableGraphCapture is true.`);ae.push(ut)}}let ne=null;return ae.some(de=>de==="gpu-buffer"||de==="ml-tensor"||de==="ml-tensor-cpu-output")&&(E=y._OrtCreateBinding(S),E===0&&It("Can't create IO binding."),ne={handle:E,outputPreferredLocations:ae,outputPreferredLocationsEncoded:ae.map(de=>de==="ml-tensor-cpu-output"?"ml-tensor":de).map(de=>Xn(de))}),_a.set(S,[S,I,$,ne,L,!1]),[S,P,j,V,Y]}catch(U){throw I.forEach(z=>y._OrtFree(z)),$.forEach(z=>y._OrtFree(z)),E!==0&&y._OrtReleaseBinding(E)!==0&&It("Can't release IO binding."),S!==0&&y._OrtReleaseSession(S)!==0&&It("Can't release session."),U}finally{y._free(h),b!==0&&y._OrtReleaseSessionOptions(b)!==0&&It("Can't release session options."),A.forEach(U=>y._free(U)),(M=y.unmountExternalData)==null||M.call(y)}},Df=i=>{var A,I,$;let c=kt(),h=_a.get(i);if(!h)throw new Error(`cannot release session. invalid session id: ${i}`);let[m,y,S,b,E]=h;b&&(E&&c._OrtClearBoundOutputs(b.handle)!==0&&It("Can't clear bound outputs."),c._OrtReleaseBinding(b.handle)!==0&&It("Can't release IO binding.")),(A=c.jsepOnReleaseSession)==null||A.call(c,i),(I=c.webnnOnReleaseSession)==null||I.call(c,i),($=c.webgpuOnReleaseSession)==null||$.call(c,i),y.forEach(x=>c._OrtFree(x)),S.forEach(x=>c._OrtFree(x)),c._OrtReleaseSession(m)!==0&&It("Can't release session."),_a.delete(i)},kf=async(i,c,h,m,y,S,b=!1)=>{if(!i){c.push(0);return}let E=kt(),A=E.PTR_SIZE,I=i[0],$=i[1],x=i[3],k=x,N,M;if(I==="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 ${S} when enableGraphCapture is true.`);if(x==="gpu-buffer"){let L=i[2].gpuBuffer;M=yr(vr(I),$);{let P=E.jsepRegisterBuffer;if(!P)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');N=P(m,S,L,M)}}else if(x==="ml-tensor"){let L=i[2].mlTensor;M=yr(vr(I),$);let P=E.webnnRegisterMLTensor;if(!P)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');N=P(m,L,vr(I),$)}else{let L=i[2];if(Array.isArray(L)){M=A*L.length,N=E._malloc(M),h.push(N);for(let P=0;P<L.length;P++){if(typeof L[P]!="string")throw new TypeError(`tensor data at index ${P} is not a string`);E.setValue(N+P*A,bs(L[P],h),"*")}}else{let P=E.webnnIsGraphInput,j=E.webnnIsGraphOutput;if(I!=="string"&&P&&j){let V=E.UTF8ToString(y);if(P(m,V)||j(m,V)){let Y=vr(I);M=yr(Y,$),k="ml-tensor";let ae=E.webnnCreateTemporaryTensor,ne=E.webnnUploadTensor;if(!ae||!ne)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');let de=await ae(m,Y,$);ne(de,new Uint8Array(L.buffer,L.byteOffset,L.byteLength)),N=de}else M=L.byteLength,N=E._malloc(M),h.push(N),E.HEAPU8.set(new Uint8Array(L.buffer,L.byteOffset,M),N)}else M=L.byteLength,N=E._malloc(M),h.push(N),E.HEAPU8.set(new Uint8Array(L.buffer,L.byteOffset,M),N)}}let U=E.stackSave(),z=E.stackAlloc(4*$.length);try{$.forEach((P,j)=>E.setValue(z+j*A,P,A===4?"i32":"i64"));let L=E._OrtCreateTensor(vr(I),N,M,z,$.length,Xn(k));L===0&&It(`Can't create tensor for input/output. session=${m}, index=${S}.`),c.push(L)}finally{E.stackRestore(U)}},Nf=async(i,c,h,m,y,S)=>{var ct,st,ut,$t;let b=kt(),E=b.PTR_SIZE,A=_a.get(i);if(!A)throw new Error(`cannot run inference. invalid session id: ${i}`);let I=A[0],$=A[1],x=A[2],k=A[3],N=A[4],M=A[5],U=c.length,z=m.length,L=0,P=[],j=[],V=[],Y=[],ae=b.stackSave(),ne=b.stackAlloc(U*E),de=b.stackAlloc(U*E),ve=b.stackAlloc(z*E),Ue=b.stackAlloc(z*E);try{[L,P]=gn(S),He("wasm prepareInputOutputTensor");for(let it=0;it<U;it++)await kf(h[it],j,Y,i,$[c[it]],c[it],N);for(let it=0;it<z;it++)await kf(y[it],V,Y,i,x[m[it]],U+m[it],N);qe("wasm prepareInputOutputTensor");for(let it=0;it<U;it++)b.setValue(ne+it*E,j[it],"*"),b.setValue(de+it*E,$[c[it]],"*");for(let it=0;it<z;it++)b.setValue(ve+it*E,V[it],"*"),b.setValue(Ue+it*E,x[m[it]],"*");if(k&&!M){let{handle:it,outputPreferredLocations:pt,outputPreferredLocationsEncoded:Fs}=k;if($.length!==U)throw new Error(`input count from feeds (${U}) is expected to be always equal to model's input count (${$.length}).`);He("wasm bindInputsOutputs");for(let Se=0;Se<U;Se++){let Be=c[Se];await b._OrtBindInput(it,$[Be],j[Se])!==0&&It(`Can't bind input[${Se}] for session=${i}.`)}for(let Se=0;Se<z;Se++){let Be=m[Se];(ct=y[Se])!=null&&ct[3]?b._OrtBindOutput(it,x[Be],V[Se],0)!==0&&It(`Can't bind pre-allocated output[${Se}] for session=${i}.`):b._OrtBindOutput(it,x[Be],0,Fs[Be])!==0&&It(`Can't bind output[${Se}] to ${pt[Se]} for session=${i}.`)}qe("wasm bindInputsOutputs"),_a.set(i,[I,$,x,k,N,!0])}(st=b.jsepOnRunStart)==null||st.call(b,I),(ut=b.webnnOnRunStart)==null||ut.call(b,I);let Tt;k?Tt=await b._OrtRunWithBinding(I,k.handle,z,ve,L):Tt=await b._OrtRun(I,de,ne,U,Ue,z,ve,L),Tt!==0&&It("failed to call OrtRun().");let at=[],St=[];He("wasm ProcessOutputTensor");for(let it=0;it<z;it++){let pt=Number(b.getValue(ve+it*E,"*"));if(pt===V[it]){at.push(y[it]);continue}let Fs=b.stackSave(),Se=b.stackAlloc(4*E),Be=!1,lt,wt=0;try{b._OrtGetTensorData(pt,Se,Se+E,Se+2*E,Se+3*E)!==0&&It(`Can't access output tensor data on index ${it}.`);let Sr=E===4?"i32":"i64",Dl=Number(b.getValue(Se,Sr));wt=b.getValue(Se+E,"*");let VT=b.getValue(Se+E*2,"*"),c1=Number(b.getValue(Se+E*3,Sr)),ma=[];for(let As=0;As<c1;As++)ma.push(Number(b.getValue(VT+As*E,Sr)));b._OrtFree(VT)!==0&&It("Can't free memory for tensor dims.");let ga=ma.reduce((As,fs)=>As*fs,1);lt=Ys(Dl);let No=k==null?void 0:k.outputPreferredLocations[m[it]];if(lt==="string"){if(No==="gpu-buffer"||No==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let As=[];for(let fs=0;fs<ga;fs++){let vi=b.getValue(wt+fs*E,"*"),d1=b.getValue(wt+(fs+1)*E,"*"),f1=fs===ga-1?void 0:d1-vi;As.push(b.UTF8ToString(vi,f1))}at.push([lt,ma,As,"cpu"])}else if(No==="gpu-buffer"&&ga>0){let As=b.jsepGetBuffer;if(!As)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let fs=As(wt),vi=yr(Dl,ga);if(vi===void 0||!Jn(lt))throw new Error(`Unsupported data type: ${lt}`);Be=!0,at.push([lt,ma,{gpuBuffer:fs,download:b.jsepCreateDownloader(fs,vi,lt),dispose:()=>{b._OrtReleaseTensor(pt)!==0&&It("Can't release tensor.")}},"gpu-buffer"])}else if(No==="ml-tensor"&&ga>0){let As=b.webnnEnsureTensor,fs=b.webnnIsGraphInputOutputTypeSupported;if(!As||!fs)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(yr(Dl,ga)===void 0||!Qn(lt))throw new Error(`Unsupported data type: ${lt}`);if(!fs(i,lt,!1))throw new Error(`preferredLocation "ml-tensor" for ${lt} output is not supported by current WebNN Context.`);let vi=await As(i,wt,Dl,ma,!1);Be=!0,at.push([lt,ma,{mlTensor:vi,download:b.webnnCreateMLTensorDownloader(wt,lt),dispose:()=>{b.webnnReleaseTensorId(wt),b._OrtReleaseTensor(pt)}},"ml-tensor"])}else if(No==="ml-tensor-cpu-output"&&ga>0){let As=b.webnnCreateMLTensorDownloader(wt,lt)(),fs=at.length;Be=!0,St.push((async()=>{let vi=[fs,await As];return b.webnnReleaseTensorId(wt),b._OrtReleaseTensor(pt),vi})()),at.push([lt,ma,[],"cpu"])}else{let As=Kr(lt),fs=new As(ga);new Uint8Array(fs.buffer,fs.byteOffset,fs.byteLength).set(b.HEAPU8.subarray(wt,wt+fs.byteLength)),at.push([lt,ma,fs,"cpu"])}}finally{b.stackRestore(Fs),lt==="string"&&wt&&b._free(wt),Be||b._OrtReleaseTensor(pt)}}k&&!N&&(b._OrtClearBoundOutputs(k.handle)!==0&&It("Can't clear bound outputs."),_a.set(i,[I,$,x,k,N,!1]));for(let[it,pt]of await Promise.all(St))at[it][2]=pt;return qe("wasm ProcessOutputTensor"),at}finally{($t=b.webnnOnRunEnd)==null||$t.call(b,I),b.stackRestore(ae),j.forEach(Tt=>b._OrtReleaseTensor(Tt)),V.forEach(Tt=>b._OrtReleaseTensor(Tt)),Y.forEach(Tt=>b._free(Tt)),L!==0&&b._OrtReleaseRunOptions(L),P.forEach(Tt=>b._free(Tt))}},Mf=i=>{let c=kt(),h=_a.get(i);if(!h)throw new Error("invalid session id");let m=h[0],y=c._OrtEndProfiling(m);y===0&&It("Can't get an profile file name."),c._OrtFree(y)},Uf=i=>{let c=[];for(let h of i){let m=h[2];!Array.isArray(m)&&"buffer"in m&&c.push(m.buffer)}return c}}),pa,fr,Ol,Do,ko,nc,Pf,ic,sl,rl,$T,xT,OT,DT,kT,NT,MT,UT,PT=_(()=>{as(),RT(),gr(),Yn(),pa=()=>!!Z.wasm.proxy&&typeof document<"u",Ol=!1,Do=!1,ko=!1,ic=new Map,sl=(i,c)=>{let h=ic.get(i);h?h.push(c):ic.set(i,[c])},rl=()=>{if(Ol||!Do||ko||!fr)throw new Error("worker not ready")},$T=i=>{switch(i.data.type){case"init-wasm":Ol=!1,i.data.err?(ko=!0,Pf[1](i.data.err)):(Do=!0,Pf[0]()),nc&&(URL.revokeObjectURL(nc),nc=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let c=ic.get(i.data.type);i.data.err?c.shift()[1](i.data.err):c.shift()[0](i.data.out);break}}},xT=async()=>{if(!Do){if(Ol)throw new Error("multiple calls to 'initWasm()' detected.");if(ko)throw new Error("previous call to 'initWasm()' failed.");if(Ol=!0,pa())return new Promise((i,c)=>{fr==null||fr.terminate(),Mi().then(([h,m])=>{try{fr=m,fr.onerror=S=>c(S),fr.onmessage=$T,Pf=[i,c];let y={type:"init-wasm",in:Z};if(!y.in.wasm.wasmPaths&&h){let S=qn();S&&(y.in.wasm.wasmPaths=S)}fr.postMessage(y),nc=h}catch(y){c(y)}},c)});try{await Vr(Z.wasm),await Rf(Z),Do=!0}catch(i){throw ko=!0,i}finally{Ol=!1}}},OT=async i=>{if(pa())return rl(),new Promise((c,h)=>{sl("init-ep",[c,h]);let m={type:"init-ep",in:{epName:i,env:Z}};fr.postMessage(m)});await $f(Z,i)},DT=async i=>pa()?(rl(),new Promise((c,h)=>{sl("copy-from",[c,h]);let m={type:"copy-from",in:{buffer:i}};fr.postMessage(m,[i.buffer])})):rc(i),kT=async(i,c)=>{if(pa()){if(c!=null&&c.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return rl(),new Promise((h,m)=>{sl("create",[h,m]);let y={type:"create",in:{model:i,options:{...c}}},S=[];i instanceof Uint8Array&&S.push(i.buffer),fr.postMessage(y,S)})}else return Of(i,c)},NT=async i=>{if(pa())return rl(),new Promise((c,h)=>{sl("release",[c,h]);let m={type:"release",in:i};fr.postMessage(m)});Df(i)},MT=async(i,c,h,m,y,S)=>{if(pa()){if(h.some(b=>b[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(y.some(b=>b))throw new Error("pre-allocated output tensor is not supported for proxy.");return rl(),new Promise((b,E)=>{sl("run",[b,E]);let A=h,I={type:"run",in:{sessionId:i,inputIndices:c,inputs:A,outputIndices:m,options:S}};fr.postMessage(I,Uf(A))})}else return Nf(i,c,h,m,y,S)},UT=async i=>{if(pa())return rl(),new Promise((c,h)=>{sl("end-profiling",[c,h]);let m={type:"end-profiling",in:i};fr.postMessage(m)});Mf(i)}}),Lf,LT,HT,a1=_(()=>{as(),PT(),ot(),Pr(),Hi(),Lf=(i,c)=>{switch(i.location){case"cpu":return[i.type,i.dims,i.data,"cpu"];case"gpu-buffer":return[i.type,i.dims,{gpuBuffer:i.gpuBuffer},"gpu-buffer"];case"ml-tensor":return[i.type,i.dims,{mlTensor:i.mlTensor},"ml-tensor"];default:throw new Error(`invalid data location: ${i.location} for ${c()}`)}},LT=i=>{switch(i[3]){case"cpu":return new Mt(i[0],i[2],i[1]);case"gpu-buffer":{let c=i[0];if(!Jn(c))throw new Error(`not supported data type: ${c} for deserializing GPU tensor`);let{gpuBuffer:h,download:m,dispose:y}=i[2];return Mt.fromGpuBuffer(h,{dataType:c,dims:i[1],download:m,dispose:y})}case"ml-tensor":{let c=i[0];if(!Qn(c))throw new Error(`not supported data type: ${c} for deserializing MLTensor tensor`);let{mlTensor:h,download:m,dispose:y}=i[2];return Mt.fromMLTensor(h,{dataType:c,dims:i[1],download:m,dispose:y})}default:throw new Error(`invalid data location: ${i[3]}`)}},HT=class{async fetchModelAndCopyToWasmMemory(i){return DT(await Zn(i))}async loadModel(i,c){ft();let h;typeof i=="string"?h=await this.fetchModelAndCopyToWasmMemory(i):h=i,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await kT(h,c),Fe()}async dispose(){return NT(this.sessionId)}async run(i,c,h){ft();let m=[],y=[];Object.entries(i).forEach(x=>{let k=x[0],N=x[1],M=this.inputNames.indexOf(k);if(M===-1)throw new Error(`invalid input '${k}'`);m.push(N),y.push(M)});let S=[],b=[];Object.entries(c).forEach(x=>{let k=x[0],N=x[1],M=this.outputNames.indexOf(k);if(M===-1)throw new Error(`invalid output '${k}'`);S.push(N),b.push(M)});let E=m.map((x,k)=>Lf(x,()=>`input "${this.inputNames[y[k]]}"`)),A=S.map((x,k)=>x?Lf(x,()=>`output "${this.outputNames[b[k]]}"`):null),I=await MT(this.sessionId,y,E,b,A,h),$={};for(let x=0;x<I.length;x++)$[this.outputNames[b[x]]]=S[x]??LT(I[x]);return Fe(),$}startProfiling(){}endProfiling(){UT(this.sessionId)}}}),FT={};v(FT,{OnnxruntimeWebAssemblyBackend:()=>Ff,initializeFlags:()=>Hf,wasmBackend:()=>BT});var Hf,Ff,BT,l1=_(()=>{as(),PT(),a1(),Hf=()=>{(typeof Z.wasm.initTimeout!="number"||Z.wasm.initTimeout<0)&&(Z.wasm.initTimeout=0);let i=Z.wasm.simd;if(typeof i!="boolean"&&i!==void 0&&i!=="fixed"&&i!=="relaxed"&&(console.warn(`Property "env.wasm.simd" is set to unknown value "${i}". Reset it to \`false\` and ignore SIMD feature checking.`),Z.wasm.simd=!1),typeof Z.wasm.proxy!="boolean"&&(Z.wasm.proxy=!1),typeof Z.wasm.trace!="boolean"&&(Z.wasm.trace=!1),typeof Z.wasm.numThreads!="number"||!Number.isInteger(Z.wasm.numThreads)||Z.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)Z.wasm.numThreads=1;else{let c=typeof navigator>"u"?g("node:os").cpus().length:navigator.hardwareConcurrency;Z.wasm.numThreads=Math.min(4,Math.ceil((c||1)/2))}},Ff=class{async init(i){Hf(),await xT(),await OT(i)}async createInferenceSessionHandler(i,c){let h=new HT;return await h.loadModel(i,c),h}},BT=new Ff}),zT={};v(zT,{InferenceSession:()=>Ut,TRACE:()=>rt,TRACE_EVENT_BEGIN:()=>He,TRACE_EVENT_END:()=>qe,TRACE_FUNC_BEGIN:()=>ft,TRACE_FUNC_END:()=>Fe,Tensor:()=>Mt,default:()=>u1,env:()=>Z,registerBackend:()=>F}),as(),as(),as();var o1="1.23.0",u1=pr;{let i=(l1(),R(FT)).wasmBackend;F("webgpu",i,5),F("webnn",i,5),F("cpu",i,10),F("wasm",i,10)}return Object.defineProperty(Z.versions,"web",{value:o1,enumerable:!0}),R(zT)})();/**
2946
2946
  * @license
2947
2947
  * Copyright 2021 Google LLC. All Rights Reserved.
2948
2948
  * Licensed under the Apache License, Version 2.0 (the "License");
@@ -2987,5 +2987,5 @@ ${S}`,E=h.createShaderModule({code:b,label:i.name});bt("verbose",()=>`[WebGPU] $
2987
2987
  * See the License for the specific language governing permissions and
2988
2988
  * limitations under the License.
2989
2989
  * =============================================================================
2990
- */f.exports=r})(bp);var Ud=bp.exports,Pd={},wp={};Object.defineProperty(wp,"__esModule",{value:!0});var Bu={},Ep;Object.defineProperty(Bu,"__esModule",{value:!0}),Bu.SileroLegacy=void 0;const Cp=vl;class Ld{constructor(t,r,l,u,s){this.ortInstance=t,this._session=r,this._h=l,this._c=u,this._sr=s,this.reset_state=()=>{const n=Array(128).fill(0);this._h=new this.ortInstance.Tensor("float32",n,[2,1,64]),this._c=new this.ortInstance.Tensor("float32",n,[2,1,64])},this.process=async n=>{var D;const _={input:new this.ortInstance.Tensor("float32",n,[1,n.length]),h:this._h,c:this._c,sr:this._sr},v=await this._session.run(_);this._h=v.hn,this._c=v.cn;const[C]=(D=v.output)==null?void 0:D.data;return{notSpeech:1-C,isSpeech:C}}}}Bu.SileroLegacy=Ld,Ep=Ld,Ld.new=async(f,t)=>{Cp.log.debug("initializing vad");const r=await t(),l=await f.InferenceSession.create(r),u=new f.Tensor("int64",[16000n]),s=Array(2*64).fill(0),n=new f.Tensor("float32",s,[2,1,64]),g=new f.Tensor("float32",s,[2,1,64]);return Cp.log.debug("vad is initialized"),new Ep(f,l,n,g,u)};var zu={},Ap;Object.defineProperty(zu,"__esModule",{value:!0}),zu.SileroV5=void 0;const Ip=vl;function Rp(f){const t=Array(256).fill(0);return new f.Tensor("float32",t,[2,1,128])}class Hd{constructor(t,r,l,u){this._session=t,this._state=r,this._sr=l,this.ortInstance=u,this.reset_state=()=>{this._state=Rp(this.ortInstance)},this.process=async s=>{var R;const g={input:new this.ortInstance.Tensor("float32",s,[1,s.length]),state:this._state,sr:this._sr},_=await this._session.run(g);this._state=_.stateN;const[v]=(R=_.output)==null?void 0:R.data;return{notSpeech:1-v,isSpeech:v}}}}zu.SileroV5=Hd,Ap=Hd,Hd.new=async(f,t)=>{Ip.log.debug("Loading VAD...");const r=await t(),l=await f.InferenceSession.create(r),u=new f.Tensor("int64",[16000n]),s=Rp(f);return Ip.log.debug("...finished loading VAD"),new Ap(l,s,u,f)},function(f){var t=Lt&&Lt.__createBinding||(Object.create?function(s,n,g,_){_===void 0&&(_=g);var v=Object.getOwnPropertyDescriptor(n,g);(!v||("get"in v?!n.__esModule:v.writable||v.configurable))&&(v={enumerable:!0,get:function(){return n[g]}}),Object.defineProperty(s,_,v)}:function(s,n,g,_){_===void 0&&(_=g),s[_]=n[g]}),r=Lt&&Lt.__exportStar||function(s,n){for(var g in s)g!=="default"&&!Object.prototype.hasOwnProperty.call(n,g)&&t(n,s,g)};Object.defineProperty(f,"__esModule",{value:!0}),f.SileroV5=f.SileroLegacy=void 0,r(wp,f);var l=Bu;Object.defineProperty(f,"SileroLegacy",{enumerable:!0,get:function(){return l.SileroLegacy}});var u=zu;Object.defineProperty(f,"SileroV5",{enumerable:!0,get:function(){return u.SileroV5}})}(Pd);var vo={};Object.defineProperty(vo,"__esModule",{value:!0}),vo.Resampler=void 0;const uA=vl;class cA{constructor(t){this.options=t,this.process=r=>{const l=[];for(const u of r)for(this.inputBuffer.push(u);this.hasEnoughDataForFrame();){const s=this.generateOutputFrame();l.push(s)}return l},t.nativeSampleRate<16e3&&uA.log.error("nativeSampleRate is too low. Should have 16000 = targetSampleRate <= nativeSampleRate"),this.inputBuffer=[]}async*stream(t){for(const r of t)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 t=new Float32Array(this.options.targetFrameSize);let r=0,l=0;for(;r<this.options.targetFrameSize;){let u=0,s=0;for(;l<Math.min(this.inputBuffer.length,(r+1)*this.options.nativeSampleRate/this.options.targetSampleRate);){const n=this.inputBuffer[l];n!==void 0&&(u+=n,s++),l++}t[r]=u/s,r++}return this.inputBuffer=this.inputBuffer.slice(l),t}}vo.Resampler=cA,function(f){var t=Lt&&Lt.__createBinding||(Object.create?function(D,H,F,q){q===void 0&&(q=F);var G=Object.getOwnPropertyDescriptor(H,F);(!G||("get"in G?!H.__esModule:G.writable||G.configurable))&&(G={enumerable:!0,get:function(){return H[F]}}),Object.defineProperty(D,q,G)}:function(D,H,F,q){q===void 0&&(q=F),D[q]=H[F]}),r=Lt&&Lt.__setModuleDefault||(Object.create?function(D,H){Object.defineProperty(D,"default",{enumerable:!0,value:H})}:function(D,H){D.default=H}),l=Lt&&Lt.__importStar||function(D){if(D&&D.__esModule)return D;var H={};if(D!=null)for(var F in D)F!=="default"&&Object.prototype.hasOwnProperty.call(D,F)&&t(H,D,F);return r(H,D),H};Object.defineProperty(f,"__esModule",{value:!0}),f.NonRealTimeVAD=f.defaultNonRealTimeVADOptions=void 0;const u=l(Ud),s=mo,n=gl,g=hn,_=Ra,v=Pd,C=vo;f.defaultNonRealTimeVADOptions={...g.defaultFrameProcessorOptions,modelURL:s.baseAssetPath+"silero_vad_legacy.onnx",modelFetcher:n.defaultModelFetcher};class R{static async new(H={}){const F={...f.defaultNonRealTimeVADOptions,...H};(0,g.validateOptions)(F),F.ortConfig!==void 0&&F.ortConfig(u);const q=()=>F.modelFetcher(F.modelURL),G=await v.SileroLegacy.new(u,q),te=new g.FrameProcessor(G.process,G.reset_state,{positiveSpeechThreshold:F.positiveSpeechThreshold,negativeSpeechThreshold:F.negativeSpeechThreshold,redemptionMs:F.redemptionMs,preSpeechPadMs:F.preSpeechPadMs,minSpeechMs:F.minSpeechMs,submitUserSpeechOnPause:F.submitUserSpeechOnPause},1536/16);return te.resume(),new this(q,u,F,te)}constructor(H,F,q,G){this.modelFetcher=H,this.ort=F,this.options=q,this.frameProcessor=G,this.frameSamples=1536}async*run(H,F){const q={nativeSampleRate:F,targetSampleRate:16e3,targetFrameSize:this.frameSamples},G=new C.Resampler(q);let te=0,X=0,we=0;for await(const re of G.stream(H)){const ke=[];await this.frameProcessor.process(re,Ne=>{ke.push(Ne)});for(const Ne of ke)switch(Ne.msg){case _.Message.SpeechStart:te=we*this.frameSamples/16;break;case _.Message.SpeechEnd:X=(we+1)*this.frameSamples/16,yield{audio:Ne.audio,start:te,end:X};break}we++}const Q=[];this.frameProcessor.endSegment(re=>{Q.push(re)});for(const re of Q)switch(re.msg){case _.Message.SpeechEnd:yield{audio:re.audio,start:te,end:we*this.frameSamples/16}}}}f.NonRealTimeVAD=R}(Sp);var _n={};Object.defineProperty(_n,"__esModule",{value:!0}),_n.audioFileToArray=_n.encodeWAV=_n.arrayBufferToBase64=_n.minFramesForTargetMS=void 0;function dA(f,t,r=16e3){return Math.ceil(f*r/1e3/t)}_n.minFramesForTargetMS=dA;function fA(f){const t=new Uint8Array(f),r=t.byteLength,l=new Array(r);for(var u=0;u<r;u++){const s=t[u];if(s===void 0)break;l[u]=String.fromCharCode(s)}return btoa(l.join(""))}_n.arrayBufferToBase64=fA;function hA(f,t=3,r=16e3,l=1,u=32){var s=u/8,n=l*s,g=new ArrayBuffer(44+f.length*s),_=new DataView(g);return Vu(_,0,"RIFF"),_.setUint32(4,36+f.length*s,!0),Vu(_,8,"WAVE"),Vu(_,12,"fmt "),_.setUint32(16,16,!0),_.setUint16(20,t,!0),_.setUint16(22,l,!0),_.setUint32(24,r,!0),_.setUint32(28,r*n,!0),_.setUint16(32,n,!0),_.setUint16(34,u,!0),Vu(_,36,"data"),_.setUint32(40,f.length*s,!0),t===1?pA(_,44,f):_A(_,44,f),g}_n.encodeWAV=hA;function _A(f,t,r){for(var l=0;l<r.length;l++,t+=4)f.setFloat32(t,r[l],!0)}function pA(f,t,r){for(var l=0;l<r.length;l++,t+=2){var u=Math.max(-1,Math.min(1,r[l]));f.setInt16(t,u<0?u*32768:u*32767,!0)}}function Vu(f,t,r){for(var l=0;l<r.length;l++)f.setUint8(t+l,r.charCodeAt(l))}async function mA(f){const t=new OfflineAudioContext(1,1,44100),r=new FileReader;let l=null;if(await new Promise(n=>{r.addEventListener("loadend",g=>{const _=r.result;t.decodeAudioData(_,v=>{l=v,t.startRendering().then(C=>{console.log("Rendering completed successfully"),n()}).catch(C=>{console.error(`Rendering failed: ${C}`)})},v=>{console.log(`Error with decoding audio data: ${v}`)})}),r.readAsArrayBuffer(f)}),l===null)throw Error("some shit");let u=l,s=new Float32Array(u.length);for(let n=0;n<u.length;n++)for(let g=0;g<u.numberOfChannels;g++)s[n]+=u.getChannelData(g)[n];return{audio:s,sampleRate:u.sampleRate}}_n.audioFileToArray=mA;var $p={};(function(f){var t=Lt&&Lt.__createBinding||(Object.create?function(te,X,we,Q){Q===void 0&&(Q=we);var re=Object.getOwnPropertyDescriptor(X,we);(!re||("get"in re?!X.__esModule:re.writable||re.configurable))&&(re={enumerable:!0,get:function(){return X[we]}}),Object.defineProperty(te,Q,re)}:function(te,X,we,Q){Q===void 0&&(Q=we),te[Q]=X[we]}),r=Lt&&Lt.__setModuleDefault||(Object.create?function(te,X){Object.defineProperty(te,"default",{enumerable:!0,value:X})}:function(te,X){te.default=X}),l=Lt&&Lt.__importStar||function(te){if(te&&te.__esModule)return te;var X={};if(te!=null)for(var we in te)we!=="default"&&Object.prototype.hasOwnProperty.call(te,we)&&t(X,te,we);return r(X,te),X};Object.defineProperty(f,"__esModule",{value:!0}),f.AudioNodeVAD=f.MicVAD=f.getDefaultRealTimeVADOptions=f.ort=f.DEFAULT_MODEL=void 0;const u=l(Ud),s=gl,n=hn,g=vl,_=Ra,v=Pd,C=vo;f.DEFAULT_MODEL="legacy",f.ort=u;const R="vad.worklet.bundle.min.js",D="silero_vad_v5.onnx",H="silero_vad_legacy.onnx",F=te=>({...n.defaultFrameProcessorOptions,onFrameProcessed:(X,we)=>{},onVADMisfire:()=>{g.log.debug("VAD misfire")},onSpeechStart:()=>{g.log.debug("Detected speech start")},onSpeechEnd:()=>{g.log.debug("Detected speech end")},onSpeechRealStart:()=>{g.log.debug("Detected real speech start")},baseAssetPath:"./",onnxWASMBasePath:"./",model:te,workletOptions:{},getStream:async()=>await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0}}),pauseStream:async X=>{X.getTracks().forEach(we=>{we.stop()})},resumeStream:async X=>await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0}}),ortConfig:X=>{X.env.logLevel="error"},startOnLoad:!0});f.getDefaultRealTimeVADOptions=F;class q{static async new(X={}){const we={...(0,f.getDefaultRealTimeVADOptions)(X.model??f.DEFAULT_MODEL),...X};(0,n.validateOptions)(we);const Q=new AudioContext,re=await G.new(Q,we),ke=new q(we,Q,re);if(we.startOnLoad)try{await ke.start()}catch(Ne){console.error("Error starting micVad",Ne)}return ke}constructor(X,we,Q,re=!1){this.options=X,this.audioContext=we,this.audioNodeVAD=Q,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()=>{var ke;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)),(ke=this.stream)!=null&&ke.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=ke=>{this.audioNodeVAD.setFrameProcessorOptions(ke)}}}f.MicVAD=q;class G{static async new(X,we={}){const Q={...(0,f.getDefaultRealTimeVADOptions)(we.model??f.DEFAULT_MODEL),...we};(0,n.validateOptions)(Q),f.ort.env.wasm.wasmPaths=Q.onnxWASMBasePath,Q.ortConfig!==void 0&&Q.ortConfig(f.ort);const re=Q.model==="v5"?D:H,ke=Q.baseAssetPath+re,Ne=Q.model==="v5"?v.SileroV5.new:v.SileroLegacy.new;let Z;try{Z=await Ne(f.ort,()=>(0,s.defaultModelFetcher)(ke))}catch(_e){throw console.error(`Encountered an error while loading model file ${ke}`),_e}const se=Q.model==="v5"?512:1536,pe=se/16,me=new n.FrameProcessor(Z.process,Z.reset_state,{positiveSpeechThreshold:Q.positiveSpeechThreshold,negativeSpeechThreshold:Q.negativeSpeechThreshold,redemptionMs:Q.redemptionMs,preSpeechPadMs:Q.preSpeechPadMs,minSpeechMs:Q.minSpeechMs,submitUserSpeechOnPause:Q.submitUserSpeechOnPause},pe),be=new G(X,Q,me,se,pe);return await be.setupAudioNode(),be}constructor(X,we,Q,re,ke){this.ctx=X,this.options=we,this.frameSamples=re,this.msPerFrame=ke,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 _.Message.FrameProcessed:this.options.onFrameProcessed(Ne.probs,Ne.frame);break;case _.Message.SpeechStart:this.options.onSpeechStart();break;case _.Message.SpeechRealStart:this.options.onSpeechRealStart();break;case _.Message.VADMisfire:this.options.onVADMisfire();break;case _.Message.SpeechEnd:this.options.onSpeechEnd(Ne.audio);break}},this.destroy=()=>{var Ne;this.audioNode instanceof AudioWorkletNode&&this.audioNode.port.postMessage({message:_.Message.SpeechStop}),this.audioNode.disconnect(),(Ne=this.gainNode)==null||Ne.disconnect()},this.setFrameProcessorOptions=Ne=>{this.frameProcessor.options={...this.frameProcessor.options,...Ne}},this.frameProcessor=Q}async setupAudioNode(){if("audioWorklet"in this.ctx&&typeof AudioWorkletNode=="function")try{const re=this.options.baseAssetPath+R;await this.ctx.audioWorklet.addModule(re);const ke=this.options.workletOptions??{};ke.processorOptions={...ke.processorOptions??{},frameSamples:this.frameSamples},this.audioNode=new AudioWorkletNode(this.ctx,"vad-helper-worklet",ke),this.audioNode.port.onmessage=async Ne=>{var Z;switch((Z=Ne.data)==null?void 0:Z.message){case _.Message.AudioFrame:let se=Ne.data.data;se instanceof ArrayBuffer||(se=new ArrayBuffer(Ne.data.data.byteLength),new Uint8Array(se).set(new Uint8Array(Ne.data.data)));const pe=new Float32Array(se);await this.processFrame(pe);break}};return}catch(re){console.log("AudioWorklet setup failed, falling back to ScriptProcessor",re)}this.resampler=new C.Resampler({nativeSampleRate:this.ctx.sampleRate,targetSampleRate:16e3,targetFrameSize:this.frameSamples??480});const we=4096;this.audioNode=this.ctx.createScriptProcessor(we,1,1),this.gainNode=this.ctx.createGain(),this.gainNode.gain.value=0;let Q=!1;this.audioNode.onaudioprocess=async re=>{if(!Q){Q=!0;try{const ke=re.inputBuffer.getChannelData(0);if(re.outputBuffer.getChannelData(0).fill(0),this.resampler){const Z=this.resampler.process(ke);for(const se of Z)await this.processFrame(se)}}catch(ke){console.error("Error processing audio:",ke)}finally{Q=!1}}},this.audioNode.connect(this.gainNode),this.gainNode.connect(this.ctx.destination)}}f.AudioNodeVAD=G})($p),function(f){Object.defineProperty(f,"__esModule",{value:!0}),f.getDefaultRealTimeVADOptions=f.MicVAD=f.DEFAULT_MODEL=f.AudioNodeVAD=f.utils=f.NonRealTimeVAD=f.Message=f.FrameProcessor=f.defaultModelFetcher=f.baseAssetPath=void 0;var t=mo;Object.defineProperty(f,"baseAssetPath",{enumerable:!0,get:function(){return t.baseAssetPath}});var r=gl;Object.defineProperty(f,"defaultModelFetcher",{enumerable:!0,get:function(){return r.defaultModelFetcher}});var l=hn;Object.defineProperty(f,"FrameProcessor",{enumerable:!0,get:function(){return l.FrameProcessor}});var u=Ra;Object.defineProperty(f,"Message",{enumerable:!0,get:function(){return u.Message}});var s=Sp;Object.defineProperty(f,"NonRealTimeVAD",{enumerable:!0,get:function(){return s.NonRealTimeVAD}});const n=_n;f.utils={audioFileToArray:n.audioFileToArray,minFramesForTargetMS:n.minFramesForTargetMS,arrayBufferToBase64:n.arrayBufferToBase64,encodeWAV:n.encodeWAV};var g=$p;Object.defineProperty(f,"AudioNodeVAD",{enumerable:!0,get:function(){return g.AudioNodeVAD}}),Object.defineProperty(f,"DEFAULT_MODEL",{enumerable:!0,get:function(){return g.DEFAULT_MODEL}}),Object.defineProperty(f,"MicVAD",{enumerable:!0,get:function(){return g.MicVAD}}),Object.defineProperty(f,"getDefaultRealTimeVADOptions",{enumerable:!0,get:function(){return g.getDefaultRealTimeVADOptions}})}(mp);const Mr={NEW_CALL:"new_call",CALL_CONFIRMED:"confirmed",CALL_FAILED:"failed",CALL_PROGRESS:"progress",CALL_ENDED:"ended"};var gA={exports:{}};(function(f){var t=function(r){var l=Object.prototype,u=l.hasOwnProperty,s=Object.defineProperty||function(Re,ye,ge){Re[ye]=ge.value},n,g=typeof Symbol=="function"?Symbol:{},_=g.iterator||"@@iterator",v=g.asyncIterator||"@@asyncIterator",C=g.toStringTag||"@@toStringTag";function R(Re,ye,ge){return Object.defineProperty(Re,ye,{value:ge,enumerable:!0,configurable:!0,writable:!0}),Re[ye]}try{R({},"")}catch{R=function(ye,ge,Le){return ye[ge]=Le}}function D(Re,ye,ge,Le){var et=ye&&ye.prototype instanceof we?ye:we,vt=Object.create(et.prototype),xt=new oe(Le||[]);return s(vt,"_invoke",{value:be(Re,ge,xt)}),vt}r.wrap=D;function H(Re,ye,ge){try{return{type:"normal",arg:Re.call(ye,ge)}}catch(Le){return{type:"throw",arg:Le}}}var F="suspendedStart",q="suspendedYield",G="executing",te="completed",X={};function we(){}function Q(){}function re(){}var ke={};R(ke,_,function(){return this});var Ne=Object.getPrototypeOf,Z=Ne&&Ne(Ne(Oe([])));Z&&Z!==l&&u.call(Z,_)&&(ke=Z);var se=re.prototype=we.prototype=Object.create(ke);Q.prototype=re,s(se,"constructor",{value:re,configurable:!0}),s(re,"constructor",{value:Q,configurable:!0}),Q.displayName=R(re,C,"GeneratorFunction");function pe(Re){["next","throw","return"].forEach(function(ye){R(Re,ye,function(ge){return this._invoke(ye,ge)})})}r.isGeneratorFunction=function(Re){var ye=typeof Re=="function"&&Re.constructor;return ye?ye===Q||(ye.displayName||ye.name)==="GeneratorFunction":!1},r.mark=function(Re){return Object.setPrototypeOf?Object.setPrototypeOf(Re,re):(Re.__proto__=re,R(Re,C,"GeneratorFunction")),Re.prototype=Object.create(se),Re},r.awrap=function(Re){return{__await:Re}};function me(Re,ye){function ge(vt,xt,dt,ze){var Ye=H(Re[vt],Re,xt);if(Ye.type==="throw")ze(Ye.arg);else{var Zt=Ye.arg,Mt=Zt.value;return Mt&&typeof Mt=="object"&&u.call(Mt,"__await")?ye.resolve(Mt.__await).then(function(nt){ge("next",nt,dt,ze)},function(nt){ge("throw",nt,dt,ze)}):ye.resolve(Mt).then(function(nt){Zt.value=nt,dt(Zt)},function(nt){return ge("throw",nt,dt,ze)})}}var Le;function et(vt,xt){function dt(){return new ye(function(ze,Ye){ge(vt,xt,ze,Ye)})}return Le=Le?Le.then(dt,dt):dt()}s(this,"_invoke",{value:et})}pe(me.prototype),R(me.prototype,v,function(){return this}),r.AsyncIterator=me,r.async=function(Re,ye,ge,Le,et){et===void 0&&(et=Promise);var vt=new me(D(Re,ye,ge,Le),et);return r.isGeneratorFunction(ye)?vt:vt.next().then(function(xt){return xt.done?xt.value:vt.next()})};function be(Re,ye,ge){var Le=F;return function(vt,xt){if(Le===G)throw new Error("Generator is already running");if(Le===te){if(vt==="throw")throw xt;return rs()}for(ge.method=vt,ge.arg=xt;;){var dt=ge.delegate;if(dt){var ze=_e(dt,ge);if(ze){if(ze===X)continue;return ze}}if(ge.method==="next")ge.sent=ge._sent=ge.arg;else if(ge.method==="throw"){if(Le===F)throw Le=te,ge.arg;ge.dispatchException(ge.arg)}else ge.method==="return"&&ge.abrupt("return",ge.arg);Le=G;var Ye=H(Re,ye,ge);if(Ye.type==="normal"){if(Le=ge.done?te:q,Ye.arg===X)continue;return{value:Ye.arg,done:ge.done}}else Ye.type==="throw"&&(Le=te,ge.method="throw",ge.arg=Ye.arg)}}}function _e(Re,ye){var ge=ye.method,Le=Re.iterator[ge];if(Le===n)return ye.delegate=null,ge==="throw"&&Re.iterator.return&&(ye.method="return",ye.arg=n,_e(Re,ye),ye.method==="throw")||ge!=="return"&&(ye.method="throw",ye.arg=new TypeError("The iterator does not provide a '"+ge+"' method")),X;var et=H(Le,Re.iterator,ye.arg);if(et.type==="throw")return ye.method="throw",ye.arg=et.arg,ye.delegate=null,X;var vt=et.arg;if(!vt)return ye.method="throw",ye.arg=new TypeError("iterator result is not an object"),ye.delegate=null,X;if(vt.done)ye[Re.resultName]=vt.value,ye.next=Re.nextLoc,ye.method!=="return"&&(ye.method="next",ye.arg=n);else return vt;return ye.delegate=null,X}pe(se),R(se,C,"Generator"),R(se,_,function(){return this}),R(se,"toString",function(){return"[object Generator]"});function Ae(Re){var ye={tryLoc:Re[0]};1 in Re&&(ye.catchLoc=Re[1]),2 in Re&&(ye.finallyLoc=Re[2],ye.afterLoc=Re[3]),this.tryEntries.push(ye)}function le(Re){var ye=Re.completion||{};ye.type="normal",delete ye.arg,Re.completion=ye}function oe(Re){this.tryEntries=[{tryLoc:"root"}],Re.forEach(Ae,this),this.reset(!0)}r.keys=function(Re){var ye=Object(Re),ge=[];for(var Le in ye)ge.push(Le);return ge.reverse(),function et(){for(;ge.length;){var vt=ge.pop();if(vt in ye)return et.value=vt,et.done=!1,et}return et.done=!0,et}};function Oe(Re){if(Re){var ye=Re[_];if(ye)return ye.call(Re);if(typeof Re.next=="function")return Re;if(!isNaN(Re.length)){var ge=-1,Le=function et(){for(;++ge<Re.length;)if(u.call(Re,ge))return et.value=Re[ge],et.done=!1,et;return et.value=n,et.done=!0,et};return Le.next=Le}}return{next:rs}}r.values=Oe;function rs(){return{value:n,done:!0}}return oe.prototype={constructor:oe,reset:function(Re){if(this.prev=0,this.next=0,this.sent=this._sent=n,this.done=!1,this.delegate=null,this.method="next",this.arg=n,this.tryEntries.forEach(le),!Re)for(var ye in this)ye.charAt(0)==="t"&&u.call(this,ye)&&!isNaN(+ye.slice(1))&&(this[ye]=n)},stop:function(){this.done=!0;var Re=this.tryEntries[0],ye=Re.completion;if(ye.type==="throw")throw ye.arg;return this.rval},dispatchException:function(Re){if(this.done)throw Re;var ye=this;function ge(ze,Ye){return vt.type="throw",vt.arg=Re,ye.next=ze,Ye&&(ye.method="next",ye.arg=n),!!Ye}for(var Le=this.tryEntries.length-1;Le>=0;--Le){var et=this.tryEntries[Le],vt=et.completion;if(et.tryLoc==="root")return ge("end");if(et.tryLoc<=this.prev){var xt=u.call(et,"catchLoc"),dt=u.call(et,"finallyLoc");if(xt&&dt){if(this.prev<et.catchLoc)return ge(et.catchLoc,!0);if(this.prev<et.finallyLoc)return ge(et.finallyLoc)}else if(xt){if(this.prev<et.catchLoc)return ge(et.catchLoc,!0)}else if(dt){if(this.prev<et.finallyLoc)return ge(et.finallyLoc)}else throw new Error("try statement without catch or finally")}}},abrupt:function(Re,ye){for(var ge=this.tryEntries.length-1;ge>=0;--ge){var Le=this.tryEntries[ge];if(Le.tryLoc<=this.prev&&u.call(Le,"finallyLoc")&&this.prev<Le.finallyLoc){var et=Le;break}}et&&(Re==="break"||Re==="continue")&&et.tryLoc<=ye&&ye<=et.finallyLoc&&(et=null);var vt=et?et.completion:{};return vt.type=Re,vt.arg=ye,et?(this.method="next",this.next=et.finallyLoc,X):this.complete(vt)},complete:function(Re,ye){if(Re.type==="throw")throw Re.arg;return Re.type==="break"||Re.type==="continue"?this.next=Re.arg:Re.type==="return"?(this.rval=this.arg=Re.arg,this.method="return",this.next="end"):Re.type==="normal"&&ye&&(this.next=ye),X},finish:function(Re){for(var ye=this.tryEntries.length-1;ye>=0;--ye){var ge=this.tryEntries[ye];if(ge.finallyLoc===Re)return this.complete(ge.completion,ge.afterLoc),le(ge),X}},catch:function(Re){for(var ye=this.tryEntries.length-1;ye>=0;--ye){var ge=this.tryEntries[ye];if(ge.tryLoc===Re){var Le=ge.completion;if(Le.type==="throw"){var et=Le.arg;le(ge)}return et}}throw new Error("illegal catch attempt")},delegateYield:function(Re,ye,ge){return this.delegate={iterator:Oe(Re),resultName:ye,nextLoc:ge},this.method==="next"&&(this.arg=n),X}},r}(f.exports);try{regeneratorRuntime=t}catch{typeof globalThis=="object"?globalThis.regeneratorRuntime=t:Function("r","regeneratorRuntime = r")(t)}})(gA);var xp={exports:{}};(function(f){(function(t,r){f.exports?f.exports=r():t.log=r()})(Lt,function(){var t=function(){},r="undefined",l=typeof window!==r&&typeof window.navigator!==r&&/Trident\/|MSIE /.test(window.navigator.userAgent),u=["trace","debug","info","warn","error"];function s(q,G){var te=q[G];if(typeof te.bind=="function")return te.bind(q);try{return Function.prototype.bind.call(te,q)}catch{return function(){return Function.prototype.apply.apply(te,[q,arguments])}}}function n(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function g(q){return q==="debug"&&(q="log"),typeof console===r?!1:q==="trace"&&l?n:console[q]!==void 0?s(console,q):console.log!==void 0?s(console,"log"):t}function _(q,G){for(var te=0;te<u.length;te++){var X=u[te];this[X]=te<q?t:this.methodFactory(X,q,G)}this.log=this.debug}function v(q,G,te){return function(){typeof console!==r&&(_.call(this,G,te),this[q].apply(this,arguments))}}function C(q,G,te){return g(q)||v.apply(this,arguments)}function R(q,G,te){var X=this,we;G=G??"WARN";var Q="loglevel";typeof q=="string"?Q+=":"+q:typeof q=="symbol"&&(Q=void 0);function re(se){var pe=(u[se]||"silent").toUpperCase();if(!(typeof window===r||!Q)){try{window.localStorage[Q]=pe;return}catch{}try{window.document.cookie=encodeURIComponent(Q)+"="+pe+";"}catch{}}}function ke(){var se;if(!(typeof window===r||!Q)){try{se=window.localStorage[Q]}catch{}if(typeof se===r)try{var pe=window.document.cookie,me=pe.indexOf(encodeURIComponent(Q)+"=");me!==-1&&(se=/^([^;]+)/.exec(pe.slice(me))[1])}catch{}return X.levels[se]===void 0&&(se=void 0),se}}function Ne(){if(!(typeof window===r||!Q)){try{window.localStorage.removeItem(Q);return}catch{}try{window.document.cookie=encodeURIComponent(Q)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}X.name=q,X.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},X.methodFactory=te||C,X.getLevel=function(){return we},X.setLevel=function(se,pe){if(typeof se=="string"&&X.levels[se.toUpperCase()]!==void 0&&(se=X.levels[se.toUpperCase()]),typeof se=="number"&&se>=0&&se<=X.levels.SILENT){if(we=se,pe!==!1&&re(se),_.call(X,se,q),typeof console===r&&se<X.levels.SILENT)return"No console available for logging"}else throw"log.setLevel() called with invalid level: "+se},X.setDefaultLevel=function(se){G=se,ke()||X.setLevel(se,!1)},X.resetLevel=function(){X.setLevel(G,!1),Ne()},X.enableAll=function(se){X.setLevel(X.levels.TRACE,se)},X.disableAll=function(se){X.setLevel(X.levels.SILENT,se)};var Z=ke();Z==null&&(Z=G),X.setLevel(Z,!1)}var D=new R,H={};D.getLogger=function(G){if(typeof G!="symbol"&&typeof G!="string"||G==="")throw new TypeError("You must supply a name when creating a logger.");var te=H[G];return te||(te=H[G]=new R(G,D.getLevel(),D.methodFactory)),te};var F=typeof window!==r?window.log:void 0;return D.noConflict=function(){return typeof window!==r&&window.log===D&&(window.log=F),D},D.getLoggers=function(){return H},D.default=D,D})})(xp);var zs=xp.exports;const Hn=()=>`${new Date().toISOString()} | metrics`,Fn=(f,t,r)=>`${f} | ${t} | ${r}`;zs.setDefaultLevel(zs.levels.TRACE);const vA=f=>{zs.info(Fn(Hn(),"log ",`set log level to ${f?"verbose":"info"}`)),zs.setLevel(f?zs.levels.TRACE:zs.levels.INFO)},yA=f=>{const t=[...Object.keys(zs.levels)];t.includes(f)?(zs.info(Fn(Hn(),"log ",`update log level to ${f.toLowerCase()}`)),zs.setLevel(f)):zs.warn(Fn(Hn(),"log ","Incorrect log level please choose one of "),t)},Ot=(f,t,r)=>{r?zs.debug(Fn(Hn(),f,t),r):zs.debug(Fn(Hn(),f,t))},Fd=(f,t)=>{zs.info(Fn(Hn(),f,t))},xa=(f,t)=>{zs.info(Fn(Hn(),f,t))},qu=(f,t)=>{zs.warn(Fn(Hn(),f,t))},Tl=(f,t)=>{zs.error(Fn(Hn(),f,t))};function TA(f){return Math.floor(Math.random()*f).toString()}function Op(f,t){let r=t;return f.forEach(l=>{r=r.replace(l,"")}),r}function SA(f,t){let r="";for(let l=0;l<t;l+=1)r+=f[TA(f.length)];return r}function bA({length:f=20,useLetters:t=!0,useNumbers:r=!0,includeSymbols:l=[],excludeSymbols:u=[]}={}){let s="abcdefghijklmnopqrstuvwxyz",n="0123456789",g=[],_=[],v=[];return t&&(u.length&&(s=Op(u,s)),_=s.split("")),r&&(u.length&&(n=Op(u,n)),v=n.split("")),g=[..._,...v,...l],SA(g,f)}var wA=bA;const yo=Ht(wA),EA=()=>"WebRTCMetrics",CA=()=>"5.0.3",zt={INBOUND:"inbound",OUTBOUND:"outbound"},Bn={IDLE:"idle",RUNNING:"running",MUTED:"muted"},To={NEW:"new",CHECKING:"checking",CONNECTED:"connected",COMPLETED:"completed",DISCONNECTED:"disconnected",FAILED:"failed",CLOSED:"closed"},AA=()=>({...{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:[]}}),Dp={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:zt.INBOUND},kp={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:zt.OUTBOUND},Np={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:zt.INBOUND},Mp={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:zt.OUTBOUND},IA=f=>{const t={pname:"",call_id:"",user_id:"",timestamp:null,count:0,audio:{},video:{},network:{infrastructure:3,local_candidate_id:"",local_candidate_type:"",local_candidate_protocol:"",local_candidate_relay_protocol:"",remote_candidate_id:"",remote_candidate_type:"",remote_candidate_protocol:""},data:{total_KBytes_in:0,total_KBytes_out:0,delta_KBytes_in:0,delta_KBytes_out:0,delta_kbs_in:0,delta_kbs_out:0,delta_kbs_bandwidth_in:0,delta_kbs_bandwidth_out:0,delta_rtt_connectivity_ms:null,total_rtt_connectivity_ms:0,total_rtt_connectivity_measure:0},experimental:{time_to_measure_ms:0}};if(f){const r={...f,audio:{},video:{},data:{...f.data},network:{...f.network},experimental:{...f.experimental}};return Object.keys(f.audio).forEach(l=>{r.audio[l]={...f.audio[l]}}),Object.keys(f.video).forEach(l=>{r.video[l]={...f.video[l]}}),r}return{...t,audio:{},video:{},data:{...t.data},network:{...t.network},experimental:{...t.experimental}}},RA={refreshEvery:2e3,startAfter:0,stopAfter:-1,verbose:!1,pname:`p-${yo()}`,cid:`c-${yo()}`,uid:`u-${yo()}`,record:!1,ticket:!0},Ur={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"},Te={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"},ue={SUCCEEDED:"succeeded",AUDIO:"audio",VIDEO:"video"},So={ETHERNET:0,CELLULAR_5G:2,WIFI:3,CELLULAR_4G:5,CELLULAR:10},Bd={ETHERNET:"ethernet",CELLULAR_4G:"cellular",WIFI:"wifi"},Me={AUDIO:"audio",VIDEO:"video",NETWORK:"network",DATA:"data"},zd="config ",$A=(f,t={},r)=>{const l={...r,...t};return t.pname||qu(zd,`Argument [String] 'cfg.pname' for the peerConnection name or id is missing - use generated '${r.pname}'`),t.cid||qu(zd,`Argument [String] 'cfg.cid' for the call name or id is missing - use generated '${r.cid}'`),t.uid||qu(zd,`Argument [String] 'cfg.uid' for the user name or id is missing - use generated '${r.uid}'`),l.pc=f,l},xA=(f={})=>{const t={...RA,...f};return t.name=EA(),t.version=CA(),t},bo=(f,t,r,l=!1,u)=>{let s=f.map(n=>{if(!r)return n[t];if(!u)return n[t][r];const g=n[t][u];return g?g[r]:null});return s=s.filter(n=>l?Number.isFinite(n)&&n>0:Number.isFinite(n)),s.length===0?[]:s},$i=f=>f.reduce((t,r)=>t+r,0)/f.length,OA=()=>`probe-${yo()}`,DA=()=>`coltr-${yo()}`,Up=f=>new Promise(t=>setTimeout(t,f)),Vd=(f,t,r)=>{t?f.call(t,r):f(r)},es=(f,t,r,l)=>{const u=bo(f,t,r,!0,l);if(u.length===0)return null;const s=u.reduce((v,C)=>v+C,0)/u.length;return s===0?null:u.map(v=>Math.abs(s-v)).reduce((v,C)=>v+C,0)/u.length*100/s},is=(f,t,r,l=!1,u)=>{const s=bo(f,t,r,l,u);return s.length===0?null:s.reduce((n,g)=>n+g,0)/s.length},Oa=(f,t,r)=>bo(f,t,r).reduce((u,s)=>u+s,0),ts=(f,t,r,l)=>{const u=bo(f,t,r,!0,l);return u.length===0?null:Math.min(...u)},ss=(f,t,r,l)=>{const u=bo(f,t,r,!1,l);return u.length===0?null:Math.max(...u)},Ps=(f,t,r,l)=>{const u=f.slice().pop();if(!u)return null;if(!r)return u[t];if(!l)return u[t][r];const s=u[t][l];return s?s[r]:null},kA=f=>f.slice().pop(),Ss=(f,t,r)=>{if(!t)return null;const l={};let u=t[ue.AUDIO][f];u||(u=r===zt.INBOUND?{...Dp}:{...kp}),l[ue.AUDIO]=u;let s=t[ue.VIDEO][f];return s||(s=r===zt.INBOUND?{...Np}:{...Mp}),l[ue.VIDEO]=s,l},wo="exporter ",NA="2.0",Pp=(f,t,r)=>{if(!f||f.length===0)return 0;const l=f[f.length-1];if(!l)return 0;const u=l[t][r];if(u){const s=u.total_rtt_ms_out,n=u.total_rtt_measure_out;return!n||!s?is(f,t,"delta_rtt_ms_out",!1,r):Number(s/n)}return null},MA=(f,t)=>{if(!f||f.length===0)return 0;const r=f[f.length-1];if(!r)return 0;const l=r[t].total_rtt_connectivity_ms,u=r[t].total_rtt_connectivity_measure;return!u||!l?is(f,t,"delta_rtt_connectivity_ms"):Number(l/u)},UA=f=>Ps(f,"network","local_candidate_type")!=="relay"?`direct/${Ps(f,"network","local_candidate_protocol")}`:`turn/${Ps(f,"network","local_candidate_relay_protocol")}`,PA=f=>{const t=Ps(f,"network","remote_candidate_type"),r=Ps(f,"network","remote_candidate_protocol");return t!=="relay"?`direct/${r}`:`turn/${r}`};class LA{constructor(t){this._start=null,this._end=null,this._cfg=t,this._referenceReport=null,this._reports=[],this._events=[]}start(){Fd(wo,"start() - start exporter...");const t=new Date;return this._start=t.toJSON(),t}stop(){Fd(wo,"stop() - stop exporter...");const t=new Date;return this._end=t.toJSON(),t}saveReferenceReport(t){this._referenceReport=t}getReferenceReport(){return this._referenceReport}addReport(t){this._cfg.ticket&&(Ot(wo,`addReport() - add report to exporter at ${t.timestamp}`),this._reports.push(t))}addCustomEvent(t){this._events.push(t)}reset(){Fd(wo,"resetReports() - reset reports"),this._reports=[],this._referenceReport=null,this._start=null,this._end=null}get ticket(){Ot(wo,"ticket() - generate ticket");const t=Ps(this._reports,"audio","total_packets_lost_in"),r=Ps(this._reports,"audio","total_packets_in"),l=Ps(this._reports,"video","total_packets_lost_in"),u=Ps(this._reports,"video","total_packets_in"),s={},n=kA(this._reports);return n&&(Object.keys(n[ue.AUDIO]).forEach(g=>{const _=n[ue.AUDIO][g];if(s[_.ssrc]={type:ue.AUDIO,direction:_.direction},_.direction===zt.INBOUND){const v={avg:is(this._reports,ue.AUDIO,"delta_jitter_ms_in",!1,g),min:ts(this._reports,ue.AUDIO,"delta_jitter_ms_in",g),max:ss(this._reports,ue.AUDIO,"delta_jitter_ms_in",g),volatility:es(this._reports,ue.AUDIO,"delta_jitter_ms_in",g),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},C={avg:is(this._reports,ue.AUDIO,"delta_kbs_in",!1,g),min:ts(this._reports,ue.AUDIO,"delta_kbs_in",g),max:ss(this._reports,ue.AUDIO,"delta_kbs_in",g),volatility:es(this._reports,ue.AUDIO,"delta_kbs_in",g),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},R={avg:is(this._reports,ue.AUDIO,"delta_KBytes_in",!1,g),min:ts(this._reports,ue.AUDIO,"delta_KBytes_in",g),max:ss(this._reports,ue.AUDIO,"delta_KBytes_in",g),volatility:es(this._reports,ue.AUDIO,"delta_KBytes_in",g),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},D={emodel:{avg:is(this._reports,ue.AUDIO,"mos_emodel_in",!1,g),min:ts(this._reports,ue.AUDIO,"mos_emodel_in",g),max:ss(this._reports,ue.AUDIO,"mos_emodel_in",g),volatility:es(this._reports,ue.AUDIO,"mos_emodel_in",g)},effective:{avg:is(this._reports,ue.AUDIO,"mos_in",!1,g),min:ts(this._reports,ue.AUDIO,"mos_in",g),max:ss(this._reports,ue.AUDIO,"mos_in",g),volatility:es(this._reports,ue.AUDIO,"mos_in",g)},_unit:{avg:"number (1-5)",min:"number (1-5)",max:"number (1-5)",volatility:"percent"}},H=Ps(this._reports,ue.AUDIO,"total_packets_lost_in",g),F=Ps(this._reports,ue.AUDIO,"total_packets_in",g),q={lost:H,avg:Math.round((H/(H+F)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};s[g].jitter=v,s[g].mos=D,s[g].traffic=R,s[g].bitrate=C,s[g].loss=q}else{const v={avg:is(this._reports,ue.AUDIO,"delta_jitter_ms_out",!1,g),min:ts(this._reports,ue.AUDIO,"delta_jitter_ms_out",g),max:ss(this._reports,ue.AUDIO,"delta_jitter_ms_out",g),volatility:es(this._reports,ue.AUDIO,"delta_jitter_ms_out",g),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},C={avg:is(this._reports,ue.AUDIO,"delta_kbs_out",!1,g),min:ts(this._reports,ue.AUDIO,"delta_kbs_out",g),max:ss(this._reports,ue.AUDIO,"delta_kbs_out",g),volatility:es(this._reports,ue.AUDIO,"delta_kbs_out",g),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},R={avg:is(this._reports,ue.AUDIO,"delta_KBytes_out",!1,g),min:ts(this._reports,ue.AUDIO,"delta_KBytes_out",g),max:ss(this._reports,ue.AUDIO,"delta_KBytes_out",g),volatility:es(this._reports,ue.AUDIO,"delta_KBytes_out",g),_unit:{avg:"KB",min:"KB",max:"KB",bitrate:"kbs",volatility:"percent"}},D={avg:Pp(this._reports,ue.AUDIO,g),min:ts(this._reports,ue.AUDIO,"delta_rtt_ms_out",g),max:ss(this._reports,ue.AUDIO,"delta_rtt_ms_out",g),volatility:es(this._reports,ue.AUDIO,"delta_rtt_ms_out",g),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},H=Ps(this._reports,ue.AUDIO,"total_packets_lost_out",g),F=Ps(this._reports,ue.AUDIO,"total_packets_out",g),q={lost:H,avg:Math.round((H/(H+F)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}},G={emodel:{avg:is(this._reports,ue.AUDIO,"mos_emodel_out",!1,g),min:ts(this._reports,ue.AUDIO,"mos_emodel_out",g),max:ss(this._reports,ue.AUDIO,"mos_emodel_out",g),volatility:es(this._reports,ue.AUDIO,"mos_emodel_out",g)},effective:{avg:is(this._reports,ue.AUDIO,"mos_out",!1,g),min:ts(this._reports,ue.AUDIO,"mos_out",g),max:ss(this._reports,ue.AUDIO,"mos_out",g),volatility:es(this._reports,ue.AUDIO,"mos_out",g)},_unit:{avg:"number (1-5)",min:"number (1-5)",max:"number (1-5)",volatility:"percent"}};s[g].jitter=v,s[g].rtt=D,s[g].traffic=R,s[g].bitrate=C,s[g].loss=q,s[g].mos=G}}),Object.keys(n[ue.VIDEO]).forEach(g=>{const _=n[ue.VIDEO][g];if(s[g]={type:ue.VIDEO,direction:_.direction},_.direction===zt.INBOUND){const v={avg:is(this._reports,ue.VIDEO,"delta_jitter_ms_in",!1,g),min:ts(this._reports,ue.VIDEO,"delta_jitter_ms_in",g),max:ss(this._reports,ue.VIDEO,"delta_jitter_ms_in",g),volatility:es(this._reports,ue.VIDEO,"delta_jitter_ms_in",g),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},C={avg:is(this._reports,ue.VIDEO,"delta_kbs_in",!1,g),min:ts(this._reports,ue.VIDEO,"delta_kbs_in",g),max:ss(this._reports,ue.VIDEO,"delta_kbs_in",g),volatility:es(this._reports,ue.VIDEO,"delta_kbs_in",g),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},R={avg:is(this._reports,ue.VIDEO,"delta_KBytes_in",!1,g),min:ts(this._reports,ue.VIDEO,"delta_KBytes_in",g),max:ss(this._reports,ue.VIDEO,"delta_KBytes_in",g),volatility:es(this._reports,ue.VIDEO,"delta_KBytes_in",g),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},D=Ps(this._reports,ue.VIDEO,"total_packets_lost_in",g),H=Ps(this._reports,ue.VIDEO,"total_packets_in",g),F={lost:D,avg:Math.round((D/(D+H)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};s[g].jitter=v,s[g].traffic=R,s[g].bitrate=C,s[g].loss=F}else{const v={avg:is(this._reports,ue.VIDEO,"delta_jitter_ms_out",!1,g),min:ts(this._reports,ue.VIDEO,"delta_jitter_ms_out",g),max:ss(this._reports,ue.VIDEO,"delta_jitter_ms_out",g),volatility:es(this._reports,ue.VIDEO,"delta_jitter_ms_out",g),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},C={avg:is(this._reports,ue.VIDEO,"delta_kbs_out",!1,g),min:ts(this._reports,ue.VIDEO,"delta_kbs_out",g),max:ss(this._reports,ue.VIDEO,"delta_kbs_out",g),volatility:es(this._reports,ue.VIDEO,"delta_kbs_out",g),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},R={avg:is(this._reports,ue.VIDEO,"delta_KBytes_out",!1,g),min:ts(this._reports,ue.VIDEO,"delta_KBytes_out",g),max:ss(this._reports,ue.VIDEO,"delta_KBytes_out",g),volatility:es(this._reports,ue.VIDEO,"delta_KBytes_out",g),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},D={avg:Pp(this._reports,ue.VIDEO,g),min:ts(this._reports,ue.VIDEO,"delta_rtt_ms_out",g),max:ss(this._reports,ue.VIDEO,"delta_rtt_ms_out",g),volatility:es(this._reports,ue.VIDEO,"delta_rtt_ms_out",g),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},H=Ps(this._reports,ue.VIDEO,"total_packets_lost_out",g),F=Ps(this._reports,ue.VIDEO,"total_packets_out",g),q={lost:H,avg:Math.round((H/(H+F)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};s[g].jitter=v,s[g].rtt=D,s[g].traffic=R,s[g].bitrate=C,s[g].loss=q}})),{version:NA,configuration:{frequency:this._cfg.refreshEvery},started:this._start,ended:this._end,ua:{agent:navigator.userAgent,pname:this._cfg.pname,user_id:this._cfg.uid},call:{call_id:this._cfg.cid,events:this._events},details:{count:this._reports.length,reports:this._cfg.record?this._reports:[],reference:this._referenceReport||null},ssrc:s,data:{rtt:{avg:MA(this._reports,"data"),min:ts(this._reports,"data","delta_rtt_connectivity_ms"),max:ss(this._reports,"data","delta_rtt_connectivity_ms"),volatility:es(this._reports,"data","delta_rtt_connectivity_ms"),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},packetsLost:{audio:{in:{avg:Math.round((t/(t+r)*100||0)*100)/100}},video:{in:{avg:Math.round((l/(l+u)*100||0)*100)/100}},unit:{avg:"percent"}},bitrate:{in:{avg:is(this._reports,"data","delta_kbs_in"),min:ts(this._reports,"data","delta_kbs_in"),max:ss(this._reports,"data","delta_kbs_in"),volatility:es(this._reports,"data","delta_kbs_in")},out:{avg:is(this._reports,"data","delta_kbs_out"),min:ts(this._reports,"data","delta_kbs_out"),max:ss(this._reports,"data","delta_kbs_out"),volatility:es(this._reports,"data","delta_kbs_out")},unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},traffic:{in:{avg:is(this._reports,"data","delta_KBytes_in"),min:ts(this._reports,"data","delta_KBytes_in"),max:ss(this._reports,"data","delta_KBytes_in"),volatility:es(this._reports,"data","delta_KBytes_in")},out:{avg:is(this._reports,"data","delta_KBytes_out"),min:ts(this._reports,"data","delta_KBytes_out"),max:ss(this._reports,"data","delta_KBytes_out"),volatility:es(this._reports,"data","delta_KBytes_out")},unit:{avg:"KBytes",min:"KBytes",max:"KBytes",volatility:"percent"}},network:{localConnection:UA(this._reports),remoteConnection:PA(this._reports)}}}}updateConfig(t){this._cfg=t}getLastReport(){return this._reports.slice().pop()||null}getBeforeLastReport(){const t=this._reports.slice();return t.pop(),t.pop()||null}getReportsNumber(){return this._reports.length}}const xi="extractor ",Lp=(f,t,r,l)=>{let u=!1;const s=l[t].total_rtt_ms_out,n=l[t].total_rtt_measure_out,g=r?r[t].total_rtt_ms_out:0,_=r?r[t].total_rtt_measure_out:0,v={rtt:null,totalRTT:s,totalRTTMeasurements:n};if(f[Te.TIMESTAMP]===l[t].timestamp_out||!Object.prototype.hasOwnProperty.call(f,Te.ROUND_TRIP_TIME)||Object.prototype.hasOwnProperty.call(f,Te.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS)&&(u=!0,Number(f[Te.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])===0||Number(f[Te.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])-_===n))return v;const C=1e3*Number(f[Te.ROUND_TRIP_TIME]);let R=s+C,D=n+1;return u&&(R=1e3*Number(f[Te.TOTAL_ROUND_TRIP_TIME])-g,D=Number(f[Te.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])-_),{rtt:C,totalRTT:R,totalRTTMeasurements:D}},HA=(f,t,r,l)=>{if(!Object.prototype.hasOwnProperty.call(f,Te.CURRENT_ROUND_TRIP_TIME))return{rtt:null,totalRTT:l[t].total_rtt_connectivity_ms,totalRTTMeasurements:l[t].total_rtt_connectivity_measure};const u=1e3*Number(f[Te.CURRENT_ROUND_TRIP_TIME]);let s=l[t].total_rtt_connectivity_ms+u,n=l[t].total_rtt_connectivity_measure+1;return Object.prototype.hasOwnProperty.call(f,Te.TOTAL_ROUND_TRIP_TIME)&&(s=1e3*Number(f[Te.TOTAL_ROUND_TRIP_TIME])-(r?r[t].total_rtt_connectivity_ms:0)),Object.prototype.hasOwnProperty.call(f,Te.RESPONSES_RECEIVED)&&(n=Number(f[Te.RESPONSES_RECEIVED])-(r?r[t].total_rtt_connectivity_measure:0)),{rtt:u,totalRTT:s,totalRTTMeasurements:n}},ju=(f,t,r)=>f[Te.TIMESTAMP]===r[t].timestamp_out||!Object.prototype.hasOwnProperty.call(f,Te.JITTER)?null:1e3*(Number(f[Te.JITTER])||0),FA=(f,t)=>{if(!Object.prototype.hasOwnProperty.call(f,Te.FRAMES_DECODED)||!Object.prototype.hasOwnProperty.call(f,Te.TOTAL_DECODE_TIME))return{delta_ms_decode_frame:t[ue.VIDEO].delta_ms_decode_frame_in,frames_decoded:t[ue.VIDEO].total_frames_decoded_in,total_decode_time:t[ue.VIDEO].total_time_decoded_in};const r=f[Te.FRAMES_DECODED],l=f[Te.TOTAL_DECODE_TIME],u=l-t[ue.VIDEO].total_time_decoded_in,s=r-t[ue.VIDEO].total_frames_decoded_in;return{delta_ms_decode_frame:s>0?u*1e3/s:0,frames_decoded:r,total_decode_time:l}},BA=(f,t)=>{if(!Object.prototype.hasOwnProperty.call(f,Te.FRAMES_ENCODED)||!Object.prototype.hasOwnProperty.call(f,Te.TOTAL_ENCODE_TIME))return{delta_ms_encode_frame:t[ue.VIDEO].delta_ms_encode_frame_out,frames_encoded:t[ue.VIDEO].total_frames_encoded_out,total_encode_time:t[ue.VIDEO].total_time_encoded_out};const r=f[Te.FRAMES_ENCODED],l=f[Te.TOTAL_ENCODE_TIME],u=l-t[ue.VIDEO].total_time_encoded_out,s=r-t[ue.VIDEO].total_frames_encoded_out;return{delta_ms_encode_frame:s>0&&u?u*1e3/s:0,frames_encoded:r,total_encode_time:l}},Hp=(f,t,r,l)=>{if(!Object.prototype.hasOwnProperty.call(f,Te.PACKETS_SENT)||!Object.prototype.hasOwnProperty.call(f,Te.BYTES_SENT))return{packetsSent:r[t].total_packets_out,packetsLost:r[t].total_packets_lost_out,bytesSent:r[t].total_KBytes_out};const u=Number(f[Te.PACKETS_SENT])||0-(l?l[t].total_packets_out:0),s=u-r[t].total_packets_out,n=Number(f[Te.BYTES_SENT])/1024-(l?l[t].total_KBytes_out:0),g=n-r[t].total_KBytes_out,_=f[Te.TIMESTAMP]||Date.now(),v=l?l.timestamp:null;let C=r.timestamp;!C&&v&&(C=v);const R=C?_-C:0,D=R>0?g*.008*1024/R*1e3:0;return{packetsSent:u,deltaPacketsSent:s,KBytesSent:n,deltaKBytesSent:g,kbsSent:D}},Fp=(f,t,r,l)=>{let u=r[t].total_packets_lost_out,s=0,n=0;return Object.prototype.hasOwnProperty.call(f,Te.PACKETS_LOST)&&(u=Number(f[Te.PACKETS_LOST])||0-(l?l[t].total_packets_lost_out:0),s=u-r[t].total_packets_lost_out),Object.prototype.hasOwnProperty.call(f,Te.FRACTION_LOST)&&(n=Number(100*f[Te.FRACTION_LOST])),{packetsLost:u,deltaPacketsLost:s,fractionLost:n}},Bp=(f,t,r,l)=>{if(!Object.prototype.hasOwnProperty.call(f,Te.PACKETS_RECEIVED)||!Object.prototype.hasOwnProperty.call(f,Te.PACKETS_LOST)||!Object.prototype.hasOwnProperty.call(f,Te.BYTES_RECEIVED))return{percent_packets_lost:r[t].percent_packets_lost_in,packetsReceived:r[t].total_packets_in,packetsLost:r[t].total_packets_lost_in,bytesReceived:r[t].total_KBytes_in};const u=Number(f[Te.PACKETS_RECEIVED])||0-(l?l[t].total_packets_in:0),s=Number(f[Te.PACKETS_LOST])||0-(l?l[t].total_packets_lost_in:0),n=s-r[t].total_packets_lost_in,g=u-r[t].total_packets_in,_=u!==r[t].total_packets_in?n*100/(n+g):0,v=Number(f[Te.BYTES_RECEIVED])/1024-(l?l[t].total_KBytes_in:0),C=v-r[t].total_KBytes_in,R=f[Te.TIMESTAMP]||Date.now(),D=l?l.timestamp:null;let H=r.timestamp;!H&&D&&(H=D);const F=H?R-H:0,q=F>0?C*.008*1024/F*1e3:0;return{percentPacketsLost:_,packetsReceived:u,deltaPacketsReceived:g,packetsLost:s,deltaPacketsLost:n,KBytesReceived:v,deltaKBytesReceived:C,kbsReceived:q}},zA=f=>f[Te.CANDIDATE_TYPE]!=="relay"?"":f[Te.RELAY_PROTOCOL]||"",VA=f=>{if(!Object.prototype.hasOwnProperty.call(f,Te.NETWORK_TYPE))return So.WIFI;switch(f[Te.NETWORK_TYPE]){case Bd.ETHERNET:return So.ETHERNET;case Bd.CELLULAR_4G:return So.CELLULAR_4G;case Bd.WIFI:return So.WIFI;default:return So.CELLULAR}},zp=f=>!Object.prototype.hasOwnProperty.call(f,Te.FRAME_HEIGHT)||!Object.prototype.hasOwnProperty.call(f,Te.FRAME_WIDTH)?{width:null,height:null,framerate:null}:{width:f[Te.FRAME_WIDTH]||null,height:f[Te.FRAME_HEIGHT]||null,framerate:f[Te.FRAMES_PER_SECOND]},qA=f=>{const t=Object.prototype.hasOwnProperty.call(f,Te.QUALITY_LIMITATION_REASON)?f[Te.QUALITY_LIMITATION_REASON]:null,r=Object.prototype.hasOwnProperty.call(f,Te.QUALITY_LIMITATION_RESOLUTION_CHANGES)?f[Te.QUALITY_LIMITATION_RESOLUTION_CHANGES]:null,l=Object.prototype.hasOwnProperty.call(f,Te.QUALITY_LIMITATION_DURATIONS)?f[Te.QUALITY_LIMITATION_DURATIONS]:null;return l&&Object.keys(l).forEach(u=>{l[u]>1e3&&(l[u]=Number(l[u]/1e3))}),{reason:t,durations:l,resolutionChanges:r}},jA=(f,t,r)=>{if(!Object.prototype.hasOwnProperty.call(f,Te.PLI)||!Object.prototype.hasOwnProperty.call(f,Te.NACK))return{pliCount:t.total_pli_sent_in,nackCount:t.total_nack_sent_in,deltaPliCount:0,deltaNackCount:0};const l=(f[Te.PLI]||0)-(r?r[ue.VIDEO].total_pli_sent_in:0),u=(f[Te.NACK]||0)-(r?r[ue.VIDEO].total_nack_sent_in:0);return{pliCount:l,nackCount:u,deltaPliCount:l-t[ue.VIDEO].total_pli_sent_in,deltaNackCount:u-t[ue.VIDEO].total_nack_sent_in}},GA=(f,t,r)=>{if(!Object.prototype.hasOwnProperty.call(f,Te.PLI)||!Object.prototype.hasOwnProperty.call(f,Te.NACK))return{pliCount:t.total_pli_received_out,nackCount:t.total_nack_received_out,deltaPliCount:0,deltaNackCount:0};const l=(f[Te.PLI]||0)-(r?r[ue.VIDEO].total_pli_received_out:0),u=(f[Te.NACK]||0)-(r?r[ue.VIDEO].total_nack_received_out:0);return{pliCount:l,nackCount:u,deltaPliCount:l-t[ue.VIDEO].total_pli_received_out,deltaNackCount:u-t[ue.VIDEO].total_nack_received_out}},WA=f=>({channels:f[Te.CHANNELS]||null,clock_rate:f[Te.CLOCK_RATE]||null,mime_type:f[Te.MIME_TYPE]||null,sdp_fmtp_line:f[Te.SDP_FMTP_LINE]||null}),KA=f=>({clock_rate:f[Te.CLOCK_RATE]||null,mime_type:f[Te.MIME_TYPE]||null}),YA=(f,t,r)=>{const l=(f[Te.BYTES_RECEIVED]||0)/1024-(r?r.data.total_KBytes_in:0),u=(f[Te.BYTES_SENT]||0)/1024-(r?r.data.total_KBytes_out:0),s=f[Te.TIMESTAMP]||Date.now(),n=l-t.data.total_KBytes_in,g=u-t.data.total_KBytes_out,_=r?r.timestamp:null;let v=t.timestamp;!v&&_&&(v=_);const C=v?s-v:0,R=C>0?n*.008*1024/C*1e3:0,D=C>0?g*.008*1024/C*1e3:0;return{total_KBytes_received:l,total_KBytes_sent:u,delta_KBytes_received:n,delta_KBytes_sent:g,kbs_speed_received:R,kbs_speed_sent:D}},JA=f=>{const t=f[Te.AVAILABLE_INCOMING_BITRATE]/1024||0,r=f[Te.AVAILABLE_OUTGOING_BITRATE]/1024||0;return{kbs_incoming_bandwidth:t,kbs_outgoing_bandwidth:r}},QA=(f,t,r,l)=>{if(!f)return[];switch(f[Te.TYPE]){case Ur.CANDIDATE_PAIR:let u=!1;if(f[Te.NOMINATED]&&f[Te.STATE]===ue.SUCCEEDED&&(u=!0,Ot(xi,`analyze() - got stats ${f[Te.TYPE]} for ${r}`,f),Te.SELECTED in f&&!f[Te.SELECTED]&&(u=!1)),u){const n=f[Te.LOCAL_CANDIDATE_ID],g=f[Te.REMOTE_CANDIDATE_ID],_=YA(f,t,l),v=JA(f),C=HA(f,"data",l,t);return[{type:Me.NETWORK,value:{local_candidate_id:n}},{type:Me.NETWORK,value:{remote_candidate_id:g}},{type:Me.DATA,value:{total_KBytes_in:_.total_KBytes_received}},{type:Me.DATA,value:{total_KBytes_out:_.total_KBytes_sent}},{type:Me.DATA,value:{delta_KBytes_in:_.delta_KBytes_received}},{type:Me.DATA,value:{delta_KBytes_out:_.delta_KBytes_sent}},{type:Me.DATA,value:{delta_kbs_in:_.kbs_speed_received}},{type:Me.DATA,value:{delta_kbs_out:_.kbs_speed_sent}},{type:Me.DATA,value:{delta_kbs_bandwidth_in:v.kbs_incoming_bandwidth}},{type:Me.DATA,value:{delta_kbs_bandwidth_out:v.kbs_outgoing_bandwidth}},{type:Me.DATA,value:{delta_rtt_connectivity_ms:C.rtt}},{type:Me.DATA,value:{total_rtt_connectivity_ms:C.totalRTT}},{type:Me.DATA,value:{total_rtt_connectivity_measure:C.totalRTTMeasurements}}]}break;case Ur.LOCAL_CANDIDATE:if(f[Te.ID]===t.network.local_candidate_id)return[{type:Me.NETWORK,value:{infrastructure:VA(f)}},{type:Me.NETWORK,value:{local_candidate_type:f[Te.CANDIDATE_TYPE]||""}},{type:Me.NETWORK,value:{local_candidate_protocol:f[Te.PROTOCOL]||""}},{type:Me.NETWORK,value:{local_candidate_relay_protocol:zA(f)}}];break;case Ur.REMOTE_CANDIDATE:if(f[Te.ID]===t.network.remote_candidate_id)return[{type:Me.NETWORK,value:{remote_candidate_type:f[Te.CANDIDATE_TYPE]||""}},{type:Me.NETWORK,value:{remote_candidate_protocol:f[Te.PROTOCOL]||""}}];break;case Ur.INBOUND_RTP:{Ot(xi,`analyze() - got stats ${f[Te.TYPE]} for ${r}`,f);const n=f[Te.SSRC],g=Ss(n,t,zt.INBOUND);g&&(g.timestamp=t.timestamp);const _=Ss(n,l,zt.INBOUND);if(_&&(_.timestamp=l.timestamp),f[Te.MEDIA_TYPE]===ue.AUDIO){const v=Bp(f,ue.AUDIO,g,_),C=ju(f,ue.AUDIO,g),R=f[Te.CODEC_ID]||"";return[{ssrc:n,type:Me.AUDIO,value:{codec_id_in:R}},{ssrc:n,type:Me.AUDIO,value:{total_packets_in:v.packetsReceived}},{ssrc:n,type:Me.AUDIO,value:{delta_packets_in:v.deltaPacketsReceived}},{ssrc:n,type:Me.AUDIO,value:{total_packets_lost_in:v.packetsLost}},{ssrc:n,type:Me.AUDIO,value:{delta_packets_lost_in:v.deltaPacketsLost}},{ssrc:n,type:Me.AUDIO,value:{percent_packets_lost_in:v.percentPacketsLost}},{ssrc:n,type:Me.AUDIO,value:{total_KBytes_in:v.KBytesReceived}},{ssrc:n,type:Me.AUDIO,value:{delta_KBytes_in:v.deltaKBytesReceived}},{ssrc:n,type:Me.AUDIO,value:{delta_kbs_in:v.kbsReceived}},{ssrc:n,type:Me.AUDIO,value:{delta_jitter_ms_in:C}}]}if(f[Te.MEDIA_TYPE]===ue.VIDEO){const v=FA(f,g),C=Bp(f,ue.VIDEO,g,_),R=ju(f,ue.VIDEO,g),D=f[Te.DECODER_IMPLEMENTATION]||null,H=f[Te.CODEC_ID]||null,F=zp(f),q=jA(f,g,_);return[{ssrc:n,type:Me.VIDEO,value:{codec_id_in:H}},{ssrc:n,type:Me.VIDEO,value:{total_packets_in:C.packetsReceived}},{ssrc:n,type:Me.VIDEO,value:{delta_packets_in:C.deltaPacketsReceived}},{ssrc:n,type:Me.VIDEO,value:{total_packets_lost_in:C.packetsLost}},{ssrc:n,type:Me.VIDEO,value:{delta_packets_lost_in:C.deltaPacketsLost}},{ssrc:n,type:Me.VIDEO,value:{percent_packets_lost_in:C.percentPacketsLost}},{ssrc:n,type:Me.VIDEO,value:{total_KBytes_in:C.KBytesReceived}},{ssrc:n,type:Me.VIDEO,value:{delta_KBytes_in:C.deltaKBytesReceived}},{ssrc:n,type:Me.VIDEO,value:{delta_kbs_in:C.kbsReceived}},{ssrc:n,type:Me.VIDEO,value:{delta_jitter_ms_in:R}},{ssrc:n,type:Me.VIDEO,value:{decoder_in:D}},{ssrc:n,type:Me.VIDEO,value:{delta_ms_decode_frame_in:v.delta_ms_decode_frame}},{ssrc:n,type:Me.VIDEO,value:{total_frames_decoded_in:v.frames_decoded}},{ssrc:n,type:Me.VIDEO,value:{total_time_decoded_in:v.total_decode_time}},{ssrc:n,type:Me.VIDEO,value:{total_nack_sent_in:q.nackCount}},{ssrc:n,type:Me.VIDEO,value:{delta_nack_sent_in:q.deltaNackCount}},{ssrc:n,type:Me.VIDEO,value:{total_pli_sent_in:q.pliCount}},{ssrc:n,type:Me.VIDEO,value:{delta_pli_sent_in:q.deltaPliCount}},{ssrc:n,type:Me.VIDEO,value:{size_in:F}}]}break}case Ur.OUTBOUND_RTP:{Ot(xi,`analyze() - got stats ${f[Te.TYPE]} for ${r}`,f);const n=f[Te.SSRC],g=Ss(n,t,zt.OUTBOUND);g&&(g.timestamp=t.timestamp);const _=Ss(n,l,zt.OUTBOUND);if(_&&(_.timestamp=l.timestamp),f[Te.MEDIA_TYPE]===ue.AUDIO){const v=f[Te.CODEC_ID]||null,C=Hp(f,ue.AUDIO,g,_);return[{ssrc:n,type:Me.AUDIO,value:{codec_id_out:v}},{ssrc:n,type:Me.AUDIO,value:{total_packets_out:C.packetsSent}},{ssrc:n,type:Me.AUDIO,value:{delta_packets_out:C.deltaPacketsSent}},{ssrc:n,type:Me.AUDIO,value:{total_KBytes_out:C.KBytesSent}},{ssrc:n,type:Me.AUDIO,value:{delta_KBytes_out:C.deltaKBytesSent}},{ssrc:n,type:Me.AUDIO,value:{delta_kbs_out:C.kbsSent}}]}if(f[Te.MEDIA_TYPE]===ue.VIDEO){const v=f[Te.ENCODER_IMPLEMENTATION]||null,C=f[Te.CODEC_ID]||null,R=BA(f,g),D=zp(f),H=qA(f),F=GA(f,g,_),q=Hp(f,ue.VIDEO,g,_);return[{ssrc:n,type:Me.VIDEO,value:{codec_id_out:C}},{ssrc:n,type:Me.VIDEO,value:{total_packets_out:q.packetsSent}},{ssrc:n,type:Me.VIDEO,value:{delta_packets_out:q.deltaPacketsSent}},{ssrc:n,type:Me.VIDEO,value:{total_KBytes_out:q.KBytesSent}},{ssrc:n,type:Me.VIDEO,value:{delta_KBytes_out:q.deltaKBytesSent}},{ssrc:n,type:Me.VIDEO,value:{delta_kbs_out:q.kbsSent}},{ssrc:n,type:Me.VIDEO,value:{encoder_out:v}},{ssrc:n,type:Me.VIDEO,value:{delta_ms_encode_frame_out:R.delta_ms_encode_frame}},{ssrc:n,type:Me.VIDEO,value:{total_frames_encoded_out:R.frames_encoded}},{ssrc:n,type:Me.VIDEO,value:{total_time_encoded_out:R.total_encode_time}},{ssrc:n,type:Me.VIDEO,value:{total_nack_received_out:F.nackCount}},{ssrc:n,type:Me.VIDEO,value:{delta_nack_received_out:F.deltaNackCount}},{ssrc:n,type:Me.VIDEO,value:{total_pli_received_out:F.pliCount}},{ssrc:n,type:Me.VIDEO,value:{delta_pli_received_out:F.deltaPliCount}},{ssrc:n,type:Me.VIDEO,value:{size_out:D}},{ssrc:n,type:Me.VIDEO,value:{limitation_out:H}}]}break}case Ur.MEDIA_SOURCE:{Ot(xi,`analyze() - got stats ${f[Te.TYPE]} for ${r}`,f);break}case Ur.TRACK:{Ot(xi,`analyze() - got stats ${f[Te.TYPE]} for ${r}`,f);break}case Ur.CODEC:const s=[];return Object.keys(t[ue.AUDIO]).forEach(n=>{const g=t[ue.AUDIO][n];if(g.codec_id_in===f[Te.ID]||g.codec_id_out===f[Te.ID]){Ot(xi,`analyze() - got stats ${f[Te.TYPE]} for ${r}`,f);const _=WA(f);f[Te.ID]===g.codec_id_in?s.push({ssrc:g.ssrc,type:Me.AUDIO,value:{codec_in:_}}):s.push({ssrc:g.ssrc,type:Me.AUDIO,value:{codec_out:_}})}}),Object.keys(t[ue.VIDEO]).forEach(n=>{const g=t[ue.VIDEO][n];if(g.codec_id_in===f[Te.ID]||g.codec_id_out===f[Te.ID]){Ot(xi,`analyze() - got stats ${f[Te.TYPE]} for ${r}`,f);const _=KA(f);f[Te.ID]===g.codec_id_in?s.push({ssrc:g.ssrc,type:Me.VIDEO,value:{codec_in:_}}):s.push({ssrc:g.ssrc,type:Me.VIDEO,value:{codec_out:_}})}}),s;case Ur.REMOTE_INBOUND_RTP:{Ot(xi,`analyze() - got stats ${f[Te.TYPE]} for ${r}`,f);const n=f[Te.SSRC],g=Ss(n,t,zt.OUTBOUND),_=Ss(n,l,zt.OUTBOUND);if(f[Te.KIND]===ue.AUDIO){const v=Lp(f,ue.AUDIO,_,g),C=ju(f,ue.AUDIO,g),R=Fp(f,ue.AUDIO,g,_);return[{ssrc:n,type:Me.AUDIO,value:{delta_rtt_ms_out:v.rtt}},{ssrc:n,type:Me.AUDIO,value:{total_rtt_ms_out:v.totalRTT}},{ssrc:n,type:Me.AUDIO,value:{total_rtt_measure_out:v.totalRTTMeasurements}},{ssrc:n,type:Me.AUDIO,value:{delta_jitter_ms_out:C}},{ssrc:n,type:Me.AUDIO,value:{timestamp_out:f[Te.TIMESTAMP]}},{ssrc:n,type:Me.AUDIO,value:{total_packets_lost_out:R.packetsLost}},{ssrc:n,type:Me.AUDIO,value:{delta_packets_lost_out:R.deltaPacketsLost}},{ssrc:n,type:Me.AUDIO,value:{percent_packets_lost_out:R.fractionLost}}]}if(f[Te.KIND]===ue.VIDEO){const v=Lp(f,ue.VIDEO,_,g),C=ju(f,ue.VIDEO,g),R=Fp(f,ue.VIDEO,g,_);return[{ssrc:n,type:Me.VIDEO,value:{delta_rtt_ms_out:v.rtt}},{ssrc:n,type:Me.VIDEO,value:{total_rtt_ms_out:v.totalRTT}},{ssrc:n,type:Me.VIDEO,value:{total_rtt_measure_out:v.totalRTTMeasurements}},{ssrc:n,type:Me.VIDEO,value:{delta_jitter_ms_out:C}},{ssrc:n,type:Me.VIDEO,value:{timestamp_out:f[Te.TIMESTAMP]}},{ssrc:n,type:Me.VIDEO,value:{total_packets_lost_out:R.packetsLost}},{ssrc:n,type:Me.VIDEO,value:{delta_packets_lost_out:R.deltaPacketsLost}},{ssrc:n,type:Me.VIDEO,value:{percent_packets_lost_out:R.fractionLost}}]}break}}return[]},Gu=f=>f<0?1:f>100?4.5:1+.035*f+7/1e6*f*(f-60)*(100-f),XA=(f,t=ue.AUDIO,r,l,u)=>{const s=Ss(u,f,zt.INBOUND),n=Ss(u,r,zt.INBOUND),g=Ss(u,l,zt.INBOUND),_=[],v=[],C=s[t].percent_packets_lost_in,R=s[t].delta_jitter_ms_in,D=n&&n[t].delta_jitter_ms_in||null,H=g&&g[t].delta_jitter_ms_in||null,F=f.data.delta_rtt_connectivity_ms,q=r&&r.data.delta_rtt_connectivity_ms||null,G=l&&l.data.delta_rtt_connectivity_ms||null;F&&_.push(F),q&&_.push(q),G&&_.push(G),R&&v.push(R),r&&D&&v.push(D),l&&H&&v.push(H);const te=_.length>0?$i(_):100,X=v.length>0?$i(v):10,we=93.2-C,Q=.18*we*we-27.9*we+1126.62,re=(te+X)/2,ke=re-177.3<0?0:1,Ne=.024*re+.11*(re-177.3)*ke,Z=Q-Ne;return Gu(Z)},ZA=(f,t=ue.AUDIO,r,l,u)=>{const s=Ss(u,f,zt.OUTBOUND),n=Ss(u,r,zt.OUTBOUND),g=Ss(u,l,zt.OUTBOUND),_=[],v=[],C=s[t].percent_packets_lost_out,R=s[t].delta_rtt_ms_out,D=n&&n[t].delta_rtt_ms_out||null,H=g&&g[t].delta_rtt_ms_out||null,F=s[t].delta_jitter_ms_out,q=n&&n[t].delta_jitter_ms_out||null,G=g&&g[t].delta_jitter_ms_out||null,te=f.data.delta_rtt_connectivity_ms,X=r&&r.data.delta_rtt_connectivity_ms||null,we=l&&l.data.delta_rtt_connectivity_ms||null;R?_.push(R):te&&_.push(te),D?_.push(D):X&&_.push(X),H?_.push(H):we&&_.push(we),F&&v.push(F),r&&q&&v.push(q),l&&G&&v.push(G);const Q=_.length>0?$i(_):100,re=v.length>0?$i(v):10,ke=93.2-C,Ne=.18*ke*ke-27.9*ke+1126.62,Z=(Q+re)/2,se=Z-177.3<0?0:1,pe=.024*Z+.11*(Z-177.3)*se,me=Ne-pe;return Gu(me)},eI=(f,t=ue.AUDIO,r,l,u)=>{const s=Ss(u,f,zt.INBOUND),n=Ss(u,r,zt.INBOUND),g=Ss(u,l,zt.INBOUND),_=[],v=[],C=s[t].percent_packets_lost_in/100,R=s[t].delta_jitter_ms_in,D=n&&n[t].delta_jitter_ms_in||null,H=g&&g[t].delta_jitter_ms_in||null,F=f.data.delta_rtt_connectivity_ms,q=r&&r.data.delta_rtt_connectivity_ms||null,G=l&&l.data.delta_rtt_connectivity_ms||null;F&&_.push(F),q&&_.push(q),G&&_.push(G),R&&v.push(R),n&&D&&v.push(D),g&&H&&v.push(H);const te=_.length>0?$i(_):100,X=v.length>0?$i(v):10,we=0,Q=19.8,re=29.7,ke=30,Ne=(te+X)/2+ke,Z=Ne-177.3<0?0:1,se=.024*Ne+.11*(Ne-177.3)*Z,me=93.2-(we+Q*Math.log(1+re*C)+se);return Gu(me)},tI=(f,t=ue.AUDIO,r,l,u)=>{const s=Ss(u,f,zt.OUTBOUND),n=Ss(u,r,zt.OUTBOUND),g=Ss(u,l,zt.OUTBOUND),_=[],v=[],C=s[t].percent_packets_lost_out/100,R=s[t].delta_rtt_ms_out,D=n&&n[t].delta_rtt_ms_out||null,H=g&&g[t].delta_rtt_ms_out||null,F=s[t].delta_jitter_ms_out,q=n&&n[t].delta_jitter_ms_out||null,G=g&&g[t].delta_jitter_ms_out||null,te=f.data.delta_rtt_connectivity_ms,X=r&&r.data.delta_rtt_connectivity_ms||null,we=l&&l.data.delta_rtt_connectivity_ms||null;R?_.push(R):te&&_.push(te),D?_.push(D):X&&_.push(X),H?_.push(H):we&&_.push(we),F&&v.push(F),n&&q&&v.push(q),g&&G&&v.push(G);const Q=_.length>0?$i(_):100,re=v.length>0?$i(v):10,ke=0,Ne=19.8,Z=29.7,se=30,pe=(Q+re)/2+se,me=pe-177.3<0?0:1,be=.024*pe+.11*(pe-177.3)*me,Ae=93.2-(ke+Ne*Math.log(1+Z*C)+be);return Gu(Ae)};class sI{constructor(t,r){this._callbacks={onreport:null,onticket:null},this._id=DA(),this._moduleName=this._id,this._probeId=r,this._config=t,this._exporter=new LA(t),this._state=Bn.IDLE,this.registerToPCEvents(),xa(this._moduleName,`new collector created for probe ${this._probeId}`)}analyze(t,r,l,u){const s=(_,v)=>_===ue.AUDIO?v===Ur.INBOUND_RTP?{...Dp}:{...kp}:v===Ur.INBOUND_RTP?{...Np}:{...Mp},n=IA(r);n.pname=this._config.pname,n.call_id=this._config.cid,n.user_id=this._config.uid,n.count=r?r.count+1:1;let g=null;return t.forEach(_=>{!g&&_.timestamp&&(g=_.timestamp),QA(_,n,n.pname,u).forEach(C=>{if(C.value&&C.type)if(C.ssrc){let R=n[C.type][C.ssrc];R||(R=s(C.type,_.type),R.ssrc=C.ssrc,n[C.type][C.ssrc]=R),Object.keys(C.value).forEach(D=>{R[D]=C.value[D]})}else Object.keys(C.value).forEach(R=>{n[C.type][R]=C.value[R]})})}),n.timestamp=g,Object.keys(n[ue.AUDIO]).forEach(_=>{const v=n[ue.AUDIO][_];v.direction===zt.INBOUND?(v.mos_emodel_in=XA(n,ue.AUDIO,r,l,v.ssrc),v.mos_in=eI(n,ue.AUDIO,r,l,v.ssrc)):(v.mos_emodel_out=ZA(n,ue.AUDIO,r,l,v.ssrc),v.mos_out=tI(n,ue.AUDIO,r,l,v.ssrc))}),n}async takeReferenceStats(){return new Promise((t,r)=>{const l=Date.now();setTimeout(async()=>{try{const u=Date.now()-l,s=Date.now(),n=await this._config.pc.getStats(),g=this.analyze(n,null,null,null),_=Date.now();g.experimental.time_to_measure_ms=_-s,g.experimental.time_to_wait_ms=u,this._exporter.saveReferenceReport(g),Ot(this._moduleName,`got reference report for probe ${this._probeId}`),t()}catch(u){r(u)}},this._config.startAfter)})}async collectStats(){try{if(this._state!==Bn.RUNNING||!this._config.pc)return Ot(this._moduleName,`report discarded (too late) for probe ${this._probeId}`),null;const t=Date.now(),r=await this._config.pc.getStats(),l=this.analyze(r,this._exporter.getLastReport(),this._exporter.getBeforeLastReport(),this._exporter.getReferenceReport()),u=Date.now();return l.experimental.time_to_measure_ms=u-t,this._exporter.addReport(l),Ot(this._moduleName,`got report for probe ${this._probeId}#${this._exporter.getReportsNumber()+1}`),this.fireOnReport(l),l}catch(t){return Tl(this._moduleName,`got error ${t}`),null}}async start(){Ot(this._moduleName,"starting"),this.state=Bn.RUNNING,this._startedTime=this._exporter.start(),Ot(this._moduleName,"started")}async mute(){this.state=Bn.MUTED,Ot(this._moduleName,"muted")}async unmute(){this.state=Bn.RUNNING,Ot(this._moduleName,"unmuted")}async stop(t){if(Ot(this._moduleName,`stopping${t?" by watchdog":""}...`),this._stoppedTime=this._exporter.stop(),this.state=Bn.IDLE,this._config.ticket){const{ticket:r}=this._exporter;this.fireOnTicket(r)}this._exporter.reset(),Ot(this._moduleName,"stopped")}registerCallback(t,r,l){t in this._callbacks?(this._callbacks[t]={callback:r,context:l},Ot(this._moduleName,`registered callback '${t}'`)):Tl(this._moduleName,`can't register callback for '${t}' - not found`)}unregisterCallback(t){t in this._callbacks?(this._callbacks[t]=null,delete this._callbacks[t],Ot(this._moduleName,`unregistered callback '${t}'`)):Tl(this._moduleName,`can't unregister callback for '${t}' - not found`)}fireOnReport(t){this._callbacks.onreport&&Vd(this._callbacks.onreport.callback,this._callbacks.onreport.context,t)}fireOnTicket(t){this._callbacks.onticket&&Vd(this._callbacks.onticket.callback,this._callbacks.onticket.context,t)}updateConfig(t){this._config=t,this._exporter.updateConfig(t)}get state(){return this._state}set state(t){this._state=t,Ot(this._moduleName,`state changed to ${t}`)}addCustomEvent(t,r,l,u){this._exporter.addCustomEvent({at:typeof t=="object"?t.toJSON():t,category:r,name:l,description:u})}async registerToPCEvents(){const{pc:t}=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{Tl(this._moduleName,"can't get devices")}},t){t.oniceconnectionstatechange=()=>{const l=t.iceConnectionState;l===To.CONNECTED||l===To.COMPLETED?this.addCustomEvent(new Date().toJSON(),"call",l,"ICE connection state"):l===To.DISCONNECTED||l===To.FAILED?this.addCustomEvent(new Date().toJSON(),"call",l,"ICE connection state"):l===To.CLOSED&&this.addCustomEvent(new Date().toJSON(),"call","ended","ICE connection state")},t.onicegatheringstatechange=()=>{const l=t.iceGatheringState;this.addCustomEvent(new Date().toJSON(),"call",l,"ICE gathering state")},t.ontrack=l=>{this.addCustomEvent(new Date().toJSON(),"call",`${l.track.kind}track`,"MediaStreamTrack received")},t.onnegotiationneeded=()=>{this.addCustomEvent(new Date().toJSON(),"call","negotiation","Media changed")};const r=t.getReceivers();if(r&&r.length>0){const l=r[0],{transport:u}=l;if(u){const{iceTransport:s}=u;s&&(s.onselectedcandidatepairchange=()=>{this.addCustomEvent(new Date().toJSON(),"call","transport","Candidates Pair changed")})}}}}}class rI{constructor(t){this._id=t.pname&&t.pname.substr(0,12).padEnd(12," ")||OA(),this._moduleName=this._id,xa(this._moduleName,"probe created"),this._config=t,this._collector=new sI(this._config,this._id)}set onreport(t){t?this._collector.registerCallback("onreport",t):this._collector.unregisterCallback("onreport")}set onticket(t){t?this._collector.registerCallback("onticket",t):this._collector.unregisterCallback("onticket")}get id(){return this._id}get pname(){return this._config.pname}get cid(){return this._config.cid}get uid(){return this._config.uid}get state(){return this._collector.state}set state(t){this._collector.state=t}addCustomEvent(t,r,l,u=new Date().toJSON()){this._collector.addCustomEvent(u,r,t,l)}get isRunning(){return this._collector.state===Bn.RUNNING}get isIdle(){return this._collector.state===Bn.IDLE}updateUserId(t){this._config.uid=t,this._collector.updateConfig(this._config)}updateCallId(t){this._config.cid=t,this._collector.updateConfig(this._config)}start(){if(!this.isIdle){qu(this._moduleName,"probe is already running");return}this._collector.start()}stop(t=!1){this.isRunning&&this._collector.stop(t)}async takeReferenceStats(){return this._collector.takeReferenceStats()}async collectStats(){return this._collector.collectStats()}}const Vs="engine ";class nI{constructor(t){this._config=t,this._probes=[],this._startedTime=null,this._callbacks={onresult:null},xa(Vs,`configured for probing every ${this._config.refreshEvery}ms`),xa(Vs,`configured for starting after ${this._config.startAfter}ms`),xa(Vs,`${!this._config.stopAfter||this._config.stopAfter!==-1?`configured for stopped after ${this._config.stopAfter}ms`:"configured for never stopped"}`),Ot(Vs,"engine initialized")}get probes(){return this._probes}get isRunning(){return this._probes.some(t=>t.isRunning)}get isIdle(){return this._probes.every(t=>t.isIdle)}addNewProbe(t,r){if(!t)throw new Error("undefined peer connection");const l=$A(t,r,this._config),u=new rI(l);return this._probes.push(u),Ot(Vs,`${this._probes.length} probes registered`),u}removeExistingProbe(t){if(!t)throw new Error("undefined probe");t.state===Bn.RUNNING&&t.stop(),this._probes=this._probes.filter(r=>t.id!==r.id)}async start(){const t=()=>{this._probes.forEach(s=>s.start())},r=async()=>Promise.all(this._probes.map(s=>s.takeReferenceStats())),l=()=>this.isIdle?!1:!this._config.stopAfter||this._config.stopAfter<0?!0:Date.now()<this._startedTime+this._config.stopAfter,u=async()=>{const s=AA(),n=this._probes.filter(g=>g.isRunning);for(const g of n){const _=await g.collectStats();_&&s.probes.push(_),Ot(Vs,`got probe ${g.id}`),await Up(0)}return s.delta_time_to_measure_probes_ms=Oa(s.probes,"experimental","time_to_measure_ms"),s.delta_KBytes_in=Oa(s.probes,"data","delta_KBytes_in"),s.delta_KBytes_out=Oa(s.probes,"data","delta_KBytes_out"),s.delta_kbs_in=Oa(s.probes,"data","delta_kbs_in"),s.delta_kbs_out=Oa(s.probes,"data","delta_kbs_out"),s.total_time_decoded_in=Oa(s.probes,"video","total_time_decoded_in"),s.total_time_encoded_out=Oa(s.probes,"video","total_time_encoded_out"),s};for(Ot(Vs,"starting to collect"),t(),Ot(Vs,"generating reference reports..."),await r(),Ot(Vs,"reference reports generated"),this._startedTime=Date.now();l();)if(Ot(Vs,`wait ${this._config.refreshEvery}ms before collecting`),await Up(this._config.refreshEvery),l()){Ot(Vs,"collecting...");const s=Date.now(),n=await u(),g=Date.now();n.delta_time_consumed_to_measure_ms=g-s,this.fireOnReports(n),Ot(Vs,"collected")}Ot(Vs,"reaching end of the collecting period..."),this.isRunning&&setTimeout(()=>{this.stop()},0)}stop(t){const r=l=>{this._probes.forEach(u=>{u.stop(l)})};xa(Vs,"stop collecting"),r(t)}registerCallback(t,r,l){t in this._callbacks?(this._callbacks[t]={callback:r,context:l},Ot(Vs,`registered callback '${t}'`)):Tl(Vs,`can't register callback for '${t}' - not found`)}unregisterCallback(t){t in this._callbacks?(this._callbacks[t]=null,delete this._callbacks[t],Ot(this._moduleName,`unregistered callback '${t}'`)):Tl(this._moduleName,`can't unregister callback for '${t}' - not found`)}fireOnReports(t){this._callbacks.onresult&&t.probes.length>0&&Vd(this._callbacks.onresult.callback,this._callbacks.onresult.context,t)}}const iI="interface ";class aI{constructor(t){this._config=xA(t),xa(iI,`welcome to ${this._config.name} version ${this._config.version}`),vA(this._config.verbose||!1),this._engine=new nI(this._config)}setupLogLevel(t){yA(t)}get version(){return this._config.version}get name(){return this._config.name}get probes(){return this._engine.probes}createProbe(t,r){return this._engine.addNewProbe(t,r)}startAllProbes(){this._engine.start()}stopAllProbes(){this._engine.stop()}get running(){return this._engine.isRunning}get idle(){return this._engine.isIdle}removeProbe(t){this._engine.removeExistingProbe(t)}set onresult(t){t?this._engine.registerCallback("onresult",t):this._engine.unregisterCallback("onresult")}}function lI(f,t){return Object.keys(f).filter(r=>t.includes(r)).reduce((r,l)=>{const u=l;return{...r,[u]:f[u]}},{})}const oI=["mos_in","codec_in","delta_KBytes_in","delta_kbs_in","delta_jitter_ms_in","delta_packets_lost_in"],uI={positiveSpeechThreshold:.6,negativeSpeechThreshold:.3,preSpeechPadMs:150,redemptionMs:1500,minSpeechMs:50};class cI{constructor(t){this.intervals={},this.analysers={},this.emitInterval=t.emitInterval||200,this.onChangeFunction=t.onChangeFunction}async start(t,r,l){r&&r.getTracks().length&&await this.beginCalculation(t,r,l)}stop(t){this.clearVolumeInterval(t),this.analysers[t]&&typeof this.analysers[t].disconnect=="function"&&(this.analysers[t].disconnect(),delete this.analysers[t])}clearVolumeInterval(t){this.intervals[t]&&(clearInterval(this.intervals[t]),delete this.intervals[t])}clearAllIntervals(){Object.keys(this.intervals).forEach(t=>{this.stop(t)}),this.intervals={},this.analysers={}}async beginCalculation(t,r,l){this.clearVolumeInterval(l);const u=t.createAnalyser(),s=t.createMediaStreamSource(r);u.smoothingTimeConstant=.8,u.fftSize=1024,s.connect(u),this.analysers[l]=u,this.intervals[l]=setInterval(()=>{const n=new Uint8Array(u.frequencyBinCount);u.getByteFrequencyData(n);let g=0;const _=n.length;for(let C=0;C<_;C++)g+=n[C];const v=g/_;this.onChangeFunction(l,v)},this.emitInterval)}}class dI{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(t=>{throw this.resumePromise=null,t})),await this.resumePromise),this.context}}Ud.env.wasm.wasmPaths="/";const Wu={SELECTED_INPUT_DEVICE:"OpensipsJSInputDevice",SELECTED_OUTPUT_DEVICE:"OpensipsJSOutputDevice"},fI=0;class hI{constructor(t){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 dI,this.context=t,this.context.on(this.context.newRTCSessionEventName,this.newRTCSessionCallback.bind(this)),this.VUMeter=new cI({onChangeFunction:this.emitVolumeChange.bind(this)}),this.processVADConfiguration(),this.initializeMediaDevices()}processVADConfiguration(){var r;const t=((r=this.context.options.configuration)==null?void 0:r.noiseReductionOptions)||{};this.noiseReduction={mode:t.mode||"disabled",checkEveryMs:t.checkEveryMs||500,noiseCheckInterval:t.noiseCheckInterval||2e3,noiseThreshold:t.noiseThreshold||.004,vadConfig:t.vadConfig||{}}}get sipOptions(){return{...this.context.options.sipOptions,mediaConstraints:this.getUserMediaConstraints}}get currentActiveRoomId(){return this.currentActiveRoomIdValue}set currentActiveRoomId(t){this.currentActiveRoomIdValue=t,this.context.emit("currentActiveRoomChanged",t)}get autoAnswer(){return this.isAutoAnswer}get callAddingInProgress(){return this.isCallAddingInProgress}set callAddingInProgress(t){this.isCallAddingInProgress=t,this.context.emit("callAddingInProgressChanged",t)}get muteWhenJoin(){return this.muteWhenJoinEnabled}get isDND(){return this.isDNDEnabled}get isCallWaiting(){return this.isCallWaitingEnabled}get speakerVolume(){return this.speakerVolumeValue}get microphoneInputLevel(){return this.microphoneInputLevelValue}get getActiveCalls(){return this.activeCalls}get hasActiveCalls(){return Object.values(this.extendedCalls).length>0}get hasActiveAnsweredCalls(){return Object.values(this.activeRooms).filter(l=>!l.incomingInProgress).length>0}get getActiveRooms(){return this.activeRooms}get isMuted(){return this.muted}get getInputDeviceList(){return this.availableMediaDevices.filter(t=>t.kind==="audioinput")}get getOutputDeviceList(){return this.availableMediaDevices.filter(t=>t.kind==="audiooutput")}get getUserMediaConstraints(){return _p()?{video:!1,audio:!0}:{audio:{deviceId:{exact:this.selectedMediaDevices.input},echoCancellation:!0,echoCancellationType:"system",noiseSuppression:!0,autoGainControl:!0,sampleRate:48e3,latency:.01},video:!1}}get selectedInputDevice(){return this.selectedMediaDevices.input}get selectedOutputDevice(){return this.selectedMediaDevices.output}get activeStream(){return this.activeStreamValue}setAvailableMediaDevices(t){this.availableMediaDevices=t,this.context.emit("changeAvailableDeviceList",t)}async updateDeviceList(){await navigator.mediaDevices.getUserMedia(this.getUserMediaConstraints);const t=await navigator.mediaDevices.enumerateDevices();this.setAvailableMediaDevices(t)}async initializeMediaDevices(){const t=localStorage.getItem(Wu.SELECTED_INPUT_DEVICE)||"default",r=localStorage.getItem(Wu.SELECTED_OUTPUT_DEVICE)||"default";try{const l=await navigator.mediaDevices.getUserMedia(this.getUserMediaConstraints),u=await navigator.mediaDevices.enumerateDevices();this.setAvailableMediaDevices(u),await this.setMicrophone(t),await this.setSpeaker(r),navigator.mediaDevices.addEventListener("devicechange",async()=>{const s=await navigator.mediaDevices.enumerateDevices();this.setAvailableMediaDevices(s)}),l.getTracks().forEach(s=>s.stop())}catch(l){console.error(l)}}async cleanupConferenceNodes(t){const r=this.conferenceNodes[t];if(!r)return;let l=0;r.sources.forEach((n,g)=>{try{n.disconnect(),l++}catch(_){console.error(`[cleanupConferenceNodes] Error disconnecting source ${g}:`,_)}});let u=0;r.destinations.forEach((n,g)=>{try{n.disconnect(),u++}catch(_){console.error(`[cleanupConferenceNodes] Error disconnecting destination ${g}:`,_)}});let s=0;r.gains.forEach((n,g)=>{try{n.disconnect(),s++}catch(_){console.error(`[cleanupConferenceNodes] Error disconnecting gain ${g}:`,_)}}),delete this.conferenceNodes[t]}setCallTime(t){const r={...t};delete r.callId,this.callTime={...this.callTime,[t.callId]:r},this.context.emit("changeCallTime",this.callTime)}removeCallTime(t){const r={...this.callTime};delete r[t],this.callTime={...r},this.context.emit("changeCallTime",this.callTime)}setTimeInterval(t,r){this.timeIntervals={...this.timeIntervals,[t]:r}}removeTimeInterval(t){const r={...this.timeIntervals};r[t]&&(clearInterval(r[t]),delete r[t],this.timeIntervals={...r})}stopCallTimer(t){this.removeTimeInterval(t),this.removeCallTime(t)}emitVolumeChange(t,r){this.context.emit("changeCallVolume",{callId:t,volume:r})}setMetricsConfig(t){this.metricConfig={...this.metricConfig,...t}}sendDTMF(t,r){if(!/^[A-D0-9*#]+$/g.test(r))throw new Error("Not allowed character used in the DTMF input");this.extendedCalls[t].sendDTMF(r)}setIsMuted(t){this.muted=t,this.context.emit("changeIsMuted",t)}processMute(t){const r=this.currentActiveRoomId;this.setIsMuted(t),this.initialStreamValue.getTracks().forEach(l=>l.enabled=!t),this.roomReconfigure(r)}mute(){this.processMute(!0)}unmute(){this.processMute(!1)}async processHold({callId:t,toHold:r,automatic:l}){const u=this.extendedCalls[t];if(!u)return;u._automaticHold=l??!1;const s=new Promise((n,g)=>{const _=setTimeout(()=>{g(new Error("Hold operation timeout"))},5e3),v=()=>{clearTimeout(_),u.putOnHoldTimestamp=r?Date.now():void 0,n()},C=R=>{clearTimeout(_),g(R)};try{r?(this.stopSessionVad(u._id),u.hold({},v)):u.unhold({},v)}catch(R){C(R)}});try{await s,this.updateCall(u);const n=Object.values(this.extendedCalls).filter(g=>g.roomId===u.roomId&&(r?t!==g._id:!0));n.length>1&&await this.doConference(n)}catch(n){throw console.error("Hold operation failed:",n),n}}holdCall(t,r=!1){return this.processHold({callId:t,automatic:r,toHold:!0})}unholdCall(t){return this.processHold({callId:t,toHold:!1})}cancelAllOutgoingUnanswered(){Object.values(this.getActiveCalls).filter(t=>t.direction==="outgoing"&&t.status===fI).forEach(t=>this.terminateCall(t._id))}answerCall(t){const r=this.extendedCalls[t];this.cancelAllOutgoingUnanswered(),r.answer(this.sipOptions),this.updateCall(r),this.setActiveRoom(r.roomId),r.connection.addEventListener("track",l=>{this.triggerAddStream(l,r)})}async moveCall(t,r){this.updateCallStatus({callId:t,isMoving:!0}),await this.processRoomChange({callId:t,roomId:r}),this.updateCallStatus({callId:t,isMoving:!1})}updateCall(t){this.activeCalls[t._id]=fp(t),this.context.emit("changeActiveCalls",this.activeCalls)}updateRoom(t){const l={...this.activeRooms[t.roomId],...t};this.activeRooms={...this.activeRooms,[t.roomId]:{...l}},this.context.emit("updateRoom",{room:l,roomList:this.activeRooms})}hasAutoAnswerHeaders(t){const r=/answer-after=0/,u=t.request.getHeader("Call-Info");return u&&r.test(u)}addCall(t,r=!0){this.activeCalls={...this.activeCalls,[t._id]:fp(t)},this.extendedCalls[t._id]=t,r&&this.context.emit("changeActiveCalls",this.activeCalls)}addCallStatus(t){this.callStatus={...this.callStatus,[t]:{isMoving:!1,isTransferring:!1,isMerging:!1,isTransferred:!1}},this.context.emit("changeCallStatus",this.callStatus)}updateCallStatus(t){const l={...{...this.callStatus[t.callId]}};t.isMoving!==void 0&&(l.isMoving=t.isMoving),t.isTransferring!==void 0&&(l.isTransferring=t.isTransferring),t.isMerging!==void 0&&(l.isMerging=t.isMerging),t.isTransferred!==void 0&&(l.isTransferred=t.isTransferred),this.callStatus={...this.callStatus,[t.callId]:{...l}},this.context.emit("changeCallStatus",this.callStatus)}removeCallStatus(t){const r={...this.callStatus};delete r[t],this.callStatus={...r},this.context.emit("changeCallStatus",this.callStatus)}addRoom(t){this.activeRooms={...this.activeRooms,[t.roomId]:t},this.context.emit("addRoom",{room:t,roomList:this.activeRooms})}async setupActiveStream(){const t=await kd(await this.managedAudioContext.getContext(),this.initialStreamValue,this.microphoneInputLevel*2);t.getTracks().forEach(r=>r.enabled=!this.isMuted),await this.setActiveStream(t)}async getActiveStream(){const t=await kd(await this.managedAudioContext.getContext(),this.initialStreamValue,this.microphoneInputLevel*2);return t.getTracks().forEach(r=>r.enabled=!this.isMuted),await this.setActiveStream(t),t}async setMicrophone(t){if(!this.getInputDeviceList.find(({deviceId:l})=>l===t)||(this.setSelectedInputDevice(t),Object.keys(this.getActiveCalls).length===0))return;await this.setupStream();const r=Object.values(this.extendedCalls).filter(l=>l.roomId===this.currentActiveRoomId);r.length===1?Object.values(r).forEach(async l=>{await this.setupActiveStream();const u=this.activeStream;l.connection.getSenders()[0].replaceTrack(u.getTracks()[0]),this.updateCall(l)}):await this.doConference(r)}async setActiveStream(t){this.activeStream&&this.stopVUMeter("origin"),await this.setupVUMeter(t,"origin"),this.activeStreamValue=t,this.context.emit("changeActiveStream",t)}async setSpeaker(t){if(!this.getOutputDeviceList.find(({deviceId:u})=>u===t))return;this.setSelectedOutputDevice(t);const r=Object.values(this.extendedCalls);if(r.length===0)return;const l=r.filter(u=>u.roomId===this.currentActiveRoomId);l.length===1?r.forEach(u=>{var s;(s=u.audioTag)==null||s.setSinkId(t),this.updateCall(u)}):await this.doConference(l)}removeRoom(t){const r={...this.activeRooms},l={...r[t]};delete r[t],this.activeRooms={...r},this.context.emit("removeRoom",{room:l,roomList:this.activeRooms})}deleteRoomIfEmpty(t){t!==void 0&&Object.values(this.extendedCalls).filter(r=>r.roomId===t).length===0&&(this.removeRoom(t),this.currentActiveRoomId===t&&(this.currentActiveRoomId=void 0))}checkInitialized(){if(!this.context.initialized)throw new Error("[OpenSIPSJS] You must call `start` method first!")}muteReconfigure(t){this.muted?t.mute({audio:!0}):t.unmute({audio:!0})}startNoiseMonitor({sessionId:t,stream:r,onNoiseDetected:l,onNoiseStop:u}){const s=new AudioContext,n=s.createMediaStreamSource(r.clone()),g=s.createAnalyser();g.fftSize=1024;const _=new Float32Array(g.fftSize);n.connect(g);const v=[];this.vadIntervals[t]&&(clearInterval(this.vadIntervals[t]),this.vadIntervals[t]=null),this.vadMrsIntervals[t]&&(clearInterval(this.vadMrsIntervals[t]),this.vadMrsIntervals[t]=null),this.vadMrsIntervals[t]=setInterval(()=>{g.getFloatTimeDomainData(_);const C=rA(_);v.push(C);const R=Math.ceil(this.noiseReduction.noiseCheckInterval/this.noiseReduction.checkEveryMs);v.length>R&&v.shift()},this.noiseReduction.checkEveryMs),this.vadIntervals[t]=setInterval(()=>{if(v.length===0)return;const C=v.reduce((H,F)=>H+F,0)/v.length,R=this.vadSessionsState[t],D=C>this.noiseReduction.noiseThreshold;R.isSpeaking||(D&&R.currentMode==="clean"?(R.currentMode="noisy",console.log("Average noise high → enable VAD"),this.context.emit("changeNoiseReductionState",{sessionId:t,enabled:!0}),l()):!D&&R.currentMode==="noisy"&&(R.currentMode="clean",console.log("Average noise low → disable VAD"),this.context.emit("changeNoiseReductionState",{sessionId:t,enabled:!1}),u()))},this.noiseReduction.noiseCheckInterval)}async processVAD(t,r){const l=r.clone();this.stopSessionVad(t._id),this.vadSessionsState[t._id]={currentMode:"clean",isSpeaking:!1};const u=await this.managedAudioContext.getContext(),s=await nA(l,u,150);let n=!1;const g=await mp.MicVAD.new({getStream:()=>new Promise(_=>_(l)),...uI,...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(!n){if(n=!0,console.log("✅ VAD initialized, starting background noise monitoring"),this.noiseReduction.mode==="enabled"){t.connection.getSenders()[0]&&t.connection.getSenders()[0].replaceTrack(s.stream.getAudioTracks()[0]);return}this.startNoiseMonitor({sessionId:t._id,stream:l,onNoiseDetected:async()=>{var _;console.log("Replace track with Vad Controlled"),await((_=t.connection.getSenders()[0])==null?void 0:_.replaceTrack(s.stream.getAudioTracks()[0]))},onNoiseStop:async()=>{const _=t.connection.getSenders()[0];_&&_.track&&_.transport&&_.transport.state!=="closed"&&_.transport.state!=="failed"&&(console.log("Replace track with Original"),await _.replaceTrack(l.getAudioTracks()[0]))}})}},onSpeechStart:()=>{var _;console.log("🎤 Speech started"),s.setSpeaking(!0),this.noiseReduction.mode==="enabled"&&((_=t.connection.getSenders()[0])==null||_.replaceTrack(s.stream.getAudioTracks()[0])),this.vadSessionsState[t._id].isSpeaking=!0},onSpeechEnd:()=>{var _;console.log("🛑 Speech end"),s.setSpeaking(!1),this.noiseReduction.mode==="enabled"&&((_=t.connection.getSenders()[0])==null||_.replaceTrack(s.stream.getAudioTracks()[0])),this.vadSessionsState[t._id].isSpeaking=!1}});this.vadSessions[t._id]&&(this.vadSessions[t._id].pause(),delete this.vadSessions[t._id]),this.vadSessions[t._id]=g,g.start()}stopSessionVad(t){this.vadSessions[t]&&(this.vadSessions[t].pause(),delete this.vadSessions[t]),this.vadIntervals[t]&&(clearInterval(this.vadIntervals[t]),delete this.vadIntervals[t]),this.vadMrsIntervals[t]&&(clearInterval(this.vadMrsIntervals[t]),delete this.vadMrsIntervals[t]),this.vadSessionsState[t]&&delete this.vadSessionsState[t]}async roomReconfigure(t){var u;if(t===void 0)return;const r=Object.values(this.extendedCalls).filter(s=>s.roomId===t),l=this.currentActiveRoomId===t;if(r.forEach((s,n)=>{if(s.audioTag){s.connection.getReceivers().forEach(_=>{_.track.enabled=!s.localMuted}),l&&this.muteReconfigure(s);const g=!l;s.audioTag.muted=g,this.updateCall(s)}}),r.length===0){!!this.conferenceNodes[t]&&await this.cleanupConferenceNodes(t),this.deleteRoomIfEmpty(t);return}if(r.length===1&&!l){const s=r[0];s.isOnHold().local||await this.holdCall(s._id,!0),!!this.conferenceNodes[t]&&await this.cleanupConferenceNodes(t);return}if(r.length===1&&l){const s=r[0];s.isOnHold().local&&s._automaticHold&&await this.unholdCall(s._id);const _=(((u=s.connection)==null?void 0:u.getSenders())||[])[0];if(s.connection&&_)try{await this.setupActiveStream();const C=this.activeStream;["enabled","dynamic"].includes(this.noiseReduction.mode)&&this.processVAD(r[0],C);const R=C.getTracks();await _.replaceTrack(R[0]),this.muteReconfigure(s)}catch(C){console.error(C)}!!this.conferenceNodes[t]&&await this.cleanupConferenceNodes(t);return}r.length>1&&await this.doConference(r)}async doConference(t){if(t.length===0)return;const r=t[0].roomId,l=this.currentActiveRoomId===r;if(t.find(_=>_.roomId!==r))return;const s=await this.managedAudioContext.getContext();if(s.state!=="running"){console.error(`[doConference] ERROR: AudioContext is not running! State: ${s.state}`);return}await this.cleanupConferenceNodes(r),this.conferenceNodes[r]={sources:new Map,destinations:new Map,gains:new Map};const n=this.conferenceNodes[r],g=new Map;t.forEach((_,v)=>{_&&_.connection&&_.connection.getReceivers().forEach((R,D)=>{var q,G,te;R.track.enabled=!_.localMuted;const H=(q=R.track)==null?void 0:q.id;(G=R.track)==null||G.readyState,(te=R.track)==null||te.kind;const F=`${_._id}-${H}`;R.track&&R.track.readyState==="live"&&g.set(F,R.track)})}),await this.setupActiveStream(),await iA.forEach(t,async(_,v)=>{if(!_||!_.connection)return;const C=s.createMediaStreamDestination();n.destinations.set(_._id,C);let R=0;if(g.forEach((q,G)=>{if(!G.startsWith(_._id))try{const te=s.createMediaStreamSource(new MediaStream([q])),X=s.createGain(),we=`${_._id}-${G}`;te.connect(X),X.connect(C),n.sources.set(we,te),n.gains.set(we,X),R++}catch(te){console.error(te)}}),l&&this.activeStreamValue)try{const q=this.activeStream,G=s.createMediaStreamSource(q),te=s.createGain(),X=`${_._id}-local`;G.connect(te),te.connect(C),n.sources.set(X,G),n.gains.set(X,te)}catch(q){console.error(q)}else l&&console.error(`Host room but no activeStreamValue - skipping host microphone for session ${_._id}`);const H=_.connection.getSenders()[0],F=C.stream.getTracks();if(["enabled","dynamic"].includes(this.noiseReduction.mode)&&this.processVAD(_,C.stream),H&&F[0])try{await H.replaceTrack(F[0]),this.muteReconfigure(_)}catch(q){console.error(q)}})}processCallerMute(t,r){const l=this.extendedCalls[t];l&&l.connection.getReceivers().length&&(l.localMuted=r,l.connection.getReceivers().forEach(u=>{u.track.enabled=!r}),this.updateCall(l))}muteCaller(t){this.processCallerMute(t,!0)}unmuteCaller(t){this.processCallerMute(t,!1)}terminateCall(t){const r=this.extendedCalls[t];r._status===4?r.terminate({status_code:603,reason_phrase:"Decline"}):r._status!==8&&r.terminate()}transferCall(t,r){if(r.toString().length===0)return new Error("Target must be passed");const l=this.extendedCalls[t];if(!l._is_confirmed&&!l._is_canceled){const u=`sip:${r}@${this.context.sipDomain}`;l.terminate({status_code:302,reason_phrase:"Moved Temporarily",extraHeaders:[`Contact: ${u}`]});return}this.updateCallStatus({callId:t,isTransferring:!0,isTransferred:!1}),l.refer(`sip:${r}@${this.context.sipDomain}`,{eventHandlers:{requestSucceeded:()=>{this.updateCallStatus({callId:t,isTransferring:!1,isTransferred:!0})},requestFailed:()=>{this.updateCallStatus({callId:t,isTransferring:!1,isTransferred:!1})}}}),this.updateCall(l)}mergeCall(t){const r=Object.values(this.extendedCalls).filter(s=>s.roomId===t);if(r.length!==2)return;const l=r[0],u=r[1];!l||!u||(this.updateCallStatus({callId:l._id,isMerging:!0}),this.updateCallStatus({callId:u._id,isMerging:!0}),l.refer(u.remote_identity.uri.toString(),{replaces:u}),this.updateCall(l))}mergeCallByIds(t,r){const l=Object.values(this.extendedCalls).find(s=>s._id===t),u=Object.values(this.extendedCalls).find(s=>s._id===r);if(!l||!u)throw new Error("Call ID is not provided");this.updateCallStatus({callId:t,isMerging:!0}),this.updateCallStatus({callId:r,isMerging:!0}),l.refer(u.remote_identity.uri.toString(),{replaces:u}),this.updateCall(l)}setDND(t){this.isDNDEnabled=t,this.context.emit("changeIsDND",t)}setCallWaiting(t){this.isCallWaitingEnabled=t,this.context.emit("changeIsCallWaiting",t)}startCallTimer(t){this.removeTimeInterval(t);const r={callId:t,hours:0,minutes:0,seconds:0,formatted:""};this.setCallTime(r);const l=setInterval(()=>{const u={...this.callTime[t]},s=sA(u);this.setCallTime({callId:t,...s})},1e3);this.setTimeInterval(t,l)}async setActiveRoom(t){const r=this.currentActiveRoomId;t!==r&&(this.currentActiveRoomId=t,await this.roomReconfigure(r),await this.roomReconfigure(t))}getNewRoomId(){const t=Object.keys(this.activeRooms);return t.length===0?1:parseInt(t.sort()[t.length-1])+1}async setupCall(t){var v,C;const r=t.session;if(this.getActiveCalls[r.id]!==void 0)return;const u=this.getNewRoomId(),s={started:new Date,incomingInProgress:!1,roomId:u};r.direction==="incoming"?(this.context.logger.log("New incoming call from",(C=(v=r._remote_identity)==null?void 0:v._uri)==null?void 0:C._user),s.incomingInProgress=!0,this.context.subscribe(Mr.CALL_CONFIRMED,R=>{r.id===R.id&&(this.updateRoom({incomingInProgress:!1,roomId:u}),this.startCallTimer(r.id))}),this.context.subscribe(Mr.CALL_FAILED,R=>{r.id===R.id&&(this.updateRoom({incomingInProgress:!1,roomId:u}),this.deleteRoomIfEmpty(u))})):r.direction==="outgoing"&&(r.once("confirmed",()=>{this.startCallTimer(r.id)}),this.startCallTimer(r.id));const n=r,g=this.hasAutoAnswerHeaders(t),_=n.direction==="incoming"&&!this.hasActiveCalls&&(g||this.autoAnswer);n.roomId=u,n.localMuted=!1,n.autoAnswer=_,_?this.addCall(n,!1):this.addCall(n),this.addCallStatus(r.id),this.addRoom(s),_&&this.answerCall(n._id)}removeCall(t){const r={...this.activeCalls};delete r[t],this.activeCalls={...r};const l={...this.extendedCalls};delete l[t],this.extendedCalls={...l},this.context.emit("changeActiveCalls",this.activeCalls)}activeCallListRemove(t){const r=this.extendedCalls[t._id];if(!r)return;this.stopVUMeter("origin"),this.stopVUMeter(t._id);const l=r.roomId;this.removeCall(t._id),this.roomReconfigure(l).then(()=>{}).catch(u=>{console.error("Error reconfiguring room after call removal:",u)})}shouldTerminateNewSession(t){if(t.session.direction==="outgoing")return!1;const l=!this.isCallWaiting&&this.hasActiveCalls;return this.isDND||l}async newRTCSessionCallback(t){const r=t.session;if(this.shouldTerminateNewSession(t)){r.terminate({status_code:486,reason_phrase:"Do Not Disturb"});return}if(this.context.triggerListener({listenerType:Mr.NEW_CALL,session:r,event:t}),r.on("ended",l=>{var s,n,g;this.stopVUMeter(r.id),this.context.logger.log("Session ended for",(n=(s=r._remote_identity)==null?void 0:s._uri)==null?void 0:n._user),this.context.triggerListener({listenerType:Mr.CALL_ENDED,session:r,event:l}),["enabled","dynamic"].includes(this.noiseReduction.mode)&&this.stopSessionVad(r._id);const u=this.getActiveCalls[r.id];u&&this.activeCallListRemove(u),this.stopCallTimer(r.id),this.removeCallStatus(r.id),this.removeCallMetrics(r.id),Object.keys(this.extendedCalls).length||(this.setIsMuted(!1),(g=this.initialStreamValue)==null||g.getTracks().forEach(_=>_.stop()),this.initialStreamValue=null),this.context.isWaitingForSessionHangup()&&!this.hasActiveAnsweredCalls&&this.context.stopSessionAfterWaiting()}),r.on("progress",l=>{var u,s;this.context.logger.log("Session in progress for",(s=(u=r._remote_identity)==null?void 0:u._uri)==null?void 0:s._user),this.context.triggerListener({listenerType:Mr.CALL_PROGRESS,session:r,event:l})}),r.on("failed",l=>{var s,n,g;this.stopVUMeter(r.id),this.context.logger.log("Session failed for",(n=(s=r._remote_identity)==null?void 0:s._uri)==null?void 0:n._user),this.context.triggerListener({listenerType:Mr.CALL_FAILED,session:r,event:l}),["enabled","dynamic"].includes(this.noiseReduction.mode)&&this.stopSessionVad(r._id),r.id===this.callAddingInProgress&&(this.callAddingInProgress=void 0);const u=this.getActiveCalls[r.id];u&&this.activeCallListRemove(u),this.stopCallTimer(r.id),this.removeCallStatus(r.id),this.removeCallMetrics(r.id),Object.keys(this.extendedCalls).length||(this.setIsMuted(!1),(g=this.initialStreamValue)==null||g.getTracks().forEach(_=>_.stop()),this.initialStreamValue=null),this.context.isWaitingForSessionHangup()&&!this.hasActiveAnsweredCalls&&this.context.stopSessionAfterWaiting()}),r.on("confirmed",l=>{var u,s;this.context.logger.log("Session confirmed for",(s=(u=r._remote_identity)==null?void 0:u._uri)==null?void 0:s._user),this.context.triggerListener({listenerType:Mr.CALL_CONFIRMED,session:r,event:l}),this.updateCall(r),r.id===this.callAddingInProgress&&(this.callAddingInProgress=void 0)}),await this.setupCall(t),r.direction==="outgoing"){const l=this.getActiveCalls[r.id].roomId;await this.setActiveRoom(l)}}setMuteWhenJoin(t){this.muteWhenJoinEnabled=t,this.context.emit("changeMuteWhenJoin",t)}setMicrophoneSensitivity(t){if(t<0||t>1)throw new Error("Value should be in range from 0 to 1!");this.microphoneInputLevelValue=t,this.roomReconfigure(this.currentActiveRoomId)}setSpeakerVolume(t){this.speakerVolumeValue=t,Object.values(this.extendedCalls).forEach(r=>{r.audioTag&&(r.audioTag.volume=t,this.updateCall(r))})}setAutoAnswer(t){this.isAutoAnswer=t}setSelectedInputDevice(t){localStorage.setItem(Wu.SELECTED_INPUT_DEVICE,t),this.selectedMediaDevices.input=t,this.context.emit("changeActiveInputMediaDevice",t)}setSelectedOutputDevice(t){localStorage.setItem(Wu.SELECTED_OUTPUT_DEVICE,t),this.selectedMediaDevices.output=t,this.context.emit("changeActiveOutputMediaDevice",t)}setCallMetrics(t){const r={...t};delete r.callId,this.callMetrics={...this.callMetrics,[t.callId]:r},this.context.emit("changeCallMetrics",this.callMetrics)}removeCallMetrics(t){const r={...this.callMetrics};delete r[t],this.callMetrics={...r},this.context.emit("changeCallMetrics",this.callMetrics)}getCallQuality(t){const r=new aI(this.metricConfig),l=r.createProbe(t.connection,{cid:t._id}),u=[];let s;l.onreport=n=>{Object.entries(n.audio).forEach(([v,C])=>{C.direction==="inbound"&&!u.includes(v)&&(u.push(v),s=v)});const g=n.audio[s];if(!g)return;const _=lI(g,oI);_.callId=t._id,this.setCallMetrics(_)},this.context.subscribe(Mr.CALL_ENDED,n=>{n._id===t._id&&r.stopAllProbes()}),r.startAllProbes()}async setupVUMeter(t,r){await this.VUMeter.start(await this.managedAudioContext.getContext(),t,r)}stopVUMeter(t){this.VUMeter.stop(t)}async setupStream(){try{const t=Date.now(),r=await navigator.mediaDevices.getUserMedia(this.getUserMediaConstraints);this.initialStreamValue&&(this.initialStreamValue.getTracks().forEach((u,s)=>{u.stop()}),this.initialStreamValue=null),this.initialStreamValue=r}catch(t){throw t}}async triggerAddStream(t,r){const l=this.muteWhenJoin||this.isMuted;this.setIsMuted(l),this.initialStreamValue||await this.setupStream();const u=await this.managedAudioContext.getContext(),s=await kd(u,this.initialStreamValue,this.microphoneInputLevel*2),n=this.isMuted||this.muteWhenJoin;s.getTracks().forEach(D=>{D.enabled=!n}),await this.setActiveStream(s),await r.connection.getSenders()[0].replaceTrack(s.getTracks()[0]);const v=new MediaStream([t.track]);!Object.values(this.extendedCalls).find(D=>D.audioTag&&D.audioTag.id===r._id)&&BC(v,r,this.selectedOutputDevice,this.speakerVolume);const R=r.roomId===this.currentActiveRoomId;r.audioTag&&(r.audioTag.muted=!R),await this.setupVUMeter(v,r._id),this.getCallQuality(r),this.updateCall(r),["enabled","dynamic"].includes(this.noiseReduction.mode)&&this.processVAD(r,s)}initCall(t,r,l=!1){if(t.length===0)return console.error("Target must be a valid string");this.context.logger.log(`Calling sip:${t}@${this.context.sipDomain}...`);const u=this.context.call(`sip:${t}@${this.context.sipDomain}`,this.sipOptions);if(this.callAddingInProgress=u.id,r&&this.currentActiveRoomId!==void 0&&(this.processRoomChange({callId:u.id,roomId:this.currentActiveRoomId}),l)){const s=Object.values(this.extendedCalls).filter(n=>n.roomId===this.currentActiveRoomId&&n._id!==u.id);for(const n of s)this.holdCall(n._id,!0)}u.connection.addEventListener("track",s=>{this.triggerAddStream(s,u)})}async processRoomChange({callId:t,roomId:r}){const l=this.extendedCalls[t];if(!l)return;const u=l.roomId;l.roomId=r,this.updateCall(l),await this.roomReconfigure(u),await this.roomReconfigure(r)}}class _I{constructor(t){this.context=t}get sipOptions(){return{...this.context.options.sipOptions}}initCall(t,r){if(t.length===0)return console.error("Target must be a valid string");this.context.logger.log(`Calling sip:${t}@${this.context.sipDomain}...`),this.context.joinVideoCall(`sip:${t}@${this.context.sipDomain}`,r,this.sipOptions)}stop(t={}){this.context.terminateJanusSessions(t)}startAudio(){this.context.enableJanusAudio(!0)}stopAudio(){this.context.enableJanusAudio(!1)}startVideo(){this.context.enableJanusVideo(!0)}stopVideo(){this.context.enableJanusVideo(!1)}changeMediaConstraints(t){this.context.changeMediaConstraints(t)}startScreenShare(){this.context.startScreenShare()}startBlur(){this.context.startBlur()}stopBlur(){this.context.stopBlur()}}class pI{constructor(t){this.activeMessages={},this.extendedMessages={},this.msrpHistory={},this.context=t,this.context.on(this.context.newMSRPSessionEventName,this.newMSRPSessionCallback.bind(this.context))}get isMSRPInitializing(){return this.isMSRPInitializingValue}get getActiveMessages(){return this.activeMessages}msrpAnswer(t){const r=this.extendedMessages[t];this.updateMSRPSession(r)}updateMSRPSession(t){this.activeMessages[t._id]=hp(t),this.context.emit("changeActiveMessages",this.activeMessages)}addMMSRPSession(t){this.activeMessages={...this.activeMessages,[t._id]:hp(t)},this.extendedMessages[t._id]=t,this.context.emit("changeActiveMessages",this.activeMessages)}addMSRPMessage(t,r){const l=this.msrpHistory[r.id]||[];l.push(t),this.msrpHistory={...this.msrpHistory,[r.id]:[...l]},this.context.emit("newMSRPMessage",{message:t,session:r})}messageTerminate(t){const r=this.extendedMessages[t];r._status!==8&&r.terminate()}addMessageSession(t){if(!t._id||this.getActiveMessages[t._id]!==void 0)return;const l=t;this.addMMSRPSession(l)}triggerMSRPListener({listenerType:t,session:r,event:l}){const u=this.context.listenersList[t];!u||!u.length||u.forEach(s=>{s(r,l)})}removeMMSRPSession(t){const r={...this.activeMessages};delete r[t],this.activeMessages={...r};const l={...this.extendedMessages};delete l[t],this.extendedMessages={...l},this.context.emit("changeActiveMessages",this.activeMessages)}activeMessageListRemove(t){this.removeMMSRPSession(t._id)}newMSRPSessionCallback(t){const r=t.session;r.on("ended",l=>{this.triggerMSRPListener({listenerType:Mr.CALL_ENDED,session:r,event:l});const u=this.getActiveMessages[r.id];this.activeMessageListRemove(u)}),r.on("failed",l=>{this.triggerMSRPListener({listenerType:Mr.CALL_FAILED,session:r,event:l});const u=this.getActiveMessages[r.id];this.activeMessageListRemove(u)}),r.on("confirmed",l=>{this.triggerMSRPListener({listenerType:Mr.CALL_CONFIRMED,session:r,event:l}),this.updateMSRPSession(r)}),r.on("newMessage",l=>{this.addMSRPMessage(l,r)}),this.addMessageSession(r)}setIsMSRPInitializing(t){this.isMSRPInitializingValue=t,this.context.emit("isMSRPInitializingChanged",t)}initMSRP(t,r,l){if(t.length===0)return console.error("Target must be a valid string");const u=this.context.startMSRP(t,l);u.on("active",()=>{this.addMessageSession(u),u.sendMSRP(r),this.setIsMSRPInitializing(!1)}),this.setIsMSRPInitializing(!0)}sendMSRP(t,r){const l=this.extendedMessages[t];if(!l)throw new Error(`MSRP session with id ${t} doesn't exist!`);l.sendMSRP(r)}}const Ku={AUDIO:"audio",VIDEO:"video",MSRP:"msrp"};class Vp{constructor(t){this.opensips=null,this.session=null,this.name=null,this.name=t}setOpensips(t){this.opensips=t}setSession(t){this.session=t}kill(){this.opensips.kill(this.name)}}class qp extends Vp{constructor(t,r){super(t),this._candidates=[],this._subscribeSent=!1,this._configureSent=!1,this._lastTrickleReceived=!1,this.type=r}connect(t={}){this.opaqueId=this.session.generateOpaqueId();const r=Nt.cloneArray(t.extraHeaders),l={from_tag:this.session._from_tag};t.fromUserName&&(l.from_uri=new Ia("sip",t.fromUserName,this.session._ua.configuration.uri.host),r.push(`P-Preferred-Identity: ${this.session._ua.configuration.uri.toString()}`)),t.fromDisplayName&&(l.from_display_name=t.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 Ds.InitialOutgoingInviteRequest(this.session.target,this.session._ua,l,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 t;this._connection.onicecandidate=r=>{this._connection.signalingState!=="stable"&&this._connection.signalingState!=="have-local-offer"||r.candidate&&(this._candidates.push(r.candidate),clearTimeout(t),t=setTimeout(()=>{this._lastTrickleReceived=!0,this._subscribeSent&&!this._configureSent&&this._sendConfigureMessage({audio:!0,video:!0})},500))}}addTracks(t){t.forEach(r=>{this._connection.addTrack(r)})}async _sendInitialRequest(){const t=new no(this.session._ua,this._request,{onRequestTimeout:()=>{this.session.onRequestTimeout()},onTransportError:()=>{this.session.onTransportError()},onAuthenticated:s=>{this._request=s},onReceiveResponse:s=>{this._receiveInviteResponse(s)}});if(await this.generateStream(),!this.stream||!this.stream.getTracks().length)return;this.addTracks(this.stream.getTracks());const r={audio:!1,video:!0};this.jsep_offer=await this._connection.createOffer(r),await this._connection.setLocalDescription(this.jsep_offer);const l={janus:"attach",plugin:"janus.plugin.videoroom",opaque_id:this.opaqueId},u=JSON.stringify(l);this._request.body=u,t.send()}_receiveInviteResponse(t){if(this._publisherSubscribeSent||!t.body)return;const r=JSON.parse(t.body);this.handleId=r.data.id;const l={janus:"message",body:{request:"join",room:this.session.room_id,ptype:"publisher",display:this.session.display_name+" (Screen Share)",opaque_id:this.opaqueId},handle_id:this.handleId},u=[this.session.getPTypeHeader(ir.PUBLISHER)];this.session.sendRequest(fe.SUBSCRIBE,{extraHeaders:u,body:JSON.stringify(l),eventHandlers:{onSuccessResponse:async s=>{var n,g,_,v;if(s.status_code===200){if(this._subscribeSent=!0,s.body)try{const C=JSON.parse(s.body)||{};((g=(n=C.plugindata)==null?void 0:n.data)==null?void 0:g.videoroom)==="joined"&&this.session.myFeedList.push(C.plugindata.data.id),(v=(_=C.plugindata)==null?void 0:_.data)!=null&&v.publishers&&this.session.receivePublishers(C)}catch(C){console.error(C)}this._lastTrickleReceived&&!this._configureSent&&this._sendConfigureMessage({audio:!0,video:!0})}}}}),this._publisherSubscribeSent=!0}async _sendConfigureMessage(t){const r=this._candidates.map(n=>({janus:"trickle",candidate:n,handle_id:this.handleId,session_id:this.session.session_id})),u={configure:{janus:"message",body:{request:"configure",record:!0,filename:this.session.getRecordFileName(),...t},jsep:this.jsep_offer,handle_id:this.handleId,session_id:this.session.session_id},trickles:[...r]},s=["Content-Type: application/json",this.session.getPTypeHeader(ir.ICE)];this.session.sendRequest(fe.INFO,{extraHeaders:s,body:JSON.stringify(u),eventHandlers:{onSuccessResponse:async n=>{this._configureSent=!0;const _=n.data.split(`\r
2990
+ */f.exports=r})(Sp);var bp=Sp.exports,Ud={},wp={};Object.defineProperty(wp,"__esModule",{value:!0});var Bu={},Ep;Object.defineProperty(Bu,"__esModule",{value:!0}),Bu.SileroLegacy=void 0;const Cp=vl;class Pd{constructor(t,r,l,u,s){this.ortInstance=t,this._session=r,this._h=l,this._c=u,this._sr=s,this.reset_state=()=>{const n=Array(128).fill(0);this._h=new this.ortInstance.Tensor("float32",n,[2,1,64]),this._c=new this.ortInstance.Tensor("float32",n,[2,1,64])},this.process=async n=>{var D;const _={input:new this.ortInstance.Tensor("float32",n,[1,n.length]),h:this._h,c:this._c,sr:this._sr},v=await this._session.run(_);this._h=v.hn,this._c=v.cn;const[C]=(D=v.output)==null?void 0:D.data;return{notSpeech:1-C,isSpeech:C}}}}Bu.SileroLegacy=Pd,Ep=Pd,Pd.new=async(f,t)=>{Cp.log.debug("initializing vad");const r=await t(),l=await f.InferenceSession.create(r),u=new f.Tensor("int64",[16000n]),s=Array(2*64).fill(0),n=new f.Tensor("float32",s,[2,1,64]),g=new f.Tensor("float32",s,[2,1,64]);return Cp.log.debug("vad is initialized"),new Ep(f,l,n,g,u)};var zu={},Ap;Object.defineProperty(zu,"__esModule",{value:!0}),zu.SileroV5=void 0;const Ip=vl;function Rp(f){const t=Array(256).fill(0);return new f.Tensor("float32",t,[2,1,128])}class Ld{constructor(t,r,l,u){this._session=t,this._state=r,this._sr=l,this.ortInstance=u,this.reset_state=()=>{this._state=Rp(this.ortInstance)},this.process=async s=>{var R;const g={input:new this.ortInstance.Tensor("float32",s,[1,s.length]),state:this._state,sr:this._sr},_=await this._session.run(g);this._state=_.stateN;const[v]=(R=_.output)==null?void 0:R.data;return{notSpeech:1-v,isSpeech:v}}}}zu.SileroV5=Ld,Ap=Ld,Ld.new=async(f,t)=>{Ip.log.debug("Loading VAD...");const r=await t(),l=await f.InferenceSession.create(r),u=new f.Tensor("int64",[16000n]),s=Rp(f);return Ip.log.debug("...finished loading VAD"),new Ap(l,s,u,f)},function(f){var t=Lt&&Lt.__createBinding||(Object.create?function(s,n,g,_){_===void 0&&(_=g);var v=Object.getOwnPropertyDescriptor(n,g);(!v||("get"in v?!n.__esModule:v.writable||v.configurable))&&(v={enumerable:!0,get:function(){return n[g]}}),Object.defineProperty(s,_,v)}:function(s,n,g,_){_===void 0&&(_=g),s[_]=n[g]}),r=Lt&&Lt.__exportStar||function(s,n){for(var g in s)g!=="default"&&!Object.prototype.hasOwnProperty.call(n,g)&&t(n,s,g)};Object.defineProperty(f,"__esModule",{value:!0}),f.SileroV5=f.SileroLegacy=void 0,r(wp,f);var l=Bu;Object.defineProperty(f,"SileroLegacy",{enumerable:!0,get:function(){return l.SileroLegacy}});var u=zu;Object.defineProperty(f,"SileroV5",{enumerable:!0,get:function(){return u.SileroV5}})}(Ud);var vo={};Object.defineProperty(vo,"__esModule",{value:!0}),vo.Resampler=void 0;const uA=vl;class cA{constructor(t){this.options=t,this.process=r=>{const l=[];for(const u of r)for(this.inputBuffer.push(u);this.hasEnoughDataForFrame();){const s=this.generateOutputFrame();l.push(s)}return l},t.nativeSampleRate<16e3&&uA.log.error("nativeSampleRate is too low. Should have 16000 = targetSampleRate <= nativeSampleRate"),this.inputBuffer=[]}async*stream(t){for(const r of t)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 t=new Float32Array(this.options.targetFrameSize);let r=0,l=0;for(;r<this.options.targetFrameSize;){let u=0,s=0;for(;l<Math.min(this.inputBuffer.length,(r+1)*this.options.nativeSampleRate/this.options.targetSampleRate);){const n=this.inputBuffer[l];n!==void 0&&(u+=n,s++),l++}t[r]=u/s,r++}return this.inputBuffer=this.inputBuffer.slice(l),t}}vo.Resampler=cA,function(f){var t=Lt&&Lt.__createBinding||(Object.create?function(D,H,F,q){q===void 0&&(q=F);var G=Object.getOwnPropertyDescriptor(H,F);(!G||("get"in G?!H.__esModule:G.writable||G.configurable))&&(G={enumerable:!0,get:function(){return H[F]}}),Object.defineProperty(D,q,G)}:function(D,H,F,q){q===void 0&&(q=F),D[q]=H[F]}),r=Lt&&Lt.__setModuleDefault||(Object.create?function(D,H){Object.defineProperty(D,"default",{enumerable:!0,value:H})}:function(D,H){D.default=H}),l=Lt&&Lt.__importStar||function(D){if(D&&D.__esModule)return D;var H={};if(D!=null)for(var F in D)F!=="default"&&Object.prototype.hasOwnProperty.call(D,F)&&t(H,D,F);return r(H,D),H};Object.defineProperty(f,"__esModule",{value:!0}),f.NonRealTimeVAD=f.defaultNonRealTimeVADOptions=void 0;const u=l(bp),s=mo,n=gl,g=hn,_=Ra,v=Ud,C=vo;f.defaultNonRealTimeVADOptions={...g.defaultFrameProcessorOptions,modelURL:s.baseAssetPath+"silero_vad_legacy.onnx",modelFetcher:n.defaultModelFetcher};class R{static async new(H={}){const F={...f.defaultNonRealTimeVADOptions,...H};(0,g.validateOptions)(F),F.ortConfig!==void 0&&F.ortConfig(u);const q=()=>F.modelFetcher(F.modelURL),G=await v.SileroLegacy.new(u,q),te=new g.FrameProcessor(G.process,G.reset_state,{positiveSpeechThreshold:F.positiveSpeechThreshold,negativeSpeechThreshold:F.negativeSpeechThreshold,redemptionMs:F.redemptionMs,preSpeechPadMs:F.preSpeechPadMs,minSpeechMs:F.minSpeechMs,submitUserSpeechOnPause:F.submitUserSpeechOnPause},1536/16);return te.resume(),new this(q,u,F,te)}constructor(H,F,q,G){this.modelFetcher=H,this.ort=F,this.options=q,this.frameProcessor=G,this.frameSamples=1536}async*run(H,F){const q={nativeSampleRate:F,targetSampleRate:16e3,targetFrameSize:this.frameSamples},G=new C.Resampler(q);let te=0,X=0,we=0;for await(const re of G.stream(H)){const ke=[];await this.frameProcessor.process(re,Ne=>{ke.push(Ne)});for(const Ne of ke)switch(Ne.msg){case _.Message.SpeechStart:te=we*this.frameSamples/16;break;case _.Message.SpeechEnd:X=(we+1)*this.frameSamples/16,yield{audio:Ne.audio,start:te,end:X};break}we++}const Q=[];this.frameProcessor.endSegment(re=>{Q.push(re)});for(const re of Q)switch(re.msg){case _.Message.SpeechEnd:yield{audio:re.audio,start:te,end:we*this.frameSamples/16}}}}f.NonRealTimeVAD=R}(Tp);var _n={};Object.defineProperty(_n,"__esModule",{value:!0}),_n.audioFileToArray=_n.encodeWAV=_n.arrayBufferToBase64=_n.minFramesForTargetMS=void 0;function dA(f,t,r=16e3){return Math.ceil(f*r/1e3/t)}_n.minFramesForTargetMS=dA;function fA(f){const t=new Uint8Array(f),r=t.byteLength,l=new Array(r);for(var u=0;u<r;u++){const s=t[u];if(s===void 0)break;l[u]=String.fromCharCode(s)}return btoa(l.join(""))}_n.arrayBufferToBase64=fA;function hA(f,t=3,r=16e3,l=1,u=32){var s=u/8,n=l*s,g=new ArrayBuffer(44+f.length*s),_=new DataView(g);return Vu(_,0,"RIFF"),_.setUint32(4,36+f.length*s,!0),Vu(_,8,"WAVE"),Vu(_,12,"fmt "),_.setUint32(16,16,!0),_.setUint16(20,t,!0),_.setUint16(22,l,!0),_.setUint32(24,r,!0),_.setUint32(28,r*n,!0),_.setUint16(32,n,!0),_.setUint16(34,u,!0),Vu(_,36,"data"),_.setUint32(40,f.length*s,!0),t===1?pA(_,44,f):_A(_,44,f),g}_n.encodeWAV=hA;function _A(f,t,r){for(var l=0;l<r.length;l++,t+=4)f.setFloat32(t,r[l],!0)}function pA(f,t,r){for(var l=0;l<r.length;l++,t+=2){var u=Math.max(-1,Math.min(1,r[l]));f.setInt16(t,u<0?u*32768:u*32767,!0)}}function Vu(f,t,r){for(var l=0;l<r.length;l++)f.setUint8(t+l,r.charCodeAt(l))}async function mA(f){const t=new OfflineAudioContext(1,1,44100),r=new FileReader;let l=null;if(await new Promise(n=>{r.addEventListener("loadend",g=>{const _=r.result;t.decodeAudioData(_,v=>{l=v,t.startRendering().then(C=>{console.log("Rendering completed successfully"),n()}).catch(C=>{console.error(`Rendering failed: ${C}`)})},v=>{console.log(`Error with decoding audio data: ${v}`)})}),r.readAsArrayBuffer(f)}),l===null)throw Error("some shit");let u=l,s=new Float32Array(u.length);for(let n=0;n<u.length;n++)for(let g=0;g<u.numberOfChannels;g++)s[n]+=u.getChannelData(g)[n];return{audio:s,sampleRate:u.sampleRate}}_n.audioFileToArray=mA;var $p={};(function(f){var t=Lt&&Lt.__createBinding||(Object.create?function(te,X,we,Q){Q===void 0&&(Q=we);var re=Object.getOwnPropertyDescriptor(X,we);(!re||("get"in re?!X.__esModule:re.writable||re.configurable))&&(re={enumerable:!0,get:function(){return X[we]}}),Object.defineProperty(te,Q,re)}:function(te,X,we,Q){Q===void 0&&(Q=we),te[Q]=X[we]}),r=Lt&&Lt.__setModuleDefault||(Object.create?function(te,X){Object.defineProperty(te,"default",{enumerable:!0,value:X})}:function(te,X){te.default=X}),l=Lt&&Lt.__importStar||function(te){if(te&&te.__esModule)return te;var X={};if(te!=null)for(var we in te)we!=="default"&&Object.prototype.hasOwnProperty.call(te,we)&&t(X,te,we);return r(X,te),X};Object.defineProperty(f,"__esModule",{value:!0}),f.AudioNodeVAD=f.MicVAD=f.getDefaultRealTimeVADOptions=f.ort=f.DEFAULT_MODEL=void 0;const u=l(bp),s=gl,n=hn,g=vl,_=Ra,v=Ud,C=vo;f.DEFAULT_MODEL="legacy",f.ort=u;const R="vad.worklet.bundle.min.js",D="silero_vad_v5.onnx",H="silero_vad_legacy.onnx",F=te=>({...n.defaultFrameProcessorOptions,onFrameProcessed:(X,we)=>{},onVADMisfire:()=>{g.log.debug("VAD misfire")},onSpeechStart:()=>{g.log.debug("Detected speech start")},onSpeechEnd:()=>{g.log.debug("Detected speech end")},onSpeechRealStart:()=>{g.log.debug("Detected real speech start")},baseAssetPath:"./",onnxWASMBasePath:"./",model:te,workletOptions:{},getStream:async()=>await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0}}),pauseStream:async X=>{X.getTracks().forEach(we=>{we.stop()})},resumeStream:async X=>await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0}}),ortConfig:X=>{X.env.logLevel="error"},startOnLoad:!0});f.getDefaultRealTimeVADOptions=F;class q{static async new(X={}){const we={...(0,f.getDefaultRealTimeVADOptions)(X.model??f.DEFAULT_MODEL),...X};(0,n.validateOptions)(we);const Q=new AudioContext,re=await G.new(Q,we),ke=new q(we,Q,re);if(we.startOnLoad)try{await ke.start()}catch(Ne){console.error("Error starting micVad",Ne)}return ke}constructor(X,we,Q,re=!1){this.options=X,this.audioContext=we,this.audioNodeVAD=Q,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()=>{var ke;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)),(ke=this.stream)!=null&&ke.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=ke=>{this.audioNodeVAD.setFrameProcessorOptions(ke)}}}f.MicVAD=q;class G{static async new(X,we={}){const Q={...(0,f.getDefaultRealTimeVADOptions)(we.model??f.DEFAULT_MODEL),...we};(0,n.validateOptions)(Q),f.ort.env.wasm.wasmPaths=Q.onnxWASMBasePath,Q.ortConfig!==void 0&&Q.ortConfig(f.ort);const re=Q.model==="v5"?D:H,ke=Q.baseAssetPath+re,Ne=Q.model==="v5"?v.SileroV5.new:v.SileroLegacy.new;let Z;try{Z=await Ne(f.ort,()=>(0,s.defaultModelFetcher)(ke))}catch(_e){throw console.error(`Encountered an error while loading model file ${ke}`),_e}const se=Q.model==="v5"?512:1536,pe=se/16,me=new n.FrameProcessor(Z.process,Z.reset_state,{positiveSpeechThreshold:Q.positiveSpeechThreshold,negativeSpeechThreshold:Q.negativeSpeechThreshold,redemptionMs:Q.redemptionMs,preSpeechPadMs:Q.preSpeechPadMs,minSpeechMs:Q.minSpeechMs,submitUserSpeechOnPause:Q.submitUserSpeechOnPause},pe),be=new G(X,Q,me,se,pe);return await be.setupAudioNode(),be}constructor(X,we,Q,re,ke){this.ctx=X,this.options=we,this.frameSamples=re,this.msPerFrame=ke,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 _.Message.FrameProcessed:this.options.onFrameProcessed(Ne.probs,Ne.frame);break;case _.Message.SpeechStart:this.options.onSpeechStart();break;case _.Message.SpeechRealStart:this.options.onSpeechRealStart();break;case _.Message.VADMisfire:this.options.onVADMisfire();break;case _.Message.SpeechEnd:this.options.onSpeechEnd(Ne.audio);break}},this.destroy=()=>{var Ne;this.audioNode instanceof AudioWorkletNode&&this.audioNode.port.postMessage({message:_.Message.SpeechStop}),this.audioNode.disconnect(),(Ne=this.gainNode)==null||Ne.disconnect()},this.setFrameProcessorOptions=Ne=>{this.frameProcessor.options={...this.frameProcessor.options,...Ne}},this.frameProcessor=Q}async setupAudioNode(){if("audioWorklet"in this.ctx&&typeof AudioWorkletNode=="function")try{const re=this.options.baseAssetPath+R;await this.ctx.audioWorklet.addModule(re);const ke=this.options.workletOptions??{};ke.processorOptions={...ke.processorOptions??{},frameSamples:this.frameSamples},this.audioNode=new AudioWorkletNode(this.ctx,"vad-helper-worklet",ke),this.audioNode.port.onmessage=async Ne=>{var Z;switch((Z=Ne.data)==null?void 0:Z.message){case _.Message.AudioFrame:let se=Ne.data.data;se instanceof ArrayBuffer||(se=new ArrayBuffer(Ne.data.data.byteLength),new Uint8Array(se).set(new Uint8Array(Ne.data.data)));const pe=new Float32Array(se);await this.processFrame(pe);break}};return}catch(re){console.log("AudioWorklet setup failed, falling back to ScriptProcessor",re)}this.resampler=new C.Resampler({nativeSampleRate:this.ctx.sampleRate,targetSampleRate:16e3,targetFrameSize:this.frameSamples??480});const we=4096;this.audioNode=this.ctx.createScriptProcessor(we,1,1),this.gainNode=this.ctx.createGain(),this.gainNode.gain.value=0;let Q=!1;this.audioNode.onaudioprocess=async re=>{if(!Q){Q=!0;try{const ke=re.inputBuffer.getChannelData(0);if(re.outputBuffer.getChannelData(0).fill(0),this.resampler){const Z=this.resampler.process(ke);for(const se of Z)await this.processFrame(se)}}catch(ke){console.error("Error processing audio:",ke)}finally{Q=!1}}},this.audioNode.connect(this.gainNode),this.gainNode.connect(this.ctx.destination)}}f.AudioNodeVAD=G})($p),function(f){Object.defineProperty(f,"__esModule",{value:!0}),f.getDefaultRealTimeVADOptions=f.MicVAD=f.DEFAULT_MODEL=f.AudioNodeVAD=f.utils=f.NonRealTimeVAD=f.Message=f.FrameProcessor=f.defaultModelFetcher=f.baseAssetPath=void 0;var t=mo;Object.defineProperty(f,"baseAssetPath",{enumerable:!0,get:function(){return t.baseAssetPath}});var r=gl;Object.defineProperty(f,"defaultModelFetcher",{enumerable:!0,get:function(){return r.defaultModelFetcher}});var l=hn;Object.defineProperty(f,"FrameProcessor",{enumerable:!0,get:function(){return l.FrameProcessor}});var u=Ra;Object.defineProperty(f,"Message",{enumerable:!0,get:function(){return u.Message}});var s=Tp;Object.defineProperty(f,"NonRealTimeVAD",{enumerable:!0,get:function(){return s.NonRealTimeVAD}});const n=_n;f.utils={audioFileToArray:n.audioFileToArray,minFramesForTargetMS:n.minFramesForTargetMS,arrayBufferToBase64:n.arrayBufferToBase64,encodeWAV:n.encodeWAV};var g=$p;Object.defineProperty(f,"AudioNodeVAD",{enumerable:!0,get:function(){return g.AudioNodeVAD}}),Object.defineProperty(f,"DEFAULT_MODEL",{enumerable:!0,get:function(){return g.DEFAULT_MODEL}}),Object.defineProperty(f,"MicVAD",{enumerable:!0,get:function(){return g.MicVAD}}),Object.defineProperty(f,"getDefaultRealTimeVADOptions",{enumerable:!0,get:function(){return g.getDefaultRealTimeVADOptions}})}(pp);const Mr={NEW_CALL:"new_call",CALL_CONFIRMED:"confirmed",CALL_FAILED:"failed",CALL_PROGRESS:"progress",CALL_ENDED:"ended"};var gA={exports:{}};(function(f){var t=function(r){var l=Object.prototype,u=l.hasOwnProperty,s=Object.defineProperty||function(Re,ye,ge){Re[ye]=ge.value},n,g=typeof Symbol=="function"?Symbol:{},_=g.iterator||"@@iterator",v=g.asyncIterator||"@@asyncIterator",C=g.toStringTag||"@@toStringTag";function R(Re,ye,ge){return Object.defineProperty(Re,ye,{value:ge,enumerable:!0,configurable:!0,writable:!0}),Re[ye]}try{R({},"")}catch{R=function(ye,ge,Le){return ye[ge]=Le}}function D(Re,ye,ge,Le){var et=ye&&ye.prototype instanceof we?ye:we,vt=Object.create(et.prototype),xt=new oe(Le||[]);return s(vt,"_invoke",{value:be(Re,ge,xt)}),vt}r.wrap=D;function H(Re,ye,ge){try{return{type:"normal",arg:Re.call(ye,ge)}}catch(Le){return{type:"throw",arg:Le}}}var F="suspendedStart",q="suspendedYield",G="executing",te="completed",X={};function we(){}function Q(){}function re(){}var ke={};R(ke,_,function(){return this});var Ne=Object.getPrototypeOf,Z=Ne&&Ne(Ne(Oe([])));Z&&Z!==l&&u.call(Z,_)&&(ke=Z);var se=re.prototype=we.prototype=Object.create(ke);Q.prototype=re,s(se,"constructor",{value:re,configurable:!0}),s(re,"constructor",{value:Q,configurable:!0}),Q.displayName=R(re,C,"GeneratorFunction");function pe(Re){["next","throw","return"].forEach(function(ye){R(Re,ye,function(ge){return this._invoke(ye,ge)})})}r.isGeneratorFunction=function(Re){var ye=typeof Re=="function"&&Re.constructor;return ye?ye===Q||(ye.displayName||ye.name)==="GeneratorFunction":!1},r.mark=function(Re){return Object.setPrototypeOf?Object.setPrototypeOf(Re,re):(Re.__proto__=re,R(Re,C,"GeneratorFunction")),Re.prototype=Object.create(se),Re},r.awrap=function(Re){return{__await:Re}};function me(Re,ye){function ge(vt,xt,dt,ze){var Ye=H(Re[vt],Re,xt);if(Ye.type==="throw")ze(Ye.arg);else{var Zt=Ye.arg,Mt=Zt.value;return Mt&&typeof Mt=="object"&&u.call(Mt,"__await")?ye.resolve(Mt.__await).then(function(nt){ge("next",nt,dt,ze)},function(nt){ge("throw",nt,dt,ze)}):ye.resolve(Mt).then(function(nt){Zt.value=nt,dt(Zt)},function(nt){return ge("throw",nt,dt,ze)})}}var Le;function et(vt,xt){function dt(){return new ye(function(ze,Ye){ge(vt,xt,ze,Ye)})}return Le=Le?Le.then(dt,dt):dt()}s(this,"_invoke",{value:et})}pe(me.prototype),R(me.prototype,v,function(){return this}),r.AsyncIterator=me,r.async=function(Re,ye,ge,Le,et){et===void 0&&(et=Promise);var vt=new me(D(Re,ye,ge,Le),et);return r.isGeneratorFunction(ye)?vt:vt.next().then(function(xt){return xt.done?xt.value:vt.next()})};function be(Re,ye,ge){var Le=F;return function(vt,xt){if(Le===G)throw new Error("Generator is already running");if(Le===te){if(vt==="throw")throw xt;return rs()}for(ge.method=vt,ge.arg=xt;;){var dt=ge.delegate;if(dt){var ze=_e(dt,ge);if(ze){if(ze===X)continue;return ze}}if(ge.method==="next")ge.sent=ge._sent=ge.arg;else if(ge.method==="throw"){if(Le===F)throw Le=te,ge.arg;ge.dispatchException(ge.arg)}else ge.method==="return"&&ge.abrupt("return",ge.arg);Le=G;var Ye=H(Re,ye,ge);if(Ye.type==="normal"){if(Le=ge.done?te:q,Ye.arg===X)continue;return{value:Ye.arg,done:ge.done}}else Ye.type==="throw"&&(Le=te,ge.method="throw",ge.arg=Ye.arg)}}}function _e(Re,ye){var ge=ye.method,Le=Re.iterator[ge];if(Le===n)return ye.delegate=null,ge==="throw"&&Re.iterator.return&&(ye.method="return",ye.arg=n,_e(Re,ye),ye.method==="throw")||ge!=="return"&&(ye.method="throw",ye.arg=new TypeError("The iterator does not provide a '"+ge+"' method")),X;var et=H(Le,Re.iterator,ye.arg);if(et.type==="throw")return ye.method="throw",ye.arg=et.arg,ye.delegate=null,X;var vt=et.arg;if(!vt)return ye.method="throw",ye.arg=new TypeError("iterator result is not an object"),ye.delegate=null,X;if(vt.done)ye[Re.resultName]=vt.value,ye.next=Re.nextLoc,ye.method!=="return"&&(ye.method="next",ye.arg=n);else return vt;return ye.delegate=null,X}pe(se),R(se,C,"Generator"),R(se,_,function(){return this}),R(se,"toString",function(){return"[object Generator]"});function Ae(Re){var ye={tryLoc:Re[0]};1 in Re&&(ye.catchLoc=Re[1]),2 in Re&&(ye.finallyLoc=Re[2],ye.afterLoc=Re[3]),this.tryEntries.push(ye)}function le(Re){var ye=Re.completion||{};ye.type="normal",delete ye.arg,Re.completion=ye}function oe(Re){this.tryEntries=[{tryLoc:"root"}],Re.forEach(Ae,this),this.reset(!0)}r.keys=function(Re){var ye=Object(Re),ge=[];for(var Le in ye)ge.push(Le);return ge.reverse(),function et(){for(;ge.length;){var vt=ge.pop();if(vt in ye)return et.value=vt,et.done=!1,et}return et.done=!0,et}};function Oe(Re){if(Re){var ye=Re[_];if(ye)return ye.call(Re);if(typeof Re.next=="function")return Re;if(!isNaN(Re.length)){var ge=-1,Le=function et(){for(;++ge<Re.length;)if(u.call(Re,ge))return et.value=Re[ge],et.done=!1,et;return et.value=n,et.done=!0,et};return Le.next=Le}}return{next:rs}}r.values=Oe;function rs(){return{value:n,done:!0}}return oe.prototype={constructor:oe,reset:function(Re){if(this.prev=0,this.next=0,this.sent=this._sent=n,this.done=!1,this.delegate=null,this.method="next",this.arg=n,this.tryEntries.forEach(le),!Re)for(var ye in this)ye.charAt(0)==="t"&&u.call(this,ye)&&!isNaN(+ye.slice(1))&&(this[ye]=n)},stop:function(){this.done=!0;var Re=this.tryEntries[0],ye=Re.completion;if(ye.type==="throw")throw ye.arg;return this.rval},dispatchException:function(Re){if(this.done)throw Re;var ye=this;function ge(ze,Ye){return vt.type="throw",vt.arg=Re,ye.next=ze,Ye&&(ye.method="next",ye.arg=n),!!Ye}for(var Le=this.tryEntries.length-1;Le>=0;--Le){var et=this.tryEntries[Le],vt=et.completion;if(et.tryLoc==="root")return ge("end");if(et.tryLoc<=this.prev){var xt=u.call(et,"catchLoc"),dt=u.call(et,"finallyLoc");if(xt&&dt){if(this.prev<et.catchLoc)return ge(et.catchLoc,!0);if(this.prev<et.finallyLoc)return ge(et.finallyLoc)}else if(xt){if(this.prev<et.catchLoc)return ge(et.catchLoc,!0)}else if(dt){if(this.prev<et.finallyLoc)return ge(et.finallyLoc)}else throw new Error("try statement without catch or finally")}}},abrupt:function(Re,ye){for(var ge=this.tryEntries.length-1;ge>=0;--ge){var Le=this.tryEntries[ge];if(Le.tryLoc<=this.prev&&u.call(Le,"finallyLoc")&&this.prev<Le.finallyLoc){var et=Le;break}}et&&(Re==="break"||Re==="continue")&&et.tryLoc<=ye&&ye<=et.finallyLoc&&(et=null);var vt=et?et.completion:{};return vt.type=Re,vt.arg=ye,et?(this.method="next",this.next=et.finallyLoc,X):this.complete(vt)},complete:function(Re,ye){if(Re.type==="throw")throw Re.arg;return Re.type==="break"||Re.type==="continue"?this.next=Re.arg:Re.type==="return"?(this.rval=this.arg=Re.arg,this.method="return",this.next="end"):Re.type==="normal"&&ye&&(this.next=ye),X},finish:function(Re){for(var ye=this.tryEntries.length-1;ye>=0;--ye){var ge=this.tryEntries[ye];if(ge.finallyLoc===Re)return this.complete(ge.completion,ge.afterLoc),le(ge),X}},catch:function(Re){for(var ye=this.tryEntries.length-1;ye>=0;--ye){var ge=this.tryEntries[ye];if(ge.tryLoc===Re){var Le=ge.completion;if(Le.type==="throw"){var et=Le.arg;le(ge)}return et}}throw new Error("illegal catch attempt")},delegateYield:function(Re,ye,ge){return this.delegate={iterator:Oe(Re),resultName:ye,nextLoc:ge},this.method==="next"&&(this.arg=n),X}},r}(f.exports);try{regeneratorRuntime=t}catch{typeof globalThis=="object"?globalThis.regeneratorRuntime=t:Function("r","regeneratorRuntime = r")(t)}})(gA);var xp={exports:{}};(function(f){(function(t,r){f.exports?f.exports=r():t.log=r()})(Lt,function(){var t=function(){},r="undefined",l=typeof window!==r&&typeof window.navigator!==r&&/Trident\/|MSIE /.test(window.navigator.userAgent),u=["trace","debug","info","warn","error"];function s(q,G){var te=q[G];if(typeof te.bind=="function")return te.bind(q);try{return Function.prototype.bind.call(te,q)}catch{return function(){return Function.prototype.apply.apply(te,[q,arguments])}}}function n(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function g(q){return q==="debug"&&(q="log"),typeof console===r?!1:q==="trace"&&l?n:console[q]!==void 0?s(console,q):console.log!==void 0?s(console,"log"):t}function _(q,G){for(var te=0;te<u.length;te++){var X=u[te];this[X]=te<q?t:this.methodFactory(X,q,G)}this.log=this.debug}function v(q,G,te){return function(){typeof console!==r&&(_.call(this,G,te),this[q].apply(this,arguments))}}function C(q,G,te){return g(q)||v.apply(this,arguments)}function R(q,G,te){var X=this,we;G=G??"WARN";var Q="loglevel";typeof q=="string"?Q+=":"+q:typeof q=="symbol"&&(Q=void 0);function re(se){var pe=(u[se]||"silent").toUpperCase();if(!(typeof window===r||!Q)){try{window.localStorage[Q]=pe;return}catch{}try{window.document.cookie=encodeURIComponent(Q)+"="+pe+";"}catch{}}}function ke(){var se;if(!(typeof window===r||!Q)){try{se=window.localStorage[Q]}catch{}if(typeof se===r)try{var pe=window.document.cookie,me=pe.indexOf(encodeURIComponent(Q)+"=");me!==-1&&(se=/^([^;]+)/.exec(pe.slice(me))[1])}catch{}return X.levels[se]===void 0&&(se=void 0),se}}function Ne(){if(!(typeof window===r||!Q)){try{window.localStorage.removeItem(Q);return}catch{}try{window.document.cookie=encodeURIComponent(Q)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch{}}}X.name=q,X.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},X.methodFactory=te||C,X.getLevel=function(){return we},X.setLevel=function(se,pe){if(typeof se=="string"&&X.levels[se.toUpperCase()]!==void 0&&(se=X.levels[se.toUpperCase()]),typeof se=="number"&&se>=0&&se<=X.levels.SILENT){if(we=se,pe!==!1&&re(se),_.call(X,se,q),typeof console===r&&se<X.levels.SILENT)return"No console available for logging"}else throw"log.setLevel() called with invalid level: "+se},X.setDefaultLevel=function(se){G=se,ke()||X.setLevel(se,!1)},X.resetLevel=function(){X.setLevel(G,!1),Ne()},X.enableAll=function(se){X.setLevel(X.levels.TRACE,se)},X.disableAll=function(se){X.setLevel(X.levels.SILENT,se)};var Z=ke();Z==null&&(Z=G),X.setLevel(Z,!1)}var D=new R,H={};D.getLogger=function(G){if(typeof G!="symbol"&&typeof G!="string"||G==="")throw new TypeError("You must supply a name when creating a logger.");var te=H[G];return te||(te=H[G]=new R(G,D.getLevel(),D.methodFactory)),te};var F=typeof window!==r?window.log:void 0;return D.noConflict=function(){return typeof window!==r&&window.log===D&&(window.log=F),D},D.getLoggers=function(){return H},D.default=D,D})})(xp);var zs=xp.exports;const Hn=()=>`${new Date().toISOString()} | metrics`,Fn=(f,t,r)=>`${f} | ${t} | ${r}`;zs.setDefaultLevel(zs.levels.TRACE);const vA=f=>{zs.info(Fn(Hn(),"log ",`set log level to ${f?"verbose":"info"}`)),zs.setLevel(f?zs.levels.TRACE:zs.levels.INFO)},yA=f=>{const t=[...Object.keys(zs.levels)];t.includes(f)?(zs.info(Fn(Hn(),"log ",`update log level to ${f.toLowerCase()}`)),zs.setLevel(f)):zs.warn(Fn(Hn(),"log ","Incorrect log level please choose one of "),t)},Ot=(f,t,r)=>{r?zs.debug(Fn(Hn(),f,t),r):zs.debug(Fn(Hn(),f,t))},Hd=(f,t)=>{zs.info(Fn(Hn(),f,t))},xa=(f,t)=>{zs.info(Fn(Hn(),f,t))},qu=(f,t)=>{zs.warn(Fn(Hn(),f,t))},Tl=(f,t)=>{zs.error(Fn(Hn(),f,t))};function TA(f){return Math.floor(Math.random()*f).toString()}function Op(f,t){let r=t;return f.forEach(l=>{r=r.replace(l,"")}),r}function SA(f,t){let r="";for(let l=0;l<t;l+=1)r+=f[TA(f.length)];return r}function bA({length:f=20,useLetters:t=!0,useNumbers:r=!0,includeSymbols:l=[],excludeSymbols:u=[]}={}){let s="abcdefghijklmnopqrstuvwxyz",n="0123456789",g=[],_=[],v=[];return t&&(u.length&&(s=Op(u,s)),_=s.split("")),r&&(u.length&&(n=Op(u,n)),v=n.split("")),g=[..._,...v,...l],SA(g,f)}var wA=bA;const yo=Ht(wA),EA=()=>"WebRTCMetrics",CA=()=>"5.0.3",zt={INBOUND:"inbound",OUTBOUND:"outbound"},Bn={IDLE:"idle",RUNNING:"running",MUTED:"muted"},To={NEW:"new",CHECKING:"checking",CONNECTED:"connected",COMPLETED:"completed",DISCONNECTED:"disconnected",FAILED:"failed",CLOSED:"closed"},AA=()=>({...{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:[]}}),Dp={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:zt.INBOUND},kp={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:zt.OUTBOUND},Np={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:zt.INBOUND},Mp={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:zt.OUTBOUND},IA=f=>{const t={pname:"",call_id:"",user_id:"",timestamp:null,count:0,audio:{},video:{},network:{infrastructure:3,local_candidate_id:"",local_candidate_type:"",local_candidate_protocol:"",local_candidate_relay_protocol:"",remote_candidate_id:"",remote_candidate_type:"",remote_candidate_protocol:""},data:{total_KBytes_in:0,total_KBytes_out:0,delta_KBytes_in:0,delta_KBytes_out:0,delta_kbs_in:0,delta_kbs_out:0,delta_kbs_bandwidth_in:0,delta_kbs_bandwidth_out:0,delta_rtt_connectivity_ms:null,total_rtt_connectivity_ms:0,total_rtt_connectivity_measure:0},experimental:{time_to_measure_ms:0}};if(f){const r={...f,audio:{},video:{},data:{...f.data},network:{...f.network},experimental:{...f.experimental}};return Object.keys(f.audio).forEach(l=>{r.audio[l]={...f.audio[l]}}),Object.keys(f.video).forEach(l=>{r.video[l]={...f.video[l]}}),r}return{...t,audio:{},video:{},data:{...t.data},network:{...t.network},experimental:{...t.experimental}}},RA={refreshEvery:2e3,startAfter:0,stopAfter:-1,verbose:!1,pname:`p-${yo()}`,cid:`c-${yo()}`,uid:`u-${yo()}`,record:!1,ticket:!0},Ur={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"},Te={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"},ue={SUCCEEDED:"succeeded",AUDIO:"audio",VIDEO:"video"},So={ETHERNET:0,CELLULAR_5G:2,WIFI:3,CELLULAR_4G:5,CELLULAR:10},Fd={ETHERNET:"ethernet",CELLULAR_4G:"cellular",WIFI:"wifi"},Me={AUDIO:"audio",VIDEO:"video",NETWORK:"network",DATA:"data"},Bd="config ",$A=(f,t={},r)=>{const l={...r,...t};return t.pname||qu(Bd,`Argument [String] 'cfg.pname' for the peerConnection name or id is missing - use generated '${r.pname}'`),t.cid||qu(Bd,`Argument [String] 'cfg.cid' for the call name or id is missing - use generated '${r.cid}'`),t.uid||qu(Bd,`Argument [String] 'cfg.uid' for the user name or id is missing - use generated '${r.uid}'`),l.pc=f,l},xA=(f={})=>{const t={...RA,...f};return t.name=EA(),t.version=CA(),t},bo=(f,t,r,l=!1,u)=>{let s=f.map(n=>{if(!r)return n[t];if(!u)return n[t][r];const g=n[t][u];return g?g[r]:null});return s=s.filter(n=>l?Number.isFinite(n)&&n>0:Number.isFinite(n)),s.length===0?[]:s},$i=f=>f.reduce((t,r)=>t+r,0)/f.length,OA=()=>`probe-${yo()}`,DA=()=>`coltr-${yo()}`,Up=f=>new Promise(t=>setTimeout(t,f)),zd=(f,t,r)=>{t?f.call(t,r):f(r)},es=(f,t,r,l)=>{const u=bo(f,t,r,!0,l);if(u.length===0)return null;const s=u.reduce((v,C)=>v+C,0)/u.length;return s===0?null:u.map(v=>Math.abs(s-v)).reduce((v,C)=>v+C,0)/u.length*100/s},is=(f,t,r,l=!1,u)=>{const s=bo(f,t,r,l,u);return s.length===0?null:s.reduce((n,g)=>n+g,0)/s.length},Oa=(f,t,r)=>bo(f,t,r).reduce((u,s)=>u+s,0),ts=(f,t,r,l)=>{const u=bo(f,t,r,!0,l);return u.length===0?null:Math.min(...u)},ss=(f,t,r,l)=>{const u=bo(f,t,r,!1,l);return u.length===0?null:Math.max(...u)},Ps=(f,t,r,l)=>{const u=f.slice().pop();if(!u)return null;if(!r)return u[t];if(!l)return u[t][r];const s=u[t][l];return s?s[r]:null},kA=f=>f.slice().pop(),Ss=(f,t,r)=>{if(!t)return null;const l={};let u=t[ue.AUDIO][f];u||(u=r===zt.INBOUND?{...Dp}:{...kp}),l[ue.AUDIO]=u;let s=t[ue.VIDEO][f];return s||(s=r===zt.INBOUND?{...Np}:{...Mp}),l[ue.VIDEO]=s,l},wo="exporter ",NA="2.0",Pp=(f,t,r)=>{if(!f||f.length===0)return 0;const l=f[f.length-1];if(!l)return 0;const u=l[t][r];if(u){const s=u.total_rtt_ms_out,n=u.total_rtt_measure_out;return!n||!s?is(f,t,"delta_rtt_ms_out",!1,r):Number(s/n)}return null},MA=(f,t)=>{if(!f||f.length===0)return 0;const r=f[f.length-1];if(!r)return 0;const l=r[t].total_rtt_connectivity_ms,u=r[t].total_rtt_connectivity_measure;return!u||!l?is(f,t,"delta_rtt_connectivity_ms"):Number(l/u)},UA=f=>Ps(f,"network","local_candidate_type")!=="relay"?`direct/${Ps(f,"network","local_candidate_protocol")}`:`turn/${Ps(f,"network","local_candidate_relay_protocol")}`,PA=f=>{const t=Ps(f,"network","remote_candidate_type"),r=Ps(f,"network","remote_candidate_protocol");return t!=="relay"?`direct/${r}`:`turn/${r}`};class LA{constructor(t){this._start=null,this._end=null,this._cfg=t,this._referenceReport=null,this._reports=[],this._events=[]}start(){Hd(wo,"start() - start exporter...");const t=new Date;return this._start=t.toJSON(),t}stop(){Hd(wo,"stop() - stop exporter...");const t=new Date;return this._end=t.toJSON(),t}saveReferenceReport(t){this._referenceReport=t}getReferenceReport(){return this._referenceReport}addReport(t){this._cfg.ticket&&(Ot(wo,`addReport() - add report to exporter at ${t.timestamp}`),this._reports.push(t))}addCustomEvent(t){this._events.push(t)}reset(){Hd(wo,"resetReports() - reset reports"),this._reports=[],this._referenceReport=null,this._start=null,this._end=null}get ticket(){Ot(wo,"ticket() - generate ticket");const t=Ps(this._reports,"audio","total_packets_lost_in"),r=Ps(this._reports,"audio","total_packets_in"),l=Ps(this._reports,"video","total_packets_lost_in"),u=Ps(this._reports,"video","total_packets_in"),s={},n=kA(this._reports);return n&&(Object.keys(n[ue.AUDIO]).forEach(g=>{const _=n[ue.AUDIO][g];if(s[_.ssrc]={type:ue.AUDIO,direction:_.direction},_.direction===zt.INBOUND){const v={avg:is(this._reports,ue.AUDIO,"delta_jitter_ms_in",!1,g),min:ts(this._reports,ue.AUDIO,"delta_jitter_ms_in",g),max:ss(this._reports,ue.AUDIO,"delta_jitter_ms_in",g),volatility:es(this._reports,ue.AUDIO,"delta_jitter_ms_in",g),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},C={avg:is(this._reports,ue.AUDIO,"delta_kbs_in",!1,g),min:ts(this._reports,ue.AUDIO,"delta_kbs_in",g),max:ss(this._reports,ue.AUDIO,"delta_kbs_in",g),volatility:es(this._reports,ue.AUDIO,"delta_kbs_in",g),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},R={avg:is(this._reports,ue.AUDIO,"delta_KBytes_in",!1,g),min:ts(this._reports,ue.AUDIO,"delta_KBytes_in",g),max:ss(this._reports,ue.AUDIO,"delta_KBytes_in",g),volatility:es(this._reports,ue.AUDIO,"delta_KBytes_in",g),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},D={emodel:{avg:is(this._reports,ue.AUDIO,"mos_emodel_in",!1,g),min:ts(this._reports,ue.AUDIO,"mos_emodel_in",g),max:ss(this._reports,ue.AUDIO,"mos_emodel_in",g),volatility:es(this._reports,ue.AUDIO,"mos_emodel_in",g)},effective:{avg:is(this._reports,ue.AUDIO,"mos_in",!1,g),min:ts(this._reports,ue.AUDIO,"mos_in",g),max:ss(this._reports,ue.AUDIO,"mos_in",g),volatility:es(this._reports,ue.AUDIO,"mos_in",g)},_unit:{avg:"number (1-5)",min:"number (1-5)",max:"number (1-5)",volatility:"percent"}},H=Ps(this._reports,ue.AUDIO,"total_packets_lost_in",g),F=Ps(this._reports,ue.AUDIO,"total_packets_in",g),q={lost:H,avg:Math.round((H/(H+F)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};s[g].jitter=v,s[g].mos=D,s[g].traffic=R,s[g].bitrate=C,s[g].loss=q}else{const v={avg:is(this._reports,ue.AUDIO,"delta_jitter_ms_out",!1,g),min:ts(this._reports,ue.AUDIO,"delta_jitter_ms_out",g),max:ss(this._reports,ue.AUDIO,"delta_jitter_ms_out",g),volatility:es(this._reports,ue.AUDIO,"delta_jitter_ms_out",g),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},C={avg:is(this._reports,ue.AUDIO,"delta_kbs_out",!1,g),min:ts(this._reports,ue.AUDIO,"delta_kbs_out",g),max:ss(this._reports,ue.AUDIO,"delta_kbs_out",g),volatility:es(this._reports,ue.AUDIO,"delta_kbs_out",g),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},R={avg:is(this._reports,ue.AUDIO,"delta_KBytes_out",!1,g),min:ts(this._reports,ue.AUDIO,"delta_KBytes_out",g),max:ss(this._reports,ue.AUDIO,"delta_KBytes_out",g),volatility:es(this._reports,ue.AUDIO,"delta_KBytes_out",g),_unit:{avg:"KB",min:"KB",max:"KB",bitrate:"kbs",volatility:"percent"}},D={avg:Pp(this._reports,ue.AUDIO,g),min:ts(this._reports,ue.AUDIO,"delta_rtt_ms_out",g),max:ss(this._reports,ue.AUDIO,"delta_rtt_ms_out",g),volatility:es(this._reports,ue.AUDIO,"delta_rtt_ms_out",g),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},H=Ps(this._reports,ue.AUDIO,"total_packets_lost_out",g),F=Ps(this._reports,ue.AUDIO,"total_packets_out",g),q={lost:H,avg:Math.round((H/(H+F)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}},G={emodel:{avg:is(this._reports,ue.AUDIO,"mos_emodel_out",!1,g),min:ts(this._reports,ue.AUDIO,"mos_emodel_out",g),max:ss(this._reports,ue.AUDIO,"mos_emodel_out",g),volatility:es(this._reports,ue.AUDIO,"mos_emodel_out",g)},effective:{avg:is(this._reports,ue.AUDIO,"mos_out",!1,g),min:ts(this._reports,ue.AUDIO,"mos_out",g),max:ss(this._reports,ue.AUDIO,"mos_out",g),volatility:es(this._reports,ue.AUDIO,"mos_out",g)},_unit:{avg:"number (1-5)",min:"number (1-5)",max:"number (1-5)",volatility:"percent"}};s[g].jitter=v,s[g].rtt=D,s[g].traffic=R,s[g].bitrate=C,s[g].loss=q,s[g].mos=G}}),Object.keys(n[ue.VIDEO]).forEach(g=>{const _=n[ue.VIDEO][g];if(s[g]={type:ue.VIDEO,direction:_.direction},_.direction===zt.INBOUND){const v={avg:is(this._reports,ue.VIDEO,"delta_jitter_ms_in",!1,g),min:ts(this._reports,ue.VIDEO,"delta_jitter_ms_in",g),max:ss(this._reports,ue.VIDEO,"delta_jitter_ms_in",g),volatility:es(this._reports,ue.VIDEO,"delta_jitter_ms_in",g),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},C={avg:is(this._reports,ue.VIDEO,"delta_kbs_in",!1,g),min:ts(this._reports,ue.VIDEO,"delta_kbs_in",g),max:ss(this._reports,ue.VIDEO,"delta_kbs_in",g),volatility:es(this._reports,ue.VIDEO,"delta_kbs_in",g),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},R={avg:is(this._reports,ue.VIDEO,"delta_KBytes_in",!1,g),min:ts(this._reports,ue.VIDEO,"delta_KBytes_in",g),max:ss(this._reports,ue.VIDEO,"delta_KBytes_in",g),volatility:es(this._reports,ue.VIDEO,"delta_KBytes_in",g),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},D=Ps(this._reports,ue.VIDEO,"total_packets_lost_in",g),H=Ps(this._reports,ue.VIDEO,"total_packets_in",g),F={lost:D,avg:Math.round((D/(D+H)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};s[g].jitter=v,s[g].traffic=R,s[g].bitrate=C,s[g].loss=F}else{const v={avg:is(this._reports,ue.VIDEO,"delta_jitter_ms_out",!1,g),min:ts(this._reports,ue.VIDEO,"delta_jitter_ms_out",g),max:ss(this._reports,ue.VIDEO,"delta_jitter_ms_out",g),volatility:es(this._reports,ue.VIDEO,"delta_jitter_ms_out",g),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},C={avg:is(this._reports,ue.VIDEO,"delta_kbs_out",!1,g),min:ts(this._reports,ue.VIDEO,"delta_kbs_out",g),max:ss(this._reports,ue.VIDEO,"delta_kbs_out",g),volatility:es(this._reports,ue.VIDEO,"delta_kbs_out",g),_unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},R={avg:is(this._reports,ue.VIDEO,"delta_KBytes_out",!1,g),min:ts(this._reports,ue.VIDEO,"delta_KBytes_out",g),max:ss(this._reports,ue.VIDEO,"delta_KBytes_out",g),volatility:es(this._reports,ue.VIDEO,"delta_KBytes_out",g),_unit:{avg:"KB",min:"KB",max:"KB",volatility:"percent"}},D={avg:Pp(this._reports,ue.VIDEO,g),min:ts(this._reports,ue.VIDEO,"delta_rtt_ms_out",g),max:ss(this._reports,ue.VIDEO,"delta_rtt_ms_out",g),volatility:es(this._reports,ue.VIDEO,"delta_rtt_ms_out",g),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},H=Ps(this._reports,ue.VIDEO,"total_packets_lost_out",g),F=Ps(this._reports,ue.VIDEO,"total_packets_out",g),q={lost:H,avg:Math.round((H/(H+F)*100||0)*100)/100,_unit:{avg:"percent",lost:"number"}};s[g].jitter=v,s[g].rtt=D,s[g].traffic=R,s[g].bitrate=C,s[g].loss=q}})),{version:NA,configuration:{frequency:this._cfg.refreshEvery},started:this._start,ended:this._end,ua:{agent:navigator.userAgent,pname:this._cfg.pname,user_id:this._cfg.uid},call:{call_id:this._cfg.cid,events:this._events},details:{count:this._reports.length,reports:this._cfg.record?this._reports:[],reference:this._referenceReport||null},ssrc:s,data:{rtt:{avg:MA(this._reports,"data"),min:ts(this._reports,"data","delta_rtt_connectivity_ms"),max:ss(this._reports,"data","delta_rtt_connectivity_ms"),volatility:es(this._reports,"data","delta_rtt_connectivity_ms"),_unit:{avg:"ms",min:"ms",max:"ms",volatility:"percent"}},packetsLost:{audio:{in:{avg:Math.round((t/(t+r)*100||0)*100)/100}},video:{in:{avg:Math.round((l/(l+u)*100||0)*100)/100}},unit:{avg:"percent"}},bitrate:{in:{avg:is(this._reports,"data","delta_kbs_in"),min:ts(this._reports,"data","delta_kbs_in"),max:ss(this._reports,"data","delta_kbs_in"),volatility:es(this._reports,"data","delta_kbs_in")},out:{avg:is(this._reports,"data","delta_kbs_out"),min:ts(this._reports,"data","delta_kbs_out"),max:ss(this._reports,"data","delta_kbs_out"),volatility:es(this._reports,"data","delta_kbs_out")},unit:{avg:"kbs",min:"kbs",max:"kbs",volatility:"percent"}},traffic:{in:{avg:is(this._reports,"data","delta_KBytes_in"),min:ts(this._reports,"data","delta_KBytes_in"),max:ss(this._reports,"data","delta_KBytes_in"),volatility:es(this._reports,"data","delta_KBytes_in")},out:{avg:is(this._reports,"data","delta_KBytes_out"),min:ts(this._reports,"data","delta_KBytes_out"),max:ss(this._reports,"data","delta_KBytes_out"),volatility:es(this._reports,"data","delta_KBytes_out")},unit:{avg:"KBytes",min:"KBytes",max:"KBytes",volatility:"percent"}},network:{localConnection:UA(this._reports),remoteConnection:PA(this._reports)}}}}updateConfig(t){this._cfg=t}getLastReport(){return this._reports.slice().pop()||null}getBeforeLastReport(){const t=this._reports.slice();return t.pop(),t.pop()||null}getReportsNumber(){return this._reports.length}}const xi="extractor ",Lp=(f,t,r,l)=>{let u=!1;const s=l[t].total_rtt_ms_out,n=l[t].total_rtt_measure_out,g=r?r[t].total_rtt_ms_out:0,_=r?r[t].total_rtt_measure_out:0,v={rtt:null,totalRTT:s,totalRTTMeasurements:n};if(f[Te.TIMESTAMP]===l[t].timestamp_out||!Object.prototype.hasOwnProperty.call(f,Te.ROUND_TRIP_TIME)||Object.prototype.hasOwnProperty.call(f,Te.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS)&&(u=!0,Number(f[Te.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])===0||Number(f[Te.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])-_===n))return v;const C=1e3*Number(f[Te.ROUND_TRIP_TIME]);let R=s+C,D=n+1;return u&&(R=1e3*Number(f[Te.TOTAL_ROUND_TRIP_TIME])-g,D=Number(f[Te.TOTAL_ROUND_TRIP_TIME_MEASUREMENTS])-_),{rtt:C,totalRTT:R,totalRTTMeasurements:D}},HA=(f,t,r,l)=>{if(!Object.prototype.hasOwnProperty.call(f,Te.CURRENT_ROUND_TRIP_TIME))return{rtt:null,totalRTT:l[t].total_rtt_connectivity_ms,totalRTTMeasurements:l[t].total_rtt_connectivity_measure};const u=1e3*Number(f[Te.CURRENT_ROUND_TRIP_TIME]);let s=l[t].total_rtt_connectivity_ms+u,n=l[t].total_rtt_connectivity_measure+1;return Object.prototype.hasOwnProperty.call(f,Te.TOTAL_ROUND_TRIP_TIME)&&(s=1e3*Number(f[Te.TOTAL_ROUND_TRIP_TIME])-(r?r[t].total_rtt_connectivity_ms:0)),Object.prototype.hasOwnProperty.call(f,Te.RESPONSES_RECEIVED)&&(n=Number(f[Te.RESPONSES_RECEIVED])-(r?r[t].total_rtt_connectivity_measure:0)),{rtt:u,totalRTT:s,totalRTTMeasurements:n}},ju=(f,t,r)=>f[Te.TIMESTAMP]===r[t].timestamp_out||!Object.prototype.hasOwnProperty.call(f,Te.JITTER)?null:1e3*(Number(f[Te.JITTER])||0),FA=(f,t)=>{if(!Object.prototype.hasOwnProperty.call(f,Te.FRAMES_DECODED)||!Object.prototype.hasOwnProperty.call(f,Te.TOTAL_DECODE_TIME))return{delta_ms_decode_frame:t[ue.VIDEO].delta_ms_decode_frame_in,frames_decoded:t[ue.VIDEO].total_frames_decoded_in,total_decode_time:t[ue.VIDEO].total_time_decoded_in};const r=f[Te.FRAMES_DECODED],l=f[Te.TOTAL_DECODE_TIME],u=l-t[ue.VIDEO].total_time_decoded_in,s=r-t[ue.VIDEO].total_frames_decoded_in;return{delta_ms_decode_frame:s>0?u*1e3/s:0,frames_decoded:r,total_decode_time:l}},BA=(f,t)=>{if(!Object.prototype.hasOwnProperty.call(f,Te.FRAMES_ENCODED)||!Object.prototype.hasOwnProperty.call(f,Te.TOTAL_ENCODE_TIME))return{delta_ms_encode_frame:t[ue.VIDEO].delta_ms_encode_frame_out,frames_encoded:t[ue.VIDEO].total_frames_encoded_out,total_encode_time:t[ue.VIDEO].total_time_encoded_out};const r=f[Te.FRAMES_ENCODED],l=f[Te.TOTAL_ENCODE_TIME],u=l-t[ue.VIDEO].total_time_encoded_out,s=r-t[ue.VIDEO].total_frames_encoded_out;return{delta_ms_encode_frame:s>0&&u?u*1e3/s:0,frames_encoded:r,total_encode_time:l}},Hp=(f,t,r,l)=>{if(!Object.prototype.hasOwnProperty.call(f,Te.PACKETS_SENT)||!Object.prototype.hasOwnProperty.call(f,Te.BYTES_SENT))return{packetsSent:r[t].total_packets_out,packetsLost:r[t].total_packets_lost_out,bytesSent:r[t].total_KBytes_out};const u=Number(f[Te.PACKETS_SENT])||0-(l?l[t].total_packets_out:0),s=u-r[t].total_packets_out,n=Number(f[Te.BYTES_SENT])/1024-(l?l[t].total_KBytes_out:0),g=n-r[t].total_KBytes_out,_=f[Te.TIMESTAMP]||Date.now(),v=l?l.timestamp:null;let C=r.timestamp;!C&&v&&(C=v);const R=C?_-C:0,D=R>0?g*.008*1024/R*1e3:0;return{packetsSent:u,deltaPacketsSent:s,KBytesSent:n,deltaKBytesSent:g,kbsSent:D}},Fp=(f,t,r,l)=>{let u=r[t].total_packets_lost_out,s=0,n=0;return Object.prototype.hasOwnProperty.call(f,Te.PACKETS_LOST)&&(u=Number(f[Te.PACKETS_LOST])||0-(l?l[t].total_packets_lost_out:0),s=u-r[t].total_packets_lost_out),Object.prototype.hasOwnProperty.call(f,Te.FRACTION_LOST)&&(n=Number(100*f[Te.FRACTION_LOST])),{packetsLost:u,deltaPacketsLost:s,fractionLost:n}},Bp=(f,t,r,l)=>{if(!Object.prototype.hasOwnProperty.call(f,Te.PACKETS_RECEIVED)||!Object.prototype.hasOwnProperty.call(f,Te.PACKETS_LOST)||!Object.prototype.hasOwnProperty.call(f,Te.BYTES_RECEIVED))return{percent_packets_lost:r[t].percent_packets_lost_in,packetsReceived:r[t].total_packets_in,packetsLost:r[t].total_packets_lost_in,bytesReceived:r[t].total_KBytes_in};const u=Number(f[Te.PACKETS_RECEIVED])||0-(l?l[t].total_packets_in:0),s=Number(f[Te.PACKETS_LOST])||0-(l?l[t].total_packets_lost_in:0),n=s-r[t].total_packets_lost_in,g=u-r[t].total_packets_in,_=u!==r[t].total_packets_in?n*100/(n+g):0,v=Number(f[Te.BYTES_RECEIVED])/1024-(l?l[t].total_KBytes_in:0),C=v-r[t].total_KBytes_in,R=f[Te.TIMESTAMP]||Date.now(),D=l?l.timestamp:null;let H=r.timestamp;!H&&D&&(H=D);const F=H?R-H:0,q=F>0?C*.008*1024/F*1e3:0;return{percentPacketsLost:_,packetsReceived:u,deltaPacketsReceived:g,packetsLost:s,deltaPacketsLost:n,KBytesReceived:v,deltaKBytesReceived:C,kbsReceived:q}},zA=f=>f[Te.CANDIDATE_TYPE]!=="relay"?"":f[Te.RELAY_PROTOCOL]||"",VA=f=>{if(!Object.prototype.hasOwnProperty.call(f,Te.NETWORK_TYPE))return So.WIFI;switch(f[Te.NETWORK_TYPE]){case Fd.ETHERNET:return So.ETHERNET;case Fd.CELLULAR_4G:return So.CELLULAR_4G;case Fd.WIFI:return So.WIFI;default:return So.CELLULAR}},zp=f=>!Object.prototype.hasOwnProperty.call(f,Te.FRAME_HEIGHT)||!Object.prototype.hasOwnProperty.call(f,Te.FRAME_WIDTH)?{width:null,height:null,framerate:null}:{width:f[Te.FRAME_WIDTH]||null,height:f[Te.FRAME_HEIGHT]||null,framerate:f[Te.FRAMES_PER_SECOND]},qA=f=>{const t=Object.prototype.hasOwnProperty.call(f,Te.QUALITY_LIMITATION_REASON)?f[Te.QUALITY_LIMITATION_REASON]:null,r=Object.prototype.hasOwnProperty.call(f,Te.QUALITY_LIMITATION_RESOLUTION_CHANGES)?f[Te.QUALITY_LIMITATION_RESOLUTION_CHANGES]:null,l=Object.prototype.hasOwnProperty.call(f,Te.QUALITY_LIMITATION_DURATIONS)?f[Te.QUALITY_LIMITATION_DURATIONS]:null;return l&&Object.keys(l).forEach(u=>{l[u]>1e3&&(l[u]=Number(l[u]/1e3))}),{reason:t,durations:l,resolutionChanges:r}},jA=(f,t,r)=>{if(!Object.prototype.hasOwnProperty.call(f,Te.PLI)||!Object.prototype.hasOwnProperty.call(f,Te.NACK))return{pliCount:t.total_pli_sent_in,nackCount:t.total_nack_sent_in,deltaPliCount:0,deltaNackCount:0};const l=(f[Te.PLI]||0)-(r?r[ue.VIDEO].total_pli_sent_in:0),u=(f[Te.NACK]||0)-(r?r[ue.VIDEO].total_nack_sent_in:0);return{pliCount:l,nackCount:u,deltaPliCount:l-t[ue.VIDEO].total_pli_sent_in,deltaNackCount:u-t[ue.VIDEO].total_nack_sent_in}},GA=(f,t,r)=>{if(!Object.prototype.hasOwnProperty.call(f,Te.PLI)||!Object.prototype.hasOwnProperty.call(f,Te.NACK))return{pliCount:t.total_pli_received_out,nackCount:t.total_nack_received_out,deltaPliCount:0,deltaNackCount:0};const l=(f[Te.PLI]||0)-(r?r[ue.VIDEO].total_pli_received_out:0),u=(f[Te.NACK]||0)-(r?r[ue.VIDEO].total_nack_received_out:0);return{pliCount:l,nackCount:u,deltaPliCount:l-t[ue.VIDEO].total_pli_received_out,deltaNackCount:u-t[ue.VIDEO].total_nack_received_out}},WA=f=>({channels:f[Te.CHANNELS]||null,clock_rate:f[Te.CLOCK_RATE]||null,mime_type:f[Te.MIME_TYPE]||null,sdp_fmtp_line:f[Te.SDP_FMTP_LINE]||null}),KA=f=>({clock_rate:f[Te.CLOCK_RATE]||null,mime_type:f[Te.MIME_TYPE]||null}),YA=(f,t,r)=>{const l=(f[Te.BYTES_RECEIVED]||0)/1024-(r?r.data.total_KBytes_in:0),u=(f[Te.BYTES_SENT]||0)/1024-(r?r.data.total_KBytes_out:0),s=f[Te.TIMESTAMP]||Date.now(),n=l-t.data.total_KBytes_in,g=u-t.data.total_KBytes_out,_=r?r.timestamp:null;let v=t.timestamp;!v&&_&&(v=_);const C=v?s-v:0,R=C>0?n*.008*1024/C*1e3:0,D=C>0?g*.008*1024/C*1e3:0;return{total_KBytes_received:l,total_KBytes_sent:u,delta_KBytes_received:n,delta_KBytes_sent:g,kbs_speed_received:R,kbs_speed_sent:D}},JA=f=>{const t=f[Te.AVAILABLE_INCOMING_BITRATE]/1024||0,r=f[Te.AVAILABLE_OUTGOING_BITRATE]/1024||0;return{kbs_incoming_bandwidth:t,kbs_outgoing_bandwidth:r}},QA=(f,t,r,l)=>{if(!f)return[];switch(f[Te.TYPE]){case Ur.CANDIDATE_PAIR:let u=!1;if(f[Te.NOMINATED]&&f[Te.STATE]===ue.SUCCEEDED&&(u=!0,Ot(xi,`analyze() - got stats ${f[Te.TYPE]} for ${r}`,f),Te.SELECTED in f&&!f[Te.SELECTED]&&(u=!1)),u){const n=f[Te.LOCAL_CANDIDATE_ID],g=f[Te.REMOTE_CANDIDATE_ID],_=YA(f,t,l),v=JA(f),C=HA(f,"data",l,t);return[{type:Me.NETWORK,value:{local_candidate_id:n}},{type:Me.NETWORK,value:{remote_candidate_id:g}},{type:Me.DATA,value:{total_KBytes_in:_.total_KBytes_received}},{type:Me.DATA,value:{total_KBytes_out:_.total_KBytes_sent}},{type:Me.DATA,value:{delta_KBytes_in:_.delta_KBytes_received}},{type:Me.DATA,value:{delta_KBytes_out:_.delta_KBytes_sent}},{type:Me.DATA,value:{delta_kbs_in:_.kbs_speed_received}},{type:Me.DATA,value:{delta_kbs_out:_.kbs_speed_sent}},{type:Me.DATA,value:{delta_kbs_bandwidth_in:v.kbs_incoming_bandwidth}},{type:Me.DATA,value:{delta_kbs_bandwidth_out:v.kbs_outgoing_bandwidth}},{type:Me.DATA,value:{delta_rtt_connectivity_ms:C.rtt}},{type:Me.DATA,value:{total_rtt_connectivity_ms:C.totalRTT}},{type:Me.DATA,value:{total_rtt_connectivity_measure:C.totalRTTMeasurements}}]}break;case Ur.LOCAL_CANDIDATE:if(f[Te.ID]===t.network.local_candidate_id)return[{type:Me.NETWORK,value:{infrastructure:VA(f)}},{type:Me.NETWORK,value:{local_candidate_type:f[Te.CANDIDATE_TYPE]||""}},{type:Me.NETWORK,value:{local_candidate_protocol:f[Te.PROTOCOL]||""}},{type:Me.NETWORK,value:{local_candidate_relay_protocol:zA(f)}}];break;case Ur.REMOTE_CANDIDATE:if(f[Te.ID]===t.network.remote_candidate_id)return[{type:Me.NETWORK,value:{remote_candidate_type:f[Te.CANDIDATE_TYPE]||""}},{type:Me.NETWORK,value:{remote_candidate_protocol:f[Te.PROTOCOL]||""}}];break;case Ur.INBOUND_RTP:{Ot(xi,`analyze() - got stats ${f[Te.TYPE]} for ${r}`,f);const n=f[Te.SSRC],g=Ss(n,t,zt.INBOUND);g&&(g.timestamp=t.timestamp);const _=Ss(n,l,zt.INBOUND);if(_&&(_.timestamp=l.timestamp),f[Te.MEDIA_TYPE]===ue.AUDIO){const v=Bp(f,ue.AUDIO,g,_),C=ju(f,ue.AUDIO,g),R=f[Te.CODEC_ID]||"";return[{ssrc:n,type:Me.AUDIO,value:{codec_id_in:R}},{ssrc:n,type:Me.AUDIO,value:{total_packets_in:v.packetsReceived}},{ssrc:n,type:Me.AUDIO,value:{delta_packets_in:v.deltaPacketsReceived}},{ssrc:n,type:Me.AUDIO,value:{total_packets_lost_in:v.packetsLost}},{ssrc:n,type:Me.AUDIO,value:{delta_packets_lost_in:v.deltaPacketsLost}},{ssrc:n,type:Me.AUDIO,value:{percent_packets_lost_in:v.percentPacketsLost}},{ssrc:n,type:Me.AUDIO,value:{total_KBytes_in:v.KBytesReceived}},{ssrc:n,type:Me.AUDIO,value:{delta_KBytes_in:v.deltaKBytesReceived}},{ssrc:n,type:Me.AUDIO,value:{delta_kbs_in:v.kbsReceived}},{ssrc:n,type:Me.AUDIO,value:{delta_jitter_ms_in:C}}]}if(f[Te.MEDIA_TYPE]===ue.VIDEO){const v=FA(f,g),C=Bp(f,ue.VIDEO,g,_),R=ju(f,ue.VIDEO,g),D=f[Te.DECODER_IMPLEMENTATION]||null,H=f[Te.CODEC_ID]||null,F=zp(f),q=jA(f,g,_);return[{ssrc:n,type:Me.VIDEO,value:{codec_id_in:H}},{ssrc:n,type:Me.VIDEO,value:{total_packets_in:C.packetsReceived}},{ssrc:n,type:Me.VIDEO,value:{delta_packets_in:C.deltaPacketsReceived}},{ssrc:n,type:Me.VIDEO,value:{total_packets_lost_in:C.packetsLost}},{ssrc:n,type:Me.VIDEO,value:{delta_packets_lost_in:C.deltaPacketsLost}},{ssrc:n,type:Me.VIDEO,value:{percent_packets_lost_in:C.percentPacketsLost}},{ssrc:n,type:Me.VIDEO,value:{total_KBytes_in:C.KBytesReceived}},{ssrc:n,type:Me.VIDEO,value:{delta_KBytes_in:C.deltaKBytesReceived}},{ssrc:n,type:Me.VIDEO,value:{delta_kbs_in:C.kbsReceived}},{ssrc:n,type:Me.VIDEO,value:{delta_jitter_ms_in:R}},{ssrc:n,type:Me.VIDEO,value:{decoder_in:D}},{ssrc:n,type:Me.VIDEO,value:{delta_ms_decode_frame_in:v.delta_ms_decode_frame}},{ssrc:n,type:Me.VIDEO,value:{total_frames_decoded_in:v.frames_decoded}},{ssrc:n,type:Me.VIDEO,value:{total_time_decoded_in:v.total_decode_time}},{ssrc:n,type:Me.VIDEO,value:{total_nack_sent_in:q.nackCount}},{ssrc:n,type:Me.VIDEO,value:{delta_nack_sent_in:q.deltaNackCount}},{ssrc:n,type:Me.VIDEO,value:{total_pli_sent_in:q.pliCount}},{ssrc:n,type:Me.VIDEO,value:{delta_pli_sent_in:q.deltaPliCount}},{ssrc:n,type:Me.VIDEO,value:{size_in:F}}]}break}case Ur.OUTBOUND_RTP:{Ot(xi,`analyze() - got stats ${f[Te.TYPE]} for ${r}`,f);const n=f[Te.SSRC],g=Ss(n,t,zt.OUTBOUND);g&&(g.timestamp=t.timestamp);const _=Ss(n,l,zt.OUTBOUND);if(_&&(_.timestamp=l.timestamp),f[Te.MEDIA_TYPE]===ue.AUDIO){const v=f[Te.CODEC_ID]||null,C=Hp(f,ue.AUDIO,g,_);return[{ssrc:n,type:Me.AUDIO,value:{codec_id_out:v}},{ssrc:n,type:Me.AUDIO,value:{total_packets_out:C.packetsSent}},{ssrc:n,type:Me.AUDIO,value:{delta_packets_out:C.deltaPacketsSent}},{ssrc:n,type:Me.AUDIO,value:{total_KBytes_out:C.KBytesSent}},{ssrc:n,type:Me.AUDIO,value:{delta_KBytes_out:C.deltaKBytesSent}},{ssrc:n,type:Me.AUDIO,value:{delta_kbs_out:C.kbsSent}}]}if(f[Te.MEDIA_TYPE]===ue.VIDEO){const v=f[Te.ENCODER_IMPLEMENTATION]||null,C=f[Te.CODEC_ID]||null,R=BA(f,g),D=zp(f),H=qA(f),F=GA(f,g,_),q=Hp(f,ue.VIDEO,g,_);return[{ssrc:n,type:Me.VIDEO,value:{codec_id_out:C}},{ssrc:n,type:Me.VIDEO,value:{total_packets_out:q.packetsSent}},{ssrc:n,type:Me.VIDEO,value:{delta_packets_out:q.deltaPacketsSent}},{ssrc:n,type:Me.VIDEO,value:{total_KBytes_out:q.KBytesSent}},{ssrc:n,type:Me.VIDEO,value:{delta_KBytes_out:q.deltaKBytesSent}},{ssrc:n,type:Me.VIDEO,value:{delta_kbs_out:q.kbsSent}},{ssrc:n,type:Me.VIDEO,value:{encoder_out:v}},{ssrc:n,type:Me.VIDEO,value:{delta_ms_encode_frame_out:R.delta_ms_encode_frame}},{ssrc:n,type:Me.VIDEO,value:{total_frames_encoded_out:R.frames_encoded}},{ssrc:n,type:Me.VIDEO,value:{total_time_encoded_out:R.total_encode_time}},{ssrc:n,type:Me.VIDEO,value:{total_nack_received_out:F.nackCount}},{ssrc:n,type:Me.VIDEO,value:{delta_nack_received_out:F.deltaNackCount}},{ssrc:n,type:Me.VIDEO,value:{total_pli_received_out:F.pliCount}},{ssrc:n,type:Me.VIDEO,value:{delta_pli_received_out:F.deltaPliCount}},{ssrc:n,type:Me.VIDEO,value:{size_out:D}},{ssrc:n,type:Me.VIDEO,value:{limitation_out:H}}]}break}case Ur.MEDIA_SOURCE:{Ot(xi,`analyze() - got stats ${f[Te.TYPE]} for ${r}`,f);break}case Ur.TRACK:{Ot(xi,`analyze() - got stats ${f[Te.TYPE]} for ${r}`,f);break}case Ur.CODEC:const s=[];return Object.keys(t[ue.AUDIO]).forEach(n=>{const g=t[ue.AUDIO][n];if(g.codec_id_in===f[Te.ID]||g.codec_id_out===f[Te.ID]){Ot(xi,`analyze() - got stats ${f[Te.TYPE]} for ${r}`,f);const _=WA(f);f[Te.ID]===g.codec_id_in?s.push({ssrc:g.ssrc,type:Me.AUDIO,value:{codec_in:_}}):s.push({ssrc:g.ssrc,type:Me.AUDIO,value:{codec_out:_}})}}),Object.keys(t[ue.VIDEO]).forEach(n=>{const g=t[ue.VIDEO][n];if(g.codec_id_in===f[Te.ID]||g.codec_id_out===f[Te.ID]){Ot(xi,`analyze() - got stats ${f[Te.TYPE]} for ${r}`,f);const _=KA(f);f[Te.ID]===g.codec_id_in?s.push({ssrc:g.ssrc,type:Me.VIDEO,value:{codec_in:_}}):s.push({ssrc:g.ssrc,type:Me.VIDEO,value:{codec_out:_}})}}),s;case Ur.REMOTE_INBOUND_RTP:{Ot(xi,`analyze() - got stats ${f[Te.TYPE]} for ${r}`,f);const n=f[Te.SSRC],g=Ss(n,t,zt.OUTBOUND),_=Ss(n,l,zt.OUTBOUND);if(f[Te.KIND]===ue.AUDIO){const v=Lp(f,ue.AUDIO,_,g),C=ju(f,ue.AUDIO,g),R=Fp(f,ue.AUDIO,g,_);return[{ssrc:n,type:Me.AUDIO,value:{delta_rtt_ms_out:v.rtt}},{ssrc:n,type:Me.AUDIO,value:{total_rtt_ms_out:v.totalRTT}},{ssrc:n,type:Me.AUDIO,value:{total_rtt_measure_out:v.totalRTTMeasurements}},{ssrc:n,type:Me.AUDIO,value:{delta_jitter_ms_out:C}},{ssrc:n,type:Me.AUDIO,value:{timestamp_out:f[Te.TIMESTAMP]}},{ssrc:n,type:Me.AUDIO,value:{total_packets_lost_out:R.packetsLost}},{ssrc:n,type:Me.AUDIO,value:{delta_packets_lost_out:R.deltaPacketsLost}},{ssrc:n,type:Me.AUDIO,value:{percent_packets_lost_out:R.fractionLost}}]}if(f[Te.KIND]===ue.VIDEO){const v=Lp(f,ue.VIDEO,_,g),C=ju(f,ue.VIDEO,g),R=Fp(f,ue.VIDEO,g,_);return[{ssrc:n,type:Me.VIDEO,value:{delta_rtt_ms_out:v.rtt}},{ssrc:n,type:Me.VIDEO,value:{total_rtt_ms_out:v.totalRTT}},{ssrc:n,type:Me.VIDEO,value:{total_rtt_measure_out:v.totalRTTMeasurements}},{ssrc:n,type:Me.VIDEO,value:{delta_jitter_ms_out:C}},{ssrc:n,type:Me.VIDEO,value:{timestamp_out:f[Te.TIMESTAMP]}},{ssrc:n,type:Me.VIDEO,value:{total_packets_lost_out:R.packetsLost}},{ssrc:n,type:Me.VIDEO,value:{delta_packets_lost_out:R.deltaPacketsLost}},{ssrc:n,type:Me.VIDEO,value:{percent_packets_lost_out:R.fractionLost}}]}break}}return[]},Gu=f=>f<0?1:f>100?4.5:1+.035*f+7/1e6*f*(f-60)*(100-f),XA=(f,t=ue.AUDIO,r,l,u)=>{const s=Ss(u,f,zt.INBOUND),n=Ss(u,r,zt.INBOUND),g=Ss(u,l,zt.INBOUND),_=[],v=[],C=s[t].percent_packets_lost_in,R=s[t].delta_jitter_ms_in,D=n&&n[t].delta_jitter_ms_in||null,H=g&&g[t].delta_jitter_ms_in||null,F=f.data.delta_rtt_connectivity_ms,q=r&&r.data.delta_rtt_connectivity_ms||null,G=l&&l.data.delta_rtt_connectivity_ms||null;F&&_.push(F),q&&_.push(q),G&&_.push(G),R&&v.push(R),r&&D&&v.push(D),l&&H&&v.push(H);const te=_.length>0?$i(_):100,X=v.length>0?$i(v):10,we=93.2-C,Q=.18*we*we-27.9*we+1126.62,re=(te+X)/2,ke=re-177.3<0?0:1,Ne=.024*re+.11*(re-177.3)*ke,Z=Q-Ne;return Gu(Z)},ZA=(f,t=ue.AUDIO,r,l,u)=>{const s=Ss(u,f,zt.OUTBOUND),n=Ss(u,r,zt.OUTBOUND),g=Ss(u,l,zt.OUTBOUND),_=[],v=[],C=s[t].percent_packets_lost_out,R=s[t].delta_rtt_ms_out,D=n&&n[t].delta_rtt_ms_out||null,H=g&&g[t].delta_rtt_ms_out||null,F=s[t].delta_jitter_ms_out,q=n&&n[t].delta_jitter_ms_out||null,G=g&&g[t].delta_jitter_ms_out||null,te=f.data.delta_rtt_connectivity_ms,X=r&&r.data.delta_rtt_connectivity_ms||null,we=l&&l.data.delta_rtt_connectivity_ms||null;R?_.push(R):te&&_.push(te),D?_.push(D):X&&_.push(X),H?_.push(H):we&&_.push(we),F&&v.push(F),r&&q&&v.push(q),l&&G&&v.push(G);const Q=_.length>0?$i(_):100,re=v.length>0?$i(v):10,ke=93.2-C,Ne=.18*ke*ke-27.9*ke+1126.62,Z=(Q+re)/2,se=Z-177.3<0?0:1,pe=.024*Z+.11*(Z-177.3)*se,me=Ne-pe;return Gu(me)},eI=(f,t=ue.AUDIO,r,l,u)=>{const s=Ss(u,f,zt.INBOUND),n=Ss(u,r,zt.INBOUND),g=Ss(u,l,zt.INBOUND),_=[],v=[],C=s[t].percent_packets_lost_in/100,R=s[t].delta_jitter_ms_in,D=n&&n[t].delta_jitter_ms_in||null,H=g&&g[t].delta_jitter_ms_in||null,F=f.data.delta_rtt_connectivity_ms,q=r&&r.data.delta_rtt_connectivity_ms||null,G=l&&l.data.delta_rtt_connectivity_ms||null;F&&_.push(F),q&&_.push(q),G&&_.push(G),R&&v.push(R),n&&D&&v.push(D),g&&H&&v.push(H);const te=_.length>0?$i(_):100,X=v.length>0?$i(v):10,we=0,Q=19.8,re=29.7,ke=30,Ne=(te+X)/2+ke,Z=Ne-177.3<0?0:1,se=.024*Ne+.11*(Ne-177.3)*Z,me=93.2-(we+Q*Math.log(1+re*C)+se);return Gu(me)},tI=(f,t=ue.AUDIO,r,l,u)=>{const s=Ss(u,f,zt.OUTBOUND),n=Ss(u,r,zt.OUTBOUND),g=Ss(u,l,zt.OUTBOUND),_=[],v=[],C=s[t].percent_packets_lost_out/100,R=s[t].delta_rtt_ms_out,D=n&&n[t].delta_rtt_ms_out||null,H=g&&g[t].delta_rtt_ms_out||null,F=s[t].delta_jitter_ms_out,q=n&&n[t].delta_jitter_ms_out||null,G=g&&g[t].delta_jitter_ms_out||null,te=f.data.delta_rtt_connectivity_ms,X=r&&r.data.delta_rtt_connectivity_ms||null,we=l&&l.data.delta_rtt_connectivity_ms||null;R?_.push(R):te&&_.push(te),D?_.push(D):X&&_.push(X),H?_.push(H):we&&_.push(we),F&&v.push(F),n&&q&&v.push(q),g&&G&&v.push(G);const Q=_.length>0?$i(_):100,re=v.length>0?$i(v):10,ke=0,Ne=19.8,Z=29.7,se=30,pe=(Q+re)/2+se,me=pe-177.3<0?0:1,be=.024*pe+.11*(pe-177.3)*me,Ae=93.2-(ke+Ne*Math.log(1+Z*C)+be);return Gu(Ae)};class sI{constructor(t,r){this._callbacks={onreport:null,onticket:null},this._id=DA(),this._moduleName=this._id,this._probeId=r,this._config=t,this._exporter=new LA(t),this._state=Bn.IDLE,this.registerToPCEvents(),xa(this._moduleName,`new collector created for probe ${this._probeId}`)}analyze(t,r,l,u){const s=(_,v)=>_===ue.AUDIO?v===Ur.INBOUND_RTP?{...Dp}:{...kp}:v===Ur.INBOUND_RTP?{...Np}:{...Mp},n=IA(r);n.pname=this._config.pname,n.call_id=this._config.cid,n.user_id=this._config.uid,n.count=r?r.count+1:1;let g=null;return t.forEach(_=>{!g&&_.timestamp&&(g=_.timestamp),QA(_,n,n.pname,u).forEach(C=>{if(C.value&&C.type)if(C.ssrc){let R=n[C.type][C.ssrc];R||(R=s(C.type,_.type),R.ssrc=C.ssrc,n[C.type][C.ssrc]=R),Object.keys(C.value).forEach(D=>{R[D]=C.value[D]})}else Object.keys(C.value).forEach(R=>{n[C.type][R]=C.value[R]})})}),n.timestamp=g,Object.keys(n[ue.AUDIO]).forEach(_=>{const v=n[ue.AUDIO][_];v.direction===zt.INBOUND?(v.mos_emodel_in=XA(n,ue.AUDIO,r,l,v.ssrc),v.mos_in=eI(n,ue.AUDIO,r,l,v.ssrc)):(v.mos_emodel_out=ZA(n,ue.AUDIO,r,l,v.ssrc),v.mos_out=tI(n,ue.AUDIO,r,l,v.ssrc))}),n}async takeReferenceStats(){return new Promise((t,r)=>{const l=Date.now();setTimeout(async()=>{try{const u=Date.now()-l,s=Date.now(),n=await this._config.pc.getStats(),g=this.analyze(n,null,null,null),_=Date.now();g.experimental.time_to_measure_ms=_-s,g.experimental.time_to_wait_ms=u,this._exporter.saveReferenceReport(g),Ot(this._moduleName,`got reference report for probe ${this._probeId}`),t()}catch(u){r(u)}},this._config.startAfter)})}async collectStats(){try{if(this._state!==Bn.RUNNING||!this._config.pc)return Ot(this._moduleName,`report discarded (too late) for probe ${this._probeId}`),null;const t=Date.now(),r=await this._config.pc.getStats(),l=this.analyze(r,this._exporter.getLastReport(),this._exporter.getBeforeLastReport(),this._exporter.getReferenceReport()),u=Date.now();return l.experimental.time_to_measure_ms=u-t,this._exporter.addReport(l),Ot(this._moduleName,`got report for probe ${this._probeId}#${this._exporter.getReportsNumber()+1}`),this.fireOnReport(l),l}catch(t){return Tl(this._moduleName,`got error ${t}`),null}}async start(){Ot(this._moduleName,"starting"),this.state=Bn.RUNNING,this._startedTime=this._exporter.start(),Ot(this._moduleName,"started")}async mute(){this.state=Bn.MUTED,Ot(this._moduleName,"muted")}async unmute(){this.state=Bn.RUNNING,Ot(this._moduleName,"unmuted")}async stop(t){if(Ot(this._moduleName,`stopping${t?" by watchdog":""}...`),this._stoppedTime=this._exporter.stop(),this.state=Bn.IDLE,this._config.ticket){const{ticket:r}=this._exporter;this.fireOnTicket(r)}this._exporter.reset(),Ot(this._moduleName,"stopped")}registerCallback(t,r,l){t in this._callbacks?(this._callbacks[t]={callback:r,context:l},Ot(this._moduleName,`registered callback '${t}'`)):Tl(this._moduleName,`can't register callback for '${t}' - not found`)}unregisterCallback(t){t in this._callbacks?(this._callbacks[t]=null,delete this._callbacks[t],Ot(this._moduleName,`unregistered callback '${t}'`)):Tl(this._moduleName,`can't unregister callback for '${t}' - not found`)}fireOnReport(t){this._callbacks.onreport&&zd(this._callbacks.onreport.callback,this._callbacks.onreport.context,t)}fireOnTicket(t){this._callbacks.onticket&&zd(this._callbacks.onticket.callback,this._callbacks.onticket.context,t)}updateConfig(t){this._config=t,this._exporter.updateConfig(t)}get state(){return this._state}set state(t){this._state=t,Ot(this._moduleName,`state changed to ${t}`)}addCustomEvent(t,r,l,u){this._exporter.addCustomEvent({at:typeof t=="object"?t.toJSON():t,category:r,name:l,description:u})}async registerToPCEvents(){const{pc:t}=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{Tl(this._moduleName,"can't get devices")}},t){t.oniceconnectionstatechange=()=>{const l=t.iceConnectionState;l===To.CONNECTED||l===To.COMPLETED?this.addCustomEvent(new Date().toJSON(),"call",l,"ICE connection state"):l===To.DISCONNECTED||l===To.FAILED?this.addCustomEvent(new Date().toJSON(),"call",l,"ICE connection state"):l===To.CLOSED&&this.addCustomEvent(new Date().toJSON(),"call","ended","ICE connection state")},t.onicegatheringstatechange=()=>{const l=t.iceGatheringState;this.addCustomEvent(new Date().toJSON(),"call",l,"ICE gathering state")},t.ontrack=l=>{this.addCustomEvent(new Date().toJSON(),"call",`${l.track.kind}track`,"MediaStreamTrack received")},t.onnegotiationneeded=()=>{this.addCustomEvent(new Date().toJSON(),"call","negotiation","Media changed")};const r=t.getReceivers();if(r&&r.length>0){const l=r[0],{transport:u}=l;if(u){const{iceTransport:s}=u;s&&(s.onselectedcandidatepairchange=()=>{this.addCustomEvent(new Date().toJSON(),"call","transport","Candidates Pair changed")})}}}}}class rI{constructor(t){this._id=t.pname&&t.pname.substr(0,12).padEnd(12," ")||OA(),this._moduleName=this._id,xa(this._moduleName,"probe created"),this._config=t,this._collector=new sI(this._config,this._id)}set onreport(t){t?this._collector.registerCallback("onreport",t):this._collector.unregisterCallback("onreport")}set onticket(t){t?this._collector.registerCallback("onticket",t):this._collector.unregisterCallback("onticket")}get id(){return this._id}get pname(){return this._config.pname}get cid(){return this._config.cid}get uid(){return this._config.uid}get state(){return this._collector.state}set state(t){this._collector.state=t}addCustomEvent(t,r,l,u=new Date().toJSON()){this._collector.addCustomEvent(u,r,t,l)}get isRunning(){return this._collector.state===Bn.RUNNING}get isIdle(){return this._collector.state===Bn.IDLE}updateUserId(t){this._config.uid=t,this._collector.updateConfig(this._config)}updateCallId(t){this._config.cid=t,this._collector.updateConfig(this._config)}start(){if(!this.isIdle){qu(this._moduleName,"probe is already running");return}this._collector.start()}stop(t=!1){this.isRunning&&this._collector.stop(t)}async takeReferenceStats(){return this._collector.takeReferenceStats()}async collectStats(){return this._collector.collectStats()}}const Vs="engine ";class nI{constructor(t){this._config=t,this._probes=[],this._startedTime=null,this._callbacks={onresult:null},xa(Vs,`configured for probing every ${this._config.refreshEvery}ms`),xa(Vs,`configured for starting after ${this._config.startAfter}ms`),xa(Vs,`${!this._config.stopAfter||this._config.stopAfter!==-1?`configured for stopped after ${this._config.stopAfter}ms`:"configured for never stopped"}`),Ot(Vs,"engine initialized")}get probes(){return this._probes}get isRunning(){return this._probes.some(t=>t.isRunning)}get isIdle(){return this._probes.every(t=>t.isIdle)}addNewProbe(t,r){if(!t)throw new Error("undefined peer connection");const l=$A(t,r,this._config),u=new rI(l);return this._probes.push(u),Ot(Vs,`${this._probes.length} probes registered`),u}removeExistingProbe(t){if(!t)throw new Error("undefined probe");t.state===Bn.RUNNING&&t.stop(),this._probes=this._probes.filter(r=>t.id!==r.id)}async start(){const t=()=>{this._probes.forEach(s=>s.start())},r=async()=>Promise.all(this._probes.map(s=>s.takeReferenceStats())),l=()=>this.isIdle?!1:!this._config.stopAfter||this._config.stopAfter<0?!0:Date.now()<this._startedTime+this._config.stopAfter,u=async()=>{const s=AA(),n=this._probes.filter(g=>g.isRunning);for(const g of n){const _=await g.collectStats();_&&s.probes.push(_),Ot(Vs,`got probe ${g.id}`),await Up(0)}return s.delta_time_to_measure_probes_ms=Oa(s.probes,"experimental","time_to_measure_ms"),s.delta_KBytes_in=Oa(s.probes,"data","delta_KBytes_in"),s.delta_KBytes_out=Oa(s.probes,"data","delta_KBytes_out"),s.delta_kbs_in=Oa(s.probes,"data","delta_kbs_in"),s.delta_kbs_out=Oa(s.probes,"data","delta_kbs_out"),s.total_time_decoded_in=Oa(s.probes,"video","total_time_decoded_in"),s.total_time_encoded_out=Oa(s.probes,"video","total_time_encoded_out"),s};for(Ot(Vs,"starting to collect"),t(),Ot(Vs,"generating reference reports..."),await r(),Ot(Vs,"reference reports generated"),this._startedTime=Date.now();l();)if(Ot(Vs,`wait ${this._config.refreshEvery}ms before collecting`),await Up(this._config.refreshEvery),l()){Ot(Vs,"collecting...");const s=Date.now(),n=await u(),g=Date.now();n.delta_time_consumed_to_measure_ms=g-s,this.fireOnReports(n),Ot(Vs,"collected")}Ot(Vs,"reaching end of the collecting period..."),this.isRunning&&setTimeout(()=>{this.stop()},0)}stop(t){const r=l=>{this._probes.forEach(u=>{u.stop(l)})};xa(Vs,"stop collecting"),r(t)}registerCallback(t,r,l){t in this._callbacks?(this._callbacks[t]={callback:r,context:l},Ot(Vs,`registered callback '${t}'`)):Tl(Vs,`can't register callback for '${t}' - not found`)}unregisterCallback(t){t in this._callbacks?(this._callbacks[t]=null,delete this._callbacks[t],Ot(this._moduleName,`unregistered callback '${t}'`)):Tl(this._moduleName,`can't unregister callback for '${t}' - not found`)}fireOnReports(t){this._callbacks.onresult&&t.probes.length>0&&zd(this._callbacks.onresult.callback,this._callbacks.onresult.context,t)}}const iI="interface ";class aI{constructor(t){this._config=xA(t),xa(iI,`welcome to ${this._config.name} version ${this._config.version}`),vA(this._config.verbose||!1),this._engine=new nI(this._config)}setupLogLevel(t){yA(t)}get version(){return this._config.version}get name(){return this._config.name}get probes(){return this._engine.probes}createProbe(t,r){return this._engine.addNewProbe(t,r)}startAllProbes(){this._engine.start()}stopAllProbes(){this._engine.stop()}get running(){return this._engine.isRunning}get idle(){return this._engine.isIdle}removeProbe(t){this._engine.removeExistingProbe(t)}set onresult(t){t?this._engine.registerCallback("onresult",t):this._engine.unregisterCallback("onresult")}}function lI(f,t){return Object.keys(f).filter(r=>t.includes(r)).reduce((r,l)=>{const u=l;return{...r,[u]:f[u]}},{})}const oI=["mos_in","codec_in","delta_KBytes_in","delta_kbs_in","delta_jitter_ms_in","delta_packets_lost_in"],uI={positiveSpeechThreshold:.6,negativeSpeechThreshold:.3,preSpeechPadMs:150,redemptionMs:1500,minSpeechMs:50};class cI{constructor(t){this.intervals={},this.analysers={},this.emitInterval=t.emitInterval||200,this.onChangeFunction=t.onChangeFunction}async start(t,r,l){r&&r.getTracks().length&&await this.beginCalculation(t,r,l)}stop(t){this.clearVolumeInterval(t),this.analysers[t]&&typeof this.analysers[t].disconnect=="function"&&(this.analysers[t].disconnect(),delete this.analysers[t])}clearVolumeInterval(t){this.intervals[t]&&(clearInterval(this.intervals[t]),delete this.intervals[t])}clearAllIntervals(){Object.keys(this.intervals).forEach(t=>{this.stop(t)}),this.intervals={},this.analysers={}}async beginCalculation(t,r,l){this.clearVolumeInterval(l);const u=t.createAnalyser(),s=t.createMediaStreamSource(r);u.smoothingTimeConstant=.8,u.fftSize=1024,s.connect(u),this.analysers[l]=u,this.intervals[l]=setInterval(()=>{const n=new Uint8Array(u.frequencyBinCount);u.getByteFrequencyData(n);let g=0;const _=n.length;for(let C=0;C<_;C++)g+=n[C];const v=g/_;this.onChangeFunction(l,v)},this.emitInterval)}}class dI{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(t=>{throw this.resumePromise=null,t})),await this.resumePromise),this.context}}const Wu={SELECTED_INPUT_DEVICE:"OpensipsJSInputDevice",SELECTED_OUTPUT_DEVICE:"OpensipsJSOutputDevice"},fI=0;class hI{constructor(t){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 dI,this.context=t,this.context.on(this.context.newRTCSessionEventName,this.newRTCSessionCallback.bind(this)),this.VUMeter=new cI({onChangeFunction:this.emitVolumeChange.bind(this)}),this.processVADConfiguration(),this.initializeMediaDevices()}processVADConfiguration(){var r;const t=((r=this.context.options.configuration)==null?void 0:r.noiseReductionOptions)||{};this.noiseReduction={mode:t.mode||"disabled",checkEveryMs:t.checkEveryMs||500,noiseCheckInterval:t.noiseCheckInterval||2e3,noiseThreshold:t.noiseThreshold||.004,vadConfig:t.vadConfig||{}}}get sipOptions(){return{...this.context.options.sipOptions,mediaConstraints:this.getUserMediaConstraints}}get currentActiveRoomId(){return this.currentActiveRoomIdValue}set currentActiveRoomId(t){this.currentActiveRoomIdValue=t,this.context.emit("currentActiveRoomChanged",t)}get autoAnswer(){return this.isAutoAnswer}get callAddingInProgress(){return this.isCallAddingInProgress}set callAddingInProgress(t){this.isCallAddingInProgress=t,this.context.emit("callAddingInProgressChanged",t)}get muteWhenJoin(){return this.muteWhenJoinEnabled}get isDND(){return this.isDNDEnabled}get isCallWaiting(){return this.isCallWaitingEnabled}get speakerVolume(){return this.speakerVolumeValue}get microphoneInputLevel(){return this.microphoneInputLevelValue}get getActiveCalls(){return this.activeCalls}get hasActiveCalls(){return Object.values(this.extendedCalls).length>0}get hasActiveAnsweredCalls(){return Object.values(this.activeRooms).filter(l=>!l.incomingInProgress).length>0}get getActiveRooms(){return this.activeRooms}get isMuted(){return this.muted}get getInputDeviceList(){return this.availableMediaDevices.filter(t=>t.kind==="audioinput")}get getOutputDeviceList(){return this.availableMediaDevices.filter(t=>t.kind==="audiooutput")}get getUserMediaConstraints(){return hp()?{video:!1,audio:!0}:{audio:{deviceId:{exact:this.selectedMediaDevices.input},echoCancellation:!0,echoCancellationType:"system",noiseSuppression:!0,autoGainControl:!0,sampleRate:48e3,latency:.01},video:!1}}get selectedInputDevice(){return this.selectedMediaDevices.input}get selectedOutputDevice(){return this.selectedMediaDevices.output}get activeStream(){return this.activeStreamValue}setAvailableMediaDevices(t){this.availableMediaDevices=t,this.context.emit("changeAvailableDeviceList",t)}async updateDeviceList(){await navigator.mediaDevices.getUserMedia(this.getUserMediaConstraints);const t=await navigator.mediaDevices.enumerateDevices();this.setAvailableMediaDevices(t)}async initializeMediaDevices(){const t=localStorage.getItem(Wu.SELECTED_INPUT_DEVICE)||"default",r=localStorage.getItem(Wu.SELECTED_OUTPUT_DEVICE)||"default";try{const l=await navigator.mediaDevices.getUserMedia(this.getUserMediaConstraints),u=await navigator.mediaDevices.enumerateDevices();this.setAvailableMediaDevices(u),await this.setMicrophone(t),await this.setSpeaker(r),navigator.mediaDevices.addEventListener("devicechange",async()=>{const s=await navigator.mediaDevices.enumerateDevices();this.setAvailableMediaDevices(s)}),l.getTracks().forEach(s=>s.stop())}catch(l){console.error(l)}}async cleanupConferenceNodes(t){const r=this.conferenceNodes[t];if(!r)return;let l=0;r.sources.forEach((n,g)=>{try{n.disconnect(),l++}catch(_){console.error(`[cleanupConferenceNodes] Error disconnecting source ${g}:`,_)}});let u=0;r.destinations.forEach((n,g)=>{try{n.disconnect(),u++}catch(_){console.error(`[cleanupConferenceNodes] Error disconnecting destination ${g}:`,_)}});let s=0;r.gains.forEach((n,g)=>{try{n.disconnect(),s++}catch(_){console.error(`[cleanupConferenceNodes] Error disconnecting gain ${g}:`,_)}}),delete this.conferenceNodes[t]}setCallTime(t){const r={...t};delete r.callId,this.callTime={...this.callTime,[t.callId]:r},this.context.emit("changeCallTime",this.callTime)}removeCallTime(t){const r={...this.callTime};delete r[t],this.callTime={...r},this.context.emit("changeCallTime",this.callTime)}setTimeInterval(t,r){this.timeIntervals={...this.timeIntervals,[t]:r}}removeTimeInterval(t){const r={...this.timeIntervals};r[t]&&(clearInterval(r[t]),delete r[t],this.timeIntervals={...r})}stopCallTimer(t){this.removeTimeInterval(t),this.removeCallTime(t)}emitVolumeChange(t,r){this.context.emit("changeCallVolume",{callId:t,volume:r})}setMetricsConfig(t){this.metricConfig={...this.metricConfig,...t}}sendDTMF(t,r){if(!/^[A-D0-9*#]+$/g.test(r))throw new Error("Not allowed character used in the DTMF input");this.extendedCalls[t].sendDTMF(r)}setIsMuted(t){this.muted=t,this.context.emit("changeIsMuted",t)}processMute(t){const r=this.currentActiveRoomId;this.setIsMuted(t),this.initialStreamValue.getTracks().forEach(l=>l.enabled=!t),this.roomReconfigure(r)}mute(){this.processMute(!0)}unmute(){this.processMute(!1)}async processHold({callId:t,toHold:r,automatic:l}){const u=this.extendedCalls[t];if(!u)return;u._automaticHold=l??!1;const s=new Promise((n,g)=>{const _=setTimeout(()=>{g(new Error("Hold operation timeout"))},5e3),v=()=>{clearTimeout(_),u.putOnHoldTimestamp=r?Date.now():void 0,n()},C=R=>{clearTimeout(_),g(R)};try{r?(this.stopSessionVad(u._id),u.hold({},v)):u.unhold({},v)}catch(R){C(R)}});try{await s,this.updateCall(u);const n=Object.values(this.extendedCalls).filter(g=>g.roomId===u.roomId&&(r?t!==g._id:!0));n.length>1&&await this.doConference(n)}catch(n){throw console.error("Hold operation failed:",n),n}}holdCall(t,r=!1){return this.processHold({callId:t,automatic:r,toHold:!0})}unholdCall(t){return this.processHold({callId:t,toHold:!1})}cancelAllOutgoingUnanswered(){Object.values(this.getActiveCalls).filter(t=>t.direction==="outgoing"&&t.status===fI).forEach(t=>this.terminateCall(t._id))}answerCall(t){const r=this.extendedCalls[t];this.cancelAllOutgoingUnanswered(),r.answer(this.sipOptions),this.updateCall(r),this.setActiveRoom(r.roomId),r.connection.addEventListener("track",l=>{this.triggerAddStream(l,r)})}async moveCall(t,r){this.updateCallStatus({callId:t,isMoving:!0}),await this.processRoomChange({callId:t,roomId:r}),this.updateCallStatus({callId:t,isMoving:!1})}updateCall(t){this.activeCalls[t._id]=dp(t),this.context.emit("changeActiveCalls",this.activeCalls)}updateRoom(t){const l={...this.activeRooms[t.roomId],...t};this.activeRooms={...this.activeRooms,[t.roomId]:{...l}},this.context.emit("updateRoom",{room:l,roomList:this.activeRooms})}hasAutoAnswerHeaders(t){const r=/answer-after=0/,u=t.request.getHeader("Call-Info");return u&&r.test(u)}addCall(t,r=!0){this.activeCalls={...this.activeCalls,[t._id]:dp(t)},this.extendedCalls[t._id]=t,r&&this.context.emit("changeActiveCalls",this.activeCalls)}addCallStatus(t){this.callStatus={...this.callStatus,[t]:{isMoving:!1,isTransferring:!1,isMerging:!1,isTransferred:!1}},this.context.emit("changeCallStatus",this.callStatus)}updateCallStatus(t){const l={...{...this.callStatus[t.callId]}};t.isMoving!==void 0&&(l.isMoving=t.isMoving),t.isTransferring!==void 0&&(l.isTransferring=t.isTransferring),t.isMerging!==void 0&&(l.isMerging=t.isMerging),t.isTransferred!==void 0&&(l.isTransferred=t.isTransferred),this.callStatus={...this.callStatus,[t.callId]:{...l}},this.context.emit("changeCallStatus",this.callStatus)}removeCallStatus(t){const r={...this.callStatus};delete r[t],this.callStatus={...r},this.context.emit("changeCallStatus",this.callStatus)}addRoom(t){this.activeRooms={...this.activeRooms,[t.roomId]:t},this.context.emit("addRoom",{room:t,roomList:this.activeRooms})}async setupActiveStream(){const t=await kd(await this.managedAudioContext.getContext(),this.initialStreamValue,this.microphoneInputLevel*2);t.getTracks().forEach(r=>r.enabled=!this.isMuted),await this.setActiveStream(t)}async getActiveStream(){const t=await kd(await this.managedAudioContext.getContext(),this.initialStreamValue,this.microphoneInputLevel*2);return t.getTracks().forEach(r=>r.enabled=!this.isMuted),await this.setActiveStream(t),t}async setMicrophone(t){if(!this.getInputDeviceList.find(({deviceId:l})=>l===t)||(this.setSelectedInputDevice(t),Object.keys(this.getActiveCalls).length===0))return;await this.setupStream();const r=Object.values(this.extendedCalls).filter(l=>l.roomId===this.currentActiveRoomId);r.length===1?Object.values(r).forEach(async l=>{await this.setupActiveStream();const u=this.activeStream;l.connection.getSenders()[0].replaceTrack(u.getTracks()[0]),this.updateCall(l)}):await this.doConference(r)}async setActiveStream(t){this.activeStream&&this.stopVUMeter("origin"),await this.setupVUMeter(t,"origin"),this.activeStreamValue=t,this.context.emit("changeActiveStream",t)}async setSpeaker(t){if(!this.getOutputDeviceList.find(({deviceId:u})=>u===t))return;this.setSelectedOutputDevice(t);const r=Object.values(this.extendedCalls);if(r.length===0)return;const l=r.filter(u=>u.roomId===this.currentActiveRoomId);l.length===1?r.forEach(u=>{var s;(s=u.audioTag)==null||s.setSinkId(t),this.updateCall(u)}):await this.doConference(l)}removeRoom(t){const r={...this.activeRooms},l={...r[t]};delete r[t],this.activeRooms={...r},this.context.emit("removeRoom",{room:l,roomList:this.activeRooms})}deleteRoomIfEmpty(t){t!==void 0&&Object.values(this.extendedCalls).filter(r=>r.roomId===t).length===0&&(this.removeRoom(t),this.currentActiveRoomId===t&&(this.currentActiveRoomId=void 0))}checkInitialized(){if(!this.context.initialized)throw new Error("[OpenSIPSJS] You must call `start` method first!")}muteReconfigure(t){this.muted?t.mute({audio:!0}):t.unmute({audio:!0})}startNoiseMonitor({sessionId:t,stream:r,onNoiseDetected:l,onNoiseStop:u}){const s=new AudioContext,n=s.createMediaStreamSource(r.clone()),g=s.createAnalyser();g.fftSize=1024;const _=new Float32Array(g.fftSize);n.connect(g);const v=[];this.vadIntervals[t]&&(clearInterval(this.vadIntervals[t]),this.vadIntervals[t]=null),this.vadMrsIntervals[t]&&(clearInterval(this.vadMrsIntervals[t]),this.vadMrsIntervals[t]=null),this.vadMrsIntervals[t]=setInterval(()=>{g.getFloatTimeDomainData(_);const C=rA(_);v.push(C);const R=Math.ceil(this.noiseReduction.noiseCheckInterval/this.noiseReduction.checkEveryMs);v.length>R&&v.shift()},this.noiseReduction.checkEveryMs),this.vadIntervals[t]=setInterval(()=>{if(v.length===0)return;const C=v.reduce((H,F)=>H+F,0)/v.length,R=this.vadSessionsState[t],D=C>this.noiseReduction.noiseThreshold;R.isSpeaking||(D&&R.currentMode==="clean"?(R.currentMode="noisy",console.log("Average noise high → enable VAD"),this.context.emit("changeNoiseReductionState",{sessionId:t,enabled:!0}),l()):!D&&R.currentMode==="noisy"&&(R.currentMode="clean",console.log("Average noise low → disable VAD"),this.context.emit("changeNoiseReductionState",{sessionId:t,enabled:!1}),u()))},this.noiseReduction.noiseCheckInterval)}async processVAD(t,r){const l=r.clone();this.stopSessionVad(t._id),this.vadSessionsState[t._id]={currentMode:"clean",isSpeaking:!1};const u=await this.managedAudioContext.getContext(),s=await nA(l,u,150);let n=!1;const g=await pp.MicVAD.new({getStream:()=>new Promise(_=>_(l)),...uI,...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(!n){if(n=!0,console.log("✅ VAD initialized, starting background noise monitoring"),this.noiseReduction.mode==="enabled"){t.connection.getSenders()[0]&&t.connection.getSenders()[0].replaceTrack(s.stream.getAudioTracks()[0]);return}this.startNoiseMonitor({sessionId:t._id,stream:l,onNoiseDetected:async()=>{var _;console.log("Replace track with Vad Controlled"),await((_=t.connection.getSenders()[0])==null?void 0:_.replaceTrack(s.stream.getAudioTracks()[0]))},onNoiseStop:async()=>{const _=t.connection.getSenders()[0];_&&_.track&&_.transport&&_.transport.state!=="closed"&&_.transport.state!=="failed"&&(console.log("Replace track with Original"),await _.replaceTrack(l.getAudioTracks()[0]))}})}},onSpeechStart:()=>{var _;console.log("🎤 Speech started"),s.setSpeaking(!0),this.noiseReduction.mode==="enabled"&&((_=t.connection.getSenders()[0])==null||_.replaceTrack(s.stream.getAudioTracks()[0])),this.vadSessionsState[t._id].isSpeaking=!0},onSpeechEnd:()=>{var _;console.log("🛑 Speech end"),s.setSpeaking(!1),this.noiseReduction.mode==="enabled"&&((_=t.connection.getSenders()[0])==null||_.replaceTrack(s.stream.getAudioTracks()[0])),this.vadSessionsState[t._id].isSpeaking=!1}});this.vadSessions[t._id]&&(this.vadSessions[t._id].pause(),delete this.vadSessions[t._id]),this.vadSessions[t._id]=g,g.start()}stopSessionVad(t){this.vadSessions[t]&&(this.vadSessions[t].pause(),delete this.vadSessions[t]),this.vadIntervals[t]&&(clearInterval(this.vadIntervals[t]),delete this.vadIntervals[t]),this.vadMrsIntervals[t]&&(clearInterval(this.vadMrsIntervals[t]),delete this.vadMrsIntervals[t]),this.vadSessionsState[t]&&delete this.vadSessionsState[t]}async roomReconfigure(t){var u;if(t===void 0)return;const r=Object.values(this.extendedCalls).filter(s=>s.roomId===t),l=this.currentActiveRoomId===t;if(r.forEach((s,n)=>{if(s.audioTag){s.connection.getReceivers().forEach(_=>{_.track.enabled=!s.localMuted}),l&&this.muteReconfigure(s);const g=!l;s.audioTag.muted=g,this.updateCall(s)}}),r.length===0){!!this.conferenceNodes[t]&&await this.cleanupConferenceNodes(t),this.deleteRoomIfEmpty(t);return}if(r.length===1&&!l){const s=r[0];s.isOnHold().local||await this.holdCall(s._id,!0),!!this.conferenceNodes[t]&&await this.cleanupConferenceNodes(t);return}if(r.length===1&&l){const s=r[0];s.isOnHold().local&&s._automaticHold&&await this.unholdCall(s._id);const _=(((u=s.connection)==null?void 0:u.getSenders())||[])[0];if(s.connection&&_)try{await this.setupActiveStream();const C=this.activeStream;["enabled","dynamic"].includes(this.noiseReduction.mode)&&this.processVAD(r[0],C);const R=C.getTracks();await _.replaceTrack(R[0]),this.muteReconfigure(s)}catch(C){console.error(C)}!!this.conferenceNodes[t]&&await this.cleanupConferenceNodes(t);return}r.length>1&&await this.doConference(r)}async doConference(t){if(t.length===0)return;const r=t[0].roomId,l=this.currentActiveRoomId===r;if(t.find(_=>_.roomId!==r))return;const s=await this.managedAudioContext.getContext();if(s.state!=="running"){console.error(`[doConference] ERROR: AudioContext is not running! State: ${s.state}`);return}await this.cleanupConferenceNodes(r),this.conferenceNodes[r]={sources:new Map,destinations:new Map,gains:new Map};const n=this.conferenceNodes[r],g=new Map;t.forEach((_,v)=>{_&&_.connection&&_.connection.getReceivers().forEach((R,D)=>{var q,G,te;R.track.enabled=!_.localMuted;const H=(q=R.track)==null?void 0:q.id;(G=R.track)==null||G.readyState,(te=R.track)==null||te.kind;const F=`${_._id}-${H}`;R.track&&R.track.readyState==="live"&&g.set(F,R.track)})}),await this.setupActiveStream(),await iA.forEach(t,async(_,v)=>{if(!_||!_.connection)return;const C=s.createMediaStreamDestination();n.destinations.set(_._id,C);let R=0;if(g.forEach((q,G)=>{if(!G.startsWith(_._id))try{const te=s.createMediaStreamSource(new MediaStream([q])),X=s.createGain(),we=`${_._id}-${G}`;te.connect(X),X.connect(C),n.sources.set(we,te),n.gains.set(we,X),R++}catch(te){console.error(te)}}),l&&this.activeStreamValue)try{const q=this.activeStream,G=s.createMediaStreamSource(q),te=s.createGain(),X=`${_._id}-local`;G.connect(te),te.connect(C),n.sources.set(X,G),n.gains.set(X,te)}catch(q){console.error(q)}else l&&console.error(`Host room but no activeStreamValue - skipping host microphone for session ${_._id}`);const H=_.connection.getSenders()[0],F=C.stream.getTracks();if(["enabled","dynamic"].includes(this.noiseReduction.mode)&&this.processVAD(_,C.stream),H&&F[0])try{await H.replaceTrack(F[0]),this.muteReconfigure(_)}catch(q){console.error(q)}})}processCallerMute(t,r){const l=this.extendedCalls[t];l&&l.connection.getReceivers().length&&(l.localMuted=r,l.connection.getReceivers().forEach(u=>{u.track.enabled=!r}),this.updateCall(l))}muteCaller(t){this.processCallerMute(t,!0)}unmuteCaller(t){this.processCallerMute(t,!1)}terminateCall(t){const r=this.extendedCalls[t];r._status===4?r.terminate({status_code:603,reason_phrase:"Decline"}):r._status!==8&&r.terminate()}transferCall(t,r){if(r.toString().length===0)return new Error("Target must be passed");const l=this.extendedCalls[t];if(!l._is_confirmed&&!l._is_canceled){const u=`sip:${r}@${this.context.sipDomain}`;l.terminate({status_code:302,reason_phrase:"Moved Temporarily",extraHeaders:[`Contact: ${u}`]});return}this.updateCallStatus({callId:t,isTransferring:!0,isTransferred:!1}),l.refer(`sip:${r}@${this.context.sipDomain}`,{eventHandlers:{requestSucceeded:()=>{this.updateCallStatus({callId:t,isTransferring:!1,isTransferred:!0})},requestFailed:()=>{this.updateCallStatus({callId:t,isTransferring:!1,isTransferred:!1})}}}),this.updateCall(l)}mergeCall(t){const r=Object.values(this.extendedCalls).filter(s=>s.roomId===t);if(r.length!==2)return;const l=r[0],u=r[1];!l||!u||(this.updateCallStatus({callId:l._id,isMerging:!0}),this.updateCallStatus({callId:u._id,isMerging:!0}),l.refer(u.remote_identity.uri.toString(),{replaces:u}),this.updateCall(l))}mergeCallByIds(t,r){const l=Object.values(this.extendedCalls).find(s=>s._id===t),u=Object.values(this.extendedCalls).find(s=>s._id===r);if(!l||!u)throw new Error("Call ID is not provided");this.updateCallStatus({callId:t,isMerging:!0}),this.updateCallStatus({callId:r,isMerging:!0}),l.refer(u.remote_identity.uri.toString(),{replaces:u}),this.updateCall(l)}setDND(t){this.isDNDEnabled=t,this.context.emit("changeIsDND",t)}setCallWaiting(t){this.isCallWaitingEnabled=t,this.context.emit("changeIsCallWaiting",t)}startCallTimer(t){this.removeTimeInterval(t);const r={callId:t,hours:0,minutes:0,seconds:0,formatted:""};this.setCallTime(r);const l=setInterval(()=>{const u={...this.callTime[t]},s=sA(u);this.setCallTime({callId:t,...s})},1e3);this.setTimeInterval(t,l)}async setActiveRoom(t){const r=this.currentActiveRoomId;t!==r&&(this.currentActiveRoomId=t,await this.roomReconfigure(r),await this.roomReconfigure(t))}getNewRoomId(){const t=Object.keys(this.activeRooms);return t.length===0?1:parseInt(t.sort()[t.length-1])+1}async setupCall(t){var v,C;const r=t.session;if(this.getActiveCalls[r.id]!==void 0)return;const u=this.getNewRoomId(),s={started:new Date,incomingInProgress:!1,roomId:u};r.direction==="incoming"?(this.context.logger.log("New incoming call from",(C=(v=r._remote_identity)==null?void 0:v._uri)==null?void 0:C._user),s.incomingInProgress=!0,this.context.subscribe(Mr.CALL_CONFIRMED,R=>{r.id===R.id&&(this.updateRoom({incomingInProgress:!1,roomId:u}),this.startCallTimer(r.id))}),this.context.subscribe(Mr.CALL_FAILED,R=>{r.id===R.id&&(this.updateRoom({incomingInProgress:!1,roomId:u}),this.deleteRoomIfEmpty(u))})):r.direction==="outgoing"&&(r.once("confirmed",()=>{this.startCallTimer(r.id)}),this.startCallTimer(r.id));const n=r,g=this.hasAutoAnswerHeaders(t),_=n.direction==="incoming"&&!this.hasActiveCalls&&(g||this.autoAnswer);n.roomId=u,n.localMuted=!1,n.autoAnswer=_,_?this.addCall(n,!1):this.addCall(n),this.addCallStatus(r.id),this.addRoom(s),_&&this.answerCall(n._id)}removeCall(t){const r={...this.activeCalls};delete r[t],this.activeCalls={...r};const l={...this.extendedCalls};delete l[t],this.extendedCalls={...l},this.context.emit("changeActiveCalls",this.activeCalls)}activeCallListRemove(t){const r=this.extendedCalls[t._id];if(!r)return;this.stopVUMeter("origin"),this.stopVUMeter(t._id);const l=r.roomId;this.removeCall(t._id),this.roomReconfigure(l).then(()=>{}).catch(u=>{console.error("Error reconfiguring room after call removal:",u)})}shouldTerminateNewSession(t){if(t.session.direction==="outgoing")return!1;const l=!this.isCallWaiting&&this.hasActiveCalls;return this.isDND||l}async newRTCSessionCallback(t){const r=t.session;if(this.shouldTerminateNewSession(t)){r.terminate({status_code:486,reason_phrase:"Do Not Disturb"});return}if(this.context.triggerListener({listenerType:Mr.NEW_CALL,session:r,event:t}),r.on("ended",l=>{var s,n,g;this.stopVUMeter(r.id),this.context.logger.log("Session ended for",(n=(s=r._remote_identity)==null?void 0:s._uri)==null?void 0:n._user),this.context.triggerListener({listenerType:Mr.CALL_ENDED,session:r,event:l}),["enabled","dynamic"].includes(this.noiseReduction.mode)&&this.stopSessionVad(r._id);const u=this.getActiveCalls[r.id];u&&this.activeCallListRemove(u),this.stopCallTimer(r.id),this.removeCallStatus(r.id),this.removeCallMetrics(r.id),Object.keys(this.extendedCalls).length||(this.setIsMuted(!1),(g=this.initialStreamValue)==null||g.getTracks().forEach(_=>_.stop()),this.initialStreamValue=null),this.context.isWaitingForSessionHangup()&&!this.hasActiveAnsweredCalls&&this.context.stopSessionAfterWaiting()}),r.on("progress",l=>{var u,s;this.context.logger.log("Session in progress for",(s=(u=r._remote_identity)==null?void 0:u._uri)==null?void 0:s._user),this.context.triggerListener({listenerType:Mr.CALL_PROGRESS,session:r,event:l})}),r.on("failed",l=>{var s,n,g;this.stopVUMeter(r.id),this.context.logger.log("Session failed for",(n=(s=r._remote_identity)==null?void 0:s._uri)==null?void 0:n._user),this.context.triggerListener({listenerType:Mr.CALL_FAILED,session:r,event:l}),["enabled","dynamic"].includes(this.noiseReduction.mode)&&this.stopSessionVad(r._id),r.id===this.callAddingInProgress&&(this.callAddingInProgress=void 0);const u=this.getActiveCalls[r.id];u&&this.activeCallListRemove(u),this.stopCallTimer(r.id),this.removeCallStatus(r.id),this.removeCallMetrics(r.id),Object.keys(this.extendedCalls).length||(this.setIsMuted(!1),(g=this.initialStreamValue)==null||g.getTracks().forEach(_=>_.stop()),this.initialStreamValue=null),this.context.isWaitingForSessionHangup()&&!this.hasActiveAnsweredCalls&&this.context.stopSessionAfterWaiting()}),r.on("confirmed",l=>{var u,s;this.context.logger.log("Session confirmed for",(s=(u=r._remote_identity)==null?void 0:u._uri)==null?void 0:s._user),this.context.triggerListener({listenerType:Mr.CALL_CONFIRMED,session:r,event:l}),this.updateCall(r),r.id===this.callAddingInProgress&&(this.callAddingInProgress=void 0)}),await this.setupCall(t),r.direction==="outgoing"){const l=this.getActiveCalls[r.id].roomId;await this.setActiveRoom(l)}}setMuteWhenJoin(t){this.muteWhenJoinEnabled=t,this.context.emit("changeMuteWhenJoin",t)}setMicrophoneSensitivity(t){if(t<0||t>1)throw new Error("Value should be in range from 0 to 1!");this.microphoneInputLevelValue=t,this.roomReconfigure(this.currentActiveRoomId)}setSpeakerVolume(t){this.speakerVolumeValue=t,Object.values(this.extendedCalls).forEach(r=>{r.audioTag&&(r.audioTag.volume=t,this.updateCall(r))})}setAutoAnswer(t){this.isAutoAnswer=t}setSelectedInputDevice(t){localStorage.setItem(Wu.SELECTED_INPUT_DEVICE,t),this.selectedMediaDevices.input=t,this.context.emit("changeActiveInputMediaDevice",t)}setSelectedOutputDevice(t){localStorage.setItem(Wu.SELECTED_OUTPUT_DEVICE,t),this.selectedMediaDevices.output=t,this.context.emit("changeActiveOutputMediaDevice",t)}setCallMetrics(t){const r={...t};delete r.callId,this.callMetrics={...this.callMetrics,[t.callId]:r},this.context.emit("changeCallMetrics",this.callMetrics)}removeCallMetrics(t){const r={...this.callMetrics};delete r[t],this.callMetrics={...r},this.context.emit("changeCallMetrics",this.callMetrics)}getCallQuality(t){const r=new aI(this.metricConfig),l=r.createProbe(t.connection,{cid:t._id}),u=[];let s;l.onreport=n=>{Object.entries(n.audio).forEach(([v,C])=>{C.direction==="inbound"&&!u.includes(v)&&(u.push(v),s=v)});const g=n.audio[s];if(!g)return;const _=lI(g,oI);_.callId=t._id,this.setCallMetrics(_)},this.context.subscribe(Mr.CALL_ENDED,n=>{n._id===t._id&&r.stopAllProbes()}),r.startAllProbes()}async setupVUMeter(t,r){await this.VUMeter.start(await this.managedAudioContext.getContext(),t,r)}stopVUMeter(t){this.VUMeter.stop(t)}async setupStream(){try{const t=Date.now(),r=await navigator.mediaDevices.getUserMedia(this.getUserMediaConstraints);this.initialStreamValue&&(this.initialStreamValue.getTracks().forEach((u,s)=>{u.stop()}),this.initialStreamValue=null),this.initialStreamValue=r}catch(t){throw t}}async triggerAddStream(t,r){const l=this.muteWhenJoin||this.isMuted;this.setIsMuted(l),this.initialStreamValue||await this.setupStream();const u=await this.managedAudioContext.getContext(),s=await kd(u,this.initialStreamValue,this.microphoneInputLevel*2),n=this.isMuted||this.muteWhenJoin;s.getTracks().forEach(D=>{D.enabled=!n}),await this.setActiveStream(s),await r.connection.getSenders()[0].replaceTrack(s.getTracks()[0]);const v=new MediaStream([t.track]);!Object.values(this.extendedCalls).find(D=>D.audioTag&&D.audioTag.id===r._id)&&BC(v,r,this.selectedOutputDevice,this.speakerVolume);const R=r.roomId===this.currentActiveRoomId;r.audioTag&&(r.audioTag.muted=!R),await this.setupVUMeter(v,r._id),this.getCallQuality(r),this.updateCall(r),["enabled","dynamic"].includes(this.noiseReduction.mode)&&this.processVAD(r,s)}initCall(t,r,l=!1){if(t.length===0)return console.error("Target must be a valid string");this.context.logger.log(`Calling sip:${t}@${this.context.sipDomain}...`);const u=this.context.call(`sip:${t}@${this.context.sipDomain}`,this.sipOptions);if(this.callAddingInProgress=u.id,r&&this.currentActiveRoomId!==void 0&&(this.processRoomChange({callId:u.id,roomId:this.currentActiveRoomId}),l)){const s=Object.values(this.extendedCalls).filter(n=>n.roomId===this.currentActiveRoomId&&n._id!==u.id);for(const n of s)this.holdCall(n._id,!0)}u.connection.addEventListener("track",s=>{this.triggerAddStream(s,u)})}async processRoomChange({callId:t,roomId:r}){const l=this.extendedCalls[t];if(!l)return;const u=l.roomId;l.roomId=r,this.updateCall(l),await this.roomReconfigure(u),await this.roomReconfigure(r)}}class _I{constructor(t){this.context=t}get sipOptions(){return{...this.context.options.sipOptions}}initCall(t,r){if(t.length===0)return console.error("Target must be a valid string");this.context.logger.log(`Calling sip:${t}@${this.context.sipDomain}...`),this.context.joinVideoCall(`sip:${t}@${this.context.sipDomain}`,r,this.sipOptions)}stop(t={}){this.context.terminateJanusSessions(t)}startAudio(){this.context.enableJanusAudio(!0)}stopAudio(){this.context.enableJanusAudio(!1)}startVideo(){this.context.enableJanusVideo(!0)}stopVideo(){this.context.enableJanusVideo(!1)}changeMediaConstraints(t){this.context.changeMediaConstraints(t)}startScreenShare(){this.context.startScreenShare()}startBlur(){this.context.startBlur()}stopBlur(){this.context.stopBlur()}}class pI{constructor(t){this.activeMessages={},this.extendedMessages={},this.msrpHistory={},this.context=t,this.context.on(this.context.newMSRPSessionEventName,this.newMSRPSessionCallback.bind(this.context))}get isMSRPInitializing(){return this.isMSRPInitializingValue}get getActiveMessages(){return this.activeMessages}msrpAnswer(t){const r=this.extendedMessages[t];this.updateMSRPSession(r)}updateMSRPSession(t){this.activeMessages[t._id]=fp(t),this.context.emit("changeActiveMessages",this.activeMessages)}addMMSRPSession(t){this.activeMessages={...this.activeMessages,[t._id]:fp(t)},this.extendedMessages[t._id]=t,this.context.emit("changeActiveMessages",this.activeMessages)}addMSRPMessage(t,r){const l=this.msrpHistory[r.id]||[];l.push(t),this.msrpHistory={...this.msrpHistory,[r.id]:[...l]},this.context.emit("newMSRPMessage",{message:t,session:r})}messageTerminate(t){const r=this.extendedMessages[t];r._status!==8&&r.terminate()}addMessageSession(t){if(!t._id||this.getActiveMessages[t._id]!==void 0)return;const l=t;this.addMMSRPSession(l)}triggerMSRPListener({listenerType:t,session:r,event:l}){const u=this.context.listenersList[t];!u||!u.length||u.forEach(s=>{s(r,l)})}removeMMSRPSession(t){const r={...this.activeMessages};delete r[t],this.activeMessages={...r};const l={...this.extendedMessages};delete l[t],this.extendedMessages={...l},this.context.emit("changeActiveMessages",this.activeMessages)}activeMessageListRemove(t){this.removeMMSRPSession(t._id)}newMSRPSessionCallback(t){const r=t.session;r.on("ended",l=>{this.triggerMSRPListener({listenerType:Mr.CALL_ENDED,session:r,event:l});const u=this.getActiveMessages[r.id];this.activeMessageListRemove(u)}),r.on("failed",l=>{this.triggerMSRPListener({listenerType:Mr.CALL_FAILED,session:r,event:l});const u=this.getActiveMessages[r.id];this.activeMessageListRemove(u)}),r.on("confirmed",l=>{this.triggerMSRPListener({listenerType:Mr.CALL_CONFIRMED,session:r,event:l}),this.updateMSRPSession(r)}),r.on("newMessage",l=>{this.addMSRPMessage(l,r)}),this.addMessageSession(r)}setIsMSRPInitializing(t){this.isMSRPInitializingValue=t,this.context.emit("isMSRPInitializingChanged",t)}initMSRP(t,r,l){if(t.length===0)return console.error("Target must be a valid string");const u=this.context.startMSRP(t,l);u.on("active",()=>{this.addMessageSession(u),u.sendMSRP(r),this.setIsMSRPInitializing(!1)}),this.setIsMSRPInitializing(!0)}sendMSRP(t,r){const l=this.extendedMessages[t];if(!l)throw new Error(`MSRP session with id ${t} doesn't exist!`);l.sendMSRP(r)}}const Ku={AUDIO:"audio",VIDEO:"video",MSRP:"msrp"};class Vp{constructor(t){this.opensips=null,this.session=null,this.name=null,this.name=t}setOpensips(t){this.opensips=t}setSession(t){this.session=t}kill(){this.opensips.kill(this.name)}}class qp extends Vp{constructor(t,r){super(t),this._candidates=[],this._subscribeSent=!1,this._configureSent=!1,this._lastTrickleReceived=!1,this.type=r}connect(t={}){this.opaqueId=this.session.generateOpaqueId();const r=Nt.cloneArray(t.extraHeaders),l={from_tag:this.session._from_tag};t.fromUserName&&(l.from_uri=new Ia("sip",t.fromUserName,this.session._ua.configuration.uri.host),r.push(`P-Preferred-Identity: ${this.session._ua.configuration.uri.toString()}`)),t.fromDisplayName&&(l.from_display_name=t.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 Ds.InitialOutgoingInviteRequest(this.session.target,this.session._ua,l,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 t;this._connection.onicecandidate=r=>{this._connection.signalingState!=="stable"&&this._connection.signalingState!=="have-local-offer"||r.candidate&&(this._candidates.push(r.candidate),clearTimeout(t),t=setTimeout(()=>{this._lastTrickleReceived=!0,this._subscribeSent&&!this._configureSent&&this._sendConfigureMessage({audio:!0,video:!0})},500))}}addTracks(t){t.forEach(r=>{this._connection.addTrack(r)})}async _sendInitialRequest(){const t=new no(this.session._ua,this._request,{onRequestTimeout:()=>{this.session.onRequestTimeout()},onTransportError:()=>{this.session.onTransportError()},onAuthenticated:s=>{this._request=s},onReceiveResponse:s=>{this._receiveInviteResponse(s)}});if(await this.generateStream(),!this.stream||!this.stream.getTracks().length)return;this.addTracks(this.stream.getTracks());const r={audio:!1,video:!0};this.jsep_offer=await this._connection.createOffer(r),await this._connection.setLocalDescription(this.jsep_offer);const l={janus:"attach",plugin:"janus.plugin.videoroom",opaque_id:this.opaqueId},u=JSON.stringify(l);this._request.body=u,t.send()}_receiveInviteResponse(t){if(this._publisherSubscribeSent||!t.body)return;const r=JSON.parse(t.body);this.handleId=r.data.id;const l={janus:"message",body:{request:"join",room:this.session.room_id,ptype:"publisher",display:this.session.display_name+" (Screen Share)",opaque_id:this.opaqueId},handle_id:this.handleId},u=[this.session.getPTypeHeader(ir.PUBLISHER)];this.session.sendRequest(fe.SUBSCRIBE,{extraHeaders:u,body:JSON.stringify(l),eventHandlers:{onSuccessResponse:async s=>{var n,g,_,v;if(s.status_code===200){if(this._subscribeSent=!0,s.body)try{const C=JSON.parse(s.body)||{};((g=(n=C.plugindata)==null?void 0:n.data)==null?void 0:g.videoroom)==="joined"&&this.session.myFeedList.push(C.plugindata.data.id),(v=(_=C.plugindata)==null?void 0:_.data)!=null&&v.publishers&&this.session.receivePublishers(C)}catch(C){console.error(C)}this._lastTrickleReceived&&!this._configureSent&&this._sendConfigureMessage({audio:!0,video:!0})}}}}),this._publisherSubscribeSent=!0}async _sendConfigureMessage(t){const r=this._candidates.map(n=>({janus:"trickle",candidate:n,handle_id:this.handleId,session_id:this.session.session_id})),u={configure:{janus:"message",body:{request:"configure",record:!0,filename:this.session.getRecordFileName(),...t},jsep:this.jsep_offer,handle_id:this.handleId,session_id:this.session.session_id},trickles:[...r]},s=["Content-Type: application/json",this.session.getPTypeHeader(ir.ICE)];this.session.sendRequest(fe.INFO,{extraHeaders:s,body:JSON.stringify(u),eventHandlers:{onSuccessResponse:async n=>{this._configureSent=!0;const _=n.data.split(`\r
2991
2991
  `),v=_[_.length-1],C=JSON.parse(v);await this._connection.setRemoteDescription(C.jsep),this._candidates=[]}}})}_sendDetach(){const t={janus:"detach",handle_id:this.handleId,session_id:this.session.session_id},r=[this.session.getPTypeHeader(ir.DETACH)];this.session.sendRequest(fe.INFO,{extraHeaders:r,body:JSON.stringify(t)}),this.session._ua.emit("pluginDetach",this.name)}async stopMedia(){this._connection&&(this._connection.close(),this._connection=null),this.stream&&(this.stream=null)}async stop(){await this.session.stopProcessPlugins(this.type);const t=this._connection.getSenders();t.forEach(r=>{const l=r.track;l&&l.stop()}),t.forEach(r=>{this._connection.removeTrack(r)}),await this.stopMedia(),this._sendDetach()}async generateStream(){throw new Error("generateStream method is not implemented")}}class jp extends Vp{constructor(t,r,l={}){super(t),this.stream=null,this.running=!1,this.immediate=!1,this.type="video",this.immediate=l.immediate||!1,this.type=r}start(t){return t}stop(){throw new Error("stop method is not implemented")}async process(t){if(this.immediate){const r=await this.start(t);return this.running=!0,r}return t}async connect(){this.running=!0,await this.session.resyncPlugins(this.type)}terminate(){this.stop()}async kill(){this.stop(),this.running=!1,await this.session.resyncPlugins(this.type)}}class mI extends NC{constructor(t,r){if(!t.modules.length)throw new Error("options.modules should include at least 1 module");const l={...t.configuration,sockets:t.socketInterfaces.map(u=>new tA.WebSocketInterface(u))};super(l),this.initialized=!1,this.connected=!1,this.logger=console,this.newRTCSessionEventName="newRTCSession",this.registeredEventName="registered",this.unregisteredEventName="unregistered",this.disconnectedEventName="disconnected",this.connectedEventName="connected",this.newMSRPSessionEventName="newMSRPSession",this.isReconnecting=!1,this.activeConnection=!1,this.waitingForSessionHangup=!1,this.waitingForSessionTimeout=null,this.reconnectionAttemptsLimit=1/0,this.reconnectionAttemptsCounter=0,this.audio=null,this.msrp=null,this.video=null,this.listenersList={},this.modules=[],t.pnExtraHeaders&&Object.keys(t.pnExtraHeaders).length&&this.registrator().setExtraContactUriParams(t.pnExtraHeaders),this.options=t,this.modules=t.modules,t.configuration.reconnectionAttemptsLimit&&(this.reconnectionAttemptsLimit=t.configuration.reconnectionAttemptsLimit),r&&zC(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(Ku.AUDIO)?this.audio.hasActiveAnsweredCalls:!1}on(t,r){return super.on(t,r)}off(t,r){return super.off(t,r)}emit(t,r){return super.emit(t,r)}get sipDomain(){return this.options.sipDomain}use(t){if(this.newStreamPlugins.find(r=>r.name===t.name)||this.processStreamPlugins.find(r=>r.name===t.name))throw new Error(`Plugin with name ${t.name} already exists`);if(t instanceof qp)t.setOpensips(this),this.newStreamPlugins.push(t);else if(t instanceof jp)t.setOpensips(this),this.processStreamPlugins.push(t);else throw new Error("Wrong plugin instance")}getPlugin(t){return this.newStreamPlugins.find(r=>r.name===t)||this.processStreamPlugins.find(r=>r.name===t)}reconnect(){if(this.reconnectionAttemptsCounter<this.reconnectionAttemptsLimit){const r=5e3*Math.pow(2,this.reconnectionAttemptsCounter);this.reconnectionAttemptsCounter++,setTimeout(this.start.bind(this),r)}else this.emit("reconnectionAttemptsLimitReached",void 0)}begin(){if(this.isConnected()){console.error("Connection is already established");return}return this.modules.includes(Ku.AUDIO)&&(this.audio=new hI(this)),this.modules.includes(Ku.MSRP)&&(this.msrp=new pI(this)),this.modules.includes(Ku.VIDEO)&&(this.video=new _I(this)),this.on(this.registeredEventName,()=>{this.logger.log("Successfully registered to",this.options.socketInterfaces[0]),this.setInitialized(!0)}),this.on(this.unregisteredEventName,()=>{this.logger.log("Unregistered from",this.options.socketInterfaces[0]),this.setInitialized(!1)}),this.on(this.connectedEventName,()=>{this.logger.log("Connected to",this.options.socketInterfaces[0]),this.setConnected(!0),this.setReconnecting(!1),this.activeConnection=!0,this.waitingForSessionHangup=!1,this.reconnectionAttemptsCounter=0}),this.on(this.disconnectedEventName,()=>{this.setConnected(!1),!this.isReconnecting&&(this.setReconnecting(!0),this.logger.log("Disconnected from",this.options.socketInterfaces[0]),this.logger.log("Reconnecting to",this.options.socketInterfaces[0]),this.hasActiveSessions?(this.waitingForSessionHangup=!0,this.stop(!1),this.waitingForSessionTimeout=setTimeout(()=>{this.terminateAllSessions(),this.setInitialized(!1),this.waitingForSessionHangup=!1,this.activeConnection&&this.reconnect()},12e5)):(this.stop(),this.setInitialized(!1),this.activeConnection&&this.reconnect()))}),this.logger.log("Connecting to",this.options.socketInterfaces[0]),this.start(),this}disconnect(){this.activeConnection=!1,this.stop()}subscribe(t,r){const u=!this.listenersList[t]||!this.listenersList[t].length?[r]:[...this.listenersList[t],r];this.listenersList={...this.listenersList,[t]:u}}removeIListener(t){const r={...this.listenersList};delete r[t],this.listenersList={...r}}triggerListener({listenerType:t,session:r,event:l}){const u=this.listenersList[t];!u||!u.length||u.forEach(s=>{s(r,l)})}setInitialized(t){this.initialized=t,this.emit("ready",t)}setConnected(t){this.connected=t,this.emit("connection",t)}setReconnecting(t){this.isReconnecting=t,this.emit("reconnecting",t)}}tr.BaseNewStreamPlugin=qp,tr.BaseProcessStreamPlugin=jp,tr.default=mI,Object.defineProperties(tr,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});