@whereby.com/browser-sdk 2.0.0-alpha12 → 2.0.0-alpha14

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.
@@ -7,7 +7,7 @@ function D(e){return e.join(P).replace(B,q).replace(N,U)}var I=" \\f\\n\\r\\t",j
7
7
  /*! (c) Andrea Giammarchi - ISC */
8
8
  var J=function(e){var t="fragment",i="template",n="content"in a(i)?function(e){var t=a(i);return t.innerHTML=e,t.content}:function(e){var n=a(t),r=a(i),o=null;if(/^[^\S]*?<(col(?:group)?|t(?:head|body|foot|r|d|h))/i.test(e)){var c=RegExp.$1;r.innerHTML="<table>"+e+"</table>",o=r.querySelectorAll(c)}else r.innerHTML=e,o=r.childNodes;return s(n,o),n};return function(e,t){return("svg"===t?r:n)(e)};function s(e,t){for(var i=t.length;i--;)e.appendChild(t[0])}function a(i){return i===t?e.createDocumentFragment():e.createElementNS("http://www.w3.org/1999/xhtml",i)}function r(e){var i=a(t),n=a("div");return n.innerHTML='<svg xmlns="http://www.w3.org/2000/svg">'+e+"</svg>",s(i,n.firstChild.childNodes),i}}(document),Q=(e,t,i,n,s)=>{const a=i.length;let r=t.length,o=a,c=0,p=0,d=null;for(;c<r||p<o;)if(r===c){const t=o<a?p?n(i[p-1],-0).nextSibling:n(i[o-p],0):s;for(;p<o;)e.insertBefore(n(i[p++],1),t)}else if(o===p)for(;c<r;)d&&d.has(t[c])||e.removeChild(n(t[c],-1)),c++;else if(t[c]===i[p])c++,p++;else if(t[r-1]===i[o-1])r--,o--;else if(t[c]===i[o-1]&&i[p]===t[r-1]){const s=n(t[--r],-1).nextSibling;e.insertBefore(n(i[p++],1),n(t[c++],-1).nextSibling),e.insertBefore(n(i[--o],1),s),t[r]=i[o]}else{if(!d){d=new Map;let e=p;for(;e<o;)d.set(i[e],e++)}if(d.has(t[c])){const s=d.get(t[c]);if(p<s&&s<o){let a=c,l=1;for(;++a<r&&a<o&&d.get(t[a])===s+l;)l++;if(l>s-p){const a=n(t[c],0);for(;p<s;)e.insertBefore(n(i[p++],1),a)}else e.replaceChild(n(i[p++],1),n(t[c++],-1))}else c++}else e.removeChild(n(t[c++],-1))}return i},Y=function(e,t,i,n,s){var a=s in e,r=e.createDocumentFragment();return r.appendChild(e.createTextNode("g")),r.appendChild(e.createTextNode("")),(a?e.importNode(r,!0):r.cloneNode(!0)).childNodes.length<2?function e(t,i){for(var n=t.cloneNode(),s=t.childNodes||[],a=s.length,r=0;i&&r<a;r++)n.appendChild(e(s[r],i));return n}:a?e.importNode:function(e,t){return e.cloneNode(!!t)}}(document,0,0,0,"importNode"),X="".trim||function(){return String(this).replace(/^\s+|\s+/g,"")},Z=T?function(e,t){var i=t.join(" ");return t.slice.call(e,0).sort((function(e,t){return i.indexOf(e.name)<=i.indexOf(t.name)?-1:1}))}:function(e,t){return t.slice.call(e,0)};function ee(e,t){for(var i=t.length,n=0;n<i;)e=e.childNodes[t[n++]];return e}function te(e,t,i,n){for(var s=e.childNodes,a=s.length,r=0;r<a;){var o=s[r];switch(o.nodeType){case 1:var c=n.concat(r);ie(o,t,i,c),te(o,t,i,c);break;case 8:var p=o.textContent;if(p===k)i.shift(),t.push(E.test(e.nodeName)?ae(e,n):ne(o,n.concat(r)));else switch(p.slice(0,2)){case"/*":if("*/"!==p.slice(-2))break;case"👻":e.removeChild(o),r--,a--}break;case 3:E.test(e.nodeName)&&X.call(o.textContent)===P&&(i.shift(),t.push(ae(e,n)))}r++}}function ie(e,t,i,n){for(var s=e.attributes,a=[],r=[],o=Z(s,i),c=o.length,p=0;p<c;){var d,l=o[p++],u=l.value===k;if(u||1<(d=l.value.split(P)).length){var m=l.name;if(a.indexOf(m)<0){a.push(m);var h=i.shift().replace(u?/^(?:|[\S\s]*?\s)(\S+?)\s*=\s*('|")?$/:new RegExp("^(?:|[\\S\\s]*?\\s)("+m+")\\s*=\\s*('|\")[\\S\\s]*","i"),"$1"),f=s[h]||s[h.toLowerCase()];if(u)t.push(se(f,n,h,null));else{for(var g=d.length-2;g--;)i.shift();t.push(se(f,n,h,d))}}r.push(l)}}p=0;for(var v=(0<(c=r.length)&&T&&!("ownerSVGElement"in e));p<c;){var b=r[p++];v&&(b.value=""),e.removeAttribute(b.name)}var _=e.nodeName;if(/^script$/i.test(_)){var y=document.createElement(_);for(c=s.length,p=0;p<c;)y.setAttributeNode(s[p++].cloneNode(!0));y.textContent=e.textContent,e.parentNode.replaceChild(y,e)}}function ne(e,t){return{type:"any",node:e,path:t}}function se(e,t,i,n){return{type:"attr",node:e,path:t,name:i,sparse:n}}function ae(e,t){return{type:"text",node:e,path:t}}var re=G(new _);function oe(e,t){var i=(e.convert||D)(t),n=e.transform;n&&(i=n(i));var s=J(i,e.type);de(s);var a=[];return te(s,a,t.slice(0),[]),{content:s,updates:function(i){for(var n=[],s=a.length,r=0,o=0;r<s;){var c=a[r++],p=ee(i,c.path);switch(c.type){case"any":n.push({fn:e.any(p,[]),sparse:!1});break;case"attr":var d=c.sparse,l=e.attribute(p,c.name,c.node);null===d?n.push({fn:l,sparse:!1}):(o+=d.length-2,n.push({fn:l,sparse:!0,values:d}));break;case"text":n.push({fn:e.text(p),sparse:!1}),p.textContent=""}}return s+=o,function(){var e=arguments.length;if(s!==e-1)throw new Error(e-1+" values instead of "+s+"\n"+t.join("${value}"));for(var a=1,r=1;a<e;){var o=n[a-r];if(o.sparse){var c=o.values,p=c[0],d=1,l=c.length;for(r+=l-2;d<l;)p+=arguments[a++]+c[d++];o.fn(p)}else o.fn(arguments[a++])}return i}}}}function ce(e,t){var i=re.get(t)||re.set(t,oe(e,t));return i.updates(Y.call(document,i.content,!0))}var pe=[];function de(e){for(var t=e.childNodes,i=t.length;i--;){var n=t[i];1!==n.nodeType&&0===X.call(n.textContent).length&&e.removeChild(n)}}
9
9
  /*! (c) Andrea Giammarchi - ISC */var le=function(){var e=/acit|ex(?:s|g|n|p|$)|rph|ows|mnc|ntw|ine[ch]|zoo|^ord/i,t=/([^A-Z])([A-Z]+)/g;return function(e,t){return"ownerSVGElement"in e?function(e,t){var i;t?i=t.cloneNode(!0):(e.setAttribute("style","--hyper:style;"),i=e.getAttributeNode("style"));return i.value="",e.setAttributeNode(i),n(i,!0)}(e,t):n(e.style,!1)};function i(e,t,i){return t+"-"+i.toLowerCase()}function n(n,s){var a,r;return function(o){var c,p,d,l;switch(typeof o){case"object":if(o){if("object"===a){if(!s&&r!==o)for(p in r)p in o||(n[p]="")}else s?n.value="":n.cssText="";for(p in c=s?{}:n,o)d="number"!=typeof(l=o[p])||e.test(p)?l:l+"px",!s&&/^--/.test(p)?c.setProperty(p,d):c[p]=d;a="object",s?n.value=function(e){var n,s=[];for(n in e)s.push(n.replace(t,i),":",e[n],";");return s.join("")}(r=c):r=o;break}default:r!=o&&(a="string",r=o,s?n.value=o||"":n.cssText=o||"")}}}}();const ue=(e,t)=>{let i,n=!0;const s=document.createAttributeNS(null,t);return t=>{i!==t&&(i=t,null==i?n||(e.removeAttributeNode(s),n=!0):(s.value=t,n&&(e.setAttributeNodeNS(s),n=!1)))}},me=({dataset:e})=>t=>{for(const i in t){const n=t[i];null==n?delete e[i]:e[i]=n}},he=(e,t)=>"dataset"===t?me(e):i=>{e[t]=i},fe=/^(?:form|list)$/i,ge=(e,t)=>e.ownerDocument.createTextNode(t);function ve(e){return this.type=e,function(e){var t=pe,i=de;return function(n){return t!==n&&(i=ce(e,t=n)),i.apply(null,arguments)}}(this)}function be(e){return e(this)}ve.prototype={attribute(e,t,i){const n="svg"===this.type;switch(t){case"class":if(n)return ue(e,t);t="className";case"props":return he(e,t);case"aria":return(e=>t=>{for(const i in t){const n="role"===i?i:`aria-${i}`,s=t[i];null==s?e.removeAttribute(n):e.setAttribute(n,s)}})(e);case"style":return le(e,i,n);case"ref":return(e=>t=>{"function"==typeof t?t(e):t.current=e})(e);case".dataset":return me(e);default:return"."===t.slice(0,1)?he(e,t.slice(1)):"?"===t.slice(0,1)?((e,t,i)=>n=>{i!==!!n&&((i=!!n)?e.setAttribute(t,""):e.removeAttribute(t))})(e,t.slice(1)):"on"===t.slice(0,2)?((e,t)=>{let i,n=t.slice(2);return!(t in e)&&t.toLowerCase()in e&&(n=n.toLowerCase()),t=>{const s=$(t)?t:[t,!1];i!==s[0]&&(i&&e.removeEventListener(n,i,s[1]),(i=s[0])&&e.addEventListener(n,i,s[1]))}})(e,t):!(t in e)||n||fe.test(t)?ue(e,t):((e,t)=>{let i;return n=>{i!==n&&(i=n,e[t]!==n&&(null==n?(e[t]="",e.removeAttribute(t)):e[t]=n))}})(e,t)}},any(e,t){const{type:i}=this;let n,s=!1;const a=r=>{switch(typeof r){case"string":case"number":case"boolean":s?n!==r&&(n=r,t[0].textContent=r):(s=!0,n=r,t=Q(e.parentNode,t,[ge(e,r)],H,e));break;case"function":a(r(e));break;case"object":case"undefined":if(null==r){s=!1,t=Q(e.parentNode,t,[],H,e);break}default:if(s=!1,n=r,$(r))if(0===r.length)t.length&&(t=Q(e.parentNode,t,[],H,e));else switch(typeof r[0]){case"string":case"number":case"boolean":a(String(r));break;case"function":a(r.map(be,e));break;case"object":$(r[0])&&(r=r.concat.apply([],r));default:t=Q(e.parentNode,t,r,H,e)}else"ELEMENT_NODE"in r?t=Q(e.parentNode,t,11===r.nodeType?W.call(r.childNodes):[r],H,e):"text"in r?a(String(r.text)):"any"in r?a(r.any):"html"in r?t=Q(e.parentNode,t,W.call(J([].concat(r.html).join(""),i).childNodes),H,e):"length"in r&&a(W.call(r))}};return a},text(e){let t;const i=n=>{if(t!==n){t=n;const s=typeof n;"object"===s&&n?"text"in n?i(String(n.text)):"any"in n?i(n.any):"html"in n?i([].concat(n.html).join("")):"length"in n&&i(W.call(n).join("")):"function"===s?i(n(e)):e.textContent=null==n?"":n}};return i}};const{create:_e,freeze:ye,keys:xe}=Object,we=ve.prototype,Se=G(new _),Re=e=>({html:ke("html",e),svg:ke("svg",e),render(t,i){const n="function"==typeof i?i():i,s=Se.get(t)||Se.set(t,Ce()),a=n instanceof Ee?Te(e,s,n):n;return a!==s.wire&&(s.wire=a,t.textContent="",t.appendChild(a.valueOf())),t}}),Ce=()=>({stack:[],entry:null,wire:null}),ke=(e,t)=>{const i=G(new _);return n.for=(e,s)=>{const a=i.get(e)||i.set(e,_e(null));return a[s]||(a[s]=(e=>function(){return Te(t,e,n.apply(null,arguments))})(Ce()))},n.node=function(){return Te(t,Ce(),n.apply(null,arguments)).valueOf()},n;function n(){return new Ee(e,De.apply(null,arguments))}},Te=(e,t,{type:i,template:n,values:s})=>{const{length:a}=s;Pe(e,t,s,a);let{entry:r}=t;if(r&&r.template===n&&r.type===i)r.tag(n,...s);else{const a=new e(i);t.entry=r={type:i,template:n,tag:a,wire:K(a(n,...s))}}return r.wire},Pe=(e,{stack:t},i,n)=>{for(let s=0;s<n;s++){const n=i[s];n instanceof Oe?i[s]=Te(e,t[s]||(t[s]=Ce()),n):$(n)?Pe(e,t[s]||(t[s]=Ce()),n,n.length):t[s]=null}n<t.length&&t.splice(n)};function Ee(e,t){this.type=e,this.template=t.shift(),this.values=t}ye(Ee);const Oe=Ee;function De(){let e=[],t=0,{length:i}=arguments;for(;t<i;)e.push(arguments[t++]);return e}Re(ve);var Ie="function"==typeof cancelAnimationFrame,je=Ie?cancelAnimationFrame:clearTimeout,Le=Ie?requestAnimationFrame:setTimeout;function Me(e){var t,i,n,s,a;return o(),function(e,o,p){return n=e,s=o,a=p,i||(i=Le(r)),--t<0&&c(!0),c};function r(){o(),n.apply(s,a||[])}function o(){t=e||1/0,i=Ie?0:null}function c(e){var t=!!i;return t&&(je(i),e&&r()),t}}
10
- /*! (c) Andrea Giammarchi - ISC */let Ae=null;const Ne=G(new WeakMap),Be=(e,t,i)=>{e.apply(t,i)},Fe={async:!1,always:!1},Ue=(e,t)=>"function"==typeof t?t(e):t,ze=(e,t,i,n)=>{const s=Ae.i++,{hook:a,args:r,stack:o,length:c}=Ae;s===c&&(Ae.length=o.push({}));const p=o[s];if(p.args=r,s===c){const s="function"==typeof i,{async:r,always:o}=(s?n:i)||n||Fe;p.$=s?i(t):Ue(void 0,t),p._=r?Ne.get(a)||Ne.set(a,Me()):Be,p.f=t=>{const i=e(p.$,t);(o||p.$!==i)&&(p.$=i,p._(a,null,p.args))}}return[p.$,p.f]},qe=new WeakMap;function $e({hook:e}){return e===this.hook}const Ve=new WeakMap,We=G(Ve),Ge=()=>{},He=e=>(t,i)=>{const n=Ae.i++,{hook:s,after:a,stack:r,length:o}=Ae;if(n<o){const s=r[n],{update:o,values:c,stop:p}=s;if(!i||i.some(Xe,c)){s.values=i,e&&p(e);const{clean:n}=s;n&&(s.clean=null,n());const r=()=>{s.clean=t()};e?o(r):a.push(r)}}else{const n=e?Me():Ge,o={clean:null,update:n,values:i,stop:Ge};Ae.length=r.push(o),(We.get(s)||We.set(s,[])).push(o);const c=()=>{o.clean=t()};e?o.stop=n(c):a.push(c)}},Ke=e=>{(Ve.get(e)||[]).forEach((e=>{const{clean:t,stop:i}=e;i(),t&&(e.clean=null,t())}))};Ve.has.bind(Ve);const Je=He(!0),Qe=He(!1),Ye=(e,t)=>{const i=Ae.i++,{stack:n,length:s}=Ae;return i===s?Ae.length=n.push({$:e(),_:t}):t&&!t.some(Xe,n[i]._)||(n[i]={$:e(),_:t}),n[i].$};function Xe(e,t){return e!==this[t]}let Ze=null;try{Ze=new{o(){}}.o}catch(Yt){}let et=e=>class extends e{};if(Ze){const{getPrototypeOf:e,setPrototypeOf:t}=Object,{construct:i}="object"==typeof Reflect?Reflect:{construct(e,i,n){const s=[null];for(let e=0;e<i.length;e++)s.push(i[e]);const a=e.bind.apply(e,s);return t(new a,n.prototype)}};et=function(n,s){function a(){return i(s?e(n):n,arguments,a)}return t(a.prototype,n.prototype),t(a,n)}}const tt={map:{},re:null},it=e=>new RegExp(`<(/)?(${e.join("|")})([^A-Za-z0-9:._-])`,"g");let nt=null;const st=(e,t)=>{const{map:i,re:n}=nt||t;return e.replace(n,((e,t,n,s)=>{const{tagName:a,is:r,element:o}=i[n];return o?t?`</${r}>`:`<${r}${s}`:t?`</${a}>`:`<${a} is="${r}"${s}`}))},at=({tagName:e,is:t,element:i})=>i?t:`${e}[is="${t}"]`,rt=()=>nt,ot=e=>{nt=e},ct={useCallback:(e,t)=>Ye((()=>e),t),useContext:e=>{const{hook:t,args:i}=Ae,n=qe.get(e),s={hook:t,args:i};return n.some($e,s)||n.push(s),e.value},useEffect:Je,useLayoutEffect:Qe,useMemo:Ye,useReducer:ze,useRef:e=>{const t=Ae.i++,{stack:i,length:n}=Ae;return t===n&&(Ae.length=i.push({current:e})),i[t]},useState:(e,t)=>ze(Ue,e,void 0,t)},{render:pt,html:dt,svg:lt}=(e=>{const t=_e(we);return xe(e).forEach((i=>{t[i]=e[i](t[i]||("convert"===i?D:String))})),i.prototype=t,Re(i);function i(){return ve.apply(this,arguments)}})({transform:()=>e=>st(e,tt)}),{defineProperties:ut}=Object,mt=new _,ht=new _,ft=new _,gt=new C,vt="attributeChangedCallback",bt="connectedCallback",_t=`dis${bt}`,yt=(e,t,i)=>{if(i in e){const n=e[i];t[i]={configurable:true,value(){return It.call(this),n.apply(this,arguments)}}}else t[i]={configurable:true,value:It}},xt=e=>{const{prototype:t}=e,i=[],n={html:{configurable:true,get:Et},svg:{configurable:true,get:Ot}};if(n["_🔥"]={value:{events:i,info:null}},"handleEvent"in t||(n.handleEvent={configurable:true,value:Dt}),"render"in t&&t.render.length){const{oninit:e}=t;ut(t,{oninit:{configurable:true,value(){const t=(e=>{const t=[];return function i(){const n=Ae,s=[];Ae={hook:i,args:arguments,stack:t,i:0,length:t.length,after:s};try{return e.apply(null,arguments)}finally{Ae=n;for(let e=0,{length:t}=s;e<t;e++)s[e]()}}})(this.render.bind(this,ct));ut(this,{render:{configurable:true,value:t}}),this.addEventListener("disconnected",Ke.bind(null,t),!1),e&&e.apply(this,arguments)}}})}"oninit"in t&&(i.push("init"),yt(t,n,"render")),yt(t,n,vt),yt(t,n,bt),yt(t,n,_t),[[vt,"onattributechanged",jt],[bt,"onconnected",Lt],[_t,"ondisconnected",At],[bt,"render",Mt]].forEach((([e,s,a])=>{if(!(e in t)&&s in t)if("render"!==s&&i.push(s.slice(2)),e in n){const t=n[e].value;n[e]={configurable:true,value(){return t.apply(this,arguments),a.apply(this,arguments)}}}else n[e]={configurable:true,value:a}}));const s=e.booleanAttributes||[];s.forEach((e=>{e in t||(n[e]={configurable:true,get(){return this.hasAttribute(e)},set(t){t&&"false"!==t?this.setAttribute(e,t):this.removeAttribute(e)}})}));const a=e.observedAttributes||[];a.forEach((e=>{e in t||(n[e]={configurable:true,get(){return this.getAttribute(e)},set(t){null==t?this.removeAttribute(e):this.setAttribute(e,t)}})}));(e.mappedAttributes||[]).forEach((e=>{const s=new _,a="on"+e in t;a&&i.push(e),n[e]={configurable:true,get(){return s.get(this)},set(t){if(s.set(this,t),a){const i=wt(e);if(i.detail=t,gt.has(this))this.dispatchEvent(i);else{const e=ft.get(this);e?e.push(i):ft.set(this,[i])}}}}})),ut(t,n);const r=s.concat(a);return r.length?ut(e,{observedAttributes:{configurable:true,get:()=>r}}):e},wt=e=>new x(e),St=(...e)=>new Oe("html",e);St.for=dt.for;const Rt=(...e)=>new Oe("svg",e);Rt.for=lt.for;const Ct=(e,t,i)=>{const n=kt(e,t,new _);return i.set(e,n),n},kt=(e,t,i)=>(n,...s)=>{const a=i.get(n)||((e,t,{info:i})=>{const n=i?st(t.join("_🔥"),i).split("_🔥"):t;return e.set(t,n),n})(i,n,e["_🔥"]);return pt(e,(()=>t(a,...s)))};function Tt(e){this.addEventListener(e,this)}function Pt(e){this.dispatchEvent(e)}function Et(){return mt.get(this)||Ct(this,St,mt)}function Ot(){return ht.get(this)||Ct(this,Rt,ht)}function Dt(e){this[`on${e.type}`](e)}function It(){if(!gt.has(this)){gt.add(this),this["_🔥"].events.forEach(Tt,this),this.dispatchEvent(wt("init"));const e=ft.get(this);e&&(ft.delete(this),e.forEach(Pt,this))}}function jt(e,t,i){const n=wt("attributechanged");n.attributeName=e,n.oldValue=t,n.newValue=i,this.dispatchEvent(n)}function Lt(){this.dispatchEvent(wt("connected"))}function Mt(){this.render()}function At(){this.dispatchEvent(wt("disconnected"))}const{create:Nt,defineProperty:Bt,defineProperties:Ft,getOwnPropertyNames:Ut,getOwnPropertySymbols:zt,getOwnPropertyDescriptor:qt,keys:$t}=Object,Vt={element:HTMLElement},Wt=new _;new _;const Gt=new _;new _;const Ht=e=>{const t=Nt(null),i=Nt(null),n={prototype:i,statics:t};return Ut(e).concat(zt(e)).forEach((n=>{const s=qt(e,n);switch(s.enumerable=!1,n){case"extends":n="tagName";case"contains":case"includes":case"name":case"booleanAttributes":case"mappedAttributes":case"observedAttributes":case"style":case"tagName":t[n]=s;break;default:i[n]=s}})),n},Kt=(e,t,i)=>{if(!/^([A-Z][A-Za-z0-9_]*)(<([A-Za-z0-9:._-]+)>|:([A-Za-z0-9:._-]+))?$/.test(e))throw"Invalid name";const{$1:n,$3:s,$4:a}=RegExp;let r=s||a||t.tagName||t.extends||"element";const o="fragment"===r;if(o)r="element";else if(!/^[A-Za-z0-9:._-]+$/.test(r))throw"Invalid tag";let c="",p="";r.indexOf("-")<0?(c=n.replace(/(([A-Z0-9])([A-Z0-9][a-z]))|(([a-z])([A-Z]))/g,"$2$5-$3$6").toLowerCase()+i,c.indexOf("-")<0&&(p="-heresy")):(c=r+i,r="element");const d=c+p;if(customElements.get(d))throw`Duplicated ${d} definition`;const l=et("object"==typeof t?Gt.get(t)||((e,t)=>{const{statics:i,prototype:n}=Ht(e),s=et(Vt[t]||(Vt[t]=document.createElement(t).constructor),!1);return Ft(s.prototype,n),Ft(s,i),Gt.set(e,xt(s)),s})(t,r):Wt.get(t)||(e=>{const t=et(e,!1);return Wt.set(e,xt(t)),t})(t),!0),u="element"===r;if(Bt(l,"new",{value:u?()=>document.createElement(d):()=>document.createElement(r,{is:d})}),Bt(l.prototype,"is",{value:d}),""===i){const e=(e=>{const{length:t}=e;let i=0,n=0;for(;n<t;)i=(i<<5)-i+e.charCodeAt(n++),i&=i;return i.toString(36)})(c.toUpperCase());tt.map[n]=Jt(l,r,d,{id:e,i:0}),tt.re=it($t(tt.map))}if(o){const{render:e}=l.prototype;Bt(l.prototype,"render",{configurable:!0,value(){if(e&&e.apply(this,arguments),this.parentNode){const{firstChild:e}=this;let t=null;if(e){const i=document.createRange();i.setStartBefore(e),i.setEndAfter(this.lastChild),t=i.extractContents(),this.parentNode.replaceChild(t,this)}}}})}const m=[d,l];return u||m.push({extends:r}),customElements.define(...m),{Class:l,is:d,name:n,tagName:r}},Jt=(e,t,i,n)=>{const{prototype:s}=e,a=((e,t)=>({tagName:e,is:t,element:"element"===e}))(t,i),r=[at(a)],o=e.includes||e.contains;if(o){const e={};$t(o).forEach((t=>{const i=`-${n.id}-${n.i++}`,{Class:s,is:a,name:c,tagName:p}=Kt(t,o[t],i);r.push(at(e[c]=Jt(s,p,a,n)))}));const t=it($t(e)),{events:i}=s["_🔥"],a={events:i,info:{map:e,re:t}};if(Bt(s,"_🔥",{value:a}),"render"in s){const{render:e}=s,{info:t}=a;Bt(s,"render",{configurable:!0,value(){const i=rt();ot(t);const n=e.apply(this,arguments);return ot(i),n}})}}return"style"in e&&(e=>{if((e||"").length){const t=document.createElement("style");t.type="text/css",t.styleSheet?t.styleSheet.cssText=e:t.appendChild(document.createTextNode(e));const i=document.head||document.querySelector("head");i.insertBefore(t,i.lastChild)}})(e.style(...r)),a},Qt=["audio","background","cameraaccess","chat","people","embed","emptyRoomInvitation","help","leaveButton","precallReview","screenshare","video","floatSelf","recording","logo","locking","participantCount","settingsButton","pipButton","moreButton","personality","subgridLabels","lowData","breakout"];var Yt,Xt;function Zt(e,t,i,n){return new(i||(i=Promise))((function(s,a){function r(e){try{c(n.next(e))}catch(e){a(e)}}function o(e){try{c(n.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(r,o)}c((n=n.apply(e,t||[])).next())}))}Yt="WherebyEmbed",Xt={oninit(){this.iframe=((e,t)=>e?e[t]||(e[t]={current:null}):{current:null})()},onconnected(){window.addEventListener("message",this.onmessage)},ondisconnected(){window.removeEventListener("message",this.onmessage)},observedAttributes:["displayName","minimal","room","subdomain","lang","metadata","groups","virtualBackgroundUrl","avatarUrl",...Qt].map((e=>e.toLowerCase())),onattributechanged({attributeName:e,oldValue:t}){["room","subdomain"].includes(e)&&null==t||this.render()},style:e=>`\n ${e} {\n display: block;\n }\n ${e} iframe {\n border: none;\n height: 100%;\n width: 100%;\n }\n `,_postCommand(e,t=[]){this.iframe.current&&this.iframe.current.contentWindow.postMessage({command:e,args:t},this.url.origin)},startRecording(){this._postCommand("start_recording")},stopRecording(){this._postCommand("stop_recording")},toggleCamera(e){this._postCommand("toggle_camera",[e])},toggleMicrophone(e){this._postCommand("toggle_microphone",[e])},toggleScreenshare(e){this._postCommand("toggle_screenshare",[e])},onmessage({origin:e,data:t}){if(e!==this.url.origin)return;const{type:i,payload:n}=t;this.dispatchEvent(new CustomEvent(i,{detail:n}))},render(){const{avatarurl:e,displayname:t,lang:i,metadata:n,minimal:s,room:a,groups:r,virtualbackgroundurl:o}=this;if(!a)return this.html`Whereby: Missing room attribute.`;const c=/https:\/\/([^.]+)(\.whereby.com|-ip-\d+-\d+-\d+-\d+.hereby.dev:4443)\/.+/.exec(a),p=c&&c[1]||this.subdomain;if(!p)return this.html`Whereby: Missing subdomain attr.`;if(!c)return this.html`could not parse URL.`;const d=c[2]||".whereby.com";this.url=new URL(a,`https://${p}${d}`);const l=new URL(a);return l.searchParams.get("roomKey")&&this.url.searchParams.append("roomKey",l.searchParams.get("roomKey")),Object.entries(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({jsApi:!0,we:"2.0.0-alpha12",iframeSource:p},t&&{displayName:t}),i&&{lang:i}),n&&{metadata:n}),r&&{groups:r}),o&&{virtualBackgroundUrl:o}),e&&{avatarUrl:e}),null!=s&&{embed:s}),Qt.reduce(((e,t)=>null!=this[t.toLowerCase()]?Object.assign(Object.assign({},e),{[t]:this[t.toLowerCase()]}):e),{}))).forEach((([e,t])=>{this.url.searchParams.has(e)||"string"!=typeof t||this.url.searchParams.set(e,t)})),this.html`
10
+ /*! (c) Andrea Giammarchi - ISC */let Ae=null;const Ne=G(new WeakMap),Be=(e,t,i)=>{e.apply(t,i)},Fe={async:!1,always:!1},Ue=(e,t)=>"function"==typeof t?t(e):t,ze=(e,t,i,n)=>{const s=Ae.i++,{hook:a,args:r,stack:o,length:c}=Ae;s===c&&(Ae.length=o.push({}));const p=o[s];if(p.args=r,s===c){const s="function"==typeof i,{async:r,always:o}=(s?n:i)||n||Fe;p.$=s?i(t):Ue(void 0,t),p._=r?Ne.get(a)||Ne.set(a,Me()):Be,p.f=t=>{const i=e(p.$,t);(o||p.$!==i)&&(p.$=i,p._(a,null,p.args))}}return[p.$,p.f]},qe=new WeakMap;function $e({hook:e}){return e===this.hook}const Ve=new WeakMap,We=G(Ve),Ge=()=>{},He=e=>(t,i)=>{const n=Ae.i++,{hook:s,after:a,stack:r,length:o}=Ae;if(n<o){const s=r[n],{update:o,values:c,stop:p}=s;if(!i||i.some(Xe,c)){s.values=i,e&&p(e);const{clean:n}=s;n&&(s.clean=null,n());const r=()=>{s.clean=t()};e?o(r):a.push(r)}}else{const n=e?Me():Ge,o={clean:null,update:n,values:i,stop:Ge};Ae.length=r.push(o),(We.get(s)||We.set(s,[])).push(o);const c=()=>{o.clean=t()};e?o.stop=n(c):a.push(c)}},Ke=e=>{(Ve.get(e)||[]).forEach((e=>{const{clean:t,stop:i}=e;i(),t&&(e.clean=null,t())}))};Ve.has.bind(Ve);const Je=He(!0),Qe=He(!1),Ye=(e,t)=>{const i=Ae.i++,{stack:n,length:s}=Ae;return i===s?Ae.length=n.push({$:e(),_:t}):t&&!t.some(Xe,n[i]._)||(n[i]={$:e(),_:t}),n[i].$};function Xe(e,t){return e!==this[t]}let Ze=null;try{Ze=new{o(){}}.o}catch(Yt){}let et=e=>class extends e{};if(Ze){const{getPrototypeOf:e,setPrototypeOf:t}=Object,{construct:i}="object"==typeof Reflect?Reflect:{construct(e,i,n){const s=[null];for(let e=0;e<i.length;e++)s.push(i[e]);const a=e.bind.apply(e,s);return t(new a,n.prototype)}};et=function(n,s){function a(){return i(s?e(n):n,arguments,a)}return t(a.prototype,n.prototype),t(a,n)}}const tt={map:{},re:null},it=e=>new RegExp(`<(/)?(${e.join("|")})([^A-Za-z0-9:._-])`,"g");let nt=null;const st=(e,t)=>{const{map:i,re:n}=nt||t;return e.replace(n,((e,t,n,s)=>{const{tagName:a,is:r,element:o}=i[n];return o?t?`</${r}>`:`<${r}${s}`:t?`</${a}>`:`<${a} is="${r}"${s}`}))},at=({tagName:e,is:t,element:i})=>i?t:`${e}[is="${t}"]`,rt=()=>nt,ot=e=>{nt=e},ct={useCallback:(e,t)=>Ye((()=>e),t),useContext:e=>{const{hook:t,args:i}=Ae,n=qe.get(e),s={hook:t,args:i};return n.some($e,s)||n.push(s),e.value},useEffect:Je,useLayoutEffect:Qe,useMemo:Ye,useReducer:ze,useRef:e=>{const t=Ae.i++,{stack:i,length:n}=Ae;return t===n&&(Ae.length=i.push({current:e})),i[t]},useState:(e,t)=>ze(Ue,e,void 0,t)},{render:pt,html:dt,svg:lt}=(e=>{const t=_e(we);return xe(e).forEach((i=>{t[i]=e[i](t[i]||("convert"===i?D:String))})),i.prototype=t,Re(i);function i(){return ve.apply(this,arguments)}})({transform:()=>e=>st(e,tt)}),{defineProperties:ut}=Object,mt=new _,ht=new _,ft=new _,gt=new C,vt="attributeChangedCallback",bt="connectedCallback",_t=`dis${bt}`,yt=(e,t,i)=>{if(i in e){const n=e[i];t[i]={configurable:true,value(){return It.call(this),n.apply(this,arguments)}}}else t[i]={configurable:true,value:It}},xt=e=>{const{prototype:t}=e,i=[],n={html:{configurable:true,get:Et},svg:{configurable:true,get:Ot}};if(n["_🔥"]={value:{events:i,info:null}},"handleEvent"in t||(n.handleEvent={configurable:true,value:Dt}),"render"in t&&t.render.length){const{oninit:e}=t;ut(t,{oninit:{configurable:true,value(){const t=(e=>{const t=[];return function i(){const n=Ae,s=[];Ae={hook:i,args:arguments,stack:t,i:0,length:t.length,after:s};try{return e.apply(null,arguments)}finally{Ae=n;for(let e=0,{length:t}=s;e<t;e++)s[e]()}}})(this.render.bind(this,ct));ut(this,{render:{configurable:true,value:t}}),this.addEventListener("disconnected",Ke.bind(null,t),!1),e&&e.apply(this,arguments)}}})}"oninit"in t&&(i.push("init"),yt(t,n,"render")),yt(t,n,vt),yt(t,n,bt),yt(t,n,_t),[[vt,"onattributechanged",jt],[bt,"onconnected",Lt],[_t,"ondisconnected",At],[bt,"render",Mt]].forEach((([e,s,a])=>{if(!(e in t)&&s in t)if("render"!==s&&i.push(s.slice(2)),e in n){const t=n[e].value;n[e]={configurable:true,value(){return t.apply(this,arguments),a.apply(this,arguments)}}}else n[e]={configurable:true,value:a}}));const s=e.booleanAttributes||[];s.forEach((e=>{e in t||(n[e]={configurable:true,get(){return this.hasAttribute(e)},set(t){t&&"false"!==t?this.setAttribute(e,t):this.removeAttribute(e)}})}));const a=e.observedAttributes||[];a.forEach((e=>{e in t||(n[e]={configurable:true,get(){return this.getAttribute(e)},set(t){null==t?this.removeAttribute(e):this.setAttribute(e,t)}})}));(e.mappedAttributes||[]).forEach((e=>{const s=new _,a="on"+e in t;a&&i.push(e),n[e]={configurable:true,get(){return s.get(this)},set(t){if(s.set(this,t),a){const i=wt(e);if(i.detail=t,gt.has(this))this.dispatchEvent(i);else{const e=ft.get(this);e?e.push(i):ft.set(this,[i])}}}}})),ut(t,n);const r=s.concat(a);return r.length?ut(e,{observedAttributes:{configurable:true,get:()=>r}}):e},wt=e=>new x(e),St=(...e)=>new Oe("html",e);St.for=dt.for;const Rt=(...e)=>new Oe("svg",e);Rt.for=lt.for;const Ct=(e,t,i)=>{const n=kt(e,t,new _);return i.set(e,n),n},kt=(e,t,i)=>(n,...s)=>{const a=i.get(n)||((e,t,{info:i})=>{const n=i?st(t.join("_🔥"),i).split("_🔥"):t;return e.set(t,n),n})(i,n,e["_🔥"]);return pt(e,(()=>t(a,...s)))};function Tt(e){this.addEventListener(e,this)}function Pt(e){this.dispatchEvent(e)}function Et(){return mt.get(this)||Ct(this,St,mt)}function Ot(){return ht.get(this)||Ct(this,Rt,ht)}function Dt(e){this[`on${e.type}`](e)}function It(){if(!gt.has(this)){gt.add(this),this["_🔥"].events.forEach(Tt,this),this.dispatchEvent(wt("init"));const e=ft.get(this);e&&(ft.delete(this),e.forEach(Pt,this))}}function jt(e,t,i){const n=wt("attributechanged");n.attributeName=e,n.oldValue=t,n.newValue=i,this.dispatchEvent(n)}function Lt(){this.dispatchEvent(wt("connected"))}function Mt(){this.render()}function At(){this.dispatchEvent(wt("disconnected"))}const{create:Nt,defineProperty:Bt,defineProperties:Ft,getOwnPropertyNames:Ut,getOwnPropertySymbols:zt,getOwnPropertyDescriptor:qt,keys:$t}=Object,Vt={element:HTMLElement},Wt=new _;new _;const Gt=new _;new _;const Ht=e=>{const t=Nt(null),i=Nt(null),n={prototype:i,statics:t};return Ut(e).concat(zt(e)).forEach((n=>{const s=qt(e,n);switch(s.enumerable=!1,n){case"extends":n="tagName";case"contains":case"includes":case"name":case"booleanAttributes":case"mappedAttributes":case"observedAttributes":case"style":case"tagName":t[n]=s;break;default:i[n]=s}})),n},Kt=(e,t,i)=>{if(!/^([A-Z][A-Za-z0-9_]*)(<([A-Za-z0-9:._-]+)>|:([A-Za-z0-9:._-]+))?$/.test(e))throw"Invalid name";const{$1:n,$3:s,$4:a}=RegExp;let r=s||a||t.tagName||t.extends||"element";const o="fragment"===r;if(o)r="element";else if(!/^[A-Za-z0-9:._-]+$/.test(r))throw"Invalid tag";let c="",p="";r.indexOf("-")<0?(c=n.replace(/(([A-Z0-9])([A-Z0-9][a-z]))|(([a-z])([A-Z]))/g,"$2$5-$3$6").toLowerCase()+i,c.indexOf("-")<0&&(p="-heresy")):(c=r+i,r="element");const d=c+p;if(customElements.get(d))throw`Duplicated ${d} definition`;const l=et("object"==typeof t?Gt.get(t)||((e,t)=>{const{statics:i,prototype:n}=Ht(e),s=et(Vt[t]||(Vt[t]=document.createElement(t).constructor),!1);return Ft(s.prototype,n),Ft(s,i),Gt.set(e,xt(s)),s})(t,r):Wt.get(t)||(e=>{const t=et(e,!1);return Wt.set(e,xt(t)),t})(t),!0),u="element"===r;if(Bt(l,"new",{value:u?()=>document.createElement(d):()=>document.createElement(r,{is:d})}),Bt(l.prototype,"is",{value:d}),""===i){const e=(e=>{const{length:t}=e;let i=0,n=0;for(;n<t;)i=(i<<5)-i+e.charCodeAt(n++),i&=i;return i.toString(36)})(c.toUpperCase());tt.map[n]=Jt(l,r,d,{id:e,i:0}),tt.re=it($t(tt.map))}if(o){const{render:e}=l.prototype;Bt(l.prototype,"render",{configurable:!0,value(){if(e&&e.apply(this,arguments),this.parentNode){const{firstChild:e}=this;let t=null;if(e){const i=document.createRange();i.setStartBefore(e),i.setEndAfter(this.lastChild),t=i.extractContents(),this.parentNode.replaceChild(t,this)}}}})}const m=[d,l];return u||m.push({extends:r}),customElements.define(...m),{Class:l,is:d,name:n,tagName:r}},Jt=(e,t,i,n)=>{const{prototype:s}=e,a=((e,t)=>({tagName:e,is:t,element:"element"===e}))(t,i),r=[at(a)],o=e.includes||e.contains;if(o){const e={};$t(o).forEach((t=>{const i=`-${n.id}-${n.i++}`,{Class:s,is:a,name:c,tagName:p}=Kt(t,o[t],i);r.push(at(e[c]=Jt(s,p,a,n)))}));const t=it($t(e)),{events:i}=s["_🔥"],a={events:i,info:{map:e,re:t}};if(Bt(s,"_🔥",{value:a}),"render"in s){const{render:e}=s,{info:t}=a;Bt(s,"render",{configurable:!0,value(){const i=rt();ot(t);const n=e.apply(this,arguments);return ot(i),n}})}}return"style"in e&&(e=>{if((e||"").length){const t=document.createElement("style");t.type="text/css",t.styleSheet?t.styleSheet.cssText=e:t.appendChild(document.createTextNode(e));const i=document.head||document.querySelector("head");i.insertBefore(t,i.lastChild)}})(e.style(...r)),a},Qt=["audio","background","cameraaccess","chat","people","embed","emptyRoomInvitation","help","leaveButton","precallReview","screenshare","video","floatSelf","recording","logo","locking","participantCount","settingsButton","pipButton","moreButton","personality","subgridLabels","lowData","breakout"];var Yt,Xt;function Zt(e,t,i,n){return new(i||(i=Promise))((function(s,a){function r(e){try{c(n.next(e))}catch(e){a(e)}}function o(e){try{c(n.throw(e))}catch(e){a(e)}}function c(e){var t;e.done?s(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(r,o)}c((n=n.apply(e,t||[])).next())}))}Yt="WherebyEmbed",Xt={oninit(){this.iframe=((e,t)=>e?e[t]||(e[t]={current:null}):{current:null})()},onconnected(){window.addEventListener("message",this.onmessage)},ondisconnected(){window.removeEventListener("message",this.onmessage)},observedAttributes:["displayName","minimal","room","subdomain","lang","metadata","groups","virtualBackgroundUrl","avatarUrl",...Qt].map((e=>e.toLowerCase())),onattributechanged({attributeName:e,oldValue:t}){["room","subdomain"].includes(e)&&null==t||this.render()},style:e=>`\n ${e} {\n display: block;\n }\n ${e} iframe {\n border: none;\n height: 100%;\n width: 100%;\n }\n `,_postCommand(e,t=[]){this.iframe.current&&this.iframe.current.contentWindow.postMessage({command:e,args:t},this.url.origin)},startRecording(){this._postCommand("start_recording")},stopRecording(){this._postCommand("stop_recording")},toggleCamera(e){this._postCommand("toggle_camera",[e])},toggleMicrophone(e){this._postCommand("toggle_microphone",[e])},toggleScreenshare(e){this._postCommand("toggle_screenshare",[e])},onmessage({origin:e,data:t}){if(e!==this.url.origin)return;const{type:i,payload:n}=t;this.dispatchEvent(new CustomEvent(i,{detail:n}))},render(){const{avatarurl:e,displayname:t,lang:i,metadata:n,minimal:s,room:a,groups:r,virtualbackgroundurl:o}=this;if(!a)return this.html`Whereby: Missing room attribute.`;const c=/https:\/\/([^.]+)(\.whereby.com|-ip-\d+-\d+-\d+-\d+.hereby.dev:4443)\/.+/.exec(a),p=c&&c[1]||this.subdomain;if(!p)return this.html`Whereby: Missing subdomain attr.`;if(!c)return this.html`could not parse URL.`;const d=c[2]||".whereby.com";this.url=new URL(a,`https://${p}${d}`);const l=new URL(a);return l.searchParams.get("roomKey")&&this.url.searchParams.append("roomKey",l.searchParams.get("roomKey")),Object.entries(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({jsApi:!0,we:"2.0.0-alpha14",iframeSource:p},t&&{displayName:t}),i&&{lang:i}),n&&{metadata:n}),r&&{groups:r}),o&&{virtualBackgroundUrl:o}),e&&{avatarUrl:e}),null!=s&&{embed:s}),Qt.reduce(((e,t)=>null!=this[t.toLowerCase()]?Object.assign(Object.assign({},e),{[t]:this[t.toLowerCase()]}):e),{}))).forEach((([e,t])=>{this.url.searchParams.has(e)||"string"!=typeof t||this.url.searchParams.set(e,t)})),this.html`
11
11
  <iframe
12
12
  ref=${this.iframe}
13
13
  src=${this.url}
@@ -25,7 +25,7 @@ var J=function(e){var t="fragment",i="template",n="content"in a(i)?function(e){v
25
25
  * @contributor David Ellis <d.f.ellis@ieee.org>
26
26
  * @license MIT
27
27
  */
28
- var vs=e,bs=t,_s=i.spawn,ys=xs;function xs(e){e=e||{};var t,i,a=this,r=n,o=s,c={},p=!1,d={"User-Agent":"node-XMLHttpRequest",Accept:"*/*"},l=Object.assign({},d),u=["accept-charset","accept-encoding","access-control-request-headers","access-control-request-method","connection","content-length","content-transfer-encoding","cookie","cookie2","date","expect","host","keep-alive","origin","referer","te","trailer","transfer-encoding","upgrade","via"],m=["TRACE","TRACK","CONNECT"],h=!1,f=!1,g=!1,v={};this.UNSENT=0,this.OPENED=1,this.HEADERS_RECEIVED=2,this.LOADING=3,this.DONE=4,this.readyState=this.UNSENT,this.onreadystatechange=null,this.responseText="",this.responseXML="",this.status=null,this.statusText=null;this.open=function(e,t,i,n,s){if(this.abort(),f=!1,g=!1,!function(e){return e&&-1===m.indexOf(e)}(e))throw new Error("SecurityError: Request method not allowed");c={method:e,url:t.toString(),async:"boolean"!=typeof i||i,user:n||null,password:s||null},b(this.OPENED)},this.setDisableHeaderCheck=function(e){p=e},this.setRequestHeader=function(e,t){if(this.readyState!=this.OPENED)throw new Error("INVALID_STATE_ERR: setRequestHeader can only be called when state is OPEN");if(!function(e){return p||e&&-1===u.indexOf(e.toLowerCase())}(e))return console.warn('Refused to set unsafe header "'+e+'"'),!1;if(h)throw new Error("INVALID_STATE_ERR: send flag is true");return l[e]=t,!0},this.getResponseHeader=function(e){return"string"==typeof e&&this.readyState>this.OPENED&&i.headers[e.toLowerCase()]&&!f?i.headers[e.toLowerCase()]:null},this.getAllResponseHeaders=function(){if(this.readyState<this.HEADERS_RECEIVED||f)return"";var e="";for(var t in i.headers)"set-cookie"!==t&&"set-cookie2"!==t&&(e+=t+": "+i.headers[t]+"\r\n");return e.substr(0,e.length-2)},this.getRequestHeader=function(e){return"string"==typeof e&&l[e]?l[e]:""},this.send=function(n){if(this.readyState!=this.OPENED)throw new Error("INVALID_STATE_ERR: connection must be opened before send() is called");if(h)throw new Error("INVALID_STATE_ERR: send has already been called");var s,p=!1,d=!1,u=bs.parse(c.url);switch(u.protocol){case"https:":p=!0;case"http:":s=u.hostname;break;case"file:":d=!0;break;case void 0:case"":s="localhost";break;default:throw new Error("Protocol not supported.")}if(d){if("GET"!==c.method)throw new Error("XMLHttpRequest: Only GET method is supported");if(c.async)vs.readFile(unescape(u.pathname),"utf8",(function(e,t){e?a.handleError(e,e.errno||-1):(a.status=200,a.responseText=t,b(a.DONE))}));else try{this.responseText=vs.readFileSync(unescape(u.pathname),"utf8"),this.status=200,b(a.DONE)}catch(e){this.handleError(e,e.errno||-1)}}else{var m=u.port||(p?443:80),g=u.pathname+(u.search?u.search:"");if(l.Host=s,p&&443===m||80===m||(l.Host+=":"+u.port),c.user){void 0===c.password&&(c.password="");var v=new Buffer(c.user+":"+c.password);l.Authorization="Basic "+v.toString("base64")}"GET"===c.method||"HEAD"===c.method?n=null:n?(l["Content-Length"]=Buffer.isBuffer(n)?n.length:Buffer.byteLength(n),l["Content-Type"]||(l["Content-Type"]="text/plain;charset=UTF-8")):"POST"===c.method&&(l["Content-Length"]=0);var _=e.agent||!1,y={host:s,port:m,path:g,method:c.method,headers:l,agent:_};if(p&&(y.pfx=e.pfx,y.key=e.key,y.passphrase=e.passphrase,y.cert=e.cert,y.ca=e.ca,y.ciphers=e.ciphers,y.rejectUnauthorized=!1!==e.rejectUnauthorized),f=!1,c.async){var x=p?o.request:r.request;h=!0,a.dispatchEvent("readystatechange");var w=function(n){if(302===(i=n).statusCode||303===i.statusCode||307===i.statusCode){c.url=i.headers.location;var r=bs.parse(c.url);s=r.hostname;var o={hostname:r.hostname,port:r.port,path:r.path,method:303===i.statusCode?"GET":c.method,headers:l};return p&&(o.pfx=e.pfx,o.key=e.key,o.passphrase=e.passphrase,o.cert=e.cert,o.ca=e.ca,o.ciphers=e.ciphers,o.rejectUnauthorized=!1!==e.rejectUnauthorized),void(t=x(o,w).on("error",S)).end()}i&&i.setEncoding&&i.setEncoding("utf8"),b(a.HEADERS_RECEIVED),a.status=i.statusCode,i.on("data",(function(e){e&&(a.responseText+=e),h&&b(a.LOADING)})),i.on("end",(function(){h&&(h=!1,b(a.DONE))})),i.on("error",(function(e){a.handleError(e)}))},S=function(e){a.handleError(e)};t=x(y,w).on("error",S),e.autoUnref&&t.on("socket",(e=>{e.unref()})),n&&t.write(n),t.end(),a.dispatchEvent("loadstart")}else{var R=".node-xmlhttprequest-content-"+process.pid,C=".node-xmlhttprequest-sync-"+process.pid;vs.writeFileSync(C,"","utf8");for(var k="var http = require('http'), https = require('https'), fs = require('fs');var doRequest = http"+(p?"s":"")+".request;var options = "+JSON.stringify(y)+";var responseText = '';var req = doRequest(options, function(response) {response.setEncoding('utf8');response.on('data', function(chunk) { responseText += chunk;});response.on('end', function() {fs.writeFileSync('"+R+"', 'NODE-XMLHTTPREQUEST-STATUS:' + response.statusCode + ',' + responseText, 'utf8');fs.unlinkSync('"+C+"');});response.on('error', function(error) {fs.writeFileSync('"+R+"', 'NODE-XMLHTTPREQUEST-ERROR:' + JSON.stringify(error), 'utf8');fs.unlinkSync('"+C+"');});}).on('error', function(error) {fs.writeFileSync('"+R+"', 'NODE-XMLHTTPREQUEST-ERROR:' + JSON.stringify(error), 'utf8');fs.unlinkSync('"+C+"');});"+(n?"req.write('"+JSON.stringify(n).slice(1,-1).replace(/'/g,"\\'")+"');":"")+"req.end();",T=_s(process.argv[0],["-e",k]);vs.existsSync(C););if(a.responseText=vs.readFileSync(R,"utf8"),T.stdin.end(),vs.unlinkSync(R),a.responseText.match(/^NODE-XMLHTTPREQUEST-ERROR:/)){var P=a.responseText.replace(/^NODE-XMLHTTPREQUEST-ERROR:/,"");a.handleError(P,503)}else a.status=a.responseText.replace(/^NODE-XMLHTTPREQUEST-STATUS:([0-9]*),.*/,"$1"),a.responseText=a.responseText.replace(/^NODE-XMLHTTPREQUEST-STATUS:[0-9]*,(.*)/,"$1"),b(a.DONE)}}},this.handleError=function(e,t){this.status=t||0,this.statusText=e,this.responseText=e.stack,f=!0,b(this.DONE)},this.abort=function(){t&&(t.abort(),t=null),l=Object.assign({},d),this.responseText="",this.responseXML="",f=g=!0,this.readyState===this.UNSENT||this.readyState===this.OPENED&&!h||this.readyState===this.DONE||(h=!1,b(this.DONE)),this.readyState=this.UNSENT},this.addEventListener=function(e,t){e in v||(v[e]=[]),v[e].push(t)},this.removeEventListener=function(e,t){e in v&&(v[e]=v[e].filter((function(e){return e!==t})))},this.dispatchEvent=function(e){if("function"==typeof a["on"+e]&&(this.readyState===this.DONE?setImmediate((function(){a["on"+e]()})):a["on"+e]()),e in v)for(let t=0,i=v[e].length;t<i;t++)this.readyState===this.DONE?setImmediate((function(){v[e][t].call(a)})):v[e][t].call(a)};var b=function(e){if(!(a.readyState===e||a.readyState===a.UNSENT&&g)&&(a.readyState=e,(c.async||a.readyState<a.OPENED||a.readyState===a.DONE)&&a.dispatchEvent("readystatechange"),a.readyState===a.DONE)){let e;e=g?"abort":f?"error":"load",a.dispatchEvent(e),a.dispatchEvent("loadend")}}}xs.XMLHttpRequest=xs;const ws=ys||v({__proto__:null,default:ys},[ys]);function Ss(){}const Rs=null!=new ws({xdomain:!1}).responseType;class Cs extends ts{constructor(e,t){super(),rs(this,t),this.opts=t,this.method=t.method||"GET",this.uri=e,this.async=!1!==t.async,this.data=void 0!==t.data?t.data:null,this.create()}create(){const e=ns(this.opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");e.xdomain=!!this.opts.xd,e.xscheme=!!this.opts.xs;const t=this.xhr=new ws(e);try{t.open(this.method,this.uri,this.async);try{if(this.opts.extraHeaders){t.setDisableHeaderCheck&&t.setDisableHeaderCheck(!0);for(let e in this.opts.extraHeaders)this.opts.extraHeaders.hasOwnProperty(e)&&t.setRequestHeader(e,this.opts.extraHeaders[e])}}catch(e){}if("POST"===this.method)try{t.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch(e){}try{t.setRequestHeader("Accept","*/*")}catch(e){}"withCredentials"in t&&(t.withCredentials=this.opts.withCredentials),this.opts.requestTimeout&&(t.timeout=this.opts.requestTimeout),t.onreadystatechange=()=>{4===t.readyState&&(200===t.status||1223===t.status?this.onLoad():this.setTimeoutFn((()=>{this.onError("number"==typeof t.status?t.status:0)}),0))},t.send(this.data)}catch(e){return void this.setTimeoutFn((()=>{this.onError(e)}),0)}"undefined"!=typeof document&&(this.index=Cs.requestsCount++,Cs.requests[this.index]=this)}onError(e){this.emitReserved("error",e,this.xhr),this.cleanup(!0)}cleanup(e){if(void 0!==this.xhr&&null!==this.xhr){if(this.xhr.onreadystatechange=Ss,e)try{this.xhr.abort()}catch(e){}"undefined"!=typeof document&&delete Cs.requests[this.index],this.xhr=null}}onLoad(){const e=this.xhr.responseText;null!==e&&(this.emitReserved("data",e),this.emitReserved("success"),this.cleanup())}abort(){this.cleanup()}}if(Cs.requestsCount=0,Cs.requests={},"undefined"!=typeof document)if("function"==typeof attachEvent)attachEvent("onunload",ks);else if("function"==typeof addEventListener){addEventListener("onpagehide"in is?"pagehide":"unload",ks,!1)}function ks(){for(let e in Cs.requests)Cs.requests.hasOwnProperty(e)&&Cs.requests[e].abort()}var Ts={},Ps={get exports(){return Ts},set exports(e){Ts=e}},Es={BINARY_TYPES:["nodebuffer","arraybuffer","fragments"],EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}};const{EMPTY_BUFFER:Os}=Es;function Ds(e,t,i,n,s){for(let a=0;a<s;a++)i[n+a]=e[a]^t[3&a]}function Is(e,t){for(let i=0;i<e.length;i++)e[i]^=t[3&i]}if(Ps.exports={concat:function(e,t){if(0===e.length)return Os;if(1===e.length)return e[0];const i=Buffer.allocUnsafe(t);let n=0;for(let t=0;t<e.length;t++){const s=e[t];i.set(s,n),n+=s.length}return n<t?i.slice(0,n):i},mask:Ds,toArrayBuffer:function(e){return e.byteLength===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength)},toBuffer:function e(t){if(e.readOnly=!0,Buffer.isBuffer(t))return t;let i;return t instanceof ArrayBuffer?i=Buffer.from(t):ArrayBuffer.isView(t)?i=Buffer.from(t.buffer,t.byteOffset,t.byteLength):(i=Buffer.from(t),e.readOnly=!1),i},unmask:Is},!process.env.WS_NO_BUFFER_UTIL)try{const e=require("bufferutil");Ts.mask=function(t,i,n,s,a){a<48?Ds(t,i,n,s,a):e.mask(t,i,n,s,a)},Ts.unmask=function(t,i){t.length<32?Is(t,i):e.unmask(t,i)}}catch(e){}const js=Symbol("kDone"),Ls=Symbol("kRun");const Ms=r,As=Ts,Ns=class{constructor(e){this[js]=()=>{this.pending--,this[Ls]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Ls]()}[Ls](){if(this.pending!==this.concurrency&&this.jobs.length){const e=this.jobs.shift();this.pending++,e(this[js])}}},{kStatusCode:Bs}=Es,Fs=Buffer.from([0,0,255,255]),Us=Symbol("permessage-deflate"),zs=Symbol("total-length"),qs=Symbol("callback"),$s=Symbol("buffers"),Vs=Symbol("error");let Ws;var Gs=class{constructor(e,t,i){if(this._maxPayload=0|i,this._options=e||{},this._threshold=void 0!==this._options.threshold?this._options.threshold:1024,this._isServer=!!t,this._deflate=null,this._inflate=null,this.params=null,!Ws){const e=void 0!==this._options.concurrencyLimit?this._options.concurrencyLimit:10;Ws=new Ns(e)}}static get extensionName(){return"permessage-deflate"}offer(){const e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:null==this._options.clientMaxWindowBits&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){const e=this._deflate[qs];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){const t=this._options,i=e.find((e=>!(!1===t.serverNoContextTakeover&&e.server_no_context_takeover||e.server_max_window_bits&&(!1===t.serverMaxWindowBits||"number"==typeof t.serverMaxWindowBits&&t.serverMaxWindowBits>e.server_max_window_bits)||"number"==typeof t.clientMaxWindowBits&&!e.client_max_window_bits)));if(!i)throw new Error("None of the extension offers can be accepted");return t.serverNoContextTakeover&&(i.server_no_context_takeover=!0),t.clientNoContextTakeover&&(i.client_no_context_takeover=!0),"number"==typeof t.serverMaxWindowBits&&(i.server_max_window_bits=t.serverMaxWindowBits),"number"==typeof t.clientMaxWindowBits?i.client_max_window_bits=t.clientMaxWindowBits:!0!==i.client_max_window_bits&&!1!==t.clientMaxWindowBits||delete i.client_max_window_bits,i}acceptAsClient(e){const t=e[0];if(!1===this._options.clientNoContextTakeover&&t.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(t.client_max_window_bits){if(!1===this._options.clientMaxWindowBits||"number"==typeof this._options.clientMaxWindowBits&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"')}else"number"==typeof this._options.clientMaxWindowBits&&(t.client_max_window_bits=this._options.clientMaxWindowBits);return t}normalizeParams(e){return e.forEach((e=>{Object.keys(e).forEach((t=>{let i=e[t];if(i.length>1)throw new Error(`Parameter "${t}" must have only a single value`);if(i=i[0],"client_max_window_bits"===t){if(!0!==i){const e=+i;if(!Number.isInteger(e)||e<8||e>15)throw new TypeError(`Invalid value for parameter "${t}": ${i}`);i=e}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${t}": ${i}`)}else if("server_max_window_bits"===t){const e=+i;if(!Number.isInteger(e)||e<8||e>15)throw new TypeError(`Invalid value for parameter "${t}": ${i}`);i=e}else{if("client_no_context_takeover"!==t&&"server_no_context_takeover"!==t)throw new Error(`Unknown parameter "${t}"`);if(!0!==i)throw new TypeError(`Invalid value for parameter "${t}": ${i}`)}e[t]=i}))})),e}decompress(e,t,i){Ws.add((n=>{this._decompress(e,t,((e,t)=>{n(),i(e,t)}))}))}compress(e,t,i){Ws.add((n=>{this._compress(e,t,((e,t)=>{n(),i(e,t)}))}))}_decompress(e,t,i){const n=this._isServer?"client":"server";if(!this._inflate){const e=`${n}_max_window_bits`,t="number"!=typeof this.params[e]?Ms.Z_DEFAULT_WINDOWBITS:this.params[e];this._inflate=Ms.createInflateRaw({...this._options.zlibInflateOptions,windowBits:t}),this._inflate[Us]=this,this._inflate[zs]=0,this._inflate[$s]=[],this._inflate.on("error",Js),this._inflate.on("data",Ks)}this._inflate[qs]=i,this._inflate.write(e),t&&this._inflate.write(Fs),this._inflate.flush((()=>{const e=this._inflate[Vs];if(e)return this._inflate.close(),this._inflate=null,void i(e);const s=As.concat(this._inflate[$s],this._inflate[zs]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[zs]=0,this._inflate[$s]=[],t&&this.params[`${n}_no_context_takeover`]&&this._inflate.reset()),i(null,s)}))}_compress(e,t,i){const n=this._isServer?"server":"client";if(!this._deflate){const e=`${n}_max_window_bits`,t="number"!=typeof this.params[e]?Ms.Z_DEFAULT_WINDOWBITS:this.params[e];this._deflate=Ms.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:t}),this._deflate[zs]=0,this._deflate[$s]=[],this._deflate.on("data",Hs)}this._deflate[qs]=i,this._deflate.write(e),this._deflate.flush(Ms.Z_SYNC_FLUSH,(()=>{if(!this._deflate)return;let e=As.concat(this._deflate[$s],this._deflate[zs]);t&&(e=e.slice(0,e.length-4)),this._deflate[qs]=null,this._deflate[zs]=0,this._deflate[$s]=[],t&&this.params[`${n}_no_context_takeover`]&&this._deflate.reset(),i(null,e)}))}};function Hs(e){this[$s].push(e),this[zs]+=e.length}function Ks(e){this[zs]+=e.length,this[Us]._maxPayload<1||this[zs]<=this[Us]._maxPayload?this[$s].push(e):(this[Vs]=new RangeError("Max payload size exceeded"),this[Vs].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Vs][Bs]=1009,this.removeListener("data",Ks),this.reset())}function Js(e){this[Us]._inflate=null,e[Bs]=1007,this[qs](e)}var Qs={};function Ys(e){const t=e.length;let i=0;for(;i<t;)if(0==(128&e[i]))i++;else if(192==(224&e[i])){if(i+1===t||128!=(192&e[i+1])||192==(254&e[i]))return!1;i+=2}else if(224==(240&e[i])){if(i+2>=t||128!=(192&e[i+1])||128!=(192&e[i+2])||224===e[i]&&128==(224&e[i+1])||237===e[i]&&160==(224&e[i+1]))return!1;i+=3}else{if(240!=(248&e[i]))return!1;if(i+3>=t||128!=(192&e[i+1])||128!=(192&e[i+2])||128!=(192&e[i+3])||240===e[i]&&128==(240&e[i+1])||244===e[i]&&e[i+1]>143||e[i]>244)return!1;i+=4}return!0}if({get exports(){return Qs},set exports(e){Qs=e}}.exports={isValidStatusCode:function(e){return e>=1e3&&e<=1014&&1004!==e&&1005!==e&&1006!==e||e>=3e3&&e<=4999},isValidUTF8:Ys,tokenChars:[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0]},!process.env.WS_NO_UTF_8_VALIDATE)try{const e=require("utf-8-validate");Qs.isValidUTF8=function(t){return t.length<150?Ys(t):e(t)}}catch(e){}const{Writable:Xs}=a,Zs=Gs,{BINARY_TYPES:ea,EMPTY_BUFFER:ta,kStatusCode:ia,kWebSocket:na}=Es,{concat:sa,toArrayBuffer:aa,unmask:ra}=Ts,{isValidStatusCode:oa,isValidUTF8:ca}=Qs;var pa=class extends Xs{constructor(e={}){super(),this._binaryType=e.binaryType||ea[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=0|e.maxPayload,this._skipUTF8Validation=!!e.skipUTF8Validation,this[na]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._state=0,this._loop=!1}_write(e,t,i){if(8===this._opcode&&0==this._state)return i();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(i)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){const t=this._buffers[0];return this._buffers[0]=t.slice(e),t.slice(0,e)}const t=Buffer.allocUnsafe(e);do{const i=this._buffers[0],n=t.length-e;e>=i.length?t.set(this._buffers.shift(),n):(t.set(new Uint8Array(i.buffer,i.byteOffset,e),n),this._buffers[0]=i.slice(e)),e-=i.length}while(e>0);return t}startLoop(e){let t;this._loop=!0;do{switch(this._state){case 0:t=this.getInfo();break;case 1:t=this.getPayloadLength16();break;case 2:t=this.getPayloadLength64();break;case 3:this.getMask();break;case 4:t=this.getData(e);break;default:return void(this._loop=!1)}}while(this._loop);e(t)}getInfo(){if(this._bufferedBytes<2)return void(this._loop=!1);const e=this.consume(2);if(0!=(48&e[0]))return this._loop=!1,da(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");const t=64==(64&e[0]);if(t&&!this._extensions[Zs.extensionName])return this._loop=!1,da(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");if(this._fin=128==(128&e[0]),this._opcode=15&e[0],this._payloadLength=127&e[1],0===this._opcode){if(t)return this._loop=!1,da(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");if(!this._fragmented)return this._loop=!1,da(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");this._opcode=this._fragmented}else if(1===this._opcode||2===this._opcode){if(this._fragmented)return this._loop=!1,da(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");this._compressed=t}else{if(!(this._opcode>7&&this._opcode<11))return this._loop=!1,da(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");if(!this._fin)return this._loop=!1,da(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");if(t)return this._loop=!1,da(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");if(this._payloadLength>125)return this._loop=!1,da(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH")}if(this._fin||this._fragmented||(this._fragmented=this._opcode),this._masked=128==(128&e[1]),this._isServer){if(!this._masked)return this._loop=!1,da(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK")}else if(this._masked)return this._loop=!1,da(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");if(126===this._payloadLength)this._state=1;else{if(127!==this._payloadLength)return this.haveLength();this._state=2}}getPayloadLength16(){if(!(this._bufferedBytes<2))return this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength();this._loop=!1}getPayloadLength64(){if(this._bufferedBytes<8)return void(this._loop=!1);const e=this.consume(8),t=e.readUInt32BE(0);return t>Math.pow(2,21)-1?(this._loop=!1,da(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH")):(this._payloadLength=t*Math.pow(2,32)+e.readUInt32BE(4),this.haveLength())}haveLength(){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0))return this._loop=!1,da(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");this._masked?this._state=3:this._state=4}getMask(){this._bufferedBytes<4?this._loop=!1:(this._mask=this.consume(4),this._state=4)}getData(e){let t=ta;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength)return void(this._loop=!1);t=this.consume(this._payloadLength),this._masked&&0!=(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])&&ra(t,this._mask)}return this._opcode>7?this.controlMessage(t):this._compressed?(this._state=5,void this.decompress(t,e)):(t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage())}decompress(e,t){this._extensions[Zs.extensionName].decompress(e,this._fin,((e,i)=>{if(e)return t(e);if(i.length){if(this._messageLength+=i.length,this._messageLength>this._maxPayload&&this._maxPayload>0)return t(da(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"));this._fragments.push(i)}const n=this.dataMessage();if(n)return t(n);this.startLoop(t)}))}dataMessage(){if(this._fin){const e=this._messageLength,t=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],2===this._opcode){let i;i="nodebuffer"===this._binaryType?sa(t,e):"arraybuffer"===this._binaryType?aa(sa(t,e)):t,this.emit("message",i,!0)}else{const i=sa(t,e);if(!this._skipUTF8Validation&&!ca(i))return this._loop=!1,da(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");this.emit("message",i,!1)}}this._state=0}controlMessage(e){if(8===this._opcode)if(this._loop=!1,0===e.length)this.emit("conclude",1005,ta),this.end();else{if(1===e.length)return da(RangeError,"invalid payload length 1",!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");{const t=e.readUInt16BE(0);if(!oa(t))return da(RangeError,`invalid status code ${t}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");const i=e.slice(2);if(!this._skipUTF8Validation&&!ca(i))return da(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");this.emit("conclude",t,i),this.end()}}else 9===this._opcode?this.emit("ping",e):this.emit("pong",e);this._state=0}};function da(e,t,i,n,s){const a=new e(i?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(a,da),a.code=s,a[ia]=n,a}const{randomFillSync:la}=p,ua=Gs,{EMPTY_BUFFER:ma}=Es,{isValidStatusCode:ha}=Qs,{mask:fa,toBuffer:ga}=Ts,va=Symbol("kByteLength"),ba=Buffer.alloc(4);class _a{constructor(e,t,i){this._extensions=t||{},i&&(this._generateMask=i,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._deflating=!1,this._queue=[]}static frame(e,t){let i,n,s=!1,a=2,r=!1;t.mask&&(i=t.maskBuffer||ba,t.generateMask?t.generateMask(i):la(i,0,4),r=0==(i[0]|i[1]|i[2]|i[3]),a=6),"string"==typeof e?n=t.mask&&!r||void 0===t[va]?(e=Buffer.from(e)).length:t[va]:(n=e.length,s=t.mask&&t.readOnly&&!r);let o=n;n>=65536?(a+=8,o=127):n>125&&(a+=2,o=126);const c=Buffer.allocUnsafe(s?n+a:a);return c[0]=t.fin?128|t.opcode:t.opcode,t.rsv1&&(c[0]|=64),c[1]=o,126===o?c.writeUInt16BE(n,2):127===o&&(c[2]=c[3]=0,c.writeUIntBE(n,4,6)),t.mask?(c[1]|=128,c[a-4]=i[0],c[a-3]=i[1],c[a-2]=i[2],c[a-1]=i[3],r?[c,e]:s?(fa(e,i,c,a,n),[c]):(fa(e,i,e,0,n),[c,e])):[c,e]}close(e,t,i,n){let s;if(void 0===e)s=ma;else{if("number"!=typeof e||!ha(e))throw new TypeError("First argument must be a valid error code number");if(void 0!==t&&t.length){const i=Buffer.byteLength(t);if(i>123)throw new RangeError("The message must not be greater than 123 bytes");s=Buffer.allocUnsafe(2+i),s.writeUInt16BE(e,0),"string"==typeof t?s.write(t,2):s.set(t,2)}else s=Buffer.allocUnsafe(2),s.writeUInt16BE(e,0)}const a={[va]:s.length,fin:!0,generateMask:this._generateMask,mask:i,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._deflating?this.enqueue([this.dispatch,s,!1,a,n]):this.sendFrame(_a.frame(s,a),n)}ping(e,t,i){let n,s;if("string"==typeof e?(n=Buffer.byteLength(e),s=!1):(n=(e=ga(e)).length,s=ga.readOnly),n>125)throw new RangeError("The data size must not be greater than 125 bytes");const a={[va]:n,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:9,readOnly:s,rsv1:!1};this._deflating?this.enqueue([this.dispatch,e,!1,a,i]):this.sendFrame(_a.frame(e,a),i)}pong(e,t,i){let n,s;if("string"==typeof e?(n=Buffer.byteLength(e),s=!1):(n=(e=ga(e)).length,s=ga.readOnly),n>125)throw new RangeError("The data size must not be greater than 125 bytes");const a={[va]:n,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:10,readOnly:s,rsv1:!1};this._deflating?this.enqueue([this.dispatch,e,!1,a,i]):this.sendFrame(_a.frame(e,a),i)}send(e,t,i){const n=this._extensions[ua.extensionName];let s,a,r=t.binary?2:1,o=t.compress;if("string"==typeof e?(s=Buffer.byteLength(e),a=!1):(s=(e=ga(e)).length,a=ga.readOnly),this._firstFragment?(this._firstFragment=!1,o&&n&&n.params[n._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(o=s>=n._threshold),this._compress=o):(o=!1,r=0),t.fin&&(this._firstFragment=!0),n){const n={[va]:s,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:r,readOnly:a,rsv1:o};this._deflating?this.enqueue([this.dispatch,e,this._compress,n,i]):this.dispatch(e,this._compress,n,i)}else this.sendFrame(_a.frame(e,{[va]:s,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:r,readOnly:a,rsv1:!1}),i)}dispatch(e,t,i,n){if(!t)return void this.sendFrame(_a.frame(e,i),n);const s=this._extensions[ua.extensionName];this._bufferedBytes+=i[va],this._deflating=!0,s.compress(e,i.fin,((e,t)=>{if(this._socket.destroyed){const e=new Error("The socket was closed while data was being compressed");"function"==typeof n&&n(e);for(let t=0;t<this._queue.length;t++){const i=this._queue[t],n=i[i.length-1];"function"==typeof n&&n(e)}}else this._bufferedBytes-=i[va],this._deflating=!1,i.readOnly=!1,this.sendFrame(_a.frame(t,i),n),this.dequeue()}))}dequeue(){for(;!this._deflating&&this._queue.length;){const e=this._queue.shift();this._bufferedBytes-=e[3][va],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][va],this._queue.push(e)}sendFrame(e,t){2===e.length?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork()):this._socket.write(e[0],t)}}var ya=_a;const{kForOnEventAttribute:xa,kListener:wa}=Es,Sa=Symbol("kCode"),Ra=Symbol("kData"),Ca=Symbol("kError"),ka=Symbol("kMessage"),Ta=Symbol("kReason"),Pa=Symbol("kTarget"),Ea=Symbol("kType"),Oa=Symbol("kWasClean");class Da{constructor(e){this[Pa]=null,this[Ea]=e}get target(){return this[Pa]}get type(){return this[Ea]}}Object.defineProperty(Da.prototype,"target",{enumerable:!0}),Object.defineProperty(Da.prototype,"type",{enumerable:!0});class Ia extends Da{constructor(e,t={}){super(e),this[Sa]=void 0===t.code?0:t.code,this[Ta]=void 0===t.reason?"":t.reason,this[Oa]=void 0!==t.wasClean&&t.wasClean}get code(){return this[Sa]}get reason(){return this[Ta]}get wasClean(){return this[Oa]}}Object.defineProperty(Ia.prototype,"code",{enumerable:!0}),Object.defineProperty(Ia.prototype,"reason",{enumerable:!0}),Object.defineProperty(Ia.prototype,"wasClean",{enumerable:!0});class ja extends Da{constructor(e,t={}){super(e),this[Ca]=void 0===t.error?null:t.error,this[ka]=void 0===t.message?"":t.message}get error(){return this[Ca]}get message(){return this[ka]}}Object.defineProperty(ja.prototype,"error",{enumerable:!0}),Object.defineProperty(ja.prototype,"message",{enumerable:!0});class La extends Da{constructor(e,t={}){super(e),this[Ra]=void 0===t.data?null:t.data}get data(){return this[Ra]}}Object.defineProperty(La.prototype,"data",{enumerable:!0});const Ma={addEventListener(e,t,i={}){for(const n of this.listeners(e))if(!i[xa]&&n[wa]===t&&!n[xa])return;let n;if("message"===e)n=function(e,i){const n=new La("message",{data:i?e:e.toString()});n[Pa]=this,Na(t,this,n)};else if("close"===e)n=function(e,i){const n=new Ia("close",{code:e,reason:i.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});n[Pa]=this,Na(t,this,n)};else if("error"===e)n=function(e){const i=new ja("error",{error:e,message:e.message});i[Pa]=this,Na(t,this,i)};else{if("open"!==e)return;n=function(){const e=new Da("open");e[Pa]=this,Na(t,this,e)}}n[xa]=!!i[xa],n[wa]=t,i.once?this.once(e,n):this.on(e,n)},removeEventListener(e,t){for(const i of this.listeners(e))if(i[wa]===t&&!i[xa]){this.removeListener(e,i);break}}};var Aa={CloseEvent:Ia,ErrorEvent:ja,Event:Da,EventTarget:Ma,MessageEvent:La};function Na(e,t,i){"object"==typeof e&&e.handleEvent?e.handleEvent.call(e,i):e.call(t,i)}const{tokenChars:Ba}=Qs;function Fa(e,t,i){void 0===e[t]?e[t]=[i]:e[t].push(i)}var Ua={format:function(e){return Object.keys(e).map((t=>{let i=e[t];return Array.isArray(i)||(i=[i]),i.map((e=>[t].concat(Object.keys(e).map((t=>{let i=e[t];return Array.isArray(i)||(i=[i]),i.map((e=>!0===e?t:`${t}=${e}`)).join("; ")}))).join("; "))).join(", ")})).join(", ")},parse:function(e){const t=Object.create(null);let i,n,s=Object.create(null),a=!1,r=!1,o=!1,c=-1,p=-1,d=-1,l=0;for(;l<e.length;l++)if(p=e.charCodeAt(l),void 0===i)if(-1===d&&1===Ba[p])-1===c&&(c=l);else if(0===l||32!==p&&9!==p){if(59!==p&&44!==p)throw new SyntaxError(`Unexpected character at index ${l}`);{if(-1===c)throw new SyntaxError(`Unexpected character at index ${l}`);-1===d&&(d=l);const n=e.slice(c,d);44===p?(Fa(t,n,s),s=Object.create(null)):i=n,c=d=-1}}else-1===d&&-1!==c&&(d=l);else if(void 0===n)if(-1===d&&1===Ba[p])-1===c&&(c=l);else if(32===p||9===p)-1===d&&-1!==c&&(d=l);else if(59===p||44===p){if(-1===c)throw new SyntaxError(`Unexpected character at index ${l}`);-1===d&&(d=l),Fa(s,e.slice(c,d),!0),44===p&&(Fa(t,i,s),s=Object.create(null),i=void 0),c=d=-1}else{if(61!==p||-1===c||-1!==d)throw new SyntaxError(`Unexpected character at index ${l}`);n=e.slice(c,l),c=d=-1}else if(r){if(1!==Ba[p])throw new SyntaxError(`Unexpected character at index ${l}`);-1===c?c=l:a||(a=!0),r=!1}else if(o)if(1===Ba[p])-1===c&&(c=l);else if(34===p&&-1!==c)o=!1,d=l;else{if(92!==p)throw new SyntaxError(`Unexpected character at index ${l}`);r=!0}else if(34===p&&61===e.charCodeAt(l-1))o=!0;else if(-1===d&&1===Ba[p])-1===c&&(c=l);else if(-1===c||32!==p&&9!==p){if(59!==p&&44!==p)throw new SyntaxError(`Unexpected character at index ${l}`);{if(-1===c)throw new SyntaxError(`Unexpected character at index ${l}`);-1===d&&(d=l);let r=e.slice(c,d);a&&(r=r.replace(/\\/g,""),a=!1),Fa(s,n,r),44===p&&(Fa(t,i,s),s=Object.create(null),i=void 0),n=void 0,c=d=-1}}else-1===d&&(d=l);if(-1===c||o||32===p||9===p)throw new SyntaxError("Unexpected end of input");-1===d&&(d=l);const u=e.slice(c,d);return void 0===i?Fa(t,u,s):(void 0===n?Fa(s,u,!0):Fa(s,n,a?u.replace(/\\/g,""):u),Fa(t,i,s)),t}};const za=d,qa=s,$a=n,Va=o,Wa=c,{randomBytes:Ga,createHash:Ha}=p,{URL:Ka}=t,Ja=Gs,Qa=pa,Ya=ya,{BINARY_TYPES:Xa,EMPTY_BUFFER:Za,GUID:er,kForOnEventAttribute:tr,kListener:ir,kStatusCode:nr,kWebSocket:sr,NOOP:ar}=Es,{EventTarget:{addEventListener:rr,removeEventListener:or}}=Aa,{format:cr,parse:pr}=Ua,{toBuffer:dr}=Ts,lr=Symbol("kAborted"),ur=[8,13],mr=["CONNECTING","OPEN","CLOSING","CLOSED"],hr=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;class fr extends za{constructor(e,t,i){super(),this._binaryType=Xa[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Za,this._closeTimer=null,this._extensions={},this._paused=!1,this._protocol="",this._readyState=fr.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,null!==e?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,void 0===t?t=[]:Array.isArray(t)||("object"==typeof t&&null!==t?(i=t,t=[]):t=[t]),gr(this,e,t,i)):this._isServer=!0}get binaryType(){return this._binaryType}set binaryType(e){Xa.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,t,i){const n=new Qa({binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation});this._sender=new Ya(e,this._extensions,i.generateMask),this._receiver=n,this._socket=e,n[sr]=this,e[sr]=this,n.on("conclude",wr),n.on("drain",Sr),n.on("error",Rr),n.on("message",kr),n.on("ping",Tr),n.on("pong",Pr),e.setTimeout(0),e.setNoDelay(),t.length>0&&e.unshift(t),e.on("close",Or),e.on("data",Dr),e.on("end",Ir),e.on("error",jr),this._readyState=fr.OPEN,this.emit("open")}emitClose(){if(!this._socket)return this._readyState=fr.CLOSED,void this.emit("close",this._closeCode,this._closeMessage);this._extensions[Ja.extensionName]&&this._extensions[Ja.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=fr.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,t){if(this.readyState!==fr.CLOSED){if(this.readyState===fr.CONNECTING){const e="WebSocket was closed before the connection was established";return yr(this,this._req,e)}this.readyState!==fr.CLOSING?(this._readyState=fr.CLOSING,this._sender.close(e,t,!this._isServer,(e=>{e||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())})),this._closeTimer=setTimeout(this._socket.destroy.bind(this._socket),3e4)):this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end()}}pause(){this.readyState!==fr.CONNECTING&&this.readyState!==fr.CLOSED&&(this._paused=!0,this._socket.pause())}ping(e,t,i){if(this.readyState===fr.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");"function"==typeof e?(i=e,e=t=void 0):"function"==typeof t&&(i=t,t=void 0),"number"==typeof e&&(e=e.toString()),this.readyState===fr.OPEN?(void 0===t&&(t=!this._isServer),this._sender.ping(e||Za,t,i)):xr(this,e,i)}pong(e,t,i){if(this.readyState===fr.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");"function"==typeof e?(i=e,e=t=void 0):"function"==typeof t&&(i=t,t=void 0),"number"==typeof e&&(e=e.toString()),this.readyState===fr.OPEN?(void 0===t&&(t=!this._isServer),this._sender.pong(e||Za,t,i)):xr(this,e,i)}resume(){this.readyState!==fr.CONNECTING&&this.readyState!==fr.CLOSED&&(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,t,i){if(this.readyState===fr.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if("function"==typeof t&&(i=t,t={}),"number"==typeof e&&(e=e.toString()),this.readyState!==fr.OPEN)return void xr(this,e,i);const n={binary:"string"!=typeof e,mask:!this._isServer,compress:!0,fin:!0,...t};this._extensions[Ja.extensionName]||(n.compress=!1),this._sender.send(e||Za,n,i)}terminate(){if(this.readyState!==fr.CLOSED){if(this.readyState===fr.CONNECTING){const e="WebSocket was closed before the connection was established";return yr(this,this._req,e)}this._socket&&(this._readyState=fr.CLOSING,this._socket.destroy())}}}function gr(e,t,i,n){const s={protocolVersion:ur[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...n,createConnection:void 0,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(!ur.includes(s.protocolVersion))throw new RangeError(`Unsupported protocol version: ${s.protocolVersion} (supported versions: ${ur.join(", ")})`);let a;if(t instanceof Ka)a=t,e._url=t.href;else{try{a=new Ka(t)}catch(e){throw new SyntaxError(`Invalid URL: ${t}`)}e._url=t}const r="wss:"===a.protocol,o="ws+unix:"===a.protocol;let c;if("ws:"===a.protocol||r||o?o&&!a.pathname?c="The URL's pathname is empty":a.hash&&(c="The URL contains a fragment identifier"):c='The URL\'s protocol must be one of "ws:", "wss:", or "ws+unix:"',c){const t=new SyntaxError(c);if(0===e._redirects)throw t;return void vr(e,t)}const p=r?443:80,d=Ga(16).toString("base64"),l=r?qa.request:$a.request,u=new Set;let m,h;if(s.createConnection=r?_r:br,s.defaultPort=s.defaultPort||p,s.port=a.port||p,s.host=a.hostname.startsWith("[")?a.hostname.slice(1,-1):a.hostname,s.headers={...s.headers,"Sec-WebSocket-Version":s.protocolVersion,"Sec-WebSocket-Key":d,Connection:"Upgrade",Upgrade:"websocket"},s.path=a.pathname+a.search,s.timeout=s.handshakeTimeout,s.perMessageDeflate&&(m=new Ja(!0!==s.perMessageDeflate?s.perMessageDeflate:{},!1,s.maxPayload),s.headers["Sec-WebSocket-Extensions"]=cr({[Ja.extensionName]:m.offer()})),i.length){for(const e of i){if("string"!=typeof e||!hr.test(e)||u.has(e))throw new SyntaxError("An invalid or duplicated subprotocol was specified");u.add(e)}s.headers["Sec-WebSocket-Protocol"]=i.join(",")}if(s.origin&&(s.protocolVersion<13?s.headers["Sec-WebSocket-Origin"]=s.origin:s.headers.Origin=s.origin),(a.username||a.password)&&(s.auth=`${a.username}:${a.password}`),o){const e=s.path.split(":");s.socketPath=e[0],s.path=e[1]}if(s.followRedirects){if(0===e._redirects){e._originalIpc=o,e._originalSecure=r,e._originalHostOrSocketPath=o?s.socketPath:a.host;const t=n&&n.headers;if(n={...n,headers:{}},t)for(const[e,i]of Object.entries(t))n.headers[e.toLowerCase()]=i}else if(0===e.listenerCount("redirect")){const t=o?!!e._originalIpc&&s.socketPath===e._originalHostOrSocketPath:!e._originalIpc&&a.host===e._originalHostOrSocketPath;(!t||e._originalSecure&&!r)&&(delete s.headers.authorization,delete s.headers.cookie,t||delete s.headers.host,s.auth=void 0)}s.auth&&!n.headers.authorization&&(n.headers.authorization="Basic "+Buffer.from(s.auth).toString("base64")),h=e._req=l(s),e._redirects&&e.emit("redirect",e.url,h)}else h=e._req=l(s);s.timeout&&h.on("timeout",(()=>{yr(e,h,"Opening handshake has timed out")})),h.on("error",(t=>{null===h||h[lr]||(h=e._req=null,vr(e,t))})),h.on("response",(a=>{const r=a.headers.location,o=a.statusCode;if(r&&s.followRedirects&&o>=300&&o<400){if(++e._redirects>s.maxRedirects)return void yr(e,h,"Maximum redirects exceeded");let a;h.abort();try{a=new Ka(r,t)}catch(t){const i=new SyntaxError(`Invalid URL: ${r}`);return void vr(e,i)}gr(e,a,i,n)}else e.emit("unexpected-response",h,a)||yr(e,h,`Unexpected server response: ${a.statusCode}`)})),h.on("upgrade",((t,i,n)=>{if(e.emit("upgrade",t),e.readyState!==fr.CONNECTING)return;if(h=e._req=null,"websocket"!==t.headers.upgrade.toLowerCase())return void yr(e,i,"Invalid Upgrade header");const a=Ha("sha1").update(d+er).digest("base64");if(t.headers["sec-websocket-accept"]!==a)return void yr(e,i,"Invalid Sec-WebSocket-Accept header");const r=t.headers["sec-websocket-protocol"];let o;if(void 0!==r?u.size?u.has(r)||(o="Server sent an invalid subprotocol"):o="Server sent a subprotocol but none was requested":u.size&&(o="Server sent no subprotocol"),o)return void yr(e,i,o);r&&(e._protocol=r);const c=t.headers["sec-websocket-extensions"];if(void 0!==c){if(!m){return void yr(e,i,"Server sent a Sec-WebSocket-Extensions header but no extension was requested")}let t;try{t=pr(c)}catch(t){return void yr(e,i,"Invalid Sec-WebSocket-Extensions header")}const n=Object.keys(t);if(1!==n.length||n[0]!==Ja.extensionName){return void yr(e,i,"Server indicated an extension that was not requested")}try{m.accept(t[Ja.extensionName])}catch(t){return void yr(e,i,"Invalid Sec-WebSocket-Extensions header")}e._extensions[Ja.extensionName]=m}e.setSocket(i,n,{generateMask:s.generateMask,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation})})),h.end()}function vr(e,t){e._readyState=fr.CLOSING,e.emit("error",t),e.emitClose()}function br(e){return e.path=e.socketPath,Va.connect(e)}function _r(e){return e.path=void 0,e.servername||""===e.servername||(e.servername=Va.isIP(e.host)?"":e.host),Wa.connect(e)}function yr(e,t,i){e._readyState=fr.CLOSING;const n=new Error(i);Error.captureStackTrace(n,yr),t.setHeader?(t[lr]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(vr,e,n)):(t.destroy(n),t.once("error",e.emit.bind(e,"error")),t.once("close",e.emitClose.bind(e)))}function xr(e,t,i){if(t){const i=dr(t).length;e._socket?e._sender._bufferedBytes+=i:e._bufferedAmount+=i}if(i){i(new Error(`WebSocket is not open: readyState ${e.readyState} (${mr[e.readyState]})`))}}function wr(e,t){const i=this[sr];i._closeFrameReceived=!0,i._closeMessage=t,i._closeCode=e,void 0!==i._socket[sr]&&(i._socket.removeListener("data",Dr),process.nextTick(Er,i._socket),1005===e?i.close():i.close(e,t))}function Sr(){const e=this[sr];e.isPaused||e._socket.resume()}function Rr(e){const t=this[sr];void 0!==t._socket[sr]&&(t._socket.removeListener("data",Dr),process.nextTick(Er,t._socket),t.close(e[nr])),t.emit("error",e)}function Cr(){this[sr].emitClose()}function kr(e,t){this[sr].emit("message",e,t)}function Tr(e){const t=this[sr];t.pong(e,!t._isServer,ar),t.emit("ping",e)}function Pr(e){this[sr].emit("pong",e)}function Er(e){e.resume()}function Or(){const e=this[sr];let t;this.removeListener("close",Or),this.removeListener("data",Dr),this.removeListener("end",Ir),e._readyState=fr.CLOSING,this._readableState.endEmitted||e._closeFrameReceived||e._receiver._writableState.errorEmitted||null===(t=e._socket.read())||e._receiver.write(t),e._receiver.end(),this[sr]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on("error",Cr),e._receiver.on("finish",Cr))}function Dr(e){this[sr]._receiver.write(e)||this.pause()}function Ir(){const e=this[sr];e._readyState=fr.CLOSING,e._receiver.end(),this.end()}function jr(){const e=this[sr];this.removeListener("error",jr),this.on("error",ar),e&&(e._readyState=fr.CLOSING,this.destroy())}Object.defineProperty(fr,"CONNECTING",{enumerable:!0,value:mr.indexOf("CONNECTING")}),Object.defineProperty(fr.prototype,"CONNECTING",{enumerable:!0,value:mr.indexOf("CONNECTING")}),Object.defineProperty(fr,"OPEN",{enumerable:!0,value:mr.indexOf("OPEN")}),Object.defineProperty(fr.prototype,"OPEN",{enumerable:!0,value:mr.indexOf("OPEN")}),Object.defineProperty(fr,"CLOSING",{enumerable:!0,value:mr.indexOf("CLOSING")}),Object.defineProperty(fr.prototype,"CLOSING",{enumerable:!0,value:mr.indexOf("CLOSING")}),Object.defineProperty(fr,"CLOSED",{enumerable:!0,value:mr.indexOf("CLOSED")}),Object.defineProperty(fr.prototype,"CLOSED",{enumerable:!0,value:mr.indexOf("CLOSED")}),["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach((e=>{Object.defineProperty(fr.prototype,e,{enumerable:!0})})),["open","error","close","message"].forEach((e=>{Object.defineProperty(fr.prototype,`on${e}`,{enumerable:!0,get(){for(const t of this.listeners(e))if(t[tr])return t[ir];return null},set(t){for(const t of this.listeners(e))if(t[tr]){this.removeListener(e,t);break}"function"==typeof t&&this.addEventListener(e,t,{[tr]:!0})}})})),fr.prototype.addEventListener=rr,fr.prototype.removeEventListener=or;const Lr=fr,Mr=process.nextTick,Ar="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase();const Nr={websocket:class extends cs{constructor(e){super(e),this.supportsBinary=!e.forceBase64}get name(){return"websocket"}doOpen(){if(!this.check())return;const e=this.uri(),t=this.opts.protocols,i=Ar?{}:ns(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(i.headers=this.opts.extraHeaders);try{this.ws=new Lr(e,t,i)}catch(e){return this.emitReserved("error",e)}this.ws.binaryType=this.socket.binaryType||"nodebuffer",this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=e=>this.onClose({description:"websocket connection closed",context:e}),this.ws.onmessage=e=>this.onData(e.data),this.ws.onerror=e=>this.onError("websocket error",e)}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const i=e[t],n=t===e.length-1;Kn(i,this.supportsBinary,(e=>{const t={};if(i.options&&(t.compress=i.options.compress),this.opts.perMessageDeflate){("string"==typeof e?Buffer.byteLength(e):e.length)<this.opts.perMessageDeflate.threshold&&(t.compress=!1)}try{this.ws.send(e,t)}catch(e){}n&&Mr((()=>{this.writable=!0,this.emitReserved("drain")}),this.setTimeoutFn)}))}}doClose(){void 0!==this.ws&&(this.ws.close(),this.ws=null)}uri(){let e=this.query||{};const t=this.opts.secure?"wss":"ws";let i="";this.opts.port&&("wss"===t&&443!==Number(this.opts.port)||"ws"===t&&80!==Number(this.opts.port))&&(i=":"+this.opts.port),this.opts.timestampRequests&&(e[this.opts.timestampParam]=fs()),this.supportsBinary||(e.b64=1);const n=gs(e);return t+"://"+(-1!==this.opts.hostname.indexOf(":")?"["+this.opts.hostname+"]":this.opts.hostname)+i+this.opts.path+(n.length?"?"+n:"")}check(){return!!Lr}},polling:class extends cs{constructor(e){if(super(e),this.polling=!1,"undefined"!=typeof location){const t="https:"===location.protocol;let i=location.port;i||(i=t?"443":"80"),this.xd="undefined"!=typeof location&&e.hostname!==location.hostname||i!==e.port,this.xs=e.secure!==t}const t=e&&e.forceBase64;this.supportsBinary=Rs&&!t}get name(){return"polling"}doOpen(){this.poll()}pause(e){this.readyState="pausing";const t=()=>{this.readyState="paused",e()};if(this.polling||!this.writable){let e=0;this.polling&&(e++,this.once("pollComplete",(function(){--e||t()}))),this.writable||(e++,this.once("drain",(function(){--e||t()})))}else t()}poll(){this.polling=!0,this.doPoll(),this.emitReserved("poll")}onData(e){((e,t)=>{const i=e.split(es),n=[];for(let e=0;e<i.length;e++){const s=Yn(i[e],t);if(n.push(s),"error"===s.type)break}return n})(e,this.socket.binaryType).forEach((e=>{if("opening"===this.readyState&&"open"===e.type&&this.onOpen(),"close"===e.type)return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(e)})),"closed"!==this.readyState&&(this.polling=!1,this.emitReserved("pollComplete"),"open"===this.readyState&&this.poll())}doClose(){const e=()=>{this.write([{type:"close"}])};"open"===this.readyState?e():this.once("open",e)}write(e){this.writable=!1,((e,t)=>{const i=e.length,n=new Array(i);let s=0;e.forEach(((e,a)=>{Kn(e,!1,(e=>{n[a]=e,++s===i&&t(n.join(es))}))}))})(e,(e=>{this.doWrite(e,(()=>{this.writable=!0,this.emitReserved("drain")}))}))}uri(){let e=this.query||{};const t=this.opts.secure?"https":"http";let i="";!1!==this.opts.timestampRequests&&(e[this.opts.timestampParam]=fs()),this.supportsBinary||e.sid||(e.b64=1),this.opts.port&&("https"===t&&443!==Number(this.opts.port)||"http"===t&&80!==Number(this.opts.port))&&(i=":"+this.opts.port);const n=gs(e);return t+"://"+(-1!==this.opts.hostname.indexOf(":")?"["+this.opts.hostname+"]":this.opts.hostname)+i+this.opts.path+(n.length?"?"+n:"")}request(e={}){return Object.assign(e,{xd:this.xd,xs:this.xs},this.opts),new Cs(this.uri(),e)}doWrite(e,t){const i=this.request({method:"POST",data:e});i.on("success",t),i.on("error",((e,t)=>{this.onError("xhr post error",e,t)}))}doPoll(){const e=this.request();e.on("data",this.onData.bind(this)),e.on("error",((e,t)=>{this.onError("xhr poll error",e,t)})),this.pollXhr=e}}},Br=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,Fr=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function Ur(e){const t=e,i=e.indexOf("["),n=e.indexOf("]");-1!=i&&-1!=n&&(e=e.substring(0,i)+e.substring(i,n).replace(/:/g,";")+e.substring(n,e.length));let s=Br.exec(e||""),a={},r=14;for(;r--;)a[Fr[r]]=s[r]||"";return-1!=i&&-1!=n&&(a.source=t,a.host=a.host.substring(1,a.host.length-1).replace(/;/g,":"),a.authority=a.authority.replace("[","").replace("]","").replace(/;/g,":"),a.ipv6uri=!0),a.pathNames=function(e,t){const i=/\/{2,9}/g,n=t.replace(i,"/").split("/");"/"!=t.slice(0,1)&&0!==t.length||n.splice(0,1);"/"==t.slice(-1)&&n.splice(n.length-1,1);return n}(0,a.path),a.queryKey=function(e,t){const i={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,(function(e,t,n){t&&(i[t]=n)})),i}(0,a.query),a}class zr extends ts{constructor(e,t={}){super(),this.writeBuffer=[],e&&"object"==typeof e&&(t=e,e=null),e?(e=Ur(e),t.hostname=e.host,t.secure="https"===e.protocol||"wss"===e.protocol,t.port=e.port,e.query&&(t.query=e.query)):t.host&&(t.hostname=Ur(t.host).host),rs(this,t),this.secure=null!=t.secure?t.secure:"undefined"!=typeof location&&"https:"===location.protocol,t.hostname&&!t.port&&(t.port=this.secure?"443":"80"),this.hostname=t.hostname||("undefined"!=typeof location?location.hostname:"localhost"),this.port=t.port||("undefined"!=typeof location&&location.port?location.port:this.secure?"443":"80"),this.transports=t.transports||["polling","websocket"],this.writeBuffer=[],this.prevBufferLen=0,this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!0},t),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),"string"==typeof this.opts.query&&(this.opts.query=function(e){let t={},i=e.split("&");for(let e=0,n=i.length;e<n;e++){let n=i[e].split("=");t[decodeURIComponent(n[0])]=decodeURIComponent(n[1])}return t}(this.opts.query)),this.id=null,this.upgrades=null,this.pingInterval=null,this.pingTimeout=null,this.pingTimeoutTimer=null,"function"==typeof addEventListener&&(this.opts.closeOnBeforeunload&&(this.beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this.beforeunloadEventListener,!1)),"localhost"!==this.hostname&&(this.offlineEventListener=()=>{this.onClose("transport close",{description:"network connection lost"})},addEventListener("offline",this.offlineEventListener,!1))),this.open()}createTransport(e){const t=Object.assign({},this.opts.query);t.EIO=4,t.transport=e,this.id&&(t.sid=this.id);const i=Object.assign({},this.opts.transportOptions[e],this.opts,{query:t,socket:this,hostname:this.hostname,secure:this.secure,port:this.port});return new Nr[e](i)}open(){let e;if(this.opts.rememberUpgrade&&zr.priorWebsocketSuccess&&-1!==this.transports.indexOf("websocket"))e="websocket";else{if(0===this.transports.length)return void this.setTimeoutFn((()=>{this.emitReserved("error","No transports available")}),0);e=this.transports[0]}this.readyState="opening";try{e=this.createTransport(e)}catch(e){return this.transports.shift(),void this.open()}e.open(),this.setTransport(e)}setTransport(e){this.transport&&this.transport.removeAllListeners(),this.transport=e,e.on("drain",this.onDrain.bind(this)).on("packet",this.onPacket.bind(this)).on("error",this.onError.bind(this)).on("close",(e=>this.onClose("transport close",e)))}probe(e){let t=this.createTransport(e),i=!1;zr.priorWebsocketSuccess=!1;const n=()=>{i||(t.send([{type:"ping",data:"probe"}]),t.once("packet",(e=>{if(!i)if("pong"===e.type&&"probe"===e.data){if(this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;zr.priorWebsocketSuccess="websocket"===t.name,this.transport.pause((()=>{i||"closed"!==this.readyState&&(p(),this.setTransport(t),t.send([{type:"upgrade"}]),this.emitReserved("upgrade",t),t=null,this.upgrading=!1,this.flush())}))}else{const e=new Error("probe error");e.transport=t.name,this.emitReserved("upgradeError",e)}})))};function s(){i||(i=!0,p(),t.close(),t=null)}const a=e=>{const i=new Error("probe error: "+e);i.transport=t.name,s(),this.emitReserved("upgradeError",i)};function r(){a("transport closed")}function o(){a("socket closed")}function c(e){t&&e.name!==t.name&&s()}const p=()=>{t.removeListener("open",n),t.removeListener("error",a),t.removeListener("close",r),this.off("close",o),this.off("upgrading",c)};t.once("open",n),t.once("error",a),t.once("close",r),this.once("close",o),this.once("upgrading",c),t.open()}onOpen(){if(this.readyState="open",zr.priorWebsocketSuccess="websocket"===this.transport.name,this.emitReserved("open"),this.flush(),"open"===this.readyState&&this.opts.upgrade){let e=0;const t=this.upgrades.length;for(;e<t;e++)this.probe(this.upgrades[e])}}onPacket(e){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState)switch(this.emitReserved("packet",e),this.emitReserved("heartbeat"),e.type){case"open":this.onHandshake(JSON.parse(e.data));break;case"ping":this.resetPingTimeout(),this.sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong");break;case"error":const t=new Error("server error");t.code=e.data,this.onError(t);break;case"message":this.emitReserved("data",e.data),this.emitReserved("message",e.data)}}onHandshake(e){this.emitReserved("handshake",e),this.id=e.sid,this.transport.query.sid=e.sid,this.upgrades=this.filterUpgrades(e.upgrades),this.pingInterval=e.pingInterval,this.pingTimeout=e.pingTimeout,this.maxPayload=e.maxPayload,this.onOpen(),"closed"!==this.readyState&&this.resetPingTimeout()}resetPingTimeout(){this.clearTimeoutFn(this.pingTimeoutTimer),this.pingTimeoutTimer=this.setTimeoutFn((()=>{this.onClose("ping timeout")}),this.pingInterval+this.pingTimeout),this.opts.autoUnref&&this.pingTimeoutTimer.unref()}onDrain(){this.writeBuffer.splice(0,this.prevBufferLen),this.prevBufferLen=0,0===this.writeBuffer.length?this.emitReserved("drain"):this.flush()}flush(){if("closed"!==this.readyState&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const e=this.getWritablePackets();this.transport.send(e),this.prevBufferLen=e.length,this.emitReserved("flush")}}getWritablePackets(){if(!(this.maxPayload&&"polling"===this.transport.name&&this.writeBuffer.length>1))return this.writeBuffer;let e=1;for(let i=0;i<this.writeBuffer.length;i++){const n=this.writeBuffer[i].data;if(n&&(e+="string"==typeof(t=n)?function(e){let t=0,i=0;for(let n=0,s=e.length;n<s;n++)t=e.charCodeAt(n),t<128?i+=1:t<2048?i+=2:t<55296||t>=57344?i+=3:(n++,i+=4);return i}(t):Math.ceil(1.33*(t.byteLength||t.size))),i>0&&e>this.maxPayload)return this.writeBuffer.slice(0,i);e+=2}var t;return this.writeBuffer}write(e,t,i){return this.sendPacket("message",e,t,i),this}send(e,t,i){return this.sendPacket("message",e,t,i),this}sendPacket(e,t,i,n){if("function"==typeof t&&(n=t,t=void 0),"function"==typeof i&&(n=i,i=null),"closing"===this.readyState||"closed"===this.readyState)return;(i=i||{}).compress=!1!==i.compress;const s={type:e,data:t,options:i};this.emitReserved("packetCreate",s),this.writeBuffer.push(s),n&&this.once("flush",n),this.flush()}close(){const e=()=>{this.onClose("forced close"),this.transport.close()},t=()=>{this.off("upgrade",t),this.off("upgradeError",t),e()},i=()=>{this.once("upgrade",t),this.once("upgradeError",t)};return"opening"!==this.readyState&&"open"!==this.readyState||(this.readyState="closing",this.writeBuffer.length?this.once("drain",(()=>{this.upgrading?i():e()})):this.upgrading?i():e()),this}onError(e){zr.priorWebsocketSuccess=!1,this.emitReserved("error",e),this.onClose("transport error",e)}onClose(e,t){"opening"!==this.readyState&&"open"!==this.readyState&&"closing"!==this.readyState||(this.clearTimeoutFn(this.pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),"function"==typeof removeEventListener&&(removeEventListener("beforeunload",this.beforeunloadEventListener,!1),removeEventListener("offline",this.offlineEventListener,!1)),this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this.prevBufferLen=0)}filterUpgrades(e){const t=[];let i=0;const n=e.length;for(;i<n;i++)~this.transports.indexOf(e[i])&&t.push(e[i]);return t}}zr.protocol=4;const qr="function"==typeof ArrayBuffer,$r=Object.prototype.toString,Vr="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===$r.call(Blob),Wr="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===$r.call(File);function Gr(e){return qr&&(e instanceof ArrayBuffer||(e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer)(e))||Vr&&e instanceof Blob||Wr&&e instanceof File}function Hr(e,t){if(!e||"object"!=typeof e)return!1;if(Array.isArray(e)){for(let t=0,i=e.length;t<i;t++)if(Hr(e[t]))return!0;return!1}if(Gr(e))return!0;if(e.toJSON&&"function"==typeof e.toJSON&&1===arguments.length)return Hr(e.toJSON(),!0);for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t)&&Hr(e[t]))return!0;return!1}function Kr(e){const t=[],i=e.data,n=e;return n.data=Jr(i,t),n.attachments=t.length,{packet:n,buffers:t}}function Jr(e,t){if(!e)return e;if(Gr(e)){const i={_placeholder:!0,num:t.length};return t.push(e),i}if(Array.isArray(e)){const i=new Array(e.length);for(let n=0;n<e.length;n++)i[n]=Jr(e[n],t);return i}if("object"==typeof e&&!(e instanceof Date)){const i={};for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&(i[n]=Jr(e[n],t));return i}return e}function Qr(e,t){return e.data=Yr(e.data,t),delete e.attachments,e}function Yr(e,t){if(!e)return e;if(e&&!0===e._placeholder){if("number"==typeof e.num&&e.num>=0&&e.num<t.length)return t[e.num];throw new Error("illegal attachments")}if(Array.isArray(e))for(let i=0;i<e.length;i++)e[i]=Yr(e[i],t);else if("object"==typeof e)for(const i in e)Object.prototype.hasOwnProperty.call(e,i)&&(e[i]=Yr(e[i],t));return e}var Xr;!function(e){e[e.CONNECT=0]="CONNECT",e[e.DISCONNECT=1]="DISCONNECT",e[e.EVENT=2]="EVENT",e[e.ACK=3]="ACK",e[e.CONNECT_ERROR=4]="CONNECT_ERROR",e[e.BINARY_EVENT=5]="BINARY_EVENT",e[e.BINARY_ACK=6]="BINARY_ACK"}(Xr||(Xr={}));class Zr extends ts{constructor(e){super(),this.reviver=e}add(e){let t;if("string"==typeof e){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");t=this.decodeString(e);const i=t.type===Xr.BINARY_EVENT;i||t.type===Xr.BINARY_ACK?(t.type=i?Xr.EVENT:Xr.ACK,this.reconstructor=new eo(t),0===t.attachments&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else{if(!Gr(e)&&!e.base64)throw new Error("Unknown type: "+e);if(!this.reconstructor)throw new Error("got binary data when not reconstructing a packet");t=this.reconstructor.takeBinaryData(e),t&&(this.reconstructor=null,super.emitReserved("decoded",t))}}decodeString(e){let t=0;const i={type:Number(e.charAt(0))};if(void 0===Xr[i.type])throw new Error("unknown packet type "+i.type);if(i.type===Xr.BINARY_EVENT||i.type===Xr.BINARY_ACK){const n=t+1;for(;"-"!==e.charAt(++t)&&t!=e.length;);const s=e.substring(n,t);if(s!=Number(s)||"-"!==e.charAt(t))throw new Error("Illegal attachments");i.attachments=Number(s)}if("/"===e.charAt(t+1)){const n=t+1;for(;++t;){if(","===e.charAt(t))break;if(t===e.length)break}i.nsp=e.substring(n,t)}else i.nsp="/";const n=e.charAt(t+1);if(""!==n&&Number(n)==n){const n=t+1;for(;++t;){const i=e.charAt(t);if(null==i||Number(i)!=i){--t;break}if(t===e.length)break}i.id=Number(e.substring(n,t+1))}if(e.charAt(++t)){const n=this.tryParse(e.substr(t));if(!Zr.isPayloadValid(i.type,n))throw new Error("invalid payload");i.data=n}return i}tryParse(e){try{return JSON.parse(e,this.reviver)}catch(e){return!1}}static isPayloadValid(e,t){switch(e){case Xr.CONNECT:return"object"==typeof t;case Xr.DISCONNECT:return void 0===t;case Xr.CONNECT_ERROR:return"string"==typeof t||"object"==typeof t;case Xr.EVENT:case Xr.BINARY_EVENT:return Array.isArray(t)&&t.length>0;case Xr.ACK:case Xr.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class eo{constructor(e){this.packet=e,this.buffers=[],this.reconPack=e}takeBinaryData(e){if(this.buffers.push(e),this.buffers.length===this.reconPack.attachments){const e=Qr(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}var to=Object.freeze({__proto__:null,protocol:5,get PacketType(){return Xr},Encoder:class{constructor(e){this.replacer=e}encode(e){return e.type!==Xr.EVENT&&e.type!==Xr.ACK||!Hr(e)?[this.encodeAsString(e)]:this.encodeAsBinary({type:e.type===Xr.EVENT?Xr.BINARY_EVENT:Xr.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id})}encodeAsString(e){let t=""+e.type;return e.type!==Xr.BINARY_EVENT&&e.type!==Xr.BINARY_ACK||(t+=e.attachments+"-"),e.nsp&&"/"!==e.nsp&&(t+=e.nsp+","),null!=e.id&&(t+=e.id),null!=e.data&&(t+=JSON.stringify(e.data,this.replacer)),t}encodeAsBinary(e){const t=Kr(e),i=this.encodeAsString(t.packet),n=t.buffers;return n.unshift(i),n}},Decoder:Zr});function io(e,t,i){return e.on(t,i),function(){e.off(t,i)}}const no=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class so extends ts{constructor(e,t,i){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=e,this.nsp=t,i&&i.auth&&(this.auth=i.auth),this._opts=Object.assign({},i),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const e=this.io;this.subs=[io(e,"open",this.onopen.bind(this)),io(e,"packet",this.onpacket.bind(this)),io(e,"error",this.onerror.bind(this)),io(e,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected||(this.subEvents(),this.io._reconnecting||this.io.open(),"open"===this.io._readyState&&this.onopen()),this}open(){return this.connect()}send(...e){return e.unshift("message"),this.emit.apply(this,e),this}emit(e,...t){if(no.hasOwnProperty(e))throw new Error('"'+e.toString()+'" is a reserved event name');if(t.unshift(e),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(t),this;const i={type:Xr.EVENT,data:t,options:{}};if(i.options.compress=!1!==this.flags.compress,"function"==typeof t[t.length-1]){const e=this.ids++,n=t.pop();this._registerAckCallback(e,n),i.id=e}const n=this.io.engine&&this.io.engine.transport&&this.io.engine.transport.writable;return this.flags.volatile&&(!n||!this.connected)||(this.connected?(this.notifyOutgoingListeners(i),this.packet(i)):this.sendBuffer.push(i)),this.flags={},this}_registerAckCallback(e,t){var i;const n=null!==(i=this.flags.timeout)&&void 0!==i?i:this._opts.ackTimeout;if(void 0===n)return void(this.acks[e]=t);const s=this.io.setTimeoutFn((()=>{delete this.acks[e];for(let t=0;t<this.sendBuffer.length;t++)this.sendBuffer[t].id===e&&this.sendBuffer.splice(t,1);t.call(this,new Error("operation has timed out"))}),n);this.acks[e]=(...e)=>{this.io.clearTimeoutFn(s),t.apply(this,[null,...e])}}emitWithAck(e,...t){const i=void 0!==this.flags.timeout||void 0!==this._opts.ackTimeout;return new Promise(((n,s)=>{t.push(((e,t)=>i?e?s(e):n(t):n(e))),this.emit(e,...t)}))}_addToQueue(e){let t;"function"==typeof e[e.length-1]&&(t=e.pop());const i={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push(((e,...n)=>{if(i!==this._queue[0])return;return null!==e?i.tryCount>this._opts.retries&&(this._queue.shift(),t&&t(e)):(this._queue.shift(),t&&t(null,...n)),i.pending=!1,this._drainQueue()})),this._queue.push(i),this._drainQueue()}_drainQueue(e=!1){if(!this.connected||0===this._queue.length)return;const t=this._queue[0];t.pending&&!e||(t.pending=!0,t.tryCount++,this.flags=t.flags,this.emit.apply(this,t.args))}packet(e){e.nsp=this.nsp,this.io._packet(e)}onopen(){"function"==typeof this.auth?this.auth((e=>{this._sendConnectPacket(e)})):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:Xr.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},e):e})}onerror(e){this.connected||this.emitReserved("connect_error",e)}onclose(e,t){this.connected=!1,delete this.id,this.emitReserved("disconnect",e,t)}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case Xr.CONNECT:e.data&&e.data.sid?this.onconnect(e.data.sid,e.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case Xr.EVENT:case Xr.BINARY_EVENT:this.onevent(e);break;case Xr.ACK:case Xr.BINARY_ACK:this.onack(e);break;case Xr.DISCONNECT:this.ondisconnect();break;case Xr.CONNECT_ERROR:this.destroy();const t=new Error(e.data.message);t.data=e.data.data,this.emitReserved("connect_error",t)}}onevent(e){const t=e.data||[];null!=e.id&&t.push(this.ack(e.id)),this.connected?this.emitEvent(t):this.receiveBuffer.push(Object.freeze(t))}emitEvent(e){if(this._anyListeners&&this._anyListeners.length){const t=this._anyListeners.slice();for(const i of t)i.apply(this,e)}super.emit.apply(this,e),this._pid&&e.length&&"string"==typeof e[e.length-1]&&(this._lastOffset=e[e.length-1])}ack(e){const t=this;let i=!1;return function(...n){i||(i=!0,t.packet({type:Xr.ACK,id:e,data:n}))}}onack(e){const t=this.acks[e.id];"function"==typeof t&&(t.apply(this,e.data),delete this.acks[e.id])}onconnect(e,t){this.id=e,this.recovered=t&&this._pid===t,this._pid=t,this.connected=!0,this.emitBuffered(),this.emitReserved("connect"),this._drainQueue(!0)}emitBuffered(){this.receiveBuffer.forEach((e=>this.emitEvent(e))),this.receiveBuffer=[],this.sendBuffer.forEach((e=>{this.notifyOutgoingListeners(e),this.packet(e)})),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach((e=>e())),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:Xr.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(e){return this.flags.compress=e,this}get volatile(){return this.flags.volatile=!0,this}timeout(e){return this.flags.timeout=e,this}onAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(e),this}prependAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(e),this}offAny(e){if(!this._anyListeners)return this;if(e){const t=this._anyListeners;for(let i=0;i<t.length;i++)if(e===t[i])return t.splice(i,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(e),this}prependAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(e),this}offAnyOutgoing(e){if(!this._anyOutgoingListeners)return this;if(e){const t=this._anyOutgoingListeners;for(let i=0;i<t.length;i++)if(e===t[i])return t.splice(i,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(e){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const t=this._anyOutgoingListeners.slice();for(const i of t)i.apply(this,e.data)}}}function ao(e){e=e||{},this.ms=e.min||100,this.max=e.max||1e4,this.factor=e.factor||2,this.jitter=e.jitter>0&&e.jitter<=1?e.jitter:0,this.attempts=0}ao.prototype.duration=function(){var e=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var t=Math.random(),i=Math.floor(t*this.jitter*e);e=0==(1&Math.floor(10*t))?e-i:e+i}return 0|Math.min(e,this.max)},ao.prototype.reset=function(){this.attempts=0},ao.prototype.setMin=function(e){this.ms=e},ao.prototype.setMax=function(e){this.max=e},ao.prototype.setJitter=function(e){this.jitter=e};class ro extends ts{constructor(e,t){var i;super(),this.nsps={},this.subs=[],e&&"object"==typeof e&&(t=e,e=void 0),(t=t||{}).path=t.path||"/socket.io",this.opts=t,rs(this,t),this.reconnection(!1!==t.reconnection),this.reconnectionAttempts(t.reconnectionAttempts||1/0),this.reconnectionDelay(t.reconnectionDelay||1e3),this.reconnectionDelayMax(t.reconnectionDelayMax||5e3),this.randomizationFactor(null!==(i=t.randomizationFactor)&&void 0!==i?i:.5),this.backoff=new ao({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(null==t.timeout?2e4:t.timeout),this._readyState="closed",this.uri=e;const n=t.parser||to;this.encoder=new n.Encoder,this.decoder=new n.Decoder,this._autoConnect=!1!==t.autoConnect,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,this):this._reconnection}reconnectionAttempts(e){return void 0===e?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var t;return void 0===e?this._reconnectionDelay:(this._reconnectionDelay=e,null===(t=this.backoff)||void 0===t||t.setMin(e),this)}randomizationFactor(e){var t;return void 0===e?this._randomizationFactor:(this._randomizationFactor=e,null===(t=this.backoff)||void 0===t||t.setJitter(e),this)}reconnectionDelayMax(e){var t;return void 0===e?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,null===(t=this.backoff)||void 0===t||t.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&0===this.backoff.attempts&&this.reconnect()}open(e){if(~this._readyState.indexOf("open"))return this;this.engine=new zr(this.uri,this.opts);const t=this.engine,i=this;this._readyState="opening",this.skipReconnect=!1;const n=io(t,"open",(function(){i.onopen(),e&&e()})),s=io(t,"error",(t=>{i.cleanup(),i._readyState="closed",this.emitReserved("error",t),e?e(t):i.maybeReconnectOnOpen()}));if(!1!==this._timeout){const e=this._timeout;0===e&&n();const i=this.setTimeoutFn((()=>{n(),t.close(),t.emit("error",new Error("timeout"))}),e);this.opts.autoUnref&&i.unref(),this.subs.push((function(){clearTimeout(i)}))}return this.subs.push(n),this.subs.push(s),this}connect(e){return this.open(e)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const e=this.engine;this.subs.push(io(e,"ping",this.onping.bind(this)),io(e,"data",this.ondata.bind(this)),io(e,"error",this.onerror.bind(this)),io(e,"close",this.onclose.bind(this)),io(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(e){try{this.decoder.add(e)}catch(e){this.onclose("parse error",e)}}ondecoded(e){Mr((()=>{this.emitReserved("packet",e)}),this.setTimeoutFn)}onerror(e){this.emitReserved("error",e)}socket(e,t){let i=this.nsps[e];return i?this._autoConnect&&!i.active&&i.connect():(i=new so(this,e,t),this.nsps[e]=i),i}_destroy(e){const t=Object.keys(this.nsps);for(const e of t){if(this.nsps[e].active)return}this._close()}_packet(e){const t=this.encoder.encode(e);for(let i=0;i<t.length;i++)this.engine.write(t[i],e.options)}cleanup(){this.subs.forEach((e=>e())),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close"),this.engine&&this.engine.close()}disconnect(){return this._close()}onclose(e,t){this.cleanup(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",e,t),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const e=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const t=this.backoff.duration();this._reconnecting=!0;const i=this.setTimeoutFn((()=>{e.skipReconnect||(this.emitReserved("reconnect_attempt",e.backoff.attempts),e.skipReconnect||e.open((t=>{t?(e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",t)):e.onreconnect()})))}),t);this.opts.autoUnref&&i.unref(),this.subs.push((function(){clearTimeout(i)}))}}onreconnect(){const e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",e)}}const oo={};function co(e,t){"object"==typeof e&&(t=e,e=void 0);const i=function(e,t="",i){let n=e;i=i||"undefined"!=typeof location&&location,null==e&&(e=i.protocol+"//"+i.host),"string"==typeof e&&("/"===e.charAt(0)&&(e="/"===e.charAt(1)?i.protocol+e:i.host+e),/^(https?|wss?):\/\//.test(e)||(e=void 0!==i?i.protocol+"//"+e:"https://"+e),n=Ur(e)),n.port||(/^(http|ws)$/.test(n.protocol)?n.port="80":/^(http|ws)s$/.test(n.protocol)&&(n.port="443")),n.path=n.path||"/";const s=-1!==n.host.indexOf(":")?"["+n.host+"]":n.host;return n.id=n.protocol+"://"+s+":"+n.port+t,n.href=n.protocol+"://"+s+(i&&i.port===n.port?"":":"+n.port),n}(e,(t=t||{}).path||"/socket.io"),n=i.source,s=i.id,a=i.path,r=oo[s]&&a in oo[s].nsps;let o;return t.forceNew||t["force new connection"]||!1===t.multiplex||r?o=new ro(n,t):(oo[s]||(oo[s]=new ro(n,t)),o=oo[s]),i.query&&!t.query&&(t.query=i.queryKey),o.socket(i.path,t)}Object.assign(co,{Manager:ro,Socket:so,io:co,connect:co});class po{constructor(e,t){t&&!t.transports&&(t.transports=["websocket"]),this._socket=co(e,t),this._socket.io.on("reconnect",(()=>{this._socket.sendBuffer=[]})),this._socket.io.on("reconnect_attempt",(()=>{this._wasConnectedUsingWebsocket?(this._socket.io.opts.transports=["websocket"],"safari"!==Vn.browserDetails.browser&&delete this._wasConnectedUsingWebsocket):this._socket.io.opts.transports=["polling","websocket"]})),this._socket.on("connect",(()=>{"websocket"===this.getTransport()&&(this._wasConnectedUsingWebsocket=!0)}))}connect(){this.isConnected()||this.isConnecting()||this._socket.open()}disconnect(){this._socket.disconnect()}disconnectOnConnect(){this._socket.once("connect",(()=>{this._socket.disconnect()}))}emit(){this._socket.emit.apply(this._socket,arguments)}emitIfConnected(e,t){this.isConnected()&&this.emit(e,t)}getTransport(){return this._socket&&this._socket.io&&this._socket.io.engine&&this._socket.io.engine.transport&&this._socket.io.engine.transport.name}getManager(){return this._socket.io}isConnecting(){return this._socket&&this._socket.connecting}isConnected(){return this._socket&&this._socket.connected}on(e,t){return this._socket.on(e,t),()=>{this._socket.off(e,t)}}once(e,t){this._socket.once(e,t)}off(e,t){this._socket.off(e,t)}}var lo="connection_blocked_by_network",uo="dominant_speaker";const mo=Vn.browserDetails.browser,ho=Vn.browserDetails.version;function fo(e,t){let i=e.match(/a=ssrc-group:FID (\d+) (\d+)\r\n/),n=t.match(/a=ssrc-group:FID (\d+) (\d+)\r\n/);i||(i=e.match(/a=ssrc:(\d+) cname:(.*)\r\n/g)[1].match(/a=ssrc:(\d+)/),n=t.match(/a=ssrc:(\d+) cname:(.*)\r\n/g)[1].match(/a=ssrc:(\d+)/));for(let e=1;e<i.length;e++)t=t.replace(new RegExp(n[e],"g"),i[e]);return t}function go(e){return"firefox"!==mo?e:jn.splitLines(e.trim()).map((e=>e.startsWith("a=msid-semantic:")?"a=msid-semantic: WMS *":e)).join("\r\n")+"\r\n"}const vo=console;function bo(e,t){const i=e.getSenders().find((e=>e.track&&"video"===e.track.kind));if(!i)return Promise.resolve();const n=i.getParameters();return n.encodings&&0===n.encodings.length?Promise.resolve():(n.encodings||(n.encodings=[{}]),0===t?delete n.encodings[0].maxBitrate:n.encodings[0].maxBitrate=1e3*t,i.setParameters(n).catch((e=>{vo.error("setParameters err: ",e)})))}const _o=console;class yo{constructor({peerConnectionId:e,bandwidth:t,maximumTurnBandwidth:i,deprioritizeH264Encoding:n}){this.peerConnectionId=e,this.relayCandidateSeen=!1,this.pc=null,this.wasEverConnected=!1,this.connectionStatus=null,this.stats={totalSent:0,totalRecv:0},this.bandwidth=t||0,this.maximumTurnBandwidth=i,this.pending=[],this.isOperationPending=!1,this.streamIds=[],this.streams=[],this.earlyIceCandidates=[],this.afterConnected=new Promise((e=>{this.registerConnected=e})),this.offerOptions={offerToReceiveAudio:!0,offerToReceiveVideo:!0},this._deprioritizeH264Encoding=n}setAndGetPeerConnection({clientId:e,constraints:t,peerConnectionConfig:i,shouldAddLocalVideo:n}){return this.peerConnectionConfig=i,this.shouldAddLocalVideo=n,this.clientId=e,this.pc=new RTCPeerConnection(i,t),this.signalingState=this.pc.signalingState,this.pc.addEventListener("signalingstatechange",(()=>{if(this.signalingState!==this.pc.signalingState&&(this.signalingState=this.pc.signalingState,"stable"===this.pc.signalingState)){this.isOperationPending=!1;const e=this.pending.shift();e&&e.apply()}})),this.pc}addStream(e){this.streamIds.push(e.id),this.streams.push(e),RTCPeerConnection.prototype.addTrack?(e.getAudioTracks().forEach((t=>{this.pc.addTrack(t,e)})),e.getVideoTracks().forEach((t=>{this.pc.addTrack(t,e)}))):this.pc.addStream(e)}addTrack(e,t){t||(t=this.streams[0]),t.addTrack(e),this.pc.addTrack(e,t)}removeTrack(e){this.streams[0].removeTrack(e);const t=this.pc.getSenders().find((t=>t.track===e));t&&this.pc.removeTrack(t)}removeStream(e){for(let t=0;t<this.streamIds.length;t++)this.streamIds[t]===e.id&&(this.streamIds.splice(t,1),this.streams.splice(t,1));this.pc&&(this.pc.removeTrack?e.getTracks().forEach((e=>{const t=this.pc.getSenders().find((t=>t.track===e));t&&this.pc.removeTrack(t)})):this.pc.removeStream&&this.pc.removeStream(e))}_setRemoteDescription(e){return this._deprioritizeH264Encoding&&(e.sdp=function(e){return jn.splitSections(e).map((e=>{if("video"!==jn.getKind(e))return e;const t=jn.matchPrefix(e,"a=rtpmap:").map((e=>jn.parseRtpMap(e))).filter((e=>/h264/i.test(e.name))).map((e=>""+e.payloadType));if(!t.length)return e;const i=jn.matchPrefix(e,"m=video")[0],n=/(\s\d+)+$/i.exec(i)[0],s=[...n.split(" ").filter((e=>e&&!t.includes(e))),...t].join(" "),a=i.replace(n," "+s);return e.replace(i,a)})).join("")}(e.sdp)),this.srdComplete=this.pc.setRemoteDescription(e),this.srdComplete.then((()=>{this.earlyIceCandidates.forEach((e=>this.pc.addIceCandidate(e))),this.earlyIceCandidates=[]}))}handleOffer(e){if(!this.canModifyPeerConnection())return new Promise((t=>{this.pending.push((()=>this.handleOffer(e).then(t)))}));this.isOperationPending=!0;let t=e.sdp;t=function(e){return"safari"!==mo&&("firefox"!==mo||ho>=63||60===ho)?e:jn.splitLines(e.trim()).filter((e=>!e.startsWith("a=extmap:")||"urn:ietf:params:rtp-hdrext:sdes:mid"!==jn.parseExtmap(e).uri)).join("\r\n")+"\r\n"}(t),t=go(t);const i={type:e.type,sdp:t};let n;return this._setRemoteDescription(i).then((()=>this.pc.createAnswer())).then((e=>(n=e,this.pc.setLocalDescription(e)))).then((()=>bo(this.pc,this.bandwidth))).then((()=>n))}handleAnswer(e){if(this.pendingOffer){const t=this.pendingOffer;return delete this.pendingOffer,this.pc.setLocalDescription(t).then((()=>this.handleAnswer(e)))}let t=e.sdp;t=go(t);const i={type:e.type,sdp:t};return this._setRemoteDescription(i).then((()=>bo(this.pc,this.bandwidth)),(e=>{_o.warn("Could not set remote description from remote answer: ",e)}))}addIceCandidate(e){this.srdComplete?this.srdComplete.then((()=>{"closed"!==this.pc.signalingState&&("safari"===Vn.browserDetails.browser&&e&&""===e.candidate||this.pc.addIceCandidate(e).catch((t=>{_o.warn("Failed to add ICE candidate ('%s'): %s",e?e.candidate:null,t)})))})):this.earlyIceCandidates.push(e)}canModifyPeerConnection(){return"stable"===this.pc.signalingState&&!this.isOperationPending}close(){const e=this.pc;if(e){e.oniceconnectionstatechange=null,e.onicecandidate=null,e.ontrack=null;try{e.close()}catch(e){console.warn("failures during close of session",e)}}}hasConnectedPeerConnection(){return this.pc&&"connected"===this.pc.connectionState}replaceTrack(e,t){const i=this.pc;if(!i)return!1;const n=i.getSenders();function s(i){const s=e=>e&&`id:${e.id},kind:${e.kind},state:${e.readyState}`;_o.warn(`${i}. newTrack:${s(t)}, oldTrack:${s(e)}, sender tracks: ${JSON.stringify(n.map((e=>`s ${s(e.track)}`)))}, sender first codecs: ${JSON.stringify(n.map((e=>(e.getParameters().codecs||[])[0])))}`)}if(n.length||s("No senders!"),e||(e=(n.find((e=>e.track&&e.track.kind===t.kind))||{}).track)||s("No sender with same kind! Add new track then."),window.RTCRtpSender&&window.RTCRtpSender.prototype.replaceTrack){if(e){const i=()=>{for(let i=0;i<n.length;i++){const a=n[i],r=a.track;if(a||r||s("One of the tracks is null!"),r.id===t.id)return Promise.resolve(t);if(r.id===e.id)return n[i].replaceTrack(t)}return null};let a=i();if(a)return a;let r=null,o=null;a=new Promise(((e,t)=>{r=e,o=t}));let c=0,p=setInterval((async()=>{const e=i();if(!e)return void(3<++c&&(clearInterval(p),p=null,s("No sender track to replace"),o("No sender track to replace")));clearInterval(p),p=null;const t=await e;r(t)}),1e3);return a}const a=this.streams.find((e=>e.getTracks().find((e=>e.id===t.id))))||this.streams[0];return a?i.addTrack(t,a):(s("No stream?"),Promise.reject(new Error("replaceTrack: No stream?")))}if(!this.canModifyPeerConnection())return void this.pending.push((()=>{this.replaceTrack(e,t)}));this.isOperationPending=!0;const a=i.onnegotiationneeded;return i.onnegotiationneeded=null,this.removeTrack(e),this.addTrack(t),setTimeout((()=>{i.onnegotiationneeded=a}),0),"offer"===i.localDescription.type?i.createOffer().then((e=>(e.sdp=fo(i.localDescription.sdp,e.sdp),i.setLocalDescription(e)))).then((()=>this._setRemoteDescription(i.remoteDescription))):this._setRemoteDescription(i.remoteDescription).then((()=>i.createAnswer())).then((e=>(e.sdp=fo(i.localDescription.sdp,e.sdp),i.setLocalDescription(e))))}maybeRestrictRelayBandwidth(){var e;this.pc.getStats&&(e=this.pc,e.getStats(null).then((e=>{let t,i;return e.forEach((n=>{if("transport"===n.type&&n.selectedCandidatePairId){const s=e.get(n.selectedCandidatePairId);if(!s)return;return t=e.get(s.localCandidateId).candidateType,void(i=e.get(s.remoteCandidateId).candidateType)}"candidate-pair"===n.type&&n.selected&&(t=e.get(n.localCandidateId).candidateType,i=e.get(n.remoteCandidateId).candidateType)})),"relay"===t||"relayed"===t||"relay"===i||"relayed"===i}))).then((e=>{e&&0===this.bandwidth&&this.changeBandwidth(this.maximumTurnBandwidth)}))}changeBandwidth(e){e!==this.bandwidth&&(this.canModifyPeerConnection()?(this.bandwidth=e,this.pc.localDescription&&""!==this.pc.localDescription.type&&bo(this.pc,this.bandwidth)):this.pending.push((()=>this.changeBandwidth(e))))}}process.env.AWF_BASE_URL,process.env.AWF_API_BASE_URL,process.env.AP_ROOM_BASE_URL;const xo=console,wo=Vn.browserDetails.browser,So=Vn.browserDetails.version;const Ro=console,Co=Vn.browserDetails.browser;class ko extends class{constructor({selfId:e,room:t,emitter:i,serverSocket:n,webrtcProvider:s,features:a}){u.ok(e,"selfId is required"),u.ok(t,"room is required"),u.ok(i&&i.emit,"emitter is required"),u.ok(n instanceof po,"serverSocket is required"),u.ok(s,"webrtcProvider is required");const{name:r,session:o,iceServers:c,sfuServer:p,mediaserverConfigTtlSeconds:d}=t;this._selfId=e,this._roomName=r,this._roomSessionId=o&&o.id,this.peerConnections={},this.localStreams={},this.enabledLocalStreamIds=[],this._socketListenerDeregisterFunctions=[],this._emitter=i,this._serverSocket=n,this._webrtcProvider=s,this._features=a||{},this.offerOptions={offerToReceiveAudio:!0,offerToReceiveVideo:!0},this._pendingActionsForConnectedPeerConnections=[],this._updateAndScheduleMediaServersRefresh({sfuServer:p,iceServers:c.iceServers||[],mediaserverConfigTtlSeconds:d})}numberOfPeerconnections(){return Object.keys(this.peerConnections).length}numberOfRemotePeers(){return Object.values(this.peerConnections).filter((e=>e.clientId!==this._selfId)).length}_setConnectionStatus(e,t,i){const n=e.connectionStatus;n!==t&&e.peerConnectionId!==this._selfId&&(n===Pi&&t===Ci||(e.connectionStatus=t,setTimeout((()=>{this._emit(_i,{streamIds:e.streamIds,clientId:i,status:t,previous:n})}),0)))}_emitServerEvent(e,t,i){this._serverSocket.emit(e,t,i)}_emit(e,t){this._emitter.emit(e,t)}isInitializedWith({selfId:e,roomName:t,isSfu:i}){return this._selfId===e&&this._roomName===t&&i===!!this._sfuServer}supportsScreenShareAudio(){return!0}_addEnabledLocalStreamId(e){this.enabledLocalStreamIds.push(e)}_deleteEnabledLocalStreamId(e){const t=this.enabledLocalStreamIds.indexOf(e);-1!==t&&this.enabledLocalStreamIds.splice(t,1)}_getSession(e){return e in this.peerConnections?this.peerConnections[e]:null}_getOrCreateSession(e,t){let i=this.peerConnections[e];if(void 0===i){const n="safari"===wo&&So>=14&&this._features.deprioritizeH264OnSafari;this.peerConnections[e]=i=new yo({peerConnectionId:e,bandwidth:t,maximumTurnBandwidth:this._features.restrictBandwidthWhenUsingRelay?512:768,deprioritizeH264Encoding:n})}return i}_getLocalCameraStream(){return this.localStreams[0]}_getNonLocalCameraStreamIds(){return Object.keys(this.localStreams).filter((e=>"0"!==e))}_isScreensharingLocally(){return this._getNonLocalCameraStreamIds().length>0}_getFirstLocalNonCameraStream(){const e=this._getNonLocalCameraStreamIds();return 0===e.length?null:this.localStreams[e[0]]}_transformIncomingSdp(e){return{type:e.type,sdp:e.sdpU}}_transformOutgoingSdp(e){return{type:e.type,sdpU:e.sdp}}_createSession({clientId:e,initialBandwidth:t,isOfferer:i,peerConnectionId:n,shouldAddLocalVideo:s}){if(!n)throw new Error("peerConnectionId is missing");if(!e)throw new Error("clientId is missing");const a=this._getOrCreateSession(n,t),r={optional:[]};"chrome"===wo&&r.optional.push({googCpuOveruseDetection:!0});const o={iceServers:this._iceServers};if(this._features.turnServerOverrideHost){const e=this._features.turnServerOverrideHost,t=e.indexOf(":")>0?"":":443",i=":"+e+t;o.iceServers=o.iceServers.map((e=>{const t=Object.assign({},e);return t.url&&(t.url=t.url.replace(/:[^?]*/,i)),t.urls&&(t.urls=t.urls.map((e=>e.replace(/:[^?]*/,i)))),t}))}if(this._features.useOnlyTURN){o.iceTransportPolicy="relay";const e={onlyudp:/^turn:.*transport=udp$/,onlytcp:/^turn:.*transport=tcp$/,onlytls:/^turns:.*transport=tcp$/}[this._features.useOnlyTURN];e&&(o.iceServers=o.iceServers.filter((t=>t.url&&t.url.match(e))))}"chrome"===wo&&(o.sdpSemantics="unified-plan");const c=a.setAndGetPeerConnection({constraints:r,peerConnectionConfig:o,shouldAddLocalVideo:s,clientId:e});c.ontrack=t=>{const i=t.streams[0];"default"===i.id&&0===i.getAudioTracks().length||-1===a.streamIds.indexOf(i.id)&&(a.streamIds.push(i.id),this._emit(yi,{clientId:e,stream:i}),a.connectionStatus===Ti&&setTimeout((()=>{this._emit(_i,{streamIds:a.streamIds,clientId:e,status:a.connectionStatus,previous:Ci})}),0))},c.oniceconnectionstatechange=()=>{let t;const i=a.connectionStatus;switch(c.iceConnectionState){case"checking":t=Ci;break;case"connected":case"completed":t=Ti,a.wasEverConnected||(this._pendingActionsForConnectedPeerConnections.forEach((e=>{"function"==typeof e&&e()})),this._pendingActionsForConnectedPeerConnections=[]),!a.wasEverConnected&&(c.iceConnectionState.match(/connected|completed/)||"chrome"===wo&&c.localDescription&&"answer"===c.localDescription.type)&&(a.wasEverConnected=!0,"false"!==this._features.bandwidth&&this.maybeRestrictRelayBandwidth(a)),a.registerConnected();break;case"disconnected":t=Pi,setTimeout((()=>{"disconnected"===c.iceConnectionState&&this._maybeRestartIce(e,a)}),2e3);break;case"failed":t=ki,i!==t&&this._maybeRestartIce(e,a),null!==a.relayCandidateSeen||a.wasEverConnected||this._emit(lo);break;default:return}this._setConnectionStatus(a,t,e)},c.onconnectionstate=()=>{switch(c.connectionState){case"connected":a.registerConnected();break;case"failed":const t=ki;null!==a.relayCandidateSeen||a.wasEverConnected||this._emit(lo),this._setConnectionStatus(a,t,e)}};const p=this.localStreams[0];return s&&p&&a.addStream(p),s&&Object.keys(this.localStreams).forEach((e=>{if("0"===e)return;const t=this.localStreams[e];i?a.addStream(t):a.afterConnected.then((()=>{this._emitServerEvent(Oi,{receiverId:a.clientId,streamId:t.id,hasAudioTrack:!!t.getAudioTracks().length}),this._withForcedRenegotiation(a,(()=>a.addStream(t)))}))})),a}_cleanup(e){const t=this._getSession(e);t?(t.close(),delete this.peerConnections[e]):xo.warn("No RTCPeerConnection in RTCManager.disconnect()",e)}_forEachPeerConnection(e){Object.keys(this.peerConnections).forEach((t=>{const i=this.peerConnections[t];e(i)}))}_addStreamToPeerConnections(e){this._forEachPeerConnection((t=>{this._withForcedRenegotiation(t,(()=>t.addStream(e)))}))}_addTrackToPeerConnections(e,t){this._forEachPeerConnection((i=>{this._withForcedRenegotiation(i,(()=>i.addTrack(e,t)))}))}_replaceTrackToPeerConnections(e,t){const i=[];return this._forEachPeerConnection((n=>{if(!n.hasConnectedPeerConnection()){xo.log("Session doesn't have a connected PeerConnection, adding pending action!");const s=this._pendingActionsForConnectedPeerConnections;if(!s)return void xo.warn("No pending action is created to repalce track, because the pending actions array is null");const a=new Promise(((i,a)=>{s.push((()=>{const s=n.replaceTrack(e,t);if(!s)return xo.error("replaceTrack returned false!"),void a("ReplaceTrack returned false");s.then((e=>i(e))).catch((e=>a(e)))}))}));return void i.push(a)}const s=n.replaceTrack(e,t);s?i.push(s):xo.error("replaceTrack returned false!")})),Promise.all(i)}_removeStreamFromPeerConnections(e){this._forEachPeerConnection((t=>{this._withForcedRenegotiation(t,(()=>t.removeStream(e)))}))}_removeTrackFromPeerConnections(e){this._forEachPeerConnection((t=>{this._withForcedRenegotiation(t,(()=>t.removeTrack(e)))}))}_addLocalStream(e,t){this._addEnabledLocalStreamId(e),this.localStreams[e]=t}_removeLocalStream(e){delete this.localStreams[e],this._deleteEnabledLocalStreamId(e)}maybeRestrictRelayBandwidth(e){e.maybeRestrictRelayBandwidth()}addNewStream(e,t){t!==this.localStreams[e]&&(this._addLocalStream(e,t),"0"!==e?this._shareScreen(e,t):this._addStreamToPeerConnections(t))}removeStream(e,t){this._removeLocalStream(e,t)}replaceTrack(e,t){return this._replaceTrackToPeerConnections(e,t)}accept({clientId:e,shouldAddLocalVideo:t}){return this.acceptNewStream({streamId:e,clientId:e,shouldAddLocalVideo:t})}disconnectAll(){Object.keys(this.peerConnections).forEach((e=>{this.disconnect(e)})),this.peerConnections={},this._socketListenerDeregisterFunctions.forEach((e=>{e()})),this._socketListenerDeregisterFunctions=[]}stopOrResumeAudio(){}stopOrResumeVideo(){}fixChromeAudio(e){if("chrome"!==wo)return;const t=this._getLocalCameraStream(),i=t.getAudioTracks()[0];return i&&"ended"===i.readyState?navigator.mediaDevices.getUserMedia({audio:e}).then((e=>{const n=e.getAudioTracks()[0];return n.enabled=i.enabled,t.removeTrack(i),t.addTrack(n),this.replaceTrack(i,n)})):void 0}_updateAndScheduleMediaServersRefresh({iceServers:e,sfuServer:t,mediaserverConfigTtlSeconds:i}){this._iceServers=e,this._sfuServer=t,this._mediaserverConfigTtlSeconds=i,this._clearMediaServersRefresh(),i&&(this._fetchMediaServersTimer=setTimeout((()=>this._emitServerEvent(Ei)),1e3*i))}_clearMediaServersRefresh(){this._fetchMediaServersTimer&&(clearTimeout(this._fetchMediaServersTimer),this._fetchMediaServersTimer=null)}setupSocketListeners(){this._socketListenerDeregisterFunctions=[()=>this._clearMediaServersRefresh(),this._serverSocket.on(Ii,(e=>{e.error?xo.warn("FETCH_MEDIASERVER_CONFIG failed:",e.error):this._updateAndScheduleMediaServersRefresh(e)})),this._serverSocket.on(Ai,(e=>{this._connect(e.clientId)})),this._serverSocket.on(Li,(e=>{const t=this._getSession(e.clientId);t?t.addIceCandidate(e.message):xo.warn("No RTCPeerConnection on ICE_CANDIDATE",e)})),this._serverSocket.on(Mi,(e=>{const t=this._getSession(e.clientId);t?t.addIceCandidate(null):xo.warn("No RTCPeerConnection on ICE_END_OF_CANDIDATES",e)})),this._serverSocket.on(Bi,(e=>{const t=this._getSession(e.clientId);if(!t)return void xo.warn("No RTCPeerConnection on SDP_OFFER",e);const i=this._transformIncomingSdp(e.message,t.pc);t.handleOffer(i).then((t=>{this._emitServerEvent(Ni,{receiverId:e.clientId,message:this._transformOutgoingSdp(t)})}))})),this._serverSocket.on(Ni,(e=>{const t=this._getSession(e.clientId);if(!t)return void xo.warn("No RTCPeerConnection on SDP_ANSWER",e);const i=this._transformIncomingSdp(e.message,t.pc);t.handleAnswer(i)}))]}setRoomSessionId(e){this._roomSessionId=e}}{_connect(e){let t=this._getSession(e),i=t&&t.bandwidth||0;return t?(Ro.warn("Replacing peer session",e),this._cleanup(e)):i=this._changeBandwidthForAllClients(!0),t=this._createP2pSession(e,i,!0,!0),this._negotiatePeerConnection(e,t),Promise.resolve(t)}_maybeRestartIce(e,t){const i=t.pc;"disconnected"!==i.iceConnectionState&&"failed"!==i.iceConnectionState||"offer"===i.localDescription.type&&(t.wasEverConnected=!1,t.relayCandidateSeen=!1,this._negotiatePeerConnection(e,t,Object.assign({},this.offerOptions,{iceRestart:!0})))}_negotiatePeerConnection(e,t,i){if(!t)return void Ro.warn("No RTCPeerConnection in negotiatePeerConnection()",e);const n=t.pc;t.canModifyPeerConnection()?(t.isOperationPending=!0,n.createOffer(i||this.offerOptions).then((i=>{this._emitServerEvent(Bi,{receiverId:e,message:this._transformOutgoingSdp(i)}),"chrome"===Co&&n.getSenders().filter((e=>e.track&&"video"===e.track.kind)).length>=2?t.pendingOffer=i:n.setLocalDescription(i).catch((e=>{Ro.warn("RTCPeerConnection.setLocalDescription() failed with local offer",e)}))})).catch((e=>{Ro.warn("RTCPeerConnection.createOffer() failed to create local offer",e)}))):t.pending.push((()=>{this._negotiatePeerConnection(e,t,i)}))}_withForcedRenegotiation(e,t){const i=e.pc,n=i.onnegotationneeded;i.onnegotiationneeded=null,t(),this._negotiatePeerConnection(e.clientId,e),setTimeout((()=>i.onnegotiationneeded=n),0)}_changeBandwidthForAllClients(e){let t=this.numberOfPeerconnections();if(e&&(t+=1),0===t)return 0;t>7&&(t=7);const i=this._features.bandwidth?parseInt(this._features.bandwidth,10):{1:0,2:this._features.highP2PBandwidth?768:384,3:this._features.highP2PBandwidth?512:256,4:192,5:128,6:128,7:64}[t];return void 0===i?0:(this._forEachPeerConnection((e=>{e.changeBandwidth(i)})),i)}_createP2pSession(e,t,i,n){const s=this._createSession({peerConnectionId:e,clientId:e,initialBandwidth:t,shouldAddLocalVideo:i,isOfferer:n}),a=s.pc,r=this.localStreams[0];return i&&r&&!r.getVideoTracks().length&&this._stoppedVideoTrack&&a.addTrack(this._stoppedVideoTrack,r),a.onicecandidate=t=>{t.candidate?(s.relayCandidateSeen=s.relayCandidateSeen||"relay"===t.candidate.type,this._emitServerEvent(Li,{receiverId:e,message:t.candidate})):this._emitServerEvent(Mi,{receiverId:e})},a.onnegotiationneeded=()=>{"new"!==a.iceConnectionState&&s.connectionStatus&&this._negotiatePeerConnection(e,s)},s}acceptNewStream({streamId:e,clientId:t,shouldAddLocalVideo:i}){let n=this._getSession(t);if(n&&e!==t)return n;let s=n&&n.bandwidth||0;return n?(Ro.warn("Replacing peer session",t),this._cleanup(t)):s=this._changeBandwidthForAllClients(!0),n=this._createP2pSession(t,s,i),this._emitServerEvent(Ai,{receiverId:t}),n}disconnect(e){this._cleanup(e),this._changeBandwidthForAllClients(!1);0===this.numberOfPeerconnections()&&setTimeout((()=>{this.numberOfPeerconnections()}),6e4)}updateStreamResolution(){}stopOrResumeAudio(){}stopOrResumeVideo(e,t){if("chrome"===Co)if(!1===t)setTimeout((()=>{e.getVideoTracks().forEach((t=>{!1===t.enabled&&(t.stop(),e.removeTrack(t),this._emit(Ri,{stream:e,track:t}),this._stoppedVideoTrack=t)}))}),5e3);else if(this._features.simplifiedVegaClientOn){const t=e.getVideoTracks()?.[0];this._stoppedVideoTrack?(this._replaceTrackToPeerConnections(this._stoppedVideoTrack,t),delete this._stoppedVideoTrack,this._emit(Si,{streamId:e.id,tracks:[t],screenShare:!1})):t||this._addTrackToPeerConnections(t)}else if(0===e.getVideoTracks().length){const t=this._webrtcProvider.getMediaConstraints().video;if(!t)return;navigator.mediaDevices.getUserMedia({video:t}).then((t=>{const i=t.getVideoTracks()[0];e.addTrack(i),this._emit(Si,{streamId:e.id,tracks:[i],screenShare:!1}),this._stoppedVideoTrack?(this._replaceTrackToPeerConnections(this._stoppedVideoTrack,i),delete this._stoppedVideoTrack):this._addTrackToPeerConnections(i)}))}}_shareScreen(e,t){this._emitServerEvent(Oi,{streamId:e,hasAudioTrack:!!t.getAudioTracks().length}),this._addStreamToPeerConnections(t)}removeStream(e,t,i){super.removeStream(e,t),this._removeStreamFromPeerConnections(t),this._emitServerEvent(Di,{streamId:e,requestedByClientId:i})}}var To,Po,Eo,Oo,Do,Io={},jo={},Lo={},Mo={get exports(){return Lo},set exports(e){Lo=e}};function Ao(){if(Po)return To;Po=1;var e=1e3,t=60*e,i=60*t,n=24*i,s=7*n,a=365.25*n;function r(e,t,i,n){var s=t>=1.5*i;return Math.round(e/i)+" "+n+(s?"s":"")}return To=function(o,c){c=c||{};var p=typeof o;if("string"===p&&o.length>0)return function(r){if((r=String(r)).length>100)return;var o=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(r);if(!o)return;var c=parseFloat(o[1]);switch((o[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return c*a;case"weeks":case"week":case"w":return c*s;case"days":case"day":case"d":return c*n;case"hours":case"hour":case"hrs":case"hr":case"h":return c*i;case"minutes":case"minute":case"mins":case"min":case"m":return c*t;case"seconds":case"second":case"secs":case"sec":case"s":return c*e;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return c;default:return}}(o);if("number"===p&&isFinite(o))return c.long?function(s){var a=Math.abs(s);if(a>=n)return r(s,a,n,"day");if(a>=i)return r(s,a,i,"hour");if(a>=t)return r(s,a,t,"minute");if(a>=e)return r(s,a,e,"second");return s+" ms"}(o):function(s){var a=Math.abs(s);if(a>=n)return Math.round(s/n)+"d";if(a>=i)return Math.round(s/i)+"h";if(a>=t)return Math.round(s/t)+"m";if(a>=e)return Math.round(s/e)+"s";return s+"ms"}(o);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(o))}}function No(){if(Oo)return Eo;return Oo=1,Eo=function(e){function t(e){let n,s,a,r=null;function o(...e){if(!o.enabled)return;const i=o,s=Number(new Date),a=s-(n||s);i.diff=a,i.prev=n,i.curr=s,n=s,e[0]=t.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let r=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,((n,s)=>{if("%%"===n)return"%";r++;const a=t.formatters[s];if("function"==typeof a){const t=e[r];n=a.call(i,t),e.splice(r,1),r--}return n})),t.formatArgs.call(i,e);(i.log||t.log).apply(i,e)}return o.namespace=e,o.useColors=t.useColors(),o.color=t.selectColor(e),o.extend=i,o.destroy=t.destroy,Object.defineProperty(o,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==r?r:(s!==t.namespaces&&(s=t.namespaces,a=t.enabled(e)),a),set:e=>{r=e}}),"function"==typeof t.init&&t.init(o),o}function i(e,i){const n=t(this.namespace+(void 0===i?":":i)+e);return n.log=this.log,n}function n(e){return e.toString().substring(2,e.toString().length-2).replace(/\.\*\?$/,"*")}return t.debug=t,t.default=t,t.coerce=function(e){if(e instanceof Error)return e.stack||e.message;return e},t.disable=function(){const e=[...t.names.map(n),...t.skips.map(n).map((e=>"-"+e))].join(",");return t.enable(""),e},t.enable=function(e){let i;t.save(e),t.namespaces=e,t.names=[],t.skips=[];const n=("string"==typeof e?e:"").split(/[\s,]+/),s=n.length;for(i=0;i<s;i++)n[i]&&("-"===(e=n[i].replace(/\*/g,".*?"))[0]?t.skips.push(new RegExp("^"+e.slice(1)+"$")):t.names.push(new RegExp("^"+e+"$")))},t.enabled=function(e){if("*"===e[e.length-1])return!0;let i,n;for(i=0,n=t.skips.length;i<n;i++)if(t.skips[i].test(e))return!1;for(i=0,n=t.names.length;i<n;i++)if(t.names[i].test(e))return!0;return!1},t.humanize=Ao(),t.destroy=function(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")},Object.keys(e).forEach((i=>{t[i]=e[i]})),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){let i=0;for(let t=0;t<e.length;t++)i=(i<<5)-i+e.charCodeAt(t),i|=0;return t.colors[Math.abs(i)%t.colors.length]},t.enable(t.load()),t},Eo}var Bo,Fo,Uo,zo,qo,$o={},Vo={get exports(){return $o},set exports(e){$o=e}};function Wo(){return Fo?Bo:(Fo=1,Bo=(e,t=process.argv)=>{const i=e.startsWith("-")?"":1===e.length?"-":"--",n=t.indexOf(i+e),s=t.indexOf("--");return-1!==n&&(-1===s||n<s)})}function Go(){return qo||(qo=1,function(e,t){const i=m,n=h;t.init=function(e){e.inspectOpts={};const i=Object.keys(t.inspectOpts);for(let n=0;n<i.length;n++)e.inspectOpts[i[n]]=t.inspectOpts[i[n]]},t.log=function(...e){return process.stderr.write(n.format(...e)+"\n")},t.formatArgs=function(i){const{namespace:n,useColors:s}=this;if(s){const t=this.color,s="[3"+(t<8?t:"8;5;"+t),a=` ${s};1m${n} `;i[0]=a+i[0].split("\n").join("\n"+a),i.push(s+"m+"+e.exports.humanize(this.diff)+"")}else i[0]=function(){if(t.inspectOpts.hideDate)return"";return(new Date).toISOString()+" "}()+n+" "+i[0]},t.save=function(e){e?process.env.DEBUG=e:delete process.env.DEBUG},t.load=function(){return process.env.DEBUG},t.useColors=function(){return"colors"in t.inspectOpts?Boolean(t.inspectOpts.colors):i.isatty(process.stderr.fd)},t.destroy=n.deprecate((()=>{}),"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."),t.colors=[6,2,3,4,5,1];try{const e=function(){if(zo)return Uo;zo=1;const e=f,t=m,i=Wo(),{env:n}=process;let s;function a(e){return 0!==e&&{level:e,hasBasic:!0,has256:e>=2,has16m:e>=3}}function r(t,a){if(0===s)return 0;if(i("color=16m")||i("color=full")||i("color=truecolor"))return 3;if(i("color=256"))return 2;if(t&&!a&&void 0===s)return 0;const r=s||0;if("dumb"===n.TERM)return r;if("win32"===process.platform){const t=e.release().split(".");return Number(t[0])>=10&&Number(t[2])>=10586?Number(t[2])>=14931?3:2:1}if("CI"in n)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE"].some((e=>e in n))||"codeship"===n.CI_NAME?1:r;if("TEAMCITY_VERSION"in n)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(n.TEAMCITY_VERSION)?1:0;if("truecolor"===n.COLORTERM)return 3;if("TERM_PROGRAM"in n){const e=parseInt((n.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(n.TERM_PROGRAM){case"iTerm.app":return e>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(n.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(n.TERM)||"COLORTERM"in n?1:r}return i("no-color")||i("no-colors")||i("color=false")||i("color=never")?s=0:(i("color")||i("colors")||i("color=true")||i("color=always"))&&(s=1),"FORCE_COLOR"in n&&(s="true"===n.FORCE_COLOR?1:"false"===n.FORCE_COLOR?0:0===n.FORCE_COLOR.length?1:Math.min(parseInt(n.FORCE_COLOR,10),3)),Uo={supportsColor:function(e){return a(r(e,e&&e.isTTY))},stdout:a(r(!0,t.isatty(1))),stderr:a(r(!0,t.isatty(2)))},Uo}();e&&(e.stderr||e).level>=2&&(t.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221])}catch(e){}t.inspectOpts=Object.keys(process.env).filter((e=>/^debug_/i.test(e))).reduce(((e,t)=>{const i=t.substring(6).toLowerCase().replace(/_([a-z])/g,((e,t)=>t.toUpperCase()));let n=process.env[t];return n=!!/^(yes|on|true|enabled)$/i.test(n)||!/^(no|off|false|disabled)$/i.test(n)&&("null"===n?null:Number(n)),e[i]=n,e}),{}),e.exports=No()(t);const{formatters:s}=e.exports;s.o=function(e){return this.inspectOpts.colors=this.useColors,n.inspect(e,this.inspectOpts).split("\n").map((e=>e.trim())).join(" ")},s.O=function(e){return this.inspectOpts.colors=this.useColors,n.inspect(e,this.inspectOpts)}}(Vo,$o)),$o}!function(e){"undefined"==typeof process||"renderer"===process.type||!0===process.browser||process.__nwjs?e.exports=(Do||(Do=1,function(e,t){t.formatArgs=function(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;const i="color: "+this.color;t.splice(1,0,i,"color: inherit");let n=0,s=0;t[0].replace(/%[a-zA-Z%]/g,(e=>{"%%"!==e&&(n++,"%c"===e&&(s=n))})),t.splice(s,0,i)},t.save=function(e){try{e?t.storage.setItem("debug",e):t.storage.removeItem("debug")}catch(e){}},t.load=function(){let e;try{e=t.storage.getItem("debug")}catch(e){}return!e&&"undefined"!=typeof process&&"env"in process&&(e=process.env.DEBUG),e},t.useColors=function(){return!("undefined"==typeof window||!window.process||"renderer"!==window.process.type&&!window.process.__nwjs)||("undefined"==typeof navigator||!navigator.userAgent||!navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))&&("undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/))},t.storage=function(){try{return localStorage}catch(e){}}(),t.destroy=(()=>{let e=!1;return()=>{e||(e=!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"],t.log=console.debug||console.log||(()=>{}),e.exports=No()(t);const{formatters:i}=e.exports;i.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}(Mo,Lo)),Lo):e.exports=Go()}({get exports(){return jo},set exports(e){jo=e}});var Ho={};const Ko={"Amazon Silk":"amazon_silk","Android Browser":"android",Bada:"bada",BlackBerry:"blackberry",Chrome:"chrome",Chromium:"chromium",Electron:"electron",Epiphany:"epiphany",Firefox:"firefox",Focus:"focus",Generic:"generic","Google Search":"google_search",Googlebot:"googlebot","Internet Explorer":"ie","K-Meleon":"k_meleon",Maxthon:"maxthon","Microsoft Edge":"edge","MZ Browser":"mz","NAVER Whale Browser":"naver",Opera:"opera","Opera Coast":"opera_coast",PhantomJS:"phantomjs",Puffin:"puffin",QupZilla:"qupzilla",QQ:"qq",QQLite:"qqlite",Safari:"safari",Sailfish:"sailfish","Samsung Internet for Android":"samsung_internet",SeaMonkey:"seamonkey",Sleipnir:"sleipnir",Swing:"swing",Tizen:"tizen","UC Browser":"uc",Vivaldi:"vivaldi","WebOS Browser":"webos",WeChat:"wechat","Yandex Browser":"yandex",Roku:"roku"},Jo={amazon_silk:"Amazon Silk",android:"Android Browser",bada:"Bada",blackberry:"BlackBerry",chrome:"Chrome",chromium:"Chromium",electron:"Electron",epiphany:"Epiphany",firefox:"Firefox",focus:"Focus",generic:"Generic",googlebot:"Googlebot",google_search:"Google Search",ie:"Internet Explorer",k_meleon:"K-Meleon",maxthon:"Maxthon",edge:"Microsoft Edge",mz:"MZ Browser",naver:"NAVER Whale Browser",opera:"Opera",opera_coast:"Opera Coast",phantomjs:"PhantomJS",puffin:"Puffin",qupzilla:"QupZilla",qq:"QQ Browser",qqlite:"QQ Browser Lite",safari:"Safari",sailfish:"Sailfish",samsung_internet:"Samsung Internet for Android",seamonkey:"SeaMonkey",sleipnir:"Sleipnir",swing:"Swing",tizen:"Tizen",uc:"UC Browser",vivaldi:"Vivaldi",webos:"WebOS Browser",wechat:"WeChat",yandex:"Yandex Browser"},Qo={tablet:"tablet",mobile:"mobile",desktop:"desktop",tv:"tv"},Yo={WindowsPhone:"Windows Phone",Windows:"Windows",MacOS:"macOS",iOS:"iOS",Android:"Android",WebOS:"WebOS",BlackBerry:"BlackBerry",Bada:"Bada",Tizen:"Tizen",Linux:"Linux",ChromeOS:"Chrome OS",PlayStation4:"PlayStation 4",Roku:"Roku"},Xo={EdgeHTML:"EdgeHTML",Blink:"Blink",Trident:"Trident",Presto:"Presto",Gecko:"Gecko",WebKit:"WebKit"};class Zo{static getFirstMatch(e,t){const i=t.match(e);return i&&i.length>0&&i[1]||""}static getSecondMatch(e,t){const i=t.match(e);return i&&i.length>1&&i[2]||""}static matchAndReturnConst(e,t,i){if(e.test(t))return i}static getWindowsVersionName(e){switch(e){case"NT":return"NT";case"XP":case"NT 5.1":return"XP";case"NT 5.0":return"2000";case"NT 5.2":return"2003";case"NT 6.0":return"Vista";case"NT 6.1":return"7";case"NT 6.2":return"8";case"NT 6.3":return"8.1";case"NT 10.0":return"10";default:return}}static getMacOSVersionName(e){const t=e.split(".").splice(0,2).map((e=>parseInt(e,10)||0));if(t.push(0),10===t[0])switch(t[1]){case 5:return"Leopard";case 6:return"Snow Leopard";case 7:return"Lion";case 8:return"Mountain Lion";case 9:return"Mavericks";case 10:return"Yosemite";case 11:return"El Capitan";case 12:return"Sierra";case 13:return"High Sierra";case 14:return"Mojave";case 15:return"Catalina";default:return}}static getAndroidVersionName(e){const t=e.split(".").splice(0,2).map((e=>parseInt(e,10)||0));if(t.push(0),!(1===t[0]&&t[1]<5))return 1===t[0]&&t[1]<6?"Cupcake":1===t[0]&&t[1]>=6?"Donut":2===t[0]&&t[1]<2?"Eclair":2===t[0]&&2===t[1]?"Froyo":2===t[0]&&t[1]>2?"Gingerbread":3===t[0]?"Honeycomb":4===t[0]&&t[1]<1?"Ice Cream Sandwich":4===t[0]&&t[1]<4?"Jelly Bean":4===t[0]&&t[1]>=4?"KitKat":5===t[0]?"Lollipop":6===t[0]?"Marshmallow":7===t[0]?"Nougat":8===t[0]?"Oreo":9===t[0]?"Pie":void 0}static getVersionPrecision(e){return e.split(".").length}static compareVersions(e,t,i=!1){const n=Zo.getVersionPrecision(e),s=Zo.getVersionPrecision(t);let a=Math.max(n,s),r=0;const o=Zo.map([e,t],(e=>{const t=a-Zo.getVersionPrecision(e),i=e+new Array(t+1).join(".0");return Zo.map(i.split("."),(e=>new Array(20-e.length).join("0")+e)).reverse()}));for(i&&(r=a-Math.min(n,s)),a-=1;a>=r;){if(o[0][a]>o[1][a])return 1;if(o[0][a]===o[1][a]){if(a===r)return 0;a-=1}else if(o[0][a]<o[1][a])return-1}}static map(e,t){const i=[];let n;if(Array.prototype.map)return Array.prototype.map.call(e,t);for(n=0;n<e.length;n+=1)i.push(t(e[n]));return i}static find(e,t){let i,n;if(Array.prototype.find)return Array.prototype.find.call(e,t);for(i=0,n=e.length;i<n;i+=1){const n=e[i];if(t(n,i))return n}}static assign(e,...t){const i=e;let n,s;if(Object.assign)return Object.assign(e,...t);for(n=0,s=t.length;n<s;n+=1){const e=t[n];if("object"==typeof e&&null!==e){Object.keys(e).forEach((t=>{i[t]=e[t]}))}}return e}static getBrowserAlias(e){return Ko[e]}static getBrowserTypeByAlias(e){return Jo[e]||""}}const ec=/version\/(\d+(\.?_?\d+)+)/i,tc=[{test:[/googlebot/i],describe(e){const t={name:"Googlebot"},i=Zo.getFirstMatch(/googlebot\/(\d+(\.\d+))/i,e)||Zo.getFirstMatch(ec,e);return i&&(t.version=i),t}},{test:[/opera/i],describe(e){const t={name:"Opera"},i=Zo.getFirstMatch(ec,e)||Zo.getFirstMatch(/(?:opera)[\s/](\d+(\.?_?\d+)+)/i,e);return i&&(t.version=i),t}},{test:[/opr\/|opios/i],describe(e){const t={name:"Opera"},i=Zo.getFirstMatch(/(?:opr|opios)[\s/](\S+)/i,e)||Zo.getFirstMatch(ec,e);return i&&(t.version=i),t}},{test:[/SamsungBrowser/i],describe(e){const t={name:"Samsung Internet for Android"},i=Zo.getFirstMatch(ec,e)||Zo.getFirstMatch(/(?:SamsungBrowser)[\s/](\d+(\.?_?\d+)+)/i,e);return i&&(t.version=i),t}},{test:[/Whale/i],describe(e){const t={name:"NAVER Whale Browser"},i=Zo.getFirstMatch(ec,e)||Zo.getFirstMatch(/(?:whale)[\s/](\d+(?:\.\d+)+)/i,e);return i&&(t.version=i),t}},{test:[/MZBrowser/i],describe(e){const t={name:"MZ Browser"},i=Zo.getFirstMatch(/(?:MZBrowser)[\s/](\d+(?:\.\d+)+)/i,e)||Zo.getFirstMatch(ec,e);return i&&(t.version=i),t}},{test:[/focus/i],describe(e){const t={name:"Focus"},i=Zo.getFirstMatch(/(?:focus)[\s/](\d+(?:\.\d+)+)/i,e)||Zo.getFirstMatch(ec,e);return i&&(t.version=i),t}},{test:[/swing/i],describe(e){const t={name:"Swing"},i=Zo.getFirstMatch(/(?:swing)[\s/](\d+(?:\.\d+)+)/i,e)||Zo.getFirstMatch(ec,e);return i&&(t.version=i),t}},{test:[/coast/i],describe(e){const t={name:"Opera Coast"},i=Zo.getFirstMatch(ec,e)||Zo.getFirstMatch(/(?:coast)[\s/](\d+(\.?_?\d+)+)/i,e);return i&&(t.version=i),t}},{test:[/opt\/\d+(?:.?_?\d+)+/i],describe(e){const t={name:"Opera Touch"},i=Zo.getFirstMatch(/(?:opt)[\s/](\d+(\.?_?\d+)+)/i,e)||Zo.getFirstMatch(ec,e);return i&&(t.version=i),t}},{test:[/yabrowser/i],describe(e){const t={name:"Yandex Browser"},i=Zo.getFirstMatch(/(?:yabrowser)[\s/](\d+(\.?_?\d+)+)/i,e)||Zo.getFirstMatch(ec,e);return i&&(t.version=i),t}},{test:[/ucbrowser/i],describe(e){const t={name:"UC Browser"},i=Zo.getFirstMatch(ec,e)||Zo.getFirstMatch(/(?:ucbrowser)[\s/](\d+(\.?_?\d+)+)/i,e);return i&&(t.version=i),t}},{test:[/Maxthon|mxios/i],describe(e){const t={name:"Maxthon"},i=Zo.getFirstMatch(ec,e)||Zo.getFirstMatch(/(?:Maxthon|mxios)[\s/](\d+(\.?_?\d+)+)/i,e);return i&&(t.version=i),t}},{test:[/epiphany/i],describe(e){const t={name:"Epiphany"},i=Zo.getFirstMatch(ec,e)||Zo.getFirstMatch(/(?:epiphany)[\s/](\d+(\.?_?\d+)+)/i,e);return i&&(t.version=i),t}},{test:[/puffin/i],describe(e){const t={name:"Puffin"},i=Zo.getFirstMatch(ec,e)||Zo.getFirstMatch(/(?:puffin)[\s/](\d+(\.?_?\d+)+)/i,e);return i&&(t.version=i),t}},{test:[/sleipnir/i],describe(e){const t={name:"Sleipnir"},i=Zo.getFirstMatch(ec,e)||Zo.getFirstMatch(/(?:sleipnir)[\s/](\d+(\.?_?\d+)+)/i,e);return i&&(t.version=i),t}},{test:[/k-meleon/i],describe(e){const t={name:"K-Meleon"},i=Zo.getFirstMatch(ec,e)||Zo.getFirstMatch(/(?:k-meleon)[\s/](\d+(\.?_?\d+)+)/i,e);return i&&(t.version=i),t}},{test:[/micromessenger/i],describe(e){const t={name:"WeChat"},i=Zo.getFirstMatch(/(?:micromessenger)[\s/](\d+(\.?_?\d+)+)/i,e)||Zo.getFirstMatch(ec,e);return i&&(t.version=i),t}},{test:[/qqbrowser/i],describe(e){const t={name:/qqbrowserlite/i.test(e)?"QQ Browser Lite":"QQ Browser"},i=Zo.getFirstMatch(/(?:qqbrowserlite|qqbrowser)[/](\d+(\.?_?\d+)+)/i,e)||Zo.getFirstMatch(ec,e);return i&&(t.version=i),t}},{test:[/msie|trident/i],describe(e){const t={name:"Internet Explorer"},i=Zo.getFirstMatch(/(?:msie |rv:)(\d+(\.?_?\d+)+)/i,e);return i&&(t.version=i),t}},{test:[/\sedg\//i],describe(e){const t={name:"Microsoft Edge"},i=Zo.getFirstMatch(/\sedg\/(\d+(\.?_?\d+)+)/i,e);return i&&(t.version=i),t}},{test:[/edg([ea]|ios)/i],describe(e){const t={name:"Microsoft Edge"},i=Zo.getSecondMatch(/edg([ea]|ios)\/(\d+(\.?_?\d+)+)/i,e);return i&&(t.version=i),t}},{test:[/vivaldi/i],describe(e){const t={name:"Vivaldi"},i=Zo.getFirstMatch(/vivaldi\/(\d+(\.?_?\d+)+)/i,e);return i&&(t.version=i),t}},{test:[/seamonkey/i],describe(e){const t={name:"SeaMonkey"},i=Zo.getFirstMatch(/seamonkey\/(\d+(\.?_?\d+)+)/i,e);return i&&(t.version=i),t}},{test:[/sailfish/i],describe(e){const t={name:"Sailfish"},i=Zo.getFirstMatch(/sailfish\s?browser\/(\d+(\.\d+)?)/i,e);return i&&(t.version=i),t}},{test:[/silk/i],describe(e){const t={name:"Amazon Silk"},i=Zo.getFirstMatch(/silk\/(\d+(\.?_?\d+)+)/i,e);return i&&(t.version=i),t}},{test:[/phantom/i],describe(e){const t={name:"PhantomJS"},i=Zo.getFirstMatch(/phantomjs\/(\d+(\.?_?\d+)+)/i,e);return i&&(t.version=i),t}},{test:[/slimerjs/i],describe(e){const t={name:"SlimerJS"},i=Zo.getFirstMatch(/slimerjs\/(\d+(\.?_?\d+)+)/i,e);return i&&(t.version=i),t}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe(e){const t={name:"BlackBerry"},i=Zo.getFirstMatch(ec,e)||Zo.getFirstMatch(/blackberry[\d]+\/(\d+(\.?_?\d+)+)/i,e);return i&&(t.version=i),t}},{test:[/(web|hpw)[o0]s/i],describe(e){const t={name:"WebOS Browser"},i=Zo.getFirstMatch(ec,e)||Zo.getFirstMatch(/w(?:eb)?[o0]sbrowser\/(\d+(\.?_?\d+)+)/i,e);return i&&(t.version=i),t}},{test:[/bada/i],describe(e){const t={name:"Bada"},i=Zo.getFirstMatch(/dolfin\/(\d+(\.?_?\d+)+)/i,e);return i&&(t.version=i),t}},{test:[/tizen/i],describe(e){const t={name:"Tizen"},i=Zo.getFirstMatch(/(?:tizen\s?)?browser\/(\d+(\.?_?\d+)+)/i,e)||Zo.getFirstMatch(ec,e);return i&&(t.version=i),t}},{test:[/qupzilla/i],describe(e){const t={name:"QupZilla"},i=Zo.getFirstMatch(/(?:qupzilla)[\s/](\d+(\.?_?\d+)+)/i,e)||Zo.getFirstMatch(ec,e);return i&&(t.version=i),t}},{test:[/firefox|iceweasel|fxios/i],describe(e){const t={name:"Firefox"},i=Zo.getFirstMatch(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,e);return i&&(t.version=i),t}},{test:[/electron/i],describe(e){const t={name:"Electron"},i=Zo.getFirstMatch(/(?:electron)\/(\d+(\.?_?\d+)+)/i,e);return i&&(t.version=i),t}},{test:[/MiuiBrowser/i],describe(e){const t={name:"Miui"},i=Zo.getFirstMatch(/(?:MiuiBrowser)[\s/](\d+(\.?_?\d+)+)/i,e);return i&&(t.version=i),t}},{test:[/chromium/i],describe(e){const t={name:"Chromium"},i=Zo.getFirstMatch(/(?:chromium)[\s/](\d+(\.?_?\d+)+)/i,e)||Zo.getFirstMatch(ec,e);return i&&(t.version=i),t}},{test:[/chrome|crios|crmo/i],describe(e){const t={name:"Chrome"},i=Zo.getFirstMatch(/(?:chrome|crios|crmo)\/(\d+(\.?_?\d+)+)/i,e);return i&&(t.version=i),t}},{test:[/GSA/i],describe(e){const t={name:"Google Search"},i=Zo.getFirstMatch(/(?:GSA)\/(\d+(\.?_?\d+)+)/i,e);return i&&(t.version=i),t}},{test(e){const t=!e.test(/like android/i),i=e.test(/android/i);return t&&i},describe(e){const t={name:"Android Browser"},i=Zo.getFirstMatch(ec,e);return i&&(t.version=i),t}},{test:[/playstation 4/i],describe(e){const t={name:"PlayStation 4"},i=Zo.getFirstMatch(ec,e);return i&&(t.version=i),t}},{test:[/safari|applewebkit/i],describe(e){const t={name:"Safari"},i=Zo.getFirstMatch(ec,e);return i&&(t.version=i),t}},{test:[/.*/i],describe(e){const t=-1!==e.search("\\(")?/^(.*)\/(.*)[ \t]\((.*)/:/^(.*)\/(.*) /;return{name:Zo.getFirstMatch(t,e),version:Zo.getSecondMatch(t,e)}}}];var ic=[{test:[/Roku\/DVP/],describe(e){const t=Zo.getFirstMatch(/Roku\/DVP-(\d+\.\d+)/i,e);return{name:Yo.Roku,version:t}}},{test:[/windows phone/i],describe(e){const t=Zo.getFirstMatch(/windows phone (?:os)?\s?(\d+(\.\d+)*)/i,e);return{name:Yo.WindowsPhone,version:t}}},{test:[/windows /i],describe(e){const t=Zo.getFirstMatch(/Windows ((NT|XP)( \d\d?.\d)?)/i,e),i=Zo.getWindowsVersionName(t);return{name:Yo.Windows,version:t,versionName:i}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe(e){const t={name:Yo.iOS},i=Zo.getSecondMatch(/(Version\/)(\d[\d.]+)/,e);return i&&(t.version=i),t}},{test:[/macintosh/i],describe(e){const t=Zo.getFirstMatch(/mac os x (\d+(\.?_?\d+)+)/i,e).replace(/[_\s]/g,"."),i=Zo.getMacOSVersionName(t),n={name:Yo.MacOS,version:t};return i&&(n.versionName=i),n}},{test:[/(ipod|iphone|ipad)/i],describe(e){const t=Zo.getFirstMatch(/os (\d+([_\s]\d+)*) like mac os x/i,e).replace(/[_\s]/g,".");return{name:Yo.iOS,version:t}}},{test(e){const t=!e.test(/like android/i),i=e.test(/android/i);return t&&i},describe(e){const t=Zo.getFirstMatch(/android[\s/-](\d+(\.\d+)*)/i,e),i=Zo.getAndroidVersionName(t),n={name:Yo.Android,version:t};return i&&(n.versionName=i),n}},{test:[/(web|hpw)[o0]s/i],describe(e){const t=Zo.getFirstMatch(/(?:web|hpw)[o0]s\/(\d+(\.\d+)*)/i,e),i={name:Yo.WebOS};return t&&t.length&&(i.version=t),i}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe(e){const t=Zo.getFirstMatch(/rim\stablet\sos\s(\d+(\.\d+)*)/i,e)||Zo.getFirstMatch(/blackberry\d+\/(\d+([_\s]\d+)*)/i,e)||Zo.getFirstMatch(/\bbb(\d+)/i,e);return{name:Yo.BlackBerry,version:t}}},{test:[/bada/i],describe(e){const t=Zo.getFirstMatch(/bada\/(\d+(\.\d+)*)/i,e);return{name:Yo.Bada,version:t}}},{test:[/tizen/i],describe(e){const t=Zo.getFirstMatch(/tizen[/\s](\d+(\.\d+)*)/i,e);return{name:Yo.Tizen,version:t}}},{test:[/linux/i],describe:()=>({name:Yo.Linux})},{test:[/CrOS/],describe:()=>({name:Yo.ChromeOS})},{test:[/PlayStation 4/],describe(e){const t=Zo.getFirstMatch(/PlayStation 4[/\s](\d+(\.\d+)*)/i,e);return{name:Yo.PlayStation4,version:t}}}],nc=[{test:[/googlebot/i],describe:()=>({type:"bot",vendor:"Google"})},{test:[/huawei/i],describe(e){const t=Zo.getFirstMatch(/(can-l01)/i,e)&&"Nova",i={type:Qo.mobile,vendor:"Huawei"};return t&&(i.model=t),i}},{test:[/nexus\s*(?:7|8|9|10).*/i],describe:()=>({type:Qo.tablet,vendor:"Nexus"})},{test:[/ipad/i],describe:()=>({type:Qo.tablet,vendor:"Apple",model:"iPad"})},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe:()=>({type:Qo.tablet,vendor:"Apple",model:"iPad"})},{test:[/kftt build/i],describe:()=>({type:Qo.tablet,vendor:"Amazon",model:"Kindle Fire HD 7"})},{test:[/silk/i],describe:()=>({type:Qo.tablet,vendor:"Amazon"})},{test:[/tablet(?! pc)/i],describe:()=>({type:Qo.tablet})},{test(e){const t=e.test(/ipod|iphone/i),i=e.test(/like (ipod|iphone)/i);return t&&!i},describe(e){const t=Zo.getFirstMatch(/(ipod|iphone)/i,e);return{type:Qo.mobile,vendor:"Apple",model:t}}},{test:[/nexus\s*[0-6].*/i,/galaxy nexus/i],describe:()=>({type:Qo.mobile,vendor:"Nexus"})},{test:[/[^-]mobi/i],describe:()=>({type:Qo.mobile})},{test:e=>"blackberry"===e.getBrowserName(!0),describe:()=>({type:Qo.mobile,vendor:"BlackBerry"})},{test:e=>"bada"===e.getBrowserName(!0),describe:()=>({type:Qo.mobile})},{test:e=>"windows phone"===e.getBrowserName(),describe:()=>({type:Qo.mobile,vendor:"Microsoft"})},{test(e){const t=Number(String(e.getOSVersion()).split(".")[0]);return"android"===e.getOSName(!0)&&t>=3},describe:()=>({type:Qo.tablet})},{test:e=>"android"===e.getOSName(!0),describe:()=>({type:Qo.mobile})},{test:e=>"macos"===e.getOSName(!0),describe:()=>({type:Qo.desktop,vendor:"Apple"})},{test:e=>"windows"===e.getOSName(!0),describe:()=>({type:Qo.desktop})},{test:e=>"linux"===e.getOSName(!0),describe:()=>({type:Qo.desktop})},{test:e=>"playstation 4"===e.getOSName(!0),describe:()=>({type:Qo.tv})},{test:e=>"roku"===e.getOSName(!0),describe:()=>({type:Qo.tv})}],sc=[{test:e=>"microsoft edge"===e.getBrowserName(!0),describe(e){if(/\sedg\//i.test(e))return{name:Xo.Blink};const t=Zo.getFirstMatch(/edge\/(\d+(\.?_?\d+)+)/i,e);return{name:Xo.EdgeHTML,version:t}}},{test:[/trident/i],describe(e){const t={name:Xo.Trident},i=Zo.getFirstMatch(/trident\/(\d+(\.?_?\d+)+)/i,e);return i&&(t.version=i),t}},{test:e=>e.test(/presto/i),describe(e){const t={name:Xo.Presto},i=Zo.getFirstMatch(/presto\/(\d+(\.?_?\d+)+)/i,e);return i&&(t.version=i),t}},{test(e){const t=e.test(/gecko/i),i=e.test(/like gecko/i);return t&&!i},describe(e){const t={name:Xo.Gecko},i=Zo.getFirstMatch(/gecko\/(\d+(\.?_?\d+)+)/i,e);return i&&(t.version=i),t}},{test:[/(apple)?webkit\/537\.36/i],describe:()=>({name:Xo.Blink})},{test:[/(apple)?webkit/i],describe(e){const t={name:Xo.WebKit},i=Zo.getFirstMatch(/webkit\/(\d+(\.?_?\d+)+)/i,e);return i&&(t.version=i),t}}];class ac{constructor(e,t=!1){if(null==e||""===e)throw new Error("UserAgent parameter can't be empty");this._ua=e,this.parsedResult={},!0!==t&&this.parse()}getUA(){return this._ua}test(e){return e.test(this._ua)}parseBrowser(){this.parsedResult.browser={};const e=Zo.find(tc,(e=>{if("function"==typeof e.test)return e.test(this);if(e.test instanceof Array)return e.test.some((e=>this.test(e)));throw new Error("Browser's test function is not valid")}));return e&&(this.parsedResult.browser=e.describe(this.getUA())),this.parsedResult.browser}getBrowser(){return this.parsedResult.browser?this.parsedResult.browser:this.parseBrowser()}getBrowserName(e){return e?String(this.getBrowser().name).toLowerCase()||"":this.getBrowser().name||""}getBrowserVersion(){return this.getBrowser().version}getOS(){return this.parsedResult.os?this.parsedResult.os:this.parseOS()}parseOS(){this.parsedResult.os={};const e=Zo.find(ic,(e=>{if("function"==typeof e.test)return e.test(this);if(e.test instanceof Array)return e.test.some((e=>this.test(e)));throw new Error("Browser's test function is not valid")}));return e&&(this.parsedResult.os=e.describe(this.getUA())),this.parsedResult.os}getOSName(e){const{name:t}=this.getOS();return e?String(t).toLowerCase()||"":t||""}getOSVersion(){return this.getOS().version}getPlatform(){return this.parsedResult.platform?this.parsedResult.platform:this.parsePlatform()}getPlatformType(e=!1){const{type:t}=this.getPlatform();return e?String(t).toLowerCase()||"":t||""}parsePlatform(){this.parsedResult.platform={};const e=Zo.find(nc,(e=>{if("function"==typeof e.test)return e.test(this);if(e.test instanceof Array)return e.test.some((e=>this.test(e)));throw new Error("Browser's test function is not valid")}));return e&&(this.parsedResult.platform=e.describe(this.getUA())),this.parsedResult.platform}getEngine(){return this.parsedResult.engine?this.parsedResult.engine:this.parseEngine()}getEngineName(e){return e?String(this.getEngine().name).toLowerCase()||"":this.getEngine().name||""}parseEngine(){this.parsedResult.engine={};const e=Zo.find(sc,(e=>{if("function"==typeof e.test)return e.test(this);if(e.test instanceof Array)return e.test.some((e=>this.test(e)));throw new Error("Browser's test function is not valid")}));return e&&(this.parsedResult.engine=e.describe(this.getUA())),this.parsedResult.engine}parse(){return this.parseBrowser(),this.parseOS(),this.parsePlatform(),this.parseEngine(),this}getResult(){return Zo.assign({},this.parsedResult)}satisfies(e){const t={};let i=0;const n={};let s=0;if(Object.keys(e).forEach((a=>{const r=e[a];"string"==typeof r?(n[a]=r,s+=1):"object"==typeof r&&(t[a]=r,i+=1)})),i>0){const e=Object.keys(t),i=Zo.find(e,(e=>this.isOS(e)));if(i){const e=this.satisfies(t[i]);if(void 0!==e)return e}const n=Zo.find(e,(e=>this.isPlatform(e)));if(n){const e=this.satisfies(t[n]);if(void 0!==e)return e}}if(s>0){const e=Object.keys(n),t=Zo.find(e,(e=>this.isBrowser(e,!0)));if(void 0!==t)return this.compareVersion(n[t])}}isBrowser(e,t=!1){const i=this.getBrowserName().toLowerCase();let n=e.toLowerCase();const s=Zo.getBrowserTypeByAlias(n);return t&&s&&(n=s.toLowerCase()),n===i}compareVersion(e){let t=[0],i=e,n=!1;const s=this.getBrowserVersion();if("string"==typeof s)return">"===e[0]||"<"===e[0]?(i=e.substr(1),"="===e[1]?(n=!0,i=e.substr(2)):t=[],">"===e[0]?t.push(1):t.push(-1)):"="===e[0]?i=e.substr(1):"~"===e[0]&&(n=!0,i=e.substr(1)),t.indexOf(Zo.compareVersions(s,i,n))>-1}isOS(e){return this.getOSName(!0)===String(e).toLowerCase()}isPlatform(e){return this.getPlatformType(!0)===String(e).toLowerCase()}isEngine(e){return this.getEngineName(!0)===String(e).toLowerCase()}is(e,t=!1){return this.isBrowser(e,t)||this.isOS(e)||this.isPlatform(e)}some(e=[]){return e.some((e=>this.is(e)))}}
28
+ var vs=e,bs=t,_s=i.spawn,ys=xs;function xs(e){e=e||{};var t,i,a=this,r=n,o=s,c={},p=!1,d={"User-Agent":"node-XMLHttpRequest",Accept:"*/*"},l=Object.assign({},d),u=["accept-charset","accept-encoding","access-control-request-headers","access-control-request-method","connection","content-length","content-transfer-encoding","cookie","cookie2","date","expect","host","keep-alive","origin","referer","te","trailer","transfer-encoding","upgrade","via"],m=["TRACE","TRACK","CONNECT"],h=!1,f=!1,g=!1,v={};this.UNSENT=0,this.OPENED=1,this.HEADERS_RECEIVED=2,this.LOADING=3,this.DONE=4,this.readyState=this.UNSENT,this.onreadystatechange=null,this.responseText="",this.responseXML="",this.status=null,this.statusText=null;this.open=function(e,t,i,n,s){if(this.abort(),f=!1,g=!1,!function(e){return e&&-1===m.indexOf(e)}(e))throw new Error("SecurityError: Request method not allowed");c={method:e,url:t.toString(),async:"boolean"!=typeof i||i,user:n||null,password:s||null},b(this.OPENED)},this.setDisableHeaderCheck=function(e){p=e},this.setRequestHeader=function(e,t){if(this.readyState!=this.OPENED)throw new Error("INVALID_STATE_ERR: setRequestHeader can only be called when state is OPEN");if(!function(e){return p||e&&-1===u.indexOf(e.toLowerCase())}(e))return console.warn('Refused to set unsafe header "'+e+'"'),!1;if(h)throw new Error("INVALID_STATE_ERR: send flag is true");return l[e]=t,!0},this.getResponseHeader=function(e){return"string"==typeof e&&this.readyState>this.OPENED&&i.headers[e.toLowerCase()]&&!f?i.headers[e.toLowerCase()]:null},this.getAllResponseHeaders=function(){if(this.readyState<this.HEADERS_RECEIVED||f)return"";var e="";for(var t in i.headers)"set-cookie"!==t&&"set-cookie2"!==t&&(e+=t+": "+i.headers[t]+"\r\n");return e.substr(0,e.length-2)},this.getRequestHeader=function(e){return"string"==typeof e&&l[e]?l[e]:""},this.send=function(n){if(this.readyState!=this.OPENED)throw new Error("INVALID_STATE_ERR: connection must be opened before send() is called");if(h)throw new Error("INVALID_STATE_ERR: send has already been called");var s,p=!1,d=!1,u=bs.parse(c.url);switch(u.protocol){case"https:":p=!0;case"http:":s=u.hostname;break;case"file:":d=!0;break;case void 0:case"":s="localhost";break;default:throw new Error("Protocol not supported.")}if(d){if("GET"!==c.method)throw new Error("XMLHttpRequest: Only GET method is supported");if(c.async)vs.readFile(unescape(u.pathname),"utf8",(function(e,t){e?a.handleError(e,e.errno||-1):(a.status=200,a.responseText=t,b(a.DONE))}));else try{this.responseText=vs.readFileSync(unescape(u.pathname),"utf8"),this.status=200,b(a.DONE)}catch(e){this.handleError(e,e.errno||-1)}}else{var m=u.port||(p?443:80),g=u.pathname+(u.search?u.search:"");if(l.Host=s,p&&443===m||80===m||(l.Host+=":"+u.port),c.user){void 0===c.password&&(c.password="");var v=new Buffer(c.user+":"+c.password);l.Authorization="Basic "+v.toString("base64")}"GET"===c.method||"HEAD"===c.method?n=null:n?(l["Content-Length"]=Buffer.isBuffer(n)?n.length:Buffer.byteLength(n),l["Content-Type"]||(l["Content-Type"]="text/plain;charset=UTF-8")):"POST"===c.method&&(l["Content-Length"]=0);var _=e.agent||!1,y={host:s,port:m,path:g,method:c.method,headers:l,agent:_};if(p&&(y.pfx=e.pfx,y.key=e.key,y.passphrase=e.passphrase,y.cert=e.cert,y.ca=e.ca,y.ciphers=e.ciphers,y.rejectUnauthorized=!1!==e.rejectUnauthorized),f=!1,c.async){var x=p?o.request:r.request;h=!0,a.dispatchEvent("readystatechange");var w=function(n){if(302===(i=n).statusCode||303===i.statusCode||307===i.statusCode){c.url=i.headers.location;var r=bs.parse(c.url);s=r.hostname;var o={hostname:r.hostname,port:r.port,path:r.path,method:303===i.statusCode?"GET":c.method,headers:l};return p&&(o.pfx=e.pfx,o.key=e.key,o.passphrase=e.passphrase,o.cert=e.cert,o.ca=e.ca,o.ciphers=e.ciphers,o.rejectUnauthorized=!1!==e.rejectUnauthorized),void(t=x(o,w).on("error",S)).end()}i&&i.setEncoding&&i.setEncoding("utf8"),b(a.HEADERS_RECEIVED),a.status=i.statusCode,i.on("data",(function(e){e&&(a.responseText+=e),h&&b(a.LOADING)})),i.on("end",(function(){h&&(h=!1,b(a.DONE))})),i.on("error",(function(e){a.handleError(e)}))},S=function(e){a.handleError(e)};t=x(y,w).on("error",S),e.autoUnref&&t.on("socket",(e=>{e.unref()})),n&&t.write(n),t.end(),a.dispatchEvent("loadstart")}else{var R=".node-xmlhttprequest-content-"+process.pid,C=".node-xmlhttprequest-sync-"+process.pid;vs.writeFileSync(C,"","utf8");for(var k="var http = require('http'), https = require('https'), fs = require('fs');var doRequest = http"+(p?"s":"")+".request;var options = "+JSON.stringify(y)+";var responseText = '';var req = doRequest(options, function(response) {response.setEncoding('utf8');response.on('data', function(chunk) { responseText += chunk;});response.on('end', function() {fs.writeFileSync('"+R+"', 'NODE-XMLHTTPREQUEST-STATUS:' + response.statusCode + ',' + responseText, 'utf8');fs.unlinkSync('"+C+"');});response.on('error', function(error) {fs.writeFileSync('"+R+"', 'NODE-XMLHTTPREQUEST-ERROR:' + JSON.stringify(error), 'utf8');fs.unlinkSync('"+C+"');});}).on('error', function(error) {fs.writeFileSync('"+R+"', 'NODE-XMLHTTPREQUEST-ERROR:' + JSON.stringify(error), 'utf8');fs.unlinkSync('"+C+"');});"+(n?"req.write('"+JSON.stringify(n).slice(1,-1).replace(/'/g,"\\'")+"');":"")+"req.end();",T=_s(process.argv[0],["-e",k]);vs.existsSync(C););if(a.responseText=vs.readFileSync(R,"utf8"),T.stdin.end(),vs.unlinkSync(R),a.responseText.match(/^NODE-XMLHTTPREQUEST-ERROR:/)){var P=a.responseText.replace(/^NODE-XMLHTTPREQUEST-ERROR:/,"");a.handleError(P,503)}else a.status=a.responseText.replace(/^NODE-XMLHTTPREQUEST-STATUS:([0-9]*),.*/,"$1"),a.responseText=a.responseText.replace(/^NODE-XMLHTTPREQUEST-STATUS:[0-9]*,(.*)/,"$1"),b(a.DONE)}}},this.handleError=function(e,t){this.status=t||0,this.statusText=e,this.responseText=e.stack,f=!0,b(this.DONE)},this.abort=function(){t&&(t.abort(),t=null),l=Object.assign({},d),this.responseText="",this.responseXML="",f=g=!0,this.readyState===this.UNSENT||this.readyState===this.OPENED&&!h||this.readyState===this.DONE||(h=!1,b(this.DONE)),this.readyState=this.UNSENT},this.addEventListener=function(e,t){e in v||(v[e]=[]),v[e].push(t)},this.removeEventListener=function(e,t){e in v&&(v[e]=v[e].filter((function(e){return e!==t})))},this.dispatchEvent=function(e){if("function"==typeof a["on"+e]&&(this.readyState===this.DONE?setImmediate((function(){a["on"+e]()})):a["on"+e]()),e in v)for(let t=0,i=v[e].length;t<i;t++)this.readyState===this.DONE?setImmediate((function(){v[e][t].call(a)})):v[e][t].call(a)};var b=function(e){if(!(a.readyState===e||a.readyState===a.UNSENT&&g)&&(a.readyState=e,(c.async||a.readyState<a.OPENED||a.readyState===a.DONE)&&a.dispatchEvent("readystatechange"),a.readyState===a.DONE)){let e;e=g?"abort":f?"error":"load",a.dispatchEvent(e),a.dispatchEvent("loadend")}}}xs.XMLHttpRequest=xs;const ws=ys||v({__proto__:null,default:ys},[ys]);function Ss(){}const Rs=null!=new ws({xdomain:!1}).responseType;class Cs extends ts{constructor(e,t){super(),rs(this,t),this.opts=t,this.method=t.method||"GET",this.uri=e,this.async=!1!==t.async,this.data=void 0!==t.data?t.data:null,this.create()}create(){const e=ns(this.opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");e.xdomain=!!this.opts.xd,e.xscheme=!!this.opts.xs;const t=this.xhr=new ws(e);try{t.open(this.method,this.uri,this.async);try{if(this.opts.extraHeaders){t.setDisableHeaderCheck&&t.setDisableHeaderCheck(!0);for(let e in this.opts.extraHeaders)this.opts.extraHeaders.hasOwnProperty(e)&&t.setRequestHeader(e,this.opts.extraHeaders[e])}}catch(e){}if("POST"===this.method)try{t.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch(e){}try{t.setRequestHeader("Accept","*/*")}catch(e){}"withCredentials"in t&&(t.withCredentials=this.opts.withCredentials),this.opts.requestTimeout&&(t.timeout=this.opts.requestTimeout),t.onreadystatechange=()=>{4===t.readyState&&(200===t.status||1223===t.status?this.onLoad():this.setTimeoutFn((()=>{this.onError("number"==typeof t.status?t.status:0)}),0))},t.send(this.data)}catch(e){return void this.setTimeoutFn((()=>{this.onError(e)}),0)}"undefined"!=typeof document&&(this.index=Cs.requestsCount++,Cs.requests[this.index]=this)}onError(e){this.emitReserved("error",e,this.xhr),this.cleanup(!0)}cleanup(e){if(void 0!==this.xhr&&null!==this.xhr){if(this.xhr.onreadystatechange=Ss,e)try{this.xhr.abort()}catch(e){}"undefined"!=typeof document&&delete Cs.requests[this.index],this.xhr=null}}onLoad(){const e=this.xhr.responseText;null!==e&&(this.emitReserved("data",e),this.emitReserved("success"),this.cleanup())}abort(){this.cleanup()}}if(Cs.requestsCount=0,Cs.requests={},"undefined"!=typeof document)if("function"==typeof attachEvent)attachEvent("onunload",ks);else if("function"==typeof addEventListener){addEventListener("onpagehide"in is?"pagehide":"unload",ks,!1)}function ks(){for(let e in Cs.requests)Cs.requests.hasOwnProperty(e)&&Cs.requests[e].abort()}var Ts={},Ps={get exports(){return Ts},set exports(e){Ts=e}},Es={BINARY_TYPES:["nodebuffer","arraybuffer","fragments"],EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}};const{EMPTY_BUFFER:Os}=Es;function Ds(e,t,i,n,s){for(let a=0;a<s;a++)i[n+a]=e[a]^t[3&a]}function Is(e,t){for(let i=0;i<e.length;i++)e[i]^=t[3&i]}if(Ps.exports={concat:function(e,t){if(0===e.length)return Os;if(1===e.length)return e[0];const i=Buffer.allocUnsafe(t);let n=0;for(let t=0;t<e.length;t++){const s=e[t];i.set(s,n),n+=s.length}return n<t?i.slice(0,n):i},mask:Ds,toArrayBuffer:function(e){return e.byteLength===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength)},toBuffer:function e(t){if(e.readOnly=!0,Buffer.isBuffer(t))return t;let i;return t instanceof ArrayBuffer?i=Buffer.from(t):ArrayBuffer.isView(t)?i=Buffer.from(t.buffer,t.byteOffset,t.byteLength):(i=Buffer.from(t),e.readOnly=!1),i},unmask:Is},!process.env.WS_NO_BUFFER_UTIL)try{const e=require("bufferutil");Ts.mask=function(t,i,n,s,a){a<48?Ds(t,i,n,s,a):e.mask(t,i,n,s,a)},Ts.unmask=function(t,i){t.length<32?Is(t,i):e.unmask(t,i)}}catch(e){}const js=Symbol("kDone"),Ls=Symbol("kRun");const Ms=r,As=Ts,Ns=class{constructor(e){this[js]=()=>{this.pending--,this[Ls]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Ls]()}[Ls](){if(this.pending!==this.concurrency&&this.jobs.length){const e=this.jobs.shift();this.pending++,e(this[js])}}},{kStatusCode:Bs}=Es,Fs=Buffer.from([0,0,255,255]),Us=Symbol("permessage-deflate"),zs=Symbol("total-length"),qs=Symbol("callback"),$s=Symbol("buffers"),Vs=Symbol("error");let Ws;var Gs=class{constructor(e,t,i){if(this._maxPayload=0|i,this._options=e||{},this._threshold=void 0!==this._options.threshold?this._options.threshold:1024,this._isServer=!!t,this._deflate=null,this._inflate=null,this.params=null,!Ws){const e=void 0!==this._options.concurrencyLimit?this._options.concurrencyLimit:10;Ws=new Ns(e)}}static get extensionName(){return"permessage-deflate"}offer(){const e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:null==this._options.clientMaxWindowBits&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){const e=this._deflate[qs];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){const t=this._options,i=e.find((e=>!(!1===t.serverNoContextTakeover&&e.server_no_context_takeover||e.server_max_window_bits&&(!1===t.serverMaxWindowBits||"number"==typeof t.serverMaxWindowBits&&t.serverMaxWindowBits>e.server_max_window_bits)||"number"==typeof t.clientMaxWindowBits&&!e.client_max_window_bits)));if(!i)throw new Error("None of the extension offers can be accepted");return t.serverNoContextTakeover&&(i.server_no_context_takeover=!0),t.clientNoContextTakeover&&(i.client_no_context_takeover=!0),"number"==typeof t.serverMaxWindowBits&&(i.server_max_window_bits=t.serverMaxWindowBits),"number"==typeof t.clientMaxWindowBits?i.client_max_window_bits=t.clientMaxWindowBits:!0!==i.client_max_window_bits&&!1!==t.clientMaxWindowBits||delete i.client_max_window_bits,i}acceptAsClient(e){const t=e[0];if(!1===this._options.clientNoContextTakeover&&t.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(t.client_max_window_bits){if(!1===this._options.clientMaxWindowBits||"number"==typeof this._options.clientMaxWindowBits&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"')}else"number"==typeof this._options.clientMaxWindowBits&&(t.client_max_window_bits=this._options.clientMaxWindowBits);return t}normalizeParams(e){return e.forEach((e=>{Object.keys(e).forEach((t=>{let i=e[t];if(i.length>1)throw new Error(`Parameter "${t}" must have only a single value`);if(i=i[0],"client_max_window_bits"===t){if(!0!==i){const e=+i;if(!Number.isInteger(e)||e<8||e>15)throw new TypeError(`Invalid value for parameter "${t}": ${i}`);i=e}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${t}": ${i}`)}else if("server_max_window_bits"===t){const e=+i;if(!Number.isInteger(e)||e<8||e>15)throw new TypeError(`Invalid value for parameter "${t}": ${i}`);i=e}else{if("client_no_context_takeover"!==t&&"server_no_context_takeover"!==t)throw new Error(`Unknown parameter "${t}"`);if(!0!==i)throw new TypeError(`Invalid value for parameter "${t}": ${i}`)}e[t]=i}))})),e}decompress(e,t,i){Ws.add((n=>{this._decompress(e,t,((e,t)=>{n(),i(e,t)}))}))}compress(e,t,i){Ws.add((n=>{this._compress(e,t,((e,t)=>{n(),i(e,t)}))}))}_decompress(e,t,i){const n=this._isServer?"client":"server";if(!this._inflate){const e=`${n}_max_window_bits`,t="number"!=typeof this.params[e]?Ms.Z_DEFAULT_WINDOWBITS:this.params[e];this._inflate=Ms.createInflateRaw({...this._options.zlibInflateOptions,windowBits:t}),this._inflate[Us]=this,this._inflate[zs]=0,this._inflate[$s]=[],this._inflate.on("error",Js),this._inflate.on("data",Ks)}this._inflate[qs]=i,this._inflate.write(e),t&&this._inflate.write(Fs),this._inflate.flush((()=>{const e=this._inflate[Vs];if(e)return this._inflate.close(),this._inflate=null,void i(e);const s=As.concat(this._inflate[$s],this._inflate[zs]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[zs]=0,this._inflate[$s]=[],t&&this.params[`${n}_no_context_takeover`]&&this._inflate.reset()),i(null,s)}))}_compress(e,t,i){const n=this._isServer?"server":"client";if(!this._deflate){const e=`${n}_max_window_bits`,t="number"!=typeof this.params[e]?Ms.Z_DEFAULT_WINDOWBITS:this.params[e];this._deflate=Ms.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:t}),this._deflate[zs]=0,this._deflate[$s]=[],this._deflate.on("data",Hs)}this._deflate[qs]=i,this._deflate.write(e),this._deflate.flush(Ms.Z_SYNC_FLUSH,(()=>{if(!this._deflate)return;let e=As.concat(this._deflate[$s],this._deflate[zs]);t&&(e=e.slice(0,e.length-4)),this._deflate[qs]=null,this._deflate[zs]=0,this._deflate[$s]=[],t&&this.params[`${n}_no_context_takeover`]&&this._deflate.reset(),i(null,e)}))}};function Hs(e){this[$s].push(e),this[zs]+=e.length}function Ks(e){this[zs]+=e.length,this[Us]._maxPayload<1||this[zs]<=this[Us]._maxPayload?this[$s].push(e):(this[Vs]=new RangeError("Max payload size exceeded"),this[Vs].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Vs][Bs]=1009,this.removeListener("data",Ks),this.reset())}function Js(e){this[Us]._inflate=null,e[Bs]=1007,this[qs](e)}var Qs={};function Ys(e){const t=e.length;let i=0;for(;i<t;)if(0==(128&e[i]))i++;else if(192==(224&e[i])){if(i+1===t||128!=(192&e[i+1])||192==(254&e[i]))return!1;i+=2}else if(224==(240&e[i])){if(i+2>=t||128!=(192&e[i+1])||128!=(192&e[i+2])||224===e[i]&&128==(224&e[i+1])||237===e[i]&&160==(224&e[i+1]))return!1;i+=3}else{if(240!=(248&e[i]))return!1;if(i+3>=t||128!=(192&e[i+1])||128!=(192&e[i+2])||128!=(192&e[i+3])||240===e[i]&&128==(240&e[i+1])||244===e[i]&&e[i+1]>143||e[i]>244)return!1;i+=4}return!0}if({get exports(){return Qs},set exports(e){Qs=e}}.exports={isValidStatusCode:function(e){return e>=1e3&&e<=1014&&1004!==e&&1005!==e&&1006!==e||e>=3e3&&e<=4999},isValidUTF8:Ys,tokenChars:[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0]},!process.env.WS_NO_UTF_8_VALIDATE)try{const e=require("utf-8-validate");Qs.isValidUTF8=function(t){return t.length<150?Ys(t):e(t)}}catch(e){}const{Writable:Xs}=a,Zs=Gs,{BINARY_TYPES:ea,EMPTY_BUFFER:ta,kStatusCode:ia,kWebSocket:na}=Es,{concat:sa,toArrayBuffer:aa,unmask:ra}=Ts,{isValidStatusCode:oa,isValidUTF8:ca}=Qs;var pa=class extends Xs{constructor(e={}){super(),this._binaryType=e.binaryType||ea[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=0|e.maxPayload,this._skipUTF8Validation=!!e.skipUTF8Validation,this[na]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._state=0,this._loop=!1}_write(e,t,i){if(8===this._opcode&&0==this._state)return i();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(i)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){const t=this._buffers[0];return this._buffers[0]=t.slice(e),t.slice(0,e)}const t=Buffer.allocUnsafe(e);do{const i=this._buffers[0],n=t.length-e;e>=i.length?t.set(this._buffers.shift(),n):(t.set(new Uint8Array(i.buffer,i.byteOffset,e),n),this._buffers[0]=i.slice(e)),e-=i.length}while(e>0);return t}startLoop(e){let t;this._loop=!0;do{switch(this._state){case 0:t=this.getInfo();break;case 1:t=this.getPayloadLength16();break;case 2:t=this.getPayloadLength64();break;case 3:this.getMask();break;case 4:t=this.getData(e);break;default:return void(this._loop=!1)}}while(this._loop);e(t)}getInfo(){if(this._bufferedBytes<2)return void(this._loop=!1);const e=this.consume(2);if(0!=(48&e[0]))return this._loop=!1,da(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");const t=64==(64&e[0]);if(t&&!this._extensions[Zs.extensionName])return this._loop=!1,da(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");if(this._fin=128==(128&e[0]),this._opcode=15&e[0],this._payloadLength=127&e[1],0===this._opcode){if(t)return this._loop=!1,da(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");if(!this._fragmented)return this._loop=!1,da(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");this._opcode=this._fragmented}else if(1===this._opcode||2===this._opcode){if(this._fragmented)return this._loop=!1,da(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");this._compressed=t}else{if(!(this._opcode>7&&this._opcode<11))return this._loop=!1,da(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");if(!this._fin)return this._loop=!1,da(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");if(t)return this._loop=!1,da(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");if(this._payloadLength>125)return this._loop=!1,da(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH")}if(this._fin||this._fragmented||(this._fragmented=this._opcode),this._masked=128==(128&e[1]),this._isServer){if(!this._masked)return this._loop=!1,da(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK")}else if(this._masked)return this._loop=!1,da(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");if(126===this._payloadLength)this._state=1;else{if(127!==this._payloadLength)return this.haveLength();this._state=2}}getPayloadLength16(){if(!(this._bufferedBytes<2))return this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength();this._loop=!1}getPayloadLength64(){if(this._bufferedBytes<8)return void(this._loop=!1);const e=this.consume(8),t=e.readUInt32BE(0);return t>Math.pow(2,21)-1?(this._loop=!1,da(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH")):(this._payloadLength=t*Math.pow(2,32)+e.readUInt32BE(4),this.haveLength())}haveLength(){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0))return this._loop=!1,da(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");this._masked?this._state=3:this._state=4}getMask(){this._bufferedBytes<4?this._loop=!1:(this._mask=this.consume(4),this._state=4)}getData(e){let t=ta;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength)return void(this._loop=!1);t=this.consume(this._payloadLength),this._masked&&0!=(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])&&ra(t,this._mask)}return this._opcode>7?this.controlMessage(t):this._compressed?(this._state=5,void this.decompress(t,e)):(t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage())}decompress(e,t){this._extensions[Zs.extensionName].decompress(e,this._fin,((e,i)=>{if(e)return t(e);if(i.length){if(this._messageLength+=i.length,this._messageLength>this._maxPayload&&this._maxPayload>0)return t(da(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"));this._fragments.push(i)}const n=this.dataMessage();if(n)return t(n);this.startLoop(t)}))}dataMessage(){if(this._fin){const e=this._messageLength,t=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],2===this._opcode){let i;i="nodebuffer"===this._binaryType?sa(t,e):"arraybuffer"===this._binaryType?aa(sa(t,e)):t,this.emit("message",i,!0)}else{const i=sa(t,e);if(!this._skipUTF8Validation&&!ca(i))return this._loop=!1,da(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");this.emit("message",i,!1)}}this._state=0}controlMessage(e){if(8===this._opcode)if(this._loop=!1,0===e.length)this.emit("conclude",1005,ta),this.end();else{if(1===e.length)return da(RangeError,"invalid payload length 1",!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");{const t=e.readUInt16BE(0);if(!oa(t))return da(RangeError,`invalid status code ${t}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");const i=e.slice(2);if(!this._skipUTF8Validation&&!ca(i))return da(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");this.emit("conclude",t,i),this.end()}}else 9===this._opcode?this.emit("ping",e):this.emit("pong",e);this._state=0}};function da(e,t,i,n,s){const a=new e(i?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(a,da),a.code=s,a[ia]=n,a}const{randomFillSync:la}=p,ua=Gs,{EMPTY_BUFFER:ma}=Es,{isValidStatusCode:ha}=Qs,{mask:fa,toBuffer:ga}=Ts,va=Symbol("kByteLength"),ba=Buffer.alloc(4);class _a{constructor(e,t,i){this._extensions=t||{},i&&(this._generateMask=i,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._deflating=!1,this._queue=[]}static frame(e,t){let i,n,s=!1,a=2,r=!1;t.mask&&(i=t.maskBuffer||ba,t.generateMask?t.generateMask(i):la(i,0,4),r=0==(i[0]|i[1]|i[2]|i[3]),a=6),"string"==typeof e?n=t.mask&&!r||void 0===t[va]?(e=Buffer.from(e)).length:t[va]:(n=e.length,s=t.mask&&t.readOnly&&!r);let o=n;n>=65536?(a+=8,o=127):n>125&&(a+=2,o=126);const c=Buffer.allocUnsafe(s?n+a:a);return c[0]=t.fin?128|t.opcode:t.opcode,t.rsv1&&(c[0]|=64),c[1]=o,126===o?c.writeUInt16BE(n,2):127===o&&(c[2]=c[3]=0,c.writeUIntBE(n,4,6)),t.mask?(c[1]|=128,c[a-4]=i[0],c[a-3]=i[1],c[a-2]=i[2],c[a-1]=i[3],r?[c,e]:s?(fa(e,i,c,a,n),[c]):(fa(e,i,e,0,n),[c,e])):[c,e]}close(e,t,i,n){let s;if(void 0===e)s=ma;else{if("number"!=typeof e||!ha(e))throw new TypeError("First argument must be a valid error code number");if(void 0!==t&&t.length){const i=Buffer.byteLength(t);if(i>123)throw new RangeError("The message must not be greater than 123 bytes");s=Buffer.allocUnsafe(2+i),s.writeUInt16BE(e,0),"string"==typeof t?s.write(t,2):s.set(t,2)}else s=Buffer.allocUnsafe(2),s.writeUInt16BE(e,0)}const a={[va]:s.length,fin:!0,generateMask:this._generateMask,mask:i,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._deflating?this.enqueue([this.dispatch,s,!1,a,n]):this.sendFrame(_a.frame(s,a),n)}ping(e,t,i){let n,s;if("string"==typeof e?(n=Buffer.byteLength(e),s=!1):(n=(e=ga(e)).length,s=ga.readOnly),n>125)throw new RangeError("The data size must not be greater than 125 bytes");const a={[va]:n,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:9,readOnly:s,rsv1:!1};this._deflating?this.enqueue([this.dispatch,e,!1,a,i]):this.sendFrame(_a.frame(e,a),i)}pong(e,t,i){let n,s;if("string"==typeof e?(n=Buffer.byteLength(e),s=!1):(n=(e=ga(e)).length,s=ga.readOnly),n>125)throw new RangeError("The data size must not be greater than 125 bytes");const a={[va]:n,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:10,readOnly:s,rsv1:!1};this._deflating?this.enqueue([this.dispatch,e,!1,a,i]):this.sendFrame(_a.frame(e,a),i)}send(e,t,i){const n=this._extensions[ua.extensionName];let s,a,r=t.binary?2:1,o=t.compress;if("string"==typeof e?(s=Buffer.byteLength(e),a=!1):(s=(e=ga(e)).length,a=ga.readOnly),this._firstFragment?(this._firstFragment=!1,o&&n&&n.params[n._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(o=s>=n._threshold),this._compress=o):(o=!1,r=0),t.fin&&(this._firstFragment=!0),n){const n={[va]:s,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:r,readOnly:a,rsv1:o};this._deflating?this.enqueue([this.dispatch,e,this._compress,n,i]):this.dispatch(e,this._compress,n,i)}else this.sendFrame(_a.frame(e,{[va]:s,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:r,readOnly:a,rsv1:!1}),i)}dispatch(e,t,i,n){if(!t)return void this.sendFrame(_a.frame(e,i),n);const s=this._extensions[ua.extensionName];this._bufferedBytes+=i[va],this._deflating=!0,s.compress(e,i.fin,((e,t)=>{if(this._socket.destroyed){const e=new Error("The socket was closed while data was being compressed");"function"==typeof n&&n(e);for(let t=0;t<this._queue.length;t++){const i=this._queue[t],n=i[i.length-1];"function"==typeof n&&n(e)}}else this._bufferedBytes-=i[va],this._deflating=!1,i.readOnly=!1,this.sendFrame(_a.frame(t,i),n),this.dequeue()}))}dequeue(){for(;!this._deflating&&this._queue.length;){const e=this._queue.shift();this._bufferedBytes-=e[3][va],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][va],this._queue.push(e)}sendFrame(e,t){2===e.length?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork()):this._socket.write(e[0],t)}}var ya=_a;const{kForOnEventAttribute:xa,kListener:wa}=Es,Sa=Symbol("kCode"),Ra=Symbol("kData"),Ca=Symbol("kError"),ka=Symbol("kMessage"),Ta=Symbol("kReason"),Pa=Symbol("kTarget"),Ea=Symbol("kType"),Oa=Symbol("kWasClean");class Da{constructor(e){this[Pa]=null,this[Ea]=e}get target(){return this[Pa]}get type(){return this[Ea]}}Object.defineProperty(Da.prototype,"target",{enumerable:!0}),Object.defineProperty(Da.prototype,"type",{enumerable:!0});class Ia extends Da{constructor(e,t={}){super(e),this[Sa]=void 0===t.code?0:t.code,this[Ta]=void 0===t.reason?"":t.reason,this[Oa]=void 0!==t.wasClean&&t.wasClean}get code(){return this[Sa]}get reason(){return this[Ta]}get wasClean(){return this[Oa]}}Object.defineProperty(Ia.prototype,"code",{enumerable:!0}),Object.defineProperty(Ia.prototype,"reason",{enumerable:!0}),Object.defineProperty(Ia.prototype,"wasClean",{enumerable:!0});class ja extends Da{constructor(e,t={}){super(e),this[Ca]=void 0===t.error?null:t.error,this[ka]=void 0===t.message?"":t.message}get error(){return this[Ca]}get message(){return this[ka]}}Object.defineProperty(ja.prototype,"error",{enumerable:!0}),Object.defineProperty(ja.prototype,"message",{enumerable:!0});class La extends Da{constructor(e,t={}){super(e),this[Ra]=void 0===t.data?null:t.data}get data(){return this[Ra]}}Object.defineProperty(La.prototype,"data",{enumerable:!0});const Ma={addEventListener(e,t,i={}){for(const n of this.listeners(e))if(!i[xa]&&n[wa]===t&&!n[xa])return;let n;if("message"===e)n=function(e,i){const n=new La("message",{data:i?e:e.toString()});n[Pa]=this,Na(t,this,n)};else if("close"===e)n=function(e,i){const n=new Ia("close",{code:e,reason:i.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});n[Pa]=this,Na(t,this,n)};else if("error"===e)n=function(e){const i=new ja("error",{error:e,message:e.message});i[Pa]=this,Na(t,this,i)};else{if("open"!==e)return;n=function(){const e=new Da("open");e[Pa]=this,Na(t,this,e)}}n[xa]=!!i[xa],n[wa]=t,i.once?this.once(e,n):this.on(e,n)},removeEventListener(e,t){for(const i of this.listeners(e))if(i[wa]===t&&!i[xa]){this.removeListener(e,i);break}}};var Aa={CloseEvent:Ia,ErrorEvent:ja,Event:Da,EventTarget:Ma,MessageEvent:La};function Na(e,t,i){"object"==typeof e&&e.handleEvent?e.handleEvent.call(e,i):e.call(t,i)}const{tokenChars:Ba}=Qs;function Fa(e,t,i){void 0===e[t]?e[t]=[i]:e[t].push(i)}var Ua={format:function(e){return Object.keys(e).map((t=>{let i=e[t];return Array.isArray(i)||(i=[i]),i.map((e=>[t].concat(Object.keys(e).map((t=>{let i=e[t];return Array.isArray(i)||(i=[i]),i.map((e=>!0===e?t:`${t}=${e}`)).join("; ")}))).join("; "))).join(", ")})).join(", ")},parse:function(e){const t=Object.create(null);let i,n,s=Object.create(null),a=!1,r=!1,o=!1,c=-1,p=-1,d=-1,l=0;for(;l<e.length;l++)if(p=e.charCodeAt(l),void 0===i)if(-1===d&&1===Ba[p])-1===c&&(c=l);else if(0===l||32!==p&&9!==p){if(59!==p&&44!==p)throw new SyntaxError(`Unexpected character at index ${l}`);{if(-1===c)throw new SyntaxError(`Unexpected character at index ${l}`);-1===d&&(d=l);const n=e.slice(c,d);44===p?(Fa(t,n,s),s=Object.create(null)):i=n,c=d=-1}}else-1===d&&-1!==c&&(d=l);else if(void 0===n)if(-1===d&&1===Ba[p])-1===c&&(c=l);else if(32===p||9===p)-1===d&&-1!==c&&(d=l);else if(59===p||44===p){if(-1===c)throw new SyntaxError(`Unexpected character at index ${l}`);-1===d&&(d=l),Fa(s,e.slice(c,d),!0),44===p&&(Fa(t,i,s),s=Object.create(null),i=void 0),c=d=-1}else{if(61!==p||-1===c||-1!==d)throw new SyntaxError(`Unexpected character at index ${l}`);n=e.slice(c,l),c=d=-1}else if(r){if(1!==Ba[p])throw new SyntaxError(`Unexpected character at index ${l}`);-1===c?c=l:a||(a=!0),r=!1}else if(o)if(1===Ba[p])-1===c&&(c=l);else if(34===p&&-1!==c)o=!1,d=l;else{if(92!==p)throw new SyntaxError(`Unexpected character at index ${l}`);r=!0}else if(34===p&&61===e.charCodeAt(l-1))o=!0;else if(-1===d&&1===Ba[p])-1===c&&(c=l);else if(-1===c||32!==p&&9!==p){if(59!==p&&44!==p)throw new SyntaxError(`Unexpected character at index ${l}`);{if(-1===c)throw new SyntaxError(`Unexpected character at index ${l}`);-1===d&&(d=l);let r=e.slice(c,d);a&&(r=r.replace(/\\/g,""),a=!1),Fa(s,n,r),44===p&&(Fa(t,i,s),s=Object.create(null),i=void 0),n=void 0,c=d=-1}}else-1===d&&(d=l);if(-1===c||o||32===p||9===p)throw new SyntaxError("Unexpected end of input");-1===d&&(d=l);const u=e.slice(c,d);return void 0===i?Fa(t,u,s):(void 0===n?Fa(s,u,!0):Fa(s,n,a?u.replace(/\\/g,""):u),Fa(t,i,s)),t}};const za=d,qa=s,$a=n,Va=o,Wa=c,{randomBytes:Ga,createHash:Ha}=p,{URL:Ka}=t,Ja=Gs,Qa=pa,Ya=ya,{BINARY_TYPES:Xa,EMPTY_BUFFER:Za,GUID:er,kForOnEventAttribute:tr,kListener:ir,kStatusCode:nr,kWebSocket:sr,NOOP:ar}=Es,{EventTarget:{addEventListener:rr,removeEventListener:or}}=Aa,{format:cr,parse:pr}=Ua,{toBuffer:dr}=Ts,lr=Symbol("kAborted"),ur=[8,13],mr=["CONNECTING","OPEN","CLOSING","CLOSED"],hr=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;class fr extends za{constructor(e,t,i){super(),this._binaryType=Xa[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Za,this._closeTimer=null,this._extensions={},this._paused=!1,this._protocol="",this._readyState=fr.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,null!==e?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,void 0===t?t=[]:Array.isArray(t)||("object"==typeof t&&null!==t?(i=t,t=[]):t=[t]),gr(this,e,t,i)):this._isServer=!0}get binaryType(){return this._binaryType}set binaryType(e){Xa.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,t,i){const n=new Qa({binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation});this._sender=new Ya(e,this._extensions,i.generateMask),this._receiver=n,this._socket=e,n[sr]=this,e[sr]=this,n.on("conclude",wr),n.on("drain",Sr),n.on("error",Rr),n.on("message",kr),n.on("ping",Tr),n.on("pong",Pr),e.setTimeout(0),e.setNoDelay(),t.length>0&&e.unshift(t),e.on("close",Or),e.on("data",Dr),e.on("end",Ir),e.on("error",jr),this._readyState=fr.OPEN,this.emit("open")}emitClose(){if(!this._socket)return this._readyState=fr.CLOSED,void this.emit("close",this._closeCode,this._closeMessage);this._extensions[Ja.extensionName]&&this._extensions[Ja.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=fr.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,t){if(this.readyState!==fr.CLOSED){if(this.readyState===fr.CONNECTING){const e="WebSocket was closed before the connection was established";return yr(this,this._req,e)}this.readyState!==fr.CLOSING?(this._readyState=fr.CLOSING,this._sender.close(e,t,!this._isServer,(e=>{e||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())})),this._closeTimer=setTimeout(this._socket.destroy.bind(this._socket),3e4)):this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end()}}pause(){this.readyState!==fr.CONNECTING&&this.readyState!==fr.CLOSED&&(this._paused=!0,this._socket.pause())}ping(e,t,i){if(this.readyState===fr.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");"function"==typeof e?(i=e,e=t=void 0):"function"==typeof t&&(i=t,t=void 0),"number"==typeof e&&(e=e.toString()),this.readyState===fr.OPEN?(void 0===t&&(t=!this._isServer),this._sender.ping(e||Za,t,i)):xr(this,e,i)}pong(e,t,i){if(this.readyState===fr.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");"function"==typeof e?(i=e,e=t=void 0):"function"==typeof t&&(i=t,t=void 0),"number"==typeof e&&(e=e.toString()),this.readyState===fr.OPEN?(void 0===t&&(t=!this._isServer),this._sender.pong(e||Za,t,i)):xr(this,e,i)}resume(){this.readyState!==fr.CONNECTING&&this.readyState!==fr.CLOSED&&(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,t,i){if(this.readyState===fr.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if("function"==typeof t&&(i=t,t={}),"number"==typeof e&&(e=e.toString()),this.readyState!==fr.OPEN)return void xr(this,e,i);const n={binary:"string"!=typeof e,mask:!this._isServer,compress:!0,fin:!0,...t};this._extensions[Ja.extensionName]||(n.compress=!1),this._sender.send(e||Za,n,i)}terminate(){if(this.readyState!==fr.CLOSED){if(this.readyState===fr.CONNECTING){const e="WebSocket was closed before the connection was established";return yr(this,this._req,e)}this._socket&&(this._readyState=fr.CLOSING,this._socket.destroy())}}}function gr(e,t,i,n){const s={protocolVersion:ur[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...n,createConnection:void 0,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(!ur.includes(s.protocolVersion))throw new RangeError(`Unsupported protocol version: ${s.protocolVersion} (supported versions: ${ur.join(", ")})`);let a;if(t instanceof Ka)a=t,e._url=t.href;else{try{a=new Ka(t)}catch(e){throw new SyntaxError(`Invalid URL: ${t}`)}e._url=t}const r="wss:"===a.protocol,o="ws+unix:"===a.protocol;let c;if("ws:"===a.protocol||r||o?o&&!a.pathname?c="The URL's pathname is empty":a.hash&&(c="The URL contains a fragment identifier"):c='The URL\'s protocol must be one of "ws:", "wss:", or "ws+unix:"',c){const t=new SyntaxError(c);if(0===e._redirects)throw t;return void vr(e,t)}const p=r?443:80,d=Ga(16).toString("base64"),l=r?qa.request:$a.request,u=new Set;let m,h;if(s.createConnection=r?_r:br,s.defaultPort=s.defaultPort||p,s.port=a.port||p,s.host=a.hostname.startsWith("[")?a.hostname.slice(1,-1):a.hostname,s.headers={...s.headers,"Sec-WebSocket-Version":s.protocolVersion,"Sec-WebSocket-Key":d,Connection:"Upgrade",Upgrade:"websocket"},s.path=a.pathname+a.search,s.timeout=s.handshakeTimeout,s.perMessageDeflate&&(m=new Ja(!0!==s.perMessageDeflate?s.perMessageDeflate:{},!1,s.maxPayload),s.headers["Sec-WebSocket-Extensions"]=cr({[Ja.extensionName]:m.offer()})),i.length){for(const e of i){if("string"!=typeof e||!hr.test(e)||u.has(e))throw new SyntaxError("An invalid or duplicated subprotocol was specified");u.add(e)}s.headers["Sec-WebSocket-Protocol"]=i.join(",")}if(s.origin&&(s.protocolVersion<13?s.headers["Sec-WebSocket-Origin"]=s.origin:s.headers.Origin=s.origin),(a.username||a.password)&&(s.auth=`${a.username}:${a.password}`),o){const e=s.path.split(":");s.socketPath=e[0],s.path=e[1]}if(s.followRedirects){if(0===e._redirects){e._originalIpc=o,e._originalSecure=r,e._originalHostOrSocketPath=o?s.socketPath:a.host;const t=n&&n.headers;if(n={...n,headers:{}},t)for(const[e,i]of Object.entries(t))n.headers[e.toLowerCase()]=i}else if(0===e.listenerCount("redirect")){const t=o?!!e._originalIpc&&s.socketPath===e._originalHostOrSocketPath:!e._originalIpc&&a.host===e._originalHostOrSocketPath;(!t||e._originalSecure&&!r)&&(delete s.headers.authorization,delete s.headers.cookie,t||delete s.headers.host,s.auth=void 0)}s.auth&&!n.headers.authorization&&(n.headers.authorization="Basic "+Buffer.from(s.auth).toString("base64")),h=e._req=l(s),e._redirects&&e.emit("redirect",e.url,h)}else h=e._req=l(s);s.timeout&&h.on("timeout",(()=>{yr(e,h,"Opening handshake has timed out")})),h.on("error",(t=>{null===h||h[lr]||(h=e._req=null,vr(e,t))})),h.on("response",(a=>{const r=a.headers.location,o=a.statusCode;if(r&&s.followRedirects&&o>=300&&o<400){if(++e._redirects>s.maxRedirects)return void yr(e,h,"Maximum redirects exceeded");let a;h.abort();try{a=new Ka(r,t)}catch(t){const i=new SyntaxError(`Invalid URL: ${r}`);return void vr(e,i)}gr(e,a,i,n)}else e.emit("unexpected-response",h,a)||yr(e,h,`Unexpected server response: ${a.statusCode}`)})),h.on("upgrade",((t,i,n)=>{if(e.emit("upgrade",t),e.readyState!==fr.CONNECTING)return;if(h=e._req=null,"websocket"!==t.headers.upgrade.toLowerCase())return void yr(e,i,"Invalid Upgrade header");const a=Ha("sha1").update(d+er).digest("base64");if(t.headers["sec-websocket-accept"]!==a)return void yr(e,i,"Invalid Sec-WebSocket-Accept header");const r=t.headers["sec-websocket-protocol"];let o;if(void 0!==r?u.size?u.has(r)||(o="Server sent an invalid subprotocol"):o="Server sent a subprotocol but none was requested":u.size&&(o="Server sent no subprotocol"),o)return void yr(e,i,o);r&&(e._protocol=r);const c=t.headers["sec-websocket-extensions"];if(void 0!==c){if(!m){return void yr(e,i,"Server sent a Sec-WebSocket-Extensions header but no extension was requested")}let t;try{t=pr(c)}catch(t){return void yr(e,i,"Invalid Sec-WebSocket-Extensions header")}const n=Object.keys(t);if(1!==n.length||n[0]!==Ja.extensionName){return void yr(e,i,"Server indicated an extension that was not requested")}try{m.accept(t[Ja.extensionName])}catch(t){return void yr(e,i,"Invalid Sec-WebSocket-Extensions header")}e._extensions[Ja.extensionName]=m}e.setSocket(i,n,{generateMask:s.generateMask,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation})})),h.end()}function vr(e,t){e._readyState=fr.CLOSING,e.emit("error",t),e.emitClose()}function br(e){return e.path=e.socketPath,Va.connect(e)}function _r(e){return e.path=void 0,e.servername||""===e.servername||(e.servername=Va.isIP(e.host)?"":e.host),Wa.connect(e)}function yr(e,t,i){e._readyState=fr.CLOSING;const n=new Error(i);Error.captureStackTrace(n,yr),t.setHeader?(t[lr]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(vr,e,n)):(t.destroy(n),t.once("error",e.emit.bind(e,"error")),t.once("close",e.emitClose.bind(e)))}function xr(e,t,i){if(t){const i=dr(t).length;e._socket?e._sender._bufferedBytes+=i:e._bufferedAmount+=i}if(i){i(new Error(`WebSocket is not open: readyState ${e.readyState} (${mr[e.readyState]})`))}}function wr(e,t){const i=this[sr];i._closeFrameReceived=!0,i._closeMessage=t,i._closeCode=e,void 0!==i._socket[sr]&&(i._socket.removeListener("data",Dr),process.nextTick(Er,i._socket),1005===e?i.close():i.close(e,t))}function Sr(){const e=this[sr];e.isPaused||e._socket.resume()}function Rr(e){const t=this[sr];void 0!==t._socket[sr]&&(t._socket.removeListener("data",Dr),process.nextTick(Er,t._socket),t.close(e[nr])),t.emit("error",e)}function Cr(){this[sr].emitClose()}function kr(e,t){this[sr].emit("message",e,t)}function Tr(e){const t=this[sr];t.pong(e,!t._isServer,ar),t.emit("ping",e)}function Pr(e){this[sr].emit("pong",e)}function Er(e){e.resume()}function Or(){const e=this[sr];let t;this.removeListener("close",Or),this.removeListener("data",Dr),this.removeListener("end",Ir),e._readyState=fr.CLOSING,this._readableState.endEmitted||e._closeFrameReceived||e._receiver._writableState.errorEmitted||null===(t=e._socket.read())||e._receiver.write(t),e._receiver.end(),this[sr]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on("error",Cr),e._receiver.on("finish",Cr))}function Dr(e){this[sr]._receiver.write(e)||this.pause()}function Ir(){const e=this[sr];e._readyState=fr.CLOSING,e._receiver.end(),this.end()}function jr(){const e=this[sr];this.removeListener("error",jr),this.on("error",ar),e&&(e._readyState=fr.CLOSING,this.destroy())}Object.defineProperty(fr,"CONNECTING",{enumerable:!0,value:mr.indexOf("CONNECTING")}),Object.defineProperty(fr.prototype,"CONNECTING",{enumerable:!0,value:mr.indexOf("CONNECTING")}),Object.defineProperty(fr,"OPEN",{enumerable:!0,value:mr.indexOf("OPEN")}),Object.defineProperty(fr.prototype,"OPEN",{enumerable:!0,value:mr.indexOf("OPEN")}),Object.defineProperty(fr,"CLOSING",{enumerable:!0,value:mr.indexOf("CLOSING")}),Object.defineProperty(fr.prototype,"CLOSING",{enumerable:!0,value:mr.indexOf("CLOSING")}),Object.defineProperty(fr,"CLOSED",{enumerable:!0,value:mr.indexOf("CLOSED")}),Object.defineProperty(fr.prototype,"CLOSED",{enumerable:!0,value:mr.indexOf("CLOSED")}),["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach((e=>{Object.defineProperty(fr.prototype,e,{enumerable:!0})})),["open","error","close","message"].forEach((e=>{Object.defineProperty(fr.prototype,`on${e}`,{enumerable:!0,get(){for(const t of this.listeners(e))if(t[tr])return t[ir];return null},set(t){for(const t of this.listeners(e))if(t[tr]){this.removeListener(e,t);break}"function"==typeof t&&this.addEventListener(e,t,{[tr]:!0})}})})),fr.prototype.addEventListener=rr,fr.prototype.removeEventListener=or;const Lr=fr,Mr=process.nextTick,Ar="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase();const Nr={websocket:class extends cs{constructor(e){super(e),this.supportsBinary=!e.forceBase64}get name(){return"websocket"}doOpen(){if(!this.check())return;const e=this.uri(),t=this.opts.protocols,i=Ar?{}:ns(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(i.headers=this.opts.extraHeaders);try{this.ws=new Lr(e,t,i)}catch(e){return this.emitReserved("error",e)}this.ws.binaryType=this.socket.binaryType||"nodebuffer",this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=e=>this.onClose({description:"websocket connection closed",context:e}),this.ws.onmessage=e=>this.onData(e.data),this.ws.onerror=e=>this.onError("websocket error",e)}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const i=e[t],n=t===e.length-1;Kn(i,this.supportsBinary,(e=>{const t={};if(i.options&&(t.compress=i.options.compress),this.opts.perMessageDeflate){("string"==typeof e?Buffer.byteLength(e):e.length)<this.opts.perMessageDeflate.threshold&&(t.compress=!1)}try{this.ws.send(e,t)}catch(e){}n&&Mr((()=>{this.writable=!0,this.emitReserved("drain")}),this.setTimeoutFn)}))}}doClose(){void 0!==this.ws&&(this.ws.close(),this.ws=null)}uri(){let e=this.query||{};const t=this.opts.secure?"wss":"ws";let i="";this.opts.port&&("wss"===t&&443!==Number(this.opts.port)||"ws"===t&&80!==Number(this.opts.port))&&(i=":"+this.opts.port),this.opts.timestampRequests&&(e[this.opts.timestampParam]=fs()),this.supportsBinary||(e.b64=1);const n=gs(e);return t+"://"+(-1!==this.opts.hostname.indexOf(":")?"["+this.opts.hostname+"]":this.opts.hostname)+i+this.opts.path+(n.length?"?"+n:"")}check(){return!!Lr}},polling:class extends cs{constructor(e){if(super(e),this.polling=!1,"undefined"!=typeof location){const t="https:"===location.protocol;let i=location.port;i||(i=t?"443":"80"),this.xd="undefined"!=typeof location&&e.hostname!==location.hostname||i!==e.port,this.xs=e.secure!==t}const t=e&&e.forceBase64;this.supportsBinary=Rs&&!t}get name(){return"polling"}doOpen(){this.poll()}pause(e){this.readyState="pausing";const t=()=>{this.readyState="paused",e()};if(this.polling||!this.writable){let e=0;this.polling&&(e++,this.once("pollComplete",(function(){--e||t()}))),this.writable||(e++,this.once("drain",(function(){--e||t()})))}else t()}poll(){this.polling=!0,this.doPoll(),this.emitReserved("poll")}onData(e){((e,t)=>{const i=e.split(es),n=[];for(let e=0;e<i.length;e++){const s=Yn(i[e],t);if(n.push(s),"error"===s.type)break}return n})(e,this.socket.binaryType).forEach((e=>{if("opening"===this.readyState&&"open"===e.type&&this.onOpen(),"close"===e.type)return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(e)})),"closed"!==this.readyState&&(this.polling=!1,this.emitReserved("pollComplete"),"open"===this.readyState&&this.poll())}doClose(){const e=()=>{this.write([{type:"close"}])};"open"===this.readyState?e():this.once("open",e)}write(e){this.writable=!1,((e,t)=>{const i=e.length,n=new Array(i);let s=0;e.forEach(((e,a)=>{Kn(e,!1,(e=>{n[a]=e,++s===i&&t(n.join(es))}))}))})(e,(e=>{this.doWrite(e,(()=>{this.writable=!0,this.emitReserved("drain")}))}))}uri(){let e=this.query||{};const t=this.opts.secure?"https":"http";let i="";!1!==this.opts.timestampRequests&&(e[this.opts.timestampParam]=fs()),this.supportsBinary||e.sid||(e.b64=1),this.opts.port&&("https"===t&&443!==Number(this.opts.port)||"http"===t&&80!==Number(this.opts.port))&&(i=":"+this.opts.port);const n=gs(e);return t+"://"+(-1!==this.opts.hostname.indexOf(":")?"["+this.opts.hostname+"]":this.opts.hostname)+i+this.opts.path+(n.length?"?"+n:"")}request(e={}){return Object.assign(e,{xd:this.xd,xs:this.xs},this.opts),new Cs(this.uri(),e)}doWrite(e,t){const i=this.request({method:"POST",data:e});i.on("success",t),i.on("error",((e,t)=>{this.onError("xhr post error",e,t)}))}doPoll(){const e=this.request();e.on("data",this.onData.bind(this)),e.on("error",((e,t)=>{this.onError("xhr poll error",e,t)})),this.pollXhr=e}}},Br=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,Fr=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function Ur(e){const t=e,i=e.indexOf("["),n=e.indexOf("]");-1!=i&&-1!=n&&(e=e.substring(0,i)+e.substring(i,n).replace(/:/g,";")+e.substring(n,e.length));let s=Br.exec(e||""),a={},r=14;for(;r--;)a[Fr[r]]=s[r]||"";return-1!=i&&-1!=n&&(a.source=t,a.host=a.host.substring(1,a.host.length-1).replace(/;/g,":"),a.authority=a.authority.replace("[","").replace("]","").replace(/;/g,":"),a.ipv6uri=!0),a.pathNames=function(e,t){const i=/\/{2,9}/g,n=t.replace(i,"/").split("/");"/"!=t.slice(0,1)&&0!==t.length||n.splice(0,1);"/"==t.slice(-1)&&n.splice(n.length-1,1);return n}(0,a.path),a.queryKey=function(e,t){const i={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,(function(e,t,n){t&&(i[t]=n)})),i}(0,a.query),a}class zr extends ts{constructor(e,t={}){super(),this.writeBuffer=[],e&&"object"==typeof e&&(t=e,e=null),e?(e=Ur(e),t.hostname=e.host,t.secure="https"===e.protocol||"wss"===e.protocol,t.port=e.port,e.query&&(t.query=e.query)):t.host&&(t.hostname=Ur(t.host).host),rs(this,t),this.secure=null!=t.secure?t.secure:"undefined"!=typeof location&&"https:"===location.protocol,t.hostname&&!t.port&&(t.port=this.secure?"443":"80"),this.hostname=t.hostname||("undefined"!=typeof location?location.hostname:"localhost"),this.port=t.port||("undefined"!=typeof location&&location.port?location.port:this.secure?"443":"80"),this.transports=t.transports||["polling","websocket"],this.writeBuffer=[],this.prevBufferLen=0,this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!0},t),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),"string"==typeof this.opts.query&&(this.opts.query=function(e){let t={},i=e.split("&");for(let e=0,n=i.length;e<n;e++){let n=i[e].split("=");t[decodeURIComponent(n[0])]=decodeURIComponent(n[1])}return t}(this.opts.query)),this.id=null,this.upgrades=null,this.pingInterval=null,this.pingTimeout=null,this.pingTimeoutTimer=null,"function"==typeof addEventListener&&(this.opts.closeOnBeforeunload&&(this.beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this.beforeunloadEventListener,!1)),"localhost"!==this.hostname&&(this.offlineEventListener=()=>{this.onClose("transport close",{description:"network connection lost"})},addEventListener("offline",this.offlineEventListener,!1))),this.open()}createTransport(e){const t=Object.assign({},this.opts.query);t.EIO=4,t.transport=e,this.id&&(t.sid=this.id);const i=Object.assign({},this.opts.transportOptions[e],this.opts,{query:t,socket:this,hostname:this.hostname,secure:this.secure,port:this.port});return new Nr[e](i)}open(){let e;if(this.opts.rememberUpgrade&&zr.priorWebsocketSuccess&&-1!==this.transports.indexOf("websocket"))e="websocket";else{if(0===this.transports.length)return void this.setTimeoutFn((()=>{this.emitReserved("error","No transports available")}),0);e=this.transports[0]}this.readyState="opening";try{e=this.createTransport(e)}catch(e){return this.transports.shift(),void this.open()}e.open(),this.setTransport(e)}setTransport(e){this.transport&&this.transport.removeAllListeners(),this.transport=e,e.on("drain",this.onDrain.bind(this)).on("packet",this.onPacket.bind(this)).on("error",this.onError.bind(this)).on("close",(e=>this.onClose("transport close",e)))}probe(e){let t=this.createTransport(e),i=!1;zr.priorWebsocketSuccess=!1;const n=()=>{i||(t.send([{type:"ping",data:"probe"}]),t.once("packet",(e=>{if(!i)if("pong"===e.type&&"probe"===e.data){if(this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;zr.priorWebsocketSuccess="websocket"===t.name,this.transport.pause((()=>{i||"closed"!==this.readyState&&(p(),this.setTransport(t),t.send([{type:"upgrade"}]),this.emitReserved("upgrade",t),t=null,this.upgrading=!1,this.flush())}))}else{const e=new Error("probe error");e.transport=t.name,this.emitReserved("upgradeError",e)}})))};function s(){i||(i=!0,p(),t.close(),t=null)}const a=e=>{const i=new Error("probe error: "+e);i.transport=t.name,s(),this.emitReserved("upgradeError",i)};function r(){a("transport closed")}function o(){a("socket closed")}function c(e){t&&e.name!==t.name&&s()}const p=()=>{t.removeListener("open",n),t.removeListener("error",a),t.removeListener("close",r),this.off("close",o),this.off("upgrading",c)};t.once("open",n),t.once("error",a),t.once("close",r),this.once("close",o),this.once("upgrading",c),t.open()}onOpen(){if(this.readyState="open",zr.priorWebsocketSuccess="websocket"===this.transport.name,this.emitReserved("open"),this.flush(),"open"===this.readyState&&this.opts.upgrade){let e=0;const t=this.upgrades.length;for(;e<t;e++)this.probe(this.upgrades[e])}}onPacket(e){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState)switch(this.emitReserved("packet",e),this.emitReserved("heartbeat"),e.type){case"open":this.onHandshake(JSON.parse(e.data));break;case"ping":this.resetPingTimeout(),this.sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong");break;case"error":const t=new Error("server error");t.code=e.data,this.onError(t);break;case"message":this.emitReserved("data",e.data),this.emitReserved("message",e.data)}}onHandshake(e){this.emitReserved("handshake",e),this.id=e.sid,this.transport.query.sid=e.sid,this.upgrades=this.filterUpgrades(e.upgrades),this.pingInterval=e.pingInterval,this.pingTimeout=e.pingTimeout,this.maxPayload=e.maxPayload,this.onOpen(),"closed"!==this.readyState&&this.resetPingTimeout()}resetPingTimeout(){this.clearTimeoutFn(this.pingTimeoutTimer),this.pingTimeoutTimer=this.setTimeoutFn((()=>{this.onClose("ping timeout")}),this.pingInterval+this.pingTimeout),this.opts.autoUnref&&this.pingTimeoutTimer.unref()}onDrain(){this.writeBuffer.splice(0,this.prevBufferLen),this.prevBufferLen=0,0===this.writeBuffer.length?this.emitReserved("drain"):this.flush()}flush(){if("closed"!==this.readyState&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const e=this.getWritablePackets();this.transport.send(e),this.prevBufferLen=e.length,this.emitReserved("flush")}}getWritablePackets(){if(!(this.maxPayload&&"polling"===this.transport.name&&this.writeBuffer.length>1))return this.writeBuffer;let e=1;for(let i=0;i<this.writeBuffer.length;i++){const n=this.writeBuffer[i].data;if(n&&(e+="string"==typeof(t=n)?function(e){let t=0,i=0;for(let n=0,s=e.length;n<s;n++)t=e.charCodeAt(n),t<128?i+=1:t<2048?i+=2:t<55296||t>=57344?i+=3:(n++,i+=4);return i}(t):Math.ceil(1.33*(t.byteLength||t.size))),i>0&&e>this.maxPayload)return this.writeBuffer.slice(0,i);e+=2}var t;return this.writeBuffer}write(e,t,i){return this.sendPacket("message",e,t,i),this}send(e,t,i){return this.sendPacket("message",e,t,i),this}sendPacket(e,t,i,n){if("function"==typeof t&&(n=t,t=void 0),"function"==typeof i&&(n=i,i=null),"closing"===this.readyState||"closed"===this.readyState)return;(i=i||{}).compress=!1!==i.compress;const s={type:e,data:t,options:i};this.emitReserved("packetCreate",s),this.writeBuffer.push(s),n&&this.once("flush",n),this.flush()}close(){const e=()=>{this.onClose("forced close"),this.transport.close()},t=()=>{this.off("upgrade",t),this.off("upgradeError",t),e()},i=()=>{this.once("upgrade",t),this.once("upgradeError",t)};return"opening"!==this.readyState&&"open"!==this.readyState||(this.readyState="closing",this.writeBuffer.length?this.once("drain",(()=>{this.upgrading?i():e()})):this.upgrading?i():e()),this}onError(e){zr.priorWebsocketSuccess=!1,this.emitReserved("error",e),this.onClose("transport error",e)}onClose(e,t){"opening"!==this.readyState&&"open"!==this.readyState&&"closing"!==this.readyState||(this.clearTimeoutFn(this.pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),"function"==typeof removeEventListener&&(removeEventListener("beforeunload",this.beforeunloadEventListener,!1),removeEventListener("offline",this.offlineEventListener,!1)),this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this.prevBufferLen=0)}filterUpgrades(e){const t=[];let i=0;const n=e.length;for(;i<n;i++)~this.transports.indexOf(e[i])&&t.push(e[i]);return t}}zr.protocol=4;const qr="function"==typeof ArrayBuffer,$r=Object.prototype.toString,Vr="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===$r.call(Blob),Wr="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===$r.call(File);function Gr(e){return qr&&(e instanceof ArrayBuffer||(e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer)(e))||Vr&&e instanceof Blob||Wr&&e instanceof File}function Hr(e,t){if(!e||"object"!=typeof e)return!1;if(Array.isArray(e)){for(let t=0,i=e.length;t<i;t++)if(Hr(e[t]))return!0;return!1}if(Gr(e))return!0;if(e.toJSON&&"function"==typeof e.toJSON&&1===arguments.length)return Hr(e.toJSON(),!0);for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t)&&Hr(e[t]))return!0;return!1}function Kr(e){const t=[],i=e.data,n=e;return n.data=Jr(i,t),n.attachments=t.length,{packet:n,buffers:t}}function Jr(e,t){if(!e)return e;if(Gr(e)){const i={_placeholder:!0,num:t.length};return t.push(e),i}if(Array.isArray(e)){const i=new Array(e.length);for(let n=0;n<e.length;n++)i[n]=Jr(e[n],t);return i}if("object"==typeof e&&!(e instanceof Date)){const i={};for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&(i[n]=Jr(e[n],t));return i}return e}function Qr(e,t){return e.data=Yr(e.data,t),delete e.attachments,e}function Yr(e,t){if(!e)return e;if(e&&!0===e._placeholder){if("number"==typeof e.num&&e.num>=0&&e.num<t.length)return t[e.num];throw new Error("illegal attachments")}if(Array.isArray(e))for(let i=0;i<e.length;i++)e[i]=Yr(e[i],t);else if("object"==typeof e)for(const i in e)Object.prototype.hasOwnProperty.call(e,i)&&(e[i]=Yr(e[i],t));return e}var Xr;!function(e){e[e.CONNECT=0]="CONNECT",e[e.DISCONNECT=1]="DISCONNECT",e[e.EVENT=2]="EVENT",e[e.ACK=3]="ACK",e[e.CONNECT_ERROR=4]="CONNECT_ERROR",e[e.BINARY_EVENT=5]="BINARY_EVENT",e[e.BINARY_ACK=6]="BINARY_ACK"}(Xr||(Xr={}));class Zr extends ts{constructor(e){super(),this.reviver=e}add(e){let t;if("string"==typeof e){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");t=this.decodeString(e);const i=t.type===Xr.BINARY_EVENT;i||t.type===Xr.BINARY_ACK?(t.type=i?Xr.EVENT:Xr.ACK,this.reconstructor=new eo(t),0===t.attachments&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else{if(!Gr(e)&&!e.base64)throw new Error("Unknown type: "+e);if(!this.reconstructor)throw new Error("got binary data when not reconstructing a packet");t=this.reconstructor.takeBinaryData(e),t&&(this.reconstructor=null,super.emitReserved("decoded",t))}}decodeString(e){let t=0;const i={type:Number(e.charAt(0))};if(void 0===Xr[i.type])throw new Error("unknown packet type "+i.type);if(i.type===Xr.BINARY_EVENT||i.type===Xr.BINARY_ACK){const n=t+1;for(;"-"!==e.charAt(++t)&&t!=e.length;);const s=e.substring(n,t);if(s!=Number(s)||"-"!==e.charAt(t))throw new Error("Illegal attachments");i.attachments=Number(s)}if("/"===e.charAt(t+1)){const n=t+1;for(;++t;){if(","===e.charAt(t))break;if(t===e.length)break}i.nsp=e.substring(n,t)}else i.nsp="/";const n=e.charAt(t+1);if(""!==n&&Number(n)==n){const n=t+1;for(;++t;){const i=e.charAt(t);if(null==i||Number(i)!=i){--t;break}if(t===e.length)break}i.id=Number(e.substring(n,t+1))}if(e.charAt(++t)){const n=this.tryParse(e.substr(t));if(!Zr.isPayloadValid(i.type,n))throw new Error("invalid payload");i.data=n}return i}tryParse(e){try{return JSON.parse(e,this.reviver)}catch(e){return!1}}static isPayloadValid(e,t){switch(e){case Xr.CONNECT:return"object"==typeof t;case Xr.DISCONNECT:return void 0===t;case Xr.CONNECT_ERROR:return"string"==typeof t||"object"==typeof t;case Xr.EVENT:case Xr.BINARY_EVENT:return Array.isArray(t)&&t.length>0;case Xr.ACK:case Xr.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class eo{constructor(e){this.packet=e,this.buffers=[],this.reconPack=e}takeBinaryData(e){if(this.buffers.push(e),this.buffers.length===this.reconPack.attachments){const e=Qr(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}var to=Object.freeze({__proto__:null,protocol:5,get PacketType(){return Xr},Encoder:class{constructor(e){this.replacer=e}encode(e){return e.type!==Xr.EVENT&&e.type!==Xr.ACK||!Hr(e)?[this.encodeAsString(e)]:this.encodeAsBinary({type:e.type===Xr.EVENT?Xr.BINARY_EVENT:Xr.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id})}encodeAsString(e){let t=""+e.type;return e.type!==Xr.BINARY_EVENT&&e.type!==Xr.BINARY_ACK||(t+=e.attachments+"-"),e.nsp&&"/"!==e.nsp&&(t+=e.nsp+","),null!=e.id&&(t+=e.id),null!=e.data&&(t+=JSON.stringify(e.data,this.replacer)),t}encodeAsBinary(e){const t=Kr(e),i=this.encodeAsString(t.packet),n=t.buffers;return n.unshift(i),n}},Decoder:Zr});function io(e,t,i){return e.on(t,i),function(){e.off(t,i)}}const no=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class so extends ts{constructor(e,t,i){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=e,this.nsp=t,i&&i.auth&&(this.auth=i.auth),this._opts=Object.assign({},i),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const e=this.io;this.subs=[io(e,"open",this.onopen.bind(this)),io(e,"packet",this.onpacket.bind(this)),io(e,"error",this.onerror.bind(this)),io(e,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected||(this.subEvents(),this.io._reconnecting||this.io.open(),"open"===this.io._readyState&&this.onopen()),this}open(){return this.connect()}send(...e){return e.unshift("message"),this.emit.apply(this,e),this}emit(e,...t){if(no.hasOwnProperty(e))throw new Error('"'+e.toString()+'" is a reserved event name');if(t.unshift(e),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(t),this;const i={type:Xr.EVENT,data:t,options:{}};if(i.options.compress=!1!==this.flags.compress,"function"==typeof t[t.length-1]){const e=this.ids++,n=t.pop();this._registerAckCallback(e,n),i.id=e}const n=this.io.engine&&this.io.engine.transport&&this.io.engine.transport.writable;return this.flags.volatile&&(!n||!this.connected)||(this.connected?(this.notifyOutgoingListeners(i),this.packet(i)):this.sendBuffer.push(i)),this.flags={},this}_registerAckCallback(e,t){var i;const n=null!==(i=this.flags.timeout)&&void 0!==i?i:this._opts.ackTimeout;if(void 0===n)return void(this.acks[e]=t);const s=this.io.setTimeoutFn((()=>{delete this.acks[e];for(let t=0;t<this.sendBuffer.length;t++)this.sendBuffer[t].id===e&&this.sendBuffer.splice(t,1);t.call(this,new Error("operation has timed out"))}),n);this.acks[e]=(...e)=>{this.io.clearTimeoutFn(s),t.apply(this,[null,...e])}}emitWithAck(e,...t){const i=void 0!==this.flags.timeout||void 0!==this._opts.ackTimeout;return new Promise(((n,s)=>{t.push(((e,t)=>i?e?s(e):n(t):n(e))),this.emit(e,...t)}))}_addToQueue(e){let t;"function"==typeof e[e.length-1]&&(t=e.pop());const i={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push(((e,...n)=>{if(i!==this._queue[0])return;return null!==e?i.tryCount>this._opts.retries&&(this._queue.shift(),t&&t(e)):(this._queue.shift(),t&&t(null,...n)),i.pending=!1,this._drainQueue()})),this._queue.push(i),this._drainQueue()}_drainQueue(e=!1){if(!this.connected||0===this._queue.length)return;const t=this._queue[0];t.pending&&!e||(t.pending=!0,t.tryCount++,this.flags=t.flags,this.emit.apply(this,t.args))}packet(e){e.nsp=this.nsp,this.io._packet(e)}onopen(){"function"==typeof this.auth?this.auth((e=>{this._sendConnectPacket(e)})):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:Xr.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},e):e})}onerror(e){this.connected||this.emitReserved("connect_error",e)}onclose(e,t){this.connected=!1,delete this.id,this.emitReserved("disconnect",e,t)}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case Xr.CONNECT:e.data&&e.data.sid?this.onconnect(e.data.sid,e.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case Xr.EVENT:case Xr.BINARY_EVENT:this.onevent(e);break;case Xr.ACK:case Xr.BINARY_ACK:this.onack(e);break;case Xr.DISCONNECT:this.ondisconnect();break;case Xr.CONNECT_ERROR:this.destroy();const t=new Error(e.data.message);t.data=e.data.data,this.emitReserved("connect_error",t)}}onevent(e){const t=e.data||[];null!=e.id&&t.push(this.ack(e.id)),this.connected?this.emitEvent(t):this.receiveBuffer.push(Object.freeze(t))}emitEvent(e){if(this._anyListeners&&this._anyListeners.length){const t=this._anyListeners.slice();for(const i of t)i.apply(this,e)}super.emit.apply(this,e),this._pid&&e.length&&"string"==typeof e[e.length-1]&&(this._lastOffset=e[e.length-1])}ack(e){const t=this;let i=!1;return function(...n){i||(i=!0,t.packet({type:Xr.ACK,id:e,data:n}))}}onack(e){const t=this.acks[e.id];"function"==typeof t&&(t.apply(this,e.data),delete this.acks[e.id])}onconnect(e,t){this.id=e,this.recovered=t&&this._pid===t,this._pid=t,this.connected=!0,this.emitBuffered(),this.emitReserved("connect"),this._drainQueue(!0)}emitBuffered(){this.receiveBuffer.forEach((e=>this.emitEvent(e))),this.receiveBuffer=[],this.sendBuffer.forEach((e=>{this.notifyOutgoingListeners(e),this.packet(e)})),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach((e=>e())),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:Xr.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(e){return this.flags.compress=e,this}get volatile(){return this.flags.volatile=!0,this}timeout(e){return this.flags.timeout=e,this}onAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(e),this}prependAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(e),this}offAny(e){if(!this._anyListeners)return this;if(e){const t=this._anyListeners;for(let i=0;i<t.length;i++)if(e===t[i])return t.splice(i,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(e),this}prependAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(e),this}offAnyOutgoing(e){if(!this._anyOutgoingListeners)return this;if(e){const t=this._anyOutgoingListeners;for(let i=0;i<t.length;i++)if(e===t[i])return t.splice(i,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(e){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const t=this._anyOutgoingListeners.slice();for(const i of t)i.apply(this,e.data)}}}function ao(e){e=e||{},this.ms=e.min||100,this.max=e.max||1e4,this.factor=e.factor||2,this.jitter=e.jitter>0&&e.jitter<=1?e.jitter:0,this.attempts=0}ao.prototype.duration=function(){var e=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var t=Math.random(),i=Math.floor(t*this.jitter*e);e=0==(1&Math.floor(10*t))?e-i:e+i}return 0|Math.min(e,this.max)},ao.prototype.reset=function(){this.attempts=0},ao.prototype.setMin=function(e){this.ms=e},ao.prototype.setMax=function(e){this.max=e},ao.prototype.setJitter=function(e){this.jitter=e};class ro extends ts{constructor(e,t){var i;super(),this.nsps={},this.subs=[],e&&"object"==typeof e&&(t=e,e=void 0),(t=t||{}).path=t.path||"/socket.io",this.opts=t,rs(this,t),this.reconnection(!1!==t.reconnection),this.reconnectionAttempts(t.reconnectionAttempts||1/0),this.reconnectionDelay(t.reconnectionDelay||1e3),this.reconnectionDelayMax(t.reconnectionDelayMax||5e3),this.randomizationFactor(null!==(i=t.randomizationFactor)&&void 0!==i?i:.5),this.backoff=new ao({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(null==t.timeout?2e4:t.timeout),this._readyState="closed",this.uri=e;const n=t.parser||to;this.encoder=new n.Encoder,this.decoder=new n.Decoder,this._autoConnect=!1!==t.autoConnect,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,this):this._reconnection}reconnectionAttempts(e){return void 0===e?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var t;return void 0===e?this._reconnectionDelay:(this._reconnectionDelay=e,null===(t=this.backoff)||void 0===t||t.setMin(e),this)}randomizationFactor(e){var t;return void 0===e?this._randomizationFactor:(this._randomizationFactor=e,null===(t=this.backoff)||void 0===t||t.setJitter(e),this)}reconnectionDelayMax(e){var t;return void 0===e?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,null===(t=this.backoff)||void 0===t||t.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&0===this.backoff.attempts&&this.reconnect()}open(e){if(~this._readyState.indexOf("open"))return this;this.engine=new zr(this.uri,this.opts);const t=this.engine,i=this;this._readyState="opening",this.skipReconnect=!1;const n=io(t,"open",(function(){i.onopen(),e&&e()})),s=io(t,"error",(t=>{i.cleanup(),i._readyState="closed",this.emitReserved("error",t),e?e(t):i.maybeReconnectOnOpen()}));if(!1!==this._timeout){const e=this._timeout;0===e&&n();const i=this.setTimeoutFn((()=>{n(),t.close(),t.emit("error",new Error("timeout"))}),e);this.opts.autoUnref&&i.unref(),this.subs.push((function(){clearTimeout(i)}))}return this.subs.push(n),this.subs.push(s),this}connect(e){return this.open(e)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const e=this.engine;this.subs.push(io(e,"ping",this.onping.bind(this)),io(e,"data",this.ondata.bind(this)),io(e,"error",this.onerror.bind(this)),io(e,"close",this.onclose.bind(this)),io(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(e){try{this.decoder.add(e)}catch(e){this.onclose("parse error",e)}}ondecoded(e){Mr((()=>{this.emitReserved("packet",e)}),this.setTimeoutFn)}onerror(e){this.emitReserved("error",e)}socket(e,t){let i=this.nsps[e];return i?this._autoConnect&&!i.active&&i.connect():(i=new so(this,e,t),this.nsps[e]=i),i}_destroy(e){const t=Object.keys(this.nsps);for(const e of t){if(this.nsps[e].active)return}this._close()}_packet(e){const t=this.encoder.encode(e);for(let i=0;i<t.length;i++)this.engine.write(t[i],e.options)}cleanup(){this.subs.forEach((e=>e())),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close"),this.engine&&this.engine.close()}disconnect(){return this._close()}onclose(e,t){this.cleanup(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",e,t),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const e=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const t=this.backoff.duration();this._reconnecting=!0;const i=this.setTimeoutFn((()=>{e.skipReconnect||(this.emitReserved("reconnect_attempt",e.backoff.attempts),e.skipReconnect||e.open((t=>{t?(e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",t)):e.onreconnect()})))}),t);this.opts.autoUnref&&i.unref(),this.subs.push((function(){clearTimeout(i)}))}}onreconnect(){const e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",e)}}const oo={};function co(e,t){"object"==typeof e&&(t=e,e=void 0);const i=function(e,t="",i){let n=e;i=i||"undefined"!=typeof location&&location,null==e&&(e=i.protocol+"//"+i.host),"string"==typeof e&&("/"===e.charAt(0)&&(e="/"===e.charAt(1)?i.protocol+e:i.host+e),/^(https?|wss?):\/\//.test(e)||(e=void 0!==i?i.protocol+"//"+e:"https://"+e),n=Ur(e)),n.port||(/^(http|ws)$/.test(n.protocol)?n.port="80":/^(http|ws)s$/.test(n.protocol)&&(n.port="443")),n.path=n.path||"/";const s=-1!==n.host.indexOf(":")?"["+n.host+"]":n.host;return n.id=n.protocol+"://"+s+":"+n.port+t,n.href=n.protocol+"://"+s+(i&&i.port===n.port?"":":"+n.port),n}(e,(t=t||{}).path||"/socket.io"),n=i.source,s=i.id,a=i.path,r=oo[s]&&a in oo[s].nsps;let o;return t.forceNew||t["force new connection"]||!1===t.multiplex||r?o=new ro(n,t):(oo[s]||(oo[s]=new ro(n,t)),o=oo[s]),i.query&&!t.query&&(t.query=i.queryKey),o.socket(i.path,t)}Object.assign(co,{Manager:ro,Socket:so,io:co,connect:co});class po{constructor(e,t){t&&!t.transports&&(t.transports=["websocket"]),this._socket=co(e,t),this._socket.io.on("reconnect",(()=>{this._socket.sendBuffer=[]})),this._socket.io.on("reconnect_attempt",(()=>{this._wasConnectedUsingWebsocket?(this._socket.io.opts.transports=["websocket"],"safari"!==Vn.browserDetails.browser&&delete this._wasConnectedUsingWebsocket):this._socket.io.opts.transports=["polling","websocket"]})),this._socket.on("connect",(()=>{"websocket"===this.getTransport()&&(this._wasConnectedUsingWebsocket=!0)}))}connect(){this.isConnected()||this.isConnecting()||this._socket.open()}disconnect(){this._socket.disconnect()}disconnectOnConnect(){this._socket.once("connect",(()=>{this._socket.disconnect()}))}emit(){this._socket.emit.apply(this._socket,arguments)}emitIfConnected(e,t){this.isConnected()&&this.emit(e,t)}getTransport(){return this._socket&&this._socket.io&&this._socket.io.engine&&this._socket.io.engine.transport&&this._socket.io.engine.transport.name}getManager(){return this._socket.io}isConnecting(){return this._socket&&this._socket.connecting}isConnected(){return this._socket&&this._socket.connected}on(e,t){return this._socket.on(e,t),()=>{this._socket.off(e,t)}}once(e,t){this._socket.once(e,t)}off(e,t){this._socket.off(e,t)}}var lo="connection_blocked_by_network",uo="dominant_speaker";const mo=Vn.browserDetails.browser,ho=Vn.browserDetails.version;function fo(e,t){let i=e.match(/a=ssrc-group:FID (\d+) (\d+)\r\n/),n=t.match(/a=ssrc-group:FID (\d+) (\d+)\r\n/);i||(i=e.match(/a=ssrc:(\d+) cname:(.*)\r\n/g)[1].match(/a=ssrc:(\d+)/),n=t.match(/a=ssrc:(\d+) cname:(.*)\r\n/g)[1].match(/a=ssrc:(\d+)/));for(let e=1;e<i.length;e++)t=t.replace(new RegExp(n[e],"g"),i[e]);return t}function go(e){return"firefox"!==mo?e:jn.splitLines(e.trim()).map((e=>e.startsWith("a=msid-semantic:")?"a=msid-semantic: WMS *":e)).join("\r\n")+"\r\n"}const vo=console;function bo(e,t){const i=e.getSenders().find((e=>e.track&&"video"===e.track.kind));if(!i)return Promise.resolve();const n=i.getParameters();return n.encodings&&0===n.encodings.length?Promise.resolve():(n.encodings||(n.encodings=[{}]),0===t?delete n.encodings[0].maxBitrate:n.encodings[0].maxBitrate=1e3*t,i.setParameters(n).catch((e=>{vo.error("setParameters err: ",e)})))}const _o=console;class yo{constructor({peerConnectionId:e,bandwidth:t,maximumTurnBandwidth:i,deprioritizeH264Encoding:n}){this.peerConnectionId=e,this.relayCandidateSeen=!1,this.pc=null,this.wasEverConnected=!1,this.connectionStatus=null,this.stats={totalSent:0,totalRecv:0},this.bandwidth=t||0,this.maximumTurnBandwidth=i,this.pending=[],this.isOperationPending=!1,this.streamIds=[],this.streams=[],this.earlyIceCandidates=[],this.afterConnected=new Promise((e=>{this.registerConnected=e})),this.offerOptions={offerToReceiveAudio:!0,offerToReceiveVideo:!0},this._deprioritizeH264Encoding=n}setAndGetPeerConnection({clientId:e,constraints:t,peerConnectionConfig:i,shouldAddLocalVideo:n}){return this.peerConnectionConfig=i,this.shouldAddLocalVideo=n,this.clientId=e,this.pc=new RTCPeerConnection(i,t),this.signalingState=this.pc.signalingState,this.pc.addEventListener("signalingstatechange",(()=>{if(this.signalingState!==this.pc.signalingState&&(this.signalingState=this.pc.signalingState,"stable"===this.pc.signalingState)){this.isOperationPending=!1;const e=this.pending.shift();e&&e.apply()}})),this.pc}addStream(e){this.streamIds.push(e.id),this.streams.push(e),RTCPeerConnection.prototype.addTrack?(e.getAudioTracks().forEach((t=>{this.pc.addTrack(t,e)})),e.getVideoTracks().forEach((t=>{this.pc.addTrack(t,e)}))):this.pc.addStream(e)}addTrack(e,t){t||(t=this.streams[0]),t.addTrack(e),this.pc.addTrack(e,t)}removeTrack(e){this.streams[0].removeTrack(e);const t=this.pc.getSenders().find((t=>t.track===e));t&&this.pc.removeTrack(t)}removeStream(e){for(let t=0;t<this.streamIds.length;t++)this.streamIds[t]===e.id&&(this.streamIds.splice(t,1),this.streams.splice(t,1));this.pc&&(this.pc.removeTrack?e.getTracks().forEach((e=>{const t=this.pc.getSenders().find((t=>t.track===e));t&&this.pc.removeTrack(t)})):this.pc.removeStream&&this.pc.removeStream(e))}_setRemoteDescription(e){return this._deprioritizeH264Encoding&&(e.sdp=function(e){return jn.splitSections(e).map((e=>{if("video"!==jn.getKind(e))return e;const t=jn.matchPrefix(e,"a=rtpmap:").map((e=>jn.parseRtpMap(e))).filter((e=>/h264/i.test(e.name))).map((e=>""+e.payloadType));if(!t.length)return e;const i=jn.matchPrefix(e,"m=video")[0],n=/(\s\d+)+$/i.exec(i)[0],s=[...n.split(" ").filter((e=>e&&!t.includes(e))),...t].join(" "),a=i.replace(n," "+s);return e.replace(i,a)})).join("")}(e.sdp)),this.srdComplete=this.pc.setRemoteDescription(e),this.srdComplete.then((()=>{this.earlyIceCandidates.forEach((e=>this.pc.addIceCandidate(e))),this.earlyIceCandidates=[]}))}handleOffer(e){if(!this.canModifyPeerConnection())return new Promise((t=>{this.pending.push((()=>this.handleOffer(e).then(t)))}));this.isOperationPending=!0;let t=e.sdp;t=function(e){return"safari"!==mo&&("firefox"!==mo||ho>=63||60===ho)?e:jn.splitLines(e.trim()).filter((e=>!e.startsWith("a=extmap:")||"urn:ietf:params:rtp-hdrext:sdes:mid"!==jn.parseExtmap(e).uri)).join("\r\n")+"\r\n"}(t),t=go(t);const i={type:e.type,sdp:t};let n;return this._setRemoteDescription(i).then((()=>this.pc.createAnswer())).then((e=>(n=e,this.pc.setLocalDescription(e)))).then((()=>bo(this.pc,this.bandwidth))).then((()=>n))}handleAnswer(e){if(this.pendingOffer){const t=this.pendingOffer;return delete this.pendingOffer,this.pc.setLocalDescription(t).then((()=>this.handleAnswer(e)))}let t=e.sdp;t=go(t);const i={type:e.type,sdp:t};return this._setRemoteDescription(i).then((()=>bo(this.pc,this.bandwidth)),(e=>{_o.warn("Could not set remote description from remote answer: ",e)}))}addIceCandidate(e){this.srdComplete?this.srdComplete.then((()=>{"closed"!==this.pc.signalingState&&("safari"===Vn.browserDetails.browser&&e&&""===e.candidate||this.pc.addIceCandidate(e).catch((t=>{_o.warn("Failed to add ICE candidate ('%s'): %s",e?e.candidate:null,t)})))})):this.earlyIceCandidates.push(e)}canModifyPeerConnection(){return"stable"===this.pc.signalingState&&!this.isOperationPending}close(){const e=this.pc;if(e){e.oniceconnectionstatechange=null,e.onicecandidate=null,e.ontrack=null;try{e.close()}catch(e){console.warn("failures during close of session",e)}}}hasConnectedPeerConnection(){return this.pc&&"connected"===this.pc.connectionState}replaceTrack(e,t){const i=this.pc;if(!i)return!1;const n=i.getSenders();function s(i){const s=e=>e&&`id:${e.id},kind:${e.kind},state:${e.readyState}`;_o.warn(`${i}. newTrack:${s(t)}, oldTrack:${s(e)}, sender tracks: ${JSON.stringify(n.map((e=>`s ${s(e.track)}`)))}, sender first codecs: ${JSON.stringify(n.map((e=>(e.getParameters().codecs||[])[0])))}`)}if(n.length||s("No senders!"),e||(e=(n.find((e=>e.track&&e.track.kind===t.kind))||{}).track)||s("No sender with same kind! Add new track then."),window.RTCRtpSender&&window.RTCRtpSender.prototype.replaceTrack){if(e){const i=()=>{for(let i=0;i<n.length;i++){const a=n[i],r=a.track;if(a||r||s("One of the tracks is null!"),r.id===t.id)return Promise.resolve(t);if(r.id===e.id)return n[i].replaceTrack(t)}return null};let a=i();if(a)return a;let r=null,o=null;a=new Promise(((e,t)=>{r=e,o=t}));let c=0,p=setInterval((async()=>{const e=i();if(!e)return void(3<++c&&(clearInterval(p),p=null,s("No sender track to replace"),o("No sender track to replace")));clearInterval(p),p=null;const t=await e;r(t)}),1e3);return a}const a=this.streams.find((e=>e.getTracks().find((e=>e.id===t.id))))||this.streams[0];return a?i.addTrack(t,a):(s("No stream?"),Promise.reject(new Error("replaceTrack: No stream?")))}if(!this.canModifyPeerConnection())return void this.pending.push((()=>{this.replaceTrack(e,t)}));this.isOperationPending=!0;const a=i.onnegotiationneeded;return i.onnegotiationneeded=null,this.removeTrack(e),this.addTrack(t),setTimeout((()=>{i.onnegotiationneeded=a}),0),"offer"===i.localDescription.type?i.createOffer().then((e=>(e.sdp=fo(i.localDescription.sdp,e.sdp),i.setLocalDescription(e)))).then((()=>this._setRemoteDescription(i.remoteDescription))):this._setRemoteDescription(i.remoteDescription).then((()=>i.createAnswer())).then((e=>(e.sdp=fo(i.localDescription.sdp,e.sdp),i.setLocalDescription(e))))}maybeRestrictRelayBandwidth(){var e;this.pc.getStats&&(e=this.pc,e.getStats(null).then((e=>{let t,i;return e.forEach((n=>{if("transport"===n.type&&n.selectedCandidatePairId){const s=e.get(n.selectedCandidatePairId);if(!s)return;return t=e.get(s.localCandidateId).candidateType,void(i=e.get(s.remoteCandidateId).candidateType)}"candidate-pair"===n.type&&n.selected&&(t=e.get(n.localCandidateId).candidateType,i=e.get(n.remoteCandidateId).candidateType)})),"relay"===t||"relayed"===t||"relay"===i||"relayed"===i}))).then((e=>{e&&0===this.bandwidth&&this.changeBandwidth(this.maximumTurnBandwidth)}))}changeBandwidth(e){e!==this.bandwidth&&(this.canModifyPeerConnection()?(this.bandwidth=e,this.pc.localDescription&&""!==this.pc.localDescription.type&&bo(this.pc,this.bandwidth)):this.pending.push((()=>this.changeBandwidth(e))))}}const xo=console,wo=Vn.browserDetails.browser,So=Vn.browserDetails.version;const Ro=console,Co=Vn.browserDetails.browser;class ko extends class{constructor({selfId:e,room:t,emitter:i,serverSocket:n,webrtcProvider:s,features:a}){u.ok(e,"selfId is required"),u.ok(t,"room is required"),u.ok(i&&i.emit,"emitter is required"),u.ok(n instanceof po,"serverSocket is required"),u.ok(s,"webrtcProvider is required");const{name:r,session:o,iceServers:c,sfuServer:p,mediaserverConfigTtlSeconds:d}=t;this._selfId=e,this._roomName=r,this._roomSessionId=o&&o.id,this.peerConnections={},this.localStreams={},this.enabledLocalStreamIds=[],this._socketListenerDeregisterFunctions=[],this._emitter=i,this._serverSocket=n,this._webrtcProvider=s,this._features=a||{},this.offerOptions={offerToReceiveAudio:!0,offerToReceiveVideo:!0},this._pendingActionsForConnectedPeerConnections=[],this._updateAndScheduleMediaServersRefresh({sfuServer:p,iceServers:c.iceServers||[],mediaserverConfigTtlSeconds:d})}numberOfPeerconnections(){return Object.keys(this.peerConnections).length}numberOfRemotePeers(){return Object.values(this.peerConnections).filter((e=>e.clientId!==this._selfId)).length}_setConnectionStatus(e,t,i){const n=e.connectionStatus;n!==t&&e.peerConnectionId!==this._selfId&&(n===Pi&&t===Ci||(e.connectionStatus=t,setTimeout((()=>{this._emit(_i,{streamIds:e.streamIds,clientId:i,status:t,previous:n})}),0)))}_emitServerEvent(e,t,i){this._serverSocket.emit(e,t,i)}_emit(e,t){this._emitter.emit(e,t)}isInitializedWith({selfId:e,roomName:t,isSfu:i}){return this._selfId===e&&this._roomName===t&&i===!!this._sfuServer}supportsScreenShareAudio(){return!0}_addEnabledLocalStreamId(e){this.enabledLocalStreamIds.push(e)}_deleteEnabledLocalStreamId(e){const t=this.enabledLocalStreamIds.indexOf(e);-1!==t&&this.enabledLocalStreamIds.splice(t,1)}_getSession(e){return e in this.peerConnections?this.peerConnections[e]:null}_getOrCreateSession(e,t){let i=this.peerConnections[e];if(void 0===i){const n="safari"===wo&&So>=14&&this._features.deprioritizeH264OnSafari;this.peerConnections[e]=i=new yo({peerConnectionId:e,bandwidth:t,maximumTurnBandwidth:this._features.restrictBandwidthWhenUsingRelay?512:768,deprioritizeH264Encoding:n})}return i}_getLocalCameraStream(){return this.localStreams[0]}_getNonLocalCameraStreamIds(){return Object.keys(this.localStreams).filter((e=>"0"!==e))}_isScreensharingLocally(){return this._getNonLocalCameraStreamIds().length>0}_getFirstLocalNonCameraStream(){const e=this._getNonLocalCameraStreamIds();return 0===e.length?null:this.localStreams[e[0]]}_transformIncomingSdp(e){return{type:e.type,sdp:e.sdpU}}_transformOutgoingSdp(e){return{type:e.type,sdpU:e.sdp}}_createSession({clientId:e,initialBandwidth:t,isOfferer:i,peerConnectionId:n,shouldAddLocalVideo:s}){if(!n)throw new Error("peerConnectionId is missing");if(!e)throw new Error("clientId is missing");const a=this._getOrCreateSession(n,t),r={optional:[]};"chrome"===wo&&r.optional.push({googCpuOveruseDetection:!0});const o={iceServers:this._iceServers};if(this._features.turnServerOverrideHost){const e=this._features.turnServerOverrideHost,t=e.indexOf(":")>0?"":":443",i=":"+e+t;o.iceServers=o.iceServers.map((e=>{const t=Object.assign({},e);return t.url&&(t.url=t.url.replace(/:[^?]*/,i)),t.urls&&(t.urls=t.urls.map((e=>e.replace(/:[^?]*/,i)))),t}))}if(this._features.useOnlyTURN){o.iceTransportPolicy="relay";const e={onlyudp:/^turn:.*transport=udp$/,onlytcp:/^turn:.*transport=tcp$/,onlytls:/^turns:.*transport=tcp$/}[this._features.useOnlyTURN];e&&(o.iceServers=o.iceServers.filter((t=>t.url&&t.url.match(e))))}"chrome"===wo&&(o.sdpSemantics="unified-plan");const c=a.setAndGetPeerConnection({constraints:r,peerConnectionConfig:o,shouldAddLocalVideo:s,clientId:e});c.ontrack=t=>{const i=t.streams[0];"default"===i.id&&0===i.getAudioTracks().length||-1===a.streamIds.indexOf(i.id)&&(a.streamIds.push(i.id),this._emit(yi,{clientId:e,stream:i}),a.connectionStatus===Ti&&setTimeout((()=>{this._emit(_i,{streamIds:a.streamIds,clientId:e,status:a.connectionStatus,previous:Ci})}),0))},c.oniceconnectionstatechange=()=>{let t;const i=a.connectionStatus;switch(c.iceConnectionState){case"checking":t=Ci;break;case"connected":case"completed":t=Ti,a.wasEverConnected||(this._pendingActionsForConnectedPeerConnections.forEach((e=>{"function"==typeof e&&e()})),this._pendingActionsForConnectedPeerConnections=[]),!a.wasEverConnected&&(c.iceConnectionState.match(/connected|completed/)||"chrome"===wo&&c.localDescription&&"answer"===c.localDescription.type)&&(a.wasEverConnected=!0,"false"!==this._features.bandwidth&&this.maybeRestrictRelayBandwidth(a)),a.registerConnected();break;case"disconnected":t=Pi,setTimeout((()=>{"disconnected"===c.iceConnectionState&&this._maybeRestartIce(e,a)}),2e3);break;case"failed":t=ki,i!==t&&this._maybeRestartIce(e,a),null!==a.relayCandidateSeen||a.wasEverConnected||this._emit(lo);break;default:return}this._setConnectionStatus(a,t,e)},c.onconnectionstate=()=>{switch(c.connectionState){case"connected":a.registerConnected();break;case"failed":const t=ki;null!==a.relayCandidateSeen||a.wasEverConnected||this._emit(lo),this._setConnectionStatus(a,t,e)}};const p=this.localStreams[0];return s&&p&&a.addStream(p),s&&Object.keys(this.localStreams).forEach((e=>{if("0"===e)return;const t=this.localStreams[e];i?a.addStream(t):a.afterConnected.then((()=>{this._emitServerEvent(Oi,{receiverId:a.clientId,streamId:t.id,hasAudioTrack:!!t.getAudioTracks().length}),this._withForcedRenegotiation(a,(()=>a.addStream(t)))}))})),a}_cleanup(e){const t=this._getSession(e);t?(t.close(),delete this.peerConnections[e]):xo.warn("No RTCPeerConnection in RTCManager.disconnect()",e)}_forEachPeerConnection(e){Object.keys(this.peerConnections).forEach((t=>{const i=this.peerConnections[t];e(i)}))}_addStreamToPeerConnections(e){this._forEachPeerConnection((t=>{this._withForcedRenegotiation(t,(()=>t.addStream(e)))}))}_addTrackToPeerConnections(e,t){this._forEachPeerConnection((i=>{this._withForcedRenegotiation(i,(()=>i.addTrack(e,t)))}))}_replaceTrackToPeerConnections(e,t){const i=[];return this._forEachPeerConnection((n=>{if(!n.hasConnectedPeerConnection()){xo.log("Session doesn't have a connected PeerConnection, adding pending action!");const s=this._pendingActionsForConnectedPeerConnections;if(!s)return void xo.warn("No pending action is created to repalce track, because the pending actions array is null");const a=new Promise(((i,a)=>{s.push((()=>{const s=n.replaceTrack(e,t);if(!s)return xo.error("replaceTrack returned false!"),void a("ReplaceTrack returned false");s.then((e=>i(e))).catch((e=>a(e)))}))}));return void i.push(a)}const s=n.replaceTrack(e,t);s?i.push(s):xo.error("replaceTrack returned false!")})),Promise.all(i)}_removeStreamFromPeerConnections(e){this._forEachPeerConnection((t=>{this._withForcedRenegotiation(t,(()=>t.removeStream(e)))}))}_removeTrackFromPeerConnections(e){this._forEachPeerConnection((t=>{this._withForcedRenegotiation(t,(()=>t.removeTrack(e)))}))}_addLocalStream(e,t){this._addEnabledLocalStreamId(e),this.localStreams[e]=t}_removeLocalStream(e){delete this.localStreams[e],this._deleteEnabledLocalStreamId(e)}maybeRestrictRelayBandwidth(e){e.maybeRestrictRelayBandwidth()}addNewStream(e,t){t!==this.localStreams[e]&&(this._addLocalStream(e,t),"0"!==e?this._shareScreen(e,t):this._addStreamToPeerConnections(t))}removeStream(e,t){this._removeLocalStream(e,t)}replaceTrack(e,t){return this._replaceTrackToPeerConnections(e,t)}accept({clientId:e,shouldAddLocalVideo:t}){return this.acceptNewStream({streamId:e,clientId:e,shouldAddLocalVideo:t})}disconnectAll(){Object.keys(this.peerConnections).forEach((e=>{this.disconnect(e)})),this.peerConnections={},this._socketListenerDeregisterFunctions.forEach((e=>{e()})),this._socketListenerDeregisterFunctions=[]}stopOrResumeAudio(){}stopOrResumeVideo(){}fixChromeAudio(e){if("chrome"!==wo)return;const t=this._getLocalCameraStream(),i=t.getAudioTracks()[0];return i&&"ended"===i.readyState?navigator.mediaDevices.getUserMedia({audio:e}).then((e=>{const n=e.getAudioTracks()[0];return n.enabled=i.enabled,t.removeTrack(i),t.addTrack(n),this.replaceTrack(i,n)})):void 0}_updateAndScheduleMediaServersRefresh({iceServers:e,sfuServer:t,mediaserverConfigTtlSeconds:i}){this._iceServers=e,this._sfuServer=t,this._mediaserverConfigTtlSeconds=i,this._clearMediaServersRefresh(),i&&(this._fetchMediaServersTimer=setTimeout((()=>this._emitServerEvent(Ei)),1e3*i))}_clearMediaServersRefresh(){this._fetchMediaServersTimer&&(clearTimeout(this._fetchMediaServersTimer),this._fetchMediaServersTimer=null)}setupSocketListeners(){this._socketListenerDeregisterFunctions=[()=>this._clearMediaServersRefresh(),this._serverSocket.on(Ii,(e=>{e.error?xo.warn("FETCH_MEDIASERVER_CONFIG failed:",e.error):this._updateAndScheduleMediaServersRefresh(e)})),this._serverSocket.on(Ai,(e=>{this._connect(e.clientId)})),this._serverSocket.on(Li,(e=>{const t=this._getSession(e.clientId);t?t.addIceCandidate(e.message):xo.warn("No RTCPeerConnection on ICE_CANDIDATE",e)})),this._serverSocket.on(Mi,(e=>{const t=this._getSession(e.clientId);t?t.addIceCandidate(null):xo.warn("No RTCPeerConnection on ICE_END_OF_CANDIDATES",e)})),this._serverSocket.on(Bi,(e=>{const t=this._getSession(e.clientId);if(!t)return void xo.warn("No RTCPeerConnection on SDP_OFFER",e);const i=this._transformIncomingSdp(e.message,t.pc);t.handleOffer(i).then((t=>{this._emitServerEvent(Ni,{receiverId:e.clientId,message:this._transformOutgoingSdp(t)})}))})),this._serverSocket.on(Ni,(e=>{const t=this._getSession(e.clientId);if(!t)return void xo.warn("No RTCPeerConnection on SDP_ANSWER",e);const i=this._transformIncomingSdp(e.message,t.pc);t.handleAnswer(i)}))]}setRoomSessionId(e){this._roomSessionId=e}}{_connect(e){let t=this._getSession(e),i=t&&t.bandwidth||0;return t?(Ro.warn("Replacing peer session",e),this._cleanup(e)):i=this._changeBandwidthForAllClients(!0),t=this._createP2pSession(e,i,!0,!0),this._negotiatePeerConnection(e,t),Promise.resolve(t)}_maybeRestartIce(e,t){const i=t.pc;"disconnected"!==i.iceConnectionState&&"failed"!==i.iceConnectionState||"offer"===i.localDescription.type&&(t.wasEverConnected=!1,t.relayCandidateSeen=!1,this._negotiatePeerConnection(e,t,Object.assign({},this.offerOptions,{iceRestart:!0})))}_negotiatePeerConnection(e,t,i){if(!t)return void Ro.warn("No RTCPeerConnection in negotiatePeerConnection()",e);const n=t.pc;t.canModifyPeerConnection()?(t.isOperationPending=!0,n.createOffer(i||this.offerOptions).then((i=>{this._emitServerEvent(Bi,{receiverId:e,message:this._transformOutgoingSdp(i)}),"chrome"===Co&&n.getSenders().filter((e=>e.track&&"video"===e.track.kind)).length>=2?t.pendingOffer=i:n.setLocalDescription(i).catch((e=>{Ro.warn("RTCPeerConnection.setLocalDescription() failed with local offer",e)}))})).catch((e=>{Ro.warn("RTCPeerConnection.createOffer() failed to create local offer",e)}))):t.pending.push((()=>{this._negotiatePeerConnection(e,t,i)}))}_withForcedRenegotiation(e,t){const i=e.pc,n=i.onnegotationneeded;i.onnegotiationneeded=null,t(),this._negotiatePeerConnection(e.clientId,e),setTimeout((()=>i.onnegotiationneeded=n),0)}_changeBandwidthForAllClients(e){let t=this.numberOfPeerconnections();if(e&&(t+=1),0===t)return 0;t>7&&(t=7);const i=this._features.bandwidth?parseInt(this._features.bandwidth,10):{1:0,2:this._features.highP2PBandwidth?768:384,3:this._features.highP2PBandwidth?512:256,4:192,5:128,6:128,7:64}[t];return void 0===i?0:(this._forEachPeerConnection((e=>{e.changeBandwidth(i)})),i)}_createP2pSession(e,t,i,n){const s=this._createSession({peerConnectionId:e,clientId:e,initialBandwidth:t,shouldAddLocalVideo:i,isOfferer:n}),a=s.pc,r=this.localStreams[0];return i&&r&&!r.getVideoTracks().length&&this._stoppedVideoTrack&&a.addTrack(this._stoppedVideoTrack,r),a.onicecandidate=t=>{t.candidate?(s.relayCandidateSeen=s.relayCandidateSeen||"relay"===t.candidate.type,this._emitServerEvent(Li,{receiverId:e,message:t.candidate})):this._emitServerEvent(Mi,{receiverId:e})},a.onnegotiationneeded=()=>{"new"!==a.iceConnectionState&&s.connectionStatus&&this._negotiatePeerConnection(e,s)},s}acceptNewStream({streamId:e,clientId:t,shouldAddLocalVideo:i}){let n=this._getSession(t);if(n&&e!==t)return n;let s=n&&n.bandwidth||0;return n?(Ro.warn("Replacing peer session",t),this._cleanup(t)):s=this._changeBandwidthForAllClients(!0),n=this._createP2pSession(t,s,i),this._emitServerEvent(Ai,{receiverId:t}),n}disconnect(e){this._cleanup(e),this._changeBandwidthForAllClients(!1);0===this.numberOfPeerconnections()&&setTimeout((()=>{this.numberOfPeerconnections()}),6e4)}updateStreamResolution(){}stopOrResumeAudio(){}stopOrResumeVideo(e,t){if("chrome"===Co)if(!1===t)setTimeout((()=>{e.getVideoTracks().forEach((t=>{!1===t.enabled&&(t.stop(),e.removeTrack(t),this._emit(Ri,{stream:e,track:t}),this._stoppedVideoTrack=t)}))}),5e3);else if(this._features.simplifiedVegaClientOn){const t=e.getVideoTracks()?.[0];this._stoppedVideoTrack?(this._replaceTrackToPeerConnections(this._stoppedVideoTrack,t),delete this._stoppedVideoTrack,this._emit(Si,{streamId:e.id,tracks:[t],screenShare:!1})):t||this._addTrackToPeerConnections(t)}else if(0===e.getVideoTracks().length){const t=this._webrtcProvider.getMediaConstraints().video;if(!t)return;navigator.mediaDevices.getUserMedia({video:t}).then((t=>{const i=t.getVideoTracks()[0];e.addTrack(i),this._emit(Si,{streamId:e.id,tracks:[i],screenShare:!1}),this._stoppedVideoTrack?(this._replaceTrackToPeerConnections(this._stoppedVideoTrack,i),delete this._stoppedVideoTrack):this._addTrackToPeerConnections(i)}))}}_shareScreen(e,t){this._emitServerEvent(Oi,{streamId:e,hasAudioTrack:!!t.getAudioTracks().length}),this._addStreamToPeerConnections(t)}removeStream(e,t,i){super.removeStream(e,t),this._removeStreamFromPeerConnections(t),this._emitServerEvent(Di,{streamId:e,requestedByClientId:i})}}var To,Po,Eo,Oo,Do,Io={},jo={},Lo={},Mo={get exports(){return Lo},set exports(e){Lo=e}};function Ao(){if(Po)return To;Po=1;var e=1e3,t=60*e,i=60*t,n=24*i,s=7*n,a=365.25*n;function r(e,t,i,n){var s=t>=1.5*i;return Math.round(e/i)+" "+n+(s?"s":"")}return To=function(o,c){c=c||{};var p=typeof o;if("string"===p&&o.length>0)return function(r){if((r=String(r)).length>100)return;var o=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(r);if(!o)return;var c=parseFloat(o[1]);switch((o[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return c*a;case"weeks":case"week":case"w":return c*s;case"days":case"day":case"d":return c*n;case"hours":case"hour":case"hrs":case"hr":case"h":return c*i;case"minutes":case"minute":case"mins":case"min":case"m":return c*t;case"seconds":case"second":case"secs":case"sec":case"s":return c*e;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return c;default:return}}(o);if("number"===p&&isFinite(o))return c.long?function(s){var a=Math.abs(s);if(a>=n)return r(s,a,n,"day");if(a>=i)return r(s,a,i,"hour");if(a>=t)return r(s,a,t,"minute");if(a>=e)return r(s,a,e,"second");return s+" ms"}(o):function(s){var a=Math.abs(s);if(a>=n)return Math.round(s/n)+"d";if(a>=i)return Math.round(s/i)+"h";if(a>=t)return Math.round(s/t)+"m";if(a>=e)return Math.round(s/e)+"s";return s+"ms"}(o);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(o))}}function No(){if(Oo)return Eo;return Oo=1,Eo=function(e){function t(e){let n,s,a,r=null;function o(...e){if(!o.enabled)return;const i=o,s=Number(new Date),a=s-(n||s);i.diff=a,i.prev=n,i.curr=s,n=s,e[0]=t.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let r=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,((n,s)=>{if("%%"===n)return"%";r++;const a=t.formatters[s];if("function"==typeof a){const t=e[r];n=a.call(i,t),e.splice(r,1),r--}return n})),t.formatArgs.call(i,e);(i.log||t.log).apply(i,e)}return o.namespace=e,o.useColors=t.useColors(),o.color=t.selectColor(e),o.extend=i,o.destroy=t.destroy,Object.defineProperty(o,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==r?r:(s!==t.namespaces&&(s=t.namespaces,a=t.enabled(e)),a),set:e=>{r=e}}),"function"==typeof t.init&&t.init(o),o}function i(e,i){const n=t(this.namespace+(void 0===i?":":i)+e);return n.log=this.log,n}function n(e){return e.toString().substring(2,e.toString().length-2).replace(/\.\*\?$/,"*")}return t.debug=t,t.default=t,t.coerce=function(e){if(e instanceof Error)return e.stack||e.message;return e},t.disable=function(){const e=[...t.names.map(n),...t.skips.map(n).map((e=>"-"+e))].join(",");return t.enable(""),e},t.enable=function(e){let i;t.save(e),t.namespaces=e,t.names=[],t.skips=[];const n=("string"==typeof e?e:"").split(/[\s,]+/),s=n.length;for(i=0;i<s;i++)n[i]&&("-"===(e=n[i].replace(/\*/g,".*?"))[0]?t.skips.push(new RegExp("^"+e.slice(1)+"$")):t.names.push(new RegExp("^"+e+"$")))},t.enabled=function(e){if("*"===e[e.length-1])return!0;let i,n;for(i=0,n=t.skips.length;i<n;i++)if(t.skips[i].test(e))return!1;for(i=0,n=t.names.length;i<n;i++)if(t.names[i].test(e))return!0;return!1},t.humanize=Ao(),t.destroy=function(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")},Object.keys(e).forEach((i=>{t[i]=e[i]})),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){let i=0;for(let t=0;t<e.length;t++)i=(i<<5)-i+e.charCodeAt(t),i|=0;return t.colors[Math.abs(i)%t.colors.length]},t.enable(t.load()),t},Eo}var Bo,Fo,Uo,zo,qo,$o={},Vo={get exports(){return $o},set exports(e){$o=e}};function Wo(){return Fo?Bo:(Fo=1,Bo=(e,t=process.argv)=>{const i=e.startsWith("-")?"":1===e.length?"-":"--",n=t.indexOf(i+e),s=t.indexOf("--");return-1!==n&&(-1===s||n<s)})}function Go(){return qo||(qo=1,function(e,t){const i=m,n=h;t.init=function(e){e.inspectOpts={};const i=Object.keys(t.inspectOpts);for(let n=0;n<i.length;n++)e.inspectOpts[i[n]]=t.inspectOpts[i[n]]},t.log=function(...e){return process.stderr.write(n.format(...e)+"\n")},t.formatArgs=function(i){const{namespace:n,useColors:s}=this;if(s){const t=this.color,s="[3"+(t<8?t:"8;5;"+t),a=` ${s};1m${n} `;i[0]=a+i[0].split("\n").join("\n"+a),i.push(s+"m+"+e.exports.humanize(this.diff)+"")}else i[0]=function(){if(t.inspectOpts.hideDate)return"";return(new Date).toISOString()+" "}()+n+" "+i[0]},t.save=function(e){e?process.env.DEBUG=e:delete process.env.DEBUG},t.load=function(){return process.env.DEBUG},t.useColors=function(){return"colors"in t.inspectOpts?Boolean(t.inspectOpts.colors):i.isatty(process.stderr.fd)},t.destroy=n.deprecate((()=>{}),"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."),t.colors=[6,2,3,4,5,1];try{const e=function(){if(zo)return Uo;zo=1;const e=f,t=m,i=Wo(),{env:n}=process;let s;function a(e){return 0!==e&&{level:e,hasBasic:!0,has256:e>=2,has16m:e>=3}}function r(t,a){if(0===s)return 0;if(i("color=16m")||i("color=full")||i("color=truecolor"))return 3;if(i("color=256"))return 2;if(t&&!a&&void 0===s)return 0;const r=s||0;if("dumb"===n.TERM)return r;if("win32"===process.platform){const t=e.release().split(".");return Number(t[0])>=10&&Number(t[2])>=10586?Number(t[2])>=14931?3:2:1}if("CI"in n)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE"].some((e=>e in n))||"codeship"===n.CI_NAME?1:r;if("TEAMCITY_VERSION"in n)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(n.TEAMCITY_VERSION)?1:0;if("truecolor"===n.COLORTERM)return 3;if("TERM_PROGRAM"in n){const e=parseInt((n.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(n.TERM_PROGRAM){case"iTerm.app":return e>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(n.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(n.TERM)||"COLORTERM"in n?1:r}return i("no-color")||i("no-colors")||i("color=false")||i("color=never")?s=0:(i("color")||i("colors")||i("color=true")||i("color=always"))&&(s=1),"FORCE_COLOR"in n&&(s="true"===n.FORCE_COLOR?1:"false"===n.FORCE_COLOR?0:0===n.FORCE_COLOR.length?1:Math.min(parseInt(n.FORCE_COLOR,10),3)),Uo={supportsColor:function(e){return a(r(e,e&&e.isTTY))},stdout:a(r(!0,t.isatty(1))),stderr:a(r(!0,t.isatty(2)))},Uo}();e&&(e.stderr||e).level>=2&&(t.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221])}catch(e){}t.inspectOpts=Object.keys(process.env).filter((e=>/^debug_/i.test(e))).reduce(((e,t)=>{const i=t.substring(6).toLowerCase().replace(/_([a-z])/g,((e,t)=>t.toUpperCase()));let n=process.env[t];return n=!!/^(yes|on|true|enabled)$/i.test(n)||!/^(no|off|false|disabled)$/i.test(n)&&("null"===n?null:Number(n)),e[i]=n,e}),{}),e.exports=No()(t);const{formatters:s}=e.exports;s.o=function(e){return this.inspectOpts.colors=this.useColors,n.inspect(e,this.inspectOpts).split("\n").map((e=>e.trim())).join(" ")},s.O=function(e){return this.inspectOpts.colors=this.useColors,n.inspect(e,this.inspectOpts)}}(Vo,$o)),$o}!function(e){"undefined"==typeof process||"renderer"===process.type||!0===process.browser||process.__nwjs?e.exports=(Do||(Do=1,function(e,t){t.formatArgs=function(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;const i="color: "+this.color;t.splice(1,0,i,"color: inherit");let n=0,s=0;t[0].replace(/%[a-zA-Z%]/g,(e=>{"%%"!==e&&(n++,"%c"===e&&(s=n))})),t.splice(s,0,i)},t.save=function(e){try{e?t.storage.setItem("debug",e):t.storage.removeItem("debug")}catch(e){}},t.load=function(){let e;try{e=t.storage.getItem("debug")}catch(e){}return!e&&"undefined"!=typeof process&&"env"in process&&(e=process.env.DEBUG),e},t.useColors=function(){return!("undefined"==typeof window||!window.process||"renderer"!==window.process.type&&!window.process.__nwjs)||("undefined"==typeof navigator||!navigator.userAgent||!navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))&&("undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/))},t.storage=function(){try{return localStorage}catch(e){}}(),t.destroy=(()=>{let e=!1;return()=>{e||(e=!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"],t.log=console.debug||console.log||(()=>{}),e.exports=No()(t);const{formatters:i}=e.exports;i.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}(Mo,Lo)),Lo):e.exports=Go()}({get exports(){return jo},set exports(e){jo=e}});var Ho={};const Ko={"Amazon Silk":"amazon_silk","Android Browser":"android",Bada:"bada",BlackBerry:"blackberry",Chrome:"chrome",Chromium:"chromium",Electron:"electron",Epiphany:"epiphany",Firefox:"firefox",Focus:"focus",Generic:"generic","Google Search":"google_search",Googlebot:"googlebot","Internet Explorer":"ie","K-Meleon":"k_meleon",Maxthon:"maxthon","Microsoft Edge":"edge","MZ Browser":"mz","NAVER Whale Browser":"naver",Opera:"opera","Opera Coast":"opera_coast",PhantomJS:"phantomjs",Puffin:"puffin",QupZilla:"qupzilla",QQ:"qq",QQLite:"qqlite",Safari:"safari",Sailfish:"sailfish","Samsung Internet for Android":"samsung_internet",SeaMonkey:"seamonkey",Sleipnir:"sleipnir",Swing:"swing",Tizen:"tizen","UC Browser":"uc",Vivaldi:"vivaldi","WebOS Browser":"webos",WeChat:"wechat","Yandex Browser":"yandex",Roku:"roku"},Jo={amazon_silk:"Amazon Silk",android:"Android Browser",bada:"Bada",blackberry:"BlackBerry",chrome:"Chrome",chromium:"Chromium",electron:"Electron",epiphany:"Epiphany",firefox:"Firefox",focus:"Focus",generic:"Generic",googlebot:"Googlebot",google_search:"Google Search",ie:"Internet Explorer",k_meleon:"K-Meleon",maxthon:"Maxthon",edge:"Microsoft Edge",mz:"MZ Browser",naver:"NAVER Whale Browser",opera:"Opera",opera_coast:"Opera Coast",phantomjs:"PhantomJS",puffin:"Puffin",qupzilla:"QupZilla",qq:"QQ Browser",qqlite:"QQ Browser Lite",safari:"Safari",sailfish:"Sailfish",samsung_internet:"Samsung Internet for Android",seamonkey:"SeaMonkey",sleipnir:"Sleipnir",swing:"Swing",tizen:"Tizen",uc:"UC Browser",vivaldi:"Vivaldi",webos:"WebOS Browser",wechat:"WeChat",yandex:"Yandex Browser"},Qo={tablet:"tablet",mobile:"mobile",desktop:"desktop",tv:"tv"},Yo={WindowsPhone:"Windows Phone",Windows:"Windows",MacOS:"macOS",iOS:"iOS",Android:"Android",WebOS:"WebOS",BlackBerry:"BlackBerry",Bada:"Bada",Tizen:"Tizen",Linux:"Linux",ChromeOS:"Chrome OS",PlayStation4:"PlayStation 4",Roku:"Roku"},Xo={EdgeHTML:"EdgeHTML",Blink:"Blink",Trident:"Trident",Presto:"Presto",Gecko:"Gecko",WebKit:"WebKit"};class Zo{static getFirstMatch(e,t){const i=t.match(e);return i&&i.length>0&&i[1]||""}static getSecondMatch(e,t){const i=t.match(e);return i&&i.length>1&&i[2]||""}static matchAndReturnConst(e,t,i){if(e.test(t))return i}static getWindowsVersionName(e){switch(e){case"NT":return"NT";case"XP":case"NT 5.1":return"XP";case"NT 5.0":return"2000";case"NT 5.2":return"2003";case"NT 6.0":return"Vista";case"NT 6.1":return"7";case"NT 6.2":return"8";case"NT 6.3":return"8.1";case"NT 10.0":return"10";default:return}}static getMacOSVersionName(e){const t=e.split(".").splice(0,2).map((e=>parseInt(e,10)||0));if(t.push(0),10===t[0])switch(t[1]){case 5:return"Leopard";case 6:return"Snow Leopard";case 7:return"Lion";case 8:return"Mountain Lion";case 9:return"Mavericks";case 10:return"Yosemite";case 11:return"El Capitan";case 12:return"Sierra";case 13:return"High Sierra";case 14:return"Mojave";case 15:return"Catalina";default:return}}static getAndroidVersionName(e){const t=e.split(".").splice(0,2).map((e=>parseInt(e,10)||0));if(t.push(0),!(1===t[0]&&t[1]<5))return 1===t[0]&&t[1]<6?"Cupcake":1===t[0]&&t[1]>=6?"Donut":2===t[0]&&t[1]<2?"Eclair":2===t[0]&&2===t[1]?"Froyo":2===t[0]&&t[1]>2?"Gingerbread":3===t[0]?"Honeycomb":4===t[0]&&t[1]<1?"Ice Cream Sandwich":4===t[0]&&t[1]<4?"Jelly Bean":4===t[0]&&t[1]>=4?"KitKat":5===t[0]?"Lollipop":6===t[0]?"Marshmallow":7===t[0]?"Nougat":8===t[0]?"Oreo":9===t[0]?"Pie":void 0}static getVersionPrecision(e){return e.split(".").length}static compareVersions(e,t,i=!1){const n=Zo.getVersionPrecision(e),s=Zo.getVersionPrecision(t);let a=Math.max(n,s),r=0;const o=Zo.map([e,t],(e=>{const t=a-Zo.getVersionPrecision(e),i=e+new Array(t+1).join(".0");return Zo.map(i.split("."),(e=>new Array(20-e.length).join("0")+e)).reverse()}));for(i&&(r=a-Math.min(n,s)),a-=1;a>=r;){if(o[0][a]>o[1][a])return 1;if(o[0][a]===o[1][a]){if(a===r)return 0;a-=1}else if(o[0][a]<o[1][a])return-1}}static map(e,t){const i=[];let n;if(Array.prototype.map)return Array.prototype.map.call(e,t);for(n=0;n<e.length;n+=1)i.push(t(e[n]));return i}static find(e,t){let i,n;if(Array.prototype.find)return Array.prototype.find.call(e,t);for(i=0,n=e.length;i<n;i+=1){const n=e[i];if(t(n,i))return n}}static assign(e,...t){const i=e;let n,s;if(Object.assign)return Object.assign(e,...t);for(n=0,s=t.length;n<s;n+=1){const e=t[n];if("object"==typeof e&&null!==e){Object.keys(e).forEach((t=>{i[t]=e[t]}))}}return e}static getBrowserAlias(e){return Ko[e]}static getBrowserTypeByAlias(e){return Jo[e]||""}}const ec=/version\/(\d+(\.?_?\d+)+)/i,tc=[{test:[/googlebot/i],describe(e){const t={name:"Googlebot"},i=Zo.getFirstMatch(/googlebot\/(\d+(\.\d+))/i,e)||Zo.getFirstMatch(ec,e);return i&&(t.version=i),t}},{test:[/opera/i],describe(e){const t={name:"Opera"},i=Zo.getFirstMatch(ec,e)||Zo.getFirstMatch(/(?:opera)[\s/](\d+(\.?_?\d+)+)/i,e);return i&&(t.version=i),t}},{test:[/opr\/|opios/i],describe(e){const t={name:"Opera"},i=Zo.getFirstMatch(/(?:opr|opios)[\s/](\S+)/i,e)||Zo.getFirstMatch(ec,e);return i&&(t.version=i),t}},{test:[/SamsungBrowser/i],describe(e){const t={name:"Samsung Internet for Android"},i=Zo.getFirstMatch(ec,e)||Zo.getFirstMatch(/(?:SamsungBrowser)[\s/](\d+(\.?_?\d+)+)/i,e);return i&&(t.version=i),t}},{test:[/Whale/i],describe(e){const t={name:"NAVER Whale Browser"},i=Zo.getFirstMatch(ec,e)||Zo.getFirstMatch(/(?:whale)[\s/](\d+(?:\.\d+)+)/i,e);return i&&(t.version=i),t}},{test:[/MZBrowser/i],describe(e){const t={name:"MZ Browser"},i=Zo.getFirstMatch(/(?:MZBrowser)[\s/](\d+(?:\.\d+)+)/i,e)||Zo.getFirstMatch(ec,e);return i&&(t.version=i),t}},{test:[/focus/i],describe(e){const t={name:"Focus"},i=Zo.getFirstMatch(/(?:focus)[\s/](\d+(?:\.\d+)+)/i,e)||Zo.getFirstMatch(ec,e);return i&&(t.version=i),t}},{test:[/swing/i],describe(e){const t={name:"Swing"},i=Zo.getFirstMatch(/(?:swing)[\s/](\d+(?:\.\d+)+)/i,e)||Zo.getFirstMatch(ec,e);return i&&(t.version=i),t}},{test:[/coast/i],describe(e){const t={name:"Opera Coast"},i=Zo.getFirstMatch(ec,e)||Zo.getFirstMatch(/(?:coast)[\s/](\d+(\.?_?\d+)+)/i,e);return i&&(t.version=i),t}},{test:[/opt\/\d+(?:.?_?\d+)+/i],describe(e){const t={name:"Opera Touch"},i=Zo.getFirstMatch(/(?:opt)[\s/](\d+(\.?_?\d+)+)/i,e)||Zo.getFirstMatch(ec,e);return i&&(t.version=i),t}},{test:[/yabrowser/i],describe(e){const t={name:"Yandex Browser"},i=Zo.getFirstMatch(/(?:yabrowser)[\s/](\d+(\.?_?\d+)+)/i,e)||Zo.getFirstMatch(ec,e);return i&&(t.version=i),t}},{test:[/ucbrowser/i],describe(e){const t={name:"UC Browser"},i=Zo.getFirstMatch(ec,e)||Zo.getFirstMatch(/(?:ucbrowser)[\s/](\d+(\.?_?\d+)+)/i,e);return i&&(t.version=i),t}},{test:[/Maxthon|mxios/i],describe(e){const t={name:"Maxthon"},i=Zo.getFirstMatch(ec,e)||Zo.getFirstMatch(/(?:Maxthon|mxios)[\s/](\d+(\.?_?\d+)+)/i,e);return i&&(t.version=i),t}},{test:[/epiphany/i],describe(e){const t={name:"Epiphany"},i=Zo.getFirstMatch(ec,e)||Zo.getFirstMatch(/(?:epiphany)[\s/](\d+(\.?_?\d+)+)/i,e);return i&&(t.version=i),t}},{test:[/puffin/i],describe(e){const t={name:"Puffin"},i=Zo.getFirstMatch(ec,e)||Zo.getFirstMatch(/(?:puffin)[\s/](\d+(\.?_?\d+)+)/i,e);return i&&(t.version=i),t}},{test:[/sleipnir/i],describe(e){const t={name:"Sleipnir"},i=Zo.getFirstMatch(ec,e)||Zo.getFirstMatch(/(?:sleipnir)[\s/](\d+(\.?_?\d+)+)/i,e);return i&&(t.version=i),t}},{test:[/k-meleon/i],describe(e){const t={name:"K-Meleon"},i=Zo.getFirstMatch(ec,e)||Zo.getFirstMatch(/(?:k-meleon)[\s/](\d+(\.?_?\d+)+)/i,e);return i&&(t.version=i),t}},{test:[/micromessenger/i],describe(e){const t={name:"WeChat"},i=Zo.getFirstMatch(/(?:micromessenger)[\s/](\d+(\.?_?\d+)+)/i,e)||Zo.getFirstMatch(ec,e);return i&&(t.version=i),t}},{test:[/qqbrowser/i],describe(e){const t={name:/qqbrowserlite/i.test(e)?"QQ Browser Lite":"QQ Browser"},i=Zo.getFirstMatch(/(?:qqbrowserlite|qqbrowser)[/](\d+(\.?_?\d+)+)/i,e)||Zo.getFirstMatch(ec,e);return i&&(t.version=i),t}},{test:[/msie|trident/i],describe(e){const t={name:"Internet Explorer"},i=Zo.getFirstMatch(/(?:msie |rv:)(\d+(\.?_?\d+)+)/i,e);return i&&(t.version=i),t}},{test:[/\sedg\//i],describe(e){const t={name:"Microsoft Edge"},i=Zo.getFirstMatch(/\sedg\/(\d+(\.?_?\d+)+)/i,e);return i&&(t.version=i),t}},{test:[/edg([ea]|ios)/i],describe(e){const t={name:"Microsoft Edge"},i=Zo.getSecondMatch(/edg([ea]|ios)\/(\d+(\.?_?\d+)+)/i,e);return i&&(t.version=i),t}},{test:[/vivaldi/i],describe(e){const t={name:"Vivaldi"},i=Zo.getFirstMatch(/vivaldi\/(\d+(\.?_?\d+)+)/i,e);return i&&(t.version=i),t}},{test:[/seamonkey/i],describe(e){const t={name:"SeaMonkey"},i=Zo.getFirstMatch(/seamonkey\/(\d+(\.?_?\d+)+)/i,e);return i&&(t.version=i),t}},{test:[/sailfish/i],describe(e){const t={name:"Sailfish"},i=Zo.getFirstMatch(/sailfish\s?browser\/(\d+(\.\d+)?)/i,e);return i&&(t.version=i),t}},{test:[/silk/i],describe(e){const t={name:"Amazon Silk"},i=Zo.getFirstMatch(/silk\/(\d+(\.?_?\d+)+)/i,e);return i&&(t.version=i),t}},{test:[/phantom/i],describe(e){const t={name:"PhantomJS"},i=Zo.getFirstMatch(/phantomjs\/(\d+(\.?_?\d+)+)/i,e);return i&&(t.version=i),t}},{test:[/slimerjs/i],describe(e){const t={name:"SlimerJS"},i=Zo.getFirstMatch(/slimerjs\/(\d+(\.?_?\d+)+)/i,e);return i&&(t.version=i),t}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe(e){const t={name:"BlackBerry"},i=Zo.getFirstMatch(ec,e)||Zo.getFirstMatch(/blackberry[\d]+\/(\d+(\.?_?\d+)+)/i,e);return i&&(t.version=i),t}},{test:[/(web|hpw)[o0]s/i],describe(e){const t={name:"WebOS Browser"},i=Zo.getFirstMatch(ec,e)||Zo.getFirstMatch(/w(?:eb)?[o0]sbrowser\/(\d+(\.?_?\d+)+)/i,e);return i&&(t.version=i),t}},{test:[/bada/i],describe(e){const t={name:"Bada"},i=Zo.getFirstMatch(/dolfin\/(\d+(\.?_?\d+)+)/i,e);return i&&(t.version=i),t}},{test:[/tizen/i],describe(e){const t={name:"Tizen"},i=Zo.getFirstMatch(/(?:tizen\s?)?browser\/(\d+(\.?_?\d+)+)/i,e)||Zo.getFirstMatch(ec,e);return i&&(t.version=i),t}},{test:[/qupzilla/i],describe(e){const t={name:"QupZilla"},i=Zo.getFirstMatch(/(?:qupzilla)[\s/](\d+(\.?_?\d+)+)/i,e)||Zo.getFirstMatch(ec,e);return i&&(t.version=i),t}},{test:[/firefox|iceweasel|fxios/i],describe(e){const t={name:"Firefox"},i=Zo.getFirstMatch(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,e);return i&&(t.version=i),t}},{test:[/electron/i],describe(e){const t={name:"Electron"},i=Zo.getFirstMatch(/(?:electron)\/(\d+(\.?_?\d+)+)/i,e);return i&&(t.version=i),t}},{test:[/MiuiBrowser/i],describe(e){const t={name:"Miui"},i=Zo.getFirstMatch(/(?:MiuiBrowser)[\s/](\d+(\.?_?\d+)+)/i,e);return i&&(t.version=i),t}},{test:[/chromium/i],describe(e){const t={name:"Chromium"},i=Zo.getFirstMatch(/(?:chromium)[\s/](\d+(\.?_?\d+)+)/i,e)||Zo.getFirstMatch(ec,e);return i&&(t.version=i),t}},{test:[/chrome|crios|crmo/i],describe(e){const t={name:"Chrome"},i=Zo.getFirstMatch(/(?:chrome|crios|crmo)\/(\d+(\.?_?\d+)+)/i,e);return i&&(t.version=i),t}},{test:[/GSA/i],describe(e){const t={name:"Google Search"},i=Zo.getFirstMatch(/(?:GSA)\/(\d+(\.?_?\d+)+)/i,e);return i&&(t.version=i),t}},{test(e){const t=!e.test(/like android/i),i=e.test(/android/i);return t&&i},describe(e){const t={name:"Android Browser"},i=Zo.getFirstMatch(ec,e);return i&&(t.version=i),t}},{test:[/playstation 4/i],describe(e){const t={name:"PlayStation 4"},i=Zo.getFirstMatch(ec,e);return i&&(t.version=i),t}},{test:[/safari|applewebkit/i],describe(e){const t={name:"Safari"},i=Zo.getFirstMatch(ec,e);return i&&(t.version=i),t}},{test:[/.*/i],describe(e){const t=-1!==e.search("\\(")?/^(.*)\/(.*)[ \t]\((.*)/:/^(.*)\/(.*) /;return{name:Zo.getFirstMatch(t,e),version:Zo.getSecondMatch(t,e)}}}];var ic=[{test:[/Roku\/DVP/],describe(e){const t=Zo.getFirstMatch(/Roku\/DVP-(\d+\.\d+)/i,e);return{name:Yo.Roku,version:t}}},{test:[/windows phone/i],describe(e){const t=Zo.getFirstMatch(/windows phone (?:os)?\s?(\d+(\.\d+)*)/i,e);return{name:Yo.WindowsPhone,version:t}}},{test:[/windows /i],describe(e){const t=Zo.getFirstMatch(/Windows ((NT|XP)( \d\d?.\d)?)/i,e),i=Zo.getWindowsVersionName(t);return{name:Yo.Windows,version:t,versionName:i}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe(e){const t={name:Yo.iOS},i=Zo.getSecondMatch(/(Version\/)(\d[\d.]+)/,e);return i&&(t.version=i),t}},{test:[/macintosh/i],describe(e){const t=Zo.getFirstMatch(/mac os x (\d+(\.?_?\d+)+)/i,e).replace(/[_\s]/g,"."),i=Zo.getMacOSVersionName(t),n={name:Yo.MacOS,version:t};return i&&(n.versionName=i),n}},{test:[/(ipod|iphone|ipad)/i],describe(e){const t=Zo.getFirstMatch(/os (\d+([_\s]\d+)*) like mac os x/i,e).replace(/[_\s]/g,".");return{name:Yo.iOS,version:t}}},{test(e){const t=!e.test(/like android/i),i=e.test(/android/i);return t&&i},describe(e){const t=Zo.getFirstMatch(/android[\s/-](\d+(\.\d+)*)/i,e),i=Zo.getAndroidVersionName(t),n={name:Yo.Android,version:t};return i&&(n.versionName=i),n}},{test:[/(web|hpw)[o0]s/i],describe(e){const t=Zo.getFirstMatch(/(?:web|hpw)[o0]s\/(\d+(\.\d+)*)/i,e),i={name:Yo.WebOS};return t&&t.length&&(i.version=t),i}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe(e){const t=Zo.getFirstMatch(/rim\stablet\sos\s(\d+(\.\d+)*)/i,e)||Zo.getFirstMatch(/blackberry\d+\/(\d+([_\s]\d+)*)/i,e)||Zo.getFirstMatch(/\bbb(\d+)/i,e);return{name:Yo.BlackBerry,version:t}}},{test:[/bada/i],describe(e){const t=Zo.getFirstMatch(/bada\/(\d+(\.\d+)*)/i,e);return{name:Yo.Bada,version:t}}},{test:[/tizen/i],describe(e){const t=Zo.getFirstMatch(/tizen[/\s](\d+(\.\d+)*)/i,e);return{name:Yo.Tizen,version:t}}},{test:[/linux/i],describe:()=>({name:Yo.Linux})},{test:[/CrOS/],describe:()=>({name:Yo.ChromeOS})},{test:[/PlayStation 4/],describe(e){const t=Zo.getFirstMatch(/PlayStation 4[/\s](\d+(\.\d+)*)/i,e);return{name:Yo.PlayStation4,version:t}}}],nc=[{test:[/googlebot/i],describe:()=>({type:"bot",vendor:"Google"})},{test:[/huawei/i],describe(e){const t=Zo.getFirstMatch(/(can-l01)/i,e)&&"Nova",i={type:Qo.mobile,vendor:"Huawei"};return t&&(i.model=t),i}},{test:[/nexus\s*(?:7|8|9|10).*/i],describe:()=>({type:Qo.tablet,vendor:"Nexus"})},{test:[/ipad/i],describe:()=>({type:Qo.tablet,vendor:"Apple",model:"iPad"})},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe:()=>({type:Qo.tablet,vendor:"Apple",model:"iPad"})},{test:[/kftt build/i],describe:()=>({type:Qo.tablet,vendor:"Amazon",model:"Kindle Fire HD 7"})},{test:[/silk/i],describe:()=>({type:Qo.tablet,vendor:"Amazon"})},{test:[/tablet(?! pc)/i],describe:()=>({type:Qo.tablet})},{test(e){const t=e.test(/ipod|iphone/i),i=e.test(/like (ipod|iphone)/i);return t&&!i},describe(e){const t=Zo.getFirstMatch(/(ipod|iphone)/i,e);return{type:Qo.mobile,vendor:"Apple",model:t}}},{test:[/nexus\s*[0-6].*/i,/galaxy nexus/i],describe:()=>({type:Qo.mobile,vendor:"Nexus"})},{test:[/[^-]mobi/i],describe:()=>({type:Qo.mobile})},{test:e=>"blackberry"===e.getBrowserName(!0),describe:()=>({type:Qo.mobile,vendor:"BlackBerry"})},{test:e=>"bada"===e.getBrowserName(!0),describe:()=>({type:Qo.mobile})},{test:e=>"windows phone"===e.getBrowserName(),describe:()=>({type:Qo.mobile,vendor:"Microsoft"})},{test(e){const t=Number(String(e.getOSVersion()).split(".")[0]);return"android"===e.getOSName(!0)&&t>=3},describe:()=>({type:Qo.tablet})},{test:e=>"android"===e.getOSName(!0),describe:()=>({type:Qo.mobile})},{test:e=>"macos"===e.getOSName(!0),describe:()=>({type:Qo.desktop,vendor:"Apple"})},{test:e=>"windows"===e.getOSName(!0),describe:()=>({type:Qo.desktop})},{test:e=>"linux"===e.getOSName(!0),describe:()=>({type:Qo.desktop})},{test:e=>"playstation 4"===e.getOSName(!0),describe:()=>({type:Qo.tv})},{test:e=>"roku"===e.getOSName(!0),describe:()=>({type:Qo.tv})}],sc=[{test:e=>"microsoft edge"===e.getBrowserName(!0),describe(e){if(/\sedg\//i.test(e))return{name:Xo.Blink};const t=Zo.getFirstMatch(/edge\/(\d+(\.?_?\d+)+)/i,e);return{name:Xo.EdgeHTML,version:t}}},{test:[/trident/i],describe(e){const t={name:Xo.Trident},i=Zo.getFirstMatch(/trident\/(\d+(\.?_?\d+)+)/i,e);return i&&(t.version=i),t}},{test:e=>e.test(/presto/i),describe(e){const t={name:Xo.Presto},i=Zo.getFirstMatch(/presto\/(\d+(\.?_?\d+)+)/i,e);return i&&(t.version=i),t}},{test(e){const t=e.test(/gecko/i),i=e.test(/like gecko/i);return t&&!i},describe(e){const t={name:Xo.Gecko},i=Zo.getFirstMatch(/gecko\/(\d+(\.?_?\d+)+)/i,e);return i&&(t.version=i),t}},{test:[/(apple)?webkit\/537\.36/i],describe:()=>({name:Xo.Blink})},{test:[/(apple)?webkit/i],describe(e){const t={name:Xo.WebKit},i=Zo.getFirstMatch(/webkit\/(\d+(\.?_?\d+)+)/i,e);return i&&(t.version=i),t}}];class ac{constructor(e,t=!1){if(null==e||""===e)throw new Error("UserAgent parameter can't be empty");this._ua=e,this.parsedResult={},!0!==t&&this.parse()}getUA(){return this._ua}test(e){return e.test(this._ua)}parseBrowser(){this.parsedResult.browser={};const e=Zo.find(tc,(e=>{if("function"==typeof e.test)return e.test(this);if(e.test instanceof Array)return e.test.some((e=>this.test(e)));throw new Error("Browser's test function is not valid")}));return e&&(this.parsedResult.browser=e.describe(this.getUA())),this.parsedResult.browser}getBrowser(){return this.parsedResult.browser?this.parsedResult.browser:this.parseBrowser()}getBrowserName(e){return e?String(this.getBrowser().name).toLowerCase()||"":this.getBrowser().name||""}getBrowserVersion(){return this.getBrowser().version}getOS(){return this.parsedResult.os?this.parsedResult.os:this.parseOS()}parseOS(){this.parsedResult.os={};const e=Zo.find(ic,(e=>{if("function"==typeof e.test)return e.test(this);if(e.test instanceof Array)return e.test.some((e=>this.test(e)));throw new Error("Browser's test function is not valid")}));return e&&(this.parsedResult.os=e.describe(this.getUA())),this.parsedResult.os}getOSName(e){const{name:t}=this.getOS();return e?String(t).toLowerCase()||"":t||""}getOSVersion(){return this.getOS().version}getPlatform(){return this.parsedResult.platform?this.parsedResult.platform:this.parsePlatform()}getPlatformType(e=!1){const{type:t}=this.getPlatform();return e?String(t).toLowerCase()||"":t||""}parsePlatform(){this.parsedResult.platform={};const e=Zo.find(nc,(e=>{if("function"==typeof e.test)return e.test(this);if(e.test instanceof Array)return e.test.some((e=>this.test(e)));throw new Error("Browser's test function is not valid")}));return e&&(this.parsedResult.platform=e.describe(this.getUA())),this.parsedResult.platform}getEngine(){return this.parsedResult.engine?this.parsedResult.engine:this.parseEngine()}getEngineName(e){return e?String(this.getEngine().name).toLowerCase()||"":this.getEngine().name||""}parseEngine(){this.parsedResult.engine={};const e=Zo.find(sc,(e=>{if("function"==typeof e.test)return e.test(this);if(e.test instanceof Array)return e.test.some((e=>this.test(e)));throw new Error("Browser's test function is not valid")}));return e&&(this.parsedResult.engine=e.describe(this.getUA())),this.parsedResult.engine}parse(){return this.parseBrowser(),this.parseOS(),this.parsePlatform(),this.parseEngine(),this}getResult(){return Zo.assign({},this.parsedResult)}satisfies(e){const t={};let i=0;const n={};let s=0;if(Object.keys(e).forEach((a=>{const r=e[a];"string"==typeof r?(n[a]=r,s+=1):"object"==typeof r&&(t[a]=r,i+=1)})),i>0){const e=Object.keys(t),i=Zo.find(e,(e=>this.isOS(e)));if(i){const e=this.satisfies(t[i]);if(void 0!==e)return e}const n=Zo.find(e,(e=>this.isPlatform(e)));if(n){const e=this.satisfies(t[n]);if(void 0!==e)return e}}if(s>0){const e=Object.keys(n),t=Zo.find(e,(e=>this.isBrowser(e,!0)));if(void 0!==t)return this.compareVersion(n[t])}}isBrowser(e,t=!1){const i=this.getBrowserName().toLowerCase();let n=e.toLowerCase();const s=Zo.getBrowserTypeByAlias(n);return t&&s&&(n=s.toLowerCase()),n===i}compareVersion(e){let t=[0],i=e,n=!1;const s=this.getBrowserVersion();if("string"==typeof s)return">"===e[0]||"<"===e[0]?(i=e.substr(1),"="===e[1]?(n=!0,i=e.substr(2)):t=[],">"===e[0]?t.push(1):t.push(-1)):"="===e[0]?i=e.substr(1):"~"===e[0]&&(n=!0,i=e.substr(1)),t.indexOf(Zo.compareVersions(s,i,n))>-1}isOS(e){return this.getOSName(!0)===String(e).toLowerCase()}isPlatform(e){return this.getPlatformType(!0)===String(e).toLowerCase()}isEngine(e){return this.getEngineName(!0)===String(e).toLowerCase()}is(e,t=!1){return this.isBrowser(e,t)||this.isOS(e)||this.isPlatform(e)}some(e=[]){return e.some((e=>this.is(e)))}}
29
29
  /*!
30
30
  * Bowser - a browser detector
31
31
  * https://github.com/lancedikson/bowser
@@ -40,4 +40,4 @@ let Kc;Uc.AwaitQueue=class{constructor(){this.pendingTasks=new Map,this.nextTask
40
40
  * Copyright(c) 2015 Douglas Christopher Wilson
41
41
  * MIT Licensed
42
42
  */
43
- function(e){var t=Nf,i=g.extname,n=/^\s*([^;\s]*)(?:;|\s|$)/,s=/^text\//i;function a(e){if(!e||"string"!=typeof e)return!1;var i=n.exec(e),a=i&&t[i[1].toLowerCase()];return a&&a.charset?a.charset:!(!i||!s.test(i[1]))&&"UTF-8"}e.charset=a,e.charsets={lookup:a},e.contentType=function(t){if(!t||"string"!=typeof t)return!1;var i=-1===t.indexOf("/")?e.lookup(t):t;if(!i)return!1;if(-1===i.indexOf("charset")){var n=e.charset(i);n&&(i+="; charset="+n.toLowerCase())}return i},e.extension=function(t){if(!t||"string"!=typeof t)return!1;var i=n.exec(t),s=i&&e.extensions[i[1].toLowerCase()];if(!s||!s.length)return!1;return s[0]},e.extensions=Object.create(null),e.lookup=function(t){if(!t||"string"!=typeof t)return!1;var n=i("x."+t).toLowerCase().substr(1);if(!n)return!1;return e.types[n]||!1},e.types=Object.create(null),function(e,i){var n=["nginx","apache",void 0,"iana"];Object.keys(t).forEach((function(s){var a=t[s],r=a.extensions;if(r&&r.length){e[s]=r;for(var o=0;o<r.length;o++){var c=r[o];if(i[c]){var p=n.indexOf(t[i[c]].source),d=n.indexOf(a.source);if("application/octet-stream"!==i[c]&&(p>d||p===d&&"application/"===i[c].substr(0,12)))continue}i[c]=s}}}))}(e.extensions,e.types)}(Af);var Ff=function(e){var t="function"==typeof setImmediate?setImmediate:"object"==typeof process&&"function"==typeof process.nextTick?process.nextTick:null;t?t(e):setTimeout(e,0)};var Uf=Ff,zf=function(e){var t=!1;return Uf((function(){t=!0})),function(i,n){t?e(i,n):Uf((function(){e(i,n)}))}};var qf=function(e){Object.keys(e.jobs).forEach($f.bind(e)),e.jobs={}};function $f(e){"function"==typeof this.jobs[e]&&this.jobs[e]()}var Vf=zf,Wf=qf,Gf=function(e,t,i,n){var s=i.keyedList?i.keyedList[i.index]:i.index;i.jobs[s]=function(e,t,i,n){var s;s=2==e.length?e(i,Vf(n)):e(i,t,Vf(n));return s}(t,s,e[s],(function(e,t){s in i.jobs&&(delete i.jobs[s],e?Wf(i):i.results[s]=t,n(e,i.results))}))};var Hf=function(e,t){var i=!Array.isArray(e),n={index:0,keyedList:i||t?Object.keys(e):null,jobs:{},results:i?{}:[],size:i?Object.keys(e).length:e.length};t&&n.keyedList.sort(i?t:function(i,n){return t(e[i],e[n])});return n};var Kf=qf,Jf=zf,Qf=function(e){if(!Object.keys(this.jobs).length)return;this.index=this.size,Kf(this),Jf(e)(null,this.results)};var Yf=Gf,Xf=Hf,Zf=Qf,eg=function(e,t,i){var n=Xf(e);for(;n.index<(n.keyedList||e).length;)Yf(e,t,n,(function(e,t){e?i(e,t):0!==Object.keys(n.jobs).length||i(null,n.results)})),n.index++;return Zf.bind(n,i)};var tg={},ig=Gf,ng=Hf,sg=Qf;function ag(e,t){return e<t?-1:e>t?1:0}({get exports(){return tg},set exports(e){tg=e}}).exports=function(e,t,i,n){var s=ng(e,i);return ig(e,t,s,(function i(a,r){a?n(a,r):(s.index++,s.index<(s.keyedList||e).length?ig(e,t,s,i):n(null,s.results))})),sg.bind(s,n)},tg.ascending=ag,tg.descending=function(e,t){return-1*ag(e,t)};var rg=tg;var og={parallel:eg,serial:function(e,t,i){return rg(e,t,null,i)},serialOrdered:tg},cg=Lf,pg=h,dg=g,lg=n,ug=s,mg=t.parse,hg=e,fg=a.Stream,gg=Af,vg=og,bg=function(e,t){return Object.keys(t).forEach((function(i){e[i]=e[i]||t[i]})),e},_g=yg;function yg(e){if(!(this instanceof yg))return new yg(e);for(var t in this._overheadLength=0,this._valueLength=0,this._valuesToMeasure=[],cg.call(this),e=e||{})this[t]=e[t]}function xg(e){return Rf.isPlainObject(e)||Rf.isArray(e)}function wg(e){return Rf.endsWith(e,"[]")?e.slice(0,-2):e}function Sg(e,t,i){return e?e.concat(t).map((function(e,t){return e=wg(e),!i&&t?"["+e+"]":e})).join(i?".":""):t}pg.inherits(yg,cg),yg.LINE_BREAK="\r\n",yg.DEFAULT_CONTENT_TYPE="application/octet-stream",yg.prototype.append=function(e,t,i){"string"==typeof(i=i||{})&&(i={filename:i});var n=cg.prototype.append.bind(this);if("number"==typeof t&&(t=""+t),pg.isArray(t))this._error(new Error("Arrays are not supported."));else{var s=this._multiPartHeader(e,t,i),a=this._multiPartFooter();n(s),n(t),n(a),this._trackLength(s,t,i)}},yg.prototype._trackLength=function(e,t,i){var n=0;null!=i.knownLength?n+=+i.knownLength:Buffer.isBuffer(t)?n=t.length:"string"==typeof t&&(n=Buffer.byteLength(t)),this._valueLength+=n,this._overheadLength+=Buffer.byteLength(e)+yg.LINE_BREAK.length,t&&(t.path||t.readable&&t.hasOwnProperty("httpVersion")||t instanceof fg)&&(i.knownLength||this._valuesToMeasure.push(t))},yg.prototype._lengthRetriever=function(e,t){e.hasOwnProperty("fd")?null!=e.end&&e.end!=1/0&&null!=e.start?t(null,e.end+1-(e.start?e.start:0)):hg.stat(e.path,(function(i,n){var s;i?t(i):(s=n.size-(e.start?e.start:0),t(null,s))})):e.hasOwnProperty("httpVersion")?t(null,+e.headers["content-length"]):e.hasOwnProperty("httpModule")?(e.on("response",(function(i){e.pause(),t(null,+i.headers["content-length"])})),e.resume()):t("Unknown stream")},yg.prototype._multiPartHeader=function(e,t,i){if("string"==typeof i.header)return i.header;var n,s=this._getContentDisposition(t,i),a=this._getContentType(t,i),r="",o={"Content-Disposition":["form-data",'name="'+e+'"'].concat(s||[]),"Content-Type":[].concat(a||[])};for(var c in"object"==typeof i.header&&bg(o,i.header),o)o.hasOwnProperty(c)&&null!=(n=o[c])&&(Array.isArray(n)||(n=[n]),n.length&&(r+=c+": "+n.join("; ")+yg.LINE_BREAK));return"--"+this.getBoundary()+yg.LINE_BREAK+r+yg.LINE_BREAK},yg.prototype._getContentDisposition=function(e,t){var i,n;return"string"==typeof t.filepath?i=dg.normalize(t.filepath).replace(/\\/g,"/"):t.filename||e.name||e.path?i=dg.basename(t.filename||e.name||e.path):e.readable&&e.hasOwnProperty("httpVersion")&&(i=dg.basename(e.client._httpMessage.path||"")),i&&(n='filename="'+i+'"'),n},yg.prototype._getContentType=function(e,t){var i=t.contentType;return!i&&e.name&&(i=gg.lookup(e.name)),!i&&e.path&&(i=gg.lookup(e.path)),!i&&e.readable&&e.hasOwnProperty("httpVersion")&&(i=e.headers["content-type"]),i||!t.filepath&&!t.filename||(i=gg.lookup(t.filepath||t.filename)),i||"object"!=typeof e||(i=yg.DEFAULT_CONTENT_TYPE),i},yg.prototype._multiPartFooter=function(){return function(e){var t=yg.LINE_BREAK;0===this._streams.length&&(t+=this._lastBoundary()),e(t)}.bind(this)},yg.prototype._lastBoundary=function(){return"--"+this.getBoundary()+"--"+yg.LINE_BREAK},yg.prototype.getHeaders=function(e){var t,i={"content-type":"multipart/form-data; boundary="+this.getBoundary()};for(t in e)e.hasOwnProperty(t)&&(i[t.toLowerCase()]=e[t]);return i},yg.prototype.setBoundary=function(e){this._boundary=e},yg.prototype.getBoundary=function(){return this._boundary||this._generateBoundary(),this._boundary},yg.prototype.getBuffer=function(){for(var e=new Buffer.alloc(0),t=this.getBoundary(),i=0,n=this._streams.length;i<n;i++)"function"!=typeof this._streams[i]&&(e=Buffer.isBuffer(this._streams[i])?Buffer.concat([e,this._streams[i]]):Buffer.concat([e,Buffer.from(this._streams[i])]),"string"==typeof this._streams[i]&&this._streams[i].substring(2,t.length+2)===t||(e=Buffer.concat([e,Buffer.from(yg.LINE_BREAK)])));return Buffer.concat([e,Buffer.from(this._lastBoundary())])},yg.prototype._generateBoundary=function(){for(var e="--------------------------",t=0;t<24;t++)e+=Math.floor(10*Math.random()).toString(16);this._boundary=e},yg.prototype.getLengthSync=function(){var e=this._overheadLength+this._valueLength;return this._streams.length&&(e+=this._lastBoundary().length),this.hasKnownLength()||this._error(new Error("Cannot calculate proper length in synchronous way.")),e},yg.prototype.hasKnownLength=function(){var e=!0;return this._valuesToMeasure.length&&(e=!1),e},yg.prototype.getLength=function(e){var t=this._overheadLength+this._valueLength;this._streams.length&&(t+=this._lastBoundary().length),this._valuesToMeasure.length?vg.parallel(this._valuesToMeasure,this._lengthRetriever,(function(i,n){i?e(i):(n.forEach((function(e){t+=e})),e(null,t))})):process.nextTick(e.bind(this,null,t))},yg.prototype.submit=function(e,t){var i,n,s={method:"post"};return"string"==typeof e?(e=mg(e),n=bg({port:e.port,path:e.pathname,host:e.hostname,protocol:e.protocol},s)):(n=bg(e,s)).port||(n.port="https:"==n.protocol?443:80),n.headers=this.getHeaders(e.headers),i="https:"==n.protocol?ug.request(n):lg.request(n),this.getLength(function(e,n){if(e&&"Unknown stream"!==e)this._error(e);else if(n&&i.setHeader("Content-Length",n),this.pipe(i),t){var s,a=function(e,n){return i.removeListener("error",a),i.removeListener("response",s),t.call(this,e,n)};s=a.bind(this,null),i.on("error",a),i.on("response",s)}}.bind(this)),i},yg.prototype._error=function(e){this.error||(this.error=e,this.pause(),this.emit("error",e))},yg.prototype.toString=function(){return"[object FormData]"};const Rg=Rf.toFlatObject(Rf,{},null,(function(e){return/^is[A-Z]/.test(e)}));function Cg(e,t,i){if(!Rf.isObject(e))throw new TypeError("target must be an object");t=t||new(_g||FormData);const n=(i=Rf.toFlatObject(i,{metaTokens:!0,dots:!1,indexes:!1},!1,(function(e,t){return!Rf.isUndefined(t[e])}))).metaTokens,s=i.visitor||d,a=i.dots,r=i.indexes,o=(i.Blob||"undefined"!=typeof Blob&&Blob)&&((c=t)&&Rf.isFunction(c.append)&&"FormData"===c[Symbol.toStringTag]&&c[Symbol.iterator]);var c;if(!Rf.isFunction(s))throw new TypeError("visitor must be a function");function p(e){if(null===e)return"";if(Rf.isDate(e))return e.toISOString();if(!o&&Rf.isBlob(e))throw new Cf("Blob is not supported. Use a Buffer instead.");return Rf.isArrayBuffer(e)||Rf.isTypedArray(e)?o&&"function"==typeof Blob?new Blob([e]):Buffer.from(e):e}function d(e,i,s){let o=e;if(e&&!s&&"object"==typeof e)if(Rf.endsWith(i,"{}"))i=n?i:i.slice(0,-2),e=JSON.stringify(e);else if(Rf.isArray(e)&&function(e){return Rf.isArray(e)&&!e.some(xg)}(e)||Rf.isFileList(e)||Rf.endsWith(i,"[]")&&(o=Rf.toArray(e)))return i=wg(i),o.forEach((function(e,n){!Rf.isUndefined(e)&&null!==e&&t.append(!0===r?Sg([i],n,a):null===r?i:i+"[]",p(e))})),!1;return!!xg(e)||(t.append(Sg(s,i,a),p(e)),!1)}const l=[],u=Object.assign(Rg,{defaultVisitor:d,convertValue:p,isVisitable:xg});if(!Rf.isObject(e))throw new TypeError("data must be an object");return function e(i,n){if(!Rf.isUndefined(i)){if(-1!==l.indexOf(i))throw Error("Circular reference detected in "+n.join("."));l.push(i),Rf.forEach(i,(function(i,a){!0===(!(Rf.isUndefined(i)||null===i)&&s.call(t,i,Rf.isString(a)?a.trim():a,n,u))&&e(i,n?n.concat(a):[a])})),l.pop()}}(e),t}function kg(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,(function(e){return t[e]}))}function Tg(e,t){this._pairs=[],e&&Cg(e,this,t)}const Pg=Tg.prototype;function Eg(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function Og(e,t,i){if(!t)return e;const n=i&&i.encode||Eg,s=i&&i.serialize;let a;if(a=s?s(t,i):Rf.isURLSearchParams(t)?t.toString():new Tg(t,i).toString(n),a){const t=e.indexOf("#");-1!==t&&(e=e.slice(0,t)),e+=(-1===e.indexOf("?")?"?":"&")+a}return e}Pg.append=function(e,t){this._pairs.push([e,t])},Pg.toString=function(e){const t=e?function(t){return e.call(this,t,kg)}:kg;return this._pairs.map((function(e){return t(e[0])+"="+t(e[1])}),"").join("&")};class Dg{constructor(){this.handlers=[]}use(e,t,i){return this.handlers.push({fulfilled:e,rejected:t,synchronous:!!i&&i.synchronous,runWhen:i?i.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(e){Rf.forEach(this.handlers,(function(t){null!==t&&e(t)}))}}var Ig={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},jg={isNode:!0,classes:{URLSearchParams:t.URLSearchParams,FormData:_g,Blob:"undefined"!=typeof Blob&&Blob||null},protocols:["http","https","file","data"]};function Lg(e){function t(e,i,n,s){let a=e[s++];const r=Number.isFinite(+a),o=s>=e.length;if(a=!a&&Rf.isArray(n)?n.length:a,o)return Rf.hasOwnProp(n,a)?n[a]=[n[a],i]:n[a]=i,!r;n[a]&&Rf.isObject(n[a])||(n[a]=[]);return t(e,i,n[a],s)&&Rf.isArray(n[a])&&(n[a]=function(e){const t={},i=Object.keys(e);let n;const s=i.length;let a;for(n=0;n<s;n++)a=i[n],t[a]=e[a];return t}(n[a])),!r}if(Rf.isFormData(e)&&Rf.isFunction(e.entries)){const i={};return Rf.forEachEntry(e,((e,n)=>{t(function(e){return Rf.matchAll(/\w+|\[(\w*)]/g,e).map((e=>"[]"===e[0]?"":e[1]||e[0]))}(e),n,i,0)})),i}return null}const Mg={"Content-Type":void 0};const Ag={transitional:Ig,adapter:["xhr","http"],transformRequest:[function(e,t){const i=t.getContentType()||"",n=i.indexOf("application/json")>-1,s=Rf.isObject(e);s&&Rf.isHTMLForm(e)&&(e=new FormData(e));if(Rf.isFormData(e))return n&&n?JSON.stringify(Lg(e)):e;if(Rf.isArrayBuffer(e)||Rf.isBuffer(e)||Rf.isStream(e)||Rf.isFile(e)||Rf.isBlob(e))return e;if(Rf.isArrayBufferView(e))return e.buffer;if(Rf.isURLSearchParams(e))return t.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let a;if(s){if(i.indexOf("application/x-www-form-urlencoded")>-1)return function(e,t){return Cg(e,new jg.classes.URLSearchParams,Object.assign({visitor:function(e,t,i,n){return Rf.isBuffer(e)?(this.append(t,e.toString("base64")),!1):n.defaultVisitor.apply(this,arguments)}},t))}(e,this.formSerializer).toString();if((a=Rf.isFileList(e))||i.indexOf("multipart/form-data")>-1){const t=this.env&&this.env.FormData;return Cg(a?{"files[]":e}:e,t&&new t,this.formSerializer)}}return s||n?(t.setContentType("application/json",!1),function(e,t,i){if(Rf.isString(e))try{return(t||JSON.parse)(e),Rf.trim(e)}catch(e){if("SyntaxError"!==e.name)throw e}return(i||JSON.stringify)(e)}(e)):e}],transformResponse:[function(e){const t=this.transitional||Ag.transitional,i=t&&t.forcedJSONParsing,n="json"===this.responseType;if(e&&Rf.isString(e)&&(i&&!this.responseType||n)){const i=!(t&&t.silentJSONParsing)&&n;try{return JSON.parse(e)}catch(e){if(i){if("SyntaxError"===e.name)throw Cf.from(e,Cf.ERR_BAD_RESPONSE,this,null,this.response);throw e}}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:jg.classes.FormData,Blob:jg.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*"}}};Rf.forEach(["delete","get","head"],(function(e){Ag.headers[e]={}})),Rf.forEach(["post","put","patch"],(function(e){Ag.headers[e]=Rf.merge(Mg)}));const Ng=Rf.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]);const Bg=Symbol("internals");function Fg(e){return e&&String(e).trim().toLowerCase()}function Ug(e){return!1===e||null==e?e:Rf.isArray(e)?e.map(Ug):String(e)}function zg(e,t,i,n){return Rf.isFunction(n)?n.call(this,t,i):Rf.isString(t)?Rf.isString(n)?-1!==t.indexOf(n):Rf.isRegExp(n)?n.test(t):void 0:void 0}class qg{constructor(e){e&&this.set(e)}set(e,t,i){const n=this;function s(e,t,i){const s=Fg(t);if(!s)throw new Error("header name must be a non-empty string");const a=Rf.findKey(n,s);(!a||void 0===n[a]||!0===i||void 0===i&&!1!==n[a])&&(n[a||t]=Ug(e))}const a=(e,t)=>Rf.forEach(e,((e,i)=>s(e,i,t)));return Rf.isPlainObject(e)||e instanceof this.constructor?a(e,t):Rf.isString(e)&&(e=e.trim())&&!/^[-_a-zA-Z]+$/.test(e.trim())?a((e=>{const t={};let i,n,s;return e&&e.split("\n").forEach((function(e){s=e.indexOf(":"),i=e.substring(0,s).trim().toLowerCase(),n=e.substring(s+1).trim(),!i||t[i]&&Ng[i]||("set-cookie"===i?t[i]?t[i].push(n):t[i]=[n]:t[i]=t[i]?t[i]+", "+n:n)})),t})(e),t):null!=e&&s(t,e,i),this}get(e,t){if(e=Fg(e)){const i=Rf.findKey(this,e);if(i){const e=this[i];if(!t)return e;if(!0===t)return function(e){const t=Object.create(null),i=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let n;for(;n=i.exec(e);)t[n[1]]=n[2];return t}(e);if(Rf.isFunction(t))return t.call(this,e,i);if(Rf.isRegExp(t))return t.exec(e);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,t){if(e=Fg(e)){const i=Rf.findKey(this,e);return!(!i||t&&!zg(0,this[i],i,t))}return!1}delete(e,t){const i=this;let n=!1;function s(e){if(e=Fg(e)){const s=Rf.findKey(i,e);!s||t&&!zg(0,i[s],s,t)||(delete i[s],n=!0)}}return Rf.isArray(e)?e.forEach(s):s(e),n}clear(){return Object.keys(this).forEach(this.delete.bind(this))}normalize(e){const t=this,i={};return Rf.forEach(this,((n,s)=>{const a=Rf.findKey(i,s);if(a)return t[a]=Ug(n),void delete t[s];const r=e?function(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,((e,t,i)=>t.toUpperCase()+i))}(s):String(s).trim();r!==s&&delete t[s],t[r]=Ug(n),i[r]=!0})),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const t=Object.create(null);return Rf.forEach(this,((i,n)=>{null!=i&&!1!==i&&(t[n]=e&&Rf.isArray(i)?i.join(", "):i)})),t}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map((([e,t])=>e+": "+t)).join("\n")}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static concat(e,...t){const i=new this(e);return t.forEach((e=>i.set(e))),i}static accessor(e){const t=(this[Bg]=this[Bg]={accessors:{}}).accessors,i=this.prototype;function n(e){const n=Fg(e);t[n]||(!function(e,t){const i=Rf.toCamelCase(" "+t);["get","set","has"].forEach((n=>{Object.defineProperty(e,n+i,{value:function(e,i,s){return this[n].call(this,t,e,i,s)},configurable:!0})}))}(i,e),t[n]=!0)}return Rf.isArray(e)?e.forEach(n):n(e),this}}function $g(e,t){const i=this||Ag,n=t||i,s=qg.from(n.headers);let a=n.data;return Rf.forEach(e,(function(e){a=e.call(i,a,s.normalize(),t?t.status:void 0)})),s.normalize(),a}function Vg(e){return!(!e||!e.__CANCEL__)}function Wg(e,t,i){Cf.call(this,null==e?"canceled":e,Cf.ERR_CANCELED,t,i),this.name="CanceledError"}function Gg(e,t,i){const n=i.config.validateStatus;i.status&&n&&!n(i.status)?t(new Cf("Request failed with status code "+i.status,[Cf.ERR_BAD_REQUEST,Cf.ERR_BAD_RESPONSE][Math.floor(i.status/100)-4],i.config,i.request,i)):e(i)}function Hg(e,t){return e&&!function(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}(t)?function(e,t){return t?e.replace(/\/+$/,"")+"/"+t.replace(/^\/+/,""):e}(e,t):t}qg.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent"]),Rf.freezeMethods(qg.prototype),Rf.freezeMethods(qg),Rf.inherits(Wg,Cf,{__CANCEL__:!0});var Kg=t.parse,Jg={ftp:21,gopher:70,http:80,https:443,ws:80,wss:443},Qg=String.prototype.endsWith||function(e){return e.length<=this.length&&-1!==this.indexOf(e,this.length-e.length)};function Yg(e){return process.env[e.toLowerCase()]||process.env[e.toUpperCase()]||""}var Xg,Zg=function(e){var t="string"==typeof e?Kg(e):e||{},i=t.protocol,n=t.host,s=t.port;if("string"!=typeof n||!n||"string"!=typeof i)return"";if(i=i.split(":",1)[0],!function(e,t){var i=(Yg("npm_config_no_proxy")||Yg("no_proxy")).toLowerCase();if(!i)return!0;if("*"===i)return!1;return i.split(/[,\s]/).every((function(i){if(!i)return!0;var n=i.match(/^(.+):(\d+)$/),s=n?n[1]:i,a=n?parseInt(n[2]):0;return!(!a||a===t)||(/^[.*]/.test(s)?("*"===s.charAt(0)&&(s=s.slice(1)),!Qg.call(e,s)):e!==s)}))}(n=n.replace(/:\d*$/,""),s=parseInt(s)||Jg[i]||0))return"";var a=Yg("npm_config_"+i+"_proxy")||Yg(i+"_proxy")||Yg("npm_config_proxy")||Yg("all_proxy");return a&&-1===a.indexOf("://")&&(a=i+"://"+a),a},ev={},tv={get exports(){return ev},set exports(e){ev=e}},iv=t,nv=iv.URL,sv=n,av=s,rv=a.Writable,ov=u,cv=function(){if(!Xg){try{Xg=jo("follow-redirects")}catch(e){}"function"!=typeof Xg&&(Xg=function(){})}Xg.apply(null,arguments)},pv=["abort","aborted","connect","error","socket","timeout"],dv=Object.create(null);pv.forEach((function(e){dv[e]=function(t,i,n){this._redirectable.emit(e,t,i,n)}}));var lv=xv("ERR_INVALID_URL","Invalid URL",TypeError),uv=xv("ERR_FR_REDIRECTION_FAILURE","Redirected request failed"),mv=xv("ERR_FR_TOO_MANY_REDIRECTS","Maximum number of redirects exceeded"),hv=xv("ERR_FR_MAX_BODY_LENGTH_EXCEEDED","Request body larger than maxBodyLength limit"),fv=xv("ERR_STREAM_WRITE_AFTER_END","write after end");function gv(e,t){rv.call(this),this._sanitizeOptions(e),this._options=e,this._ended=!1,this._ending=!1,this._redirectCount=0,this._redirects=[],this._requestBodyLength=0,this._requestBodyBuffers=[],t&&this.on("response",t);var i=this;this._onNativeResponse=function(e){i._processResponse(e)},this._performRequest()}function vv(e){var t={maxRedirects:21,maxBodyLength:10485760},i={};return Object.keys(e).forEach((function(n){var s=n+":",a=i[s]=e[n],r=t[n]=Object.create(a);Object.defineProperties(r,{request:{value:function(e,n,a){if(Sv(e)){var r;try{r=_v(new nv(e))}catch(t){r=iv.parse(e)}if(!Sv(r.protocol))throw new lv({input:e});e=r}else nv&&e instanceof nv?e=_v(e):(a=n,n=e,e={protocol:s});return Rv(n)&&(a=n,n=null),(n=Object.assign({maxRedirects:t.maxRedirects,maxBodyLength:t.maxBodyLength},e,n)).nativeProtocols=i,Sv(n.host)||Sv(n.hostname)||(n.hostname="::1"),ov.equal(n.protocol,s,"protocol mismatch"),cv("options",n),new gv(n,a)},configurable:!0,enumerable:!0,writable:!0},get:{value:function(e,t,i){var n=r.request(e,t,i);return n.end(),n},configurable:!0,enumerable:!0,writable:!0}})})),t}function bv(){}function _v(e){var t={protocol:e.protocol,hostname:e.hostname.startsWith("[")?e.hostname.slice(1,-1):e.hostname,hash:e.hash,search:e.search,pathname:e.pathname,path:e.pathname+e.search,href:e.href};return""!==e.port&&(t.port=Number(e.port)),t}function yv(e,t){var i;for(var n in t)e.test(n)&&(i=t[n],delete t[n]);return null==i?void 0:String(i).trim()}function xv(e,t,i){function n(i){Error.captureStackTrace(this,this.constructor),Object.assign(this,i||{}),this.code=e,this.message=this.cause?t+": "+this.cause.message:t}return n.prototype=new(i||Error),n.prototype.constructor=n,n.prototype.name="Error ["+e+"]",n}function wv(e){for(var t of pv)e.removeListener(t,dv[t]);e.on("error",bv),e.abort()}function Sv(e){return"string"==typeof e||e instanceof String}function Rv(e){return"function"==typeof e}gv.prototype=Object.create(rv.prototype),gv.prototype.abort=function(){wv(this._currentRequest),this.emit("abort")},gv.prototype.write=function(e,t,i){if(this._ending)throw new fv;if(!Sv(e)&&("object"!=typeof(n=e)||!("length"in n)))throw new TypeError("data should be a string, Buffer or Uint8Array");var n;Rv(t)&&(i=t,t=null),0!==e.length?this._requestBodyLength+e.length<=this._options.maxBodyLength?(this._requestBodyLength+=e.length,this._requestBodyBuffers.push({data:e,encoding:t}),this._currentRequest.write(e,t,i)):(this.emit("error",new hv),this.abort()):i&&i()},gv.prototype.end=function(e,t,i){if(Rv(e)?(i=e,e=t=null):Rv(t)&&(i=t,t=null),e){var n=this,s=this._currentRequest;this.write(e,t,(function(){n._ended=!0,s.end(null,null,i)})),this._ending=!0}else this._ended=this._ending=!0,this._currentRequest.end(null,null,i)},gv.prototype.setHeader=function(e,t){this._options.headers[e]=t,this._currentRequest.setHeader(e,t)},gv.prototype.removeHeader=function(e){delete this._options.headers[e],this._currentRequest.removeHeader(e)},gv.prototype.setTimeout=function(e,t){var i=this;function n(t){t.setTimeout(e),t.removeListener("timeout",t.destroy),t.addListener("timeout",t.destroy)}function s(t){i._timeout&&clearTimeout(i._timeout),i._timeout=setTimeout((function(){i.emit("timeout"),a()}),e),n(t)}function a(){i._timeout&&(clearTimeout(i._timeout),i._timeout=null),i.removeListener("abort",a),i.removeListener("error",a),i.removeListener("response",a),t&&i.removeListener("timeout",t),i.socket||i._currentRequest.removeListener("socket",s)}return t&&this.on("timeout",t),this.socket?s(this.socket):this._currentRequest.once("socket",s),this.on("socket",n),this.on("abort",a),this.on("error",a),this.on("response",a),this},["flushHeaders","getHeader","setNoDelay","setSocketKeepAlive"].forEach((function(e){gv.prototype[e]=function(t,i){return this._currentRequest[e](t,i)}})),["aborted","connection","socket"].forEach((function(e){Object.defineProperty(gv.prototype,e,{get:function(){return this._currentRequest[e]}})})),gv.prototype._sanitizeOptions=function(e){if(e.headers||(e.headers={}),e.host&&(e.hostname||(e.hostname=e.host),delete e.host),!e.pathname&&e.path){var t=e.path.indexOf("?");t<0?e.pathname=e.path:(e.pathname=e.path.substring(0,t),e.search=e.path.substring(t))}},gv.prototype._performRequest=function(){var e=this._options.protocol,t=this._options.nativeProtocols[e];if(t){if(this._options.agents){var i=e.slice(0,-1);this._options.agent=this._options.agents[i]}var n=this._currentRequest=t.request(this._options,this._onNativeResponse);for(var s of(n._redirectable=this,pv))n.on(s,dv[s]);if(this._currentUrl=/^\//.test(this._options.path)?iv.format(this._options):this._options.path,this._isRedirect){var a=0,r=this,o=this._requestBodyBuffers;!function e(t){if(n===r._currentRequest)if(t)r.emit("error",t);else if(a<o.length){var i=o[a++];n.finished||n.write(i.data,i.encoding,e)}else r._ended&&n.end()}()}}else this.emit("error",new TypeError("Unsupported protocol "+e))},gv.prototype._processResponse=function(e){var t=e.statusCode;this._options.trackRedirects&&this._redirects.push({url:this._currentUrl,headers:e.headers,statusCode:t});var i=e.headers.location;if(!i||!1===this._options.followRedirects||t<300||t>=400)return e.responseUrl=this._currentUrl,e.redirects=this._redirects,this.emit("response",e),void(this._requestBodyBuffers=[]);if(wv(this._currentRequest),e.destroy(),++this._redirectCount>this._options.maxRedirects)this.emit("error",new mv);else{var n,s=this._options.beforeRedirect;s&&(n=Object.assign({Host:e.req.getHeader("host")},this._options.headers));var a=this._options.method;((301===t||302===t)&&"POST"===this._options.method||303===t&&!/^(?:GET|HEAD)$/.test(this._options.method))&&(this._options.method="GET",this._requestBodyBuffers=[],yv(/^content-/i,this._options.headers));var r,o=yv(/^host$/i,this._options.headers),c=iv.parse(this._currentUrl),p=o||c.host,d=/^\w+:/.test(i)?this._currentUrl:iv.format(Object.assign(c,{host:p}));try{r=iv.resolve(d,i)}catch(e){return void this.emit("error",new uv({cause:e}))}cv("redirecting to",r),this._isRedirect=!0;var l=iv.parse(r);if(Object.assign(this._options,l),(l.protocol!==c.protocol&&"https:"!==l.protocol||l.host!==p&&!function(e,t){ov(Sv(e)&&Sv(t));var i=e.length-t.length-1;return i>0&&"."===e[i]&&e.endsWith(t)}(l.host,p))&&yv(/^(?:authorization|cookie)$/i,this._options.headers),Rv(s)){var u={headers:e.headers,statusCode:t},m={url:d,method:a,headers:n};try{s(this._options,u,m)}catch(e){return void this.emit("error",e)}this._sanitizeOptions(this._options)}try{this._performRequest()}catch(e){this.emit("error",new uv({cause:e}))}}},tv.exports=vv({http:sv,https:av}),ev.wrap=vv;function Cv(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}const kv=/^(?:([^;]+);)?(?:[^;]+;)?(base64|),([\s\S]*)$/;function Tv(e,t){e=e||10;const i=new Array(e),n=new Array(e);let s,a=0,r=0;return t=void 0!==t?t:1e3,function(o){const c=Date.now(),p=n[r];s||(s=c),i[a]=o,n[a]=c;let d=r,l=0;for(;d!==a;)l+=i[d++],d%=e;if(a=(a+1)%e,a===r&&(r=(r+1)%e),c-s<t)return;const u=p&&c-p;return u?Math.round(1e3*l/u):void 0}}const Pv=Symbol("internals");class Ev extends a.Transform{constructor(e){super({readableHighWaterMark:(e=Rf.toFlatObject(e,{maxRate:0,chunkSize:65536,minChunkSize:100,timeWindow:500,ticksRate:2,samplesCount:15},null,((e,t)=>!Rf.isUndefined(t[e])))).chunkSize});const t=this,i=this[Pv]={length:e.length,timeWindow:e.timeWindow,ticksRate:e.ticksRate,chunkSize:e.chunkSize,maxRate:e.maxRate,minChunkSize:e.minChunkSize,bytesSeen:0,isCaptured:!1,notifiedBytesLoaded:0,ts:Date.now(),bytes:0,onReadCallback:null},n=Tv(i.ticksRate*e.samplesCount,i.timeWindow);this.on("newListener",(e=>{"progress"===e&&(i.isCaptured||(i.isCaptured=!0))}));let s=0;i.updateProgress=function(e,t){let i=0;const n=1e3/t;let s=null;return function(t,a){const r=Date.now();if(t||r-i>n)return s&&(clearTimeout(s),s=null),i=r,e.apply(null,a);s||(s=setTimeout((()=>(s=null,i=Date.now(),e.apply(null,a))),n-(r-i)))}}((function(){const e=i.length,a=i.bytesSeen,r=a-s;if(!r||t.destroyed)return;const o=n(r);s=a,process.nextTick((()=>{t.emit("progress",{loaded:a,total:e,progress:e?a/e:void 0,bytes:r,rate:o||void 0,estimated:o&&e&&a<=e?(e-a)/o:void 0})}))}),i.ticksRate);const a=()=>{i.updateProgress(!0)};this.once("end",a),this.once("error",a)}_read(e){const t=this[Pv];return t.onReadCallback&&t.onReadCallback(),super._read(e)}_transform(e,t,i){const n=this,s=this[Pv],a=s.maxRate,r=this.readableHighWaterMark,o=s.timeWindow,c=a/(1e3/o),p=!1!==s.minChunkSize?Math.max(s.minChunkSize,.01*c):0;const d=(e,t)=>{const i=Buffer.byteLength(e);let d,l=null,u=r,m=0;if(a){const e=Date.now();(!s.ts||(m=e-s.ts)>=o)&&(s.ts=e,d=c-s.bytes,s.bytes=d<0?-d:0,m=0),d=c-s.bytes}if(a){if(d<=0)return setTimeout((()=>{t(null,e)}),o-m);d<u&&(u=d)}u&&i>u&&i-u>p&&(l=e.subarray(u),e=e.subarray(0,u)),function(e,t){const i=Buffer.byteLength(e);s.bytesSeen+=i,s.bytes+=i,s.isCaptured&&s.updateProgress(),n.push(e)?process.nextTick(t):s.onReadCallback=()=>{s.onReadCallback=null,process.nextTick(t)}}(e,l?()=>{process.nextTick(t,null,l)}:t)};d(e,(function e(t,n){if(t)return i(t);n?d(n,e):i(null)}))}setLength(e){return this[Pv].length=+e,this}}const Ov={flush:r.constants.Z_SYNC_FLUSH,finishFlush:r.constants.Z_SYNC_FLUSH},Dv={flush:r.constants.BROTLI_OPERATION_FLUSH,finishFlush:r.constants.BROTLI_OPERATION_FLUSH},Iv=Rf.isFunction(r.createBrotliDecompress),{http:jv,https:Lv}=ev,Mv=/https:?/,Av=jg.protocols.map((e=>e+":"));function Nv(e){e.beforeRedirects.proxy&&e.beforeRedirects.proxy(e),e.beforeRedirects.config&&e.beforeRedirects.config(e)}function Bv(e,t,i){let n=t;if(!n&&!1!==n){const e=Zg(i);e&&(n=new URL(e))}if(n){if(n.username&&(n.auth=(n.username||"")+":"+(n.password||"")),n.auth){(n.auth.username||n.auth.password)&&(n.auth=(n.auth.username||"")+":"+(n.auth.password||""));const t=Buffer.from(n.auth,"utf8").toString("base64");e.headers["Proxy-Authorization"]="Basic "+t}e.headers.host=e.hostname+(e.port?":"+e.port:"");const t=n.hostname||n.host;e.hostname=t,e.host=t,e.port=n.port,e.path=i,n.protocol&&(e.protocol=n.protocol.includes(":")?n.protocol:`${n.protocol}:`)}e.beforeRedirects.proxy=function(e){Bv(e,t,e.href)}}var Fv="undefined"!=typeof process&&"process"===Rf.kindOf(process)&&function(e){return new Promise((function(t,i){let o=e.data;const c=e.responseType,p=e.responseEncoding,l=e.method.toUpperCase();let u,m,h,f=!1;const g=new d;function v(){u||(u=!0,e.cancelToken&&e.cancelToken.unsubscribe(x),e.signal&&e.signal.removeEventListener("abort",x),g.removeAllListeners())}function b(e,n){m||(m=!0,n&&(f=!0,v()),n?i(e):t(e))}const _=function(e){b(e)},y=function(e){b(e,!0)};function x(t){g.emit("abort",!t||t.type?new Wg(null,e,h):t)}g.once("abort",y),(e.cancelToken||e.signal)&&(e.cancelToken&&e.cancelToken.subscribe(x),e.signal&&(e.signal.aborted?x():e.signal.addEventListener("abort",x)));const w=Hg(e.baseURL,e.url),S=new URL(w),R=S.protocol||Av[0];if("data:"===R){let t;if("GET"!==l)return Gg(_,y,{status:405,statusText:"method not allowed",headers:{},config:e});try{t=function(e,t,i){const n=i&&i.Blob||jg.classes.Blob,s=Cv(e);if(void 0===t&&n&&(t=!0),"data"===s){e=s.length?e.slice(s.length+1):e;const i=kv.exec(e);if(!i)throw new Cf("Invalid URL",Cf.ERR_INVALID_URL);const a=i[1],r=i[2],o=i[3],c=Buffer.from(decodeURIComponent(o),r?"base64":"utf8");if(t){if(!n)throw new Cf("Blob is not supported",Cf.ERR_NOT_SUPPORT);return new n([c],{type:a})}return c}throw new Cf("Unsupported protocol "+s,Cf.ERR_NOT_SUPPORT)}(e.url,"blob"===c,{Blob:e.env&&e.env.Blob})}catch(t){throw Cf.from(t,Cf.ERR_BAD_REQUEST,e)}return"text"===c?(t=t.toString(p),p&&"utf8"!==p||(o=Rf.stripBOM(t))):"stream"===c&&(t=a.Readable.from(t)),Gg(_,y,{data:t,status:200,statusText:"OK",headers:new qg,config:e})}if(-1===Av.indexOf(R))return y(new Cf("Unsupported protocol "+R,Cf.ERR_BAD_REQUEST,e));const C=qg.from(e.headers).normalize();C.set("User-Agent","axios/1.2.3",!1);const k=e.onDownloadProgress,T=e.onUploadProgress,P=e.maxRate;let E,O;if(Rf.isFormData(o)&&Rf.isFunction(o.getHeaders))C.set(o.getHeaders());else if(o&&!Rf.isStream(o)){if(Buffer.isBuffer(o));else if(Rf.isArrayBuffer(o))o=Buffer.from(new Uint8Array(o));else{if(!Rf.isString(o))return y(new Cf("Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream",Cf.ERR_BAD_REQUEST,e));o=Buffer.from(o,"utf-8")}if(C.set("Content-Length",o.length,!1),e.maxBodyLength>-1&&o.length>e.maxBodyLength)return y(new Cf("Request body larger than maxBodyLength limit",Cf.ERR_BAD_REQUEST,e))}const D=Rf.toFiniteNumber(C.getContentLength());let I,j;if(Rf.isArray(P)?(E=P[0],O=P[1]):E=O=P,o&&(T||E)&&(Rf.isStream(o)||(o=a.Readable.from(o,{objectMode:!1})),o=a.pipeline([o,new Ev({length:D,maxRate:Rf.toFiniteNumber(E)})],Rf.noop),T&&o.on("progress",(e=>{T(Object.assign(e,{upload:!0}))}))),e.auth){I=(e.auth.username||"")+":"+(e.auth.password||"")}if(!I&&S.username){I=S.username+":"+S.password}I&&C.delete("authorization");try{j=Og(S.pathname+S.search,e.params,e.paramsSerializer).replace(/^\?/,"")}catch(t){const i=new Error(t.message);return i.config=e,i.url=e.url,i.exists=!0,y(i)}C.set("Accept-Encoding","gzip, compress, deflate"+(Iv?", br":""),!1);const L={path:j,method:l,headers:C.toJSON(),agents:{http:e.httpAgent,https:e.httpsAgent},auth:I,protocol:R,beforeRedirect:Nv,beforeRedirects:{}};let M;e.socketPath?L.socketPath=e.socketPath:(L.hostname=S.hostname,L.port=S.port,Bv(L,e.proxy,R+"//"+S.hostname+(S.port?":"+S.port:"")+L.path));const A=Mv.test(L.protocol);if(L.agent=A?e.httpsAgent:e.httpAgent,e.transport?M=e.transport:0===e.maxRedirects?M=A?s:n:(e.maxRedirects&&(L.maxRedirects=e.maxRedirects),e.beforeRedirect&&(L.beforeRedirects.config=e.beforeRedirect),M=A?Lv:jv),e.maxBodyLength>-1?L.maxBodyLength=e.maxBodyLength:L.maxBodyLength=1/0,e.insecureHTTPParser&&(L.insecureHTTPParser=e.insecureHTTPParser),h=M.request(L,(function(t){if(h.destroyed)return;const i=[t],n=+t.headers["content-length"];if(k){const e=new Ev({length:Rf.toFiniteNumber(n),maxRate:Rf.toFiniteNumber(O)});k&&e.on("progress",(e=>{k(Object.assign(e,{download:!0}))})),i.push(e)}let s=t;const o=t.req||h;if(!1!==e.decompress&&t.headers["content-encoding"])switch("HEAD"!==l&&204!==t.statusCode||delete t.headers["content-encoding"],t.headers["content-encoding"]){case"gzip":case"x-gzip":case"compress":case"x-compress":case"deflate":i.push(r.createUnzip(Ov)),delete t.headers["content-encoding"];break;case"br":Iv&&(i.push(r.createBrotliDecompress(Dv)),delete t.headers["content-encoding"])}s=i.length>1?a.pipeline(i,Rf.noop):i[0];const d=a.finished(s,(()=>{d(),v()})),u={status:t.statusCode,statusText:t.statusMessage,headers:new qg(t.headers),config:e,request:o};if("stream"===c)u.data=s,Gg(_,y,u);else{const t=[];let i=0;s.on("data",(function(n){t.push(n),i+=n.length,e.maxContentLength>-1&&i>e.maxContentLength&&(f=!0,s.destroy(),y(new Cf("maxContentLength size of "+e.maxContentLength+" exceeded",Cf.ERR_BAD_RESPONSE,e,o)))})),s.on("aborted",(function(){if(f)return;const t=new Cf("maxContentLength size of "+e.maxContentLength+" exceeded",Cf.ERR_BAD_RESPONSE,e,o);s.destroy(t),y(t)})),s.on("error",(function(t){h.destroyed||y(Cf.from(t,null,e,o))})),s.on("end",(function(){try{let e=1===t.length?t[0]:Buffer.concat(t);"arraybuffer"!==c&&(e=e.toString(p),p&&"utf8"!==p||(e=Rf.stripBOM(e))),u.data=e}catch(t){y(Cf.from(t,null,e,u.request,u))}Gg(_,y,u)}))}g.once("abort",(e=>{s.destroyed||(s.emit("error",e),s.destroy())}))})),g.once("abort",(e=>{y(e),h.destroy(e)})),h.on("error",(function(t){y(Cf.from(t,null,e,h))})),h.on("socket",(function(e){e.setKeepAlive(!0,6e4)})),e.timeout){const t=parseInt(e.timeout,10);if(isNaN(t))return void y(new Cf("error trying to parse `config.timeout` to int",Cf.ERR_BAD_OPTION_VALUE,e,h));h.setTimeout(t,(function(){if(m)return;let t=e.timeout?"timeout of "+e.timeout+"ms exceeded":"timeout exceeded";const i=e.transitional||Ig;e.timeoutErrorMessage&&(t=e.timeoutErrorMessage),y(new Cf(t,i.clarifyTimeoutError?Cf.ETIMEDOUT:Cf.ECONNABORTED,e,h)),x()}))}if(Rf.isStream(o)){let t=!1,i=!1;o.on("end",(()=>{t=!0})),o.once("error",(e=>{i=!0,h.destroy(e)})),o.on("close",(()=>{t||i||x(new Wg("Request stream has been aborted",e,h))})),o.pipe(h)}else h.end(o)}))},Uv=jg.isStandardBrowserEnv?{write:function(e,t,i,n,s,a){const r=[];r.push(e+"="+encodeURIComponent(t)),Rf.isNumber(i)&&r.push("expires="+new Date(i).toGMTString()),Rf.isString(n)&&r.push("path="+n),Rf.isString(s)&&r.push("domain="+s),!0===a&&r.push("secure"),document.cookie=r.join("; ")},read:function(e){const t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove:function(e){this.write(e,"",Date.now()-864e5)}}:{write:function(){},read:function(){return null},remove:function(){}},zv=jg.isStandardBrowserEnv?function(){const e=/(msie|trident)/i.test(navigator.userAgent),t=document.createElement("a");let i;function n(i){let n=i;return e&&(t.setAttribute("href",n),n=t.href),t.setAttribute("href",n),{href:t.href,protocol:t.protocol?t.protocol.replace(/:$/,""):"",host:t.host,search:t.search?t.search.replace(/^\?/,""):"",hash:t.hash?t.hash.replace(/^#/,""):"",hostname:t.hostname,port:t.port,pathname:"/"===t.pathname.charAt(0)?t.pathname:"/"+t.pathname}}return i=n(window.location.href),function(e){const t=Rf.isString(e)?n(e):e;return t.protocol===i.protocol&&t.host===i.host}}():function(){return!0};function qv(e,t){let i=0;const n=Tv(50,250);return s=>{const a=s.loaded,r=s.lengthComputable?s.total:void 0,o=a-i,c=n(o);i=a;const p={loaded:a,total:r,progress:r?a/r:void 0,bytes:o,rate:c||void 0,estimated:c&&r&&a<=r?(r-a)/c:void 0,event:s};p[t?"download":"upload"]=!0,e(p)}}var $v="undefined"!=typeof XMLHttpRequest&&function(e){return new Promise((function(t,i){let n=e.data;const s=qg.from(e.headers).normalize(),a=e.responseType;let r;function o(){e.cancelToken&&e.cancelToken.unsubscribe(r),e.signal&&e.signal.removeEventListener("abort",r)}Rf.isFormData(n)&&(jg.isStandardBrowserEnv||jg.isStandardBrowserWebWorkerEnv)&&s.setContentType(!1);let c=new XMLHttpRequest;if(e.auth){const t=e.auth.username||"",i=e.auth.password?unescape(encodeURIComponent(e.auth.password)):"";s.set("Authorization","Basic "+btoa(t+":"+i))}const p=Hg(e.baseURL,e.url);function d(){if(!c)return;const n=qg.from("getAllResponseHeaders"in c&&c.getAllResponseHeaders());Gg((function(e){t(e),o()}),(function(e){i(e),o()}),{data:a&&"text"!==a&&"json"!==a?c.response:c.responseText,status:c.status,statusText:c.statusText,headers:n,config:e,request:c}),c=null}if(c.open(e.method.toUpperCase(),Og(p,e.params,e.paramsSerializer),!0),c.timeout=e.timeout,"onloadend"in c?c.onloadend=d:c.onreadystatechange=function(){c&&4===c.readyState&&(0!==c.status||c.responseURL&&0===c.responseURL.indexOf("file:"))&&setTimeout(d)},c.onabort=function(){c&&(i(new Cf("Request aborted",Cf.ECONNABORTED,e,c)),c=null)},c.onerror=function(){i(new Cf("Network Error",Cf.ERR_NETWORK,e,c)),c=null},c.ontimeout=function(){let t=e.timeout?"timeout of "+e.timeout+"ms exceeded":"timeout exceeded";const n=e.transitional||Ig;e.timeoutErrorMessage&&(t=e.timeoutErrorMessage),i(new Cf(t,n.clarifyTimeoutError?Cf.ETIMEDOUT:Cf.ECONNABORTED,e,c)),c=null},jg.isStandardBrowserEnv){const t=(e.withCredentials||zv(p))&&e.xsrfCookieName&&Uv.read(e.xsrfCookieName);t&&s.set(e.xsrfHeaderName,t)}void 0===n&&s.setContentType(null),"setRequestHeader"in c&&Rf.forEach(s.toJSON(),(function(e,t){c.setRequestHeader(t,e)})),Rf.isUndefined(e.withCredentials)||(c.withCredentials=!!e.withCredentials),a&&"json"!==a&&(c.responseType=e.responseType),"function"==typeof e.onDownloadProgress&&c.addEventListener("progress",qv(e.onDownloadProgress,!0)),"function"==typeof e.onUploadProgress&&c.upload&&c.upload.addEventListener("progress",qv(e.onUploadProgress)),(e.cancelToken||e.signal)&&(r=t=>{c&&(i(!t||t.type?new Wg(null,e,c):t),c.abort(),c=null)},e.cancelToken&&e.cancelToken.subscribe(r),e.signal&&(e.signal.aborted?r():e.signal.addEventListener("abort",r)));const l=Cv(p);l&&-1===jg.protocols.indexOf(l)?i(new Cf("Unsupported protocol "+l+":",Cf.ERR_BAD_REQUEST,e)):c.send(n||null)}))};const Vv={http:Fv,xhr:$v};Rf.forEach(Vv,((e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch(e){}Object.defineProperty(e,"adapterName",{value:t})}}));var Wv=e=>{e=Rf.isArray(e)?e:[e];const{length:t}=e;let i,n;for(let s=0;s<t&&(i=e[s],!(n=Rf.isString(i)?Vv[i.toLowerCase()]:i));s++);if(!n){if(!1===n)throw new Cf(`Adapter ${i} is not supported by the environment`,"ERR_NOT_SUPPORT");throw new Error(Rf.hasOwnProp(Vv,i)?`Adapter '${i}' is not available in the build`:`Unknown adapter '${i}'`)}if(!Rf.isFunction(n))throw new TypeError("adapter is not a function");return n};function Gv(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new Wg(null,e)}function Hv(e){Gv(e),e.headers=qg.from(e.headers),e.data=$g.call(e,e.transformRequest),-1!==["post","put","patch"].indexOf(e.method)&&e.headers.setContentType("application/x-www-form-urlencoded",!1);return Wv(e.adapter||Ag.adapter)(e).then((function(t){return Gv(e),t.data=$g.call(e,e.transformResponse,t),t.headers=qg.from(t.headers),t}),(function(t){return Vg(t)||(Gv(e),t&&t.response&&(t.response.data=$g.call(e,e.transformResponse,t.response),t.response.headers=qg.from(t.response.headers))),Promise.reject(t)}))}const Kv=e=>e instanceof qg?e.toJSON():e;function Jv(e,t){t=t||{};const i={};function n(e,t,i){return Rf.isPlainObject(e)&&Rf.isPlainObject(t)?Rf.merge.call({caseless:i},e,t):Rf.isPlainObject(t)?Rf.merge({},t):Rf.isArray(t)?t.slice():t}function s(e,t,i){return Rf.isUndefined(t)?Rf.isUndefined(e)?void 0:n(void 0,e,i):n(e,t,i)}function a(e,t){if(!Rf.isUndefined(t))return n(void 0,t)}function r(e,t){return Rf.isUndefined(t)?Rf.isUndefined(e)?void 0:n(void 0,e):n(void 0,t)}function o(i,s,a){return a in t?n(i,s):a in e?n(void 0,i):void 0}const c={url:a,method:a,data:a,baseURL:r,transformRequest:r,transformResponse:r,paramsSerializer:r,timeout:r,timeoutMessage:r,withCredentials:r,adapter:r,responseType:r,xsrfCookieName:r,xsrfHeaderName:r,onUploadProgress:r,onDownloadProgress:r,decompress:r,maxContentLength:r,maxBodyLength:r,beforeRedirect:r,transport:r,httpAgent:r,httpsAgent:r,cancelToken:r,socketPath:r,responseEncoding:r,validateStatus:o,headers:(e,t)=>s(Kv(e),Kv(t),!0)};return Rf.forEach(Object.keys(e).concat(Object.keys(t)),(function(n){const a=c[n]||s,r=a(e[n],t[n],n);Rf.isUndefined(r)&&a!==o||(i[n]=r)})),i}const Qv={};["object","boolean","number","function","string","symbol"].forEach(((e,t)=>{Qv[e]=function(i){return typeof i===e||"a"+(t<1?"n ":" ")+e}}));const Yv={};Qv.transitional=function(e,t,i){function n(e,t){return"[Axios v1.2.3] Transitional option '"+e+"'"+t+(i?". "+i:"")}return(i,s,a)=>{if(!1===e)throw new Cf(n(s," has been removed"+(t?" in "+t:"")),Cf.ERR_DEPRECATED);return t&&!Yv[s]&&(Yv[s]=!0,console.warn(n(s," has been deprecated since v"+t+" and will be removed in the near future"))),!e||e(i,s,a)}};var Xv={assertOptions:function(e,t,i){if("object"!=typeof e)throw new Cf("options must be an object",Cf.ERR_BAD_OPTION_VALUE);const n=Object.keys(e);let s=n.length;for(;s-- >0;){const a=n[s],r=t[a];if(r){const t=e[a],i=void 0===t||r(t,a,e);if(!0!==i)throw new Cf("option "+a+" must be "+i,Cf.ERR_BAD_OPTION_VALUE)}else if(!0!==i)throw new Cf("Unknown option "+a,Cf.ERR_BAD_OPTION)}},validators:Qv};const Zv=Xv.validators;class eb{constructor(e){this.defaults=e,this.interceptors={request:new Dg,response:new Dg}}request(e,t){"string"==typeof e?(t=t||{}).url=e:t=e||{},t=Jv(this.defaults,t);const{transitional:i,paramsSerializer:n,headers:s}=t;let a;void 0!==i&&Xv.assertOptions(i,{silentJSONParsing:Zv.transitional(Zv.boolean),forcedJSONParsing:Zv.transitional(Zv.boolean),clarifyTimeoutError:Zv.transitional(Zv.boolean)},!1),void 0!==n&&Xv.assertOptions(n,{encode:Zv.function,serialize:Zv.function},!0),t.method=(t.method||this.defaults.method||"get").toLowerCase(),a=s&&Rf.merge(s.common,s[t.method]),a&&Rf.forEach(["delete","get","head","post","put","patch","common"],(e=>{delete s[e]})),t.headers=qg.concat(a,s);const r=[];let o=!0;this.interceptors.request.forEach((function(e){"function"==typeof e.runWhen&&!1===e.runWhen(t)||(o=o&&e.synchronous,r.unshift(e.fulfilled,e.rejected))}));const c=[];let p;this.interceptors.response.forEach((function(e){c.push(e.fulfilled,e.rejected)}));let d,l=0;if(!o){const e=[Hv.bind(this),void 0];for(e.unshift.apply(e,r),e.push.apply(e,c),d=e.length,p=Promise.resolve(t);l<d;)p=p.then(e[l++],e[l++]);return p}d=r.length;let u=t;for(l=0;l<d;){const e=r[l++],t=r[l++];try{u=e(u)}catch(e){t.call(this,e);break}}try{p=Hv.call(this,u)}catch(e){return Promise.reject(e)}for(l=0,d=c.length;l<d;)p=p.then(c[l++],c[l++]);return p}getUri(e){return Og(Hg((e=Jv(this.defaults,e)).baseURL,e.url),e.params,e.paramsSerializer)}}Rf.forEach(["delete","get","head","options"],(function(e){eb.prototype[e]=function(t,i){return this.request(Jv(i||{},{method:e,url:t,data:(i||{}).data}))}})),Rf.forEach(["post","put","patch"],(function(e){function t(t){return function(i,n,s){return this.request(Jv(s||{},{method:e,headers:t?{"Content-Type":"multipart/form-data"}:{},url:i,data:n}))}}eb.prototype[e]=t(),eb.prototype[e+"Form"]=t(!0)}));class tb{constructor(e){if("function"!=typeof e)throw new TypeError("executor must be a function.");let t;this.promise=new Promise((function(e){t=e}));const i=this;this.promise.then((e=>{if(!i._listeners)return;let t=i._listeners.length;for(;t-- >0;)i._listeners[t](e);i._listeners=null})),this.promise.then=e=>{let t;const n=new Promise((e=>{i.subscribe(e),t=e})).then(e);return n.cancel=function(){i.unsubscribe(t)},n},e((function(e,n,s){i.reason||(i.reason=new Wg(e,n,s),t(i.reason))}))}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){this.reason?e(this.reason):this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;const t=this._listeners.indexOf(e);-1!==t&&this._listeners.splice(t,1)}static source(){let e;return{token:new tb((function(t){e=t})),cancel:e}}}const ib={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(ib).forEach((([e,t])=>{ib[t]=e}));const nb=function e(t){const i=new eb(t),n=Kh(eb.prototype.request,i);return Rf.extend(n,eb.prototype,i,{allOwnKeys:!0}),Rf.extend(n,i,null,{allOwnKeys:!0}),n.create=function(i){return e(Jv(t,i))},n}(Ag);nb.Axios=eb,nb.CanceledError=Wg,nb.CancelToken=tb,nb.isCancel=Vg,nb.VERSION="1.2.3",nb.toFormData=Cg,nb.AxiosError=Cf,nb.Cancel=nb.CanceledError,nb.all=function(e){return Promise.all(e)},nb.spread=function(e){return function(t){return e.apply(null,t)}},nb.isAxiosError=function(e){return Rf.isObject(e)&&!0===e.isAxiosError},nb.mergeConfig=Jv,nb.AxiosHeaders=qg,nb.formToJSON=e=>Lg(Rf.isHTMLForm(e)?new FormData(e):e),nb.HttpStatusCode=ib,nb.default=nb;class sb{constructor(e={}){this.data=void 0===e.data?{}:e.data,this.headers=e.headers||{},this.status=e.status||200,this.statusText=e.statusText||"OK",this.url=e.url||null}}function ab(e,t){return u.ok(e,`${t} is required`),e}function rb(e,t){return u.ok("boolean"==typeof e,`${t}<boolean> is required`),e}function ob(e,t){return u.ok("number"==typeof e,`${t}<number> is required`),e}function cb(e,t){return u.ok("string"==typeof e,`${t}<string> is required`),e}function pb(e,t,i){const n=i||t.name[0].toLowerCase()+t.name.substring(1);return u.ok(e instanceof t,`${n}<${t.name}> is required`),e}function db(e,t="roomName"){return cb(e,t),u.equal("string"==typeof e&&e[0],"/",`${t} must begin with a '/'`),e}function lb(e,t){return u.ok(Array.isArray(e),`${t}<array> is required`),e}function ub(e,t){if(null==e||"object"!=typeof e||Array.isArray(e))throw new Error(`${t} must be a record. ${JSON.stringify(e)}`);return e}function mb(e,t,i){cb(t,"name"),function(e,t,i,n){cb(i,"name");const s=n||`${i} must be null or of type ${t}`;u.ok(null===e||typeof e===t,s)}(e,"string",t,i)}function hb({baseUrl:e,url:t}){return u.ok("string"==typeof t,"url<String> is required"),e?e+t:t}class fb{constructor({baseUrl:e}){cb(e,"baseUrl"),this._baseUrl=e}_requestAxios(e,t){const i=Object.assign({},t,{url:e,baseURL:this._baseUrl});return nb.request(i)}request(e,t){return cb(e,"url"),u.equal(e[0],"/",'url<String> only accepts relative URLs beginning with "/".'),u.ok(t,"options are required"),this._requestAxios(e,t).then((e=>{const{data:t,headers:i,status:n,statusText:s,config:a}=e,r=a&&a.url?hb({baseUrl:a.baseURL,url:a.url}):null;return new sb({data:t,headers:i,status:n,statusText:s,url:r})})).catch((e=>{const t=e.response;if(!t)throw new Error("Could not make the request.");const{data:i,headers:n,status:s,statusText:a,config:r}=t,o=r&&r.url?hb({baseUrl:r.baseURL,url:r.url}):null;return Promise.reject(new sb({data:i,headers:n,status:s,statusText:a,url:o}))}))}}class gb{constructor({httpClient:e}){u.ok(e,"httpClient is required"),this._httpClient=e}static dataToFormData(e){u.ok(e,"data is required");const t=new FormData;return Object.keys(e).forEach((i=>{const n=e[i];t.append(i,n)})),t}request(e,t={}){const i=Object.assign(t.headers||{},{"Content-Type":void 0});return this._httpClient.request(e,Object.assign(t,{headers:i,transformRequest:gb.dataToFormData}))}}let vb;vb="object"==typeof window?window.btoa||Hh:"object"==typeof global&&global.btoa||Hh;const bb=()=>Promise.resolve(null);class _b{constructor({httpClient:e,fetchDeviceCredentials:t}){this._httpClient=e,this._fetchDeviceCredentials=t}request(e,t){return this._fetchDeviceCredentials().then((i=>{const n=Object.assign({},t.headers,function(e){if(e&&e.credentials){const t=`${e.credentials.uuid}:${e.hmac}`;return{Authorization:`Basic ${vb(t)}`}}return{}}(i),{"X-Appearin-Device-Platform":"web"}),s=Object.assign({},t,{headers:n});return this._httpClient.request(e,s)}))}}class yb{constructor({baseUrl:e="https://api.appearin.net",fetchDeviceCredentials:t=bb}={}){cb(e,"baseUrl"),u.ok("function"==typeof t,"fetchDeviceCredentials<Function> is required"),this.authenticatedHttpClient=new _b({httpClient:new fb({baseUrl:e}),fetchDeviceCredentials:t}),this.authenticatedFormDataHttpClient=new gb({httpClient:this.authenticatedHttpClient})}request(e,t){return cb(e,"url"),u.equal(e[0],"/",'url<String> only accepts relative URLs beginning with "/".'),u.ok(t,"options are required"),this.authenticatedHttpClient.request(e,t)}requestMultipart(e,t){return cb(e,"url"),u.equal(e[0],"/",'url<String> only accepts relative URLs beginning with "/".'),u.ok(t,"options are required"),this.authenticatedFormDataHttpClient.request(e,t)}}function xb(e,t){return cb(ub(e,"data")[t],t)}const wb=(Sb=xb,(e,t)=>{const i=ub(e,"data")[t];return null==i?null:Sb(e,t)});var Sb;function Rb(e,t){const i=xb(e,t),n=new Date(i);if(isNaN(n.getTime()))throw new Error(`Invalid date for ${i}`);return n}function Cb(e,t,i){return function(e,t){return lb(ub(e,"data")[t],t)}(e,t).map((e=>i(e)))}class kb{constructor(e,t,i){this.credentials={uuid:e},this.hmac=t,this.userId=i}toJson(){return Object.assign({credentials:this.credentials,hmac:this.hmac},this.userId&&{userId:this.userId})}static fromJson(e){return new kb(xb(function(e,t){const i=ub(e,"data")[t];return void 0===i?null:i}(e,"credentials"),"uuid"),xb(e,"hmac"),wb(e,"userId")||void 0)}}class Tb{constructor({apiClient:e}){this._apiClient=pb(e,yb)}getCredentials(){return this._apiClient.request("/devices",{method:"post"}).then((({data:e})=>kb.fromJson(e))).catch((e=>{if(e.response&&404===e.response.status)return null;throw e}))}}class Pb{constructor(e,t){this._key=e,this._chromeStorage=t}loadOrDefault(e){return new Promise((t=>{this._chromeStorage.get(this._key,(i=>{t(i[this._key]||e)}))}))}save(e){return new Promise((t=>{this._chromeStorage.set({[this._key]:e},(()=>{t()}))}))}}class Eb{constructor(e,t){ab(t,"localStorage"),this._key=cb(e,"key"),this._localStorage=t}loadOrDefault(e){try{const t=this._localStorage.getItem(this._key);if(t)try{return Promise.resolve(JSON.parse(t))}catch(e){}return Promise.resolve(e)}catch(t){return console.warn("Error getting access to storage. Are cookies blocked?",t),Promise.resolve(e)}}save(e){try{return this._localStorage.setItem(this._key,JSON.stringify(e)),Promise.resolve()}catch(e){return console.warn("Error getting access to storage. Are cookies blocked?",e),Promise.reject(e)}}}let Ob;try{Ob=self.localStorage}catch(e){Ob={getItem:()=>{},key:()=>{},setItem:()=>{},removeItem:()=>{},hasOwnProperty:()=>{},length:0}}var Db=Ob;const Ib="credentials_saved";class jb extends d{constructor({deviceService:e,credentialsStore:t}){super(),this._deviceService=pb(e,Tb),this._credentialsStore=t}static create({baseUrl:e,storeName:t="CredentialsStorage",storeType:i="localStorage"}){const n=new Tb({apiClient:new yb({baseUrl:e})});let s=null;if("localStorage"===i)s=new Eb(t,Db);else{if("chromeStorage"!==i)throw new Error(`Unknown store type: ${i}`);s=new Pb(t,window.chrome.storage.local)}return new jb({deviceService:n,credentialsStore:s})}_fetchNewCredentialsFromApi(){const e=this._credentialsStore;return new Promise((t=>{const i=()=>{this._deviceService.getCredentials().then((i=>e.save(i?i.toJson():null).then((()=>t(i))))).catch((()=>{setTimeout(i,2e3)}))};i()}))}getCurrentCredentials(){return this._credentialsStore.loadOrDefault(null).then((e=>e?kb.fromJson(e):null))}getCredentials(){return this.credentialsPromise||(this.credentialsPromise=this.getCurrentCredentials().then((e=>e||this._fetchNewCredentialsFromApi()))),this.credentialsPromise}saveCredentials(e){return this.credentialsPromise=void 0,this._credentialsStore.save(e.toJson()).then((()=>(this.emit(Ib,e),e)))}setUserId(e){return this.getCurrentCredentials().then((t=>{t||console.error("Illegal state: no credentials to set user id for.");if(null===t||t.userId!==e)return this._credentialsStore.save(Object.assign({},null==t?void 0:t.toJson(),{userId:e}))})).then((()=>{}))}}const Lb=()=>Promise.resolve(void 0);class Mb{constructor({apiClient:e,fetchOrganization:t=Lb}){this._apiClient=pb(e,yb),u.ok("function"==typeof t,"fetchOrganization<Function> is required"),this._fetchOrganization=t,this._apiClient=e}_callRequestMethod(e,t,i){return cb(t,"url"),u.equal(t[0],"/",'url<String> only accepts relative URLs beginning with "/".'),u.ok(i,"options are required"),this._fetchOrganization().then((n=>{if(!n)return this._apiClient[e](t,i);const{organizationId:s}=n;return this._apiClient[e](`/organizations/${encodeURIComponent(s)}${t}`,i)}))}request(e,t){return this._callRequestMethod("request",e,t)}requestMultipart(e,t){return this._callRequestMethod("requestMultipart",e,t)}}class Ab{constructor({isExhausted:e,renewsAt:t,totalMinutesLimit:i,totalMinutesUsed:n}){this.isExhausted=e,this.renewsAt=t,this.totalMinutesLimit=i,this.totalMinutesUsed=n}static fromJson(e){return new Ab({isExhausted:rb(e.isExhausted,"isExhausted"),renewsAt:new Date(cb(e.renewsAt,"renewsAt")),totalMinutesLimit:ob(e.totalMinutesLimit,"totalMinutesLimit"),totalMinutesUsed:ob(e.totalMinutesUsed,"totalMinutesUsed")})}}class Nb{constructor({basePlanId:e,embeddedFreeTierStatus:t,isDeactivated:i,isOnTrial:n,onTrialUntil:s,trialStatus:a}){this.basePlanId=e,this.isDeactivated=i,this.isOnTrial=n,this.onTrialUntil=s||null,this.trialStatus=a||null,this.embeddedFreeTierStatus=t||null}static fromJson(e){return new Nb({basePlanId:"string"==typeof e.basePlanId?e.basePlanId:null,isDeactivated:rb(e.isDeactivated,"isDeactivated"),isOnTrial:rb(e.isOnTrial,"isOnTrial"),onTrialUntil:"string"==typeof e.onTrialUntil?new Date(e.onTrialUntil):null,trialStatus:"string"==typeof e.trialStatus?e.trialStatus:null,embeddedFreeTierStatus:e.embeddedFreeTierStatus?Ab.fromJson(e.embeddedFreeTierStatus):null})}}function Bb(e){return null!=e}function Fb(e={}){return{maxNumberOfInvitationsAndUsers:Bb(null==e?void 0:e.maxNumberOfInvitationsAndUsers)?Number(null==e?void 0:e.maxNumberOfInvitationsAndUsers):null,maxNumberOfClaimedRooms:Bb(null==e?void 0:e.maxNumberOfClaimedRooms)?Number(null==e?void 0:e.maxNumberOfClaimedRooms):null,maxRoomLimitPerOrganization:Bb(null==e?void 0:e.maxRoomLimitPerOrganization)?Number(null==e?void 0:e.maxRoomLimitPerOrganization):null,trialMinutesLimit:Bb(null==e?void 0:e.trialMinutesLimit)?Number(null==e?void 0:e.trialMinutesLimit):null,includedUnits:Bb(null==e?void 0:e.includedUnits)?Number(null==e?void 0:e.includedUnits):null}}class Ub{constructor(e){this.logoImageUrl=null,this.roomBackgroundImageUrl=null,this.roomBackgroundThumbnailUrl=null,this.roomKnockPageBackgroundImageUrl=null,this.roomKnockPageBackgroundThumbnailUrl=null,this.preferences=null,this.onboardingSurvey=null,this.type=null,pb(e,Object,"properties"),cb(e.organizationId,"organizationId"),cb(e.organizationName,"organizationName"),cb(e.subdomain,"subdomain"),pb(e.permissions,Object,"permissions"),pb(e.limits,Object,"limits"),this.organizationId=e.organizationId,this.organizationName=e.organizationName,this.subdomain=e.subdomain,this.permissions=e.permissions,this.limits=e.limits,this.account=e.account?new Nb(e.account):null,this.logoImageUrl=e.logoImageUrl,this.roomBackgroundImageUrl=e.roomBackgroundImageUrl,this.roomBackgroundThumbnailUrl=e.roomBackgroundThumbnailUrl,this.roomKnockPageBackgroundImageUrl=e.roomKnockPageBackgroundImageUrl,this.roomKnockPageBackgroundThumbnailUrl=e.roomKnockPageBackgroundThumbnailUrl,this.preferences=e.preferences,this.onboardingSurvey=e.onboardingSurvey,this.type=e.type}static fromJson(e){const t=pb(e,Object,"data"),i=(null==t?void 0:t.preferences)||{},n=(null==t?void 0:t.onboardingSurvey)||null,s=pb(t.permissions,Object,"permissions");return new Ub({organizationId:cb(t.organizationId,"organizationId"),organizationName:cb(t.organizationName,"organizationName"),subdomain:cb(t.subdomain,"subdomain"),permissions:s,limits:Fb(pb(t.limits,Object,"limits")),account:t.account?Nb.fromJson(t.account):null,logoImageUrl:"string"==typeof t.logoImageUrl?t.logoImageUrl:null,roomBackgroundImageUrl:"string"==typeof t.roomBackgroundImageUrl?t.roomBackgroundImageUrl:null,roomBackgroundThumbnailUrl:"string"==typeof t.roomBackgroundThumbnailUrl?t.roomBackgroundThumbnailUrl:null,roomKnockPageBackgroundImageUrl:"string"==typeof t.roomKnockPageBackgroundImageUrl?t.roomKnockPageBackgroundImageUrl:null,roomKnockPageBackgroundThumbnailUrl:"string"==typeof t.roomKnockPageBackgroundThumbnailUrl?t.roomKnockPageBackgroundThumbnailUrl:null,preferences:i,onboardingSurvey:n,type:"string"==typeof t.type?t.type:null})}}Ub.GLOBAL_ORGANIZATION_ID="1";class zb{constructor({apiClient:e}){this._apiClient=pb(e,yb)}createOrganization({organizationName:e,subdomain:t,owner:i}){const{displayName:n,consents:s}=i||{},a="email"in i?{value:i.email,verificationCode:cb(i.verificationCode,"owner.verificationCode")}:null,r="idToken"in i?i.idToken:null;if(cb(t,"subdomain"),cb(e,"organizationName"),cb(n,"owner.displayName"),u.ok(a||r,"owner.email or owner.idToken is required"),s){lb(s,"consents");for(const{consentRevisionId:e,action:t}of s)cb(e,"consentRevisionId"),mb(t,"action")}return this._apiClient.request("/organizations",{method:"POST",data:{organizationName:e,type:"private",subdomain:t,owner:Object.assign(Object.assign(Object.assign(Object.assign({},a&&{email:a}),r&&{idToken:r}),s&&{consents:s}),{displayName:n})}}).then((({data:e})=>xb(e,"organizationId")))}getOrganizationBySubdomain(e){return cb(e,"subdomain"),this._apiClient.request(`/organization-subdomains/${encodeURIComponent(e)}/?fields=permissions,account,onboardingSurvey`,{method:"GET"}).then((({data:e})=>Ub.fromJson(e))).catch((e=>{if(e instanceof sb){if(404===e.status)return null;throw new Error(e.statusText)}throw e}))}getOrganizationByOrganizationId(e){return cb(e,"organizationId"),this._apiClient.request(`/organizations/${encodeURIComponent(e)}?fields=permissions,account`,{method:"GET"}).then((({data:e})=>Ub.fromJson(e))).catch((e=>{if(e instanceof sb){if(404===e.status)return null;throw new Error(e.statusText)}throw e}))}getOrganizationsByContactPoint(e){const{code:t}=e,i="email"in e?e.email:null,n="phoneNumber"in e?e.phoneNumber:null;u.ok((i||n)&&!(i&&n),"either email or phoneNumber is required"),cb(t,"code");const s=i?{type:"email",value:i}:{type:"phoneNumber",value:n};return this._apiClient.request("/organization-queries",{method:"POST",data:{contactPoint:s,code:t}}).then((({data:e})=>Cb(e,"organizations",(e=>Ub.fromJson(e)))))}getOrganizationsByIdToken({idToken:e}){return cb(e,"idToken"),this._apiClient.request("/organization-queries",{method:"POST",data:{idToken:e}}).then((({data:e})=>Cb(e,"organizations",(e=>Ub.fromJson(Object.assign({permissions:{},limits:{}},ub(e,"organization")))))))}getOrganizationsByLoggedInUser(){return this._apiClient.request("/user/organizations",{method:"GET"}).then((({data:e})=>Cb(e,"organizations",(e=>Ub.fromJson(Object.assign({permissions:{},limits:{}},ub(e,"organization")))))))}getSubdomainAvailability(e){return cb(e,"subdomain"),this._apiClient.request(`/organization-subdomains/${encodeURIComponent(e)}/availability`,{method:"GET"}).then((({data:e})=>(pb(e,Object,"data"),{status:xb(e,"status")})))}updatePreferences({organizationId:e,preferences:t}){return ab(e,"organizationId"),ab(t,"preferences"),this._apiClient.request(`/organizations/${encodeURIComponent(e)}/preferences`,{method:"PATCH",data:t}).then((()=>{}))}deleteOrganization({organizationId:e}){return ab(e,"organizationId"),this._apiClient.request(`/organizations/${encodeURIComponent(e)}`,{method:"DELETE"}).then((()=>{}))}}class qb{constructor({organizationService:e,subdomain:t}){pb(e,zb),cb(t,"subdomain"),this._organizationService=e,this._subdomain=t,this._organizationPromise=null}initOrganization(){return this.fetchOrganization().then((()=>{}))}fetchOrganization(){return this._organizationPromise||(this._organizationPromise=this._organizationService.getOrganizationBySubdomain(this._subdomain)),this._organizationPromise}}class $b{constructor(e={}){u.ok(e instanceof Object,"properties<object> must be empty or an object"),this.isClaimed=!1,this.isBanned=!1,this.isLocked=!1,this.knockPage={backgroundImageUrl:null,backgroundThumbnailUrl:null},this.logoUrl=null,this.backgroundImageUrl=null,this.backgroundThumbnailUrl=null,this.type=null,this.legacyRoomType=null,this.mode=null,this.product=null,this.roomName=null,this.theme=null,this.preferences={},this.protectedPreferences={},this.publicProfile=null;const t={};Object.getOwnPropertyNames(e).forEach((i=>{-1!==Object.getOwnPropertyNames(this).indexOf(i)&&(t[i]=e[i])})),void 0!==e.ownerId&&(this.ownerId=e.ownerId),void 0!==e.meeting&&(this.meeting=e.meeting),Object.assign(this,t)}}class Vb{constructor({meetingId:e,roomName:t,roomUrl:i,startDate:n,endDate:s,hostRoomUrl:a,viewerRoomUrl:r}){cb(e,"meetingId"),cb(t,"roomName"),cb(i,"roomUrl"),pb(n,Date,"startDate"),pb(s,Date,"endDate"),this.meetingId=e,this.roomName=t,this.roomUrl=i,this.startDate=n,this.endDate=s,this.hostRoomUrl=a,this.viewerRoomUrl=r}static fromJson(e){return new Vb({meetingId:xb(e,"meetingId"),roomName:xb(e,"roomName"),roomUrl:xb(e,"roomUrl"),startDate:Rb(e,"startDate"),endDate:Rb(e,"endDate"),hostRoomUrl:wb(e,"hostRoomUrl"),viewerRoomUrl:wb(e,"viewerRoomUrl")})}}function Wb(e,t=""){return`/room/${encodeURIComponent(e.substring(1))}${t}`}class Gb{constructor({organizationApiClient:e}){this._organizationApiClient=pb(e,Mb)}getRooms({types:e,fields:t=[]}={}){return lb(e,"types"),lb(t,"fields"),this._organizationApiClient.request("/room",{method:"GET",params:{types:e.join(","),fields:t.join(","),includeOnlyLegacyRoomType:"false"}}).then((({data:e})=>e.rooms.map((e=>new $b(e)))))}getRoom({roomName:e,fields:t}){db(e);const i=encodeURIComponent(e.substring(1));return this._organizationApiClient.request(`/rooms/${i}`,{method:"GET",params:Object.assign({includeOnlyLegacyRoomType:"false"},t&&{fields:t.join(",")})}).then((({data:t})=>new $b(Object.assign({},t,Object.assign({roomName:e},t.meeting&&{meeting:Vb.fromJson(t.meeting)}))))).catch((t=>{if(404===t.status)return new $b({roomName:e,isClaimed:!1,mode:"normal",product:{categoryName:"personal_free"},type:"personal",legacyRoomType:"free"});if(400===t.status&&"Banned room"===t.data.error)return new $b({roomName:e,isBanned:!0});throw new Error(t.data?t.data.error:"Could not fetch room information")}))}claimRoom({roomName:e,type:t,mode:i,isLocked:n}){return db(e),cb(t,"type"),this._organizationApiClient.request("/room/claim",{method:"POST",data:Object.assign(Object.assign({roomName:e,type:t},"string"==typeof i&&{mode:i}),"boolean"==typeof n&&{isLocked:n})}).then((()=>{})).catch((e=>{throw new Error(e.data.error||"Failed to claim room")}))}unclaimRoom(e){db(e);const t=encodeURIComponent(e.substring(1));return this._organizationApiClient.request(`/room/${t}`,{method:"DELETE"}).then((()=>{}))}renameRoom({roomName:e,newRoomName:t}){db(e),cb(t,"newRoomName");const i=encodeURIComponent(e.substring(1));return this._organizationApiClient.request(`/room/${i}/roomName`,{method:"PUT",data:{newRoomName:t}}).then((()=>{}))}changeMode({roomName:e,mode:t}){db(e),cb(t,"mode");const i=encodeURIComponent(e.substring(1));return this._organizationApiClient.request(`/room/${i}/mode`,{method:"PUT",data:{mode:t}}).then((()=>{}))}updatePreferences({roomName:e,preferences:t}){db(e),pb(t,Object,"preferences");const i=encodeURIComponent(e.substring(1));return this._organizationApiClient.request(`/room/${i}/preferences`,{method:"PATCH",data:t}).then((()=>{}))}updateProtectedPreferences({roomName:e,preferences:t}){db(e),pb(t,Object,"preferences");const i=encodeURIComponent(e.substring(1));return this._organizationApiClient.request(`/room/${i}/protected-preferences`,{method:"PATCH",data:t}).then((()=>{}))}getRoomPermissions(e,{roomKey:t}={}){return db(e),this._organizationApiClient.request(Wb(e,"/permissions"),Object.assign({method:"GET"},t&&{headers:{"X-Whereby-Room-Key":t}})).then((e=>{const{permissions:t,limits:i}=e.data;return{permissions:t,limits:i}}))}getRoomMetrics({roomName:e,metrics:t,from:i,to:n}){return db(e),cb(t,"metrics"),this._organizationApiClient.request(Wb(e,"/metrics"),{method:"GET",params:{metrics:t,from:i,to:n}}).then((e=>e.data))}changeType({roomName:e,type:t}){db(e),function(e,t,i){if(ab(e,"value"),lb(t,"allowedValues"),!t.includes(e))throw new Error(`${i}<string> must be one of the following: ${t.join(", ")}`)}(t,["personal","personal_xl"],"type");const i=encodeURIComponent(e.substring(1));return this._organizationApiClient.request(`/room/${i}/type`,{method:"PUT",data:{type:t}}).then((()=>{}))}getForestSocialImage({roomName:e,count:t}){return db(e),ob(t,"count"),this._organizationApiClient.request(Wb(e,`/forest-social-image/${t}`),{method:"GET"}).then((e=>e.data.imageUrl))}}class Hb{constructor({displayName:e,id:t,stream:i,isAudioEnabled:n,isVideoEnabled:s}){this.isLocalParticipant=!1,this.displayName=e,this.id=t,this.stream=i,this.isAudioEnabled=n,this.isVideoEnabled=s}}class Kb extends Hb{constructor({displayName:e,id:t,newJoiner:i,streams:n,isAudioEnabled:s,isVideoEnabled:a}){super({displayName:e,id:t,isAudioEnabled:s,isVideoEnabled:a}),this.newJoiner=i,this.streams=n.map((e=>({id:e,state:i?"new_accept":"to_accept"})))}updateStreamState(e,t){const i=this.streams.find((t=>t.id===e));i&&(i.state=t)}}class Jb extends Hb{constructor({displayName:e,id:t,stream:i,isAudioEnabled:n,isVideoEnabled:s}){super({displayName:e,id:t,stream:i,isAudioEnabled:n,isVideoEnabled:s}),this.isLocalParticipant=!0}}const Qb=process.env.REACT_APP_API_BASE_URL||"https://api.whereby.dev",Yb=process.env.REACT_APP_SIGNAL_BASE_URL||"wss://signal.appearin.net",Xb=["recorder","streamer"];const Zb=()=>{},e_=EventTarget;class t_ extends e_{constructor(e,{displayName:t,localMedia:i,localMediaConstraints:n,logger:s,roomKey:a}){super(),this.localParticipant=null,this.remoteParticipants=[],this._ownsLocalMedia=!1,this.organizationId="",this.roomConnectionStatus="",this.roomUrl=new URL(e);const r=new URLSearchParams(this.roomUrl.search);this._roomKey=a||r.get("roomKey"),this.roomName=this.roomUrl.pathname,this.logger=s||{debug:Zb,error:Zb,log:Zb,warn:Zb},this.displayName=t,this.localMediaConstraints=n;const o=Gh({host:this.roomUrl.host});if(i)this.localMedia=i;else{if(!n)throw new Error("Missing constraints");this.localMedia=new fi(n),this._ownsLocalMedia=!0}this.credentialsService=jb.create({baseUrl:Qb}),this.apiClient=new yb({fetchDeviceCredentials:this.credentialsService.getCredentials.bind(this.credentialsService),baseUrl:Qb}),this.organizationService=new zb({apiClient:this.apiClient}),this.organizationServiceCache=new qb({organizationService:this.organizationService,subdomain:o.subdomain}),this.organizationApiClient=new Mb({apiClient:this.apiClient,fetchOrganization:()=>Zt(this,void 0,void 0,(function*(){return(yield this.organizationServiceCache.fetchOrganization())||void 0}))}),this.roomService=new Gb({organizationApiClient:this.organizationApiClient}),this.signalSocket=function(){const e=new URL(Yb),t=`${e.pathname.replace(/^\/$/,"")}/protocol/socket.io/v4`,i=e.origin;return new po(i,{autoConnect:!1,host:i,path:t,reconnectionDelay:5e3,reconnectionDelayMax:3e4,timeout:1e4,withCredentials:!0})}(),this.signalSocket.on("new_client",this._handleNewClient.bind(this)),this.signalSocket.on("chat_message",this._handleNewChatMessage.bind(this)),this.signalSocket.on("client_left",this._handleClientLeft.bind(this)),this.signalSocket.on("audio_enabled",this._handleClientAudioEnabled.bind(this)),this.signalSocket.on("video_enabled",this._handleClientVideoEnabled.bind(this)),this.signalSocket.on("client_metadata_received",this._handleClientMetadataReceived.bind(this)),this.signalSocket.on("knock_handled",this._handleKnockHandled.bind(this)),this.signalSocket.on("knocker_left",this._handleKnockerLeft.bind(this)),this.signalSocket.on("room_joined",this._handleRoomJoined.bind(this)),this.signalSocket.on("room_knocked",this._handleRoomKnocked.bind(this)),this.localMedia.addEventListener("camera_enabled",(e=>{const{enabled:t}=e.detail;this.signalSocket.emit("enable_video",{enabled:t})})),this.localMedia.addEventListener("microphone_enabled",(e=>{const{enabled:t}=e.detail;this.signalSocket.emit("enable_audio",{enabled:t})}));const c={getMediaConstraints:()=>({audio:this.localMedia.isMicrophoneEnabled(),video:this.localMedia.isCameraEnabled()}),deferrable:e=>!e};this.rtcManagerDispatcher=new Vh({emitter:{emit:this._handleRtcEvent.bind(this)},serverSocket:this.signalSocket,webrtcProvider:c,features:{lowDataModeEnabled:!1,sfuServerOverrideHost:void 0,turnServerOverrideHost:void 0,useOnlyTURN:void 0,vp9On:!1,h264On:!1,simulcastScreenshareOn:!1}})}get roomKey(){return this._roomKey}_handleNewChatMessage(e){this.dispatchEvent(new CustomEvent("chat_message",{detail:e}))}_handleNewClient({client:e}){if(Xb.includes(e.role.roleName))return;const t=new Kb(Object.assign(Object.assign({},e),{newJoiner:!0}));this.remoteParticipants=[...this.remoteParticipants,t],this._handleAcceptStreams([t]),this.dispatchEvent(new CustomEvent("participant_joined",{detail:{remoteParticipant:t}}))}_handleClientLeft({clientId:e}){const t=this.remoteParticipants.find((t=>t.id===e));this.remoteParticipants=this.remoteParticipants.filter((t=>t.id!==e)),t&&this.dispatchEvent(new CustomEvent("participant_left",{detail:{participantId:t.id}}))}_handleClientAudioEnabled({clientId:e,isAudioEnabled:t}){const i=this.remoteParticipants.find((t=>t.id===e));i&&this.dispatchEvent(new CustomEvent("participant_audio_enabled",{detail:{participantId:i.id,isAudioEnabled:t}}))}_handleClientVideoEnabled({clientId:e,isVideoEnabled:t}){const i=this.remoteParticipants.find((t=>t.id===e));i&&this.dispatchEvent(new CustomEvent("participant_video_enabled",{detail:{participantId:i.id,isVideoEnabled:t}}))}_handleClientMetadataReceived({payload:{clientId:e,displayName:t}}){const i=this.remoteParticipants.find((t=>t.id===e));i&&this.dispatchEvent(new CustomEvent("participant_metadata_changed",{detail:{participantId:i.id,displayName:t}}))}_handleKnockHandled(e){const{resolution:t}=e;"accepted"===t?(this.roomConnectionStatus="accepted",this._roomKey=e.metadata.roomKey,this._joinRoom()):"rejected"===t&&(this.roomConnectionStatus="rejected",this.dispatchEvent(new CustomEvent("room_connection_status_changed",{detail:{roomConnectionStatus:this.roomConnectionStatus}})))}_handleKnockerLeft(e){const{clientId:t}=e;this.dispatchEvent(new CustomEvent("waiting_participant_left",{detail:{participantId:t}}))}_handleRoomJoined(e){const{error:t,isLocked:i,room:n,selfId:s}=e;if("room_locked"===t&&i)return this.roomConnectionStatus="room_locked",void this.dispatchEvent(new CustomEvent("room_connection_status_changed",{detail:{roomConnectionStatus:this.roomConnectionStatus}}));if(n){const{clients:e,knockers:t}=n,i=e.find((e=>e.id===s));if(!i)throw new Error("Missing local client");this.localParticipant=new Jb(Object.assign(Object.assign({},i),{stream:this.localMedia.stream||void 0})),this.remoteParticipants=e.filter((e=>e.id!==s)).map((e=>new Kb(Object.assign(Object.assign({},e),{newJoiner:!1})))),this.roomConnectionStatus="connected",this.dispatchEvent(new CustomEvent("room_joined",{detail:{localParticipant:this.localParticipant,remoteParticipants:this.remoteParticipants,waitingParticipants:t.map((e=>({id:e.clientId,displayName:e.displayName})))}}))}}_handleRoomKnocked(e){const{clientId:t,displayName:i}=e;this.dispatchEvent(new CustomEvent("waiting_participant_joined",{detail:{participantId:t,displayName:i}}))}_handleRtcEvent(e,t){return"rtc_manager_created"===e?this._handleRtcManagerCreated(t):"stream_added"===e?this._handleStreamAdded(t):void this.logger.log(`Unhandled RTC event ${e}`)}_handleRtcManagerCreated({rtcManager:e}){var t;this.rtcManager=e,this.localMedia.addRtcManager(e),this.localMedia.stream&&(null===(t=this.rtcManager)||void 0===t||t.addNewStream("0",this.localMedia.stream,!this.localMedia.isMicrophoneEnabled(),!this.localMedia.isCameraEnabled())),this.remoteParticipants.length&&this._handleAcceptStreams(this.remoteParticipants)}_handleAcceptStreams(e){var t,i;if(!this.rtcManager)return void this.logger.log("Unable to accept streams, no rtc manager");const n=null===(i=(t=this.rtcManager).shouldAcceptStreamsFromBothSides)||void 0===i?void 0:i.call(t);e.forEach((e=>{const{id:t,streams:i,newJoiner:s}=e;i.forEach((i=>{var a,r;const{id:o,state:c}=i;let p;if("done_accept"!==c&&(p=(s&&"0"===o?"new":"to")+"_accept"),p){if("to_accept"===p||"new_accept"===p&&n||"old_accept"===p&&!n)this.logger.log(`Accepting stream ${o} from ${t}`),null===(a=this.rtcManager)||void 0===a||a.acceptNewStream({streamId:"0"===o?t:o,clientId:t,shouldAddLocalVideo:"0"===o,activeBreakout:false});else if("new_accept"===p||"old_accept"===p);else if("to_unaccept"===p)this.logger.log(`Disconnecting stream ${o} from ${t}`),null===(r=this.rtcManager)||void 0===r||r.disconnect("0"===o?t:o,false);else if("done_accept"!==p)return void this.logger.warn(`Stream state not handled: ${p} for ${t}-${o}`);e.updateStreamState(o,c.replace(/to_|new_|old_/,"done_"))}}))}))}_handleStreamAdded({clientId:e,stream:t,streamId:i}){this.remoteParticipants.find((t=>t.id===e))?this.dispatchEvent(new CustomEvent("participant_stream_added",{detail:{participantId:e,stream:t,streamId:i}})):this.logger.log("WARN: Could not find participant for incoming stream")}_joinRoom(){this.signalSocket.emit("join_room",{avatarUrl:null,config:{isAudioEnabled:this.localMedia.isMicrophoneEnabled(),isVideoEnabled:this.localMedia.isCameraEnabled()},deviceCapabilities:{canScreenshare:!0},displayName:this.displayName,isCoLocated:!1,isDevicePermissionDenied:!1,kickFromOtherRooms:!1,organizationId:this.organizationId,roomKey:this.roomKey,roomName:this.roomName,selfId:"",userAgent:`browser-sdk:${r_}`})}join(){return Zt(this,void 0,void 0,(function*(){if(["connected","connecting"].includes(this.roomConnectionStatus))return void console.warn(`Trying to join when room state is already ${this.roomConnectionStatus}`);this.logger.log("Joining room"),this.signalSocket.connect(),this.roomConnectionStatus="connecting",this.dispatchEvent(new CustomEvent("room_connection_status_changed",{detail:{roomConnectionStatus:this.roomConnectionStatus}}));const e=yield this.organizationServiceCache.fetchOrganization();if(!e)throw new Error("Invalid room url");this.organizationId=e.organizationId,this._ownsLocalMedia&&(yield this.localMedia.start());const t=yield this.credentialsService.getCredentials();this.logger.log("Connected to signal socket"),this.signalSocket.emit("identify_device",{deviceCredentials:t}),this.signalSocket.once("device_identified",(()=>{this._joinRoom()}))}))}knock(){this.roomConnectionStatus="knocking",this.dispatchEvent(new CustomEvent("room_connection_status_changed",{detail:{roomConnectionStatus:this.roomConnectionStatus}})),this.signalSocket.emit("knock_room",{displayName:this.displayName,imageUrl:null,kickFromOtherRooms:!0,liveVideo:!1,organizationId:this.organizationId,roomKey:this._roomKey,roomName:this.roomName})}leave(){this.roomConnectionStatus="disconnecting",this._ownsLocalMedia&&this.localMedia.stop(),this.rtcManager&&(this.localMedia.removeRtcManager(this.rtcManager),this.rtcManager.disconnectAll(),this.rtcManager=void 0),this.signalSocket&&(this.signalSocket.emit("leave_room"),this.signalSocket.disconnect(),this.roomConnectionStatus="disconnected")}sendChatMessage(e){this.signalSocket.emit("chat_message",{text:e})}setDisplayName(e){this.signalSocket.emit("send_client_metadata",{type:"UserData",payload:{displayName:e}})}acceptWaitingParticipant(e){this.signalSocket.emit("handle_knock",{action:"accept",clientId:e,response:{}})}rejectWaitingParticipant(e){this.signalSocket.emit("handle_knock",{action:"reject",clientId:e,response:{}})}}const i_={chatMessages:[],roomConnectionStatus:"",isJoining:!1,joinError:null,mostRecentChatMessage:null,remoteParticipants:[],waitingParticipants:[]};function n_(e,t,i){const n=e.find((e=>e.id===t));if(!n)return e;const s=e.indexOf(n);return[...e.slice(0,s),Object.assign(Object.assign({},n),i),...e.slice(s+1)]}function s_(e,t){switch(t.type){case"CHAT_MESSAGE":return Object.assign(Object.assign({},e),{chatMessages:[...e.chatMessages,t.payload],mostRecentChatMessage:t.payload});case"ROOM_JOINED":return Object.assign(Object.assign({},e),{localParticipant:t.payload.localParticipant,remoteParticipants:t.payload.remoteParticipants,waitingParticipants:t.payload.waitingParticipants,roomConnectionStatus:"connected"});case"ROOM_CONNECTION_STATUS_CHANGED":return Object.assign(Object.assign({},e),{roomConnectionStatus:t.payload.roomConnectionStatus});case"PARTICIPANT_AUDIO_ENABLED":return Object.assign(Object.assign({},e),{remoteParticipants:n_(e.remoteParticipants,t.payload.participantId,{isAudioEnabled:t.payload.isAudioEnabled})});case"PARTICIPANT_JOINED":return Object.assign(Object.assign({},e),{remoteParticipants:[...e.remoteParticipants,t.payload.paritipant]});case"PARTICIPANT_LEFT":return Object.assign(Object.assign({},e),{remoteParticipants:[...e.remoteParticipants.filter((e=>e.id!==t.payload.participantId))]});case"PARTICIPANT_STREAM_ADDED":return Object.assign(Object.assign({},e),{remoteParticipants:n_(e.remoteParticipants,t.payload.participantId,{stream:t.payload.stream})});case"PARTICIPANT_VIDEO_ENABLED":return Object.assign(Object.assign({},e),{remoteParticipants:n_(e.remoteParticipants,t.payload.participantId,{isVideoEnabled:t.payload.isVideoEnabled})});case"PARTICIPANT_METADATA_CHANGED":return Object.assign(Object.assign({},e),{remoteParticipants:[...e.remoteParticipants.map((e=>e.id===t.payload.participantId?Object.assign(Object.assign({},e),{displayName:t.payload.displayName}):e))]});case"LOCAL_CLIENT_DISPLAY_NAME_CHANGED":return e.localParticipant?Object.assign(Object.assign({},e),{localParticipant:Object.assign(Object.assign({},e.localParticipant),{displayName:t.payload.displayName})}):e;case"WAITING_PARTICIPANT_JOINED":return Object.assign(Object.assign({},e),{waitingParticipants:[...e.waitingParticipants,{id:t.payload.participantId,displayName:t.payload.displayName}]});case"WAITING_PARTICIPANT_LEFT":return Object.assign(Object.assign({},e),{waitingParticipants:e.waitingParticipants.filter((e=>e.id!==t.payload.participantId))});default:throw e}}function a_(e,t){const[i]=si.useState((()=>{var i;return new t_(e,Object.assign(Object.assign({},t),{localMedia:(null===(i=null==t?void 0:t.localMedia)||void 0===i?void 0:i._ref)||void 0}))})),[n,s]=si.useReducer(s_,i_);return si.useEffect((()=>(i.addEventListener("chat_message",(e=>{const t=e.detail;s({type:"CHAT_MESSAGE",payload:t})})),i.addEventListener("participant_audio_enabled",(e=>{const{participantId:t,isAudioEnabled:i}=e.detail;s({type:"PARTICIPANT_AUDIO_ENABLED",payload:{participantId:t,isAudioEnabled:i}})})),i.addEventListener("participant_joined",(e=>{const{remoteParticipant:t}=e.detail;s({type:"PARTICIPANT_JOINED",payload:{paritipant:t}})})),i.addEventListener("participant_left",(e=>{const{participantId:t}=e.detail;s({type:"PARTICIPANT_LEFT",payload:{participantId:t}})})),i.addEventListener("participant_stream_added",(e=>{const{participantId:t,stream:i}=e.detail;s({type:"PARTICIPANT_STREAM_ADDED",payload:{participantId:t,stream:i}})})),i.addEventListener("room_connection_status_changed",(e=>{const{roomConnectionStatus:t}=e.detail;s({type:"ROOM_CONNECTION_STATUS_CHANGED",payload:{roomConnectionStatus:t}})})),i.addEventListener("room_joined",(e=>{const{localParticipant:t,remoteParticipants:i,waitingParticipants:n}=e.detail;s({type:"ROOM_JOINED",payload:{localParticipant:t,remoteParticipants:i,waitingParticipants:n}})})),i.addEventListener("participant_video_enabled",(e=>{const{participantId:t,isVideoEnabled:i}=e.detail;s({type:"PARTICIPANT_VIDEO_ENABLED",payload:{participantId:t,isVideoEnabled:i}})})),i.addEventListener("participant_metadata_changed",(e=>{const{participantId:t,displayName:i}=e.detail;s({type:"PARTICIPANT_METADATA_CHANGED",payload:{participantId:t,displayName:i}})})),i.addEventListener("waiting_participant_joined",(e=>{const{participantId:t,displayName:i}=e.detail;s({type:"WAITING_PARTICIPANT_JOINED",payload:{participantId:t,displayName:i}})})),i.addEventListener("waiting_participant_left",(e=>{const{participantId:t}=e.detail;s({type:"WAITING_PARTICIPANT_LEFT",payload:{participantId:t}})})),i.join(),()=>{i.leave()})),[]),{state:n,actions:{knock:()=>{i.knock()},sendChatMessage:e=>{i.sendChatMessage(e)},setDisplayName:e=>{i.setDisplayName(e),s({type:"LOCAL_CLIENT_DISPLAY_NAME_CHANGED",payload:{displayName:e}})},toggleCamera:e=>{i.localMedia.toggleCameraEnabled(e)},toggleMicrophone:e=>{i.localMedia.toggleMichrophoneEnabled(e)},acceptWaitingParticipant:e=>{i.acceptWaitingParticipant(e)},rejectWaitingParticipant:e=>{i.rejectWaitingParticipant(e)}},components:{VideoView:mi},_ref:i}}const r_="2.0.0-alpha12";export{mi as VideoView,r_ as sdkVersion,bi as useLocalMedia,a_ as useRoomConnection};
43
+ function(e){var t=Nf,i=g.extname,n=/^\s*([^;\s]*)(?:;|\s|$)/,s=/^text\//i;function a(e){if(!e||"string"!=typeof e)return!1;var i=n.exec(e),a=i&&t[i[1].toLowerCase()];return a&&a.charset?a.charset:!(!i||!s.test(i[1]))&&"UTF-8"}e.charset=a,e.charsets={lookup:a},e.contentType=function(t){if(!t||"string"!=typeof t)return!1;var i=-1===t.indexOf("/")?e.lookup(t):t;if(!i)return!1;if(-1===i.indexOf("charset")){var n=e.charset(i);n&&(i+="; charset="+n.toLowerCase())}return i},e.extension=function(t){if(!t||"string"!=typeof t)return!1;var i=n.exec(t),s=i&&e.extensions[i[1].toLowerCase()];if(!s||!s.length)return!1;return s[0]},e.extensions=Object.create(null),e.lookup=function(t){if(!t||"string"!=typeof t)return!1;var n=i("x."+t).toLowerCase().substr(1);if(!n)return!1;return e.types[n]||!1},e.types=Object.create(null),function(e,i){var n=["nginx","apache",void 0,"iana"];Object.keys(t).forEach((function(s){var a=t[s],r=a.extensions;if(r&&r.length){e[s]=r;for(var o=0;o<r.length;o++){var c=r[o];if(i[c]){var p=n.indexOf(t[i[c]].source),d=n.indexOf(a.source);if("application/octet-stream"!==i[c]&&(p>d||p===d&&"application/"===i[c].substr(0,12)))continue}i[c]=s}}}))}(e.extensions,e.types)}(Af);var Ff=function(e){var t="function"==typeof setImmediate?setImmediate:"object"==typeof process&&"function"==typeof process.nextTick?process.nextTick:null;t?t(e):setTimeout(e,0)};var Uf=Ff,zf=function(e){var t=!1;return Uf((function(){t=!0})),function(i,n){t?e(i,n):Uf((function(){e(i,n)}))}};var qf=function(e){Object.keys(e.jobs).forEach($f.bind(e)),e.jobs={}};function $f(e){"function"==typeof this.jobs[e]&&this.jobs[e]()}var Vf=zf,Wf=qf,Gf=function(e,t,i,n){var s=i.keyedList?i.keyedList[i.index]:i.index;i.jobs[s]=function(e,t,i,n){var s;s=2==e.length?e(i,Vf(n)):e(i,t,Vf(n));return s}(t,s,e[s],(function(e,t){s in i.jobs&&(delete i.jobs[s],e?Wf(i):i.results[s]=t,n(e,i.results))}))};var Hf=function(e,t){var i=!Array.isArray(e),n={index:0,keyedList:i||t?Object.keys(e):null,jobs:{},results:i?{}:[],size:i?Object.keys(e).length:e.length};t&&n.keyedList.sort(i?t:function(i,n){return t(e[i],e[n])});return n};var Kf=qf,Jf=zf,Qf=function(e){if(!Object.keys(this.jobs).length)return;this.index=this.size,Kf(this),Jf(e)(null,this.results)};var Yf=Gf,Xf=Hf,Zf=Qf,eg=function(e,t,i){var n=Xf(e);for(;n.index<(n.keyedList||e).length;)Yf(e,t,n,(function(e,t){e?i(e,t):0!==Object.keys(n.jobs).length||i(null,n.results)})),n.index++;return Zf.bind(n,i)};var tg={},ig=Gf,ng=Hf,sg=Qf;function ag(e,t){return e<t?-1:e>t?1:0}({get exports(){return tg},set exports(e){tg=e}}).exports=function(e,t,i,n){var s=ng(e,i);return ig(e,t,s,(function i(a,r){a?n(a,r):(s.index++,s.index<(s.keyedList||e).length?ig(e,t,s,i):n(null,s.results))})),sg.bind(s,n)},tg.ascending=ag,tg.descending=function(e,t){return-1*ag(e,t)};var rg=tg;var og={parallel:eg,serial:function(e,t,i){return rg(e,t,null,i)},serialOrdered:tg},cg=Lf,pg=h,dg=g,lg=n,ug=s,mg=t.parse,hg=e,fg=a.Stream,gg=Af,vg=og,bg=function(e,t){return Object.keys(t).forEach((function(i){e[i]=e[i]||t[i]})),e},_g=yg;function yg(e){if(!(this instanceof yg))return new yg(e);for(var t in this._overheadLength=0,this._valueLength=0,this._valuesToMeasure=[],cg.call(this),e=e||{})this[t]=e[t]}function xg(e){return Rf.isPlainObject(e)||Rf.isArray(e)}function wg(e){return Rf.endsWith(e,"[]")?e.slice(0,-2):e}function Sg(e,t,i){return e?e.concat(t).map((function(e,t){return e=wg(e),!i&&t?"["+e+"]":e})).join(i?".":""):t}pg.inherits(yg,cg),yg.LINE_BREAK="\r\n",yg.DEFAULT_CONTENT_TYPE="application/octet-stream",yg.prototype.append=function(e,t,i){"string"==typeof(i=i||{})&&(i={filename:i});var n=cg.prototype.append.bind(this);if("number"==typeof t&&(t=""+t),pg.isArray(t))this._error(new Error("Arrays are not supported."));else{var s=this._multiPartHeader(e,t,i),a=this._multiPartFooter();n(s),n(t),n(a),this._trackLength(s,t,i)}},yg.prototype._trackLength=function(e,t,i){var n=0;null!=i.knownLength?n+=+i.knownLength:Buffer.isBuffer(t)?n=t.length:"string"==typeof t&&(n=Buffer.byteLength(t)),this._valueLength+=n,this._overheadLength+=Buffer.byteLength(e)+yg.LINE_BREAK.length,t&&(t.path||t.readable&&t.hasOwnProperty("httpVersion")||t instanceof fg)&&(i.knownLength||this._valuesToMeasure.push(t))},yg.prototype._lengthRetriever=function(e,t){e.hasOwnProperty("fd")?null!=e.end&&e.end!=1/0&&null!=e.start?t(null,e.end+1-(e.start?e.start:0)):hg.stat(e.path,(function(i,n){var s;i?t(i):(s=n.size-(e.start?e.start:0),t(null,s))})):e.hasOwnProperty("httpVersion")?t(null,+e.headers["content-length"]):e.hasOwnProperty("httpModule")?(e.on("response",(function(i){e.pause(),t(null,+i.headers["content-length"])})),e.resume()):t("Unknown stream")},yg.prototype._multiPartHeader=function(e,t,i){if("string"==typeof i.header)return i.header;var n,s=this._getContentDisposition(t,i),a=this._getContentType(t,i),r="",o={"Content-Disposition":["form-data",'name="'+e+'"'].concat(s||[]),"Content-Type":[].concat(a||[])};for(var c in"object"==typeof i.header&&bg(o,i.header),o)o.hasOwnProperty(c)&&null!=(n=o[c])&&(Array.isArray(n)||(n=[n]),n.length&&(r+=c+": "+n.join("; ")+yg.LINE_BREAK));return"--"+this.getBoundary()+yg.LINE_BREAK+r+yg.LINE_BREAK},yg.prototype._getContentDisposition=function(e,t){var i,n;return"string"==typeof t.filepath?i=dg.normalize(t.filepath).replace(/\\/g,"/"):t.filename||e.name||e.path?i=dg.basename(t.filename||e.name||e.path):e.readable&&e.hasOwnProperty("httpVersion")&&(i=dg.basename(e.client._httpMessage.path||"")),i&&(n='filename="'+i+'"'),n},yg.prototype._getContentType=function(e,t){var i=t.contentType;return!i&&e.name&&(i=gg.lookup(e.name)),!i&&e.path&&(i=gg.lookup(e.path)),!i&&e.readable&&e.hasOwnProperty("httpVersion")&&(i=e.headers["content-type"]),i||!t.filepath&&!t.filename||(i=gg.lookup(t.filepath||t.filename)),i||"object"!=typeof e||(i=yg.DEFAULT_CONTENT_TYPE),i},yg.prototype._multiPartFooter=function(){return function(e){var t=yg.LINE_BREAK;0===this._streams.length&&(t+=this._lastBoundary()),e(t)}.bind(this)},yg.prototype._lastBoundary=function(){return"--"+this.getBoundary()+"--"+yg.LINE_BREAK},yg.prototype.getHeaders=function(e){var t,i={"content-type":"multipart/form-data; boundary="+this.getBoundary()};for(t in e)e.hasOwnProperty(t)&&(i[t.toLowerCase()]=e[t]);return i},yg.prototype.setBoundary=function(e){this._boundary=e},yg.prototype.getBoundary=function(){return this._boundary||this._generateBoundary(),this._boundary},yg.prototype.getBuffer=function(){for(var e=new Buffer.alloc(0),t=this.getBoundary(),i=0,n=this._streams.length;i<n;i++)"function"!=typeof this._streams[i]&&(e=Buffer.isBuffer(this._streams[i])?Buffer.concat([e,this._streams[i]]):Buffer.concat([e,Buffer.from(this._streams[i])]),"string"==typeof this._streams[i]&&this._streams[i].substring(2,t.length+2)===t||(e=Buffer.concat([e,Buffer.from(yg.LINE_BREAK)])));return Buffer.concat([e,Buffer.from(this._lastBoundary())])},yg.prototype._generateBoundary=function(){for(var e="--------------------------",t=0;t<24;t++)e+=Math.floor(10*Math.random()).toString(16);this._boundary=e},yg.prototype.getLengthSync=function(){var e=this._overheadLength+this._valueLength;return this._streams.length&&(e+=this._lastBoundary().length),this.hasKnownLength()||this._error(new Error("Cannot calculate proper length in synchronous way.")),e},yg.prototype.hasKnownLength=function(){var e=!0;return this._valuesToMeasure.length&&(e=!1),e},yg.prototype.getLength=function(e){var t=this._overheadLength+this._valueLength;this._streams.length&&(t+=this._lastBoundary().length),this._valuesToMeasure.length?vg.parallel(this._valuesToMeasure,this._lengthRetriever,(function(i,n){i?e(i):(n.forEach((function(e){t+=e})),e(null,t))})):process.nextTick(e.bind(this,null,t))},yg.prototype.submit=function(e,t){var i,n,s={method:"post"};return"string"==typeof e?(e=mg(e),n=bg({port:e.port,path:e.pathname,host:e.hostname,protocol:e.protocol},s)):(n=bg(e,s)).port||(n.port="https:"==n.protocol?443:80),n.headers=this.getHeaders(e.headers),i="https:"==n.protocol?ug.request(n):lg.request(n),this.getLength(function(e,n){if(e&&"Unknown stream"!==e)this._error(e);else if(n&&i.setHeader("Content-Length",n),this.pipe(i),t){var s,a=function(e,n){return i.removeListener("error",a),i.removeListener("response",s),t.call(this,e,n)};s=a.bind(this,null),i.on("error",a),i.on("response",s)}}.bind(this)),i},yg.prototype._error=function(e){this.error||(this.error=e,this.pause(),this.emit("error",e))},yg.prototype.toString=function(){return"[object FormData]"};const Rg=Rf.toFlatObject(Rf,{},null,(function(e){return/^is[A-Z]/.test(e)}));function Cg(e,t,i){if(!Rf.isObject(e))throw new TypeError("target must be an object");t=t||new(_g||FormData);const n=(i=Rf.toFlatObject(i,{metaTokens:!0,dots:!1,indexes:!1},!1,(function(e,t){return!Rf.isUndefined(t[e])}))).metaTokens,s=i.visitor||d,a=i.dots,r=i.indexes,o=(i.Blob||"undefined"!=typeof Blob&&Blob)&&((c=t)&&Rf.isFunction(c.append)&&"FormData"===c[Symbol.toStringTag]&&c[Symbol.iterator]);var c;if(!Rf.isFunction(s))throw new TypeError("visitor must be a function");function p(e){if(null===e)return"";if(Rf.isDate(e))return e.toISOString();if(!o&&Rf.isBlob(e))throw new Cf("Blob is not supported. Use a Buffer instead.");return Rf.isArrayBuffer(e)||Rf.isTypedArray(e)?o&&"function"==typeof Blob?new Blob([e]):Buffer.from(e):e}function d(e,i,s){let o=e;if(e&&!s&&"object"==typeof e)if(Rf.endsWith(i,"{}"))i=n?i:i.slice(0,-2),e=JSON.stringify(e);else if(Rf.isArray(e)&&function(e){return Rf.isArray(e)&&!e.some(xg)}(e)||Rf.isFileList(e)||Rf.endsWith(i,"[]")&&(o=Rf.toArray(e)))return i=wg(i),o.forEach((function(e,n){!Rf.isUndefined(e)&&null!==e&&t.append(!0===r?Sg([i],n,a):null===r?i:i+"[]",p(e))})),!1;return!!xg(e)||(t.append(Sg(s,i,a),p(e)),!1)}const l=[],u=Object.assign(Rg,{defaultVisitor:d,convertValue:p,isVisitable:xg});if(!Rf.isObject(e))throw new TypeError("data must be an object");return function e(i,n){if(!Rf.isUndefined(i)){if(-1!==l.indexOf(i))throw Error("Circular reference detected in "+n.join("."));l.push(i),Rf.forEach(i,(function(i,a){!0===(!(Rf.isUndefined(i)||null===i)&&s.call(t,i,Rf.isString(a)?a.trim():a,n,u))&&e(i,n?n.concat(a):[a])})),l.pop()}}(e),t}function kg(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,(function(e){return t[e]}))}function Tg(e,t){this._pairs=[],e&&Cg(e,this,t)}const Pg=Tg.prototype;function Eg(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function Og(e,t,i){if(!t)return e;const n=i&&i.encode||Eg,s=i&&i.serialize;let a;if(a=s?s(t,i):Rf.isURLSearchParams(t)?t.toString():new Tg(t,i).toString(n),a){const t=e.indexOf("#");-1!==t&&(e=e.slice(0,t)),e+=(-1===e.indexOf("?")?"?":"&")+a}return e}Pg.append=function(e,t){this._pairs.push([e,t])},Pg.toString=function(e){const t=e?function(t){return e.call(this,t,kg)}:kg;return this._pairs.map((function(e){return t(e[0])+"="+t(e[1])}),"").join("&")};class Dg{constructor(){this.handlers=[]}use(e,t,i){return this.handlers.push({fulfilled:e,rejected:t,synchronous:!!i&&i.synchronous,runWhen:i?i.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(e){Rf.forEach(this.handlers,(function(t){null!==t&&e(t)}))}}var Ig={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},jg={isNode:!0,classes:{URLSearchParams:t.URLSearchParams,FormData:_g,Blob:"undefined"!=typeof Blob&&Blob||null},protocols:["http","https","file","data"]};function Lg(e){function t(e,i,n,s){let a=e[s++];const r=Number.isFinite(+a),o=s>=e.length;if(a=!a&&Rf.isArray(n)?n.length:a,o)return Rf.hasOwnProp(n,a)?n[a]=[n[a],i]:n[a]=i,!r;n[a]&&Rf.isObject(n[a])||(n[a]=[]);return t(e,i,n[a],s)&&Rf.isArray(n[a])&&(n[a]=function(e){const t={},i=Object.keys(e);let n;const s=i.length;let a;for(n=0;n<s;n++)a=i[n],t[a]=e[a];return t}(n[a])),!r}if(Rf.isFormData(e)&&Rf.isFunction(e.entries)){const i={};return Rf.forEachEntry(e,((e,n)=>{t(function(e){return Rf.matchAll(/\w+|\[(\w*)]/g,e).map((e=>"[]"===e[0]?"":e[1]||e[0]))}(e),n,i,0)})),i}return null}const Mg={"Content-Type":void 0};const Ag={transitional:Ig,adapter:["xhr","http"],transformRequest:[function(e,t){const i=t.getContentType()||"",n=i.indexOf("application/json")>-1,s=Rf.isObject(e);s&&Rf.isHTMLForm(e)&&(e=new FormData(e));if(Rf.isFormData(e))return n&&n?JSON.stringify(Lg(e)):e;if(Rf.isArrayBuffer(e)||Rf.isBuffer(e)||Rf.isStream(e)||Rf.isFile(e)||Rf.isBlob(e))return e;if(Rf.isArrayBufferView(e))return e.buffer;if(Rf.isURLSearchParams(e))return t.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let a;if(s){if(i.indexOf("application/x-www-form-urlencoded")>-1)return function(e,t){return Cg(e,new jg.classes.URLSearchParams,Object.assign({visitor:function(e,t,i,n){return Rf.isBuffer(e)?(this.append(t,e.toString("base64")),!1):n.defaultVisitor.apply(this,arguments)}},t))}(e,this.formSerializer).toString();if((a=Rf.isFileList(e))||i.indexOf("multipart/form-data")>-1){const t=this.env&&this.env.FormData;return Cg(a?{"files[]":e}:e,t&&new t,this.formSerializer)}}return s||n?(t.setContentType("application/json",!1),function(e,t,i){if(Rf.isString(e))try{return(t||JSON.parse)(e),Rf.trim(e)}catch(e){if("SyntaxError"!==e.name)throw e}return(i||JSON.stringify)(e)}(e)):e}],transformResponse:[function(e){const t=this.transitional||Ag.transitional,i=t&&t.forcedJSONParsing,n="json"===this.responseType;if(e&&Rf.isString(e)&&(i&&!this.responseType||n)){const i=!(t&&t.silentJSONParsing)&&n;try{return JSON.parse(e)}catch(e){if(i){if("SyntaxError"===e.name)throw Cf.from(e,Cf.ERR_BAD_RESPONSE,this,null,this.response);throw e}}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:jg.classes.FormData,Blob:jg.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*"}}};Rf.forEach(["delete","get","head"],(function(e){Ag.headers[e]={}})),Rf.forEach(["post","put","patch"],(function(e){Ag.headers[e]=Rf.merge(Mg)}));const Ng=Rf.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]);const Bg=Symbol("internals");function Fg(e){return e&&String(e).trim().toLowerCase()}function Ug(e){return!1===e||null==e?e:Rf.isArray(e)?e.map(Ug):String(e)}function zg(e,t,i,n){return Rf.isFunction(n)?n.call(this,t,i):Rf.isString(t)?Rf.isString(n)?-1!==t.indexOf(n):Rf.isRegExp(n)?n.test(t):void 0:void 0}class qg{constructor(e){e&&this.set(e)}set(e,t,i){const n=this;function s(e,t,i){const s=Fg(t);if(!s)throw new Error("header name must be a non-empty string");const a=Rf.findKey(n,s);(!a||void 0===n[a]||!0===i||void 0===i&&!1!==n[a])&&(n[a||t]=Ug(e))}const a=(e,t)=>Rf.forEach(e,((e,i)=>s(e,i,t)));return Rf.isPlainObject(e)||e instanceof this.constructor?a(e,t):Rf.isString(e)&&(e=e.trim())&&!/^[-_a-zA-Z]+$/.test(e.trim())?a((e=>{const t={};let i,n,s;return e&&e.split("\n").forEach((function(e){s=e.indexOf(":"),i=e.substring(0,s).trim().toLowerCase(),n=e.substring(s+1).trim(),!i||t[i]&&Ng[i]||("set-cookie"===i?t[i]?t[i].push(n):t[i]=[n]:t[i]=t[i]?t[i]+", "+n:n)})),t})(e),t):null!=e&&s(t,e,i),this}get(e,t){if(e=Fg(e)){const i=Rf.findKey(this,e);if(i){const e=this[i];if(!t)return e;if(!0===t)return function(e){const t=Object.create(null),i=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let n;for(;n=i.exec(e);)t[n[1]]=n[2];return t}(e);if(Rf.isFunction(t))return t.call(this,e,i);if(Rf.isRegExp(t))return t.exec(e);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,t){if(e=Fg(e)){const i=Rf.findKey(this,e);return!(!i||t&&!zg(0,this[i],i,t))}return!1}delete(e,t){const i=this;let n=!1;function s(e){if(e=Fg(e)){const s=Rf.findKey(i,e);!s||t&&!zg(0,i[s],s,t)||(delete i[s],n=!0)}}return Rf.isArray(e)?e.forEach(s):s(e),n}clear(){return Object.keys(this).forEach(this.delete.bind(this))}normalize(e){const t=this,i={};return Rf.forEach(this,((n,s)=>{const a=Rf.findKey(i,s);if(a)return t[a]=Ug(n),void delete t[s];const r=e?function(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,((e,t,i)=>t.toUpperCase()+i))}(s):String(s).trim();r!==s&&delete t[s],t[r]=Ug(n),i[r]=!0})),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const t=Object.create(null);return Rf.forEach(this,((i,n)=>{null!=i&&!1!==i&&(t[n]=e&&Rf.isArray(i)?i.join(", "):i)})),t}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map((([e,t])=>e+": "+t)).join("\n")}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static concat(e,...t){const i=new this(e);return t.forEach((e=>i.set(e))),i}static accessor(e){const t=(this[Bg]=this[Bg]={accessors:{}}).accessors,i=this.prototype;function n(e){const n=Fg(e);t[n]||(!function(e,t){const i=Rf.toCamelCase(" "+t);["get","set","has"].forEach((n=>{Object.defineProperty(e,n+i,{value:function(e,i,s){return this[n].call(this,t,e,i,s)},configurable:!0})}))}(i,e),t[n]=!0)}return Rf.isArray(e)?e.forEach(n):n(e),this}}function $g(e,t){const i=this||Ag,n=t||i,s=qg.from(n.headers);let a=n.data;return Rf.forEach(e,(function(e){a=e.call(i,a,s.normalize(),t?t.status:void 0)})),s.normalize(),a}function Vg(e){return!(!e||!e.__CANCEL__)}function Wg(e,t,i){Cf.call(this,null==e?"canceled":e,Cf.ERR_CANCELED,t,i),this.name="CanceledError"}function Gg(e,t,i){const n=i.config.validateStatus;i.status&&n&&!n(i.status)?t(new Cf("Request failed with status code "+i.status,[Cf.ERR_BAD_REQUEST,Cf.ERR_BAD_RESPONSE][Math.floor(i.status/100)-4],i.config,i.request,i)):e(i)}function Hg(e,t){return e&&!function(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}(t)?function(e,t){return t?e.replace(/\/+$/,"")+"/"+t.replace(/^\/+/,""):e}(e,t):t}qg.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent"]),Rf.freezeMethods(qg.prototype),Rf.freezeMethods(qg),Rf.inherits(Wg,Cf,{__CANCEL__:!0});var Kg=t.parse,Jg={ftp:21,gopher:70,http:80,https:443,ws:80,wss:443},Qg=String.prototype.endsWith||function(e){return e.length<=this.length&&-1!==this.indexOf(e,this.length-e.length)};function Yg(e){return process.env[e.toLowerCase()]||process.env[e.toUpperCase()]||""}var Xg,Zg=function(e){var t="string"==typeof e?Kg(e):e||{},i=t.protocol,n=t.host,s=t.port;if("string"!=typeof n||!n||"string"!=typeof i)return"";if(i=i.split(":",1)[0],!function(e,t){var i=(Yg("npm_config_no_proxy")||Yg("no_proxy")).toLowerCase();if(!i)return!0;if("*"===i)return!1;return i.split(/[,\s]/).every((function(i){if(!i)return!0;var n=i.match(/^(.+):(\d+)$/),s=n?n[1]:i,a=n?parseInt(n[2]):0;return!(!a||a===t)||(/^[.*]/.test(s)?("*"===s.charAt(0)&&(s=s.slice(1)),!Qg.call(e,s)):e!==s)}))}(n=n.replace(/:\d*$/,""),s=parseInt(s)||Jg[i]||0))return"";var a=Yg("npm_config_"+i+"_proxy")||Yg(i+"_proxy")||Yg("npm_config_proxy")||Yg("all_proxy");return a&&-1===a.indexOf("://")&&(a=i+"://"+a),a},ev={},tv={get exports(){return ev},set exports(e){ev=e}},iv=t,nv=iv.URL,sv=n,av=s,rv=a.Writable,ov=u,cv=function(){if(!Xg){try{Xg=jo("follow-redirects")}catch(e){}"function"!=typeof Xg&&(Xg=function(){})}Xg.apply(null,arguments)},pv=["abort","aborted","connect","error","socket","timeout"],dv=Object.create(null);pv.forEach((function(e){dv[e]=function(t,i,n){this._redirectable.emit(e,t,i,n)}}));var lv=xv("ERR_INVALID_URL","Invalid URL",TypeError),uv=xv("ERR_FR_REDIRECTION_FAILURE","Redirected request failed"),mv=xv("ERR_FR_TOO_MANY_REDIRECTS","Maximum number of redirects exceeded"),hv=xv("ERR_FR_MAX_BODY_LENGTH_EXCEEDED","Request body larger than maxBodyLength limit"),fv=xv("ERR_STREAM_WRITE_AFTER_END","write after end");function gv(e,t){rv.call(this),this._sanitizeOptions(e),this._options=e,this._ended=!1,this._ending=!1,this._redirectCount=0,this._redirects=[],this._requestBodyLength=0,this._requestBodyBuffers=[],t&&this.on("response",t);var i=this;this._onNativeResponse=function(e){i._processResponse(e)},this._performRequest()}function vv(e){var t={maxRedirects:21,maxBodyLength:10485760},i={};return Object.keys(e).forEach((function(n){var s=n+":",a=i[s]=e[n],r=t[n]=Object.create(a);Object.defineProperties(r,{request:{value:function(e,n,a){if(Sv(e)){var r;try{r=_v(new nv(e))}catch(t){r=iv.parse(e)}if(!Sv(r.protocol))throw new lv({input:e});e=r}else nv&&e instanceof nv?e=_v(e):(a=n,n=e,e={protocol:s});return Rv(n)&&(a=n,n=null),(n=Object.assign({maxRedirects:t.maxRedirects,maxBodyLength:t.maxBodyLength},e,n)).nativeProtocols=i,Sv(n.host)||Sv(n.hostname)||(n.hostname="::1"),ov.equal(n.protocol,s,"protocol mismatch"),cv("options",n),new gv(n,a)},configurable:!0,enumerable:!0,writable:!0},get:{value:function(e,t,i){var n=r.request(e,t,i);return n.end(),n},configurable:!0,enumerable:!0,writable:!0}})})),t}function bv(){}function _v(e){var t={protocol:e.protocol,hostname:e.hostname.startsWith("[")?e.hostname.slice(1,-1):e.hostname,hash:e.hash,search:e.search,pathname:e.pathname,path:e.pathname+e.search,href:e.href};return""!==e.port&&(t.port=Number(e.port)),t}function yv(e,t){var i;for(var n in t)e.test(n)&&(i=t[n],delete t[n]);return null==i?void 0:String(i).trim()}function xv(e,t,i){function n(i){Error.captureStackTrace(this,this.constructor),Object.assign(this,i||{}),this.code=e,this.message=this.cause?t+": "+this.cause.message:t}return n.prototype=new(i||Error),n.prototype.constructor=n,n.prototype.name="Error ["+e+"]",n}function wv(e){for(var t of pv)e.removeListener(t,dv[t]);e.on("error",bv),e.abort()}function Sv(e){return"string"==typeof e||e instanceof String}function Rv(e){return"function"==typeof e}gv.prototype=Object.create(rv.prototype),gv.prototype.abort=function(){wv(this._currentRequest),this.emit("abort")},gv.prototype.write=function(e,t,i){if(this._ending)throw new fv;if(!Sv(e)&&("object"!=typeof(n=e)||!("length"in n)))throw new TypeError("data should be a string, Buffer or Uint8Array");var n;Rv(t)&&(i=t,t=null),0!==e.length?this._requestBodyLength+e.length<=this._options.maxBodyLength?(this._requestBodyLength+=e.length,this._requestBodyBuffers.push({data:e,encoding:t}),this._currentRequest.write(e,t,i)):(this.emit("error",new hv),this.abort()):i&&i()},gv.prototype.end=function(e,t,i){if(Rv(e)?(i=e,e=t=null):Rv(t)&&(i=t,t=null),e){var n=this,s=this._currentRequest;this.write(e,t,(function(){n._ended=!0,s.end(null,null,i)})),this._ending=!0}else this._ended=this._ending=!0,this._currentRequest.end(null,null,i)},gv.prototype.setHeader=function(e,t){this._options.headers[e]=t,this._currentRequest.setHeader(e,t)},gv.prototype.removeHeader=function(e){delete this._options.headers[e],this._currentRequest.removeHeader(e)},gv.prototype.setTimeout=function(e,t){var i=this;function n(t){t.setTimeout(e),t.removeListener("timeout",t.destroy),t.addListener("timeout",t.destroy)}function s(t){i._timeout&&clearTimeout(i._timeout),i._timeout=setTimeout((function(){i.emit("timeout"),a()}),e),n(t)}function a(){i._timeout&&(clearTimeout(i._timeout),i._timeout=null),i.removeListener("abort",a),i.removeListener("error",a),i.removeListener("response",a),t&&i.removeListener("timeout",t),i.socket||i._currentRequest.removeListener("socket",s)}return t&&this.on("timeout",t),this.socket?s(this.socket):this._currentRequest.once("socket",s),this.on("socket",n),this.on("abort",a),this.on("error",a),this.on("response",a),this},["flushHeaders","getHeader","setNoDelay","setSocketKeepAlive"].forEach((function(e){gv.prototype[e]=function(t,i){return this._currentRequest[e](t,i)}})),["aborted","connection","socket"].forEach((function(e){Object.defineProperty(gv.prototype,e,{get:function(){return this._currentRequest[e]}})})),gv.prototype._sanitizeOptions=function(e){if(e.headers||(e.headers={}),e.host&&(e.hostname||(e.hostname=e.host),delete e.host),!e.pathname&&e.path){var t=e.path.indexOf("?");t<0?e.pathname=e.path:(e.pathname=e.path.substring(0,t),e.search=e.path.substring(t))}},gv.prototype._performRequest=function(){var e=this._options.protocol,t=this._options.nativeProtocols[e];if(t){if(this._options.agents){var i=e.slice(0,-1);this._options.agent=this._options.agents[i]}var n=this._currentRequest=t.request(this._options,this._onNativeResponse);for(var s of(n._redirectable=this,pv))n.on(s,dv[s]);if(this._currentUrl=/^\//.test(this._options.path)?iv.format(this._options):this._options.path,this._isRedirect){var a=0,r=this,o=this._requestBodyBuffers;!function e(t){if(n===r._currentRequest)if(t)r.emit("error",t);else if(a<o.length){var i=o[a++];n.finished||n.write(i.data,i.encoding,e)}else r._ended&&n.end()}()}}else this.emit("error",new TypeError("Unsupported protocol "+e))},gv.prototype._processResponse=function(e){var t=e.statusCode;this._options.trackRedirects&&this._redirects.push({url:this._currentUrl,headers:e.headers,statusCode:t});var i=e.headers.location;if(!i||!1===this._options.followRedirects||t<300||t>=400)return e.responseUrl=this._currentUrl,e.redirects=this._redirects,this.emit("response",e),void(this._requestBodyBuffers=[]);if(wv(this._currentRequest),e.destroy(),++this._redirectCount>this._options.maxRedirects)this.emit("error",new mv);else{var n,s=this._options.beforeRedirect;s&&(n=Object.assign({Host:e.req.getHeader("host")},this._options.headers));var a=this._options.method;((301===t||302===t)&&"POST"===this._options.method||303===t&&!/^(?:GET|HEAD)$/.test(this._options.method))&&(this._options.method="GET",this._requestBodyBuffers=[],yv(/^content-/i,this._options.headers));var r,o=yv(/^host$/i,this._options.headers),c=iv.parse(this._currentUrl),p=o||c.host,d=/^\w+:/.test(i)?this._currentUrl:iv.format(Object.assign(c,{host:p}));try{r=iv.resolve(d,i)}catch(e){return void this.emit("error",new uv({cause:e}))}cv("redirecting to",r),this._isRedirect=!0;var l=iv.parse(r);if(Object.assign(this._options,l),(l.protocol!==c.protocol&&"https:"!==l.protocol||l.host!==p&&!function(e,t){ov(Sv(e)&&Sv(t));var i=e.length-t.length-1;return i>0&&"."===e[i]&&e.endsWith(t)}(l.host,p))&&yv(/^(?:authorization|cookie)$/i,this._options.headers),Rv(s)){var u={headers:e.headers,statusCode:t},m={url:d,method:a,headers:n};try{s(this._options,u,m)}catch(e){return void this.emit("error",e)}this._sanitizeOptions(this._options)}try{this._performRequest()}catch(e){this.emit("error",new uv({cause:e}))}}},tv.exports=vv({http:sv,https:av}),ev.wrap=vv;function Cv(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}const kv=/^(?:([^;]+);)?(?:[^;]+;)?(base64|),([\s\S]*)$/;function Tv(e,t){e=e||10;const i=new Array(e),n=new Array(e);let s,a=0,r=0;return t=void 0!==t?t:1e3,function(o){const c=Date.now(),p=n[r];s||(s=c),i[a]=o,n[a]=c;let d=r,l=0;for(;d!==a;)l+=i[d++],d%=e;if(a=(a+1)%e,a===r&&(r=(r+1)%e),c-s<t)return;const u=p&&c-p;return u?Math.round(1e3*l/u):void 0}}const Pv=Symbol("internals");class Ev extends a.Transform{constructor(e){super({readableHighWaterMark:(e=Rf.toFlatObject(e,{maxRate:0,chunkSize:65536,minChunkSize:100,timeWindow:500,ticksRate:2,samplesCount:15},null,((e,t)=>!Rf.isUndefined(t[e])))).chunkSize});const t=this,i=this[Pv]={length:e.length,timeWindow:e.timeWindow,ticksRate:e.ticksRate,chunkSize:e.chunkSize,maxRate:e.maxRate,minChunkSize:e.minChunkSize,bytesSeen:0,isCaptured:!1,notifiedBytesLoaded:0,ts:Date.now(),bytes:0,onReadCallback:null},n=Tv(i.ticksRate*e.samplesCount,i.timeWindow);this.on("newListener",(e=>{"progress"===e&&(i.isCaptured||(i.isCaptured=!0))}));let s=0;i.updateProgress=function(e,t){let i=0;const n=1e3/t;let s=null;return function(t,a){const r=Date.now();if(t||r-i>n)return s&&(clearTimeout(s),s=null),i=r,e.apply(null,a);s||(s=setTimeout((()=>(s=null,i=Date.now(),e.apply(null,a))),n-(r-i)))}}((function(){const e=i.length,a=i.bytesSeen,r=a-s;if(!r||t.destroyed)return;const o=n(r);s=a,process.nextTick((()=>{t.emit("progress",{loaded:a,total:e,progress:e?a/e:void 0,bytes:r,rate:o||void 0,estimated:o&&e&&a<=e?(e-a)/o:void 0})}))}),i.ticksRate);const a=()=>{i.updateProgress(!0)};this.once("end",a),this.once("error",a)}_read(e){const t=this[Pv];return t.onReadCallback&&t.onReadCallback(),super._read(e)}_transform(e,t,i){const n=this,s=this[Pv],a=s.maxRate,r=this.readableHighWaterMark,o=s.timeWindow,c=a/(1e3/o),p=!1!==s.minChunkSize?Math.max(s.minChunkSize,.01*c):0;const d=(e,t)=>{const i=Buffer.byteLength(e);let d,l=null,u=r,m=0;if(a){const e=Date.now();(!s.ts||(m=e-s.ts)>=o)&&(s.ts=e,d=c-s.bytes,s.bytes=d<0?-d:0,m=0),d=c-s.bytes}if(a){if(d<=0)return setTimeout((()=>{t(null,e)}),o-m);d<u&&(u=d)}u&&i>u&&i-u>p&&(l=e.subarray(u),e=e.subarray(0,u)),function(e,t){const i=Buffer.byteLength(e);s.bytesSeen+=i,s.bytes+=i,s.isCaptured&&s.updateProgress(),n.push(e)?process.nextTick(t):s.onReadCallback=()=>{s.onReadCallback=null,process.nextTick(t)}}(e,l?()=>{process.nextTick(t,null,l)}:t)};d(e,(function e(t,n){if(t)return i(t);n?d(n,e):i(null)}))}setLength(e){return this[Pv].length=+e,this}}const Ov={flush:r.constants.Z_SYNC_FLUSH,finishFlush:r.constants.Z_SYNC_FLUSH},Dv={flush:r.constants.BROTLI_OPERATION_FLUSH,finishFlush:r.constants.BROTLI_OPERATION_FLUSH},Iv=Rf.isFunction(r.createBrotliDecompress),{http:jv,https:Lv}=ev,Mv=/https:?/,Av=jg.protocols.map((e=>e+":"));function Nv(e){e.beforeRedirects.proxy&&e.beforeRedirects.proxy(e),e.beforeRedirects.config&&e.beforeRedirects.config(e)}function Bv(e,t,i){let n=t;if(!n&&!1!==n){const e=Zg(i);e&&(n=new URL(e))}if(n){if(n.username&&(n.auth=(n.username||"")+":"+(n.password||"")),n.auth){(n.auth.username||n.auth.password)&&(n.auth=(n.auth.username||"")+":"+(n.auth.password||""));const t=Buffer.from(n.auth,"utf8").toString("base64");e.headers["Proxy-Authorization"]="Basic "+t}e.headers.host=e.hostname+(e.port?":"+e.port:"");const t=n.hostname||n.host;e.hostname=t,e.host=t,e.port=n.port,e.path=i,n.protocol&&(e.protocol=n.protocol.includes(":")?n.protocol:`${n.protocol}:`)}e.beforeRedirects.proxy=function(e){Bv(e,t,e.href)}}var Fv="undefined"!=typeof process&&"process"===Rf.kindOf(process)&&function(e){return new Promise((function(t,i){let o=e.data;const c=e.responseType,p=e.responseEncoding,l=e.method.toUpperCase();let u,m,h,f=!1;const g=new d;function v(){u||(u=!0,e.cancelToken&&e.cancelToken.unsubscribe(x),e.signal&&e.signal.removeEventListener("abort",x),g.removeAllListeners())}function b(e,n){m||(m=!0,n&&(f=!0,v()),n?i(e):t(e))}const _=function(e){b(e)},y=function(e){b(e,!0)};function x(t){g.emit("abort",!t||t.type?new Wg(null,e,h):t)}g.once("abort",y),(e.cancelToken||e.signal)&&(e.cancelToken&&e.cancelToken.subscribe(x),e.signal&&(e.signal.aborted?x():e.signal.addEventListener("abort",x)));const w=Hg(e.baseURL,e.url),S=new URL(w),R=S.protocol||Av[0];if("data:"===R){let t;if("GET"!==l)return Gg(_,y,{status:405,statusText:"method not allowed",headers:{},config:e});try{t=function(e,t,i){const n=i&&i.Blob||jg.classes.Blob,s=Cv(e);if(void 0===t&&n&&(t=!0),"data"===s){e=s.length?e.slice(s.length+1):e;const i=kv.exec(e);if(!i)throw new Cf("Invalid URL",Cf.ERR_INVALID_URL);const a=i[1],r=i[2],o=i[3],c=Buffer.from(decodeURIComponent(o),r?"base64":"utf8");if(t){if(!n)throw new Cf("Blob is not supported",Cf.ERR_NOT_SUPPORT);return new n([c],{type:a})}return c}throw new Cf("Unsupported protocol "+s,Cf.ERR_NOT_SUPPORT)}(e.url,"blob"===c,{Blob:e.env&&e.env.Blob})}catch(t){throw Cf.from(t,Cf.ERR_BAD_REQUEST,e)}return"text"===c?(t=t.toString(p),p&&"utf8"!==p||(o=Rf.stripBOM(t))):"stream"===c&&(t=a.Readable.from(t)),Gg(_,y,{data:t,status:200,statusText:"OK",headers:new qg,config:e})}if(-1===Av.indexOf(R))return y(new Cf("Unsupported protocol "+R,Cf.ERR_BAD_REQUEST,e));const C=qg.from(e.headers).normalize();C.set("User-Agent","axios/1.2.3",!1);const k=e.onDownloadProgress,T=e.onUploadProgress,P=e.maxRate;let E,O;if(Rf.isFormData(o)&&Rf.isFunction(o.getHeaders))C.set(o.getHeaders());else if(o&&!Rf.isStream(o)){if(Buffer.isBuffer(o));else if(Rf.isArrayBuffer(o))o=Buffer.from(new Uint8Array(o));else{if(!Rf.isString(o))return y(new Cf("Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream",Cf.ERR_BAD_REQUEST,e));o=Buffer.from(o,"utf-8")}if(C.set("Content-Length",o.length,!1),e.maxBodyLength>-1&&o.length>e.maxBodyLength)return y(new Cf("Request body larger than maxBodyLength limit",Cf.ERR_BAD_REQUEST,e))}const D=Rf.toFiniteNumber(C.getContentLength());let I,j;if(Rf.isArray(P)?(E=P[0],O=P[1]):E=O=P,o&&(T||E)&&(Rf.isStream(o)||(o=a.Readable.from(o,{objectMode:!1})),o=a.pipeline([o,new Ev({length:D,maxRate:Rf.toFiniteNumber(E)})],Rf.noop),T&&o.on("progress",(e=>{T(Object.assign(e,{upload:!0}))}))),e.auth){I=(e.auth.username||"")+":"+(e.auth.password||"")}if(!I&&S.username){I=S.username+":"+S.password}I&&C.delete("authorization");try{j=Og(S.pathname+S.search,e.params,e.paramsSerializer).replace(/^\?/,"")}catch(t){const i=new Error(t.message);return i.config=e,i.url=e.url,i.exists=!0,y(i)}C.set("Accept-Encoding","gzip, compress, deflate"+(Iv?", br":""),!1);const L={path:j,method:l,headers:C.toJSON(),agents:{http:e.httpAgent,https:e.httpsAgent},auth:I,protocol:R,beforeRedirect:Nv,beforeRedirects:{}};let M;e.socketPath?L.socketPath=e.socketPath:(L.hostname=S.hostname,L.port=S.port,Bv(L,e.proxy,R+"//"+S.hostname+(S.port?":"+S.port:"")+L.path));const A=Mv.test(L.protocol);if(L.agent=A?e.httpsAgent:e.httpAgent,e.transport?M=e.transport:0===e.maxRedirects?M=A?s:n:(e.maxRedirects&&(L.maxRedirects=e.maxRedirects),e.beforeRedirect&&(L.beforeRedirects.config=e.beforeRedirect),M=A?Lv:jv),e.maxBodyLength>-1?L.maxBodyLength=e.maxBodyLength:L.maxBodyLength=1/0,e.insecureHTTPParser&&(L.insecureHTTPParser=e.insecureHTTPParser),h=M.request(L,(function(t){if(h.destroyed)return;const i=[t],n=+t.headers["content-length"];if(k){const e=new Ev({length:Rf.toFiniteNumber(n),maxRate:Rf.toFiniteNumber(O)});k&&e.on("progress",(e=>{k(Object.assign(e,{download:!0}))})),i.push(e)}let s=t;const o=t.req||h;if(!1!==e.decompress&&t.headers["content-encoding"])switch("HEAD"!==l&&204!==t.statusCode||delete t.headers["content-encoding"],t.headers["content-encoding"]){case"gzip":case"x-gzip":case"compress":case"x-compress":case"deflate":i.push(r.createUnzip(Ov)),delete t.headers["content-encoding"];break;case"br":Iv&&(i.push(r.createBrotliDecompress(Dv)),delete t.headers["content-encoding"])}s=i.length>1?a.pipeline(i,Rf.noop):i[0];const d=a.finished(s,(()=>{d(),v()})),u={status:t.statusCode,statusText:t.statusMessage,headers:new qg(t.headers),config:e,request:o};if("stream"===c)u.data=s,Gg(_,y,u);else{const t=[];let i=0;s.on("data",(function(n){t.push(n),i+=n.length,e.maxContentLength>-1&&i>e.maxContentLength&&(f=!0,s.destroy(),y(new Cf("maxContentLength size of "+e.maxContentLength+" exceeded",Cf.ERR_BAD_RESPONSE,e,o)))})),s.on("aborted",(function(){if(f)return;const t=new Cf("maxContentLength size of "+e.maxContentLength+" exceeded",Cf.ERR_BAD_RESPONSE,e,o);s.destroy(t),y(t)})),s.on("error",(function(t){h.destroyed||y(Cf.from(t,null,e,o))})),s.on("end",(function(){try{let e=1===t.length?t[0]:Buffer.concat(t);"arraybuffer"!==c&&(e=e.toString(p),p&&"utf8"!==p||(e=Rf.stripBOM(e))),u.data=e}catch(t){y(Cf.from(t,null,e,u.request,u))}Gg(_,y,u)}))}g.once("abort",(e=>{s.destroyed||(s.emit("error",e),s.destroy())}))})),g.once("abort",(e=>{y(e),h.destroy(e)})),h.on("error",(function(t){y(Cf.from(t,null,e,h))})),h.on("socket",(function(e){e.setKeepAlive(!0,6e4)})),e.timeout){const t=parseInt(e.timeout,10);if(isNaN(t))return void y(new Cf("error trying to parse `config.timeout` to int",Cf.ERR_BAD_OPTION_VALUE,e,h));h.setTimeout(t,(function(){if(m)return;let t=e.timeout?"timeout of "+e.timeout+"ms exceeded":"timeout exceeded";const i=e.transitional||Ig;e.timeoutErrorMessage&&(t=e.timeoutErrorMessage),y(new Cf(t,i.clarifyTimeoutError?Cf.ETIMEDOUT:Cf.ECONNABORTED,e,h)),x()}))}if(Rf.isStream(o)){let t=!1,i=!1;o.on("end",(()=>{t=!0})),o.once("error",(e=>{i=!0,h.destroy(e)})),o.on("close",(()=>{t||i||x(new Wg("Request stream has been aborted",e,h))})),o.pipe(h)}else h.end(o)}))},Uv=jg.isStandardBrowserEnv?{write:function(e,t,i,n,s,a){const r=[];r.push(e+"="+encodeURIComponent(t)),Rf.isNumber(i)&&r.push("expires="+new Date(i).toGMTString()),Rf.isString(n)&&r.push("path="+n),Rf.isString(s)&&r.push("domain="+s),!0===a&&r.push("secure"),document.cookie=r.join("; ")},read:function(e){const t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove:function(e){this.write(e,"",Date.now()-864e5)}}:{write:function(){},read:function(){return null},remove:function(){}},zv=jg.isStandardBrowserEnv?function(){const e=/(msie|trident)/i.test(navigator.userAgent),t=document.createElement("a");let i;function n(i){let n=i;return e&&(t.setAttribute("href",n),n=t.href),t.setAttribute("href",n),{href:t.href,protocol:t.protocol?t.protocol.replace(/:$/,""):"",host:t.host,search:t.search?t.search.replace(/^\?/,""):"",hash:t.hash?t.hash.replace(/^#/,""):"",hostname:t.hostname,port:t.port,pathname:"/"===t.pathname.charAt(0)?t.pathname:"/"+t.pathname}}return i=n(window.location.href),function(e){const t=Rf.isString(e)?n(e):e;return t.protocol===i.protocol&&t.host===i.host}}():function(){return!0};function qv(e,t){let i=0;const n=Tv(50,250);return s=>{const a=s.loaded,r=s.lengthComputable?s.total:void 0,o=a-i,c=n(o);i=a;const p={loaded:a,total:r,progress:r?a/r:void 0,bytes:o,rate:c||void 0,estimated:c&&r&&a<=r?(r-a)/c:void 0,event:s};p[t?"download":"upload"]=!0,e(p)}}var $v="undefined"!=typeof XMLHttpRequest&&function(e){return new Promise((function(t,i){let n=e.data;const s=qg.from(e.headers).normalize(),a=e.responseType;let r;function o(){e.cancelToken&&e.cancelToken.unsubscribe(r),e.signal&&e.signal.removeEventListener("abort",r)}Rf.isFormData(n)&&(jg.isStandardBrowserEnv||jg.isStandardBrowserWebWorkerEnv)&&s.setContentType(!1);let c=new XMLHttpRequest;if(e.auth){const t=e.auth.username||"",i=e.auth.password?unescape(encodeURIComponent(e.auth.password)):"";s.set("Authorization","Basic "+btoa(t+":"+i))}const p=Hg(e.baseURL,e.url);function d(){if(!c)return;const n=qg.from("getAllResponseHeaders"in c&&c.getAllResponseHeaders());Gg((function(e){t(e),o()}),(function(e){i(e),o()}),{data:a&&"text"!==a&&"json"!==a?c.response:c.responseText,status:c.status,statusText:c.statusText,headers:n,config:e,request:c}),c=null}if(c.open(e.method.toUpperCase(),Og(p,e.params,e.paramsSerializer),!0),c.timeout=e.timeout,"onloadend"in c?c.onloadend=d:c.onreadystatechange=function(){c&&4===c.readyState&&(0!==c.status||c.responseURL&&0===c.responseURL.indexOf("file:"))&&setTimeout(d)},c.onabort=function(){c&&(i(new Cf("Request aborted",Cf.ECONNABORTED,e,c)),c=null)},c.onerror=function(){i(new Cf("Network Error",Cf.ERR_NETWORK,e,c)),c=null},c.ontimeout=function(){let t=e.timeout?"timeout of "+e.timeout+"ms exceeded":"timeout exceeded";const n=e.transitional||Ig;e.timeoutErrorMessage&&(t=e.timeoutErrorMessage),i(new Cf(t,n.clarifyTimeoutError?Cf.ETIMEDOUT:Cf.ECONNABORTED,e,c)),c=null},jg.isStandardBrowserEnv){const t=(e.withCredentials||zv(p))&&e.xsrfCookieName&&Uv.read(e.xsrfCookieName);t&&s.set(e.xsrfHeaderName,t)}void 0===n&&s.setContentType(null),"setRequestHeader"in c&&Rf.forEach(s.toJSON(),(function(e,t){c.setRequestHeader(t,e)})),Rf.isUndefined(e.withCredentials)||(c.withCredentials=!!e.withCredentials),a&&"json"!==a&&(c.responseType=e.responseType),"function"==typeof e.onDownloadProgress&&c.addEventListener("progress",qv(e.onDownloadProgress,!0)),"function"==typeof e.onUploadProgress&&c.upload&&c.upload.addEventListener("progress",qv(e.onUploadProgress)),(e.cancelToken||e.signal)&&(r=t=>{c&&(i(!t||t.type?new Wg(null,e,c):t),c.abort(),c=null)},e.cancelToken&&e.cancelToken.subscribe(r),e.signal&&(e.signal.aborted?r():e.signal.addEventListener("abort",r)));const l=Cv(p);l&&-1===jg.protocols.indexOf(l)?i(new Cf("Unsupported protocol "+l+":",Cf.ERR_BAD_REQUEST,e)):c.send(n||null)}))};const Vv={http:Fv,xhr:$v};Rf.forEach(Vv,((e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch(e){}Object.defineProperty(e,"adapterName",{value:t})}}));var Wv=e=>{e=Rf.isArray(e)?e:[e];const{length:t}=e;let i,n;for(let s=0;s<t&&(i=e[s],!(n=Rf.isString(i)?Vv[i.toLowerCase()]:i));s++);if(!n){if(!1===n)throw new Cf(`Adapter ${i} is not supported by the environment`,"ERR_NOT_SUPPORT");throw new Error(Rf.hasOwnProp(Vv,i)?`Adapter '${i}' is not available in the build`:`Unknown adapter '${i}'`)}if(!Rf.isFunction(n))throw new TypeError("adapter is not a function");return n};function Gv(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new Wg(null,e)}function Hv(e){Gv(e),e.headers=qg.from(e.headers),e.data=$g.call(e,e.transformRequest),-1!==["post","put","patch"].indexOf(e.method)&&e.headers.setContentType("application/x-www-form-urlencoded",!1);return Wv(e.adapter||Ag.adapter)(e).then((function(t){return Gv(e),t.data=$g.call(e,e.transformResponse,t),t.headers=qg.from(t.headers),t}),(function(t){return Vg(t)||(Gv(e),t&&t.response&&(t.response.data=$g.call(e,e.transformResponse,t.response),t.response.headers=qg.from(t.response.headers))),Promise.reject(t)}))}const Kv=e=>e instanceof qg?e.toJSON():e;function Jv(e,t){t=t||{};const i={};function n(e,t,i){return Rf.isPlainObject(e)&&Rf.isPlainObject(t)?Rf.merge.call({caseless:i},e,t):Rf.isPlainObject(t)?Rf.merge({},t):Rf.isArray(t)?t.slice():t}function s(e,t,i){return Rf.isUndefined(t)?Rf.isUndefined(e)?void 0:n(void 0,e,i):n(e,t,i)}function a(e,t){if(!Rf.isUndefined(t))return n(void 0,t)}function r(e,t){return Rf.isUndefined(t)?Rf.isUndefined(e)?void 0:n(void 0,e):n(void 0,t)}function o(i,s,a){return a in t?n(i,s):a in e?n(void 0,i):void 0}const c={url:a,method:a,data:a,baseURL:r,transformRequest:r,transformResponse:r,paramsSerializer:r,timeout:r,timeoutMessage:r,withCredentials:r,adapter:r,responseType:r,xsrfCookieName:r,xsrfHeaderName:r,onUploadProgress:r,onDownloadProgress:r,decompress:r,maxContentLength:r,maxBodyLength:r,beforeRedirect:r,transport:r,httpAgent:r,httpsAgent:r,cancelToken:r,socketPath:r,responseEncoding:r,validateStatus:o,headers:(e,t)=>s(Kv(e),Kv(t),!0)};return Rf.forEach(Object.keys(e).concat(Object.keys(t)),(function(n){const a=c[n]||s,r=a(e[n],t[n],n);Rf.isUndefined(r)&&a!==o||(i[n]=r)})),i}const Qv={};["object","boolean","number","function","string","symbol"].forEach(((e,t)=>{Qv[e]=function(i){return typeof i===e||"a"+(t<1?"n ":" ")+e}}));const Yv={};Qv.transitional=function(e,t,i){function n(e,t){return"[Axios v1.2.3] Transitional option '"+e+"'"+t+(i?". "+i:"")}return(i,s,a)=>{if(!1===e)throw new Cf(n(s," has been removed"+(t?" in "+t:"")),Cf.ERR_DEPRECATED);return t&&!Yv[s]&&(Yv[s]=!0,console.warn(n(s," has been deprecated since v"+t+" and will be removed in the near future"))),!e||e(i,s,a)}};var Xv={assertOptions:function(e,t,i){if("object"!=typeof e)throw new Cf("options must be an object",Cf.ERR_BAD_OPTION_VALUE);const n=Object.keys(e);let s=n.length;for(;s-- >0;){const a=n[s],r=t[a];if(r){const t=e[a],i=void 0===t||r(t,a,e);if(!0!==i)throw new Cf("option "+a+" must be "+i,Cf.ERR_BAD_OPTION_VALUE)}else if(!0!==i)throw new Cf("Unknown option "+a,Cf.ERR_BAD_OPTION)}},validators:Qv};const Zv=Xv.validators;class eb{constructor(e){this.defaults=e,this.interceptors={request:new Dg,response:new Dg}}request(e,t){"string"==typeof e?(t=t||{}).url=e:t=e||{},t=Jv(this.defaults,t);const{transitional:i,paramsSerializer:n,headers:s}=t;let a;void 0!==i&&Xv.assertOptions(i,{silentJSONParsing:Zv.transitional(Zv.boolean),forcedJSONParsing:Zv.transitional(Zv.boolean),clarifyTimeoutError:Zv.transitional(Zv.boolean)},!1),void 0!==n&&Xv.assertOptions(n,{encode:Zv.function,serialize:Zv.function},!0),t.method=(t.method||this.defaults.method||"get").toLowerCase(),a=s&&Rf.merge(s.common,s[t.method]),a&&Rf.forEach(["delete","get","head","post","put","patch","common"],(e=>{delete s[e]})),t.headers=qg.concat(a,s);const r=[];let o=!0;this.interceptors.request.forEach((function(e){"function"==typeof e.runWhen&&!1===e.runWhen(t)||(o=o&&e.synchronous,r.unshift(e.fulfilled,e.rejected))}));const c=[];let p;this.interceptors.response.forEach((function(e){c.push(e.fulfilled,e.rejected)}));let d,l=0;if(!o){const e=[Hv.bind(this),void 0];for(e.unshift.apply(e,r),e.push.apply(e,c),d=e.length,p=Promise.resolve(t);l<d;)p=p.then(e[l++],e[l++]);return p}d=r.length;let u=t;for(l=0;l<d;){const e=r[l++],t=r[l++];try{u=e(u)}catch(e){t.call(this,e);break}}try{p=Hv.call(this,u)}catch(e){return Promise.reject(e)}for(l=0,d=c.length;l<d;)p=p.then(c[l++],c[l++]);return p}getUri(e){return Og(Hg((e=Jv(this.defaults,e)).baseURL,e.url),e.params,e.paramsSerializer)}}Rf.forEach(["delete","get","head","options"],(function(e){eb.prototype[e]=function(t,i){return this.request(Jv(i||{},{method:e,url:t,data:(i||{}).data}))}})),Rf.forEach(["post","put","patch"],(function(e){function t(t){return function(i,n,s){return this.request(Jv(s||{},{method:e,headers:t?{"Content-Type":"multipart/form-data"}:{},url:i,data:n}))}}eb.prototype[e]=t(),eb.prototype[e+"Form"]=t(!0)}));class tb{constructor(e){if("function"!=typeof e)throw new TypeError("executor must be a function.");let t;this.promise=new Promise((function(e){t=e}));const i=this;this.promise.then((e=>{if(!i._listeners)return;let t=i._listeners.length;for(;t-- >0;)i._listeners[t](e);i._listeners=null})),this.promise.then=e=>{let t;const n=new Promise((e=>{i.subscribe(e),t=e})).then(e);return n.cancel=function(){i.unsubscribe(t)},n},e((function(e,n,s){i.reason||(i.reason=new Wg(e,n,s),t(i.reason))}))}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){this.reason?e(this.reason):this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;const t=this._listeners.indexOf(e);-1!==t&&this._listeners.splice(t,1)}static source(){let e;return{token:new tb((function(t){e=t})),cancel:e}}}const ib={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(ib).forEach((([e,t])=>{ib[t]=e}));const nb=function e(t){const i=new eb(t),n=Kh(eb.prototype.request,i);return Rf.extend(n,eb.prototype,i,{allOwnKeys:!0}),Rf.extend(n,i,null,{allOwnKeys:!0}),n.create=function(i){return e(Jv(t,i))},n}(Ag);nb.Axios=eb,nb.CanceledError=Wg,nb.CancelToken=tb,nb.isCancel=Vg,nb.VERSION="1.2.3",nb.toFormData=Cg,nb.AxiosError=Cf,nb.Cancel=nb.CanceledError,nb.all=function(e){return Promise.all(e)},nb.spread=function(e){return function(t){return e.apply(null,t)}},nb.isAxiosError=function(e){return Rf.isObject(e)&&!0===e.isAxiosError},nb.mergeConfig=Jv,nb.AxiosHeaders=qg,nb.formToJSON=e=>Lg(Rf.isHTMLForm(e)?new FormData(e):e),nb.HttpStatusCode=ib,nb.default=nb;class sb{constructor(e={}){this.data=void 0===e.data?{}:e.data,this.headers=e.headers||{},this.status=e.status||200,this.statusText=e.statusText||"OK",this.url=e.url||null}}function ab(e,t){return u.ok(e,`${t} is required`),e}function rb(e,t){return u.ok("boolean"==typeof e,`${t}<boolean> is required`),e}function ob(e,t){return u.ok("number"==typeof e,`${t}<number> is required`),e}function cb(e,t){return u.ok("string"==typeof e,`${t}<string> is required`),e}function pb(e,t,i){const n=i||t.name[0].toLowerCase()+t.name.substring(1);return u.ok(e instanceof t,`${n}<${t.name}> is required`),e}function db(e,t="roomName"){return cb(e,t),u.equal("string"==typeof e&&e[0],"/",`${t} must begin with a '/'`),e}function lb(e,t){return u.ok(Array.isArray(e),`${t}<array> is required`),e}function ub(e,t){if(null==e||"object"!=typeof e||Array.isArray(e))throw new Error(`${t} must be a record. ${JSON.stringify(e)}`);return e}function mb(e,t,i){cb(t,"name"),function(e,t,i,n){cb(i,"name");const s=n||`${i} must be null or of type ${t}`;u.ok(null===e||typeof e===t,s)}(e,"string",t,i)}function hb({baseUrl:e,url:t}){return u.ok("string"==typeof t,"url<String> is required"),e?e+t:t}class fb{constructor({baseUrl:e}){cb(e,"baseUrl"),this._baseUrl=e}_requestAxios(e,t){const i=Object.assign({},t,{url:e,baseURL:this._baseUrl});return nb.request(i)}request(e,t){return cb(e,"url"),u.equal(e[0],"/",'url<String> only accepts relative URLs beginning with "/".'),u.ok(t,"options are required"),this._requestAxios(e,t).then((e=>{const{data:t,headers:i,status:n,statusText:s,config:a}=e,r=a&&a.url?hb({baseUrl:a.baseURL,url:a.url}):null;return new sb({data:t,headers:i,status:n,statusText:s,url:r})})).catch((e=>{const t=e.response;if(!t)throw new Error("Could not make the request.");const{data:i,headers:n,status:s,statusText:a,config:r}=t,o=r&&r.url?hb({baseUrl:r.baseURL,url:r.url}):null;return Promise.reject(new sb({data:i,headers:n,status:s,statusText:a,url:o}))}))}}class gb{constructor({httpClient:e}){u.ok(e,"httpClient is required"),this._httpClient=e}static dataToFormData(e){u.ok(e,"data is required");const t=new FormData;return Object.keys(e).forEach((i=>{const n=e[i];t.append(i,n)})),t}request(e,t={}){const i=Object.assign(t.headers||{},{"Content-Type":void 0});return this._httpClient.request(e,Object.assign(t,{headers:i,transformRequest:gb.dataToFormData}))}}let vb;vb="object"==typeof window?window.btoa||Hh:"object"==typeof global&&global.btoa||Hh;const bb=()=>Promise.resolve(null);class _b{constructor({httpClient:e,fetchDeviceCredentials:t}){this._httpClient=e,this._fetchDeviceCredentials=t}request(e,t){return this._fetchDeviceCredentials().then((i=>{const n=Object.assign({},t.headers,function(e){if(e&&e.credentials){const t=`${e.credentials.uuid}:${e.hmac}`;return{Authorization:`Basic ${vb(t)}`}}return{}}(i),{"X-Appearin-Device-Platform":"web"}),s=Object.assign({},t,{headers:n});return this._httpClient.request(e,s)}))}}class yb{constructor({baseUrl:e="https://api.appearin.net",fetchDeviceCredentials:t=bb}={}){cb(e,"baseUrl"),u.ok("function"==typeof t,"fetchDeviceCredentials<Function> is required"),this.authenticatedHttpClient=new _b({httpClient:new fb({baseUrl:e}),fetchDeviceCredentials:t}),this.authenticatedFormDataHttpClient=new gb({httpClient:this.authenticatedHttpClient})}request(e,t){return cb(e,"url"),u.equal(e[0],"/",'url<String> only accepts relative URLs beginning with "/".'),u.ok(t,"options are required"),this.authenticatedHttpClient.request(e,t)}requestMultipart(e,t){return cb(e,"url"),u.equal(e[0],"/",'url<String> only accepts relative URLs beginning with "/".'),u.ok(t,"options are required"),this.authenticatedFormDataHttpClient.request(e,t)}}function xb(e,t){return cb(ub(e,"data")[t],t)}const wb=(Sb=xb,(e,t)=>{const i=ub(e,"data")[t];return null==i?null:Sb(e,t)});var Sb;function Rb(e,t){const i=xb(e,t),n=new Date(i);if(isNaN(n.getTime()))throw new Error(`Invalid date for ${i}`);return n}function Cb(e,t,i){return function(e,t){return lb(ub(e,"data")[t],t)}(e,t).map((e=>i(e)))}class kb{constructor(e,t,i){this.credentials={uuid:e},this.hmac=t,this.userId=i}toJson(){return Object.assign({credentials:this.credentials,hmac:this.hmac},this.userId&&{userId:this.userId})}static fromJson(e){return new kb(xb(function(e,t){const i=ub(e,"data")[t];return void 0===i?null:i}(e,"credentials"),"uuid"),xb(e,"hmac"),wb(e,"userId")||void 0)}}class Tb{constructor({apiClient:e}){this._apiClient=pb(e,yb)}getCredentials(){return this._apiClient.request("/devices",{method:"post"}).then((({data:e})=>kb.fromJson(e))).catch((e=>{if(e.response&&404===e.response.status)return null;throw e}))}}class Pb{constructor(e,t){this._key=e,this._chromeStorage=t}loadOrDefault(e){return new Promise((t=>{this._chromeStorage.get(this._key,(i=>{t(i[this._key]||e)}))}))}save(e){return new Promise((t=>{this._chromeStorage.set({[this._key]:e},(()=>{t()}))}))}}class Eb{constructor(e,t){ab(t,"localStorage"),this._key=cb(e,"key"),this._localStorage=t}loadOrDefault(e){try{const t=this._localStorage.getItem(this._key);if(t)try{return Promise.resolve(JSON.parse(t))}catch(e){}return Promise.resolve(e)}catch(t){return console.warn("Error getting access to storage. Are cookies blocked?",t),Promise.resolve(e)}}save(e){try{return this._localStorage.setItem(this._key,JSON.stringify(e)),Promise.resolve()}catch(e){return console.warn("Error getting access to storage. Are cookies blocked?",e),Promise.reject(e)}}}let Ob;try{Ob=self.localStorage}catch(e){Ob={getItem:()=>{},key:()=>{},setItem:()=>{},removeItem:()=>{},hasOwnProperty:()=>{},length:0}}var Db=Ob;const Ib="credentials_saved";class jb extends d{constructor({deviceService:e,credentialsStore:t}){super(),this._deviceService=pb(e,Tb),this._credentialsStore=t}static create({baseUrl:e,storeName:t="CredentialsStorage",storeType:i="localStorage"}){const n=new Tb({apiClient:new yb({baseUrl:e})});let s=null;if("localStorage"===i)s=new Eb(t,Db);else{if("chromeStorage"!==i)throw new Error(`Unknown store type: ${i}`);s=new Pb(t,window.chrome.storage.local)}return new jb({deviceService:n,credentialsStore:s})}_fetchNewCredentialsFromApi(){const e=this._credentialsStore;return new Promise((t=>{const i=()=>{this._deviceService.getCredentials().then((i=>e.save(i?i.toJson():null).then((()=>t(i))))).catch((()=>{setTimeout(i,2e3)}))};i()}))}getCurrentCredentials(){return this._credentialsStore.loadOrDefault(null).then((e=>e?kb.fromJson(e):null))}getCredentials(){return this.credentialsPromise||(this.credentialsPromise=this.getCurrentCredentials().then((e=>e||this._fetchNewCredentialsFromApi()))),this.credentialsPromise}saveCredentials(e){return this.credentialsPromise=void 0,this._credentialsStore.save(e.toJson()).then((()=>(this.emit(Ib,e),e)))}setUserId(e){return this.getCurrentCredentials().then((t=>{t||console.error("Illegal state: no credentials to set user id for.");if(null===t||t.userId!==e)return this._credentialsStore.save(Object.assign({},null==t?void 0:t.toJson(),{userId:e}))})).then((()=>{}))}}const Lb=()=>Promise.resolve(void 0);class Mb{constructor({apiClient:e,fetchOrganization:t=Lb}){this._apiClient=pb(e,yb),u.ok("function"==typeof t,"fetchOrganization<Function> is required"),this._fetchOrganization=t,this._apiClient=e}_callRequestMethod(e,t,i){return cb(t,"url"),u.equal(t[0],"/",'url<String> only accepts relative URLs beginning with "/".'),u.ok(i,"options are required"),this._fetchOrganization().then((n=>{if(!n)return this._apiClient[e](t,i);const{organizationId:s}=n;return this._apiClient[e](`/organizations/${encodeURIComponent(s)}${t}`,i)}))}request(e,t){return this._callRequestMethod("request",e,t)}requestMultipart(e,t){return this._callRequestMethod("requestMultipart",e,t)}}class Ab{constructor({isExhausted:e,renewsAt:t,totalMinutesLimit:i,totalMinutesUsed:n}){this.isExhausted=e,this.renewsAt=t,this.totalMinutesLimit=i,this.totalMinutesUsed=n}static fromJson(e){return new Ab({isExhausted:rb(e.isExhausted,"isExhausted"),renewsAt:new Date(cb(e.renewsAt,"renewsAt")),totalMinutesLimit:ob(e.totalMinutesLimit,"totalMinutesLimit"),totalMinutesUsed:ob(e.totalMinutesUsed,"totalMinutesUsed")})}}class Nb{constructor({basePlanId:e,embeddedFreeTierStatus:t,isDeactivated:i,isOnTrial:n,onTrialUntil:s,trialStatus:a}){this.basePlanId=e,this.isDeactivated=i,this.isOnTrial=n,this.onTrialUntil=s||null,this.trialStatus=a||null,this.embeddedFreeTierStatus=t||null}static fromJson(e){return new Nb({basePlanId:"string"==typeof e.basePlanId?e.basePlanId:null,isDeactivated:rb(e.isDeactivated,"isDeactivated"),isOnTrial:rb(e.isOnTrial,"isOnTrial"),onTrialUntil:"string"==typeof e.onTrialUntil?new Date(e.onTrialUntil):null,trialStatus:"string"==typeof e.trialStatus?e.trialStatus:null,embeddedFreeTierStatus:e.embeddedFreeTierStatus?Ab.fromJson(e.embeddedFreeTierStatus):null})}}function Bb(e){return null!=e}function Fb(e={}){return{maxNumberOfInvitationsAndUsers:Bb(null==e?void 0:e.maxNumberOfInvitationsAndUsers)?Number(null==e?void 0:e.maxNumberOfInvitationsAndUsers):null,maxNumberOfClaimedRooms:Bb(null==e?void 0:e.maxNumberOfClaimedRooms)?Number(null==e?void 0:e.maxNumberOfClaimedRooms):null,maxRoomLimitPerOrganization:Bb(null==e?void 0:e.maxRoomLimitPerOrganization)?Number(null==e?void 0:e.maxRoomLimitPerOrganization):null,trialMinutesLimit:Bb(null==e?void 0:e.trialMinutesLimit)?Number(null==e?void 0:e.trialMinutesLimit):null,includedUnits:Bb(null==e?void 0:e.includedUnits)?Number(null==e?void 0:e.includedUnits):null}}class Ub{constructor(e){this.logoImageUrl=null,this.roomBackgroundImageUrl=null,this.roomBackgroundThumbnailUrl=null,this.roomKnockPageBackgroundImageUrl=null,this.roomKnockPageBackgroundThumbnailUrl=null,this.preferences=null,this.onboardingSurvey=null,this.type=null,pb(e,Object,"properties"),cb(e.organizationId,"organizationId"),cb(e.organizationName,"organizationName"),cb(e.subdomain,"subdomain"),pb(e.permissions,Object,"permissions"),pb(e.limits,Object,"limits"),this.organizationId=e.organizationId,this.organizationName=e.organizationName,this.subdomain=e.subdomain,this.permissions=e.permissions,this.limits=e.limits,this.account=e.account?new Nb(e.account):null,this.logoImageUrl=e.logoImageUrl,this.roomBackgroundImageUrl=e.roomBackgroundImageUrl,this.roomBackgroundThumbnailUrl=e.roomBackgroundThumbnailUrl,this.roomKnockPageBackgroundImageUrl=e.roomKnockPageBackgroundImageUrl,this.roomKnockPageBackgroundThumbnailUrl=e.roomKnockPageBackgroundThumbnailUrl,this.preferences=e.preferences,this.onboardingSurvey=e.onboardingSurvey,this.type=e.type}static fromJson(e){const t=pb(e,Object,"data"),i=(null==t?void 0:t.preferences)||{},n=(null==t?void 0:t.onboardingSurvey)||null,s=pb(t.permissions,Object,"permissions");return new Ub({organizationId:cb(t.organizationId,"organizationId"),organizationName:cb(t.organizationName,"organizationName"),subdomain:cb(t.subdomain,"subdomain"),permissions:s,limits:Fb(pb(t.limits,Object,"limits")),account:t.account?Nb.fromJson(t.account):null,logoImageUrl:"string"==typeof t.logoImageUrl?t.logoImageUrl:null,roomBackgroundImageUrl:"string"==typeof t.roomBackgroundImageUrl?t.roomBackgroundImageUrl:null,roomBackgroundThumbnailUrl:"string"==typeof t.roomBackgroundThumbnailUrl?t.roomBackgroundThumbnailUrl:null,roomKnockPageBackgroundImageUrl:"string"==typeof t.roomKnockPageBackgroundImageUrl?t.roomKnockPageBackgroundImageUrl:null,roomKnockPageBackgroundThumbnailUrl:"string"==typeof t.roomKnockPageBackgroundThumbnailUrl?t.roomKnockPageBackgroundThumbnailUrl:null,preferences:i,onboardingSurvey:n,type:"string"==typeof t.type?t.type:null})}}Ub.GLOBAL_ORGANIZATION_ID="1";class zb{constructor({apiClient:e}){this._apiClient=pb(e,yb)}createOrganization({organizationName:e,subdomain:t,owner:i}){const{displayName:n,consents:s}=i||{},a="email"in i?{value:i.email,verificationCode:cb(i.verificationCode,"owner.verificationCode")}:null,r="idToken"in i?i.idToken:null;if(cb(t,"subdomain"),cb(e,"organizationName"),cb(n,"owner.displayName"),u.ok(a||r,"owner.email or owner.idToken is required"),s){lb(s,"consents");for(const{consentRevisionId:e,action:t}of s)cb(e,"consentRevisionId"),mb(t,"action")}return this._apiClient.request("/organizations",{method:"POST",data:{organizationName:e,type:"private",subdomain:t,owner:Object.assign(Object.assign(Object.assign(Object.assign({},a&&{email:a}),r&&{idToken:r}),s&&{consents:s}),{displayName:n})}}).then((({data:e})=>xb(e,"organizationId")))}getOrganizationBySubdomain(e){return cb(e,"subdomain"),this._apiClient.request(`/organization-subdomains/${encodeURIComponent(e)}/?fields=permissions,account,onboardingSurvey`,{method:"GET"}).then((({data:e})=>Ub.fromJson(e))).catch((e=>{if(e instanceof sb){if(404===e.status)return null;throw new Error(e.statusText)}throw e}))}getOrganizationByOrganizationId(e){return cb(e,"organizationId"),this._apiClient.request(`/organizations/${encodeURIComponent(e)}?fields=permissions,account`,{method:"GET"}).then((({data:e})=>Ub.fromJson(e))).catch((e=>{if(e instanceof sb){if(404===e.status)return null;throw new Error(e.statusText)}throw e}))}getOrganizationsByContactPoint(e){const{code:t}=e,i="email"in e?e.email:null,n="phoneNumber"in e?e.phoneNumber:null;u.ok((i||n)&&!(i&&n),"either email or phoneNumber is required"),cb(t,"code");const s=i?{type:"email",value:i}:{type:"phoneNumber",value:n};return this._apiClient.request("/organization-queries",{method:"POST",data:{contactPoint:s,code:t}}).then((({data:e})=>Cb(e,"organizations",(e=>Ub.fromJson(e)))))}getOrganizationsByIdToken({idToken:e}){return cb(e,"idToken"),this._apiClient.request("/organization-queries",{method:"POST",data:{idToken:e}}).then((({data:e})=>Cb(e,"organizations",(e=>Ub.fromJson(Object.assign({permissions:{},limits:{}},ub(e,"organization")))))))}getOrganizationsByLoggedInUser(){return this._apiClient.request("/user/organizations",{method:"GET"}).then((({data:e})=>Cb(e,"organizations",(e=>Ub.fromJson(Object.assign({permissions:{},limits:{}},ub(e,"organization")))))))}getSubdomainAvailability(e){return cb(e,"subdomain"),this._apiClient.request(`/organization-subdomains/${encodeURIComponent(e)}/availability`,{method:"GET"}).then((({data:e})=>(pb(e,Object,"data"),{status:xb(e,"status")})))}updatePreferences({organizationId:e,preferences:t}){return ab(e,"organizationId"),ab(t,"preferences"),this._apiClient.request(`/organizations/${encodeURIComponent(e)}/preferences`,{method:"PATCH",data:t}).then((()=>{}))}deleteOrganization({organizationId:e}){return ab(e,"organizationId"),this._apiClient.request(`/organizations/${encodeURIComponent(e)}`,{method:"DELETE"}).then((()=>{}))}}class qb{constructor({organizationService:e,subdomain:t}){pb(e,zb),cb(t,"subdomain"),this._organizationService=e,this._subdomain=t,this._organizationPromise=null}initOrganization(){return this.fetchOrganization().then((()=>{}))}fetchOrganization(){return this._organizationPromise||(this._organizationPromise=this._organizationService.getOrganizationBySubdomain(this._subdomain)),this._organizationPromise}}class $b{constructor(e={}){u.ok(e instanceof Object,"properties<object> must be empty or an object"),this.isClaimed=!1,this.isBanned=!1,this.isLocked=!1,this.knockPage={backgroundImageUrl:null,backgroundThumbnailUrl:null},this.logoUrl=null,this.backgroundImageUrl=null,this.backgroundThumbnailUrl=null,this.type=null,this.legacyRoomType=null,this.mode=null,this.product=null,this.roomName=null,this.theme=null,this.preferences={},this.protectedPreferences={},this.publicProfile=null;const t={};Object.getOwnPropertyNames(e).forEach((i=>{-1!==Object.getOwnPropertyNames(this).indexOf(i)&&(t[i]=e[i])})),void 0!==e.ownerId&&(this.ownerId=e.ownerId),void 0!==e.meeting&&(this.meeting=e.meeting),Object.assign(this,t)}}class Vb{constructor({meetingId:e,roomName:t,roomUrl:i,startDate:n,endDate:s,hostRoomUrl:a,viewerRoomUrl:r}){cb(e,"meetingId"),cb(t,"roomName"),cb(i,"roomUrl"),pb(n,Date,"startDate"),pb(s,Date,"endDate"),this.meetingId=e,this.roomName=t,this.roomUrl=i,this.startDate=n,this.endDate=s,this.hostRoomUrl=a,this.viewerRoomUrl=r}static fromJson(e){return new Vb({meetingId:xb(e,"meetingId"),roomName:xb(e,"roomName"),roomUrl:xb(e,"roomUrl"),startDate:Rb(e,"startDate"),endDate:Rb(e,"endDate"),hostRoomUrl:wb(e,"hostRoomUrl"),viewerRoomUrl:wb(e,"viewerRoomUrl")})}}function Wb(e,t=""){return`/room/${encodeURIComponent(e.substring(1))}${t}`}class Gb{constructor({organizationApiClient:e}){this._organizationApiClient=pb(e,Mb)}getRooms({types:e,fields:t=[]}={}){return lb(e,"types"),lb(t,"fields"),this._organizationApiClient.request("/room",{method:"GET",params:{types:e.join(","),fields:t.join(","),includeOnlyLegacyRoomType:"false"}}).then((({data:e})=>e.rooms.map((e=>new $b(e)))))}getRoom({roomName:e,fields:t}){db(e);const i=encodeURIComponent(e.substring(1));return this._organizationApiClient.request(`/rooms/${i}`,{method:"GET",params:Object.assign({includeOnlyLegacyRoomType:"false"},t&&{fields:t.join(",")})}).then((({data:t})=>new $b(Object.assign({},t,Object.assign({roomName:e},t.meeting&&{meeting:Vb.fromJson(t.meeting)}))))).catch((t=>{if(404===t.status)return new $b({roomName:e,isClaimed:!1,mode:"normal",product:{categoryName:"personal_free"},type:"personal",legacyRoomType:"free"});if(400===t.status&&"Banned room"===t.data.error)return new $b({roomName:e,isBanned:!0});throw new Error(t.data?t.data.error:"Could not fetch room information")}))}claimRoom({roomName:e,type:t,mode:i,isLocked:n}){return db(e),cb(t,"type"),this._organizationApiClient.request("/room/claim",{method:"POST",data:Object.assign(Object.assign({roomName:e,type:t},"string"==typeof i&&{mode:i}),"boolean"==typeof n&&{isLocked:n})}).then((()=>{})).catch((e=>{throw new Error(e.data.error||"Failed to claim room")}))}unclaimRoom(e){db(e);const t=encodeURIComponent(e.substring(1));return this._organizationApiClient.request(`/room/${t}`,{method:"DELETE"}).then((()=>{}))}renameRoom({roomName:e,newRoomName:t}){db(e),cb(t,"newRoomName");const i=encodeURIComponent(e.substring(1));return this._organizationApiClient.request(`/room/${i}/roomName`,{method:"PUT",data:{newRoomName:t}}).then((()=>{}))}changeMode({roomName:e,mode:t}){db(e),cb(t,"mode");const i=encodeURIComponent(e.substring(1));return this._organizationApiClient.request(`/room/${i}/mode`,{method:"PUT",data:{mode:t}}).then((()=>{}))}updatePreferences({roomName:e,preferences:t}){db(e),pb(t,Object,"preferences");const i=encodeURIComponent(e.substring(1));return this._organizationApiClient.request(`/room/${i}/preferences`,{method:"PATCH",data:t}).then((()=>{}))}updateProtectedPreferences({roomName:e,preferences:t}){db(e),pb(t,Object,"preferences");const i=encodeURIComponent(e.substring(1));return this._organizationApiClient.request(`/room/${i}/protected-preferences`,{method:"PATCH",data:t}).then((()=>{}))}getRoomPermissions(e,{roomKey:t}={}){return db(e),this._organizationApiClient.request(Wb(e,"/permissions"),Object.assign({method:"GET"},t&&{headers:{"X-Whereby-Room-Key":t}})).then((e=>{const{permissions:t,limits:i}=e.data;return{permissions:t,limits:i}}))}getRoomMetrics({roomName:e,metrics:t,from:i,to:n}){return db(e),cb(t,"metrics"),this._organizationApiClient.request(Wb(e,"/metrics"),{method:"GET",params:{metrics:t,from:i,to:n}}).then((e=>e.data))}changeType({roomName:e,type:t}){db(e),function(e,t,i){if(ab(e,"value"),lb(t,"allowedValues"),!t.includes(e))throw new Error(`${i}<string> must be one of the following: ${t.join(", ")}`)}(t,["personal","personal_xl"],"type");const i=encodeURIComponent(e.substring(1));return this._organizationApiClient.request(`/room/${i}/type`,{method:"PUT",data:{type:t}}).then((()=>{}))}getForestSocialImage({roomName:e,count:t}){return db(e),ob(t,"count"),this._organizationApiClient.request(Wb(e,`/forest-social-image/${t}`),{method:"GET"}).then((e=>e.data.imageUrl))}}class Hb{constructor({displayName:e,id:t,stream:i,isAudioEnabled:n,isVideoEnabled:s}){this.isLocalParticipant=!1,this.displayName=e,this.id=t,this.stream=i,this.isAudioEnabled=n,this.isVideoEnabled=s}}class Kb extends Hb{constructor({displayName:e,id:t,newJoiner:i,streams:n,isAudioEnabled:s,isVideoEnabled:a}){super({displayName:e,id:t,isAudioEnabled:s,isVideoEnabled:a}),this.newJoiner=i,this.streams=n.map((e=>({id:e,state:i?"new_accept":"to_accept"})))}updateStreamState(e,t){const i=this.streams.find((t=>t.id===e));i&&(i.state=t)}}class Jb extends Hb{constructor({displayName:e,id:t,stream:i,isAudioEnabled:n,isVideoEnabled:s}){super({displayName:e,id:t,stream:i,isAudioEnabled:n,isVideoEnabled:s}),this.isLocalParticipant=!0}}const Qb=process.env.REACT_APP_API_BASE_URL||"https://api.whereby.dev",Yb=process.env.REACT_APP_SIGNAL_BASE_URL||"wss://signal.appearin.net",Xb=["recorder","streamer"];const Zb=()=>{},e_=EventTarget;class t_ extends e_{constructor(e,{displayName:t,localMedia:i,localMediaConstraints:n,logger:s,roomKey:a}){super(),this.localParticipant=null,this.remoteParticipants=[],this._ownsLocalMedia=!1,this.organizationId="",this.roomConnectionStatus="",this.selfId=null,this.roomUrl=new URL(e);const r=new URLSearchParams(this.roomUrl.search);this._roomKey=a||r.get("roomKey"),this.roomName=this.roomUrl.pathname,this.logger=s||{debug:Zb,error:Zb,log:Zb,warn:Zb},this.displayName=t,this.localMediaConstraints=n;const o=Gh({host:this.roomUrl.host});if(i)this.localMedia=i;else{if(!n)throw new Error("Missing constraints");this.localMedia=new fi(n),this._ownsLocalMedia=!0}this.credentialsService=jb.create({baseUrl:Qb}),this.apiClient=new yb({fetchDeviceCredentials:this.credentialsService.getCredentials.bind(this.credentialsService),baseUrl:Qb}),this.organizationService=new zb({apiClient:this.apiClient}),this.organizationServiceCache=new qb({organizationService:this.organizationService,subdomain:o.subdomain}),this.organizationApiClient=new Mb({apiClient:this.apiClient,fetchOrganization:()=>Zt(this,void 0,void 0,(function*(){return(yield this.organizationServiceCache.fetchOrganization())||void 0}))}),this.roomService=new Gb({organizationApiClient:this.organizationApiClient}),this.signalSocket=function(){const e=new URL(Yb),t=`${e.pathname.replace(/^\/$/,"")}/protocol/socket.io/v4`,i=e.origin;return new po(i,{autoConnect:!1,host:i,path:t,reconnectionDelay:5e3,reconnectionDelayMax:3e4,timeout:1e4,withCredentials:!0})}(),this.signalSocket.on("new_client",this._handleNewClient.bind(this)),this.signalSocket.on("chat_message",this._handleNewChatMessage.bind(this)),this.signalSocket.on("client_left",this._handleClientLeft.bind(this)),this.signalSocket.on("audio_enabled",this._handleClientAudioEnabled.bind(this)),this.signalSocket.on("video_enabled",this._handleClientVideoEnabled.bind(this)),this.signalSocket.on("client_metadata_received",this._handleClientMetadataReceived.bind(this)),this.signalSocket.on("knock_handled",this._handleKnockHandled.bind(this)),this.signalSocket.on("knocker_left",this._handleKnockerLeft.bind(this)),this.signalSocket.on("room_joined",this._handleRoomJoined.bind(this)),this.signalSocket.on("room_knocked",this._handleRoomKnocked.bind(this)),this.localMedia.addEventListener("camera_enabled",(e=>{const{enabled:t}=e.detail;this.signalSocket.emit("enable_video",{enabled:t})})),this.localMedia.addEventListener("microphone_enabled",(e=>{const{enabled:t}=e.detail;this.signalSocket.emit("enable_audio",{enabled:t})}));const c={getMediaConstraints:()=>({audio:this.localMedia.isMicrophoneEnabled(),video:this.localMedia.isCameraEnabled()}),deferrable:e=>!e};this.rtcManagerDispatcher=new Vh({emitter:{emit:this._handleRtcEvent.bind(this)},serverSocket:this.signalSocket,webrtcProvider:c,features:{lowDataModeEnabled:!1,sfuServerOverrideHost:void 0,turnServerOverrideHost:void 0,useOnlyTURN:void 0,vp9On:!1,h264On:!1,simulcastScreenshareOn:!1}})}get roomKey(){return this._roomKey}_handleNewChatMessage(e){this.dispatchEvent(new CustomEvent("chat_message",{detail:e}))}_handleNewClient({client:e}){if(Xb.includes(e.role.roleName))return;const t=new Kb(Object.assign(Object.assign({},e),{newJoiner:!0}));this.remoteParticipants=[...this.remoteParticipants,t],this._handleAcceptStreams([t]),this.dispatchEvent(new CustomEvent("participant_joined",{detail:{remoteParticipant:t}}))}_handleClientLeft({clientId:e}){const t=this.remoteParticipants.find((t=>t.id===e));this.remoteParticipants=this.remoteParticipants.filter((t=>t.id!==e)),t&&this.dispatchEvent(new CustomEvent("participant_left",{detail:{participantId:t.id}}))}_handleClientAudioEnabled({clientId:e,isAudioEnabled:t}){const i=this.remoteParticipants.find((t=>t.id===e));i&&this.dispatchEvent(new CustomEvent("participant_audio_enabled",{detail:{participantId:i.id,isAudioEnabled:t}}))}_handleClientVideoEnabled({clientId:e,isVideoEnabled:t}){const i=this.remoteParticipants.find((t=>t.id===e));i&&this.dispatchEvent(new CustomEvent("participant_video_enabled",{detail:{participantId:i.id,isVideoEnabled:t}}))}_handleClientMetadataReceived({payload:{clientId:e,displayName:t}}){const i=this.remoteParticipants.find((t=>t.id===e));i&&this.dispatchEvent(new CustomEvent("participant_metadata_changed",{detail:{participantId:i.id,displayName:t}}))}_handleKnockHandled(e){const{clientId:t,resolution:i}=e;t===this.selfId&&("accepted"===i?(this.roomConnectionStatus="accepted",this._roomKey=e.metadata.roomKey,this._joinRoom()):"rejected"===i&&(this.roomConnectionStatus="rejected",this.dispatchEvent(new CustomEvent("room_connection_status_changed",{detail:{roomConnectionStatus:this.roomConnectionStatus}}))))}_handleKnockerLeft(e){const{clientId:t}=e;this.dispatchEvent(new CustomEvent("waiting_participant_left",{detail:{participantId:t}}))}_handleRoomJoined(e){const{error:t,isLocked:i,room:n,selfId:s}=e;if(this.selfId=s,"room_locked"===t&&i)return this.roomConnectionStatus="room_locked",void this.dispatchEvent(new CustomEvent("room_connection_status_changed",{detail:{roomConnectionStatus:this.roomConnectionStatus}}));if(n){const{clients:e,knockers:t}=n,i=e.find((e=>e.id===s));if(!i)throw new Error("Missing local client");this.localParticipant=new Jb(Object.assign(Object.assign({},i),{stream:this.localMedia.stream||void 0})),this.remoteParticipants=e.filter((e=>e.id!==s)).map((e=>new Kb(Object.assign(Object.assign({},e),{newJoiner:!1})))),this.roomConnectionStatus="connected",this.dispatchEvent(new CustomEvent("room_joined",{detail:{localParticipant:this.localParticipant,remoteParticipants:this.remoteParticipants,waitingParticipants:t.map((e=>({id:e.clientId,displayName:e.displayName})))}}))}}_handleRoomKnocked(e){const{clientId:t,displayName:i}=e;this.dispatchEvent(new CustomEvent("waiting_participant_joined",{detail:{participantId:t,displayName:i}}))}_handleRtcEvent(e,t){return"rtc_manager_created"===e?this._handleRtcManagerCreated(t):"stream_added"===e?this._handleStreamAdded(t):void this.logger.log(`Unhandled RTC event ${e}`)}_handleRtcManagerCreated({rtcManager:e}){var t;this.rtcManager=e,this.localMedia.addRtcManager(e),this.localMedia.stream&&(null===(t=this.rtcManager)||void 0===t||t.addNewStream("0",this.localMedia.stream,!this.localMedia.isMicrophoneEnabled(),!this.localMedia.isCameraEnabled())),this.remoteParticipants.length&&this._handleAcceptStreams(this.remoteParticipants)}_handleAcceptStreams(e){var t,i;if(!this.rtcManager)return void this.logger.log("Unable to accept streams, no rtc manager");const n=null===(i=(t=this.rtcManager).shouldAcceptStreamsFromBothSides)||void 0===i?void 0:i.call(t);e.forEach((e=>{const{id:t,streams:i,newJoiner:s}=e;i.forEach((i=>{var a,r;const{id:o,state:c}=i;let p;if("done_accept"!==c&&(p=(s&&"0"===o?"new":"to")+"_accept"),p){if("to_accept"===p||"new_accept"===p&&n||"old_accept"===p&&!n)this.logger.log(`Accepting stream ${o} from ${t}`),null===(a=this.rtcManager)||void 0===a||a.acceptNewStream({streamId:"0"===o?t:o,clientId:t,shouldAddLocalVideo:"0"===o,activeBreakout:false});else if("new_accept"===p||"old_accept"===p);else if("to_unaccept"===p)this.logger.log(`Disconnecting stream ${o} from ${t}`),null===(r=this.rtcManager)||void 0===r||r.disconnect("0"===o?t:o,false);else if("done_accept"!==p)return void this.logger.warn(`Stream state not handled: ${p} for ${t}-${o}`);e.updateStreamState(o,c.replace(/to_|new_|old_/,"done_"))}}))}))}_handleStreamAdded({clientId:e,stream:t,streamId:i}){this.remoteParticipants.find((t=>t.id===e))?this.dispatchEvent(new CustomEvent("participant_stream_added",{detail:{participantId:e,stream:t,streamId:i}})):this.logger.log("WARN: Could not find participant for incoming stream")}_joinRoom(){this.signalSocket.emit("join_room",{avatarUrl:null,config:{isAudioEnabled:this.localMedia.isMicrophoneEnabled(),isVideoEnabled:this.localMedia.isCameraEnabled()},deviceCapabilities:{canScreenshare:!0},displayName:this.displayName,isCoLocated:!1,isDevicePermissionDenied:!1,kickFromOtherRooms:!1,organizationId:this.organizationId,roomKey:this.roomKey,roomName:this.roomName,selfId:"",userAgent:`browser-sdk:${r_}`})}join(){return Zt(this,void 0,void 0,(function*(){if(["connected","connecting"].includes(this.roomConnectionStatus))return void console.warn(`Trying to join when room state is already ${this.roomConnectionStatus}`);this.logger.log("Joining room"),this.signalSocket.connect(),this.roomConnectionStatus="connecting",this.dispatchEvent(new CustomEvent("room_connection_status_changed",{detail:{roomConnectionStatus:this.roomConnectionStatus}}));const e=yield this.organizationServiceCache.fetchOrganization();if(!e)throw new Error("Invalid room url");this.organizationId=e.organizationId,this._ownsLocalMedia&&(yield this.localMedia.start());const t=yield this.credentialsService.getCredentials();this.logger.log("Connected to signal socket"),this.signalSocket.emit("identify_device",{deviceCredentials:t}),this.signalSocket.once("device_identified",(()=>{this._joinRoom()}))}))}knock(){this.roomConnectionStatus="knocking",this.dispatchEvent(new CustomEvent("room_connection_status_changed",{detail:{roomConnectionStatus:this.roomConnectionStatus}})),this.signalSocket.emit("knock_room",{displayName:this.displayName,imageUrl:null,kickFromOtherRooms:!0,liveVideo:!1,organizationId:this.organizationId,roomKey:this._roomKey,roomName:this.roomName})}leave(){this.roomConnectionStatus="disconnecting",this._ownsLocalMedia&&this.localMedia.stop(),this.rtcManager&&(this.localMedia.removeRtcManager(this.rtcManager),this.rtcManager.disconnectAll(),this.rtcManager=void 0),this.signalSocket&&(this.signalSocket.emit("leave_room"),this.signalSocket.disconnect(),this.roomConnectionStatus="disconnected")}sendChatMessage(e){this.signalSocket.emit("chat_message",{text:e})}setDisplayName(e){this.signalSocket.emit("send_client_metadata",{type:"UserData",payload:{displayName:e}})}acceptWaitingParticipant(e){this.signalSocket.emit("handle_knock",{action:"accept",clientId:e,response:{}})}rejectWaitingParticipant(e){this.signalSocket.emit("handle_knock",{action:"reject",clientId:e,response:{}})}}const i_={chatMessages:[],roomConnectionStatus:"",isJoining:!1,joinError:null,mostRecentChatMessage:null,remoteParticipants:[],waitingParticipants:[]};function n_(e,t,i){const n=e.find((e=>e.id===t));if(!n)return e;const s=e.indexOf(n);return[...e.slice(0,s),Object.assign(Object.assign({},n),i),...e.slice(s+1)]}function s_(e,t){switch(t.type){case"CHAT_MESSAGE":return Object.assign(Object.assign({},e),{chatMessages:[...e.chatMessages,t.payload],mostRecentChatMessage:t.payload});case"ROOM_JOINED":return Object.assign(Object.assign({},e),{localParticipant:t.payload.localParticipant,remoteParticipants:t.payload.remoteParticipants,waitingParticipants:t.payload.waitingParticipants,roomConnectionStatus:"connected"});case"ROOM_CONNECTION_STATUS_CHANGED":return Object.assign(Object.assign({},e),{roomConnectionStatus:t.payload.roomConnectionStatus});case"PARTICIPANT_AUDIO_ENABLED":return Object.assign(Object.assign({},e),{remoteParticipants:n_(e.remoteParticipants,t.payload.participantId,{isAudioEnabled:t.payload.isAudioEnabled})});case"PARTICIPANT_JOINED":return Object.assign(Object.assign({},e),{remoteParticipants:[...e.remoteParticipants,t.payload.paritipant]});case"PARTICIPANT_LEFT":return Object.assign(Object.assign({},e),{remoteParticipants:[...e.remoteParticipants.filter((e=>e.id!==t.payload.participantId))]});case"PARTICIPANT_STREAM_ADDED":return Object.assign(Object.assign({},e),{remoteParticipants:n_(e.remoteParticipants,t.payload.participantId,{stream:t.payload.stream})});case"PARTICIPANT_VIDEO_ENABLED":return Object.assign(Object.assign({},e),{remoteParticipants:n_(e.remoteParticipants,t.payload.participantId,{isVideoEnabled:t.payload.isVideoEnabled})});case"PARTICIPANT_METADATA_CHANGED":return Object.assign(Object.assign({},e),{remoteParticipants:[...e.remoteParticipants.map((e=>e.id===t.payload.participantId?Object.assign(Object.assign({},e),{displayName:t.payload.displayName}):e))]});case"LOCAL_CLIENT_DISPLAY_NAME_CHANGED":return e.localParticipant?Object.assign(Object.assign({},e),{localParticipant:Object.assign(Object.assign({},e.localParticipant),{displayName:t.payload.displayName})}):e;case"WAITING_PARTICIPANT_JOINED":return Object.assign(Object.assign({},e),{waitingParticipants:[...e.waitingParticipants,{id:t.payload.participantId,displayName:t.payload.displayName}]});case"WAITING_PARTICIPANT_LEFT":return Object.assign(Object.assign({},e),{waitingParticipants:e.waitingParticipants.filter((e=>e.id!==t.payload.participantId))});default:throw e}}function a_(e,t){const[i]=si.useState((()=>{var i;return new t_(e,Object.assign(Object.assign({},t),{localMedia:(null===(i=null==t?void 0:t.localMedia)||void 0===i?void 0:i._ref)||void 0}))})),[n,s]=si.useReducer(s_,i_);return si.useEffect((()=>(i.addEventListener("chat_message",(e=>{const t=e.detail;s({type:"CHAT_MESSAGE",payload:t})})),i.addEventListener("participant_audio_enabled",(e=>{const{participantId:t,isAudioEnabled:i}=e.detail;s({type:"PARTICIPANT_AUDIO_ENABLED",payload:{participantId:t,isAudioEnabled:i}})})),i.addEventListener("participant_joined",(e=>{const{remoteParticipant:t}=e.detail;s({type:"PARTICIPANT_JOINED",payload:{paritipant:t}})})),i.addEventListener("participant_left",(e=>{const{participantId:t}=e.detail;s({type:"PARTICIPANT_LEFT",payload:{participantId:t}})})),i.addEventListener("participant_stream_added",(e=>{const{participantId:t,stream:i}=e.detail;s({type:"PARTICIPANT_STREAM_ADDED",payload:{participantId:t,stream:i}})})),i.addEventListener("room_connection_status_changed",(e=>{const{roomConnectionStatus:t}=e.detail;s({type:"ROOM_CONNECTION_STATUS_CHANGED",payload:{roomConnectionStatus:t}})})),i.addEventListener("room_joined",(e=>{const{localParticipant:t,remoteParticipants:i,waitingParticipants:n}=e.detail;s({type:"ROOM_JOINED",payload:{localParticipant:t,remoteParticipants:i,waitingParticipants:n}})})),i.addEventListener("participant_video_enabled",(e=>{const{participantId:t,isVideoEnabled:i}=e.detail;s({type:"PARTICIPANT_VIDEO_ENABLED",payload:{participantId:t,isVideoEnabled:i}})})),i.addEventListener("participant_metadata_changed",(e=>{const{participantId:t,displayName:i}=e.detail;s({type:"PARTICIPANT_METADATA_CHANGED",payload:{participantId:t,displayName:i}})})),i.addEventListener("waiting_participant_joined",(e=>{const{participantId:t,displayName:i}=e.detail;s({type:"WAITING_PARTICIPANT_JOINED",payload:{participantId:t,displayName:i}})})),i.addEventListener("waiting_participant_left",(e=>{const{participantId:t}=e.detail;s({type:"WAITING_PARTICIPANT_LEFT",payload:{participantId:t}})})),i.join(),()=>{i.leave()})),[]),{state:n,actions:{knock:()=>{i.knock()},sendChatMessage:e=>{i.sendChatMessage(e)},setDisplayName:e=>{i.setDisplayName(e),s({type:"LOCAL_CLIENT_DISPLAY_NAME_CHANGED",payload:{displayName:e}})},toggleCamera:e=>{i.localMedia.toggleCameraEnabled(e)},toggleMicrophone:e=>{i.localMedia.toggleMichrophoneEnabled(e)},acceptWaitingParticipant:e=>{i.acceptWaitingParticipant(e)},rejectWaitingParticipant:e=>{i.rejectWaitingParticipant(e)}},components:{VideoView:mi},_ref:i}}const r_="2.0.0-alpha14";export{mi as VideoView,r_ as sdkVersion,bi as useLocalMedia,a_ as useRoomConnection};