!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).firebase=t()}(this,function(){"use strict";!function(e){var t,n,o,r,i,s,a,c,l,u;function h(e){if("string"!=typeof e&&(e=String(e)),/[^a-z0-9\-#$%&'*+.\^_`|~]/i.test(e))throw new TypeError("Invalid character in header field name");return e.toLowerCase()}function d(e){return e="string"!=typeof e?String(e):e}function p(t){var e={next:function(){var e=t.shift();return{done:void 0===e,value:e}}};return n&&(e[Symbol.iterator]=function(){return e}),e}function f(t){this.map={},t instanceof f?t.forEach(function(e,t){this.append(t,e)},this):Array.isArray(t)?t.forEach(function(e){this.append(e[0],e[1])},this):t&&Object.getOwnPropertyNames(t).forEach(function(e){this.append(e,t[e])},this)}function g(e){if(e.bodyUsed)return Promise.reject(new TypeError("Already read"));e.bodyUsed=!0}function m(n){return new Promise(function(e,t){n.onload=function(){e(n.result)},n.onerror=function(){t(n.error)}})}function v(e){var t=new FileReader,n=m(t);return t.readAsArrayBuffer(e),n}function y(e){if(e.slice)return e.slice(0);var t=new Uint8Array(e.byteLength);return t.set(new Uint8Array(e)),t.buffer}function _(){return this.bodyUsed=!1,this._initBody=function(e){if(this._bodyInit=e)if("string"==typeof e)this._bodyText=e;else if(o&&Blob.prototype.isPrototypeOf(e))this._bodyBlob=e;else if(r&&FormData.prototype.isPrototypeOf(e))this._bodyFormData=e;else if(t&&URLSearchParams.prototype.isPrototypeOf(e))this._bodyText=e.toString();else if(i&&o&&a(e))this._bodyArrayBuffer=y(e.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer]);else{if(!i||!ArrayBuffer.prototype.isPrototypeOf(e)&&!c(e))throw new Error("unsupported BodyInit type");this._bodyArrayBuffer=y(e)}else this._bodyText="";this.headers.get("content-type")||("string"==typeof e?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):t&&URLSearchParams.prototype.isPrototypeOf(e)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},o&&(this.blob=function(){var e=g(this);if(e)return e;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))},this.arrayBuffer=function(){return this._bodyArrayBuffer?g(this)||Promise.resolve(this._bodyArrayBuffer):this.blob().then(v)}),this.text=function(){var e,t,n=g(this);if(n)return n;if(this._bodyBlob)return e=this._bodyBlob,t=new FileReader,n=m(t),t.readAsText(e),n;if(this._bodyArrayBuffer)return Promise.resolve(function(e){for(var t=new Uint8Array(e),n=new Array(t.length),r=0;r<t.length;r++)n[r]=String.fromCharCode(t[r]);return n.join("")}(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},r&&(this.formData=function(){return this.text().then(b)}),this.json=function(){return this.text().then(JSON.parse)},this}function w(e,t){var n,r=(t=t||{}).body;if(e instanceof w){if(e.bodyUsed)throw new TypeError("Already read");this.url=e.url,this.credentials=e.credentials,t.headers||(this.headers=new f(e.headers)),this.method=e.method,this.mode=e.mode,r||null==e._bodyInit||(r=e._bodyInit,e.bodyUsed=!0)}else this.url=String(e);if(this.credentials=t.credentials||this.credentials||"omit",!t.headers&&this.headers||(this.headers=new f(t.headers)),this.method=(e=t.method||this.method||"GET",n=e.toUpperCase(),-1<l.indexOf(n)?n:e),this.mode=t.mode||this.mode||null,this.referrer=null,("GET"===this.method||"HEAD"===this.method)&&r)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(r)}function b(e){var r=new FormData;return e.trim().split("&").forEach(function(e){var t,n;e&&(t=(n=e.split("=")).shift().replace(/\+/g," "),n=n.join("=").replace(/\+/g," "),r.append(decodeURIComponent(t),decodeURIComponent(n)))}),r}function I(e,t){t=t||{},this.type="default",this.status=void 0===t.status?200:t.status,this.ok=200<=this.status&&this.status<300,this.statusText="statusText"in t?t.statusText:"OK",this.headers=new f(t.headers),this.url=t.url||"",this._initBody(e)}e.fetch||(t="URLSearchParams"in e,n="Symbol"in e&&"iterator"in Symbol,o="FileReader"in e&&"Blob"in e&&function(){try{return new Blob,!0}catch(e){return!1}}(),r="FormData"in e,(i="ArrayBuffer"in e)&&(s=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],a=function(e){return e&&DataView.prototype.isPrototypeOf(e)},c=ArrayBuffer.isView||function(e){return e&&-1<s.indexOf(Object.prototype.toString.call(e))}),f.prototype.append=function(e,t){e=h(e),t=d(t);var n=this.map[e];this.map[e]=n?n+","+t:t},f.prototype.delete=function(e){delete this.map[h(e)]},f.prototype.get=function(e){return e=h(e),this.has(e)?this.map[e]:null},f.prototype.has=function(e){return this.map.hasOwnProperty(h(e))},f.prototype.set=function(e,t){this.map[h(e)]=d(t)},f.prototype.forEach=function(e,t){for(var n in this.map)this.map.hasOwnProperty(n)&&e.call(t,this.map[n],n,this)},f.prototype.keys=function(){var n=[];return this.forEach(function(e,t){n.push(t)}),p(n)},f.prototype.values=function(){var t=[];return this.forEach(function(e){t.push(e)}),p(t)},f.prototype.entries=function(){var n=[];return this.forEach(function(e,t){n.push([t,e])}),p(n)},n&&(f.prototype[Symbol.iterator]=f.prototype.entries),l=["DELETE","GET","HEAD","OPTIONS","POST","PUT"],w.prototype.clone=function(){return new w(this,{body:this._bodyInit})},_.call(w.prototype),_.call(I.prototype),I.prototype.clone=function(){return new I(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new f(this.headers),url:this.url})},I.error=function(){var e=new I(null,{status:0,statusText:""});return e.type="error",e},u=[301,302,303,307,308],I.redirect=function(e,t){if(-1===u.indexOf(t))throw new RangeError("Invalid status code");return new I(null,{status:t,headers:{location:e}})},e.Headers=f,e.Request=w,e.Response=I,e.fetch=function(n,r){return new Promise(function(i,e){var t=new w(n,r),s=new XMLHttpRequest;s.onload=function(){var e,r,t={status:s.status,statusText:s.statusText,headers:(e=s.getAllResponseHeaders()||"",r=new f,e.replace(/\r?\n[\t ]+/g," ").split(/\r?\n/).forEach(function(e){var t=e.split(":"),n=t.shift().trim();n&&(t=t.join(":").trim(),r.append(n,t))}),r)};t.url="responseURL"in s?s.responseURL:t.headers.get("X-Request-URL");var n="response"in s?s.response:s.responseText;i(new I(n,t))},s.onerror=function(){e(new TypeError("Network request failed"))},s.ontimeout=function(){e(new TypeError("Network request failed"))},s.open(t.method,t.url,!0),"include"===t.credentials?s.withCredentials=!0:"omit"===t.credentials&&(s.withCredentials=!1),"responseType"in s&&o&&(s.responseType="blob"),t.headers.forEach(function(e,t){s.setRequestHeader(t,e)}),s.send(void 0===t._bodyInit?null:t._bodyInit)})},e.fetch.polyfill=!0)}("undefined"!=typeof self?self:void 0);function e(e){try{return!!e()}catch(e){return!0}}function t(e){if(!g(e))throw TypeError(String(e)+" is not an object");return e}var n="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},r=function(e){return e&&e.Math==Math&&e},i=r("object"==typeof globalThis&&globalThis)||r("object"==typeof window&&window)||r("object"==typeof self&&self)||r("object"==typeof n&&n)||Function("return this")(),s={exports:{}},o=!e(function(){return 7!=Object.defineProperty({},1,{get:function(){return 7}})[1]}),a={},c=function(e){return"object"==typeof e?null!==e:"function"==typeof e},l=c,u=i.document,h=l(u)&&l(u.createElement),d=function(e){return h?u.createElement(e):{}},p=d,f=!o&&!e(function(){return 7!=Object.defineProperty(p("div"),"a",{get:function(){return 7}}).a}),g=c,m=c,v=function(e,t){if(!m(e))return e;var n,r;if(t&&"function"==typeof(n=e.toString)&&!m(r=n.call(e)))return r;if("function"==typeof(n=e.valueOf)&&!m(r=n.call(e)))return r;if(!t&&"function"==typeof(n=e.toString)&&!m(r=n.call(e)))return r;throw TypeError("Can't convert object to primitive value")},y=f,_=t,w=v,b=Object.defineProperty;a.f=o?b:function(e,t,n){if(_(e),t=w(t,!0),_(n),y)try{return b(e,t,n)}catch(e){}if("get"in n||"set"in n)throw TypeError("Accessors not supported");return"value"in n&&(e[t]=n.value),e};var I=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}},T=a,E=I,k=o?function(e,t,n){return T.f(e,t,E(1,n))}:function(e,t,n){return e[t]=n,e},S=i,C=k,A=function(t,n){try{C(S,t,n)}catch(e){S[t]=n}return n},N=A,R="__core-js_shared__",P=i[R]||N(R,{}),x=P;(s.exports=function(e,t){return x[e]||(x[e]=void 0!==t?t:{})})("versions",[]).push({version:"3.6.5",mode:"global",copyright:"© 2020 Denis Pushkarev (zloirock.ru)"});function O(e,t){return L.call(e,t)}function D(e){return"Symbol("+String(void 0===e?"":e)+")_"+(++M+F).toString(36)}var L={}.hasOwnProperty,M=0,F=Math.random(),U=e,j=!!Object.getOwnPropertySymbols&&!U(function(){return!String(Symbol())}),q=j&&!Symbol.sham&&"symbol"==typeof Symbol.iterator,V=i,B=s.exports,W=O,z=D,K=j,$=q,H=B("wks"),G=V.Symbol,Q=$?G:G&&G.withoutSetter||z,Y=function(e){return W(H,e)||(K&&W(G,e)?H[e]=G[e]:H[e]=Q("Symbol."+e)),H[e]},X={};X[Y("toStringTag")]="z";var J="[object z]"===String(X),Z={exports:{}},ee=P,te=Function.toString;"function"!=typeof ee.inspectSource&&(ee.inspectSource=function(e){return te.call(e)});var ne,re,ie,se,oe,ae,ce,le,ue=ee.inspectSource,he=ue,de=i.WeakMap,pe="function"==typeof de&&/native code/.test(he(de)),fe=s.exports,ge=D,me=fe("keys"),ve=function(e){return me[e]||(me[e]=ge(e))},ye={},_e=c,we=k,be=O,Ie=ve,Te=ye,Ee=i.WeakMap;ce=pe?(ne=new Ee,re=ne.get,ie=ne.has,se=ne.set,oe=function(e,t){return se.call(ne,e,t),t},ae=function(e){return re.call(ne,e)||{}},function(e){return ie.call(ne,e)}):(Te[le=Ie("state")]=!0,oe=function(e,t){return we(e,le,t),t},ae=function(e){return be(e,le)?e[le]:{}},function(e){return be(e,le)});var ke={set:oe,get:ae,has:ce,enforce:function(e){return ce(e)?ae(e):oe(e,{})},getterFor:function(n){return function(e){var t;if(!_e(e)||(t=ae(e)).type!==n)throw TypeError("Incompatible receiver, "+n+" required");return t}}},Se=i,Ce=k,Ae=O,Ne=A,Re=ue,Pe=ke.get,xe=ke.enforce,Oe=String(String).split("String");(Z.exports=function(e,t,n,r){var i=!!r&&!!r.unsafe,s=!!r&&!!r.enumerable,o=!!r&&!!r.noTargetGet;"function"==typeof n&&("string"!=typeof t||Ae(n,"name")||Ce(n,"name",t),xe(n).source=Oe.join("string"==typeof t?t:"")),e!==Se?(i?!o&&e[t]&&(s=!0):delete e[t],s?e[t]=n:Ce(e,t,n)):s?e[t]=n:Ne(t,n)})(Function.prototype,"toString",function(){return"function"==typeof this&&Pe(this).source||Re(this)});var De={}.toString,Le=function(e){return De.call(e).slice(8,-1)},Me=J,Fe=Le,Ue=Y("toStringTag"),je="Arguments"==Fe(function(){return arguments}()),qe=Me?Fe:function(e){var t,n;return void 0===e?"Undefined":null===e?"Null":"string"==typeof(n=function(e,t){try{return e[t]}catch(e){}}(t=Object(e),Ue))?n:je?Fe(t):"Object"==(n=Fe(t))&&"function"==typeof t.callee?"Arguments":n},Ve=qe,Be=Z.exports;J||Be(Object.prototype,"toString",J?{}.toString:function(){return"[object "+Ve(this)+"]"},{unsafe:!0});var We=Math.ceil,ze=Math.floor,Ke=function(e){return isNaN(e=+e)?0:(0<e?ze:We)(e)},$e=function(e){if(null==e)throw TypeError("Can't call method on "+e);return e},He=Ke,Ge=$e,Qe=function(a){return function(e,t){var n,r,i=String(Ge(e)),s=He(t),o=i.length;return s<0||o<=s?a?"":void 0:(n=i.charCodeAt(s))<55296||56319<n||s+1===o||(r=i.charCodeAt(s+1))<56320||57343<r?a?i.charAt(s):n:a?i.slice(s,s+2):r-56320+(n-55296<<10)+65536}},Ye={codeAt:Qe(!1),charAt:Qe(!0)},Xe={},Je={},Ze={}.propertyIsEnumerable,et=Object.getOwnPropertyDescriptor,tt=et&&!Ze.call({1:2},1);Je.f=tt?function(e){var t=et(this,e);return!!t&&t.enumerable}:Ze;function nt(e){return at(ct(e))}var rt=e,it=Le,st="".split,ot=rt(function(){return!Object("z").propertyIsEnumerable(0)})?function(e){return"String"==it(e)?st.call(e,""):Object(e)}:Object,at=ot,ct=$e,lt=Je,ut=I,ht=nt,dt=v,pt=O,ft=f,gt=Object.getOwnPropertyDescriptor;Xe.f=o?gt:function(e,t){if(e=ht(e),t=dt(t,!0),ft)try{return gt(e,t)}catch(e){}if(pt(e,t))return ut(!lt.f.call(e,t),e[t])};function mt(e){return"function"==typeof e?e:void 0}function vt(e,t){return arguments.length<2?mt(_t[e])||mt(wt[e]):_t[e]&&_t[e][t]||wt[e]&&wt[e][t]}var yt=i,_t=yt,wt=i,bt={},It=Ke,Tt=Math.min,Et=function(e){return 0<e?Tt(It(e),9007199254740991):0},kt=Ke,St=Math.max,Ct=Math.min,At=nt,Nt=Et,Rt=function(e,t){var n=kt(e);return n<0?St(n+t,0):Ct(n,t)},Pt=function(a){return function(e,t,n){var r,i=At(e),s=Nt(i.length),o=Rt(n,s);if(a&&t!=t){for(;o<s;)if((r=i[o++])!=r)return!0}else for(;o<s;o++)if((a||o in i)&&i[o]===t)return a||o||0;return!a&&-1}},r={includes:Pt(!0),indexOf:Pt(!1)},xt=O,Ot=nt,Dt=r.indexOf,Lt=ye,n=function(e,t){var n,r=Ot(e),i=0,s=[];for(n in r)!xt(Lt,n)&&xt(r,n)&&s.push(n);for(;t.length>i;)xt(r,n=t[i++])&&(~Dt(s,n)||s.push(n));return s},l=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],Mt=n,Ft=l.concat("length","prototype");bt.f=Object.getOwnPropertyNames||function(e){return Mt(e,Ft)};N={};N.f=Object.getOwnPropertySymbols;var Ut=bt,jt=N,qt=t,R=vt("Reflect","ownKeys")||function(e){var t=Ut.f(qt(e)),n=jt.f;return n?t.concat(n(e)):t},Vt=O,Bt=R,Wt=Xe,zt=a,U=function(e,t){for(var n=Bt(t),r=zt.f,i=Wt.f,s=0;s<n.length;s++){var o=n[s];Vt(e,o)||r(e,o,i(t,o))}},Kt=e,$t=/#|\.prototype\./,B=function(e,t){var n=Gt[Ht(e)];return n==Yt||n!=Qt&&("function"==typeof t?Kt(t):!!t)},Ht=B.normalize=function(e){return String(e).replace($t,".").toLowerCase()},Gt=B.data={},Qt=B.NATIVE="N",Yt=B.POLYFILL="P",V=B,Xt=i,Jt=Xe.f,Zt=k,en=Z.exports,tn=A,nn=U,rn=V,$=function(e,t){var n,r,i,s=e.target,o=e.global,a=e.stat,c=o?Xt:a?Xt[s]||tn(s,{}):(Xt[s]||{}).prototype;if(c)for(n in t){if(r=t[n],i=e.noTargetGet?(i=Jt(c,n))&&i.value:c[n],!rn(o?n:s+(a?".":"#")+n,e.forced)&&void 0!==i){if(typeof r==typeof i)continue;nn(r,i)}(e.sham||i&&i.sham)&&Zt(r,"sham",!0),en(c,n,r,e)}},sn=$e,z=function(e){return Object(sn(e))},X=!e(function(){function e(){}return e.prototype.constructor=null,Object.getPrototypeOf(new e)!==e.prototype}),on=O,an=z,P=X,cn=ve("IE_PROTO"),ln=Object.prototype,ee=P?Object.getPrototypeOf:function(e){return e=an(e),on(e,cn)?e[cn]:"function"==typeof e.constructor&&e instanceof e.constructor?e.constructor.prototype:e instanceof Object?ln:null},he=ee,de=k,fe=O,pe=Y("iterator"),Ee=!1;[].keys&&("next"in(or=[].keys())?(ar=he(he(or)))!==Object.prototype&&(Er=ar):Ee=!0),fe(Er=null==Er?{}:Er,pe)||de(Er,pe,function(){return this});function un(){}var hn,Te={IteratorPrototype:Er,BUGGY_SAFARI_ITERATORS:Ee},dn=n,pn=l,Ie=Object.keys||function(e){return dn(e,pn)},fn=a,gn=t,mn=Ie,Me=o?Object.defineProperties:function(e,t){gn(e);for(var n,r=mn(t),i=r.length,s=0;s<i;)fn.f(e,n=r[s++],t[n]);return e},Be=vt("document","documentElement"),vn=t,yn=Me,_n=l,J=ye,wn=Be,bn=d,In="prototype",Tn="script",En=ve("IE_PROTO"),kn=function(e){return"<"+Tn+">"+e+"</"+Tn+">"},Sn=function(){try{hn=document.domain&&new ActiveXObject("htmlfile")}catch(e){}var e,t;Sn=hn?function(e){e.write(kn("")),e.close();var t=e.parentWindow.Object;return e=null,t}(hn):(e=bn("iframe"),t="java"+Tn+":",e.style.display="none",wn.appendChild(e),e.src=String(t),(e=e.contentWindow.document).open(),e.write(kn("document.F=Object")),e.close(),e.F);for(var n=_n.length;n--;)delete Sn[In][_n[n]];return Sn()};J[En]=!0;function Cn(){return this}function An(){return this}var Qe=Object.create||function(e,t){var n;return null!==e?(un[In]=vn(e),n=new un,un[In]=null,n[En]=e):n=Sn(),void 0===t?n:yn(n,t)},Nn=a.f,Rn=O,Pn=Y("toStringTag"),tt=function(e,t,n){e&&!Rn(e=n?e:e.prototype,Pn)&&Nn(e,Pn,{configurable:!0,value:t})},Ze={},xn=Te.IteratorPrototype,On=Qe,Dn=I,Ln=tt,Mn=Ze,Fn=c,Un=t,jn=function(e){if(!Fn(e)&&null!==e)throw TypeError("Can't set "+String(e)+" as a prototype");return e},rt=Object.setPrototypeOf||("__proto__"in{}?function(){var n,r=!1,e={};try{(n=Object.getOwnPropertyDescriptor(Object.prototype,"__proto__").set).call(e,[]),r=e instanceof Array}catch(e){}return function(e,t){return Un(e),jn(t),r?n.call(e,t):e.__proto__=t,e}}():void 0),qn=$,Vn=function(e,t,n){var r=t+" Iterator";return e.prototype=On(xn,{next:Dn(1,n)}),Ln(e,r,!1),Mn[r]=Cn,e},Bn=ee,Wn=rt,zn=tt,Kn=k,$n=Z.exports,f=Y,Hn=Ze,Gn=Te.IteratorPrototype,Qn=Te.BUGGY_SAFARI_ITERATORS,Yn=f("iterator"),Xn="values",Jn="entries",Pt=function(e,t,n,r,i,s,o){Vn(n,t,r);function a(e){if(e===i&&f)return f;if(!Qn&&e in d)return d[e];switch(e){case"keys":case Xn:case Jn:return function(){return new n(this,e)}}return function(){return new n(this)}}var c,l,u=t+" Iterator",h=!1,d=e.prototype,p=d[Yn]||d["@@iterator"]||i&&d[i],f=!Qn&&p||a(i),g="Array"==t&&d.entries||p;if(g&&(g=Bn(g.call(new e)),Gn!==Object.prototype&&g.next&&(Bn(g)!==Gn&&(Wn?Wn(g,Gn):"function"!=typeof g[Yn]&&Kn(g,Yn,An)),zn(g,u,!0))),i==Xn&&p&&p.name!==Xn&&(h=!0,f=function(){return p.call(this)}),d[Yn]!==f&&Kn(d,Yn,f),Hn[t]=f,i)if(c={values:a(Xn),keys:s?f:a("keys"),entries:a(Jn)},o)for(l in c)!Qn&&!h&&l in d||$n(d,l,c[l]);else qn({target:t,proto:!0,forced:Qn||h},c);return c},Zn=Ye.charAt,r=ke,R=Pt,er="String Iterator",tr=r.set,nr=r.getterFor(er);R(String,"String",function(e){tr(this,{type:er,string:String(e),index:0})},function(){var e=nr(this),t=e.string,n=e.index;return n>=t.length?{value:void 0,done:!0}:(n=Zn(t,n),e.index+=n.length,{value:n,done:!1})});var B=Qe,A=a,rr=Y("unscopables"),ir=Array.prototype;null==ir[rr]&&A.f(ir,rr,{configurable:!0,value:B(null)});var X=function(e){ir[rr][e]=!0},sr=nt,P=X,he=Ze,or=ke,ar=Pt,cr="Array Iterator",lr=or.set,ur=or.getterFor(cr),fe=ar(Array,"Array",function(e,t){lr(this,{type:cr,target:sr(e),index:0,kind:t})},function(){var e=ur(this),t=e.target,n=e.kind,r=e.index++;return!t||r>=t.length?{value:e.target=void 0,done:!0}:"keys"==n?{value:r,done:!1}:"values"==n?{value:t[r],done:!1}:{value:[r,t[r]],done:!1}},"values");he.Arguments=he.Array,P("keys"),P("values"),P("entries");var hr,dr=i,pr={CSSRuleList:0,CSSStyleDeclaration:0,CSSValueList:0,ClientRectList:0,DOMRectList:0,DOMStringList:0,DOMTokenList:1,DataTransferItemList:0,FileList:0,HTMLAllCollection:0,HTMLCollection:0,HTMLFormElement:0,HTMLSelectElement:0,MediaList:0,MimeTypeArray:0,NamedNodeMap:0,NodeList:1,PaintRequestList:0,Plugin:0,PluginArray:0,SVGLengthList:0,SVGNumberList:0,SVGPathSegList:0,SVGPointList:0,SVGStringList:0,SVGTransformList:0,SourceBufferList:0,StyleSheetList:0,TextTrackCueList:0,TextTrackList:0,TouchList:0},fr=fe,gr=k,de=Y,mr=de("iterator"),vr=de("toStringTag"),yr=fr.values;for(hr in pr){var _r=dr[hr],wr=_r&&_r.prototype;if(wr){if(wr[mr]!==yr)try{gr(wr,mr,yr)}catch(fb){wr[mr]=yr}if(wr[vr]||gr(wr,vr,hr),pr[hr])for(var br in fr)if(wr[br]!==fr[br])try{gr(wr,br,fr[br])}catch(fb){wr[br]=fr[br]}}}function Ir(e,t){this.stopped=e,this.result=t}var pe=i.Promise,Tr=Z.exports,Er=function(e,t,n){for(var r in t)Tr(e,r,t[r],n);return e},kr=vt,Sr=a,Cr=o,Ar=Y("species"),Ee=function(e){var t=kr(e),n=Sr.f;Cr&&t&&!t[Ar]&&n(t,Ar,{configurable:!0,get:function(){return this}})},n=function(e){if("function"!=typeof e)throw TypeError(String(e)+" is not a function");return e},Me=function(e,t,n){if(!(e instanceof t))throw TypeError("Incorrect "+(n?n+" ":"")+"invocation");return e},l={exports:{}},Nr=Ze,Rr=Y("iterator"),Pr=Array.prototype,J=function(e){return void 0!==e&&(Nr.Array===e||Pr[Rr]===e)},xr=n,Te=function(r,i,e){if(xr(r),void 0===i)return r;switch(e){case 0:return function(){return r.call(i)};case 1:return function(e){return r.call(i,e)};case 2:return function(e,t){return r.call(i,e,t)};case 3:return function(e,t,n){return r.call(i,e,t,n)}}return function(){return r.apply(i,arguments)}},Or=qe,Dr=Ze,Lr=Y("iterator"),f=function(e){if(null!=e)return e[Lr]||e["@@iterator"]||Dr[Or(e)]},Mr=t,Ye=function(t,e,n,r){try{return r?e(Mr(n)[0],n[1]):e(n)}catch(e){var i=t.return;throw void 0!==i&&Mr(i.call(t)),e}},Fr=t,Ur=J,jr=Et,qr=Te,Vr=f,Br=Ye;(l.exports=function(e,t,n,r,i){var s,o,a,c,l,u,h,d=qr(t,n,r?2:1);if(i)s=e;else{if("function"!=typeof(o=Vr(e)))throw TypeError("Target is not iterable");if(Ur(o)){for(a=0,c=jr(e.length);a<c;a++)if((l=r?d(Fr(h=e[a])[0],h[1]):d(e[a]))&&l instanceof Ir)return l;return new Ir(!1)}s=o.call(e)}for(u=s.next;!(h=u.call(s)).done;)if("object"==typeof(l=Br(s,d,h.value,r))&&l&&l instanceof Ir)return l;return new Ir(!1)}).stop=function(e){return new Ir(!0,e)};var Wr=Y("iterator"),zr=!1;try{var Kr=0,$r={next:function(){return{done:!!Kr++}},return:function(){zr=!0}};$r[Wr]=function(){return this},Array.from($r,function(){throw 2})}catch(fb){}function Hr(e){return function(){ai(e)}}var Gr,r=function(e,t){if(!t&&!zr)return!1;var n=!1;try{var r={};r[Wr]=function(){return{next:function(){return{done:n=!0}}}},e(r)}catch(e){}return n},Qr=t,Yr=n,Xr=Y("species"),R=function(e,t){var n,r=Qr(e).constructor;return void 0===r||null==(n=Qr(r)[Xr])?t:Yr(n)},A=vt("navigator","userAgent")||"",B=/(iphone|ipod|ipad).*applewebkit/i.test(A),Jr=i,or=e,ar=Le,he=Te,Zr=Be,ei=d,P=B,ti=Jr.location,de=Jr.setImmediate,Ze=Jr.clearImmediate,ni=Jr.process,$r=Jr.MessageChannel,ri=Jr.Dispatch,ii=0,si={},oi="onreadystatechange",ai=function(e){var t;si.hasOwnProperty(e)&&(t=si[e],delete si[e],t())},Be=function(e){ai(e.data)},d=function(e){Jr.postMessage(e+"",ti.protocol+"//"+ti.host)};de&&Ze||(de=function(e){for(var t=[],n=1;n<arguments.length;)t.push(arguments[n++]);return si[++ii]=function(){("function"==typeof e?e:Function(e)).apply(void 0,t)},Gr(ii),ii},Ze=function(e){delete si[e]},"process"==ar(ni)?Gr=function(e){ni.nextTick(Hr(e))}:ri&&ri.now?Gr=function(e){ri.now(Hr(e))}:$r&&!P?(wi=(yi=new $r).port2,yi.port1.onmessage=Be,Gr=he(wi.postMessage,wi,1)):!Jr.addEventListener||"function"!=typeof postMessage||Jr.importScripts||or(d)||"file:"===ti.protocol?Gr=oi in ei("script")?function(e){Zr.appendChild(ei("script"))[oi]=function(){Zr.removeChild(this),ai(e)}}:function(e){setTimeout(Hr(e),0)}:(Gr=d,Jr.addEventListener("message",Be,!1)));var ci,li,ui,hi,di,pi,fi,gi,ar={set:de,clear:Ze},mi=i,P=Xe.f,$r=Le,vi=ar.set,yi=B,he=mi.MutationObserver||mi.WebKitMutationObserver,_i=mi.process,wi=mi.Promise,bi="process"==$r(_i),or=P(mi,"queueMicrotask"),d=or&&or.value;d||(ci=function(){var e,t;for(bi&&(e=_i.domain)&&e.exit();li;){t=li.fn,li=li.next;try{t()}catch(e){throw li?hi():ui=void 0,e}}ui=void 0,e&&e.enter()},hi=bi?function(){_i.nextTick(ci)}:he&&!yi?(di=!0,pi=document.createTextNode(""),new he(ci).observe(pi,{characterData:!0}),function(){pi.data=di=!di}):wi&&wi.resolve?(fi=wi.resolve(void 0),gi=fi.then,function(){gi.call(fi,ci)}):function(){vi.call(mi,ci)});function Ii(e){var n,r;this.promise=new e(function(e,t){if(void 0!==n||void 0!==r)throw TypeError("Bad Promise constructor");n=e,r=t}),this.resolve=Ti(n),this.reject=Ti(r)}var Be=d||function(e){var t={fn:e,next:void 0};ui&&(ui.next=t),li||(li=t,hi()),ui=t},de={},Ti=n;de.f=function(e){return new Ii(e)};var Ei=t,ki=c,Si=de,Ze=function(e,t){if(Ei(e),ki(t)&&t.constructor===e)return t;var n=Si.f(e);return(0,n.resolve)(t),n.promise},Ci=i,B=function(e){try{return{error:!1,value:e()}}catch(e){return{error:!0,value:e}}},$r=A,P=i.process,or=P&&P.versions,yi=or&&or.v8;yi?ji=(Mi=yi.split("."))[0]+Mi[1]:$r&&(!(Mi=$r.match(/Edge\/(\d+)/))||74<=Mi[1])&&(Mi=$r.match(/Chrome\/(\d+)/))&&(ji=Mi[1]);var Ai,Ni,Ri,Pi,he=ji&&+ji,wi=$,xi=i,d=vt,A=pe,P=Z.exports,or=Er,yi=tt,$r=Ee,Oi=c,Di=n,Li=Me,Mi=Le,Fi=ue,Ui=l.exports,ji=r,qi=R,Vi=ar.set,Bi=Be,Wi=Ze,zi=function(e,t){var n=Ci.console;n&&n.error&&(1===arguments.length?n.error(e):n.error(e,t))},ue=de,Ki=B,ar=ke,Be=V,$i=he,Hi=Y("species"),Gi="Promise",Qi=ar.get,Yi=ar.set,Xi=ar.getterFor(Gi),Ji=A,Zi=xi.TypeError,es=xi.document,ts=xi.process,ns=d("fetch"),rs=ue.f,is=rs,ss="process"==Mi(ts),os=!!(es&&es.createEvent&&xi.dispatchEvent),as="unhandledrejection",cs="rejectionhandled",ls=1,us=2,hs=1,ds=2,Be=Be(Gi,function(){if(!(Fi(Ji)!==String(Ji))){if(66===$i)return!0;if(!ss&&"function"!=typeof PromiseRejectionEvent)return!0}if(51<=$i&&/native code/.test(Ji))return!1;function e(e){e(function(){},function(){})}var t=Ji.resolve(1);return(t.constructor={})[Hi]=e,!(t.then(function(){})instanceof e)}),ji=Be||!ji(function(e){Ji.all(e).catch(function(){})}),ps=function(e){var t;return!(!Oi(e)||"function"!=typeof(t=e.then))&&t},fs=function(p,f,g){var m;f.notified||(f.notified=!0,m=f.reactions,Bi(function(){for(var r,i,e=f.value,t=f.state==ls,n=0;m.length>n;){var s,o,a,c=m[n++],l=t?c.ok:c.fail,u=c.resolve,h=c.reject,d=c.domain;try{l?(t||(f.rejection===ds&&function(e,t){Vi.call(xi,function(){if(ss)ts.emit("rejectionHandled",e);else gs(cs,e,t.value)})}(p,f),f.rejection=hs),!0===l?s=e:(d&&d.enter(),s=l(e),d&&(d.exit(),a=!0)),s===c.promise?h(Zi("Promise-chain cycle")):(o=ps(s))?o.call(s,u,h):u(s)):h(e)}catch(e){d&&!a&&d.exit(),h(e)}}f.reactions=[],f.notified=!1,g&&!f.rejection&&(r=p,i=f,Vi.call(xi,function(){var e,t=i.value,n=ms(i);if(n&&(e=Ki(function(){ss?ts.emit("unhandledRejection",t,r):gs(as,r,t)}),i.rejection=ss||ms(i)?ds:hs,e.error))throw e.value}))}))},gs=function(e,t,n){var r,i;os?((r=es.createEvent("Event")).promise=t,r.reason=n,r.initEvent(e,!1,!0),xi.dispatchEvent(r)):r={promise:t,reason:n},(i=xi["on"+e])?i(r):e===as&&zi("Unhandled promise rejection",n)},ms=function(e){return e.rejection!==hs&&!e.parent},vs=function(t,n,r,i){return function(e){t(n,r,e,i)}},ys=function(e,t,n,r){t.done||(t.done=!0,(t=r?r:t).value=n,t.state=us,fs(e,t,!0))},_s=function(n,r,e,t){if(!r.done){r.done=!0,t&&(r=t);try{if(n===e)throw Zi("Promise can't be resolved itself");var i=ps(e);i?Bi(function(){var t={done:!1};try{i.call(e,vs(_s,n,t,r),vs(ys,n,t,r))}catch(e){ys(n,t,e,r)}}):(r.value=e,r.state=ls,fs(n,r,!1))}catch(e){ys(n,{done:!1},e,r)}}};Be&&(Ji=function(e){Li(this,Ji,Gi),Di(e),Ai.call(this);var t=Qi(this);try{e(vs(_s,this,t),vs(ys,this,t))}catch(e){ys(this,t,e)}},(Ai=function(e){Yi(this,{type:Gi,done:!1,notified:!1,parent:!1,reactions:[],rejection:!1,state:0,value:void 0})}).prototype=or(Ji.prototype,{then:function(e,t){var n=Xi(this),r=rs(qi(this,Ji));return r.ok="function"!=typeof e||e,r.fail="function"==typeof t&&t,r.domain=ss?ts.domain:void 0,n.parent=!0,n.reactions.push(r),0!=n.state&&fs(this,n,!1),r.promise},catch:function(e){return this.then(void 0,e)}}),Ni=function(){var e=new Ai,t=Qi(e);this.promise=e,this.resolve=vs(_s,e,t),this.reject=vs(ys,e,t)},ue.f=rs=function(e){return e===Ji||e===Ri?new Ni:is(e)},"function"==typeof A&&(Pi=A.prototype.then,P(A.prototype,"then",function(e,t){var n=this;return new Ji(function(e,t){Pi.call(n,e,t)}).then(e,t)},{unsafe:!0}),"function"==typeof ns&&wi({global:!0,enumerable:!0,forced:!0},{fetch:function(e){return Wi(Ji,ns.apply(xi,arguments))}}))),wi({global:!0,wrap:!0,forced:Be},{Promise:Ji}),yi(Ji,Gi,!1),$r(Gi),Ri=d(Gi),wi({target:Gi,stat:!0,forced:Be},{reject:function(e){var t=rs(this);return t.reject.call(void 0,e),t.promise}}),wi({target:Gi,stat:!0,forced:Be},{resolve:function(e){return Wi(this,e)}}),wi({target:Gi,stat:!0,forced:ji},{all:function(e){var a=this,t=rs(a),c=t.resolve,l=t.reject,n=Ki(function(){var r=Di(a.resolve),i=[],s=0,o=1;Ui(e,function(e){var t=s++,n=!1;i.push(void 0),o++,r.call(a,e).then(function(e){n||(n=!0,i[t]=e,--o||c(i))},l)}),--o||c(i)});return n.error&&l(n.value),t.promise},race:function(e){var n=this,r=rs(n),i=r.reject,t=Ki(function(){var t=Di(n.resolve);Ui(e,function(e){t.call(n,e).then(r.resolve,i)})});return t.error&&i(t.value),r.promise}});var d=$,ws=n,bs=de,Is=B,Ts=l.exports;d({target:"Promise",stat:!0},{allSettled:function(e){var a=this,t=bs.f(a),c=t.resolve,n=t.reject,r=Is(function(){var r=ws(a.resolve),i=[],s=0,o=1;Ts(e,function(e){var t=s++,n=!1;i.push(void 0),o++,r.call(a,e).then(function(e){n||(n=!0,i[t]={status:"fulfilled",value:e},--o||c(i))},function(e){n||(n=!0,i[t]={status:"rejected",reason:e},--o||c(i))})}),--o||c(i)});return r.error&&n(r.value),t.promise}});var Be=$,Es=pe,wi=e,ks=vt,Ss=R,Cs=Ze,ji=Z.exports;Be({target:"Promise",proto:!0,real:!0,forced:!!Es&&wi(function(){Es.prototype.finally.call({then:function(){}},function(){})})},{finally:function(t){var n=Ss(this,ks("Promise")),e="function"==typeof t;return this.then(e?function(e){return Cs(n,t()).then(function(){return e})}:t,e?function(e){return Cs(n,t()).then(function(){throw e})}:t)}}),"function"!=typeof Es||Es.prototype.finally||ji(Es.prototype,"finally",ks("Promise").prototype.finally),yt.Promise;function As(e,t){var n=this;if(!(n instanceof As))return new As(e,t);Ps&&(n=Ps(new Error(t),Rs(n)));var r=[];return xs(e,r.push,r),Ns?Ds(n,{errors:r,type:"AggregateError"}):n.errors=r,void 0!==t&&Os(n,"message",String(t)),n}var d=$,Ns=o,Rs=ee,Ps=rt,pe=Qe,Ze=a,Be=I,xs=l.exports,Os=k,wi=ke,Ds=wi.set,Ls=wi.getterFor("AggregateError");As.prototype=pe(Error.prototype,{constructor:Be(5,As),message:Be(5,""),name:Be(5,"AggregateError")}),Ns&&Ze.f(As.prototype,"errors",{get:function(){return Ls(this).errors},configurable:!0}),d({global:!0},{AggregateError:As});var Ms=de,Fs=B;$({target:"Promise",stat:!0},{try:function(e){var t=Ms.f(this),n=Fs(e);return(n.error?t.reject:t.resolve)(n.value),t.promise}});var ji=$,Us=n,js=vt,qs=de,Vs=B,Bs=l.exports,Ws="No one promise resolved";ji({target:"Promise",stat:!0},{any:function(e){var c=this,t=qs.f(c),l=t.resolve,u=t.reject,n=Vs(function(){var r=Us(c.resolve),i=[],s=0,o=1,a=!1;Bs(e,function(e){var t=s++,n=!1;i.push(void 0),o++,r.call(c,e).then(function(e){n||a||(a=!0,l(e))},function(e){n||a||(n=!0,i[t]=e,--o||u(new(js("AggregateError"))(i,Ws)))})}),--o||u(new(js("AggregateError"))(i,Ws))});return n.error&&u(n.value),t.promise}});function zs(e){throw e}var Ks=Le,wi=Array.isArray||function(e){return"Array"==Ks(e)},$s=c,Hs=wi,Gs=Y("species"),pe=function(e,t){var n;return new(void 0===(n=Hs(e)&&("function"==typeof(n=e.constructor)&&(n===Array||Hs(n.prototype))||$s(n)&&null===(n=n[Gs]))?void 0:n)?Array:n)(0===t?0:t)},Qs=Te,Ys=ot,Xs=z,Js=Et,Zs=pe,eo=[].push,Be=function(p){var f=1==p,g=2==p,m=3==p,v=4==p,y=6==p,_=5==p||y;return function(e,t,n,r){for(var i,s,o=Xs(e),a=Ys(o),c=Qs(t,n,3),l=Js(a.length),u=0,h=r||Zs,d=f?h(e,l):g?h(e,0):void 0;u<l;u++)if((_||u in a)&&(s=c(i=a[u],u,o),p))if(f)d[u]=s;else if(s)switch(p){case 3:return!0;case 5:return i;case 6:return u;case 2:eo.call(d,i)}else if(v)return!1;return y?-1:m||v?v:d}},Ze={forEach:Be(0),map:Be(1),filter:Be(2),some:Be(3),every:Be(4),find:Be(5),findIndex:Be(6)},to=o,no=e,ro=O,io=Object.defineProperty,so={},d=function(e,t){if(ro(so,e))return so[e];var n=[][e],r=!!ro(t=t||{},"ACCESSORS")&&t.ACCESSORS,i=ro(t,0)?t[0]:zs,s=ro(t,1)?t[1]:void 0;return so[e]=!!n&&!no(function(){if(r&&!to)return!0;var e={length:-1};r?io(e,1,{enumerable:!0,get:zs}):e[1]=1,n.call(e,i,s)})},de=$,oo=Ze.find,B=X,ji="find",ao=!0,Be=d(ji);ji in[]&&Array(1)[ji](function(){ao=!1}),de({target:"Array",proto:!0,forced:ao||!Be},{find:function(e){return oo(this,e,1<arguments.length?arguments[1]:void 0)}}),B(ji);var co=i,lo=Te,uo=Function.call,de=function(e,t,n){return lo(uo,co[e].prototype[t],n)};de("Array","find");var Be=$,ho=Ze.findIndex,B=X,ji="findIndex",po=!0,X=d(ji);ji in[]&&Array(1)[ji](function(){po=!1}),Be({target:"Array",proto:!0,forced:po||!X},{findIndex:function(e){return ho(this,e,1<arguments.length?arguments[1]:void 0)}}),B(ji),de("Array","findIndex");var fo=v,go=a,mo=I,X=function(e,t,n){var r=fo(t);r in e?go.f(e,r,mo(0,n)):e[r]=n},vo=Te,yo=z,_o=Ye,wo=J,bo=Et,Io=X,To=f,B=function(e){var t,n,r,i,s,o,a=yo(e),c="function"==typeof this?this:Array,l=arguments.length,u=1<l?arguments[1]:void 0,h=void 0!==u,d=To(a),p=0;if(h&&(u=vo(u,2<l?arguments[2]:void 0,2)),null==d||c==Array&&wo(d))for(n=new c(t=bo(a.length));p<t;p++)o=h?u(a[p],p):a[p],Io(n,p,o);else for(s=(i=d.call(a)).next,n=new c;!(r=s.call(i)).done;p++)o=h?_o(i,u,[r.value,p],!0):r.value,Io(n,p,o);return n.length=p,n};$({target:"Array",stat:!0,forced:!r(function(e){Array.from(e)})},{from:B}),yt.Array.from;var Eo=e,ji=$,ko=Ze.some,Ye=d,J=function(e,t){var n=[][e];return!!n&&Eo(function(){n.call(null,t||function(){throw 1},1)})}("some"),B=Ye("some");ji({target:"Array",proto:!0,forced:!J||!B},{some:function(e){return ko(this,e,1<arguments.length?arguments[1]:void 0)}}),de("Array","some");function So(e){return Ro(e)&&Po(Wo,xo(e))}var Co,d="undefined"!=typeof ArrayBuffer&&"undefined"!=typeof DataView,Ao=o,No=i,Ro=c,Po=O,xo=qe,Oo=k,Do=Z.exports,Ye=a.f,ji=ee,Lo=rt,J=Y,B=D,Mo=No.Int8Array,Fo=Mo&&Mo.prototype,qe=No.Uint8ClampedArray,ee=qe&&qe.prototype,Uo=Mo&&ji(Mo),jo=Fo&&ji(Fo),qe=Object.prototype,qo=qe.isPrototypeOf,J=J("toStringTag"),Vo=B("TYPED_ARRAY_TAG"),Bo=d&&!!Lo&&"Opera"!==xo(No.opera),d=!1,Wo={Int8Array:1,Uint8Array:1,Uint8ClampedArray:1,Int16Array:2,Uint16Array:2,Int32Array:4,Uint32Array:4,Float32Array:4,Float64Array:8};for(Co in Wo)No[Co]||(Bo=!1);if((!Bo||"function"!=typeof Uo||Uo===Function.prototype)&&(Uo=function(){throw TypeError("Incorrect invocation")},Bo))for(Co in Wo)No[Co]&&Lo(No[Co],Uo);if((!Bo||!jo||jo===qe)&&(jo=Uo.prototype,Bo))for(Co in Wo)No[Co]&&Lo(No[Co].prototype,jo);if(Bo&&ji(ee)!==jo&&Lo(ee,jo),Ao&&!Po(jo,J))for(Co in d=!0,Ye(jo,J,{get:function(){return Ro(this)?this[Vo]:void 0}}),Wo)No[Co]&&Oo(No[Co],Vo,Co);var Ye=i,J={NATIVE_ARRAY_BUFFER_VIEWS:Bo,TYPED_ARRAY_TAG:d&&Vo,aTypedArray:function(e){if(So(e))return e;throw TypeError("Target is not a typed array")},aTypedArrayConstructor:function(e){if(Lo){if(qo.call(Uo,e))return e}else for(var t in Wo)if(Po(Wo,Co)){t=No[t];if(t&&(e===t||qo.call(t,e)))return e}throw TypeError("Target is not a typed array constructor")},exportTypedArrayMethod:function(e,t,n){if(Ao){if(n)for(var r in Wo){r=No[r];r&&Po(r.prototype,e)&&delete r.prototype[e]}jo[e]&&!n||Do(jo,e,!n&&Bo&&Fo[e]||t)}},exportTypedArrayStaticMethod:function(e,t,n){var r,i;if(Ao){if(Lo){if(n)for(r in Wo)(i=No[r])&&Po(i,e)&&delete i[e];if(Uo[e]&&!n)return;try{return Do(Uo,e,!n&&Bo&&Mo[e]||t)}catch(e){}}for(r in Wo)!(i=No[r])||i[e]&&!n||Do(i,e,t)}},isView:function(e){var t=xo(e);return"DataView"===t||Po(Wo,t)},isTypedArray:So,TypedArray:Uo,TypedArrayPrototype:jo},d=fe,fe=Y("iterator"),Ye=Ye.Uint8Array,zo=d.values,Ko=d.keys,$o=d.entries,Ho=J.aTypedArray,d=J.exportTypedArrayMethod,J=Ye&&Ye.prototype[fe],Ye=!!J&&("values"==J.name||null==J.name),J=function(){return zo.call(Ho(this))};d("entries",function(){return $o.call(Ho(this))}),d("keys",function(){return Ko.call(Ho(this))}),d("values",J,!Ye),d(fe,J,!Ye);var Go=o,J=e,Qo=Ie,Yo=N,Xo=Je,Jo=z,Zo=ot,ea=Object.assign,ta=Object.defineProperty,Ye=!ea||J(function(){if(Go&&1!==ea({b:1},ea(ta({},"a",{enumerable:!0,get:function(){ta(this,"b",{value:3,enumerable:!1})}}),{b:2})).b)return!0;var e={},t={},n=Symbol(),r="abcdefghijklmnopqrst";return e[n]=7,r.split("").forEach(function(e){t[e]=e}),7!=ea({},e)[n]||Qo(ea({},t)).join("")!=r})?function(e,t){for(var n=Jo(e),r=arguments.length,i=1,s=Yo.f,o=Xo.f;i<r;)for(var a,c=Zo(arguments[i++]),l=s?Qo(c).concat(s(c)):Qo(c),u=l.length,h=0;h<u;)a=l[h++],Go&&!o.call(c,a)||(n[a]=c[a]);return n}:ea;$({target:"Object",stat:!0,forced:Object.assign!==Ye},{assign:Ye}),yt.Object.assign;var na=o,ra=Ie,ia=nt,sa=Je.f,ot=function(a){return function(e){for(var t,n=ia(e),r=ra(n),i=r.length,s=0,o=[];s<i;)t=r[s++],na&&!sa.call(n,t)||o.push(a?[t,n[t]]:n[t]);return o}},J={entries:ot(!0),values:ot(!1)},Ye=$,oa=J.entries;Ye({target:"Object",stat:!0},{entries:function(e){return oa(e)}}),yt.Object.entries;var ot=$,aa=J.values;ot({target:"Object",stat:!0},{values:function(e){return aa(e)}}),yt.Object.values;var ca=c,la=Le,ua=Y("match"),ha=function(e){var t;return ca(e)&&(void 0!==(t=e[ua])?!!t:"RegExp"==la(e))},Ye=function(e){if(ha(e))throw TypeError("The method doesn't accept regular expressions");return e},da=Y("match"),J=function(t){var n=/./;try{"/./"[t](n)}catch(e){try{return n[da]=!1,"/./"[t](n)}catch(e){}}return!1},pa=Ye,fa=$e;$({target:"String",proto:!0,forced:!J("includes")},{includes:function(e){return!!~String(fa(this)).indexOf(pa(e),1<arguments.length?arguments[1]:void 0)}}),de("String","includes");var ot=$,Le=Xe.f,ga=Et,ma=Ye,va=$e,J=J,ya="".startsWith,_a=Math.min,J=J("startsWith");ot({target:"String",proto:!0,forced:!!(J||(!(Le=Le(String.prototype,"startsWith"))||Le.writable))&&!J},{startsWith:function(e){var t=String(va(this));ma(e);var n=ga(_a(1<arguments.length?arguments[1]:void 0,t.length)),r=String(e);return ya?ya.call(t,r,n):t.slice(n,n+r.length)===r}}),de("String","startsWith");var wa=Ke,ba=$e;$({target:"String",proto:!0},{repeat:"".repeat||function(e){var t=String(ba(this)),n="",r=wa(e);if(r<0||r==1/0)throw RangeError("Wrong number of repetitions");for(;0<r;(r>>>=1)&&(t+=t))1&r&&(n+=t);return n}}),de("String","repeat");var Ia=e,Ta=he,Ea=Y("species"),Ke=$,$e=e,ka=wi,Sa=c,Ca=z,Aa=Et,Na=X,Ra=pe,de=function(t){return 51<=Ta||!Ia(function(){var e=[];return(e.constructor={})[Ea]=function(){return{foo:1}},1!==e[t](Boolean).foo})},Et=he,Pa=Y("isConcatSpreadable"),xa=9007199254740991,Oa="Maximum allowed index exceeded",X=51<=Et||!$e(function(){var e=[];return e[Pa]=!1,e.concat()[0]!==e}),pe=de("concat");Ke({target:"Array",proto:!0,forced:!X||!pe},{concat:function(e){for(var t,n,r,i=Ca(this),s=Ra(i,0),o=0,a=-1,c=arguments.length;a<c;a++)if(function(e){if(!Sa(e))return!1;var t=e[Pa];return void 0!==t?!!t:ka(e)}(r=-1===a?i:arguments[a])){if(n=Aa(r.length),xa<o+n)throw TypeError(Oa);for(t=0;t<n;t++,o++)t in r&&Na(s,o,r[t])}else{if(xa<=o)throw TypeError(Oa);Na(s,o++,r)}return s.length=o,s}});var he={},Da=nt,La=bt.f,Ma={}.toString,Fa="object"==typeof window&&window&&Object.getOwnPropertyNames?Object.getOwnPropertyNames(window):[];he.f=function(e){return Fa&&"[object Window]"==Ma.call(e)?function(e){try{return La(e)}catch(e){return Fa.slice()}}(e):La(Da(e))};Et={};Et.f=Y;function Ua(e,t){var n=_c[e]=Za(pc[lc]);return uc(n,{type:cc,tag:e,description:t}),za||(n.description=t),n}function ja(t,e){Ga(t);var n=Ya(e),r=ec(n).concat(Ac(n));return oc(r,function(e){za&&!Cc.call(n,e)||Sc(t,e,n[e])}),t}var qa=yt,Va=O,Ba=Et,Wa=a.f,$e=function(e){var t=qa.Symbol||(qa.Symbol={});Va(t,e)||Wa(t,e,{value:Ba.f(e)})},de=$,Ke=i,X=vt,za=o,pe=j,j=q,q=e,Ka=O,$a=wi,Ha=c,Ga=t,Qa=z,Ya=nt,Xa=v,Ja=I,Za=Qe,ec=Ie,v=bt,I=he,tc=N,Ie=Xe,bt=a,he=Je,N=k,Xe=Z.exports,Je=s.exports,k=ve,nc=ye,rc=D,ic=Y,s=Et,sc=$e,ve=tt,Y=ke,oc=Ze.forEach,ac=k("hidden"),cc="Symbol",lc="prototype",k=ic("toPrimitive"),uc=Y.set,hc=Y.getterFor(cc),dc=Object[lc],pc=Ke.Symbol,fc=X("JSON","stringify"),gc=Ie.f,mc=bt.f,vc=I.f,yc=he.f,_c=Je("symbols"),wc=Je("op-symbols"),bc=Je("string-to-symbol-registry"),Ic=Je("symbol-to-string-registry"),Je=Je("wks"),Ke=Ke.QObject,Tc=!Ke||!Ke[lc]||!Ke[lc].findChild,Ec=za&&q(function(){return 7!=Za(mc({},"a",{get:function(){return mc(this,"a",{value:7}).a}})).a})?function(e,t,n){var r=gc(dc,t);r&&delete dc[t],mc(e,t,n),r&&e!==dc&&mc(dc,t,r)}:mc,kc=j?function(e){return"symbol"==typeof e}:function(e){return Object(e)instanceof pc},Sc=function(e,t,n){e===dc&&Sc(wc,t,n),Ga(e);var r=Xa(t,!0);return Ga(n),Ka(_c,r)?(n.enumerable?(Ka(e,ac)&&e[ac][r]&&(e[ac][r]=!1),n=Za(n,{enumerable:Ja(0,!1)})):(Ka(e,ac)||mc(e,ac,Ja(1,{})),e[ac][r]=!0),Ec(e,r,n)):mc(e,r,n)},Cc=function(e){var t=Xa(e,!0),n=yc.call(this,t);return!(this===dc&&Ka(_c,t)&&!Ka(wc,t))&&(!(n||!Ka(this,t)||!Ka(_c,t)||Ka(this,ac)&&this[ac][t])||n)},Ke=function(e,t){var n=Ya(e),r=Xa(t,!0);if(n!==dc||!Ka(_c,r)||Ka(wc,r)){var i=gc(n,r);return!i||!Ka(_c,r)||Ka(n,ac)&&n[ac][r]||(i.enumerable=!0),i}},j=function(e){var t=vc(Ya(e)),n=[];return oc(t,function(e){Ka(_c,e)||Ka(nc,e)||n.push(e)}),n},Ac=function(e){var t=e===dc,n=vc(t?wc:Ya(e)),r=[];return oc(n,function(e){!Ka(_c,e)||t&&!Ka(dc,e)||r.push(_c[e])}),r};pe||(Xe((pc=function(){if(this instanceof pc)throw TypeError("Symbol is not a constructor");var e=arguments.length&&void 0!==arguments[0]?String(arguments[0]):void 0,t=rc(e),n=function(e){this===dc&&n.call(wc,e),Ka(this,ac)&&Ka(this[ac],t)&&(this[ac][t]=!1),Ec(this,t,Ja(1,e))};return za&&Tc&&Ec(dc,t,{configurable:!0,set:n}),Ua(t,e)})[lc],"toString",function(){return hc(this).tag}),Xe(pc,"withoutSetter",function(e){return Ua(rc(e),e)}),he.f=Cc,bt.f=Sc,Ie.f=Ke,v.f=I.f=j,tc.f=Ac,s.f=function(e){return Ua(ic(e),e)},za&&(mc(pc[lc],"description",{configurable:!0,get:function(){return hc(this).description}}),Xe(dc,"propertyIsEnumerable",Cc,{unsafe:!0}))),de({global:!0,wrap:!0,forced:!pe,sham:!pe},{Symbol:pc}),oc(ec(Je),function(e){sc(e)}),de({target:cc,stat:!0,forced:!pe},{for:function(e){var t=String(e);if(Ka(bc,t))return bc[t];var n=pc(t);return bc[t]=n,Ic[n]=t,n},keyFor:function(e){if(!kc(e))throw TypeError(e+" is not a symbol");if(Ka(Ic,e))return Ic[e]},useSetter:function(){Tc=!0},useSimple:function(){Tc=!1}}),de({target:"Object",stat:!0,forced:!pe,sham:!za},{create:function(e,t){return void 0===t?Za(e):ja(Za(e),t)},defineProperty:Sc,defineProperties:ja,getOwnPropertyDescriptor:Ke}),de({target:"Object",stat:!0,forced:!pe},{getOwnPropertyNames:j,getOwnPropertySymbols:Ac}),de({target:"Object",stat:!0,forced:q(function(){tc.f(1)})},{getOwnPropertySymbols:function(e){return tc.f(Qa(e))}}),fc&&de({target:"JSON",stat:!0,forced:!pe||q(function(){var e=pc();return"[null]"!=fc([e])||"{}"!=fc({a:e})||"{}"!=fc(Object(e))})},{stringify:function(e,t,n){for(var r,i=[e],s=1;s<arguments.length;)i.push(arguments[s++]);if((Ha(r=t)||void 0!==e)&&!kc(e))return $a(t)||(t=function(e,t){if("function"==typeof r&&(t=r.call(this,e,t)),!kc(t))return t}),i[1]=t,fc.apply(null,i)}}),pc[lc][k]||N(pc[lc],k,pc[lc].valueOf),ve(pc,cc),nc[ac]=!0,$e("asyncIterator");var Nc,Rc,Pc,xc,Oc,k=$,Dc=O,Lc=c,ve=a.f,U=U,Mc=i.Symbol;!o||"function"!=typeof Mc||"description"in Mc.prototype&&void 0===Mc().description||(Nc={},U(Rc=function(){var e=arguments.length<1||void 0===arguments[0]?void 0:String(arguments[0]),t=this instanceof Rc?new Mc(e):void 0===e?Mc():Mc(e);return""===e&&(Nc[t]=!0),t},Mc),(U=Rc.prototype=Mc.prototype).constructor=Rc,Pc=U.toString,xc="Symbol(test)"==String(Mc("test")),Oc=/^Symbol\((.*)\)[^)]+$/,ve(U,"description",{configurable:!0,get:function(){var e=Lc(this)?this.valueOf():this,t=Pc.call(e);if(Dc(Nc,e))return"";t=xc?t.slice(7,-1):t.replace(Oc,"$1");return""===t?void 0:t}}),k({global:!0,forced:!0},{Symbol:Rc})),$e("hasInstance"),$e("isConcatSpreadable"),$e("iterator"),$e("match"),$e("matchAll"),$e("replace"),$e("search"),$e("species"),$e("split"),$e("toPrimitive"),$e("toStringTag"),$e("unscopables"),tt(Math,"Math",!0),tt(i.JSON,"JSON",!0),yt.Symbol,$e("asyncDispose"),$e("dispose"),$e("observable"),$e("patternMatch"),$e("replaceAll"),Et.f("iterator");function Fc(e){qc(e,Bc,{value:{objectID:"O"+ ++Wc,weakData:{}}})}var $e={exports:{}},Et=!e(function(){return Object.isExtensible(Object.preventExtensions({}))}),ye=ye,Uc=c,jc=O,qc=a.f,Vc=Et,Bc=D("meta"),Wc=0,zc=Object.isExtensible||function(){return!0},Kc=$e.exports={REQUIRED:!1,fastKey:function(e,t){if(!Uc(e))return"symbol"==typeof e?e:("string"==typeof e?"S":"P")+e;if(!jc(e,Bc)){if(!zc(e))return"F";if(!t)return"E";Fc(e)}return e[Bc].objectID},getWeakData:function(e,t){if(!jc(e,Bc)){if(!zc(e))return!0;if(!t)return!1;Fc(e)}return e[Bc].weakData},onFreeze:function(e){return Vc&&Kc.REQUIRED&&zc(e)&&!jc(e,Bc)&&Fc(e),e}};ye[Bc]=!0;var $c=c,Hc=rt,Gc=$,Qc=i,Yc=V,Xc=Z.exports,Jc=$e.exports,Zc=l.exports,el=Me,tl=c,nl=e,rl=r,il=tt,sl=function(e,t,n){var r,i;return Hc&&"function"==typeof(r=t.constructor)&&r!==n&&$c(i=r.prototype)&&i!==n.prototype&&Hc(e,i),e},tt=function(r,e,t){function n(e){var n=p[e];Xc(p,e,"add"==e?function(e){return n.call(this,0===e?0:e),this}:"delete"==e?function(e){return!(u&&!tl(e))&&n.call(this,0===e?0:e)}:"get"==e?function(e){return u&&!tl(e)?void 0:n.call(this,0===e?0:e)}:"has"==e?function(e){return!(u&&!tl(e))&&n.call(this,0===e?0:e)}:function(e,t){return n.call(this,0===e?0:e,t),this})}var i,s,o,a,c,l=-1!==r.indexOf("Map"),u=-1!==r.indexOf("Weak"),h=l?"set":"add",d=Qc[r],p=d&&d.prototype,f=d,g={};return Yc(r,"function"!=typeof d||!(u||p.forEach&&!nl(function(){(new d).entries().next()})))?(f=t.getConstructor(e,r,l,h),Jc.REQUIRED=!0):Yc(r,!0)&&(s=(i=new f)[h](u?{}:-0,1)!=i,o=nl(function(){i.has(1)}),a=rl(function(e){new d(e)}),c=!u&&nl(function(){for(var e=new d,t=5;t--;)e[h](t,t);return!e.has(-0)}),a||(((f=e(function(e,t){el(e,f,r);var n=sl(new d,e,f);return null!=t&&Zc(t,n[h],n,l),n})).prototype=p).constructor=f),(o||c)&&(n("delete"),n("has"),l&&n("get")),(c||s)&&n(h),u&&p.clear&&delete p.clear),g[r]=f,Gc({global:!0,forced:f!=d},g),il(f,r),u||t.setStrong(f,r,l),f},ol=a.f,al=Qe,cl=Er,ll=Te,ul=Me,hl=l.exports,dl=Pt,pl=Ee,fl=o,gl=$e.exports.fastKey,ml=ke.set,vl=ke.getterFor,Pt={getConstructor:function(e,n,r,i){function s(e,t,n){var r,i,s=c(e),o=a(e,t);return o?o.value=n:(s.last=o={index:i=gl(t,!0),key:t,value:n,previous:r=s.last,next:void 0,removed:!1},s.first||(s.first=o),r&&(r.next=o),fl?s.size++:e.size++,"F"!==i&&(s.index[i]=o)),e}function a(e,t){var n,r=c(e),i=gl(t);if("F"!==i)return r.index[i];for(n=r.first;n;n=n.next)if(n.key==t)return n}var o=e(function(e,t){ul(e,o,n),ml(e,{type:n,index:al(null),first:void 0,last:void 0,size:0}),fl||(e.size=0),null!=t&&hl(t,e[i],e,r)}),c=vl(n);return cl(o.prototype,{clear:function(){for(var e=c(this),t=e.index,n=e.first;n;)n.removed=!0,n.previous&&(n.previous=n.previous.next=void 0),delete t[n.index],n=n.next;e.first=e.last=void 0,fl?e.size=0:this.size=0},delete:function(e){var t,n,r=c(this),i=a(this,e);return i&&(t=i.next,n=i.previous,delete r.index[i.index],i.removed=!0,n&&(n.next=t),t&&(t.previous=n),r.first==i&&(r.first=t),r.last==i&&(r.last=n),fl?r.size--:this.size--),!!i},forEach:function(e){for(var t,n=c(this),r=ll(e,1<arguments.length?arguments[1]:void 0,3);t=t?t.next:n.first;)for(r(t.value,t.key,this);t&&t.removed;)t=t.previous},has:function(e){return!!a(this,e)}}),cl(o.prototype,r?{get:function(e){var t=a(this,e);return t&&t.value},set:function(e,t){return s(this,0===e?0:e,t)}}:{add:function(e){return s(this,e=0===e?0:e,e)}}),fl&&ol(o.prototype,"size",{get:function(){return c(this).size}}),o},setStrong:function(e,t,n){var r=t+" Iterator",i=vl(t),s=vl(r);dl(e,t,function(e,t){ml(this,{type:r,target:e,state:i(e),kind:t,last:void 0})},function(){for(var e=s(this),t=e.kind,n=e.last;n&&n.removed;)n=n.previous;return e.target&&(e.last=n=n?n.next:e.state.first)?"keys"==t?{value:n.key,done:!1}:"values"==t?{value:n.value,done:!1}:{value:[n.key,n.value],done:!1}:{value:e.target=void 0,done:!0}},n?"entries":"values",!n,!0),pl(t)}};tt("Map",function(e){return function(){return e(this,arguments.length?arguments[0]:void 0)}},Pt),yt.Map;var yl=n,_l=Te,wl=l.exports,Ee=function(e){var t,n,r,i,s=arguments.length,o=1<s?arguments[1]:void 0;return yl(this),(t=void 0!==o)&&yl(o),null==e?new this:(n=[],t?(r=0,i=_l(o,2<s?arguments[2]:void 0,2),wl(e,function(e){n.push(i(e,r++))})):wl(e,n.push,n),new this(n))};$({target:"Map",stat:!0},{from:Ee});o=function(){for(var e=arguments.length,t=new Array(e);e--;)t[e]=arguments[e];return new this(t)};$({target:"Map",stat:!0},{of:o});var bl=t,Il=n,$e=function(){for(var e,t=bl(this),n=Il(t.delete),r=!0,i=0,s=arguments.length;i<s;i++)e=n.call(t,arguments[i]),r=r&&e;return!!r},Tl=$e;$({target:"Map",proto:!0,real:!0,forced:!1},{deleteAll:function(){return Tl.apply(this,arguments)}});var El=t,kl=f,ke=function(e){return Map.prototype.entries.call(e)},f=$,Sl=t,Cl=Te,Al=ke,Nl=l.exports;f({target:"Map",proto:!0,real:!0,forced:!1},{every:function(e){var n=Sl(this),t=Al(n),r=Cl(e,1<arguments.length?arguments[1]:void 0,3);return!Nl(t,function(e,t){if(!r(t,e,n))return Nl.stop()},void 0,!0,!0).stopped}});var f=$,Rl=vt,Pl=t,xl=n,Ol=Te,Dl=R,Ll=ke,Ml=l.exports;f({target:"Map",proto:!0,real:!0,forced:!1},{filter:function(e){var n=Pl(this),t=Ll(n),r=Ol(e,1<arguments.length?arguments[1]:void 0,3),i=new(Dl(n,Rl("Map"))),s=xl(i.set);return Ml(t,function(e,t){r(t,e,n)&&s.call(i,e,t)},void 0,!0,!0),i}});var f=$,Fl=t,Ul=Te,jl=ke,ql=l.exports;f({target:"Map",proto:!0,real:!0,forced:!1},{find:function(e){var n=Fl(this),t=jl(n),r=Ul(e,1<arguments.length?arguments[1]:void 0,3);return ql(t,function(e,t){if(r(t,e,n))return ql.stop(t)},void 0,!0,!0).result}});var f=$,Vl=t,Bl=Te,Wl=ke,zl=l.exports;f({target:"Map",proto:!0,real:!0,forced:!1},{findKey:function(e){var n=Vl(this),t=Wl(n),r=Bl(e,1<arguments.length?arguments[1]:void 0,3);return zl(t,function(e,t){if(r(t,e,n))return zl.stop(e)},void 0,!0,!0).result}});var f=$,Kl=l.exports,$l=n;f({target:"Map",stat:!0},{groupBy:function(e,n){var r=new this;$l(n);var i=$l(r.has),s=$l(r.get),o=$l(r.set);return Kl(e,function(e){var t=n(e);i.call(r,t)?s.call(r,t).push(e):o.call(r,t,[e])}),r}});var f=$,Hl=t,Gl=ke,Ql=function(e,t){return e===t||e!=e&&t!=t},Yl=l.exports;f({target:"Map",proto:!0,real:!0,forced:!1},{includes:function(n){return Yl(Gl(Hl(this)),function(e,t){if(Ql(t,n))return Yl.stop()},void 0,!0,!0).stopped}});var f=$,Xl=l.exports,Jl=n;f({target:"Map",stat:!0},{keyBy:function(e,t){var n=new this;Jl(t);var r=Jl(n.set);return Xl(e,function(e){r.call(n,t(e),e)}),n}});var f=$,Zl=t,eu=ke,tu=l.exports;f({target:"Map",proto:!0,real:!0,forced:!1},{keyOf:function(n){return tu(eu(Zl(this)),function(e,t){if(t===n)return tu.stop(e)},void 0,!0,!0).result}});var f=$,nu=vt,ru=t,iu=n,su=Te,ou=R,au=ke,cu=l.exports;f({target:"Map",proto:!0,real:!0,forced:!1},{mapKeys:function(e){var n=ru(this),t=au(n),r=su(e,1<arguments.length?arguments[1]:void 0,3),i=new(ou(n,nu("Map"))),s=iu(i.set);return cu(t,function(e,t){s.call(i,r(t,e,n),t)},void 0,!0,!0),i}});var f=$,lu=vt,uu=t,hu=n,du=Te,pu=R,fu=ke,gu=l.exports;f({target:"Map",proto:!0,real:!0,forced:!1},{mapValues:function(e){var n=uu(this),t=fu(n),r=du(e,1<arguments.length?arguments[1]:void 0,3),i=new(pu(n,lu("Map"))),s=hu(i.set);return gu(t,function(e,t){s.call(i,e,r(t,e,n))},void 0,!0,!0),i}});var f=$,mu=t,vu=n,yu=l.exports;f({target:"Map",proto:!0,real:!0,forced:!1},{merge:function(e){for(var t=mu(this),n=vu(t.set),r=0;r<arguments.length;)yu(arguments[r++],n,t,!0);return t}});var f=$,_u=t,wu=n,bu=ke,Iu=l.exports;f({target:"Map",proto:!0,real:!0,forced:!1},{reduce:function(n){var r=_u(this),e=bu(r),i=arguments.length<2,s=i?void 0:arguments[1];if(wu(n),Iu(e,function(e,t){s=i?(i=!1,t):n(s,t,e,r)},void 0,!0,!0),i)throw TypeError("Reduce of empty map with no initial value");return s}});var f=$,Tu=t,Eu=Te,ku=ke,Su=l.exports;f({target:"Map",proto:!0,real:!0,forced:!1},{some:function(e){var n=Tu(this),t=ku(n),r=Eu(e,1<arguments.length?arguments[1]:void 0,3);return Su(t,function(e,t){if(r(t,e,n))return Su.stop()},void 0,!0,!0).stopped}});var Cu=t,Au=n;$({target:"Map",proto:!0,real:!0,forced:!1},{update:function(e,t){var n=Cu(this),r=arguments.length;Au(t);var i=n.has(e);if(!i&&r<3)throw TypeError("Updating absent value");r=i?n.get(e):Au(2<r?arguments[2]:void 0)(e,n);return n.set(e,t(r,e,n)),n}});var Nu=t,f=function(e,t){var n,r=Nu(this),i=2<arguments.length?arguments[2]:void 0;if("function"!=typeof t&&"function"!=typeof i)throw TypeError("At least one callback required");return r.has(e)?(n=r.get(e),"function"==typeof t&&(n=t(n),r.set(e,n))):"function"==typeof i&&(n=i(),r.set(e,n)),n};$({target:"Map",proto:!0,real:!0,forced:!1},{upsert:f});$({target:"Map",proto:!0,real:!0,forced:!1},{updateOrInsert:f}),tt("Set",function(e){return function(){return e(this,arguments.length?arguments[0]:void 0)}},Pt),yt.Set,$({target:"Set",stat:!0},{from:Ee}),$({target:"Set",stat:!0},{of:o});var Ru=t,Pu=n,xu=function(){for(var e=Ru(this),t=Pu(e.add),n=0,r=arguments.length;n<r;n++)t.call(e,arguments[n]);return e};$({target:"Set",proto:!0,real:!0,forced:!1},{addAll:function(){return xu.apply(this,arguments)}});var Ou=$e;$({target:"Set",proto:!0,real:!0,forced:!1},{deleteAll:function(){return Ou.apply(this,arguments)}});var o=function(e){return Set.prototype.values.call(e)},$e=$,Du=t,Lu=Te,Mu=o,Fu=l.exports;$e({target:"Set",proto:!0,real:!0,forced:!1},{every:function(e){var t=Du(this),n=Mu(t),r=Lu(e,1<arguments.length?arguments[1]:void 0,3);return!Fu(n,function(e){if(!r(e,e,t))return Fu.stop()},void 0,!1,!0).stopped}});var $e=$,Uu=vt,ju=t,qu=n,Vu=R,Bu=l.exports;$e({target:"Set",proto:!0,real:!0,forced:!1},{difference:function(e){var t=ju(this),n=new(Vu(t,Uu("Set")))(t),r=qu(n.delete);return Bu(e,function(e){r.call(n,e)}),n}});var $e=$,Wu=vt,zu=t,Ku=n,$u=Te,Hu=R,Gu=o,Qu=l.exports;$e({target:"Set",proto:!0,real:!0,forced:!1},{filter:function(e){var t=zu(this),n=Gu(t),r=$u(e,1<arguments.length?arguments[1]:void 0,3),i=new(Hu(t,Wu("Set"))),s=Ku(i.add);return Qu(n,function(e){r(e,e,t)&&s.call(i,e)},void 0,!1,!0),i}});var $e=$,Yu=t,Xu=Te,Ju=o,Zu=l.exports;$e({target:"Set",proto:!0,real:!0,forced:!1},{find:function(e){var t=Yu(this),n=Ju(t),r=Xu(e,1<arguments.length?arguments[1]:void 0,3);return Zu(n,function(e){if(r(e,e,t))return Zu.stop(e)},void 0,!1,!0).result}});var $e=$,eh=vt,th=t,nh=n,rh=R,ih=l.exports;$e({target:"Set",proto:!0,real:!0,forced:!1},{intersection:function(e){var t=th(this),n=new(rh(t,eh("Set"))),r=nh(t.has),i=nh(n.add);return ih(e,function(e){r.call(t,e)&&i.call(n,e)}),n}});var $e=$,sh=t,oh=n,ah=l.exports;$e({target:"Set",proto:!0,real:!0,forced:!1},{isDisjointFrom:function(e){var t=sh(this),n=oh(t.has);return!ah(e,function(e){if(!0===n.call(t,e))return ah.stop()}).stopped}});var $e=$,ch=vt,lh=t,uh=n,hh=function(e){var t=kl(e);if("function"!=typeof t)throw TypeError(String(e)+" is not iterable");return El(t.call(e))},dh=l.exports;$e({target:"Set",proto:!0,real:!0,forced:!1},{isSubsetOf:function(e){var t=hh(this),n=lh(e),r=n.has;return"function"!=typeof r&&(n=new(ch("Set"))(e),r=uh(n.has)),!dh(t,function(e){if(!1===r.call(n,e))return dh.stop()},void 0,!1,!0).stopped}});var $e=$,ph=t,fh=n,gh=l.exports;$e({target:"Set",proto:!0,real:!0,forced:!1},{isSupersetOf:function(e){var t=ph(this),n=fh(t.has);return!gh(e,function(e){if(!1===n.call(t,e))return gh.stop()}).stopped}});var $e=$,mh=t,vh=o,yh=l.exports;$e({target:"Set",proto:!0,real:!0,forced:!1},{join:function(e){var t=mh(this),n=vh(t),r=void 0===e?",":String(e),t=[];return yh(n,t.push,t,!1,!0),t.join(r)}});var $e=$,_h=vt,wh=t,bh=n,Ih=Te,Th=R,Eh=o,kh=l.exports;$e({target:"Set",proto:!0,real:!0,forced:!1},{map:function(e){var t=wh(this),n=Eh(t),r=Ih(e,1<arguments.length?arguments[1]:void 0,3),i=new(Th(t,_h("Set"))),s=bh(i.add);return kh(n,function(e){s.call(i,r(e,e,t))},void 0,!1,!0),i}});var $e=$,Sh=t,Ch=n,Ah=o,Nh=l.exports;$e({target:"Set",proto:!0,real:!0,forced:!1},{reduce:function(t){var n=Sh(this),e=Ah(n),r=arguments.length<2,i=r?void 0:arguments[1];if(Ch(t),Nh(e,function(e){i=r?(r=!1,e):t(i,e,e,n)},void 0,!1,!0),r)throw TypeError("Reduce of empty set with no initial value");return i}});var $e=$,Rh=t,Ph=Te,xh=o,Oh=l.exports;$e({target:"Set",proto:!0,real:!0,forced:!1},{some:function(e){var t=Rh(this),n=xh(t),r=Ph(e,1<arguments.length?arguments[1]:void 0,3);return Oh(n,function(e){if(r(e,e,t))return Oh.stop()},void 0,!1,!0).stopped}});var $e=$,Dh=vt,Lh=t,Mh=n,Fh=R,Uh=l.exports;$e({target:"Set",proto:!0,real:!0,forced:!1},{symmetricDifference:function(e){var t=Lh(this),n=new(Fh(t,Dh("Set")))(t),r=Mh(n.delete),i=Mh(n.add);return Uh(e,function(e){r.call(n,e)||i.call(n,e)}),n}});var $e=$,jh=vt,qh=t,Vh=n,Bh=R,Wh=l.exports;$e({target:"Set",proto:!0,real:!0,forced:!1},{union:function(e){var t=qh(this),t=new(Bh(t,jh("Set")))(t);return Wh(e,Vh(t.add),t),t}});var zh,Kh,$h=c,Hh=Math.floor;$({target:"Number",stat:!0},{isInteger:function(e){return!$h(e)&&isFinite(e)&&Hh(e)===e}}),yt.Number.isInteger;function Gh(t){const n=[];let r=0;for(let i=0;i<t.length;i++){let e=t.charCodeAt(i);e<128?n[r++]=e:(e<2048?n[r++]=e>>6|192:(55296==(64512&e)&&i+1<t.length&&56320==(64512&t.charCodeAt(i+1))?(e=65536+((1023&e)<<10)+(1023&t.charCodeAt(++i)),n[r++]=e>>18|240,n[r++]=e>>12&63|128):n[r++]=e>>12|224,n[r++]=e>>6&63|128),n[r++]=63&e|128)}return n}function Qh(e){var t=Gh(e);return Zh.encodeByteArray(t,!0)}const Yh={NODE_CLIENT:!1,NODE_ADMIN:!1,SDK_VERSION:"${JSCORE_VERSION}"},Xh=function(e,t){if(!e)throw Jh(t)},Jh=function(e){return new Error("Firebase Database ("+Yh.SDK_VERSION+") INTERNAL ASSERT FAILED: "+e)},Zh={byteToCharMap_:null,charToByteMap_:null,byteToCharMapWebSafe_:null,charToByteMapWebSafe_:null,ENCODED_VALS_BASE:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",get ENCODED_VALS(){return this.ENCODED_VALS_BASE+"+/="},get ENCODED_VALS_WEBSAFE(){return this.ENCODED_VALS_BASE+"-_."},HAS_NATIVE_SUPPORT:"function"==typeof atob,encodeByteArray(n,e){if(!Array.isArray(n))throw Error("encodeByteArray takes an array as a parameter");this.init_();var r=e?this.byteToCharMapWebSafe_:this.byteToCharMap_;const i=[];for(let u=0;u<n.length;u+=3){var s=n[u],o=u+1<n.length,a=o?n[u+1]:0,c=u+2<n.length,l=c?n[u+2]:0;let e=(15&a)<<2|l>>6,t=63&l;c||(t=64,o||(e=64)),i.push(r[s>>2],r[(3&s)<<4|a>>4],r[e],r[t])}return i.join("")},encodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?btoa(e):this.encodeByteArray(Gh(e),t)},decodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?atob(e):function(e){const t=[];let n=0,r=0;for(;n<e.length;){var i,s,o=e[n++];o<128?t[r++]=String.fromCharCode(o):191<o&&o<224?(i=e[n++],t[r++]=String.fromCharCode((31&o)<<6|63&i)):239<o&&o<365?(s=((7&o)<<18|(63&e[n++])<<12|(63&e[n++])<<6|63&e[n++])-65536,t[r++]=String.fromCharCode(55296+(s>>10)),t[r++]=String.fromCharCode(56320+(1023&s))):(i=e[n++],s=e[n++],t[r++]=String.fromCharCode((15&o)<<12|(63&i)<<6|63&s))}return t.join("")}(this.decodeStringToByteArray(e,t))},decodeStringToByteArray(e,t){this.init_();var n=t?this.charToByteMapWebSafe_:this.charToByteMap_;const r=[];for(let c=0;c<e.length;){var i=n[e.charAt(c++)],s=c<e.length?n[e.charAt(c)]:0;++c;var o=c<e.length?n[e.charAt(c)]:64;++c;var a=c<e.length?n[e.charAt(c)]:64;if(++c,null==i||null==s||null==o||null==a)throw Error();r.push(i<<2|s>>4),64!==o&&(r.push(s<<4&240|o>>2),64!==a&&r.push(o<<6&192|a))}return r},init_(){if(!this.byteToCharMap_){this.byteToCharMap_={},this.charToByteMap_={},this.byteToCharMapWebSafe_={},this.charToByteMapWebSafe_={};for(let e=0;e<this.ENCODED_VALS.length;e++)this.byteToCharMap_[e]=this.ENCODED_VALS.charAt(e),this.charToByteMap_[this.byteToCharMap_[e]]=e,this.byteToCharMapWebSafe_[e]=this.ENCODED_VALS_WEBSAFE.charAt(e),this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[e]]=e,e>=this.ENCODED_VALS_BASE.length&&(this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(e)]=e,this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(e)]=e)}}},ed=function(e){return Qh(e).replace(/\./g,"")},td=function(e){try{return Zh.decodeString(e,!0)}catch(e){console.error("base64Decode failed: ",e)}return null};function nd(e,t){if(!(t instanceof Object))return t;switch(t.constructor){case Date:const n=t;return new Date(n.getTime());case Object:void 0===e&&(e={});break;case Array:e=[];break;default:return t}for(const r in t)t.hasOwnProperty(r)&&"__proto__"!==r&&(e[r]=nd(e[r],t[r]));return e}class rd{constructor(){this.reject=()=>{},this.resolve=()=>{},this.promise=new Promise((e,t)=>{this.resolve=e,this.reject=t})}wrapCallback(n){return(e,t)=>{e?this.reject(e):this.resolve(t),"function"==typeof n&&(this.promise.catch(()=>{}),1===n.length?n(e):n(e,t))}}}function id(e,t){if(e.uid)throw new Error('The "uid" field is no longer supported by mockUserToken. Please use "sub" instead for Firebase Auth User ID.');var n=t||"demo-project",r=e.iat||0,i=e.sub||e.user_id;if(!i)throw new Error("mockUserToken must contain 'sub' or 'user_id' field!");i=Object.assign({iss:`https://securetoken.google.com/${n}`,aud:n,iat:r,exp:r+3600,auth_time:r,sub:i,user_id:i,firebase:{sign_in_provider:"custom",identities:{}}},e);return[ed(JSON.stringify({alg:"none",type:"JWT"})),ed(JSON.stringify(i)),""].join(".")}function sd(){return"undefined"!=typeof navigator&&"string"==typeof navigator.userAgent?navigator.userAgent:""}function od(){return"undefined"!=typeof window&&!!(window.cordova||window.phonegap||window.PhoneGap)&&/ios|iphone|ipod|ipad|android|blackberry|iemobile/i.test(sd())}function ad(){try{return"[object process]"===Object.prototype.toString.call(global.process)}catch(e){return!1}}function cd(){var e="object"==typeof chrome?chrome.runtime:"object"==typeof browser?browser.runtime:void 0;return"object"==typeof e&&void 0!==e.id}function ld(){return"object"==typeof navigator&&"ReactNative"===navigator.product}function ud(){const e=sd();return 0<=e.indexOf("MSIE ")||0<=e.indexOf("Trident/")}function hd(){return!0===Yh.NODE_ADMIN}function dd(){return"object"==typeof indexedDB}function pd(){return new Promise((t,n)=>{try{let e=!0;const r="validate-browser-context-for-indexeddb-analytics-module",i=self.indexedDB.open(r);i.onsuccess=()=>{i.result.close(),e||self.indexedDB.deleteDatabase(r),t(!0)},i.onupgradeneeded=()=>{e=!1},i.onerror=()=>{var e;n((null===(e=i.error)||void 0===e?void 0:e.message)||"")}}catch(e){n(e)}})}function fd(){return!("undefined"==typeof navigator||!navigator.cookieEnabled)}class gd extends Error{constructor(e,t,n){super(t),this.code=e,this.customData=n,this.name="FirebaseError",Object.setPrototypeOf(this,gd.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,md.prototype.create)}}class md{constructor(e,t,n){this.service=e,this.serviceName=t,this.errors=n}create(e,...t){var r,n=t[0]||{},i=`${this.service}/${e}`,s=this.errors[e],s=s?(r=n,s.replace(vd,(e,t)=>{var n=r[t];return null!=n?String(n):`<${t}?>`})):"Error",s=`${this.serviceName}: ${s} (${i}).`;return new gd(i,s,n)}}const vd=/\{\$([^}]+)}/g;function yd(e){return JSON.parse(e)}function _d(e){return JSON.stringify(e)}function wd(e){let t={},n={},r={},i="";try{var s=e.split(".");t=yd(td(s[0])||""),n=yd(td(s[1])||""),i=s[2],r=n.d||{},delete n.d}catch(e){}return{header:t,claims:n,data:r,signature:i}}function bd(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Id(e,t){if(Object.prototype.hasOwnProperty.call(e,t))return e[t]}function Td(e){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}function Ed(e,t,n){const r={};for(const i in e)Object.prototype.hasOwnProperty.call(e,i)&&(r[i]=t.call(n,e[i],i,e));return r}function kd(e,t){if(e===t)return 1;const n=Object.keys(e),r=Object.keys(t);for(const o of n){if(!r.includes(o))return;var i=e[o],s=t[o];if(Sd(i)&&Sd(s)){if(!kd(i,s))return}else if(i!==s)return}for(const a of r)if(!n.includes(a))return;return 1}function Sd(e){return null!==e&&"object"==typeof e}function Cd(e){const t=[];for(const[n,r]of Object.entries(e))Array.isArray(r)?r.forEach(e=>{t.push(encodeURIComponent(n)+"="+encodeURIComponent(e))}):t.push(encodeURIComponent(n)+"="+encodeURIComponent(r));return t.length?"&"+t.join("&"):""}function Ad(e){const r={},t=e.replace(/^\?/,"").split("&");return t.forEach(e=>{var t,n;e&&([t,n]=e.split("="),r[decodeURIComponent(t)]=decodeURIComponent(n))}),r}function Nd(e){var t=e.indexOf("?");if(!t)return"";var n=e.indexOf("#",t);return e.substring(t,0<n?n:void 0)}class Rd{constructor(){this.chain_=[],this.buf_=[],this.W_=[],this.pad_=[],this.inbuf_=0,this.total_=0,this.blockSize=64,this.pad_[0]=128;for(let e=1;e<this.blockSize;++e)this.pad_[e]=0;this.reset()}reset(){this.chain_[0]=1732584193,this.chain_[1]=4023233417,this.chain_[2]=2562383102,this.chain_[3]=271733878,this.chain_[4]=3285377520,this.inbuf_=0,this.total_=0}compress_(n,r){r=r||0;const i=this.W_;if("string"==typeof n)for(let e=0;e<16;e++)i[e]=n.charCodeAt(r)<<24|n.charCodeAt(r+1)<<16|n.charCodeAt(r+2)<<8|n.charCodeAt(r+3),r+=4;else for(let t=0;t<16;t++)i[t]=n[r]<<24|n[r+1]<<16|n[r+2]<<8|n[r+3],r+=4;for(let d=16;d<80;d++){var e=i[d-3]^i[d-8]^i[d-14]^i[d-16];i[d]=4294967295&(e<<1|e>>>31)}let t=this.chain_[0],s=this.chain_[1],o=this.chain_[2],a=this.chain_[3],c=this.chain_[4],l,u;for(let p=0;p<80;p++){u=p<40?p<20?(l=a^s&(o^a),1518500249):(l=s^o^a,1859775393):p<60?(l=s&o|a&(s|o),2400959708):(l=s^o^a,3395469782);var h=(t<<5|t>>>27)+l+c+u+i[p]&4294967295;c=a,a=o,o=4294967295&(s<<30|s>>>2),s=t,t=h}this.chain_[0]=this.chain_[0]+t&4294967295,this.chain_[1]=this.chain_[1]+s&4294967295,this.chain_[2]=this.chain_[2]+o&4294967295,this.chain_[3]=this.chain_[3]+a&4294967295,this.chain_[4]=this.chain_[4]+c&4294967295}update(n,r){if(null!=n){var i=(r=void 0===r?n.length:r)-this.blockSize;let e=0;const s=this.buf_;let t=this.inbuf_;for(;e<r;){if(0===t)for(;e<=i;)this.compress_(n,e),e+=this.blockSize;if("string"==typeof n){for(;e<r;)if(s[t]=n.charCodeAt(e),++t,++e,t===this.blockSize){this.compress_(s),t=0;break}}else for(;e<r;)if(s[t]=n[e],++t,++e,t===this.blockSize){this.compress_(s),t=0;break}}this.inbuf_=t,this.total_+=r}}digest(){const t=[];let e=8*this.total_;this.inbuf_<56?this.update(this.pad_,56-this.inbuf_):this.update(this.pad_,this.blockSize-(this.inbuf_-56));for(let r=this.blockSize-1;56<=r;r--)this.buf_[r]=255&e,e/=256;this.compress_(this.buf_);let n=0;for(let i=0;i<5;i++)for(let e=24;0<=e;e-=8)t[n]=this.chain_[i]>>e&255,++n;return t}}function Pd(e,t){const n=new xd(e,t);return n.subscribe.bind(n)}class xd{constructor(e,t){this.observers=[],this.unsubscribes=[],this.observerCount=0,this.task=Promise.resolve(),this.finalized=!1,this.onNoObservers=t,this.task.then(()=>{e(this)}).catch(e=>{this.error(e)})}next(t){this.forEachObserver(e=>{e.next(t)})}error(t){this.forEachObserver(e=>{e.error(t)}),this.close(t)}complete(){this.forEachObserver(e=>{e.complete()}),this.close()}subscribe(e,t,n){let r;if(void 0===e&&void 0===t&&void 0===n)throw new Error("Missing Observer.");r=function(e,t){if("object"!=typeof e||null===e)return!1;for(const n of t)if(n in e&&"function"==typeof e[n])return!0;return!1}(e,["next","error","complete"])?e:{next:e,error:t,complete:n},void 0===r.next&&(r.next=Od),void 0===r.error&&(r.error=Od),void 0===r.complete&&(r.complete=Od);var i=this.unsubscribeOne.bind(this,this.observers.length);return this.finalized&&this.task.then(()=>{try{this.finalError?r.error(this.finalError):r.complete()}catch(e){}}),this.observers.push(r),i}unsubscribeOne(e){void 0!==this.observers&&void 0!==this.observers[e]&&(delete this.observers[e],--this.observerCount,0===this.observerCount&&void 0!==this.onNoObservers&&this.onNoObservers(this))}forEachObserver(t){if(!this.finalized)for(let e=0;e<this.observers.length;e++)this.sendOne(e,t)}sendOne(e,t){this.task.then(()=>{if(void 0!==this.observers&&void 0!==this.observers[e])try{t(this.observers[e])}catch(e){"undefined"!=typeof console&&console.error&&console.error(e)}})}close(e){this.finalized||(this.finalized=!0,void 0!==e&&(this.finalError=e),this.task.then(()=>{this.observers=void 0,this.onNoObservers=void 0}))}}function Od(){}function Dd(e,t,n,r){let i;if(r<t?i="at least "+t:n<r&&(i=0===n?"none":"no more than "+n),i){var s=e+" failed: Was called with "+r+(1===r?" argument.":" arguments.")+" Expects "+i+".";throw new Error(s)}}function Ld(e,t){return`${e} failed: ${t} argument `}function Md(e,t,n,r){if((!r||n)&&"function"!=typeof n)throw new Error(Ld(e,t)+"must be a valid function.")}function Fd(e,t,n,r){if((!r||n)&&("object"!=typeof n||null===n))throw new Error(Ld(e,t)+"must be a valid context object.")}const Ud=function(e){let t=0;for(let r=0;r<e.length;r++){var n=e.charCodeAt(r);n<128?t++:n<2048?t+=2:55296<=n&&n<=56319?(t+=4,r++):t+=3}return t},jd=1e3,qd=2,Vd=144e5,Bd=.5;function Wd(e,t=jd,n=qd){var r=t*Math.pow(n,e),i=Math.round(Bd*r*(Math.random()-.5)*2);return Math.min(Vd,r+i)}function zd(e){return e&&e._delegate?e._delegate:e}class Kd{constructor(e,t,n){this.name=e,this.instanceFactory=t,this.type=n,this.multipleInstances=!1,this.serviceProps={},this.instantiationMode="LAZY",this.onInstanceCreated=null}setInstantiationMode(e){return this.instantiationMode=e,this}setMultipleInstances(e){return this.multipleInstances=e,this}setServiceProps(e){return this.serviceProps=e,this}setInstanceCreatedCallback(e){return this.onInstanceCreated=e,this}}const $d="[DEFAULT]";class Hd{constructor(e,t){this.name=e,this.container=t,this.component=null,this.instances=new Map,this.instancesDeferred=new Map,this.instancesOptions=new Map,this.onInitCallbacks=new Map}get(e){var t=this.normalizeInstanceIdentifier(e);if(!this.instancesDeferred.has(t)){const r=new rd;if(this.instancesDeferred.set(t,r),this.isInitialized(t)||this.shouldAutoInitialize())try{var n=this.getOrInitializeService({instanceIdentifier:t});n&&r.resolve(n)}catch(e){}}return this.instancesDeferred.get(t).promise}getImmediate(e){var t=this.normalizeInstanceIdentifier(null==e?void 0:e.identifier),n=null!==(n=null==e?void 0:e.optional)&&void 0!==n&&n;if(!this.isInitialized(t)&&!this.shouldAutoInitialize()){if(n)return null;throw Error(`Service ${this.name} is not available`)}try{return this.getOrInitializeService({instanceIdentifier:t})}catch(e){if(n)return null;throw e}}getComponent(){return this.component}setComponent(e){if(e.name!==this.name)throw Error(`Mismatching Component ${e.name} for Provider ${this.name}.`);if(this.component)throw Error(`Component for ${this.name} has already been provided`);if(this.component=e,this.shouldAutoInitialize()){if("EAGER"===e.instantiationMode)try{this.getOrInitializeService({instanceIdentifier:$d})}catch(e){}for(var[t,n]of this.instancesDeferred.entries()){t=this.normalizeInstanceIdentifier(t);try{var r=this.getOrInitializeService({instanceIdentifier:t});n.resolve(r)}catch(e){}}}}clearInstance(e=$d){this.instancesDeferred.delete(e),this.instancesOptions.delete(e),this.instances.delete(e)}async delete(){const e=Array.from(this.instances.values());await Promise.all([...e.filter(e=>"INTERNAL"in e).map(e=>e.INTERNAL.delete()),...e.filter(e=>"_delete"in e).map(e=>e._delete())])}isComponentSet(){return null!=this.component}isInitialized(e=$d){return this.instances.has(e)}getOptions(e=$d){return this.instancesOptions.get(e)||{}}initialize(e={}){var{options:t={}}=e,n=this.normalizeInstanceIdentifier(e.instanceIdentifier);if(this.isInitialized(n))throw Error(`${this.name}(${n}) has already been initialized`);if(!this.isComponentSet())throw Error(`Component ${this.name} has not been registered yet`);var r,i,s=this.getOrInitializeService({instanceIdentifier:n,options:t});for([r,i]of this.instancesDeferred.entries())n===this.normalizeInstanceIdentifier(r)&&i.resolve(s);return s}onInit(e,t){var n=this.normalizeInstanceIdentifier(t);const r=null!==(i=this.onInitCallbacks.get(n))&&void 0!==i?i:new Set;r.add(e),this.onInitCallbacks.set(n,r);var i=this.instances.get(n);return i&&e(i,n),()=>{r.delete(e)}}invokeOnInitCallbacks(e,t){var n=this.onInitCallbacks.get(t);if(n)for(const r of n)try{r(e,t)}catch(e){}}getOrInitializeService({instanceIdentifier:e,options:t={}}){let n=this.instances.get(e);if(!n&&this.component&&(n=this.component.instanceFactory(this.container,{instanceIdentifier:(r=e)===$d?void 0:r,options:t}),this.instances.set(e,n),this.instancesOptions.set(e,t),this.invokeOnInitCallbacks(n,e),this.component.onInstanceCreated))try{this.component.onInstanceCreated(this.container,e,n)}catch(e){}var r;return n||null}normalizeInstanceIdentifier(e=$d){return!this.component||this.component.multipleInstances?e:$d}shouldAutoInitialize(){return!!this.component&&"EXPLICIT"!==this.component.instantiationMode}}class Gd{constructor(e){this.name=e,this.providers=new Map}addComponent(e){const t=this.getProvider(e.name);if(t.isComponentSet())throw new Error(`Component ${e.name} has already been registered with ${this.name}`);t.setComponent(e)}addOrOverwriteComponent(e){const t=this.getProvider(e.name);t.isComponentSet()&&this.providers.delete(e.name),this.addComponent(e)}getProvider(e){if(this.providers.has(e))return this.providers.get(e);var t=new Hd(e,this);return this.providers.set(e,t),t}getProviders(){return Array.from(this.providers.values())}}const Qd=[];(Kh=zh=zh||{})[Kh.DEBUG=0]="DEBUG",Kh[Kh.VERBOSE=1]="VERBOSE",Kh[Kh.INFO=2]="INFO",Kh[Kh.WARN=3]="WARN",Kh[Kh.ERROR=4]="ERROR",Kh[Kh.SILENT=5]="SILENT";const Yd={debug:zh.DEBUG,verbose:zh.VERBOSE,info:zh.INFO,warn:zh.WARN,error:zh.ERROR,silent:zh.SILENT},Xd=zh.INFO,Jd={[zh.DEBUG]:"log",[zh.VERBOSE]:"log",[zh.INFO]:"info",[zh.WARN]:"warn",[zh.ERROR]:"error"},Zd=(e,t,...n)=>{if(!(t<e.logLevel)){var r=(new Date).toISOString(),i=Jd[t];if(!i)throw new Error(`Attempted to log a message with an invalid logType (value: ${t})`);console[i](`[${r}]  ${e.name}:`,...n)}};class ep{constructor(e){this.name=e,this._logLevel=Xd,this._logHandler=Zd,this._userLogHandler=null,Qd.push(this)}get logLevel(){return this._logLevel}set logLevel(e){if(!(e in zh))throw new TypeError(`Invalid value "${e}" assigned to \`logLevel\``);this._logLevel=e}setLogLevel(e){this._logLevel="string"==typeof e?Yd[e]:e}get logHandler(){return this._logHandler}set logHandler(e){if("function"!=typeof e)throw new TypeError("Value assigned to `logHandler` must be a function");this._logHandler=e}get userLogHandler(){return this._userLogHandler}set userLogHandler(e){this._userLogHandler=e}debug(...e){this._userLogHandler&&this._userLogHandler(this,zh.DEBUG,...e),this._logHandler(this,zh.DEBUG,...e)}log(...e){this._userLogHandler&&this._userLogHandler(this,zh.VERBOSE,...e),this._logHandler(this,zh.VERBOSE,...e)}info(...e){this._userLogHandler&&this._userLogHandler(this,zh.INFO,...e),this._logHandler(this,zh.INFO,...e)}warn(...e){this._userLogHandler&&this._userLogHandler(this,zh.WARN,...e),this._logHandler(this,zh.WARN,...e)}error(...e){this._userLogHandler&&this._userLogHandler(this,zh.ERROR,...e),this._logHandler(this,zh.ERROR,...e)}}class tp{constructor(e){this.container=e}getPlatformInfoString(){const e=this.container.getProviders();return e.map(e=>{if("VERSION"!==(null==(t=e.getComponent())?void 0:t.type))return null;var t,t=e.getImmediate();return`${t.library}/${t.version}`}).filter(e=>e).join(" ")}}const np="@firebase/app",rp=new ep("@firebase/app");var ip;const sp="[DEFAULT]",op={"@firebase/app":"fire-core","@firebase/app-compat":"fire-core-compat","@firebase/analytics":"fire-analytics","@firebase/analytics-compat":"fire-analytics-compat","@firebase/app-check":"fire-app-check","@firebase/app-check-compat":"fire-app-check-compat","@firebase/auth":"fire-auth","@firebase/auth-compat":"fire-auth-compat","@firebase/database":"fire-rtdb","@firebase/database-compat":"fire-rtdb-compat","@firebase/functions":"fire-fn","@firebase/functions-compat":"fire-fn-compat","@firebase/installations":"fire-iid","@firebase/installations-compat":"fire-iid-compat","@firebase/messaging":"fire-fcm","@firebase/messaging-compat":"fire-fcm-compat","@firebase/performance":"fire-perf","@firebase/performance-compat":"fire-perf-compat","@firebase/remote-config":"fire-rc","@firebase/remote-config-compat":"fire-rc-compat","@firebase/storage":"fire-gcs","@firebase/storage-compat":"fire-gcs-compat","@firebase/firestore":"fire-fst","@firebase/firestore-compat":"fire-fst-compat","fire-js":"fire-js",firebase:"fire-js-all"},ap=new Map,cp=new Map;function lp(t,n){try{t.container.addComponent(n)}catch(e){rp.debug(`Component ${n.name} failed to register with FirebaseApp ${t.name}`,e)}}function up(e,t){e.container.addOrOverwriteComponent(t)}function hp(e){var t=e.name;if(cp.has(t))return rp.debug(`There were multiple attempts to register component ${t}.`),!1;cp.set(t,e);for(const n of ap.values())lp(n,e);return!0}function dp(e,t){return e.container.getProvider(t)}const pp=new md("app","Firebase",{"no-app":"No Firebase App '{$appName}' has been created - call Firebase App.initializeApp()","bad-app-name":"Illegal App name: '{$appName}","duplicate-app":"Firebase App named '{$appName}' already exists with different options or config","app-deleted":"Firebase App named '{$appName}' already deleted","invalid-app-argument":"firebase.{$appName}() takes either no argument or a Firebase App instance.","invalid-log-argument":"First argument to `onLog` must be null or a function."});class fp{constructor(e,t,n){this._isDeleted=!1,this._options=Object.assign({},e),this._config=Object.assign({},t),this._name=t.name,this._automaticDataCollectionEnabled=t.automaticDataCollectionEnabled,this._container=n,this.container.addComponent(new Kd("app",()=>this,"PUBLIC"))}get automaticDataCollectionEnabled(){return this.checkDestroyed(),this._automaticDataCollectionEnabled}set automaticDataCollectionEnabled(e){this.checkDestroyed(),this._automaticDataCollectionEnabled=e}get name(){return this.checkDestroyed(),this._name}get options(){return this.checkDestroyed(),this._options}get config(){return this.checkDestroyed(),this._config}get container(){return this._container}get isDeleted(){return this._isDeleted}set isDeleted(e){this._isDeleted=e}checkDestroyed(){if(this.isDeleted)throw pp.create("app-deleted",{appName:this._name})}}const gp="9.6.6";function mp(e,t={}){if("object"!=typeof t){const r=t;t={name:r}}var n=Object.assign({name:sp,automaticDataCollectionEnabled:!1},t);const r=n.name;if("string"!=typeof r||!r)throw pp.create("bad-app-name",{appName:String(r)});var i=ap.get(r);if(i){if(kd(e,i.options)&&kd(n,i.config))return i;throw pp.create("duplicate-app",{appName:r})}const s=new Gd(r);for(const o of cp.values())s.addComponent(o);n=new fp(e,n,s);return ap.set(r,n),n}function vp(e=sp){var t=ap.get(e);if(!t)throw pp.create("no-app",{appName:e});return t}async function yp(e){var t=e.name;ap.has(t)&&(ap.delete(t),await Promise.all(e.container.getProviders().map(e=>e.delete())),e.isDeleted=!0)}function _p(e,t,n){let r=null!==(s=op[e])&&void 0!==s?s:e;n&&(r+=`-${n}`);var i=r.match(/\s|\//),s=t.match(/\s|\//);if(i||s){const o=[`Unable to register library "${r}" with version "${t}":`];return i&&o.push(`library name "${r}" contains illegal characters (whitespace or "/")`),i&&s&&o.push("and"),s&&o.push(`version name "${t}" contains illegal characters (whitespace or "/")`),void rp.warn(o.join(" "))}hp(new Kd(`${r}-version`,()=>({library:r,version:t}),"VERSION"))}function wp(e,t){if(null!==e&&"function"!=typeof e)throw pp.create("invalid-log-argument");!function(s,e){for(const t of Qd){let i=null;e&&e.level&&(i=Yd[e.level]),t.userLogHandler=null===s?null:(e,t,...n)=>{var r=n.map(e=>{if(null==e)return null;if("string"==typeof e)return e;if("number"==typeof e||"boolean"==typeof e)return e.toString();if(e instanceof Error)return e.message;try{return JSON.stringify(e)}catch(e){return null}}).filter(e=>e).join(" ");t>=(null!==i&&void 0!==i?i:e.logLevel)&&s({level:zh[t].toLowerCase(),message:r,args:n,type:e.name})}}}(e,t)}function bp(e){var t;t=e,Qd.forEach(e=>{e.setLogLevel(t)})}ip="",hp(new Kd("platform-logger",e=>new tp(e),"PRIVATE")),_p(np,"0.7.16",ip),_p(np,"0.7.16","esm2017"),_p("fire-js","");var Ip=Object.freeze({__proto__:null,SDK_VERSION:gp,_DEFAULT_ENTRY_NAME:sp,_addComponent:lp,_addOrOverwriteComponent:up,_apps:ap,_clearComponents:function(){cp.clear()},_components:cp,_getProvider:dp,_registerComponent:hp,_removeServiceInstance:function(e,t,n=sp){dp(e,t).clearInstance(n)},deleteApp:yp,getApp:vp,getApps:function(){return Array.from(ap.values())},initializeApp:mp,onLog:wp,registerVersion:_p,setLogLevel:bp,FirebaseError:gd});class Tp{constructor(e,t){this._delegate=e,this.firebase=t,lp(e,new Kd("app-compat",()=>this,"PUBLIC")),this.container=e.container}get automaticDataCollectionEnabled(){return this._delegate.automaticDataCollectionEnabled}set automaticDataCollectionEnabled(e){this._delegate.automaticDataCollectionEnabled=e}get name(){return this._delegate.name}get options(){return this._delegate.options}delete(){return new Promise(e=>{this._delegate.checkDestroyed(),e()}).then(()=>(this.firebase.INTERNAL.removeApp(this.name),yp(this._delegate)))}_getService(e,t=sp){var n;this._delegate.checkDestroyed();const r=this._delegate.container.getProvider(e);return r.isInitialized()||"EXPLICIT"!==(null===(n=r.getComponent())||void 0===n?void 0:n.instantiationMode)||r.initialize(),r.getImmediate({identifier:t})}_removeServiceInstance(e,t=sp){this._delegate.container.getProvider(e).clearInstance(t)}_addComponent(e){lp(this._delegate,e)}_addOrOverwriteComponent(e){up(this._delegate,e)}toJSON(){return{name:this.name,automaticDataCollectionEnabled:this.automaticDataCollectionEnabled,options:this.options}}}const Ep=new md("app-compat","Firebase",{"no-app":"No Firebase App '{$appName}' has been created - call Firebase App.initializeApp()","invalid-app-argument":"firebase.{$appName}() takes either no argument or a Firebase App instance."});function kp(i){const s={},o={__esModule:!0,initializeApp:function(e,t={}){var n=mp(e,t);if(bd(s,n.name))return s[n.name];var r=new i(n,o);return s[n.name]=r},app:a,registerVersion:_p,setLogLevel:bp,onLog:wp,apps:null,SDK_VERSION:gp,INTERNAL:{registerComponent:function(n){const r=n.name,t=r.replace("-compat","");{var e;hp(n)&&"PUBLIC"===n.type&&(e=(e=a())=>{if("function"!=typeof e[t])throw Ep.create("invalid-app-argument",{appName:r});return e[t]()},void 0!==n.serviceProps&&nd(e,n.serviceProps),o[t]=e,i.prototype[t]=function(...e){const t=this._getService.bind(this,r);return t.apply(this,n.multipleInstances?e:[])})}return"PUBLIC"===n.type?o[t]:null},removeApp:function(e){delete s[e]},useAsService:function(e,t){if("serverAuth"===t)return null;var n=t;return n},modularAPIs:Ip}};function a(e){if(e=e||sp,!bd(s,e))throw Ep.create("no-app",{appName:e});return s[e]}return o.default=o,Object.defineProperty(o,"apps",{get:function(){return Object.keys(s).map(e=>s[e])}}),a.App=i,o}l=function e(){const t=kp(Tp);return t.INTERNAL=Object.assign(Object.assign({},t.INTERNAL),{createFirebaseNamespace:e,extendNamespace:function(e){nd(t,e)},createSubscribe:Pd,ErrorFactory:md,deepExtend:nd}),t}();const Sp=new ep("@firebase/app-compat");if("object"==typeof self&&self.self===self&&void 0!==self.firebase){Sp.warn(`
    Warning: Firebase is already defined in the global scope. Please make sure
    Firebase library is only loaded once.
  `);const ez=self.firebase.SDK_VERSION;ez&&0<=ez.indexOf("LITE")&&Sp.warn(`
    Warning: You are trying to load Firebase while using Firebase Performance standalone script.
    You should load Firebase Performance with this instance of Firebase to avoid loading duplicate code.
    `)}const Cp=l;_p("@firebase/app-compat","0.1.17",void 0);Cp.registerVersion("firebase","9.6.6","app-compat");function Ap(n){return new Promise(function(e,t){n.onsuccess=function(){e(n.result)},n.onerror=function(){t(n.error)}})}function Np(n,r,i){var s,e=new Promise(function(e,t){Ap(s=n[r].apply(n,i)).then(e,t)});return e.request=s,e}function Rp(e,n,t){t.forEach(function(t){Object.defineProperty(e.prototype,t,{get:function(){return this[n][t]},set:function(e){this[n][t]=e}})})}function Pp(t,n,r,e){e.forEach(function(e){e in r.prototype&&(t.prototype[e]=function(){return Np(this[n],e,arguments)})})}function xp(t,n,r,e){e.forEach(function(e){e in r.prototype&&(t.prototype[e]=function(){return this[n][e].apply(this[n],arguments)})})}function Op(e,r,t,n){n.forEach(function(n){n in t.prototype&&(e.prototype[n]=function(){return e=this[r],(t=Np(e,n,arguments)).then(function(e){if(e)return new Lp(e,t.request)});var e,t})})}function Dp(e){this._index=e}function Lp(e,t){this._cursor=e,this._request=t}function Mp(e){this._store=e}function Fp(n){this._tx=n,this.complete=new Promise(function(e,t){n.oncomplete=function(){e()},n.onerror=function(){t(n.error)},n.onabort=function(){t(n.error)}})}function Up(e,t,n){this._db=e,this.oldVersion=t,this.transaction=new Fp(n)}function jp(e){this._db=e}function qp(e,t,n){var r=Np(indexedDB,"open",[e,t]),i=r.request;return i&&(i.onupgradeneeded=function(e){n&&n(new Up(i.result,e.oldVersion,i.transaction))}),r.then(function(e){return new jp(e)})}function Vp(e){return Np(indexedDB,"deleteDatabase",[e])}Rp(Dp,"_index",["name","keyPath","multiEntry","unique"]),Pp(Dp,"_index",IDBIndex,["get","getKey","getAll","getAllKeys","count"]),Op(Dp,"_index",IDBIndex,["openCursor","openKeyCursor"]),Rp(Lp,"_cursor",["direction","key","primaryKey","value"]),Pp(Lp,"_cursor",IDBCursor,["update","delete"]),["advance","continue","continuePrimaryKey"].forEach(function(n){n in IDBCursor.prototype&&(Lp.prototype[n]=function(){var t=this,e=arguments;return Promise.resolve().then(function(){return t._cursor[n].apply(t._cursor,e),Ap(t._request).then(function(e){if(e)return new Lp(e,t._request)})})})}),Mp.prototype.createIndex=function(){return new Dp(this._store.createIndex.apply(this._store,arguments))},Mp.prototype.index=function(){return new Dp(this._store.index.apply(this._store,arguments))},Rp(Mp,"_store",["name","keyPath","indexNames","autoIncrement"]),Pp(Mp,"_store",IDBObjectStore,["put","add","delete","clear","get","getAll","getKey","getAllKeys","count"]),Op(Mp,"_store",IDBObjectStore,["openCursor","openKeyCursor"]),xp(Mp,"_store",IDBObjectStore,["deleteIndex"]),Fp.prototype.objectStore=function(){return new Mp(this._tx.objectStore.apply(this._tx,arguments))},Rp(Fp,"_tx",["objectStoreNames","mode"]),xp(Fp,"_tx",IDBTransaction,["abort"]),Up.prototype.createObjectStore=function(){return new Mp(this._db.createObjectStore.apply(this._db,arguments))},Rp(Up,"_db",["name","version","objectStoreNames"]),xp(Up,"_db",IDBDatabase,["deleteObjectStore","close"]),jp.prototype.transaction=function(){return new Fp(this._db.transaction.apply(this._db,arguments))},Rp(jp,"_db",["name","version","objectStoreNames"]),xp(jp,"_db",IDBDatabase,["close"]),["openCursor","openKeyCursor"].forEach(function(s){[Mp,Dp].forEach(function(e){s in e.prototype&&(e.prototype[s.replace("open","iterate")]=function(){var e,t=(e=arguments,Array.prototype.slice.call(e)),n=t[t.length-1],r=this._store||this._index,i=r[s].apply(r,t.slice(0,-1));i.onsuccess=function(){n(i.result)}})})}),[Dp,Mp].forEach(function(e){e.prototype.getAll||(e.prototype.getAll=function(e,n){var r=this,i=[];return new Promise(function(t){r.iterateCursor(e,function(e){e?(i.push(e.value),void 0===n||i.length!=n?e.continue():t(i)):t(i)})})})});$e="@firebase/installations",c="0.5.5";const Bp=1e4,Wp="w:0.5.5",zp="FIS_v2",Kp="https://firebaseinstallations.googleapis.com/v1",$p=36e5;const Hp=new md("installations","Installations",{"missing-app-config-values":'Missing App configuration value: "{$valueName}"',"not-registered":"Firebase Installation is not registered.","installation-not-found":"Firebase Installation not found.","request-failed":'{$requestName} request failed with error "{$serverCode} {$serverStatus}: {$serverMessage}"',"app-offline":"Could not process request. Application offline.","delete-pending-registration":"Can't delete installation while there is a pending registration request."});function Gp(e){return e instanceof gd&&e.code.includes("request-failed")}function Qp({projectId:e}){return`${Kp}/projects/${e}/installations`}function Yp(e){return{token:e.token,requestStatus:2,expiresIn:(e=e.expiresIn,Number(e.replace("s","000"))),creationTime:Date.now()}}async function Xp(e,t){var n=(await t.json()).error;return Hp.create("request-failed",{requestName:e,serverCode:n.code,serverMessage:n.message,serverStatus:n.status})}function Jp({apiKey:e}){return new Headers({"Content-Type":"application/json",Accept:"application/json","x-goog-api-key":e})}function Zp(e,{refreshToken:t}){const n=Jp(e);return n.append("Authorization",(t=t,`${zp} ${t}`)),n}async function ef(e){var t=await e();return 500<=t.status&&t.status<600?e():t}function tf(t){return new Promise(e=>{setTimeout(e,t)})}const nf=/^[cdef][\w-]{21}$/,rf="";function sf(){try{const t=new Uint8Array(17),n=self.crypto||self.msCrypto;n.getRandomValues(t),t[0]=112+t[0]%16;var e=function(e){const t=function(e){const t=btoa(String.fromCharCode(...e));return t.replace(/\+/g,"-").replace(/\//g,"_")}(e);return t.substr(0,22)}(t);return nf.test(e)?e:rf}catch(e){return rf}}function of(e){return`${e.appName}!${e.appId}`}const af=new Map;function cf(e,t){var n=of(e);lf(n,t),function(e,t){const n=function(){!uf&&"BroadcastChannel"in self&&(uf=new BroadcastChannel("[Firebase] FID Change"),uf.onmessage=e=>{lf(e.data.key,e.data.fid)});return uf}();n&&n.postMessage({key:e,fid:t});0===af.size&&uf&&(uf.close(),uf=null)}(n,t)}function lf(e,t){var n=af.get(e);if(n)for(const r of n)r(t)}let uf=null;const hf="firebase-installations-store";let df=null;function pf(){return df=df||qp("firebase-installations-database",1,e=>{0===e.oldVersion&&e.createObjectStore(hf)}),df}async function ff(e,t){var n=of(e);const r=await pf(),i=r.transaction(hf,"readwrite"),s=i.objectStore(hf);var o=await s.get(n);return await s.put(t,n),await i.complete,o&&o.fid===t.fid||cf(e,t.fid),t}async function gf(e){var t=of(e);const n=await pf(),r=n.transaction(hf,"readwrite");await r.objectStore(hf).delete(t),await r.complete}async function mf(e,t){var n=of(e);const r=await pf(),i=r.transaction(hf,"readwrite"),s=i.objectStore(hf);var o=await s.get(n),a=t(o);return void 0===a?await s.delete(n):await s.put(a,n),await i.complete,!a||o&&o.fid===a.fid||cf(e,a.fid),a}async function vf(n){let r;var e=await mf(n,e=>{var t=_f(e||{fid:sf(),registrationStatus:0}),t=function(e,t){{if(0!==t.registrationStatus)return 1===t.registrationStatus?{installationEntry:t,registrationPromise:async function(e){let t=await yf(e);for(;1===t.registrationStatus;)await tf(100),t=await yf(e);if(0!==t.registrationStatus)return t;{var{installationEntry:n,registrationPromise:r}=await vf(e);return r||n}}(e)}:{installationEntry:t};if(!navigator.onLine){var n=Promise.reject(Hp.create("app-offline"));return{installationEntry:t,registrationPromise:n}}var r={fid:t.fid,registrationStatus:1,registrationTime:Date.now()},n=async function(t,n){try{var e=await async function(e,{fid:t}){const n=Qp(e);var r=Jp(e),i={fid:t,authVersion:zp,appId:e.appId,sdkVersion:Wp};const s={method:"POST",headers:r,body:JSON.stringify(i)},o=await ef(()=>fetch(n,s));if(o.ok){i=await o.json();return{fid:i.fid||t,registrationStatus:2,refreshToken:i.refreshToken,authToken:Yp(i.authToken)}}throw await Xp("Create Installation",o)}(t,n);return ff(t,e)}catch(e){throw Gp(e)&&409===e.customData.serverCode?await gf(t):await ff(t,{fid:n.fid,registrationStatus:0}),e}}(e,r);return{installationEntry:r,registrationPromise:n}}}(n,t);return r=t.registrationPromise,t.installationEntry});return e.fid===rf?{installationEntry:await r}:{installationEntry:e,registrationPromise:r}}function yf(e){return mf(e,e=>{if(!e)throw Hp.create("installation-not-found");return _f(e)})}function _f(e){return 1===(t=e).registrationStatus&&t.registrationTime+Bp<Date.now()?{fid:e.fid,registrationStatus:0}:e;var t}async function wf({appConfig:e,platformLoggerProvider:t},n){const r=([i,s]=[e,n["fid"]],`${Qp(i)}/${s}/authTokens:generate`);var i,s;const o=Zp(e,n),a=t.getImmediate({optional:!0});a&&o.append("x-firebase-client",a.getPlatformInfoString());var c={installation:{sdkVersion:Wp}};const l={method:"POST",headers:o,body:JSON.stringify(c)},u=await ef(()=>fetch(r,l));if(u.ok)return Yp(await u.json());throw await Xp("Generate Auth Token",u)}async function bf(r,i=!1){let s;var e=await mf(r.appConfig,e=>{if(!Tf(e))throw Hp.create("not-registered");var t,n=e.authToken;if(i||2!==(t=n).requestStatus||function(e){var t=Date.now();return t<e.creationTime||e.creationTime+e.expiresIn<t+$p}(t)){if(1===n.requestStatus)return s=async function(e,t){let n=await If(e.appConfig);for(;1===n.authToken.requestStatus;)await tf(100),n=await If(e.appConfig);var r=n.authToken;return 0===r.requestStatus?bf(e,t):r}(r,i),e;if(!navigator.onLine)throw Hp.create("app-offline");n=(t=e,n={requestStatus:1,requestTime:Date.now()},Object.assign(Object.assign({},t),{authToken:n}));return s=async function(t,n){try{var r=await wf(t,n),e=Object.assign(Object.assign({},n),{authToken:r});return await ff(t.appConfig,e),r}catch(e){throw!Gp(e)||401!==e.customData.serverCode&&404!==e.customData.serverCode?(r=Object.assign(Object.assign({},n),{authToken:{requestStatus:0}}),await ff(t.appConfig,r)):await gf(t.appConfig),e}}(r,n),n}return e});return s?await s:e.authToken}function If(e){return mf(e,e=>{if(!Tf(e))throw Hp.create("not-registered");var t,n=e.authToken;return 1===(t=n).requestStatus&&t.requestTime+Bp<Date.now()?Object.assign(Object.assign({},e),{authToken:{requestStatus:0}}):e})}function Tf(e){return void 0!==e&&2===e.registrationStatus}async function Ef(e,t=!1){var n,r=e;return e=r.appConfig,await((n=(await vf(e)).registrationPromise)&&await n),(await bf(r,t)).token}function kf(e){return Hp.create("missing-app-config-values",{valueName:e})}const Sf="installations",Cf=e=>{var t=e.getProvider("app").getImmediate();return{app:t,appConfig:function(e){if(!e||!e.options)throw kf("App Configuration");if(!e.name)throw kf("App Name");for(const t of["projectId","apiKey","appId"])if(!e.options[t])throw kf(t);return{appName:e.name,projectId:e.options.projectId,apiKey:e.options.apiKey,appId:e.options.appId}}(t),platformLoggerProvider:dp(t,"platform-logger"),_delete:()=>Promise.resolve()}},Af=e=>{const t=dp(e.getProvider("app").getImmediate(),Sf).getImmediate();return{getId:()=>async function(e){var t=e;const{installationEntry:n,registrationPromise:r}=await vf(t.appConfig);return(r||bf(t)).catch(console.error),n.fid}(t),getToken:e=>Ef(t,e)}};hp(new Kd(Sf,Cf,"PUBLIC")),hp(new Kd("installations-internal",Af,"PRIVATE")),_p($e,c),_p($e,c,"esm2017");const Nf="analytics",Rf="firebase_id",Pf="origin",xf="https://firebase.googleapis.com/v1alpha/projects/-/apps/{app-id}/webConfig",Of="https://www.googletagmanager.com/gtag/js",Df=new ep("@firebase/analytics");function Lf(e){return Promise.all(e.map(e=>e.catch(e=>e)))}function Mf(r,i,s,o){return async function(e,t,n){try{"event"===e?await async function(e,n,r,i,s){try{let t=[];if(s&&s.send_to){let e=s.send_to;Array.isArray(e)||(e=[e]);const c=await Lf(r);for(const l of e){var o=c.find(e=>e.measurementId===l),a=o&&n[o.appId];if(!a){t=[];break}t.push(a)}}0===t.length&&(t=Object.values(n)),await Promise.all(t),e("event",i,s||{})}catch(e){Df.error(e)}}(r,i,s,t,n):"config"===e?await async function(e,t,n,r,i,s){var o=r[i];try{if(o)await t[o];else{const c=await Lf(n);var a=c.find(e=>e.measurementId===i);a&&await t[a.appId]}}catch(e){Df.error(e)}e("config",i,s)}(r,i,s,o,t,n):r("set",t)}catch(e){Df.error(e)}}}const Ff=new md("analytics","Analytics",{"already-exists":"A Firebase Analytics instance with the appId {$id}  already exists. Only one Firebase Analytics instance can be created for each appId.","already-initialized":"initializeAnalytics() cannot be called again with different options than those it was initially called with. It can be called again with the same options to return the existing instance, or getAnalytics() can be used to get a reference to the already-intialized instance.","already-initialized-settings":"Firebase Analytics has already been initialized.settings() must be called before initializing any Analytics instanceor it will have no effect.","interop-component-reg-failed":"Firebase Analytics Interop Component failed to instantiate: {$reason}","invalid-analytics-context":"Firebase Analytics is not supported in this environment. Wrap initialization of analytics in analytics.isSupported() to prevent initialization in unsupported environments. Details: {$errorInfo}","indexeddb-unavailable":"IndexedDB unavailable or restricted in this environment. Wrap initialization of analytics in analytics.isSupported() to prevent initialization in unsupported environments. Details: {$errorInfo}","fetch-throttle":"The config fetch request timed out while in an exponential backoff state. Unix timestamp in milliseconds when fetch request throttling ends: {$throttleEndTimeMillis}.","config-fetch-failed":"Dynamic config fetch failed: [{$httpStatus}] {$responseMessage}","no-api-key":'The "apiKey" field is empty in the local Firebase config. Firebase Analytics requires this field tocontain a valid API key.',"no-app-id":'The "appId" field is empty in the local Firebase config. Firebase Analytics requires this field tocontain a valid app ID.'}),Uf=30;const jf=new class{constructor(e={},t=1e3){this.throttleMetadata=e,this.intervalMillis=t}getThrottleMetadata(e){return this.throttleMetadata[e]}setThrottleMetadata(e,t){this.throttleMetadata[e]=t}deleteThrottleMetadata(e){delete this.throttleMetadata[e]}};async function qf(e){var t,{appId:n,apiKey:r}=e,r={method:"GET",headers:new Headers({Accept:"application/json","x-goog-api-key":r})},n=xf.replace("{app-id}",n);const i=await fetch(n,r);if(200===i.status||304===i.status)return i.json();{let e="";try{var s=await i.json();null!==(t=s.error)&&void 0!==t&&t.message&&(e=s.error.message)}catch(e){}throw Ff.create("config-fetch-failed",{httpStatus:i.status,responseMessage:e})}}async function Vf(e,t=jf,n){var{appId:r,apiKey:i,measurementId:s}=e.options;if(!r)throw Ff.create("no-app-id");if(!i){if(s)return{measurementId:s,appId:r};throw Ff.create("no-api-key")}var o=t.getThrottleMetadata(r)||{backoffCount:0,throttleEndTimeMillis:Date.now()};const a=new zf;return setTimeout(async()=>{a.abort()},void 0!==n?n:6e4),async function t(n,{throttleEndTimeMillis:e,backoffCount:r},i,s=jf){const{appId:o,measurementId:a}=n;try{await Bf(i,e)}catch(e){if(a)return Df.warn("Timed out fetching this Firebase app's measurement ID from the server."+` Falling back to the measurement ID ${a}`+` provided in the "measurementId" field in the local Firebase config. [${e.message}]`),{appId:o,measurementId:a};throw e}try{const c=await qf(n);return s.deleteThrottleMetadata(o),c}catch(e){if(!Wf(e)){if(s.deleteThrottleMetadata(o),a)return Df.warn("Failed to fetch this Firebase app's measurement ID from the server."+` Falling back to the measurement ID ${a}`+` provided in the "measurementId" field in the local Firebase config. [${e.message}]`),{appId:o,measurementId:a};throw e}const l=503===Number(e.customData.httpStatus)?Wd(r,s.intervalMillis,Uf):Wd(r,s.intervalMillis),u={throttleEndTimeMillis:Date.now()+l,backoffCount:r+1};return s.setThrottleMetadata(o,u),Df.debug(`Calling attemptFetch again in ${l} millis`),t(n,u,i,s)}}({appId:r,apiKey:i,measurementId:s},o,a,t)}function Bf(i,s){return new Promise((e,t)=>{var n=Math.max(s-Date.now(),0);const r=setTimeout(e,n);i.addEventListener(()=>{clearTimeout(r),t(Ff.create("fetch-throttle",{throttleEndTimeMillis:s}))})})}function Wf(e){if(!(e instanceof gd&&e.customData))return!1;var t=Number(e.customData.httpStatus);return 429===t||500===t||503===t||504===t}class zf{constructor(){this.listeners=[]}addEventListener(e){this.listeners.push(e)}abort(){this.listeners.forEach(e=>e())}}async function Kf(t,e,n,r,i,s,o){const a=Vf(t);a.then(e=>{n[e.measurementId]=e.appId,t.options.measurementId&&e.measurementId!==t.options.measurementId&&Df.warn(`The measurement ID in the local Firebase config (${t.options.measurementId})`+` does not match the measurement ID fetched from the server (${e.measurementId}).`+" To ensure analytics events are always sent to the correct Analytics property, update the measurement ID field in the local config or remove it from the local config.")}).catch(e=>Df.error(e)),e.push(a);var c=async function(){if(!dd())return Df.warn(Ff.create("indexeddb-unavailable",{errorInfo:"IndexedDB is not available in this environment."}).message),!1;try{await pd()}catch(e){return Df.warn(Ff.create("indexeddb-unavailable",{errorInfo:e}).message),!1}return!0}().then(e=>{if(e)return r.getId()}),[l,u]=await Promise.all([a,c]);!function(){var e=window.document.getElementsByTagName("script");for(const t of Object.values(e))if(t.src&&t.src.includes(Of))return t}()&&function(e,t){const n=document.createElement("script");n.src=`${Of}?l=${e}&id=${t}`,n.async=!0,document.head.appendChild(n)}(s,l.measurementId),i("js",new Date);const h=null!==(c=null==o?void 0:o.config)&&void 0!==c?c:{};return h[Pf]="firebase",h.update=!0,null!=u&&(h[Rf]=u),i("config",l.measurementId,h),l.measurementId}class $f{constructor(e){this.app=e}_delete(){return delete Hf[this.app.options.appId],Promise.resolve()}}let Hf={},Gf=[];const Qf={};let Yf="dataLayer",Xf="gtag",Jf,Zf,eg=!1;function tg(e){if(eg)throw Ff.create("already-initialized");e.dataLayerName&&(Yf=e.dataLayerName),e.gtagName&&(Xf=e.gtagName)}function ng(e,t,n){!function(){const e=[];var t;cd()&&e.push("This is a browser extension environment."),fd()||e.push("Cookies are not available."),0<e.length&&(t=e.map((e,t)=>`(${t+1}) ${e}`).join(" "),t=Ff.create("invalid-analytics-context",{errorInfo:t}),Df.warn(t.message))}();var r,i,s=e.options.appId;if(!s)throw Ff.create("no-app-id");if(!e.options.apiKey){if(!e.options.measurementId)throw Ff.create("no-api-key");Df.warn('The "apiKey" field is empty in the local Firebase config. This is needed to fetch the latest'+` measurement ID for this Firebase app. Falling back to the measurement ID ${e.options.measurementId}`+' provided in the "measurementId" field in the local Firebase config.')}if(null!=Hf[s])throw Ff.create("already-exists",{id:s});return eg||(function(e){let t=[];Array.isArray(window[e])?t=window[e]:window[e]=t,t}(Yf),{wrappedGtag:r,gtagCore:i}=function(e,t,n,r,i){let s=function(){window[r].push(arguments)};return window[i]&&"function"==typeof window[i]&&(s=window[i]),window[i]=Mf(s,e,t,n),{gtagCore:s,wrappedGtag:window[i]}}(Hf,Gf,Qf,Yf,Xf),Zf=r,Jf=i,eg=!0),Hf[s]=Kf(e,Gf,Qf,t,Jf,Yf,n),new $f(e)}async function rg(){if(cd())return!1;if(!fd())return!1;if(!dd())return!1;try{return await pd()}catch(e){return!1}}function ig(e,t,n){e=zd(e),async function(e,t,n,r){if(r&&r.global)return e("set",{screen_name:n}),Promise.resolve();e("config",await t,{update:!0,screen_name:n})}(Zf,Hf[e.app.options.appId],t,n).catch(e=>Df.error(e))}function sg(e,t,n){e=zd(e),async function(e,t,n,r){if(r&&r.global)return e("set",{user_id:n}),Promise.resolve();e("config",await t,{update:!0,user_id:n})}(Zf,Hf[e.app.options.appId],t,n).catch(e=>Df.error(e))}function og(e,t,n){e=zd(e),async function(e,t,n,r){if(r&&r.global){const i={};for(const s of Object.keys(n))i[`user_properties.${s}`]=n[s];return e("set",i),Promise.resolve()}e("config",await t,{update:!0,user_properties:n})}(Zf,Hf[e.app.options.appId],t,n).catch(e=>Df.error(e))}function ag(e,t){e=zd(e),async function(e,t){var n=await e;window[`ga-disable-${n}`]=!t}(Hf[e.app.options.appId],t).catch(e=>Df.error(e))}function cg(e,t,n,r){e=zd(e),async function(e,t,n,r,i){var s;i&&i.global?e("event",n,r):(s=await t,e("event",n,Object.assign(Object.assign({},r),{send_to:s})))}(Zf,Hf[e.app.options.appId],t,n,r).catch(e=>Df.error(e))}const lg="@firebase/analytics";hp(new Kd(Nf,(e,{options:t})=>{return ng(e.getProvider("app").getImmediate(),e.getProvider("installations-internal").getImmediate(),t)},"PUBLIC")),hp(new Kd("analytics-internal",function(e){try{const r=e.getProvider(Nf).getImmediate();return{logEvent:(e,t,n)=>cg(r,e,t,n)}}catch(e){throw Ff.create("interop-component-reg-failed",{reason:e})}},"PRIVATE")),_p(lg,"0.7.5"),_p(lg,"0.7.5","esm2017");var ug,hg;class dg{constructor(e,t){this.app=e,this._delegate=t}logEvent(e,t,n){cg(this._delegate,e,t,n)}setCurrentScreen(e,t){ig(this._delegate,e,t)}setUserId(e,t){sg(this._delegate,e,t)}setUserProperties(e,t){og(this._delegate,e,t)}setAnalyticsCollectionEnabled(e){ag(this._delegate,e)}}($=ug=ug||{}).ADD_SHIPPING_INFO="add_shipping_info",$.ADD_PAYMENT_INFO="add_payment_info",$.ADD_TO_CART="add_to_cart",$.ADD_TO_WISHLIST="add_to_wishlist",$.BEGIN_CHECKOUT="begin_checkout",$.CHECKOUT_PROGRESS="checkout_progress",$.EXCEPTION="exception",$.GENERATE_LEAD="generate_lead",$.LOGIN="login",$.PAGE_VIEW="page_view",$.PURCHASE="purchase",$.REFUND="refund",$.REMOVE_FROM_CART="remove_from_cart",$.SCREEN_VIEW="screen_view",$.SEARCH="search",$.SELECT_CONTENT="select_content",$.SELECT_ITEM="select_item",$.SELECT_PROMOTION="select_promotion",$.SET_CHECKOUT_OPTION="set_checkout_option",$.SHARE="share",$.SIGN_UP="sign_up",$.TIMING_COMPLETE="timing_complete",$.VIEW_CART="view_cart",$.VIEW_ITEM="view_item",$.VIEW_ITEM_LIST="view_item_list",$.VIEW_PROMOTION="view_promotion",$.VIEW_SEARCH_RESULTS="view_search_results";const pg=e=>{var t=e.getProvider("app-compat").getImmediate(),n=e.getProvider("analytics").getImmediate();return new dg(t,n)};hg={Analytics:dg,settings:tg,isSupported:rg,EventName:ug},Cp.INTERNAL.registerComponent(new Kd("analytics-compat",pg,"PUBLIC").setServiceProps(hg).setMultipleInstances(!0)),Cp.registerVersion("@firebase/analytics-compat","0.1.6");const fg=new Map,gg={activated:!1,tokenObservers:[]},mg={initialized:!1,enabled:!1};function vg(e){return fg.get(e)||gg}function yg(e,t){fg.set(e,t)}const _g="https://content-firebaseappcheck.googleapis.com/v1beta",wg="exchangeDebugToken",bg={OFFSET_DURATION:3e5,RETRIAL_MIN_WAIT:3e4,RETRIAL_MAX_WAIT:96e4};class Ig{constructor(e,t,n,r,i){if(this.operation=e,this.retryPolicy=t,this.getWaitDuration=n,this.lowerBound=r,this.upperBound=i,this.pending=null,i<(this.nextErrorWaitInterval=r))throw new Error("Proactive refresh lower bound greater than upper bound!")}start(){this.nextErrorWaitInterval=this.lowerBound,this.process(!0).catch(()=>{})}stop(){this.pending&&(this.pending.reject("cancelled"),this.pending=null)}isRunning(){return!!this.pending}async process(e){this.stop();try{this.pending=new rd,t=this.getNextRun(e),await new Promise(e=>{setTimeout(e,t)}),this.pending.resolve(),await this.pending.promise,this.pending=new rd,await this.operation(),this.pending.resolve(),await this.pending.promise,this.process(!0).catch(()=>{})}catch(e){this.retryPolicy(e)?this.process(!1).catch(()=>{}):this.stop()}var t}getNextRun(e){if(e)return this.nextErrorWaitInterval=this.lowerBound,this.getWaitDuration();var t=this.nextErrorWaitInterval;return this.nextErrorWaitInterval*=2,this.nextErrorWaitInterval>this.upperBound&&(this.nextErrorWaitInterval=this.upperBound),t}}const Tg=new md("appCheck","AppCheck",{"already-initialized":"You have already called initializeAppCheck() for FirebaseApp {$appName} with different options. To avoid this error, call initializeAppCheck() with the same options as when it was originally called. This will return the already initialized instance.","use-before-activation":"App Check is being used before initializeAppCheck() is called for FirebaseApp {$appName}. Call initializeAppCheck() before instantiating other Firebase services.","fetch-network-error":"Fetch failed to connect to a network. Check Internet connection. Original error: {$originalErrorMessage}.","fetch-parse-error":"Fetch client could not parse response. Original error: {$originalErrorMessage}.","fetch-status-error":"Fetch server returned an HTTP error status. HTTP status: {$httpStatus}.","storage-open":"Error thrown when opening storage. Original error: {$originalErrorMessage}.","storage-get":"Error thrown when reading from storage. Original error: {$originalErrorMessage}.","storage-set":"Error thrown when writing to storage. Original error: {$originalErrorMessage}.","recaptcha-error":"ReCAPTCHA error.",throttled:"Requests throttled due to {$httpStatus} error. Attempts allowed again after {$time}"});function Eg(e=!1){var t;return e?null===(t=self.grecaptcha)||void 0===t?void 0:t.enterprise:self.grecaptcha}function kg(e){if(!vg(e).activated)throw Tg.create("use-before-activation",{appName:e.name})}function Sg(e){var t=Math.round(e/1e3),n=Math.floor(t/86400),r=Math.floor((t-3600*n*24)/3600),i=Math.floor((t-3600*n*24-3600*r)/60),t=t-3600*n*24-3600*r-60*i;let s="";return n&&(s+=Cg(n)+"d:"),r&&(s+=Cg(r)+"h:"),s+=Cg(i)+"m:"+Cg(t)+"s",s}function Cg(e){return 0===e?"00":10<=e?e.toString():"0"+e}async function Ag({url:e,body:t},n){const r={"Content-Type":"application/json"},i=n.getImmediate({optional:!0});i&&(r["X-Firebase-Client"]=i.getPlatformInfoString());var s={method:"POST",body:JSON.stringify(t),headers:r};let o;try{o=await fetch(e,s)}catch(e){throw Tg.create("fetch-network-error",{originalErrorMessage:e.message})}if(200!==o.status)throw Tg.create("fetch-status-error",{httpStatus:o.status});let a;try{a=await o.json()}catch(e){throw Tg.create("fetch-parse-error",{originalErrorMessage:e.message})}var c=a.ttl.match(/^([\d.]+)(s)$/);if(!c||!c[2]||isNaN(Number(c[1])))throw Tg.create("fetch-parse-error",{originalErrorMessage:"ttl field (timeToLive) is not in standard Protobuf Duration "+`format: ${a.ttl}`});s=1e3*Number(c[1]),c=Date.now();return{token:a.attestationToken,expireTimeMillis:c+s,issuedAtTimeMillis:c}}const Ng="firebase-app-check-database",Rg=1,Pg="firebase-app-check-store",xg="debug-token";let Og=null;function Dg(){return Og||(Og=new Promise((t,n)=>{try{const e=indexedDB.open(Ng,Rg);e.onsuccess=e=>{t(e.target.result)},e.onerror=e=>{var t;n(Tg.create("storage-open",{originalErrorMessage:null===(t=e.target.error)||void 0===t?void 0:t.message}))},e.onupgradeneeded=e=>{const t=e.target.result;0===e.oldVersion&&t.createObjectStore(Pg,{keyPath:"compositeKey"})}}catch(e){n(Tg.create("storage-open",{originalErrorMessage:e.message}))}}),Og)}async function Lg(e,t){const n=await Dg(),r=n.transaction(Pg,"readwrite"),i=r.objectStore(Pg),s=i.put({compositeKey:e,value:t});return new Promise((t,n)=>{s.onsuccess=e=>{t()},r.onerror=e=>{var t;n(Tg.create("storage-set",{originalErrorMessage:null===(t=e.target.error)||void 0===t?void 0:t.message}))}})}async function Mg(e){const t=await Dg(),i=t.transaction(Pg,"readonly"),n=i.objectStore(Pg),s=n.get(e);return new Promise((n,r)=>{s.onsuccess=e=>{var t=e.target.result;n(t?t.value:void 0)},i.onerror=e=>{var t;r(Tg.create("storage-get",{originalErrorMessage:null===(t=e.target.error)||void 0===t?void 0:t.message}))}})}function Fg(e){return`${e.options.appId}-${e.name}`}const Ug=new ep("@firebase/app-check");async function jg(t){if(dd()){let e=void 0;try{e=await Mg(Fg(t))}catch(e){Ug.warn(`Failed to read token from IndexedDB. Error: ${e}`)}return e}}function qg(e,t){return dd()?Lg(Fg(e),t).catch(e=>{Ug.warn(`Failed to write token to IndexedDB. Error: ${e}`)}):Promise.resolve()}async function Vg(){let e=void 0;try{e=await Mg(xg)}catch(e){}if(e)return e;var t,n="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=16*Math.random()|0,n="x"===e?t:3&t|8;return n.toString(16)});return t=n,Lg(xg,t).catch(e=>Ug.warn(`Failed to persist debug token to IndexedDB. Error: ${e}`)),n}function Bg(){return mg.enabled}async function Wg(){var e=mg;if(e.enabled&&e.token)return e.token.promise;throw Error(`
            Can't get debug token in production mode.
        `)}function zg(){var e=function(){if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if("undefined"!=typeof global)return global;throw new Error("Unable to locate global object.")}();const t=mg;if(t.initialized=!0,"string"==typeof e.FIREBASE_APPCHECK_DEBUG_TOKEN||!0===e.FIREBASE_APPCHECK_DEBUG_TOKEN){t.enabled=!0;const n=new rd;t.token=n,"string"==typeof e.FIREBASE_APPCHECK_DEBUG_TOKEN?n.resolve(e.FIREBASE_APPCHECK_DEBUG_TOKEN):n.resolve(Vg())}}const Kg={error:"UNKNOWN_ERROR"};async function $g(e,t=!1){var n=e.app;kg(n);const r=vg(n);let i=r.token,s=void 0;if(i||(a=await r.cachedTokenPromise)&&Xg(a)&&(i=a),!t&&i&&Xg(i))return{token:i.token};let o=!1;if(Bg()){r.exchangeTokenPromise||(r.exchangeTokenPromise=Ag(function(e,t){var{projectId:n,appId:r,apiKey:i}=e.options;return{url:`${_g}/projects/${n}/apps/${r}:${wg}?key=${i}`,body:{debug_token:t}}}(n,await Wg()),e.platformLoggerProvider).then(e=>(r.exchangeTokenPromise=void 0,e)),o=!0);var a=await r.exchangeTokenPromise;return await qg(n,a),yg(n,Object.assign(Object.assign({},r),{token:a})),{token:a.token}}try{r.exchangeTokenPromise||(r.exchangeTokenPromise=r.provider.getToken().then(e=>(r.exchangeTokenPromise=void 0,e)),o=!0),i=await r.exchangeTokenPromise}catch(e){"appCheck/throttled"===e.code?Ug.warn(e.message):Ug.error(e),s=e}let c;return i?(c={token:i.token},yg(n,Object.assign(Object.assign({},r),{token:i})),await qg(n,i)):c=(e=s,{token:function(e){return Zh.encodeString(JSON.stringify(e),!1)}(Kg),error:e}),o&&Yg(n,c),c}function Hg(e,t,n,r){var i=e["app"];const s=vg(i);var o={next:n,error:r,type:t};if(yg(i,Object.assign(Object.assign({},s),{tokenObservers:[...s.tokenObservers,o]})),s.token&&Xg(s.token)){const a=s.token;Promise.resolve().then(()=>{n({token:a.token}),Qg(e)}).catch(()=>{})}s.cachedTokenPromise.then(()=>Qg(e))}function Gg(e,t){const n=vg(e);var r=n.tokenObservers.filter(e=>e.next!==t);0===r.length&&n.tokenRefresher&&n.tokenRefresher.isRunning()&&n.tokenRefresher.stop(),yg(e,Object.assign(Object.assign({},n),{tokenObservers:r}))}function Qg(e){var t=e["app"],n=vg(t);let r=n.tokenRefresher;r||(r=function(n){const r=n["app"];return new Ig(async()=>{var e=vg(r);let t;if(t=e.token?await $g(n,!0):await $g(n),t.error)throw t.error},()=>!0,()=>{var e=vg(r);if(e.token){var t=e.token.issuedAtTimeMillis+.5*(e.token.expireTimeMillis-e.token.issuedAtTimeMillis)+3e5,e=e.token.expireTimeMillis-3e5,t=Math.min(t,e);return Math.max(0,t-Date.now())}return 0},bg.RETRIAL_MIN_WAIT,bg.RETRIAL_MAX_WAIT)}(e),yg(t,Object.assign(Object.assign({},n),{tokenRefresher:r}))),!r.isRunning()&&n.isTokenAutoRefreshEnabled&&r.start()}function Yg(e,t){for(const n of vg(e).tokenObservers)try{"EXTERNAL"===n.type&&null!=t.error?n.error(t.error):n.next(t)}catch(e){}}function Xg(e){return 0<e.expireTimeMillis-Date.now()}class Jg{constructor(e,t){this.app=e,this.platformLoggerProvider=t}_delete(){var e=vg(this.app)["tokenObservers"];for(const t of e)Gg(this.app,t.next);return Promise.resolve()}}const Zg="https://www.google.com/recaptcha/api.js",em="https://www.google.com/recaptcha/enterprise.js";function tm(t,n){var e=vg(t);const r=new rd;yg(t,Object.assign(Object.assign({},e),{reCAPTCHAState:{initialized:r}}));const i=im(t);e=Eg(!1);return e?rm(t,n,e,i,r):function(e){const t=document.createElement("script");t.src=Zg,t.onload=e,document.head.appendChild(t)}(()=>{var e=Eg(!1);if(!e)throw new Error("no recaptcha");rm(t,n,e,i,r)}),r.promise}function nm(t,n){var e=vg(t);const r=new rd;yg(t,Object.assign(Object.assign({},e),{reCAPTCHAState:{initialized:r}}));const i=im(t);e=Eg(!0);return e?rm(t,n,e,i,r):function(e){const t=document.createElement("script");t.src=em,t.onload=e,document.head.appendChild(t)}(()=>{var e=Eg(!0);if(!e)throw new Error("no recaptcha");rm(t,n,e,i,r)}),r.promise}function rm(r,i,s,o,a){s.ready(()=>{var e,t,n;e=r,t=s.render(o,{sitekey:i,size:"invisible"}),n=vg(e),yg(e,Object.assign(Object.assign({},n),{reCAPTCHAState:Object.assign(Object.assign({},n.reCAPTCHAState),{widgetId:t})})),a.resolve(s)})}function im(e){var t=`fire_app_check_${e.name}`;const n=document.createElement("div");return n.id=t,n.style.display="none",document.body.appendChild(n),t}async function sm(r){kg(r);const i=await vg(r).reCAPTCHAState.initialized.promise;return new Promise((e,t)=>{const n=vg(r).reCAPTCHAState;i.ready(()=>{e(i.execute(n.widgetId,{action:"fire_app_check"}))})})}class om{constructor(e){this._siteKey=e,this._throttleData=null}async getToken(){um(this._throttleData);var t=await sm(this._app).catch(e=>{throw Tg.create("recaptcha-error")});let e;try{e=await Ag(function(e,t){var{projectId:n,appId:r,apiKey:i}=e.options;return{url:`${_g}/projects/${n}/apps/${r}:exchangeRecaptchaToken?key=${i}`,body:{recaptcha_token:t}}}(this._app,t),this._platformLoggerProvider)}catch(e){throw"fetch-status-error"===e.code?(this._throttleData=lm(Number(null===(t=e.customData)||void 0===t?void 0:t.httpStatus),this._throttleData),Tg.create("throttled",{time:Sg(this._throttleData.allowRequestsAfter-Date.now()),httpStatus:this._throttleData.httpStatus})):e}return this._throttleData=null,e}initialize(e){this._app=e,this._platformLoggerProvider=dp(e,"platform-logger"),tm(e,this._siteKey).catch(()=>{})}isEqual(e){return e instanceof om&&this._siteKey===e._siteKey}}class am{constructor(e){this._siteKey=e,this._throttleData=null}async getToken(){um(this._throttleData);var t=await sm(this._app).catch(e=>{throw Tg.create("recaptcha-error")});let e;try{e=await Ag(function(e,t){var{projectId:n,appId:r,apiKey:i}=e.options;return{url:`${_g}/projects/${n}/apps/${r}:exchangeRecaptchaEnterpriseToken?key=${i}`,body:{recaptcha_enterprise_token:t}}}(this._app,t),this._platformLoggerProvider)}catch(e){throw"fetch-status-error"===e.code?(this._throttleData=lm(Number(null===(t=e.customData)||void 0===t?void 0:t.httpStatus),this._throttleData),Tg.create("throttled",{time:Sg(this._throttleData.allowRequestsAfter-Date.now()),httpStatus:this._throttleData.httpStatus})):e}return this._throttleData=null,e}initialize(e){this._app=e,this._platformLoggerProvider=dp(e,"platform-logger"),nm(e,this._siteKey).catch(()=>{})}isEqual(e){return e instanceof am&&this._siteKey===e._siteKey}}class cm{constructor(e){this._customProviderOptions=e}async getToken(){var e=await this._customProviderOptions.getToken(),t=function(e){const t=wd(e).claims;return"object"==typeof t&&t.hasOwnProperty("iat")?t.iat:null}(e.token),t=null!==t&&t<Date.now()&&0<t?1e3*t:Date.now();return Object.assign(Object.assign({},e),{issuedAtTimeMillis:t})}initialize(e){this._app=e}isEqual(e){return e instanceof cm&&this._customProviderOptions.getToken.toString()===e._customProviderOptions.getToken.toString()}}function lm(e,t){if(404===e||403===e)return{backoffCount:1,allowRequestsAfter:Date.now()+864e5,httpStatus:e};var n=t?t.backoffCount:0,r=Wd(n,1e3,2);return{backoffCount:n+1,allowRequestsAfter:Date.now()+r,httpStatus:e}}function um(e){if(e&&Date.now()-e.allowRequestsAfter<=0)throw Tg.create("throttled",{time:Sg(e.allowRequestsAfter-Date.now()),httpStatus:e.httpStatus})}function hm(e=vp(),t){const n=dp(e=zd(e),"app-check");if(mg.initialized||zg(),Bg()&&Wg().then(e=>console.log(`App Check debug token: ${e}. You will need to add it to your app's App Check settings in the Firebase console for it to work.`)),n.isInitialized()){var r=n.getImmediate();const i=n.getOptions();if(i.isTokenAutoRefreshEnabled===t.isTokenAutoRefreshEnabled&&i.provider.isEqual(t.provider))return r;throw Tg.create("already-initialized",{appName:e.name})}r=n.initialize({options:t});return function(t,e,n){const r=vg(t),i=Object.assign(Object.assign({},r),{activated:!0});i.provider=e,i.cachedTokenPromise=jg(t).then(e=>(e&&Xg(e)&&(yg(t,Object.assign(Object.assign({},vg(t)),{token:e})),Yg(t,{token:e.token})),e)),i.isTokenAutoRefreshEnabled=void 0===n?t.automaticDataCollectionEnabled:n,yg(t,i),i.provider.initialize(t)}(e,t.provider,t.isTokenAutoRefreshEnabled),vg(e).isTokenAutoRefreshEnabled&&Hg(r,"INTERNAL",()=>{}),r}const dm="app-check-internal";hp(new Kd("app-check",e=>{var t,n=e.getProvider("app").getImmediate(),r=e.getProvider("platform-logger");return t=n,e=r,new Jg(t,e)},"PUBLIC").setInstantiationMode("EXPLICIT").setInstanceCreatedCallback((e,t,n)=>{e.getProvider(dm).initialize()})),hp(new Kd(dm,e=>{var t,n=e.getProvider("app-check").getImmediate();return t=n,{getToken:e=>$g(t,e),addTokenListener:e=>Hg(t,"INTERNAL",e),removeTokenListener:e=>Gg(t.app,e)}},"PUBLIC").setInstantiationMode("EXPLICIT")),_p("@firebase/app-check","0.5.3");const pm=new md("appCheck","AppCheck",{"use-before-activation":"App Check is being used before activate() is called for FirebaseApp {$appName}. Call activate() before instantiating other Firebase services."});class fm{constructor(e){this.app=e}activate(e,t){let n;n="string"==typeof e?new om(e):e instanceof am||e instanceof om||e instanceof cm?e:new cm({getToken:e.getToken}),this._delegate=hm(this.app,{provider:n,isTokenAutoRefreshEnabled:t})}setTokenAutoRefreshEnabled(e){if(!this._delegate)throw pm.create("use-before-activation",{appName:this.app.name});!function(e,t){var n=e.app;const r=vg(n);r.tokenRefresher&&(!0===t?r.tokenRefresher.start():r.tokenRefresher.stop()),yg(n,Object.assign(Object.assign({},r),{isTokenAutoRefreshEnabled:t}))}(this._delegate,e)}getToken(e){if(!this._delegate)throw pm.create("use-before-activation",{appName:this.app.name});return async function(e,t){var n=await $g(e,t);if(n.error)throw n.error;return{token:n.token}}(this._delegate,e)}onTokenChanged(e,t,n){if(!this._delegate)throw pm.create("use-before-activation",{appName:this.app.name});return function(e,t,n){let r=()=>{},i=()=>{};return r=null!=t.next?t.next.bind(t):t,null!=t.error?i=t.error.bind(t):n&&(i=n),Hg(e,"EXTERNAL",r,i),()=>Gg(e.app,r)}(this._delegate,e,t)}}const gm=e=>{var t=e.getProvider("app-compat").getImmediate();return new fm(t)};function mm(e,t){var n={};for(i in e)Object.prototype.hasOwnProperty.call(e,i)&&t.indexOf(i)<0&&(n[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var r=0,i=Object.getOwnPropertySymbols(e);r<i.length;r++)t.indexOf(i[r])<0&&Object.prototype.propertyIsEnumerable.call(e,i[r])&&(n[i[r]]=e[i[r]]);return n}Cp.INTERNAL.registerComponent(new Kd("appCheck-compat",gm,"PUBLIC").setServiceProps({ReCaptchaEnterpriseProvider:am,ReCaptchaV3Provider:om,CustomProvider:cm})),Cp.registerVersion("@firebase/app-check-compat","0.2.3");const vm={FACEBOOK:"facebook.com",GITHUB:"github.com",GOOGLE:"google.com",PASSWORD:"password",PHONE:"phone",TWITTER:"twitter.com"},ym={EMAIL_SIGNIN:"EMAIL_SIGNIN",PASSWORD_RESET:"PASSWORD_RESET",RECOVER_EMAIL:"RECOVER_EMAIL",REVERT_SECOND_FACTOR_ADDITION:"REVERT_SECOND_FACTOR_ADDITION",VERIFY_AND_CHANGE_EMAIL:"VERIFY_AND_CHANGE_EMAIL",VERIFY_EMAIL:"VERIFY_EMAIL"};function _m(){return{"dependent-sdk-initialized-before-auth":"Another Firebase SDK was initialized and is trying to use Auth before Auth is initialized. Please be sure to call `initializeAuth` or `getAuth` before starting any other Firebase SDK."}}function wm(){return{"admin-restricted-operation":"This operation is restricted to administrators only.","argument-error":"","app-not-authorized":"This app, identified by the domain where it's hosted, is not authorized to use Firebase Authentication with the provided API key. Review your key configuration in the Google API console.","app-not-installed":"The requested mobile application corresponding to the identifier (Android package name or iOS bundle ID) provided is not installed on this device.","captcha-check-failed":"The reCAPTCHA response token provided is either invalid, expired, already used or the domain associated with it does not match the list of whitelisted domains.","code-expired":"The SMS code has expired. Please re-send the verification code to try again.","cordova-not-ready":"Cordova framework is not ready.","cors-unsupported":"This browser is not supported.","credential-already-in-use":"This credential is already associated with a different user account.","custom-token-mismatch":"The custom token corresponds to a different audience.","requires-recent-login":"This operation is sensitive and requires recent authentication. Log in again before retrying this request.","dependent-sdk-initialized-before-auth":"Another Firebase SDK was initialized and is trying to use Auth before Auth is initialized. Please be sure to call `initializeAuth` or `getAuth` before starting any other Firebase SDK.","dynamic-link-not-activated":"Please activate Dynamic Links in the Firebase Console and agree to the terms and conditions.","email-change-needs-verification":"Multi-factor users must always have a verified email.","email-already-in-use":"The email address is already in use by another account.","emulator-config-failed":'Auth instance has already been used to make a network call. Auth can no longer be configured to use the emulator. Try calling "connectAuthEmulator()" sooner.',"expired-action-code":"The action code has expired.","cancelled-popup-request":"This operation has been cancelled due to another conflicting popup being opened.","internal-error":"An internal AuthError has occurred.","invalid-app-credential":"The phone verification request contains an invalid application verifier. The reCAPTCHA token response is either invalid or expired.","invalid-app-id":"The mobile app identifier is not registed for the current project.","invalid-user-token":"This user's credential isn't valid for this project. This can happen if the user's token has been tampered with, or if the user isn't for the project associated with this API key.","invalid-auth-event":"An internal AuthError has occurred.","invalid-verification-code":"The SMS verification code used to create the phone auth credential is invalid. Please resend the verification code sms and be sure to use the verification code provided by the user.","invalid-continue-uri":"The continue URL provided in the request is invalid.","invalid-cordova-configuration":"The following Cordova plugins must be installed to enable OAuth sign-in: cordova-plugin-buildinfo, cordova-universal-links-plugin, cordova-plugin-browsertab, cordova-plugin-inappbrowser and cordova-plugin-customurlscheme.","invalid-custom-token":"The custom token format is incorrect. Please check the documentation.","invalid-dynamic-link-domain":"The provided dynamic link domain is not configured or authorized for the current project.","invalid-email":"The email address is badly formatted.","invalid-emulator-scheme":"Emulator URL must start with a valid scheme (http:// or https://).","invalid-api-key":"Your API key is invalid, please check you have copied it correctly.","invalid-cert-hash":"The SHA-1 certificate hash provided is invalid.","invalid-credential":"The supplied auth credential is malformed or has expired.","invalid-message-payload":"The email template corresponding to this action contains invalid characters in its message. Please fix by going to the Auth email templates section in the Firebase Console.","invalid-multi-factor-session":"The request does not contain a valid proof of first factor successful sign-in.","invalid-oauth-provider":"EmailAuthProvider is not supported for this operation. This operation only supports OAuth providers.","invalid-oauth-client-id":"The OAuth client ID provided is either invalid or does not match the specified API key.","unauthorized-domain":"This domain is not authorized for OAuth operations for your Firebase project. Edit the list of authorized domains from the Firebase console.","invalid-action-code":"The action code is invalid. This can happen if the code is malformed, expired, or has already been used.","wrong-password":"The password is invalid or the user does not have a password.","invalid-persistence-type":"The specified persistence type is invalid. It can only be local, session or none.","invalid-phone-number":"The format of the phone number provided is incorrect. Please enter the phone number in a format that can be parsed into E.164 format. E.164 phone numbers are written in the format [+][country code][subscriber number including area code].","invalid-provider-id":"The specified provider ID is invalid.","invalid-recipient-email":"The email corresponding to this action failed to send as the provided recipient email address is invalid.","invalid-sender":"The email template corresponding to this action contains an invalid sender email or name. Please fix by going to the Auth email templates section in the Firebase Console.","invalid-verification-id":"The verification ID used to create the phone auth credential is invalid.","invalid-tenant-id":"The Auth instance's tenant ID is invalid.","missing-android-pkg-name":"An Android Package Name must be provided if the Android App is required to be installed.","auth-domain-config-required":"Be sure to include authDomain when calling firebase.initializeApp(), by following the instructions in the Firebase console.","missing-app-credential":"The phone verification request is missing an application verifier assertion. A reCAPTCHA response token needs to be provided.","missing-verification-code":"The phone auth credential was created with an empty SMS verification code.","missing-continue-uri":"A continue URL must be provided in the request.","missing-iframe-start":"An internal AuthError has occurred.","missing-ios-bundle-id":"An iOS Bundle ID must be provided if an App Store ID is provided.","missing-or-invalid-nonce":"The request does not contain a valid nonce. This can occur if the SHA-256 hash of the provided raw nonce does not match the hashed nonce in the ID token payload.","missing-multi-factor-info":"No second factor identifier is provided.","missing-multi-factor-session":"The request is missing proof of first factor successful sign-in.","missing-phone-number":"To send verification codes, provide a phone number for the recipient.","missing-verification-id":"The phone auth credential was created with an empty verification ID.","app-deleted":"This instance of FirebaseApp has been deleted.","multi-factor-info-not-found":"The user does not have a second factor matching the identifier provided.","multi-factor-auth-required":"Proof of ownership of a second factor is required to complete sign-in.","account-exists-with-different-credential":"An account already exists with the same email address but different sign-in credentials. Sign in using a provider associated with this email address.","network-request-failed":"A network AuthError (such as timeout, interrupted connection or unreachable host) has occurred.","no-auth-event":"An internal AuthError has occurred.","no-such-provider":"User was not linked to an account with the given provider.","null-user":"A null user object was provided as the argument for an operation which requires a non-null user object.","operation-not-allowed":"The given sign-in provider is disabled for this Firebase project. Enable it in the Firebase console, under the sign-in method tab of the Auth section.","operation-not-supported-in-this-environment":'This operation is not supported in the environment this application is running on. "location.protocol" must be http, https or chrome-extension and web storage must be enabled.',"popup-blocked":"Unable to establish a connection with the popup. It may have been blocked by the browser.","popup-closed-by-user":"The popup has been closed by the user before finalizing the operation.","provider-already-linked":"User can only be linked to one identity for the given provider.","quota-exceeded":"The project's quota for this operation has been exceeded.","redirect-cancelled-by-user":"The redirect operation has been cancelled by the user before finalizing.","redirect-operation-pending":"A redirect sign-in operation is already pending.","rejected-credential":"The request contains malformed or mismatching credentials.","second-factor-already-in-use":"The second factor is already enrolled on this account.","maximum-second-factor-count-exceeded":"The maximum allowed number of second factors on a user has been exceeded.","tenant-id-mismatch":"The provided tenant ID does not match the Auth instance's tenant ID",timeout:"The operation has timed out.","user-token-expired":"The user's credential is no longer valid. The user must sign in again.","too-many-requests":"We have blocked all requests from this device due to unusual activity. Try again later.","unauthorized-continue-uri":"The domain of the continue URL is not whitelisted.  Please whitelist the domain in the Firebase console.","unsupported-first-factor":"Enrolling a second factor or signing in with a multi-factor account requires sign-in with a supported first factor.","unsupported-persistence-type":"The current environment does not support the specified persistence type.","unsupported-tenant-operation":"This operation is not supported in a multi-tenant context.","unverified-email":"The operation requires a verified email.","user-cancelled":"The user did not grant your application the permissions it requested.","user-not-found":"There is no user record corresponding to this identifier. The user may have been deleted.","user-disabled":"The user account has been disabled by an administrator.","user-mismatch":"The supplied credentials do not correspond to the previously signed in user.","user-signed-out":"","weak-password":"The password must be 6 characters long or more.","web-storage-unsupported":"This browser is not supported or 3rd party cookies and data may be disabled.","already-initialized":"initializeAuth() has already been called with different options. To avoid this error, call initializeAuth() with the same options as when it was originally called, or call getAuth() to return the already initialized instance."}}const bm=_m,Im=new md("auth","Firebase",_m()),Tm=new ep("@firebase/auth");function Em(e,...t){Tm.logLevel<=zh.ERROR&&Tm.error(`Auth (${gp}): ${e}`,...t)}function km(e,...t){throw Nm(e,...t)}function Sm(e,...t){return Nm(e,...t)}function Cm(e,t,n){var r=Object.assign(Object.assign({},bm()),{[t]:n});const i=new md("auth","Firebase",r);return i.create(t,{appName:e.name})}function Am(e,t,n){if(!(t instanceof n))throw n.name!==t.constructor.name&&km(e,"argument-error"),Cm(e,"argument-error",`Type of ${t.constructor.name} does not match expected instance.`+"Did you pass a reference from a different Auth SDK?")}function Nm(e,...t){if("string"==typeof e)return Im.create(e,...t);{var n=t[0];const r=[...t.slice(1)];return r[0]&&(r[0].appName=e.name),e._errorFactory.create(n,...r)}}function Rm(e,t,...n){if(!e)throw Nm(t,...n)}function Pm(e){var t="INTERNAL ASSERTION FAILED: "+e;throw Em(t),new Error(t)}function xm(e,t){e||Pm(t)}const Om=new Map;function Dm(e){xm(e instanceof Function,"Expected a class definition");let t=Om.get(e);return t?xm(t instanceof e,"Instance stored in cache mismatched with class"):(t=new e,Om.set(e,t)),t}function Lm(){var e;return"undefined"!=typeof self&&(null===(e=self.location)||void 0===e?void 0:e.href)||""}function Mm(){return"http:"===Fm()||"https:"===Fm()}function Fm(){var e;return"undefined"!=typeof self&&(null===(e=self.location)||void 0===e?void 0:e.protocol)||null}class Um{constructor(e,t){xm((this.shortDelay=e)<(this.longDelay=t),"Short delay should be less than long delay!"),this.isMobile=od()||ld()}get(){return"undefined"!=typeof navigator&&navigator&&"onLine"in navigator&&"boolean"==typeof navigator.onLine&&(Mm()||cd()||"connection"in navigator)&&!navigator.onLine?Math.min(5e3,this.shortDelay):this.isMobile?this.longDelay:this.shortDelay}}function jm(e,t){xm(e.emulator,"Emulator should always be set here");var n=e.emulator["url"];return t?`${n}${t.startsWith("/")?t.slice(1):t}`:n}class qm{static initialize(e,t,n){this.fetchImpl=e,t&&(this.headersImpl=t),n&&(this.responseImpl=n)}static fetch(){return this.fetchImpl||("undefined"!=typeof self&&"fetch"in self?self.fetch:void Pm("Could not find fetch implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill"))}static headers(){return this.headersImpl||("undefined"!=typeof self&&"Headers"in self?self.Headers:void Pm("Could not find Headers implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill"))}static response(){return this.responseImpl||("undefined"!=typeof self&&"Response"in self?self.Response:void Pm("Could not find Response implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill"))}}const Vm={CREDENTIAL_MISMATCH:"custom-token-mismatch",MISSING_CUSTOM_TOKEN:"internal-error",INVALID_IDENTIFIER:"invalid-email",MISSING_CONTINUE_URI:"internal-error",INVALID_PASSWORD:"wrong-password",MISSING_PASSWORD:"internal-error",EMAIL_EXISTS:"email-already-in-use",PASSWORD_LOGIN_DISABLED:"operation-not-allowed",INVALID_IDP_RESPONSE:"invalid-credential",INVALID_PENDING_TOKEN:"invalid-credential",FEDERATED_USER_ID_ALREADY_LINKED:"credential-already-in-use",MISSING_REQ_TYPE:"internal-error",EMAIL_NOT_FOUND:"user-not-found",RESET_PASSWORD_EXCEED_LIMIT:"too-many-requests",EXPIRED_OOB_CODE:"expired-action-code",INVALID_OOB_CODE:"invalid-action-code",MISSING_OOB_CODE:"internal-error",CREDENTIAL_TOO_OLD_LOGIN_AGAIN:"requires-recent-login",INVALID_ID_TOKEN:"invalid-user-token",TOKEN_EXPIRED:"user-token-expired",USER_NOT_FOUND:"user-token-expired",TOO_MANY_ATTEMPTS_TRY_LATER:"too-many-requests",INVALID_CODE:"invalid-verification-code",INVALID_SESSION_INFO:"invalid-verification-id",INVALID_TEMPORARY_PROOF:"invalid-credential",MISSING_SESSION_INFO:"missing-verification-id",SESSION_EXPIRED:"code-expired",MISSING_ANDROID_PACKAGE_NAME:"missing-android-pkg-name",UNAUTHORIZED_DOMAIN:"unauthorized-continue-uri",INVALID_OAUTH_CLIENT_ID:"invalid-oauth-client-id",ADMIN_ONLY_OPERATION:"admin-restricted-operation",INVALID_MFA_PENDING_CREDENTIAL:"invalid-multi-factor-session",MFA_ENROLLMENT_NOT_FOUND:"multi-factor-info-not-found",MISSING_MFA_ENROLLMENT_ID:"missing-multi-factor-info",MISSING_MFA_PENDING_CREDENTIAL:"missing-multi-factor-session",SECOND_FACTOR_EXISTS:"second-factor-already-in-use",SECOND_FACTOR_LIMIT_EXCEEDED:"maximum-second-factor-count-exceeded",BLOCKING_FUNCTION_ERROR_RESPONSE:"internal-error"},Bm=new Um(3e4,6e4);function Wm(e,t){return e.tenantId&&!t.tenantId?Object.assign(Object.assign({},t),{tenantId:e.tenantId}):t}async function zm(i,s,o,a,e={}){return Km(i,e,async()=>{let e={},t={};a&&("GET"===s?t=a:e={body:JSON.stringify(a)});var n=Cd(Object.assign({key:i.config.apiKey},t)).slice(1);const r=await i._getAdditionalHeaders();return r["Content-Type"]="application/json",i.languageCode&&(r["X-Firebase-Locale"]=i.languageCode),qm.fetch()(Hm(i,i.config.apiHost,o,n),Object.assign({method:s,headers:r,referrerPolicy:"no-referrer"},e))})}async function Km(t,e,n){t._canInitEmulator=!1;var r=Object.assign(Object.assign({},Vm),e);try{const o=new Gm(t),a=await Promise.race([n(),o.promise]);o.clearNetworkTimeout();var i=await a.json();if("needConfirmation"in i)throw Qm(t,"account-exists-with-different-credential",i);if(a.ok&&!("errorMessage"in i))return i;{const c=a.ok?i.errorMessage:i.error.message,[l,u]=c.split(" : ");if("FEDERATED_USER_ID_ALREADY_LINKED"===l)throw Qm(t,"credential-already-in-use",i);if("EMAIL_EXISTS"===l)throw Qm(t,"email-already-in-use",i);var s=r[l]||l.toLowerCase().replace(/[_\s]+/g,"-");if(u)throw Cm(t,s,u);km(t,s)}}catch(e){if(e instanceof gd)throw e;km(t,"network-request-failed")}}async function $m(e,t,n,r,i={}){var s=await zm(e,t,n,r,i);return"mfaPendingCredential"in s&&km(e,"multi-factor-auth-required",{_serverResponse:s}),s}function Hm(e,t,n,r){var i=`${t}${n}?${r}`;return e.config.emulator?jm(e.config,i):`${e.config.apiScheme}://${i}`}class Gm{constructor(e){this.auth=e,this.timer=null,this.promise=new Promise((e,t)=>{this.timer=setTimeout(()=>t(Sm(this.auth,"network-request-failed")),Bm.get())})}clearNetworkTimeout(){clearTimeout(this.timer)}}function Qm(e,t,n){const r={appName:e.name};n.email&&(r.email=n.email),n.phoneNumber&&(r.phoneNumber=n.phoneNumber);const i=Sm(e,t,r);return i.customData._tokenResponse=n,i}function Ym(e){if(e)try{const t=new Date(Number(e));if(!isNaN(t.getTime()))return t.toUTCString()}catch(e){}}function Xm(e){return 1e3*Number(e)}function Jm(e){var[t,n,r]=e.split(".");if(void 0===t||void 0===n||void 0===r)return Em("JWT malformed, contained fewer than 3 sections"),null;try{var i=td(n);return i?JSON.parse(i):(Em("Failed to decode base64 JWT payload"),null)}catch(e){return Em("Caught error parsing JWT payload as JSON",e),null}}async function Zm(t,n,e=!1){if(e)return n;try{return n}catch(e){throw e instanceof gd&&(n=[e["code"]][0],"auth/user-disabled"===n||"auth/user-token-expired"===n)&&t.auth.currentUser===t&&await t.auth.signOut(),e}}class ev{constructor(e){this.user=e,this.isRunning=!1,this.timerId=null,this.errorBackoff=3e4}_start(){this.isRunning||(this.isRunning=!0,this.schedule())}_stop(){this.isRunning&&(this.isRunning=!1,null!==this.timerId&&clearTimeout(this.timerId))}getInterval(e){if(e){var t=this.errorBackoff;return this.errorBackoff=Math.min(2*this.errorBackoff,96e4),t}this.errorBackoff=3e4;t=(null!==(t=this.user.stsTokenManager.expirationTime)&&void 0!==t?t:0)-Date.now()-3e5;return Math.max(0,t)}schedule(e=!1){var t;this.isRunning&&(t=this.getInterval(e),this.timerId=setTimeout(async()=>{await this.iteration()},t))}async iteration(){try{await this.user.getIdToken(!0)}catch(e){return void("auth/network-request-failed"===e.code&&this.schedule(!0))}this.schedule()}}class tv{constructor(e,t){this.createdAt=e,this.lastLoginAt=t,this._initializeTime()}_initializeTime(){this.lastSignInTime=Ym(this.lastLoginAt),this.creationTime=Ym(this.createdAt)}_copy(e){this.createdAt=e.createdAt,this.lastLoginAt=e.lastLoginAt,this._initializeTime()}toJSON(){return{createdAt:this.createdAt,lastLoginAt:this.lastLoginAt}}}async function nv(e){var t=e.auth,n=await e.getIdToken(),r=await Zm(e,async function(e,t){return zm(e,"POST","/v1/accounts:lookup",t)}(t,{idToken:n}));Rm(null==r?void 0:r.users.length,t,"internal-error");var i=r.users[0];e._notifyReloadListener(i);var s,o,t=null!==(n=i.providerUserInfo)&&void 0!==n&&n.length?i.providerUserInfo.map(e=>{var t=e["providerId"],n=mm(e,["providerId"]);return{providerId:t,uid:n.rawId||"",displayName:n.displayName||null,email:n.email||null,phoneNumber:n.phoneNumber||null,photoURL:n.photoUrl||null}}):[],r=(s=e.providerData,o=t,[...s.filter(t=>!o.some(e=>e.providerId===t.providerId)),...o]),n=e.isAnonymous,t=!(e.email&&i.passwordHash||null!==r&&r.length),t=!!n&&t,t={uid:i.localId,displayName:i.displayName||null,photoURL:i.photoUrl||null,email:i.email||null,emailVerified:i.emailVerified||!1,phoneNumber:i.phoneNumber||null,tenantId:i.tenantId||null,providerData:r,metadata:new tv(i.createdAt,i.lastLoginAt),isAnonymous:t};Object.assign(e,t)}class rv{constructor(){this.refreshToken=null,this.accessToken=null,this.expirationTime=null}get isExpired(){return!this.expirationTime||Date.now()>this.expirationTime-3e4}updateFromServerResponse(e){Rm(e.idToken,"internal-error"),Rm(void 0!==e.idToken,"internal-error"),Rm(void 0!==e.refreshToken,"internal-error");var t,n,n="expiresIn"in e&&void 0!==e.expiresIn?Number(e.expiresIn):(t=e.idToken,Rm(n=Jm(t),"internal-error"),Rm(void 0!==n.exp,"internal-error"),Rm(void 0!==n.iat,"internal-error"),Number(n.exp)-Number(n.iat));this.updateTokensAndExpiration(e.idToken,e.refreshToken,n)}async getToken(e,t=!1){return Rm(!this.accessToken||this.refreshToken,e,"user-token-expired"),t||!this.accessToken||this.isExpired?this.refreshToken?(await this.refresh(e,this.refreshToken),this.accessToken):null:this.accessToken}clearRefreshToken(){this.refreshToken=null}async refresh(e,t){var i,s,{accessToken:n,refreshToken:r,expiresIn:o}=(s=t,await{accessToken:(o=await Km(i=e,{},async()=>{var e=Cd({grant_type:"refresh_token",refresh_token:s}).slice(1),{tokenApiHost:t,apiKey:n}=i.config,n=Hm(i,t,"/v1/token",`key=${n}`);const r=await i._getAdditionalHeaders();return r["Content-Type"]="application/x-www-form-urlencoded",qm.fetch()(n,{method:"POST",headers:r,body:e})})).access_token,expiresIn:o.expires_in,refreshToken:o.refresh_token});this.updateTokensAndExpiration(n,r,Number(o))}updateTokensAndExpiration(e,t,n){this.refreshToken=t||null,this.accessToken=e||null,this.expirationTime=Date.now()+1e3*n}static fromJSON(e,t){var{refreshToken:n,accessToken:r,expirationTime:i}=t;const s=new rv;return n&&(Rm("string"==typeof n,"internal-error",{appName:e}),s.refreshToken=n),r&&(Rm("string"==typeof r,"internal-error",{appName:e}),s.accessToken=r),i&&(Rm("number"==typeof i,"internal-error",{appName:e}),s.expirationTime=i),s}toJSON(){return{refreshToken:this.refreshToken,accessToken:this.accessToken,expirationTime:this.expirationTime}}_assign(e){this.accessToken=e.accessToken,this.refreshToken=e.refreshToken,this.expirationTime=e.expirationTime}_clone(){return Object.assign(new rv,this.toJSON())}_performRefresh(){return Pm("not implemented")}}function iv(e,t){Rm("string"==typeof e||void 0===e,"internal-error",{appName:t})}class sv{constructor(e){var{uid:t,auth:n,stsTokenManager:r}=e,i=mm(e,["uid","auth","stsTokenManager"]);this.providerId="firebase",this.proactiveRefresh=new ev(this),this.reloadUserInfo=null,this.reloadListener=null,this.uid=t,this.auth=n,this.stsTokenManager=r,this.accessToken=r.accessToken,this.displayName=i.displayName||null,this.email=i.email||null,this.emailVerified=i.emailVerified||!1,this.phoneNumber=i.phoneNumber||null,this.photoURL=i.photoURL||null,this.isAnonymous=i.isAnonymous||!1,this.tenantId=i.tenantId||null,this.providerData=i.providerData?[...i.providerData]:[],this.metadata=new tv(i.createdAt||void 0,i.lastLoginAt||void 0)}async getIdToken(e){var t=await Zm(this,this.stsTokenManager.getToken(this.auth,e));return Rm(t,this.auth,"internal-error"),this.accessToken!==t&&(this.accessToken=t,await this.auth._persistUserIfCurrent(this),this.auth._notifyListenersIfCurrent(this)),t}getIdTokenResult(e){return async function(e,t=!1){const n=zd(e);var r=await n.getIdToken(t),i=Jm(r);Rm(i&&i.exp&&i.auth_time&&i.iat,n.auth,"internal-error");var s="object"==typeof i.firebase?i.firebase:void 0,o=null==s?void 0:s.sign_in_provider;return{claims:i,token:r,authTime:Ym(Xm(i.auth_time)),issuedAtTime:Ym(Xm(i.iat)),expirationTime:Ym(Xm(i.exp)),signInProvider:o||null,signInSecondFactor:(null==s?void 0:s.sign_in_second_factor)||null}}(this,e)}reload(){return async function(e){const t=zd(e);await nv(t),await t.auth._persistUserIfCurrent(t),t.auth._notifyListenersIfCurrent(t)}(this)}_assign(e){this!==e&&(Rm(this.uid===e.uid,this.auth,"internal-error"),this.displayName=e.displayName,this.photoURL=e.photoURL,this.email=e.email,this.emailVerified=e.emailVerified,this.phoneNumber=e.phoneNumber,this.isAnonymous=e.isAnonymous,this.tenantId=e.tenantId,this.providerData=e.providerData.map(e=>Object.assign({},e)),this.metadata._copy(e.metadata),this.stsTokenManager._assign(e.stsTokenManager))}_clone(e){return new sv(Object.assign(Object.assign({},this),{auth:e,stsTokenManager:this.stsTokenManager._clone()}))}_onReload(e){Rm(!this.reloadListener,this.auth,"internal-error"),this.reloadListener=e,this.reloadUserInfo&&(this._notifyReloadListener(this.reloadUserInfo),this.reloadUserInfo=null)}_notifyReloadListener(e){this.reloadListener?this.reloadListener(e):this.reloadUserInfo=e}_startProactiveRefresh(){this.proactiveRefresh._start()}_stopProactiveRefresh(){this.proactiveRefresh._stop()}async _updateTokensIfNecessary(e,t=!1){let n=!1;e.idToken&&e.idToken!==this.stsTokenManager.accessToken&&(this.stsTokenManager.updateFromServerResponse(e),n=!0),t&&await nv(this),await this.auth._persistUserIfCurrent(this),n&&this.auth._notifyListenersIfCurrent(this)}async delete(){var e=await this.getIdToken();return await Zm(this,async function(e,t){return zm(e,"POST","/v1/accounts:delete",t)}(this.auth,{idToken:e})),this.stsTokenManager.clearRefreshToken(),this.auth.signOut()}toJSON(){return Object.assign(Object.assign({uid:this.uid,email:this.email||void 0,emailVerified:this.emailVerified,displayName:this.displayName||void 0,isAnonymous:this.isAnonymous,photoURL:this.photoURL||void 0,phoneNumber:this.phoneNumber||void 0,tenantId:this.tenantId||void 0,providerData:this.providerData.map(e=>Object.assign({},e)),stsTokenManager:this.stsTokenManager.toJSON(),_redirectEventId:this._redirectEventId},this.metadata.toJSON()),{apiKey:this.auth.config.apiKey,appName:this.auth.name})}get refreshToken(){return this.stsTokenManager.refreshToken||""}static _fromJSON(e,t){var n=null!==(o=t.displayName)&&void 0!==o?o:void 0,r=null!==(g=t.email)&&void 0!==g?g:void 0,i=null!==(a=t.phoneNumber)&&void 0!==a?a:void 0,s=null!==(l=t.photoURL)&&void 0!==l?l:void 0,o=null!==(c=t.tenantId)&&void 0!==c?c:void 0,a=null!==(g=t._redirectEventId)&&void 0!==g?g:void 0,c=null!==(l=t.createdAt)&&void 0!==l?l:void 0,l=null!==(g=t.lastLoginAt)&&void 0!==g?g:void 0;const{uid:u,emailVerified:h,isAnonymous:d,providerData:p,stsTokenManager:f}=t;Rm(u&&f,e,"internal-error");var g=rv.fromJSON(this.name,f);Rm("string"==typeof u,e,"internal-error"),iv(n,e.name),iv(r,e.name),Rm("boolean"==typeof h,e,"internal-error"),Rm("boolean"==typeof d,e,"internal-error"),iv(i,e.name),iv(s,e.name),iv(o,e.name),iv(a,e.name),iv(c,e.name),iv(l,e.name);const m=new sv({uid:u,auth:e,email:r,emailVerified:h,displayName:n,isAnonymous:d,photoURL:s,phoneNumber:i,tenantId:o,stsTokenManager:g,createdAt:c,lastLoginAt:l});return p&&Array.isArray(p)&&(m.providerData=p.map(e=>Object.assign({},e))),a&&(m._redirectEventId=a),m}static async _fromIdTokenResponse(e,t,n=!1){const r=new rv;r.updateFromServerResponse(t);var i=new sv({uid:t.localId,auth:e,stsTokenManager:r,isAnonymous:n});return await nv(i),i}}class ov{constructor(){this.type="NONE",this.storage={}}async _isAvailable(){return!0}async _set(e,t){this.storage[e]=t}async _get(e){var t=this.storage[e];return void 0===t?null:t}async _remove(e){delete this.storage[e]}_addListener(e,t){}_removeListener(e,t){}}ov.type="NONE";const av=ov;function cv(e,t,n){return`firebase:${e}:${t}:${n}`}class lv{constructor(e,t,n){this.persistence=e,this.auth=t,this.userKey=n;var{config:r,name:i}=this.auth;this.fullUserKey=cv(this.userKey,r.apiKey,i),this.fullPersistenceKey=cv("persistence",r.apiKey,i),this.boundEventHandler=t._onStorageEvent.bind(t),this.persistence._addListener(this.fullUserKey,this.boundEventHandler)}setCurrentUser(e){return this.persistence._set(this.fullUserKey,e.toJSON())}async getCurrentUser(){var e=await this.persistence._get(this.fullUserKey);return e?sv._fromJSON(this.auth,e):null}removeCurrentUser(){return this.persistence._remove(this.fullUserKey)}savePersistenceForRedirect(){return this.persistence._set(this.fullPersistenceKey,this.persistence.type)}async setPersistence(e){if(this.persistence!==e){var t=await this.getCurrentUser();return await this.removeCurrentUser(),this.persistence=e,t?this.setCurrentUser(t):void 0}}delete(){this.persistence._removeListener(this.fullUserKey,this.boundEventHandler)}static async create(e,t,n="authUser"){if(!t.length)return new lv(Dm(av),e,n);const r=(await Promise.all(t.map(async e=>{if(await e._isAvailable())return e}))).filter(e=>e);let i=r[0]||Dm(av);const s=cv(n,e.config.apiKey,e.name);let o=null;for(const u of t)try{var a=await u._get(s);if(a){var c=sv._fromJSON(e,a);u!==i&&(o=c),i=u;break}}catch(e){}var l=r.filter(e=>e._shouldAllowMigration);return i._shouldAllowMigration&&l.length&&(i=l[0],o&&await i._set(s,o.toJSON()),await Promise.all(t.map(async e=>{if(e!==i)try{await e._remove(s)}catch(e){}}))),new lv(i,e,n)}}function uv(e){const t=e.toLowerCase();if(t.includes("opera/")||t.includes("opr/")||t.includes("opios/"))return"Opera";if(fv(t))return"IEMobile";if(t.includes("msie")||t.includes("trident/"))return"IE";if(t.includes("edge/"))return"Edge";if(hv(t))return"Firefox";if(t.includes("silk/"))return"Silk";if(mv(t))return"Blackberry";if(vv(t))return"Webos";if(dv(t))return"Safari";if((t.includes("chrome/")||pv(t))&&!t.includes("edge/"))return"Chrome";if(gv(t))return"Android";var n=e.match(/([a-zA-Z\d\.]+)\/[a-zA-Z\d\.]*$/);return 2===(null==n?void 0:n.length)?n[1]:"Other"}function hv(e=sd()){return/firefox\//i.test(e)}function dv(e=sd()){const t=e.toLowerCase();return t.includes("safari/")&&!t.includes("chrome/")&&!t.includes("crios/")&&!t.includes("android")}function pv(e=sd()){return/crios\//i.test(e)}function fv(e=sd()){return/iemobile/i.test(e)}function gv(e=sd()){return/android/i.test(e)}function mv(e=sd()){return/blackberry/i.test(e)}function vv(e=sd()){return/webos/i.test(e)}function yv(e=sd()){return/iphone|ipad|ipod/i.test(e)}function _v(e=sd()){return yv(e)||gv(e)||vv(e)||mv(e)||/windows phone/i.test(e)||fv(e)}function wv(e,t=[]){let n;switch(e){case"Browser":n=uv(sd());break;case"Worker":n=`${uv(sd())}-${e}`;break;default:n=e}var r=t.length?t.join(","):"FirebaseCore-web";return`${n}/JsCore/${gp}/${r}`}class bv{constructor(e,t){this.app=e,this.config=t,this.currentUser=null,this.emulatorConfig=null,this.operations=Promise.resolve(),this.authStateSubscription=new Tv(this),this.idTokenSubscription=new Tv(this),this.redirectUser=null,this.isProactiveRefreshEnabled=!1,this._canInitEmulator=!0,this._isInitialized=!1,this._deleted=!1,this._initializationPromise=null,this._popupRedirectResolver=null,this._errorFactory=Im,this.lastNotifiedUid=void 0,this.languageCode=null,this.tenantId=null,this.settings={appVerificationDisabledForTesting:!1},this.frameworks=[],this.name=e.name,this.clientVersion=t.sdkClientVersion}_initializeWithPersistence(t,n){return n&&(this._popupRedirectResolver=Dm(n)),this._initializationPromise=this.queue(async()=>{var e;if(!this._deleted&&(this.persistenceManager=await lv.create(this,t),!this._deleted)){if(null!==(e=this._popupRedirectResolver)&&void 0!==e&&e._shouldInitProactively)try{await this._popupRedirectResolver._initialize(this)}catch(e){}await this.initializeCurrentUser(n),this.lastNotifiedUid=(null===(e=this.currentUser)||void 0===e?void 0:e.uid)||null,this._deleted||(this._isInitialized=!0)}}),this._initializationPromise}async _onStorageEvent(){if(!this._deleted){var e=await this.assertedPersistence.getCurrentUser();if(this.currentUser||e)return this.currentUser&&e&&this.currentUser.uid===e.uid?(this._currentUser._assign(e),void await this.currentUser.getIdToken()):void await this._updateCurrentUser(e)}}async initializeCurrentUser(e){var t,n,r;let i=await this.assertedPersistence.getCurrentUser();return e&&this.config.authDomain&&(await this.getOrInitRedirectPersistenceManager(),t=null===(r=this.redirectUser)||void 0===r?void 0:r._redirectEventId,n=null===i||void 0===i?void 0:i._redirectEventId,r=await this.tryRedirectSignIn(e),t&&t!==n||null==r||!r.user||(i=r.user)),i?i._redirectEventId?(Rm(this._popupRedirectResolver,this,"argument-error"),await this.getOrInitRedirectPersistenceManager(),this.redirectUser&&this.redirectUser._redirectEventId===i._redirectEventId?this.directlySetCurrentUser(i):this.reloadAndSetCurrentUserOrClear(i)):this.reloadAndSetCurrentUserOrClear(i):this.directlySetCurrentUser(null)}async tryRedirectSignIn(e){let t=null;try{t=await this._popupRedirectResolver._completeRedirectFn(this,e,!0)}catch(e){await this._setRedirectUser(null)}return t}async reloadAndSetCurrentUserOrClear(e){try{await nv(e)}catch(e){if("auth/network-request-failed"!==e.code)return this.directlySetCurrentUser(null)}return this.directlySetCurrentUser(e)}useDeviceLanguage(){this.languageCode=function(){if("undefined"==typeof navigator)return null;var e=navigator;return e.languages&&e.languages[0]||e.language||null}()}async _delete(){this._deleted=!0}async updateCurrentUser(e){const t=e?zd(e):null;return t&&Rm(t.auth.config.apiKey===this.config.apiKey,this,"invalid-user-token"),this._updateCurrentUser(t&&t._clone(this))}async _updateCurrentUser(e){if(!this._deleted)return e&&Rm(this.tenantId===e.tenantId,this,"tenant-id-mismatch"),this.queue(async()=>{await this.directlySetCurrentUser(e),this.notifyAuthListeners()})}async signOut(){return(this.redirectPersistenceManager||this._popupRedirectResolver)&&await this._setRedirectUser(null),this._updateCurrentUser(null)}setPersistence(e){return this.queue(async()=>{await this.assertedPersistence.setPersistence(Dm(e))})}_getPersistence(){return this.assertedPersistence.persistence.type}_updateErrorMap(e){this._errorFactory=new md("auth","Firebase",e())}onAuthStateChanged(e,t,n){return this.registerStateListener(this.authStateSubscription,e,t,n)}onIdTokenChanged(e,t,n){return this.registerStateListener(this.idTokenSubscription,e,t,n)}toJSON(){var e;return{apiKey:this.config.apiKey,authDomain:this.config.authDomain,appName:this.name,currentUser:null===(e=this._currentUser)||void 0===e?void 0:e.toJSON()}}async _setRedirectUser(e,t){const n=await this.getOrInitRedirectPersistenceManager(t);return null===e?n.removeCurrentUser():n.setCurrentUser(e)}async getOrInitRedirectPersistenceManager(e){var t;return this.redirectPersistenceManager||(Rm(t=e&&Dm(e)||this._popupRedirectResolver,this,"argument-error"),this.redirectPersistenceManager=await lv.create(this,[Dm(t._redirectPersistence)],"redirectUser"),this.redirectUser=await this.redirectPersistenceManager.getCurrentUser()),this.redirectPersistenceManager}async _redirectUserForId(e){var t;return this._isInitialized&&await this.queue(async()=>{}),(null===(t=this._currentUser)||void 0===t?void 0:t._redirectEventId)===e?this._currentUser:(null===(t=this.redirectUser)||void 0===t?void 0:t._redirectEventId)===e?this.redirectUser:null}async _persistUserIfCurrent(e){if(e===this.currentUser)return this.queue(async()=>this.directlySetCurrentUser(e))}_notifyListenersIfCurrent(e){e===this.currentUser&&this.notifyAuthListeners()}_key(){return`${this.config.authDomain}:${this.config.apiKey}:${this.name}`}_startProactiveRefresh(){this.isProactiveRefreshEnabled=!0,this.currentUser&&this._currentUser._startProactiveRefresh()}_stopProactiveRefresh(){this.isProactiveRefreshEnabled=!1,this.currentUser&&this._currentUser._stopProactiveRefresh()}get _currentUser(){return this.currentUser}notifyAuthListeners(){var e;this._isInitialized&&(this.idTokenSubscription.next(this.currentUser),e=null!==(e=null===(e=this.currentUser)||void 0===e?void 0:e.uid)&&void 0!==e?e:null,this.lastNotifiedUid!==e&&(this.lastNotifiedUid=e,this.authStateSubscription.next(this.currentUser)))}registerStateListener(e,t,n,r){if(this._deleted)return()=>{};const i="function"==typeof t?t:t.next.bind(t),s=this._isInitialized?Promise.resolve():this._initializationPromise;return Rm(s,this,"internal-error"),s.then(()=>i(this.currentUser)),"function"==typeof t?e.addObserver(t,n,r):e.addObserver(t)}async directlySetCurrentUser(e){this.currentUser&&this.currentUser!==e&&(this._currentUser._stopProactiveRefresh(),e&&this.isProactiveRefreshEnabled&&e._startProactiveRefresh()),(this.currentUser=e)?await this.assertedPersistence.setCurrentUser(e):await this.assertedPersistence.removeCurrentUser()}queue(e){return this.operations=this.operations.then(e,e),this.operations}get assertedPersistence(){return Rm(this.persistenceManager,this,"internal-error"),this.persistenceManager}_logFramework(e){e&&!this.frameworks.includes(e)&&(this.frameworks.push(e),this.frameworks.sort(),this.clientVersion=wv(this.config.clientPlatform,this._getFrameworks()))}_getFrameworks(){return this.frameworks}async _getAdditionalHeaders(){const e={"X-Client-Version":this.clientVersion};return this.app.options.appId&&(e["X-Firebase-gmpid"]=this.app.options.appId),e}}function Iv(e){return zd(e)}class Tv{constructor(e){this.auth=e,this.observer=null,this.addObserver=Pd(e=>this.observer=e)}get next(){return Rm(this.observer,this.auth,"internal-error"),this.observer.next.bind(this.observer)}}function Ev(e,t,n){const r=Iv(e);Rm(r._canInitEmulator,r,"emulator-config-failed"),Rm(/^https?:\/\//.test(t),r,"invalid-emulator-scheme");var i=!(null==n||!n.disableWarnings);const s=kv(t);var{host:o,port:a}=function(e){const t=kv(e),n=/(\/\/)?([^?#/]+)/.exec(e.substr(t.length));if(!n)return{host:"",port:null};const r=n[2].split("@").pop()||"",i=/^(\[[^\]]+\])(:|$)/.exec(r);{if(i){var s=i[1];return{host:s,port:Sv(r.substr(s.length+1))}}var[o,s]=r.split(":");return{host:o,port:Sv(s)}}}(t);r.config.emulator={url:`${s}//${o}${null===a?"":`:${a}`}/`},r.settings.appVerificationDisabledForTesting=!0,r.emulatorConfig=Object.freeze({host:o,port:a,protocol:s.replace(":",""),options:Object.freeze({disableWarnings:i})}),i||function(){function e(){const e=document.createElement("p"),t=e.style;e.innerText="Running in emulator mode. Do not use with production credentials.",t.position="fixed",t.width="100%",t.backgroundColor="#ffffff",t.border=".1em solid #000000",t.color="#b50000",t.bottom="0px",t.left="0px",t.margin="0px",t.zIndex="10000",t.textAlign="center",e.classList.add("firebase-emulator-warning"),document.body.appendChild(e)}"undefined"!=typeof console&&"function"==typeof console.info&&console.info("WARNING: You are using the Auth Emulator, which is intended for local testing only.  Do not use with production credentials.");"undefined"!=typeof window&&"undefined"!=typeof document&&("loading"===document.readyState?window.addEventListener("DOMContentLoaded",e):e())}()}function kv(e){var t=e.indexOf(":");return t<0?"":e.substr(0,t+1)}function Sv(e){if(!e)return null;var t=Number(e);return isNaN(t)?null:t}class Cv{constructor(e,t){this.providerId=e,this.signInMethod=t}toJSON(){return Pm("not implemented")}_getIdTokenResponse(e){return Pm("not implemented")}_linkToIdToken(e,t){return Pm("not implemented")}_getReauthenticationResolver(e){return Pm("not implemented")}}async function Av(e,t){return zm(e,"POST","/v1/accounts:resetPassword",Wm(e,t))}async function Nv(e,t){return zm(e,"POST","/v1/accounts:update",t)}async function Rv(e,t){return zm(e,"POST","/v1/accounts:sendOobCode",Wm(e,t))}class Pv extends Cv{constructor(e,t,n,r=null){super("password",n),this._email=e,this._password=t,this._tenantId=r}static _fromEmailAndPassword(e,t){return new Pv(e,t,"password")}static _fromEmailAndCode(e,t,n=null){return new Pv(e,t,"emailLink",n)}toJSON(){return{email:this._email,password:this._password,signInMethod:this.signInMethod,tenantId:this._tenantId}}static fromJSON(e){var t="string"==typeof e?JSON.parse(e):e;if(null!=t&&t.email&&null!=t&&t.password){if("password"===t.signInMethod)return this._fromEmailAndPassword(t.email,t.password);if("emailLink"===t.signInMethod)return this._fromEmailAndCode(t.email,t.password,t.tenantId)}return null}async _getIdTokenResponse(e){switch(this.signInMethod){case"password":return async function(e,t){return $m(e,"POST","/v1/accounts:signInWithPassword",Wm(e,t))}(e,{returnSecureToken:!0,email:this._email,password:this._password});case"emailLink":return async function(e,t){return $m(e,"POST","/v1/accounts:signInWithEmailLink",Wm(e,t))}(e,{email:this._email,oobCode:this._password});default:km(e,"internal-error")}}async _linkToIdToken(e,t){switch(this.signInMethod){case"password":return Nv(e,{idToken:t,returnSecureToken:!0,email:this._email,password:this._password});case"emailLink":return async function(e,t){return $m(e,"POST","/v1/accounts:signInWithEmailLink",Wm(e,t))}(e,{idToken:t,email:this._email,oobCode:this._password});default:km(e,"internal-error")}}_getReauthenticationResolver(e){return this._getIdTokenResponse(e)}}async function xv(e,t){return $m(e,"POST","/v1/accounts:signInWithIdp",Wm(e,t))}class Ov extends Cv{constructor(){super(...arguments),this.pendingToken=null}static _fromParams(e){const t=new Ov(e.providerId,e.signInMethod);return e.idToken||e.accessToken?(e.idToken&&(t.idToken=e.idToken),e.accessToken&&(t.accessToken=e.accessToken),e.nonce&&!e.pendingToken&&(t.nonce=e.nonce),e.pendingToken&&(t.pendingToken=e.pendingToken)):e.oauthToken&&e.oauthTokenSecret?(t.accessToken=e.oauthToken,t.secret=e.oauthTokenSecret):km("argument-error"),t}toJSON(){return{idToken:this.idToken,accessToken:this.accessToken,secret:this.secret,nonce:this.nonce,pendingToken:this.pendingToken,providerId:this.providerId,signInMethod:this.signInMethod}}static fromJSON(e){var t="string"==typeof e?JSON.parse(e):e,{providerId:n,signInMethod:r}=t,t=mm(t,["providerId","signInMethod"]);if(!n||!r)return null;const i=new Ov(n,r);return i.idToken=t.idToken||void 0,i.accessToken=t.accessToken||void 0,i.secret=t.secret,i.nonce=t.nonce,i.pendingToken=t.pendingToken||null,i}_getIdTokenResponse(e){return xv(e,this.buildRequest())}_linkToIdToken(e,t){const n=this.buildRequest();return n.idToken=t,xv(e,n)}_getReauthenticationResolver(e){const t=this.buildRequest();return t.autoCreate=!1,xv(e,t)}buildRequest(){const e={requestUri:"http://localhost",returnSecureToken:!0};if(this.pendingToken)e.pendingToken=this.pendingToken;else{const t={};this.idToken&&(t.id_token=this.idToken),this.accessToken&&(t.access_token=this.accessToken),this.secret&&(t.oauth_token_secret=this.secret),t.providerId=this.providerId,this.nonce&&!this.pendingToken&&(t.nonce=this.nonce),e.postBody=Cd(t)}return e}}const Dv={USER_NOT_FOUND:"user-not-found"};class Lv extends Cv{constructor(e){super("phone","phone"),this.params=e}static _fromVerification(e,t){return new Lv({verificationId:e,verificationCode:t})}static _fromTokenResponse(e,t){return new Lv({phoneNumber:e,temporaryProof:t})}_getIdTokenResponse(e){return async function(e,t){return $m(e,"POST","/v1/accounts:signInWithPhoneNumber",Wm(e,t))}(e,this._makeVerificationRequest())}_linkToIdToken(e,t){return async function(e,t){var n=await $m(e,"POST","/v1/accounts:signInWithPhoneNumber",Wm(e,t));if(n.temporaryProof)throw Qm(e,"account-exists-with-different-credential",n);return n}(e,Object.assign({idToken:t},this._makeVerificationRequest()))}_getReauthenticationResolver(e){return async function(e,t){return $m(e,"POST","/v1/accounts:signInWithPhoneNumber",Wm(e,Object.assign(Object.assign({},t),{operation:"REAUTH"})),Dv)}(e,this._makeVerificationRequest())}_makeVerificationRequest(){var{temporaryProof:e,phoneNumber:t,verificationId:n,verificationCode:r}=this.params;return e&&t?{temporaryProof:e,phoneNumber:t}:{sessionInfo:n,code:r}}toJSON(){const e={providerId:this.providerId};return this.params.phoneNumber&&(e.phoneNumber=this.params.phoneNumber),this.params.temporaryProof&&(e.temporaryProof=this.params.temporaryProof),this.params.verificationCode&&(e.verificationCode=this.params.verificationCode),this.params.verificationId&&(e.verificationId=this.params.verificationId),e}static fromJSON(e){var{verificationId:t,verificationCode:n,phoneNumber:r,temporaryProof:i}=e="string"==typeof e?JSON.parse(e):e;return n||t||r||i?new Lv({verificationId:t,verificationCode:n,phoneNumber:r,temporaryProof:i}):null}}class Mv{constructor(e){var t=Ad(Nd(e)),n=null!==(r=t.apiKey)&&void 0!==r?r:null,r=null!==(i=t.oobCode)&&void 0!==i?i:null,i=function(e){switch(e){case"recoverEmail":return"RECOVER_EMAIL";case"resetPassword":return"PASSWORD_RESET";case"signIn":return"EMAIL_SIGNIN";case"verifyEmail":return"VERIFY_EMAIL";case"verifyAndChangeEmail":return"VERIFY_AND_CHANGE_EMAIL";case"revertSecondFactorAddition":return"REVERT_SECOND_FACTOR_ADDITION";default:return null}}(null!==(i=t.mode)&&void 0!==i?i:null);Rm(n&&r&&i,"argument-error"),this.apiKey=n,this.operation=i,this.code=r,this.continueUrl=null!==(r=t.continueUrl)&&void 0!==r?r:null,this.languageCode=null!==(r=t.languageCode)&&void 0!==r?r:null,this.tenantId=null!==(t=t.tenantId)&&void 0!==t?t:null}static parseLink(e){var t,n,r,t=(t=Ad(Nd(e=e)).link,n=t?Ad(Nd(t)).deep_link_id:null,((r=Ad(Nd(e)).deep_link_id)?Ad(Nd(r)).link:null)||r||n||t||e);try{return new Mv(t)}catch(e){return null}}}class Fv{constructor(){this.providerId=Fv.PROVIDER_ID}static credential(e,t){return Pv._fromEmailAndPassword(e,t)}static credentialWithLink(e,t){var n=Mv.parseLink(t);return Rm(n,"argument-error"),Pv._fromEmailAndCode(e,n.code,n.tenantId)}}Fv.PROVIDER_ID="password",Fv.EMAIL_PASSWORD_SIGN_IN_METHOD="password",Fv.EMAIL_LINK_SIGN_IN_METHOD="emailLink";class Uv{constructor(e){this.providerId=e,this.defaultLanguageCode=null,this.customParameters={}}setDefaultLanguage(e){this.defaultLanguageCode=e}setCustomParameters(e){return this.customParameters=e,this}getCustomParameters(){return this.customParameters}}class jv extends Uv{constructor(){super(...arguments),this.scopes=[]}addScope(e){return this.scopes.includes(e)||this.scopes.push(e),this}getScopes(){return[...this.scopes]}}class qv extends jv{static credentialFromJSON(e){var t="string"==typeof e?JSON.parse(e):e;return Rm("providerId"in t&&"signInMethod"in t,"argument-error"),Ov._fromParams(t)}credential(e){return this._credential(Object.assign(Object.assign({},e),{nonce:e.rawNonce}))}_credential(e){return Rm(e.idToken||e.accessToken,"argument-error"),Ov._fromParams(Object.assign(Object.assign({},e),{providerId:this.providerId,signInMethod:this.providerId}))}static credentialFromResult(e){return qv.oauthCredentialFromTaggedObject(e)}static credentialFromError(e){return qv.oauthCredentialFromTaggedObject(e.customData||{})}static oauthCredentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;var{oauthIdToken:t,oauthAccessToken:n,oauthTokenSecret:r,pendingToken:i,nonce:s,providerId:o}=e;if(!(n||r||t||i))return null;if(!o)return null;try{return new qv(o)._credential({idToken:t,accessToken:n,nonce:s,pendingToken:i})}catch(e){return null}}}class Vv extends jv{constructor(){super("facebook.com")}static credential(e){return Ov._fromParams({providerId:Vv.PROVIDER_ID,signInMethod:Vv.FACEBOOK_SIGN_IN_METHOD,accessToken:e})}static credentialFromResult(e){return Vv.credentialFromTaggedObject(e)}static credentialFromError(e){return Vv.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!(e&&"oauthAccessToken"in e))return null;if(!e.oauthAccessToken)return null;try{return Vv.credential(e.oauthAccessToken)}catch(e){return null}}}Vv.FACEBOOK_SIGN_IN_METHOD="facebook.com",Vv.PROVIDER_ID="facebook.com";class Bv extends jv{constructor(){super("google.com"),this.addScope("profile")}static credential(e,t){return Ov._fromParams({providerId:Bv.PROVIDER_ID,signInMethod:Bv.GOOGLE_SIGN_IN_METHOD,idToken:e,accessToken:t})}static credentialFromResult(e){return Bv.credentialFromTaggedObject(e)}static credentialFromError(e){return Bv.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;var{oauthIdToken:t,oauthAccessToken:n}=e;if(!t&&!n)return null;try{return Bv.credential(t,n)}catch(e){return null}}}Bv.GOOGLE_SIGN_IN_METHOD="google.com",Bv.PROVIDER_ID="google.com";class Wv extends jv{constructor(){super("github.com")}static credential(e){return Ov._fromParams({providerId:Wv.PROVIDER_ID,signInMethod:Wv.GITHUB_SIGN_IN_METHOD,accessToken:e})}static credentialFromResult(e){return Wv.credentialFromTaggedObject(e)}static credentialFromError(e){return Wv.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!(e&&"oauthAccessToken"in e))return null;if(!e.oauthAccessToken)return null;try{return Wv.credential(e.oauthAccessToken)}catch(e){return null}}}Wv.GITHUB_SIGN_IN_METHOD="github.com",Wv.PROVIDER_ID="github.com";class zv extends Cv{constructor(e,t){super(e,e),this.pendingToken=t}_getIdTokenResponse(e){return xv(e,this.buildRequest())}_linkToIdToken(e,t){const n=this.buildRequest();return n.idToken=t,xv(e,n)}_getReauthenticationResolver(e){const t=this.buildRequest();return t.autoCreate=!1,xv(e,t)}toJSON(){return{signInMethod:this.signInMethod,providerId:this.providerId,pendingToken:this.pendingToken}}static fromJSON(e){var{providerId:t,signInMethod:n,pendingToken:r}="string"==typeof e?JSON.parse(e):e;return t&&n&&r&&t===n?new zv(t,r):null}static _create(e,t){return new zv(e,t)}buildRequest(){return{requestUri:"http://localhost",returnSecureToken:!0,pendingToken:this.pendingToken}}}class Kv extends Uv{constructor(e){Rm(e.startsWith("saml."),"argument-error"),super(e)}static credentialFromResult(e){return Kv.samlCredentialFromTaggedObject(e)}static credentialFromError(e){return Kv.samlCredentialFromTaggedObject(e.customData||{})}static credentialFromJSON(e){var t=zv.fromJSON(e);return Rm(t,"argument-error"),t}static samlCredentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;var{pendingToken:t,providerId:n}=e;if(!t||!n)return null;try{return zv._create(n,t)}catch(e){return null}}}class $v extends jv{constructor(){super("twitter.com")}static credential(e,t){return Ov._fromParams({providerId:$v.PROVIDER_ID,signInMethod:$v.TWITTER_SIGN_IN_METHOD,oauthToken:e,oauthTokenSecret:t})}static credentialFromResult(e){return $v.credentialFromTaggedObject(e)}static credentialFromError(e){return $v.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;var{oauthAccessToken:t,oauthTokenSecret:n}=e;if(!t||!n)return null;try{return $v.credential(t,n)}catch(e){return null}}}async function Hv(e,t){return $m(e,"POST","/v1/accounts:signUp",Wm(e,t))}$v.TWITTER_SIGN_IN_METHOD="twitter.com",$v.PROVIDER_ID="twitter.com";class Gv{constructor(e){this.user=e.user,this.providerId=e.providerId,this._tokenResponse=e._tokenResponse,this.operationType=e.operationType}static async _fromIdTokenResponse(e,t,n,r=!1){var i=await sv._fromIdTokenResponse(e,n,r),s=Qv(n);return new Gv({user:i,providerId:s,_tokenResponse:n,operationType:t})}static async _forOperation(e,t,n){await e._updateTokensIfNecessary(n,!0);var r=Qv(n);return new Gv({user:e,providerId:r,_tokenResponse:n,operationType:t})}}function Qv(e){return e.providerId||("phoneNumber"in e?"phone":null)}class Yv extends gd{constructor(e,t,n,r){var i;super(t.code,t.message),this.operationType=n,this.user=r,Object.setPrototypeOf(this,Yv.prototype),this.customData={appName:e.name,tenantId:null!==(i=e.tenantId)&&void 0!==i?i:void 0,_serverResponse:t.customData._serverResponse,operationType:n}}static _fromErrorAndOperation(e,t,n,r){return new Yv(e,t,n,r)}}function Xv(t,n,e,r){const i="reauthenticate"===n?e._getReauthenticationResolver(t):e._getIdTokenResponse(t);return i.catch(e=>{if("auth/multi-factor-auth-required"===e.code)throw Yv._fromErrorAndOperation(t,e,n,r);throw e})}function Jv(e){return new Set(e.map(({providerId:e})=>e).filter(e=>!!e))}async function Zv(e,t){const n=zd(e);await ty(!0,n,t);var r=(e=n.auth,t={idToken:await n.getIdToken(),deleteProvider:[t]},await zm(e,"POST","/v1/accounts:update",t))["providerUserInfo"];const i=Jv(r||[]);return n.providerData=n.providerData.filter(e=>i.has(e.providerId)),i.has("phone")||(n.phoneNumber=null),await n.auth._persistUserIfCurrent(n),n}async function ey(e,t,n=!1){var r=await Zm(e,t._linkToIdToken(e.auth,await e.getIdToken()),n);return Gv._forOperation(e,"link",r)}async function ty(e,t,n){await nv(t);const r=Jv(t.providerData);var i=!1===e?"provider-already-linked":"no-such-provider";Rm(r.has(n)===e,t.auth,i)}async function ny(e,t,n=!1){var r=e["auth"],i="reauthenticate";try{var s=await Zm(e,Xv(r,i,t,e),n);Rm(s.idToken,r,"internal-error");var o=Jm(s.idToken);Rm(o,r,"internal-error");var a=o["sub"];return Rm(e.uid===a,r,"user-mismatch"),Gv._forOperation(e,i,s)}catch(e){throw"auth/user-not-found"===(null==e?void 0:e.code)&&km(r,"user-mismatch"),e}}async function ry(e,t,n=!1){var r=await Xv(e,"signIn",t),r=await Gv._fromIdTokenResponse(e,"signIn",r);return n||await e._updateCurrentUser(r.user),r}async function iy(e,t){return ry(Iv(e),t)}async function sy(e,t){var n=zd(e);return await ty(!1,n,t.providerId),ey(n,t)}async function oy(e,t){return ny(zd(e),t)}async function ay(e,t){const n=Iv(e);var r=await $m(n,"POST","/v1/accounts:signInWithCustomToken",Wm(n,{token:t,returnSecureToken:!0})),r=await Gv._fromIdTokenResponse(n,"signIn",r);return await n._updateCurrentUser(r.user),r}class cy{constructor(e,t){this.factorId=e,this.uid=t.mfaEnrollmentId,this.enrollmentTime=new Date(t.enrolledAt).toUTCString(),this.displayName=t.displayName}static _fromServerResponse(e,t){return"phoneInfo"in t?ly._fromServerResponse(e,t):km(e,"internal-error")}}class ly extends cy{constructor(e){super("phone",e),this.phoneNumber=e.phoneInfo}static _fromServerResponse(e,t){return new ly(t)}}function uy(e,t,n){var r;Rm(0<(null===(r=n.url)||void 0===r?void 0:r.length),e,"invalid-continue-uri"),Rm(void 0===n.dynamicLinkDomain||0<n.dynamicLinkDomain.length,e,"invalid-dynamic-link-domain"),t.continueUrl=n.url,t.dynamicLinkDomain=n.dynamicLinkDomain,t.canHandleCodeInApp=n.handleCodeInApp,n.iOS&&(Rm(0<n.iOS.bundleId.length,e,"missing-ios-bundle-id"),t.iOSBundleId=n.iOS.bundleId),n.android&&(Rm(0<n.android.packageName.length,e,"missing-android-pkg-name"),t.androidInstallApp=n.android.installApp,t.androidMinimumVersionCode=n.android.minimumVersion,t.androidPackageName=n.android.packageName)}async function hy(e,t,n){var r=zd(e),i={requestType:"PASSWORD_RESET",email:t};n&&uy(r,i,n),await Rv(r,i)}async function dy(e,t){await zm(e=zd(e),"POST","/v1/accounts:update",Wm(e,{oobCode:t}))}async function py(e,t){var n=zd(e),r=await Av(n,{oobCode:t}),i=r.requestType;switch(Rm(i,n,"internal-error"),i){case"EMAIL_SIGNIN":break;case"VERIFY_AND_CHANGE_EMAIL":Rm(r.newEmail,n,"internal-error");break;case"REVERT_SECOND_FACTOR_ADDITION":Rm(r.mfaInfo,n,"internal-error");default:Rm(r.email,n,"internal-error")}let s=null;return r.mfaInfo&&(s=cy._fromServerResponse(Iv(n),r.mfaInfo)),{data:{email:("VERIFY_AND_CHANGE_EMAIL"===r.requestType?r.newEmail:r.email)||null,previousEmail:("VERIFY_AND_CHANGE_EMAIL"===r.requestType?r.email:r.newEmail)||null,multiFactorInfo:s},operation:i}}async function fy(e,t,n){var r=zd(e),i={requestType:"EMAIL_SIGNIN",email:t};Rm(n.handleCodeInApp,r,"argument-error"),n&&uy(r,i,n),await Rv(r,i)}async function gy(e,t){var n=Mm()?Lm():"http://localhost",n=(await zm(e=zd(e),"POST","/v1/accounts:createAuthUri",Wm(e,{identifier:t,continueUri:n})))["signinMethods"];return n||[]}async function my(e,t){var n=zd(e),r={requestType:"VERIFY_EMAIL",idToken:await e.getIdToken()};t&&uy(n.auth,r,t);var r=(await Rv(n.auth,r))["email"];r!==e.email&&await e.reload()}async function vy(e,t,n){var r=zd(e),i={requestType:"VERIFY_AND_CHANGE_EMAIL",idToken:await e.getIdToken(),newEmail:t};n&&uy(r.auth,i,n);var i=(await Rv(r.auth,i))["email"];i!==e.email&&await e.reload()}async function yy(e,{displayName:t,photoURL:n}){if(void 0!==t||void 0!==n){const i=zd(e);var r=await i.getIdToken(),r=await Zm(i,async function(e,t){return zm(e,"POST","/v1/accounts:update",t)}(i.auth,{idToken:r,displayName:t,photoUrl:n,returnSecureToken:!0}));i.displayName=r.displayName||null,i.photoURL=r.photoUrl||null;const s=i.providerData.find(({providerId:e})=>"password"===e);s&&(s.displayName=i.displayName,s.photoURL=i.photoURL),await i._updateTokensIfNecessary(r)}}async function _y(e,t,n){var r=e["auth"];const i={idToken:await e.getIdToken(),returnSecureToken:!0};t&&(i.email=t),n&&(i.password=n);r=await Zm(e,Nv(r,i));await e._updateTokensIfNecessary(r,!0)}class wy{constructor(e,t,n={}){this.isNewUser=e,this.providerId=t,this.profile=n}}class by extends wy{constructor(e,t,n,r){super(e,t,n),this.username=r}}class Iy extends wy{constructor(e,t){super(e,"facebook.com",t)}}class Ty extends by{constructor(e,t){super(e,"github.com",t,"string"==typeof(null==t?void 0:t.login)?null==t?void 0:t.login:null)}}class Ey extends wy{constructor(e,t){super(e,"google.com",t)}}class ky extends by{constructor(e,t,n){super(e,"twitter.com",t,n)}}function Sy(e){var{user:t,_tokenResponse:n}=e;return t.isAnonymous&&!n?{providerId:null,isNewUser:!1,profile:null}:function(e){if(!e)return null;var t=e["providerId"],n=e.rawUserInfo?JSON.parse(e.rawUserInfo):{},r=e.isNewUser||"identitytoolkit#SignupNewUserResponse"===e.kind;if(!t&&null!=e&&e.idToken){var i=null===(i=null===(i=Jm(e.idToken))||void 0===i?void 0:i.firebase)||void 0===i?void 0:i.sign_in_provider;if(i){i="anonymous"!==i&&"custom"!==i?i:null;return new wy(r,i)}}if(!t)return null;switch(t){case"facebook.com":return new Iy(r,n);case"github.com":return new Ty(r,n);case"google.com":return new Ey(r,n);case"twitter.com":return new ky(r,n,e.screenName||null);case"custom":case"anonymous":return new wy(r,null);default:return new wy(r,t,n)}}(n)}class Cy{constructor(e,t){this.type=e,this.credential=t}static _fromIdtoken(e){return new Cy("enroll",e)}static _fromMfaPendingCredential(e){return new Cy("signin",e)}toJSON(){return{multiFactorSession:{["enroll"===this.type?"idToken":"pendingCredential"]:this.credential}}}static fromJSON(e){var t;if(null!=e&&e.multiFactorSession){if(null!==(t=e.multiFactorSession)&&void 0!==t&&t.pendingCredential)return Cy._fromMfaPendingCredential(e.multiFactorSession.pendingCredential);if(null!==(t=e.multiFactorSession)&&void 0!==t&&t.idToken)return Cy._fromIdtoken(e.multiFactorSession.idToken)}return null}}class Ay{constructor(e,t,n){this.session=e,this.hints=t,this.signInResolver=n}static _fromError(e,i){const s=Iv(e),o=i.customData._serverResponse;var t=(o.mfaInfo||[]).map(e=>cy._fromServerResponse(s,e));Rm(o.mfaPendingCredential,s,"internal-error");const a=Cy._fromMfaPendingCredential(o.mfaPendingCredential);return new Ay(a,t,async e=>{var t=await e._process(s,a);delete o.mfaInfo,delete o.mfaPendingCredential;var n=Object.assign(Object.assign({},o),{idToken:t.idToken,refreshToken:t.refreshToken});switch(i.operationType){case"signIn":var r=await Gv._fromIdTokenResponse(s,i.operationType,n);return await s._updateCurrentUser(r.user),r;case"reauthenticate":return Rm(i.user,s,"internal-error"),Gv._forOperation(i.user,i.operationType,n);default:km(s,"internal-error")}})}async resolveSignIn(e){return this.signInResolver(e)}}class Ny{constructor(t){this.user=t,this.enrolledFactors=[],t._onReload(e=>{e.mfaInfo&&(this.enrolledFactors=e.mfaInfo.map(e=>cy._fromServerResponse(t.auth,e)))})}static _fromUser(e){return new Ny(e)}async getSession(){return Cy._fromIdtoken(await this.user.getIdToken())}async enroll(e,t){const n=e;var r=await this.getSession(),r=await Zm(this.user,n._process(this.user.auth,r,t));return await this.user._updateTokensIfNecessary(r),this.user.reload()}async unenroll(e){const t="string"==typeof e?e:e.uid;var n,r=await this.user.getIdToken(),r=await Zm(this.user,(n=this.user.auth,e={idToken:r,mfaEnrollmentId:t},zm(n,"POST","/v2/accounts/mfaEnrollment:withdraw",Wm(n,e))));this.enrolledFactors=this.enrolledFactors.filter(({uid:e})=>e!==t),await this.user._updateTokensIfNecessary(r);try{await this.user.reload()}catch(e){if("auth/user-token-expired"!==e.code)throw e}}}const Ry=new WeakMap;const Py="__sak";class xy{constructor(e,t){this.storageRetriever=e,this.type=t}_isAvailable(){try{return this.storage?(this.storage.setItem(Py,"1"),this.storage.removeItem(Py),Promise.resolve(!0)):Promise.resolve(!1)}catch(e){return Promise.resolve(!1)}}_set(e,t){return this.storage.setItem(e,JSON.stringify(t)),Promise.resolve()}_get(e){var t=this.storage.getItem(e);return Promise.resolve(t?JSON.parse(t):null)}_remove(e){return this.storage.removeItem(e),Promise.resolve()}get storage(){return this.storageRetriever()}}class Oy extends xy{constructor(){var e;super(()=>window.localStorage,"LOCAL"),this.boundEventHandler=(e,t)=>this.onStorageEvent(e,t),this.listeners={},this.localCache={},this.pollTimer=null,this.safariLocalStorageNotSynced=(dv(e=sd())||yv(e))&&function(){try{return!(!window||window===window.top)}catch(e){return!1}}(),this.fallbackToPolling=_v(),this._shouldAllowMigration=!0}forAllChangedKeys(e){for(const r of Object.keys(this.listeners)){var t=this.storage.getItem(r),n=this.localCache[r];t!==n&&e(r,n,t)}}onStorageEvent(e,t=!1){if(e.key){const r=e.key;if(t?this.detachListener():this.stopPolling(),this.safariLocalStorageNotSynced){const i=this.storage.getItem(r);if(e.newValue!==i)null!==e.newValue?this.storage.setItem(r,e.newValue):this.storage.removeItem(r);else if(this.localCache[r]===e.newValue&&!t)return}var n=()=>{var e=this.storage.getItem(r);!t&&this.localCache[r]===e||this.notifyListeners(r,e)};const i=this.storage.getItem(r);ud()&&10===document.documentMode&&i!==e.newValue&&e.newValue!==e.oldValue?setTimeout(n,10):n()}else this.forAllChangedKeys((e,t,n)=>{this.notifyListeners(e,n)})}notifyListeners(e,t){this.localCache[e]=t;var n=this.listeners[e];if(n)for(const r of Array.from(n))r(t&&JSON.parse(t))}startPolling(){this.stopPolling(),this.pollTimer=setInterval(()=>{this.forAllChangedKeys((e,t,n)=>{this.onStorageEvent(new StorageEvent("storage",{key:e,oldValue:t,newValue:n}),!0)})},1e3)}stopPolling(){this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=null)}attachListener(){window.addEventListener("storage",this.boundEventHandler)}detachListener(){window.removeEventListener("storage",this.boundEventHandler)}_addListener(e,t){0===Object.keys(this.listeners).length&&(this.fallbackToPolling?this.startPolling():this.attachListener()),this.listeners[e]||(this.listeners[e]=new Set,this.localCache[e]=this.storage.getItem(e)),this.listeners[e].add(t)}_removeListener(e,t){this.listeners[e]&&(this.listeners[e].delete(t),0===this.listeners[e].size&&delete this.listeners[e]),0===Object.keys(this.listeners).length&&(this.detachListener(),this.stopPolling())}async _set(e,t){await super._set(e,t),this.localCache[e]=JSON.stringify(t)}async _get(e){var t=await super._get(e);return this.localCache[e]=JSON.stringify(t),t}async _remove(e){await super._remove(e),delete this.localCache[e]}}Oy.type="LOCAL";const Dy=Oy;class Ly extends xy{constructor(){super(()=>window.sessionStorage,"SESSION")}_addListener(e,t){}_removeListener(e,t){}}Ly.type="SESSION";const My=Ly;class Fy{constructor(e){this.eventTarget=e,this.handlersMap={},this.boundEventHandler=this.handleEvent.bind(this)}static _getInstance(t){var e=this.receivers.find(e=>e.isListeningto(t));if(e)return e;e=new Fy(t);return this.receivers.push(e),e}isListeningto(e){return this.eventTarget===e}async handleEvent(e){const t=e,{eventId:n,eventType:r,data:i}=t.data;var s=this.handlersMap[r];null!=s&&s.size&&(t.ports[0].postMessage({status:"ack",eventId:n,eventType:r}),s=Array.from(s).map(async e=>e(t.origin,i)),s=await Promise.all(s.map(async e=>{try{return{fulfilled:!0,value:await e}}catch(e){return{fulfilled:!1,reason:e}}})),t.ports[0].postMessage({status:"done",eventId:n,eventType:r,response:s}))}_subscribe(e,t){0===Object.keys(this.handlersMap).length&&this.eventTarget.addEventListener("message",this.boundEventHandler),this.handlersMap[e]||(this.handlersMap[e]=new Set),this.handlersMap[e].add(t)}_unsubscribe(e,t){this.handlersMap[e]&&t&&this.handlersMap[e].delete(t),t&&0!==this.handlersMap[e].size||delete this.handlersMap[e],0===Object.keys(this.handlersMap).length&&this.eventTarget.removeEventListener("message",this.boundEventHandler)}}function Uy(e="",t=10){let n="";for(let r=0;r<t;r++)n+=Math.floor(10*Math.random());return e+n}Fy.receivers=[];class jy{constructor(e){this.target=e,this.handlers=new Set}removeMessageHandler(e){e.messageChannel&&(e.messageChannel.port1.removeEventListener("message",e.onMessage),e.messageChannel.port1.close()),this.handlers.delete(e)}async _send(e,t,o=50){const a="undefined"!=typeof MessageChannel?new MessageChannel:null;if(!a)throw new Error("connection_unavailable");let c,l;return new Promise((n,r)=>{const i=Uy("",20);a.port1.start();const s=setTimeout(()=>{r(new Error("unsupported_event"))},o);l={messageChannel:a,onMessage(e){var t=e;if(t.data.eventId===i)switch(t.data.status){case"ack":clearTimeout(s),c=setTimeout(()=>{r(new Error("timeout"))},3e3);break;case"done":clearTimeout(c),n(t.data.response);break;default:clearTimeout(s),clearTimeout(c),r(new Error("invalid_response"))}}},this.handlers.add(l),a.port1.addEventListener("message",l.onMessage),this.target.postMessage({eventType:e,eventId:i,data:t},[a.port2])}).finally(()=>{l&&this.removeMessageHandler(l)})}}function qy(){return window}function Vy(){return void 0!==qy().WorkerGlobalScope&&"function"==typeof qy().importScripts}const By="firebaseLocalStorageDb",Wy="firebaseLocalStorage",zy="fbase_key";class Ky{constructor(e){this.request=e}toPromise(){return new Promise((e,t)=>{this.request.addEventListener("success",()=>{e(this.request.result)}),this.request.addEventListener("error",()=>{t(this.request.error)})})}}function $y(e,t){return e.transaction([Wy],t?"readwrite":"readonly").objectStore(Wy)}function Hy(){const r=indexedDB.open(By,1);return new Promise((n,t)=>{r.addEventListener("error",()=>{t(r.error)}),r.addEventListener("upgradeneeded",()=>{const e=r.result;try{e.createObjectStore(Wy,{keyPath:zy})}catch(e){t(e)}}),r.addEventListener("success",async()=>{const e=r.result;var t;e.objectStoreNames.contains(Wy)?n(e):(e.close(),t=indexedDB.deleteDatabase(By),await new Ky(t).toPromise(),n(await Hy()))})})}async function Gy(e,t,n){var r=$y(e,!0).put({fbase_key:t,value:n});return new Ky(r).toPromise()}function Qy(e,t){var n=$y(e,!0).delete(t);return new Ky(n).toPromise()}class Yy{constructor(){this.type="LOCAL",this._shouldAllowMigration=!0,this.listeners={},this.localCache={},this.pollTimer=null,this.pendingWrites=0,this.receiver=null,this.sender=null,this.serviceWorkerReceiverAvailable=!1,this.activeServiceWorker=null,this._workerInitializationPromise=this.initializeServiceWorkerMessaging().then(()=>{},()=>{})}async _openDb(){return this.db||(this.db=await Hy(),this.db)}async _withRetries(e){let t=0;for(;;)try{return e(await this._openDb())}catch(e){if(3<t++)throw e;this.db&&(this.db.close(),this.db=void 0)}}async initializeServiceWorkerMessaging(){return Vy()?this.initializeReceiver():this.initializeSender()}async initializeReceiver(){this.receiver=Fy._getInstance(Vy()?self:null),this.receiver._subscribe("keyChanged",async(e,t)=>{const n=await this._poll();return{keyProcessed:n.includes(t.key)}}),this.receiver._subscribe("ping",async(e,t)=>["keyChanged"])}async initializeSender(){var e,t,n;this.activeServiceWorker=await async function(){if(null===navigator||void 0===navigator||!navigator.serviceWorker)return null;try{return(await navigator.serviceWorker.ready).active}catch(e){return null}}(),this.activeServiceWorker&&(this.sender=new jy(this.activeServiceWorker),(n=await this.sender._send("ping",{},800))&&null!==(e=n[0])&&void 0!==e&&e.fulfilled&&null!==(t=n[0])&&void 0!==t&&t.value.includes("keyChanged")&&(this.serviceWorkerReceiverAvailable=!0))}async notifyServiceWorker(e){var t;if(this.sender&&this.activeServiceWorker&&((null===(t=null===navigator||void 0===navigator?void 0:navigator.serviceWorker)||void 0===t?void 0:t.controller)||null)===this.activeServiceWorker)try{await this.sender._send("keyChanged",{key:e},this.serviceWorkerReceiverAvailable?800:50)}catch(e){}}async _isAvailable(){try{if(!indexedDB)return!1;var e=await Hy();return await Gy(e,Py,"1"),await Qy(e,Py),!0}catch(e){}return!1}async _withPendingWrite(e){this.pendingWrites++;try{await e()}finally{this.pendingWrites--}}async _set(t,n){return this._withPendingWrite(async()=>(await this._withRetries(e=>Gy(e,t,n)),this.localCache[t]=n,this.notifyServiceWorker(t)))}async _get(t){var e=await this._withRetries(e=>async function(e,t){var n=$y(e,!1).get(t);return void 0===(n=await new Ky(n).toPromise())?null:n.value}(e,t));return this.localCache[t]=e}async _remove(t){return this._withPendingWrite(async()=>(await this._withRetries(e=>Qy(e,t)),delete this.localCache[t],this.notifyServiceWorker(t)))}async _poll(){var e,t,n=await this._withRetries(e=>{var t=$y(e,!1).getAll();return new Ky(t).toPromise()});if(!n)return[];if(0!==this.pendingWrites)return[];const r=[],i=new Set;for({fbase_key:e,value:t}of n)i.add(e),JSON.stringify(this.localCache[e])!==JSON.stringify(t)&&(this.notifyListeners(e,t),r.push(e));for(const s of Object.keys(this.localCache))this.localCache[s]&&!i.has(s)&&(this.notifyListeners(s,null),r.push(s));return r}notifyListeners(e,t){this.localCache[e]=t;var n=this.listeners[e];if(n)for(const r of Array.from(n))r(t)}startPolling(){this.stopPolling(),this.pollTimer=setInterval(async()=>this._poll(),800)}stopPolling(){this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=null)}_addListener(e,t){0===Object.keys(this.listeners).length&&this.startPolling(),this.listeners[e]||(this.listeners[e]=new Set,this._get(e)),this.listeners[e].add(t)}_removeListener(e,t){this.listeners[e]&&(this.listeners[e].delete(t),0===this.listeners[e].size&&delete this.listeners[e]),0===Object.keys(this.listeners).length&&this.stopPolling()}}Yy.type="LOCAL";const Xy=Yy;function Jy(i){return new Promise((e,n)=>{const t=document.createElement("script");var r;t.setAttribute("src",i),t.onload=e,t.onerror=e=>{const t=Sm("internal-error");t.customData=e,n(t)},t.type="text/javascript",t.charset="UTF-8",(null!==(r=null===(r=document.getElementsByTagName("head"))||void 0===r?void 0:r[0])&&void 0!==r?r:document).appendChild(t)})}function Zy(e){return`__${e}${Math.floor(1e6*Math.random())}`}class e_{constructor(e){this.auth=e,this.counter=1e12,this._widgets=new Map}render(e,t){var n=this.counter;return this._widgets.set(n,new t_(e,this.auth.name,t||{})),this.counter++,n}reset(e){var t,n=e||1e12;null===(t=this._widgets.get(n))||void 0===t||t.delete(),this._widgets.delete(n)}getResponse(e){var t;return(null===(t=this._widgets.get(e||1e12))||void 0===t?void 0:t.getResponse())||""}async execute(e){var t;return null===(t=this._widgets.get(e||1e12))||void 0===t||t.execute(),""}}class t_{constructor(e,t,n){this.params=n,this.timerId=null,this.deleted=!1,this.responseToken=null,this.clickHandler=()=>{this.execute()};var r="string"==typeof e?document.getElementById(e):e;Rm(r,"argument-error",{appName:t}),this.container=r,this.isVisible="invisible"!==this.params.size,this.isVisible?this.execute():this.container.addEventListener("click",this.clickHandler)}getResponse(){return this.checkIfDeleted(),this.responseToken}delete(){this.checkIfDeleted(),this.deleted=!0,this.timerId&&(clearTimeout(this.timerId),this.timerId=null),this.container.removeEventListener("click",this.clickHandler)}execute(){this.checkIfDeleted(),this.timerId||(this.timerId=window.setTimeout(()=>{this.responseToken=function(e){const t=[],n="1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";for(let r=0;r<e;r++)t.push(n.charAt(Math.floor(Math.random()*n.length)));return t.join("")}(50);const{callback:e,"expired-callback":t}=this.params;if(e)try{e(this.responseToken)}catch(e){}this.timerId=window.setTimeout(()=>{if(this.timerId=null,this.responseToken=null,t)try{t()}catch(e){}this.isVisible&&this.execute()},6e4)},500))}checkIfDeleted(){if(this.deleted)throw new Error("reCAPTCHA mock was already deleted!")}}const n_=Zy("rcb"),r_=new Um(3e4,6e4);class i_{constructor(){this.hostLanguage="",this.counter=0,this.librarySeparatelyLoaded=!!qy().grecaptcha}load(s,o=""){var e;return Rm((e=o).length<=6&&/^\s*[a-zA-Z0-9\-]*\s*$/.test(e),s,"argument-error"),this.shouldResolveImmediately(o)?Promise.resolve(qy().grecaptcha):new Promise((t,n)=>{const i=qy().setTimeout(()=>{n(Sm(s,"network-request-failed"))},r_.get());qy()[n_]=()=>{qy().clearTimeout(i),delete qy()[n_];const e=qy().grecaptcha;if(e){const r=e.render;e.render=(e,t)=>{var n=r(e,t);return this.counter++,n},this.hostLanguage=o,t(e)}else n(Sm(s,"internal-error"))},Jy(`https://www.google.com/recaptcha/api.js??${Cd({onload:n_,render:"explicit",hl:o})}`).catch(()=>{clearTimeout(i),n(Sm(s,"internal-error"))})})}clearedOneInstance(){this.counter--}shouldResolveImmediately(e){return!!qy().grecaptcha&&(e===this.hostLanguage||0<this.counter||this.librarySeparatelyLoaded)}}class s_{async load(e){return new e_(e)}clearedOneInstance(){}}const o_="recaptcha",a_={theme:"light",type:"image"};class c_{constructor(e,t=Object.assign({},a_),n){this.parameters=t,this.type=o_,this.destroyed=!1,this.widgetId=null,this.tokenChangeListeners=new Set,this.renderPromise=null,this.recaptcha=null,this.auth=Iv(n),this.isInvisible="invisible"===this.parameters.size,Rm("undefined"!=typeof document,this.auth,"operation-not-supported-in-this-environment");var r="string"==typeof e?document.getElementById(e):e;Rm(r,this.auth,"argument-error"),this.container=r,this.parameters.callback=this.makeTokenCallback(this.parameters.callback),this._recaptchaLoader=new(this.auth.settings.appVerificationDisabledForTesting?s_:i_),this.validateStartingState()}async verify(){this.assertNotDestroyed();const e=await this.render(),r=this.getAssertedRecaptcha();var t=r.getResponse(e);return t||new Promise(t=>{const n=e=>{e&&(this.tokenChangeListeners.delete(n),t(e))};this.tokenChangeListeners.add(n),this.isInvisible&&r.execute(e)})}render(){try{this.assertNotDestroyed()}catch(e){return Promise.reject(e)}return this.renderPromise||(this.renderPromise=this.makeRenderPromise().catch(e=>{throw this.renderPromise=null,e}),this.renderPromise)}_reset(){this.assertNotDestroyed(),null!==this.widgetId&&this.getAssertedRecaptcha().reset(this.widgetId)}clear(){this.assertNotDestroyed(),this.destroyed=!0,this._recaptchaLoader.clearedOneInstance(),this.isInvisible||this.container.childNodes.forEach(e=>{this.container.removeChild(e)})}validateStartingState(){Rm(!this.parameters.sitekey,this.auth,"argument-error"),Rm(this.isInvisible||!this.container.hasChildNodes(),this.auth,"argument-error"),Rm("undefined"!=typeof document,this.auth,"operation-not-supported-in-this-environment")}makeTokenCallback(n){return t=>{if(this.tokenChangeListeners.forEach(e=>e(t)),"function"==typeof n)n(t);else if("string"==typeof n){const e=qy()[n];"function"==typeof e&&e(t)}}}assertNotDestroyed(){Rm(!this.destroyed,this.auth,"internal-error")}async makeRenderPromise(){if(await this.init(),!this.widgetId){let e=this.container;var t;this.isInvisible||(t=document.createElement("div"),e.appendChild(t),e=t),this.widgetId=this.getAssertedRecaptcha().render(e,this.parameters)}return this.widgetId}async init(){Rm(Mm()&&!Vy(),this.auth,"internal-error"),await function(){let t=null;return new Promise(e=>{"complete"!==document.readyState?(t=()=>e(),window.addEventListener("load",t)):e()}).catch(e=>{throw t&&window.removeEventListener("load",t),e})}(),this.recaptcha=await this._recaptchaLoader.load(this.auth,this.auth.languageCode||void 0);var e=await((await zm(this.auth,"GET","/v1/recaptchaParams")).recaptchaSiteKey||"");Rm(e,this.auth,"internal-error"),this.parameters.sitekey=e}getAssertedRecaptcha(){return Rm(this.recaptcha,this.auth,"internal-error"),this.recaptcha}}class l_{constructor(e,t){this.verificationId=e,this.onConfirmation=t}confirm(e){var t=Lv._fromVerification(this.verificationId,e);return this.onConfirmation(t)}}async function u_(t,n,r){var i,s,o,a,c,l,u=await r.verify();try{Rm("string"==typeof u,t,"argument-error"),Rm(r.type===o_,t,"argument-error");let e;if(e="string"==typeof n?{phoneNumber:n}:n,"session"in e){var h=e.session;if("phoneNumber"in e)return Rm("enroll"===h.type,t,"internal-error"),(c=t,l={idToken:h.credential,phoneEnrollmentInfo:{phoneNumber:e.phoneNumber,recaptchaToken:u}},await zm(c,"POST","/v2/accounts/mfaEnrollment:start",Wm(c,l))).phoneSessionInfo.sessionInfo;Rm("signin"===h.type,t,"internal-error");var d=(null===(i=e.multiFactorHint)||void 0===i?void 0:i.uid)||e.multiFactorUid;return Rm(d,t,"missing-multi-factor-info"),(a={mfaPendingCredential:h.credential,mfaEnrollmentId:d,phoneSignInInfo:{recaptchaToken:u}},await zm(t,"POST","/v2/accounts/mfaSignIn:start",Wm(t,a))).phoneResponseInfo.sessionInfo}var p=(s=t,o={phoneNumber:e.phoneNumber,recaptchaToken:u},await zm(s,"POST","/v1/accounts:sendVerificationCode",Wm(s,o)))["sessionInfo"];return p}finally{r._reset()}}class h_{constructor(e){this.providerId=h_.PROVIDER_ID,this.auth=Iv(e)}verifyPhoneNumber(e,t){return u_(this.auth,e,zd(t))}static credential(e,t){return Lv._fromVerification(e,t)}static credentialFromResult(e){var t=e;return h_.credentialFromTaggedObject(t)}static credentialFromError(e){return h_.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;var{phoneNumber:t,temporaryProof:n}=e;return t&&n?Lv._fromTokenResponse(t,n):null}}function d_(e,t){return t?Dm(t):(Rm(e._popupRedirectResolver,e,"argument-error"),e._popupRedirectResolver)}h_.PROVIDER_ID="phone",h_.PHONE_SIGN_IN_METHOD="phone";class p_ extends Cv{constructor(e){super("custom","custom"),this.params=e}_getIdTokenResponse(e){return xv(e,this._buildIdpRequest())}_linkToIdToken(e,t){return xv(e,this._buildIdpRequest(t))}_getReauthenticationResolver(e){return xv(e,this._buildIdpRequest())}_buildIdpRequest(e){const t={requestUri:this.params.requestUri,sessionId:this.params.sessionId,postBody:this.params.postBody,tenantId:this.params.tenantId,pendingToken:this.params.pendingToken,returnSecureToken:!0,returnIdpCredential:!0};return e&&(t.idToken=e),t}}function f_(e){return ry(e.auth,new p_(e),e.bypassAuthState)}function g_(e){var{auth:t,user:n}=e;return Rm(n,t,"internal-error"),ny(n,new p_(e),e.bypassAuthState)}async function m_(e){var{auth:t,user:n}=e;return Rm(n,t,"internal-error"),ey(n,new p_(e),e.bypassAuthState)}class v_{constructor(e,t,n,r,i=!1){this.auth=e,this.resolver=n,this.user=r,this.bypassAuthState=i,this.pendingPromise=null,this.eventManager=null,this.filter=Array.isArray(t)?t:[t]}execute(){return new Promise(async(e,t)=>{this.pendingPromise={resolve:e,reject:t};try{this.eventManager=await this.resolver._initialize(this.auth),await this.onExecution(),this.eventManager.registerConsumer(this)}catch(e){this.reject(e)}})}async onAuthEvent(e){var{urlResponse:t,sessionId:n,postBody:r,tenantId:i,error:s,type:o}=e;if(s)this.reject(s);else{r={auth:this.auth,requestUri:t,sessionId:n,tenantId:i||void 0,postBody:r||void 0,user:this.user,bypassAuthState:this.bypassAuthState};try{this.resolve(await this.getIdpTask(o)(r))}catch(e){this.reject(e)}}}onError(e){this.reject(e)}getIdpTask(e){switch(e){case"signInViaPopup":case"signInViaRedirect":return f_;case"linkViaPopup":case"linkViaRedirect":return m_;case"reauthViaPopup":case"reauthViaRedirect":return g_;default:km(this.auth,"internal-error")}}resolve(e){xm(this.pendingPromise,"Pending promise was never set"),this.pendingPromise.resolve(e),this.unregisterAndCleanUp()}reject(e){xm(this.pendingPromise,"Pending promise was never set"),this.pendingPromise.reject(e),this.unregisterAndCleanUp()}unregisterAndCleanUp(){this.eventManager&&this.eventManager.unregisterConsumer(this),this.pendingPromise=null,this.cleanUp()}}const y_=new Um(2e3,1e4);class __ extends v_{constructor(e,t,n,r,i){super(e,t,r,i),this.provider=n,this.authWindow=null,this.pollId=null,__.currentPopupAction&&__.currentPopupAction.cancel(),__.currentPopupAction=this}async executeNotNull(){var e=await this.execute();return Rm(e,this.auth,"internal-error"),e}async onExecution(){xm(1===this.filter.length,"Popup operations only handle one event");var e=Uy();this.authWindow=await this.resolver._openPopup(this.auth,this.provider,this.filter[0],e),this.authWindow.associatedEvent=e,this.resolver._originValidation(this.auth).catch(e=>{this.reject(e)}),this.resolver._isIframeWebStorageSupported(this.auth,e=>{e||this.reject(Sm(this.auth,"web-storage-unsupported"))}),this.pollUserCancellation()}get eventId(){var e;return(null===(e=this.authWindow)||void 0===e?void 0:e.associatedEvent)||null}cancel(){this.reject(Sm(this.auth,"cancelled-popup-request"))}cleanUp(){this.authWindow&&this.authWindow.close(),this.pollId&&window.clearTimeout(this.pollId),this.authWindow=null,this.pollId=null,__.currentPopupAction=null}pollUserCancellation(){const t=()=>{var e;null!==(e=null===(e=this.authWindow)||void 0===e?void 0:e.window)&&void 0!==e&&e.closed?this.pollId=window.setTimeout(()=>{this.pollId=null,this.reject(Sm(this.auth,"popup-closed-by-user"))},2e3):this.pollId=window.setTimeout(t,y_.get())};t()}}__.currentPopupAction=null;const w_="pendingRedirect",b_=new Map;class I_ extends v_{constructor(e,t,n=!1){super(e,["signInViaRedirect","linkViaRedirect","reauthViaRedirect","unknown"],t,void 0,n),this.eventId=null}async execute(){let t=b_.get(this.auth._key());if(!t){try{const e=await async function(e,t){const n=k_(t),r=E_(e);if(!await r._isAvailable())return!1;var i="true"===await r._get(n);return await r._remove(n),i}(this.resolver,this.auth)?await super.execute():null;t=()=>Promise.resolve(e)}catch(e){t=()=>Promise.reject(e)}b_.set(this.auth._key(),t)}return this.bypassAuthState||b_.set(this.auth._key(),()=>Promise.resolve(null)),t()}async onAuthEvent(e){if("signInViaRedirect"===e.type)return super.onAuthEvent(e);if("unknown"!==e.type){if(e.eventId){var t=await this.auth._redirectUserForId(e.eventId);if(t)return this.user=t,super.onAuthEvent(e);this.resolve(null)}}else this.resolve(null)}async onExecution(){}cleanUp(){}}async function T_(e,t){return E_(e)._set(k_(t),"true")}function E_(e){return Dm(e._redirectPersistence)}function k_(e){return cv(w_,e.config.apiKey,e.name)}function S_(e,t,n){return async function(e,t,n){var r=Iv(e);Am(e,t,Uv);const i=d_(r,n);return await T_(i,r),i._openRedirect(r,t,"signInViaRedirect")}(e,t,n)}function C_(e,t,n){return async function(e,t,n){var r=zd(e);Am(r.auth,t,Uv);const i=d_(r.auth,n);await T_(i,r.auth);var s=await R_(r);return i._openRedirect(r.auth,t,"reauthViaRedirect",s)}(e,t,n)}function A_(e,t,n){return async function(e,t,n){var r=zd(e);Am(r.auth,t,Uv);const i=d_(r.auth,n);await ty(!1,r,t.providerId),await T_(i,r.auth);var s=await R_(r);return i._openRedirect(r.auth,t,"linkViaRedirect",s)}(e,t,n)}async function N_(e,t,n=!1){const r=Iv(e);var i=d_(r,t);const s=new I_(r,i,n),o=await s.execute();return o&&!n&&(delete o.user._redirectEventId,await r._persistUserIfCurrent(o.user),await r._setRedirectUser(null,t)),o}async function R_(e){var t=Uy(`${e.uid}:::`);return e._redirectEventId=t,await e.auth._setRedirectUser(e),await e.auth._persistUserIfCurrent(e),t}class P_{constructor(e){this.auth=e,this.cachedEventUids=new Set,this.consumers=new Set,this.queuedRedirectEvent=null,this.hasHandledPotentialRedirect=!1,this.lastProcessedEventTime=Date.now()}registerConsumer(e){this.consumers.add(e),this.queuedRedirectEvent&&this.isEventForConsumer(this.queuedRedirectEvent,e)&&(this.sendToConsumer(this.queuedRedirectEvent,e),this.saveEventToCache(this.queuedRedirectEvent),this.queuedRedirectEvent=null)}unregisterConsumer(e){this.consumers.delete(e)}onEvent(t){if(this.hasEventBeenHandled(t))return!1;let n=!1;return this.consumers.forEach(e=>{this.isEventForConsumer(t,e)&&(n=!0,this.sendToConsumer(t,e),this.saveEventToCache(t))}),this.hasHandledPotentialRedirect||!function(e){switch(e.type){case"signInViaRedirect":case"linkViaRedirect":case"reauthViaRedirect":return!0;case"unknown":return O_(e);default:return!1}}(t)||(this.hasHandledPotentialRedirect=!0,n||(this.queuedRedirectEvent=t,n=!0)),n}sendToConsumer(e,t){var n;e.error&&!O_(e)?(n=(null===(n=e.error.code)||void 0===n?void 0:n.split("auth/")[1])||"internal-error",t.onError(Sm(this.auth,n))):t.onAuthEvent(e)}isEventForConsumer(e,t){var n=null===t.eventId||!!e.eventId&&e.eventId===t.eventId;return t.filter.includes(e.type)&&n}hasEventBeenHandled(e){return 6e5<=Date.now()-this.lastProcessedEventTime&&this.cachedEventUids.clear(),this.cachedEventUids.has(x_(e))}saveEventToCache(e){this.cachedEventUids.add(x_(e)),this.lastProcessedEventTime=Date.now()}}function x_(e){return[e.type,e.eventId,e.sessionId,e.tenantId].filter(e=>e).join("-")}function O_({type:e,error:t}){return"unknown"===e&&"auth/no-auth-event"===(null==t?void 0:t.code)}async function D_(e,t={}){return zm(e,"GET","/v1/projects",t)}const L_=/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/,M_=/^https?/;async function F_(e){if(!e.config.emulator){var t=(await D_(e))["authorizedDomains"];for(const n of t)try{if(function(e){const t=Lm(),{protocol:n,hostname:r}=new URL(t);if(e.startsWith("chrome-extension://")){var i=new URL(e);return""===i.hostname&&""===r?"chrome-extension:"===n&&e.replace("chrome-extension://","")===t.replace("chrome-extension://",""):"chrome-extension:"===n&&i.hostname===r}if(!M_.test(n))return!1;if(L_.test(e))return r===e;const s=e.replace(/\./g,"\\."),o=new RegExp("^(.+\\."+s+"|"+s+")$","i");return o.test(r)}(n))return}catch(e){}km(e,"unauthorized-domain")}}const U_=new Um(3e4,6e4);function j_(){const t=qy().___jsl;if(null!==t&&void 0!==t&&t.H)for(const n of Object.keys(t.H))if(t.H[n].r=t.H[n].r||[],t.H[n].L=t.H[n].L||[],t.H[n].r=[...t.H[n].L],t.CP)for(let e=0;e<t.CP.length;e++)t.CP[e]=null}let q_=null;function V_(e){var i;return q_=q_||(i=e,new Promise((e,t)=>{function n(){j_(),gapi.load("gapi.iframes",{callback:()=>{e(gapi.iframes.getContext())},ontimeout:()=>{j_(),t(Sm(i,"network-request-failed"))},timeout:U_.get()})}if(null!==(r=null===(r=qy().gapi)||void 0===r?void 0:r.iframes)&&void 0!==r&&r.Iframe)e(gapi.iframes.getContext());else{if(null===(r=qy().gapi)||void 0===r||!r.load){var r=Zy("iframefcb");return qy()[r]=()=>{gapi.load?n():t(Sm(i,"network-request-failed"))},Jy(`https://apis.google.com/js/api.js?onload=${r}`).catch(e=>t(e))}n()}}).catch(e=>{throw q_=null,e})),q_}const B_=new Um(5e3,15e3),W_="__/auth/iframe",z_="emulator/auth/iframe",K_={style:{position:"absolute",top:"-100px",width:"1px",height:"1px"},"aria-hidden":"true",tabindex:"-1"},$_=new Map([["identitytoolkit.googleapis.com","p"],["staging-identitytoolkit.sandbox.googleapis.com","s"],["test-identitytoolkit.sandbox.googleapis.com","t"]]);async function H_(o){const e=await V_(o);var t=qy().gapi;return Rm(t,o,"internal-error"),e.open({where:document.body,url:function(e){var t=e.config;Rm(t.authDomain,e,"auth-domain-config-required");var n=t.emulator?jm(t,z_):`https://${e.config.authDomain}/${W_}`;const r={apiKey:t.apiKey,appName:e.name,v:gp};(t=$_.get(e.config.apiHost))&&(r.eid=t);const i=e._getFrameworks();return i.length&&(r.fw=i.join(",")),`${n}?${Cd(r).slice(1)}`}(o),messageHandlersFilter:t.iframes.CROSS_ORIGIN_IFRAMES_FILTER,attributes:K_,dontclear:!0},s=>new Promise(async(e,t)=>{await s.restyle({setHideOnLeave:!1});const n=Sm(o,"network-request-failed"),r=qy().setTimeout(()=>{t(n)},B_.get());function i(){qy().clearTimeout(r),e(s)}s.ping(i).then(i,()=>{t(n)})}))}const G_={location:"yes",resizable:"yes",statusbar:"yes",toolbar:"no"};class Q_{constructor(e){this.window=e,this.associatedEvent=null}close(){if(this.window)try{this.window.close()}catch(e){}}}function Y_(e,t,n,r=500,i=600){var s=Math.max((window.screen.availHeight-i)/2,0).toString(),o=Math.max((window.screen.availWidth-r)/2,0).toString();let a="";const c=Object.assign(Object.assign({},G_),{width:r.toString(),height:i.toString(),top:s,left:o});s=sd().toLowerCase();n&&(a=pv(s)?"_blank":n),hv(s)&&(t=t||"http://localhost",c.scrollbars="yes");var l,o=Object.entries(c).reduce((e,[t,n])=>`${e}${t}=${n},`,"");if([n=sd()]=[s],yv(n)&&null!==(l=window.navigator)&&void 0!==l&&l.standalone&&"_self"!==a)return function(e,t){const n=document.createElement("a");n.href=e,n.target=t;const r=document.createEvent("MouseEvent");r.initMouseEvent("click",!0,!0,window,1,0,0,0,0,!1,!1,!1,!1,1,null),n.dispatchEvent(r)}(t||"",a),new Q_(null);const u=window.open(t||"",a,o);Rm(u,e,"popup-blocked");try{u.focus()}catch(e){}return new Q_(u)}const X_="__/auth/handler",J_="emulator/auth/handler";function Z_(e,t,n,r,i,s){Rm(e.config.authDomain,e,"auth-domain-config-required"),Rm(e.config.apiKey,e,"invalid-api-key");const o={apiKey:e.config.apiKey,appName:e.name,authType:n,redirectUrl:r,v:gp,eventId:i};if(t instanceof Uv){t.setDefaultLanguage(e.languageCode),o.providerId=t.providerId||"",Td(t.getCustomParameters())||(o.customParameters=JSON.stringify(t.getCustomParameters()));for(var[a,c]of Object.entries(s||{}))o[a]=c}if(t instanceof jv){const u=t.getScopes().filter(e=>""!==e);0<u.length&&(o.scopes=u.join(","))}e.tenantId&&(o.tid=e.tenantId);const l=o;for(const h of Object.keys(l))void 0===l[h]&&delete l[h];return`${e=[e["config"]][0],e.emulator?jm(e,J_):`https://${e.authDomain}/${X_}`}?${Cd(l).slice(1)}`}const ew="webStorageSupport";const tw=class{constructor(){this.eventManagers={},this.iframes={},this.originValidationPromises={},this._redirectPersistence=My,this._completeRedirectFn=N_}async _openPopup(e,t,n,r){var i;return xm(null===(i=this.eventManagers[e._key()])||void 0===i?void 0:i.manager,"_initialize() not called before _openPopup()"),Y_(e,Z_(e,t,n,Lm(),r),Uy())}async _openRedirect(e,t,n,r){return await this._originValidation(e),r=Z_(e,t,n,Lm(),r),qy().location.href=r,new Promise(()=>{})}_initialize(e){const t=e._key();if(this.eventManagers[t]){const{manager:r,promise:n}=this.eventManagers[t];return r?Promise.resolve(r):(xm(n,"If manager is not set, promise should be"),n)}const n=this.initAndGetManager(e);return this.eventManagers[t]={promise:n},n.catch(()=>{delete this.eventManagers[t]}),n}async initAndGetManager(t){const e=await H_(t),n=new P_(t);return e.register("authEvent",e=>{return Rm(null==e?void 0:e.authEvent,t,"invalid-auth-event"),{status:n.onEvent(e.authEvent)?"ACK":"ERROR"}},gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER),this.eventManagers[t._key()]={manager:n},this.iframes[t._key()]=e,n}_isIframeWebStorageSupported(n,r){const e=this.iframes[n._key()];e.send(ew,{type:ew},e=>{var t=null===(t=null==e?void 0:e[0])||void 0===t?void 0:t[ew];void 0!==t&&r(!!t),km(n,"internal-error")},gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER)}_originValidation(e){var t=e._key();return this.originValidationPromises[t]||(this.originValidationPromises[t]=F_(e)),this.originValidationPromises[t]}get _shouldInitProactively(){return _v()||dv()||yv()}};class nw extends class{constructor(e){this.factorId=e}_process(e,t,n){switch(t.type){case"enroll":return this._finalizeEnroll(e,t.credential,n);case"signin":return this._finalizeSignIn(e,t.credential);default:return Pm("unexpected MultiFactorSessionType")}}}{constructor(e){super("phone"),this.credential=e}static _fromCredential(e){return new nw(e)}_finalizeEnroll(e,t,n){return e=e,n={idToken:t,displayName:n,phoneVerificationInfo:this.credential._makeVerificationRequest()},zm(e,"POST","/v2/accounts/mfaEnrollment:finalize",Wm(e,n))}_finalizeSignIn(e,t){return e=e,t={mfaPendingCredential:t,phoneVerificationInfo:this.credential._makeVerificationRequest()},zm(e,"POST","/v2/accounts/mfaSignIn:finalize",Wm(e,t))}}class rw{constructor(){}static assertion(e){return nw._fromCredential(e)}}rw.FACTOR_ID="phone";var iw,sw="@firebase/auth";class ow{constructor(e){this.auth=e,this.internalListeners=new Map}getUid(){var e;return this.assertAuthConfigured(),(null===(e=this.auth.currentUser)||void 0===e?void 0:e.uid)||null}async getToken(e){return this.assertAuthConfigured(),await this.auth._initializationPromise,this.auth.currentUser?{accessToken:await this.auth.currentUser.getIdToken(e)}:null}addAuthTokenListener(t){var e;this.assertAuthConfigured(),this.internalListeners.has(t)||(e=this.auth.onIdTokenChanged(e=>{t((null===e||void 0===e?void 0:e.stsTokenManager.accessToken)||null)}),this.internalListeners.set(t,e),this.updateProactiveRefresh())}removeAuthTokenListener(e){this.assertAuthConfigured();const t=this.internalListeners.get(e);t&&(this.internalListeners.delete(e),t(),this.updateProactiveRefresh())}assertAuthConfigured(){Rm(this.auth._initializationPromise,"dependent-sdk-initialized-before-auth")}updateProactiveRefresh(){0<this.internalListeners.size?this.auth._startProactiveRefresh():this.auth._stopProactiveRefresh()}}function aw(){return window}iw="Browser",hp(new Kd("auth",(e,{options:n})=>{var t=e.getProvider("app").getImmediate();const{apiKey:r,authDomain:i}=t.options;return(e=>{Rm(r&&!r.includes(":"),"invalid-api-key",{appName:e.name}),Rm(!(null!==i&&void 0!==i&&i.includes(":")),"argument-error",{appName:e.name});var t={apiKey:r,authDomain:i,clientPlatform:iw,apiHost:"identitytoolkit.googleapis.com",tokenApiHost:"securetoken.googleapis.com",apiScheme:"https",sdkClientVersion:wv(iw)},t=new bv(e,t);return function(e,t){const n=(null==t?void 0:t.persistence)||[];var r=(Array.isArray(n)?n:[n]).map(Dm);null!=t&&t.errorMap&&e._updateErrorMap(t.errorMap),e._initializeWithPersistence(r,null==t?void 0:t.popupRedirectResolver)}(t,n),t})(t)},"PUBLIC").setInstantiationMode("EXPLICIT").setInstanceCreatedCallback((e,t,n)=>{const r=e.getProvider("auth-internal");r.initialize()})),hp(new Kd("auth-internal",e=>{var t=Iv(e.getProvider("auth").getImmediate());return e=t,new ow(e)},"PRIVATE").setInstantiationMode("EXPLICIT")),_p(sw,"0.19.8",function(e){switch(e){case"Node":return"node";case"ReactNative":return"rn";case"Worker":return"webworker";case"Cordova":return"cordova";default:return}}(iw)),_p(sw,"0.19.8","esm2017");async function cw(e,t,n){var r=aw()["BuildInfo"];xm(t.sessionId,"AuthEvent did not contain a session ID");var i=await async function(e){const t=function(e){if(xm(/[0-9a-zA-Z]+/.test(e),"Can only convert alpha-numeric strings"),"undefined"!=typeof TextEncoder)return(new TextEncoder).encode(e);const t=new ArrayBuffer(e.length),n=new Uint8Array(t);for(let r=0;r<e.length;r++)n[r]=e.charCodeAt(r);return n}(e),n=await crypto.subtle.digest("SHA-256",t),r=Array.from(new Uint8Array(n));return r.map(e=>e.toString(16).padStart(2,"0")).join("")}(t.sessionId);const s={};return yv()?s.ibi=r.packageName:gv()?s.apn=r.packageName:km(e,"operation-not-supported-in-this-environment"),r.displayName&&(s.appDisplayName=r.displayName),s.sessionId=i,Z_(e,n,t.type,void 0,null!==(i=t.eventId)&&void 0!==i?i:void 0,s)}function lw(r){const i=aw()["cordova"];return new Promise(n=>{i.plugins.browsertab.isAvailable(e=>{let t=null;e?i.plugins.browsertab.openUrl(r):t=i.InAppBrowser.open(r,(e=sd(),/(iPad|iPhone|iPod).*OS 7_\d/i.test(e)||/(iPad|iPhone|iPod).*OS 8_\d/i.test(e)?"_blank":"_system"),"location=yes"),n(t)})})}const uw=20;class hw extends P_{constructor(){super(...arguments),this.passiveListeners=new Set,this.initPromise=new Promise(e=>{this.resolveInialized=e})}addPassiveListener(e){this.passiveListeners.add(e)}removePassiveListener(e){this.passiveListeners.delete(e)}resetRedirect(){this.queuedRedirectEvent=null,this.hasHandledPotentialRedirect=!1}onEvent(t){return this.resolveInialized(),this.passiveListeners.forEach(e=>e(t)),super.onEvent(t)}async initialized(){await this.initPromise}}function dw(e,t,n=null){return{type:t,eventId:n,urlResponse:null,sessionId:function(){const e=[],t="1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";for(let r=0;r<uw;r++){var n=Math.floor(Math.random()*t.length);e.push(t.charAt(n))}return e.join("")}(),postBody:null,tenantId:e.tenantId,error:Sm(e,"no-auth-event")}}async function pw(e){var t=await gw()._get(mw(e));return t&&await gw()._remove(mw(e)),t}function fw(e,t){var n,r,i;const s=(n=vw(t=t),o=n.link?decodeURIComponent(n.link):void 0,r=vw(o).link,i=n.deep_link_id?decodeURIComponent(n.deep_link_id):void 0,(n=vw(i).link)||i||r||o||t);if(s.includes("/__/auth/callback")){var o=vw(s),o=o.firebaseError?function(e){try{return JSON.parse(e)}catch(e){return null}}(decodeURIComponent(o.firebaseError)):null,o=null===(o=null===(o=null==o?void 0:o.code)||void 0===o?void 0:o.split("auth/"))||void 0===o?void 0:o[1],o=o?Sm(o):null;return o?{type:e.type,eventId:e.eventId,tenantId:e.tenantId,error:o,urlResponse:null,sessionId:null,postBody:null}:{type:e.type,eventId:e.eventId,tenantId:e.tenantId,sessionId:e.sessionId,urlResponse:s,postBody:null}}return null}function gw(){return Dm(Dy)}function mw(e){return cv("authEvent",e.config.apiKey,e.name)}function vw(e){if(null==e||!e.includes("?"))return{};const[,...t]=e.split("?");return Ad(t.join("?"))}const yw=class{constructor(){this._redirectPersistence=My,this._shouldInitProactively=!0,this.eventManagers=new Map,this.originValidationPromises={},this._completeRedirectFn=N_}async _initialize(e){var t=e._key();let n=this.eventManagers.get(t);return n||(n=new hw(e),this.eventManagers.set(t,n),this.attachCallbackListeners(e,n)),n}_openPopup(e){km(e,"operation-not-supported-in-this-environment")}async _openRedirect(e,t,n,r){var i,s;i=e,a=aw(),Rm("function"==typeof(null===(s=null==a?void 0:a.universalLinks)||void 0===s?void 0:s.subscribe),i,"invalid-cordova-configuration",{missingPlugin:"cordova-universal-links-plugin-fix"}),Rm(void 0!==(null===(s=null==a?void 0:a.BuildInfo)||void 0===s?void 0:s.packageName),i,"invalid-cordova-configuration",{missingPlugin:"cordova-plugin-buildInfo"}),Rm("function"==typeof(null===(s=null===(s=null===(s=null==a?void 0:a.cordova)||void 0===s?void 0:s.plugins)||void 0===s?void 0:s.browsertab)||void 0===s?void 0:s.openUrl),i,"invalid-cordova-configuration",{missingPlugin:"cordova-plugin-browsertab"}),Rm("function"==typeof(null===(s=null===(s=null===(s=null==a?void 0:a.cordova)||void 0===s?void 0:s.plugins)||void 0===s?void 0:s.browsertab)||void 0===s?void 0:s.isAvailable),i,"invalid-cordova-configuration",{missingPlugin:"cordova-plugin-browsertab"}),Rm("function"==typeof(null===(a=null===(a=null==a?void 0:a.cordova)||void 0===a?void 0:a.InAppBrowser)||void 0===a?void 0:a.open),i,"invalid-cordova-configuration",{missingPlugin:"cordova-plugin-inappbrowser"});const o=await this._initialize(e);await o.initialized(),o.resetRedirect(),b_.clear(),await this._originValidation(e);var a=dw(e,n,r);n=e,r=a,await gw()._set(mw(n),r);a=await lw(await cw(e,a,t));return async function(o,a,c){const l=aw()["cordova"];let u=()=>{};try{await new Promise((n,e)=>{let t=null;function r(){var e;n();const t=null===(e=l.plugins.browsertab)||void 0===e?void 0:e.close;"function"==typeof t&&t(),"function"==typeof(null==c?void 0:c.close)&&c.close()}function i(){t=t||window.setTimeout(()=>{e(Sm(o,"redirect-cancelled-by-user"))},2e3)}function s(){"visible"===(null===document||void 0===document?void 0:document.visibilityState)&&i()}a.addPassiveListener(r),document.addEventListener("resume",i,!1),gv()&&document.addEventListener("visibilitychange",s,!1),u=()=>{a.removePassiveListener(r),document.removeEventListener("resume",i,!1),document.removeEventListener("visibilitychange",s,!1),t&&window.clearTimeout(t)}})}finally{u()}}(e,o,a)}_isIframeWebStorageSupported(e,t){throw new Error("Method not implemented.")}_originValidation(e){var t=e._key();return this.originValidationPromises[t]||(this.originValidationPromises[t]=async function(e){var t=aw()["BuildInfo"];const n={};yv()?n.iosBundleId=t.packageName:gv()?n.androidPackageName=t.packageName:km(e,"operation-not-supported-in-this-environment"),await D_(e,n)}(e)),this.originValidationPromises[t]}attachCallbackListeners(r,i){const{universalLinks:e,handleOpenURL:t,BuildInfo:n}=aw(),s=setTimeout(async()=>{await pw(r),i.onEvent(_w())},500),o=async e=>{clearTimeout(s);var t=await pw(r);let n=null;t&&null!=e&&e.url&&(n=fw(t,e.url)),i.onEvent(n||_w())};void 0!==e&&"function"==typeof e.subscribe&&e.subscribe(null,o);const a=t,c=`${n.packageName.toLowerCase()}://`;aw().handleOpenURL=async e=>{if(e.toLowerCase().startsWith(c)&&o({url:e}),"function"==typeof a)try{a(e)}catch(e){console.error(e)}}}};function _w(){return{type:"unknown",eventId:null,sessionId:null,urlResponse:null,postBody:null,tenantId:null,error:Sm("no-auth-event")}}var ww;function bw(){var e;return(null===(e=null===self||void 0===self?void 0:self.location)||void 0===e?void 0:e.protocol)||null}function Iw(e=sd()){return!("file:"!==bw()&&"ionic:"!==bw()||!e.toLowerCase().match(/iphone|ipad|ipod|android/))}function Tw(e=sd()){return ud()&&11===(null===document||void 0===document?void 0:document.documentMode)||([e=sd()]=[e],/Edge\/\d+/.test(e))}function Ew(){try{const t=self.localStorage;var e=Uy();if(t)return t.setItem(e,"1"),t.removeItem(e),!Tw()||dd()}catch(e){return kw()&&dd()}return!1}function kw(){return"undefined"!=typeof global&&"WorkerGlobalScope"in global&&"importScripts"in global}function Sw(){return("http:"===bw()||"https:"===bw()||cd()||Iw())&&!(ld()||ad())&&Ew()&&!kw()}function Cw(){return Iw()&&"undefined"!=typeof document}const Aw={LOCAL:"local",NONE:"none",SESSION:"session"},Nw=Rm,Rw="persistence";async function Pw(e){await e._initializationPromise;const t=xw();var n=cv(Rw,e.config.apiKey,e.name);t&&t.setItem(n,e._getPersistence())}function xw(){var e;try{return(null===(e="undefined"!=typeof window?window:null)?void 0:e.sessionStorage)||null}catch(e){return null}}const Ow=Rm;class Dw{constructor(){this.browserResolver=Dm(tw),this.cordovaResolver=Dm(yw),this.underlyingResolver=null,this._redirectPersistence=My,this._completeRedirectFn=N_}async _initialize(e){return await this.selectUnderlyingResolver(),this.assertedUnderlyingResolver._initialize(e)}async _openPopup(e,t,n,r){return await this.selectUnderlyingResolver(),this.assertedUnderlyingResolver._openPopup(e,t,n,r)}async _openRedirect(e,t,n,r){return await this.selectUnderlyingResolver(),this.assertedUnderlyingResolver._openRedirect(e,t,n,r)}_isIframeWebStorageSupported(e,t){this.assertedUnderlyingResolver._isIframeWebStorageSupported(e,t)}_originValidation(e){return this.assertedUnderlyingResolver._originValidation(e)}get _shouldInitProactively(){return Cw()||this.browserResolver._shouldInitProactively}get assertedUnderlyingResolver(){return Ow(this.underlyingResolver,"internal-error"),this.underlyingResolver}async selectUnderlyingResolver(){var e;this.underlyingResolver||(e=await(!!Cw()&&new Promise(e=>{const t=setTimeout(()=>{e(!1)},1e3);document.addEventListener("deviceready",()=>{clearTimeout(t),e(!0)})})),this.underlyingResolver=e?this.cordovaResolver:this.browserResolver)}}function Lw(e){return e.unwrap()}function Mw(e,t){var n,r,i,s=null===(r=t.customData)||void 0===r?void 0:r._tokenResponse;if("auth/multi-factor-auth-required"===t.code){const a=t;a.resolver=new qw(e,(n=t,i=zd(e),Rm((o=n).customData.operationType,i,"argument-error"),Rm(null===(r=o.customData._serverResponse)||void 0===r?void 0:r.mfaPendingCredential,i,"argument-error"),Ay._fromError(i,o)))}else if(s){var o=Fw(t);const c=t;o&&(c.credential=o,c.tenantId=s.tenantId||void 0,c.email=s.email||void 0,c.phoneNumber=s.phoneNumber||void 0)}}function Fw(e){var t=(e instanceof gd?e.customData:e)["_tokenResponse"];if(!t)return null;if(!(e instanceof gd)&&"temporaryProof"in t&&"phoneNumber"in t)return h_.credentialFromResult(e);const n=t.providerId;if(!n||n===vm.PASSWORD)return null;let r;switch(n){case vm.GOOGLE:r=Bv;break;case vm.FACEBOOK:r=Vv;break;case vm.GITHUB:r=Wv;break;case vm.TWITTER:r=$v;break;default:var{oauthIdToken:i,oauthAccessToken:s,oauthTokenSecret:o,pendingToken:a,nonce:c}=t;return s||o||i||a?a?n.startsWith("saml.")?zv._create(n,a):Ov._fromParams({providerId:n,signInMethod:n,pendingToken:a,idToken:i,accessToken:s}):new qv(n).credential({idToken:i,accessToken:s,rawNonce:c}):null}return e instanceof gd?r.credentialFromError(e):r.credentialFromResult(e)}function Uw(t,e){return e.catch(e=>{throw e instanceof gd&&Mw(t,e),e}).then(e=>{var t=e.operationType,n=e.user;return{operationType:t,credential:Fw(e),additionalUserInfo:Sy(e),user:Vw.getOrCreate(n)}})}async function jw(t,e){const n=await e;return{verificationId:n.verificationId,confirm:e=>Uw(t,n.confirm(e))}}class qw{constructor(e,t){this.resolver=t,this.auth=e.wrapped()}get session(){return this.resolver.session}get hints(){return this.resolver.hints}resolveSignIn(e){return Uw(Lw(this.auth),this.resolver.resolveSignIn(e))}}class Vw{constructor(e){var t;this._delegate=e,this.multiFactor=(t=zd(e),Ry.has(t)||Ry.set(t,Ny._fromUser(t)),Ry.get(t))}static getOrCreate(e){return Vw.USER_MAP.has(e)||Vw.USER_MAP.set(e,new Vw(e)),Vw.USER_MAP.get(e)}delete(){return this._delegate.delete()}reload(){return this._delegate.reload()}toJSON(){return this._delegate.toJSON()}getIdTokenResult(e){return this._delegate.getIdTokenResult(e)}getIdToken(e){return this._delegate.getIdToken(e)}linkAndRetrieveDataWithCredential(e){return this.linkWithCredential(e)}async linkWithCredential(e){return Uw(this.auth,sy(this._delegate,e))}async linkWithPhoneNumber(e,t){return jw(this.auth,async function(e,t,n){const r=zd(e);await ty(!1,r,"phone");var i=await u_(r.auth,t,zd(n));return new l_(i,e=>sy(r,e))}(this._delegate,e,t))}async linkWithPopup(e){return Uw(this.auth,async function(e,t,n){var r=zd(e);Am(r.auth,t,Uv);var i=d_(r.auth,n);const s=new __(r.auth,"linkViaPopup",t,i,r);return s.executeNotNull()}(this._delegate,e,Dw))}async linkWithRedirect(e){return await Pw(Iv(this.auth)),A_(this._delegate,e,Dw)}reauthenticateAndRetrieveDataWithCredential(e){return this.reauthenticateWithCredential(e)}async reauthenticateWithCredential(e){return Uw(this.auth,oy(this._delegate,e))}reauthenticateWithPhoneNumber(e,t){return jw(this.auth,async function(e,t,n){const r=zd(e);var i=await u_(r.auth,t,zd(n));return new l_(i,e=>oy(r,e))}(this._delegate,e,t))}reauthenticateWithPopup(e){return Uw(this.auth,async function(e,t,n){var r=zd(e);Am(r.auth,t,Uv);var i=d_(r.auth,n);const s=new __(r.auth,"reauthViaPopup",t,i,r);return s.executeNotNull()}(this._delegate,e,Dw))}async reauthenticateWithRedirect(e){return await Pw(Iv(this.auth)),C_(this._delegate,e,Dw)}sendEmailVerification(e){return my(this._delegate,e)}async unlink(e){return await Zv(this._delegate,e),this}updateEmail(e){return _y(zd(this._delegate),e,null)}updatePassword(e){return _y(zd(this._delegate),null,e)}updatePhoneNumber(e){return async function(e,t){await ey(zd(e),t)}(this._delegate,e)}updateProfile(e){return yy(this._delegate,e)}verifyBeforeUpdateEmail(e,t){return vy(this._delegate,e,t)}get emailVerified(){return this._delegate.emailVerified}get isAnonymous(){return this._delegate.isAnonymous}get metadata(){return this._delegate.metadata}get phoneNumber(){return this._delegate.phoneNumber}get providerData(){return this._delegate.providerData}get refreshToken(){return this._delegate.refreshToken}get tenantId(){return this._delegate.tenantId}get displayName(){return this._delegate.displayName}get email(){return this._delegate.email}get photoURL(){return this._delegate.photoURL}get providerId(){return this._delegate.providerId}get uid(){return this._delegate.uid}get auth(){return this._delegate.auth}}Vw.USER_MAP=new WeakMap;const Bw=Rm;class Ww{constructor(e,t){if(this.app=e,t.isInitialized())return this._delegate=t.getImmediate(),void this.linkUnderlyingAuth();var n=e.options["apiKey"];Bw(n,"invalid-api-key",{appName:e.name}),Bw(n,"invalid-api-key",{appName:e.name});var r="undefined"!=typeof window?Dw:void 0;this._delegate=t.initialize({options:{persistence:function(e,t){const n=function(e,t){const n=xw();if(!n)return[];var r=cv(Rw,e,t);switch(n.getItem(r)){case Aw.NONE:return[av];case Aw.LOCAL:return[Xy,My];case Aw.SESSION:return[My];default:return[]}}(e,t);"undefined"==typeof self||n.includes(Xy)||n.push(Xy);if("undefined"!=typeof window)for(const r of[Dy,My])n.includes(r)||n.push(r);n.includes(av)||n.push(av);return n}(n,e.name),popupRedirectResolver:r}}),this._delegate._updateErrorMap(wm),this.linkUnderlyingAuth()}get emulatorConfig(){return this._delegate.emulatorConfig}get currentUser(){return this._delegate.currentUser?Vw.getOrCreate(this._delegate.currentUser):null}get languageCode(){return this._delegate.languageCode}set languageCode(e){this._delegate.languageCode=e}get settings(){return this._delegate.settings}get tenantId(){return this._delegate.tenantId}set tenantId(e){this._delegate.tenantId=e}useDeviceLanguage(){this._delegate.useDeviceLanguage()}signOut(){return this._delegate.signOut()}useEmulator(e,t){Ev(this._delegate,e,t)}applyActionCode(e){return dy(this._delegate,e)}checkActionCode(e){return py(this._delegate,e)}confirmPasswordReset(e,t){return async function(e,t,n){await Av(zd(e),{oobCode:t,newPassword:n})}(this._delegate,e,t)}async createUserWithEmailAndPassword(e,t){return Uw(this._delegate,async function(e,t,n){const r=Iv(e);var i=await Hv(r,{returnSecureToken:!0,email:t,password:n}),i=await Gv._fromIdTokenResponse(r,"signIn",i);return await r._updateCurrentUser(i.user),i}(this._delegate,e,t))}fetchProvidersForEmail(e){return this.fetchSignInMethodsForEmail(e)}fetchSignInMethodsForEmail(e){return gy(this._delegate,e)}isSignInWithEmailLink(e){return this._delegate,e=e,"EMAIL_SIGNIN"===(null==(t=Mv.parseLink(e))?void 0:t.operation);var t}async getRedirectResult(){Bw(Sw(),this._delegate,"operation-not-supported-in-this-environment");var e,t,n=(e=this._delegate,t=Dw,await Iv(e)._initializationPromise,await N_(e,t,!1));return n?Uw(this._delegate,Promise.resolve(n)):{credential:null,user:null}}addFrameworkForLogging(e){Iv(this._delegate)._logFramework(e)}onAuthStateChanged(e,t,n){var{next:r,error:i,complete:s}=zw(e,t,n);return this._delegate.onAuthStateChanged(r,i,s)}onIdTokenChanged(e,t,n){var{next:r,error:i,complete:s}=zw(e,t,n);return this._delegate.onIdTokenChanged(r,i,s)}sendSignInLinkToEmail(e,t){return fy(this._delegate,e,t)}sendPasswordResetEmail(e,t){return hy(this._delegate,e,t||void 0)}async setPersistence(e){var t,n;t=this._delegate,n=e,Nw(Object.values(Aw).includes(n),t,"invalid-persistence-type"),ld()?Nw(n!==Aw.SESSION,t,"unsupported-persistence-type"):ad()?Nw(n===Aw.NONE,t,"unsupported-persistence-type"):kw()?Nw(n===Aw.NONE||n===Aw.LOCAL&&dd(),t,"unsupported-persistence-type"):Nw(n===Aw.NONE||Ew(),t,"unsupported-persistence-type");let r;switch(e){case Aw.SESSION:r=My;break;case Aw.LOCAL:var i=await Dm(Xy)._isAvailable();r=i?Xy:Dy;break;case Aw.NONE:r=av;break;default:return km("argument-error",{appName:this._delegate.name})}return this._delegate.setPersistence(r)}signInAndRetrieveDataWithCredential(e){return this.signInWithCredential(e)}signInAnonymously(){return Uw(this._delegate,async function(e){const t=Iv(e);if(await t._initializationPromise,null!==(n=t.currentUser)&&void 0!==n&&n.isAnonymous)return new Gv({user:t.currentUser,providerId:null,operationType:"signIn"});var n=await Hv(t,{returnSecureToken:!0}),n=await Gv._fromIdTokenResponse(t,"signIn",n,!0);return await t._updateCurrentUser(n.user),n}(this._delegate))}signInWithCredential(e){return Uw(this._delegate,iy(this._delegate,e))}signInWithCustomToken(e){return Uw(this._delegate,ay(this._delegate,e))}signInWithEmailAndPassword(e,t){return Uw(this._delegate,(n=this._delegate,e=e,t=t,iy(zd(n),Fv.credential(e,t))));var n}signInWithEmailLink(e,t){return Uw(this._delegate,async function(e,t,n){var r=zd(e),i=Fv.credentialWithLink(t,n||Lm());return Rm(i._tenantId===(r.tenantId||null),r,"tenant-id-mismatch"),iy(r,i)}(this._delegate,e,t))}signInWithPhoneNumber(e,t){return jw(this._delegate,async function(e,t,n){const r=Iv(e);var i=await u_(r,t,zd(n));return new l_(i,e=>iy(r,e))}(this._delegate,e,t))}async signInWithPopup(e){return Bw(Sw(),this._delegate,"operation-not-supported-in-this-environment"),Uw(this._delegate,async function(e,t,n){var r=Iv(e);Am(e,t,Uv);var i=d_(r,n);const s=new __(r,"signInViaPopup",t,i);return s.executeNotNull()}(this._delegate,e,Dw))}async signInWithRedirect(e){return Bw(Sw(),this._delegate,"operation-not-supported-in-this-environment"),await Pw(this._delegate),S_(this._delegate,e,Dw)}updateCurrentUser(e){return this._delegate.updateCurrentUser(e)}verifyPasswordResetCode(e){return async function(e,t){var n=(await py(zd(e),t))["data"];return n.email}(this._delegate,e)}unwrap(){return this._delegate}_delete(){return this._delegate._delete()}linkUnderlyingAuth(){this._delegate.wrapped=()=>this}}function zw(e,t,n){let r=e;"function"!=typeof e&&({next:r,error:t,complete:n}=e);const i=r;return{next:e=>i(e&&Vw.getOrCreate(e)),error:t,complete:n}}Ww.Persistence=Aw;class Kw{constructor(){this.providerId="phone",this._delegate=new h_(Lw(Cp.auth()))}static credential(e,t){return h_.credential(e,t)}verifyPhoneNumber(e,t){return this._delegate.verifyPhoneNumber(e,t)}unwrap(){return this._delegate}}Kw.PHONE_SIGN_IN_METHOD=h_.PHONE_SIGN_IN_METHOD,Kw.PROVIDER_ID=h_.PROVIDER_ID;const $w=Rm;class Hw{constructor(e,t,n=Cp.app()){var r;$w(null===(r=n.options)||void 0===r?void 0:r.apiKey,"invalid-api-key",{appName:n.name}),this._delegate=new c_(e,t,n.auth()),this.type=this._delegate.type}clear(){this._delegate.clear()}render(){return this._delegate.render()}verify(){return this._delegate.verify()}}(ww=Cp).INTERNAL.registerComponent(new Kd("auth-compat",e=>{var t=e.getProvider("app-compat").getImmediate(),n=e.getProvider("auth");return new Ww(t,n)},"PUBLIC").setServiceProps({ActionCodeInfo:{Operation:{EMAIL_SIGNIN:ym.EMAIL_SIGNIN,PASSWORD_RESET:ym.PASSWORD_RESET,RECOVER_EMAIL:ym.RECOVER_EMAIL,REVERT_SECOND_FACTOR_ADDITION:ym.REVERT_SECOND_FACTOR_ADDITION,VERIFY_AND_CHANGE_EMAIL:ym.VERIFY_AND_CHANGE_EMAIL,VERIFY_EMAIL:ym.VERIFY_EMAIL}},EmailAuthProvider:Fv,FacebookAuthProvider:Vv,GithubAuthProvider:Wv,GoogleAuthProvider:Bv,OAuthProvider:qv,SAMLAuthProvider:Kv,PhoneAuthProvider:Kw,PhoneMultiFactorGenerator:rw,RecaptchaVerifier:Hw,TwitterAuthProvider:$v,Auth:Ww,AuthCredential:Cv,Error:gd}).setInstantiationMode("LAZY").setMultipleInstances(!1)),ww.registerVersion("@firebase/auth-compat","0.2.8");const Gw="@firebase/database";let Qw="";function Yw(e){Qw=e}class Xw{constructor(e){this.domStorage_=e,this.prefix_="firebase:"}set(e,t){null==t?this.domStorage_.removeItem(this.prefixedName_(e)):this.domStorage_.setItem(this.prefixedName_(e),_d(t))}get(e){var t=this.domStorage_.getItem(this.prefixedName_(e));return null==t?null:yd(t)}remove(e){this.domStorage_.removeItem(this.prefixedName_(e))}prefixedName_(e){return this.prefix_+e}toString(){return this.domStorage_.toString()}}class Jw{constructor(){this.cache_={},this.isInMemoryStorage=!0}set(e,t){null==t?delete this.cache_[e]:this.cache_[e]=t}get(e){return bd(this.cache_,e)?this.cache_[e]:null}remove(e){delete this.cache_[e]}}var Zw,eb,tb,nb,rb,ib,yt=function(e){try{if("undefined"!=typeof window&&void 0!==window[e]){const t=window[e];return t.setItem("firebase:sentinel","cache"),t.removeItem("firebase:sentinel"),new Xw(t)}}catch(e){}return new Jw};function sb(e){var t=function(t){const n=[];let r=0;for(let o=0;o<t.length;o++){let e=t.charCodeAt(o);var i,s;55296<=e&&e<=56319&&(i=e-55296,o++,Xh(o<t.length,"Surrogate pair missing trail surrogate."),s=t.charCodeAt(o)-56320,e=65536+(i<<10)+s),e<128?n[r++]=e:(e<2048?n[r++]=e>>6|192:(e<65536?n[r++]=e>>12|224:(n[r++]=e>>18|240,n[r++]=e>>12&63|128),n[r++]=e>>6&63|128),n[r++]=63&e|128)}return n}(e);const n=new Rd;return n.update(t),t=n.digest(),Zh.encodeByteArray(t)}const ob=yt("localStorage"),ab=yt("sessionStorage"),cb=new ep("@firebase/database"),lb=function(){let e=1;return function(){return e++}}(),ub=function(...e){let t="";for(let r=0;r<e.length;r++){var n=e[r];Array.isArray(n)||n&&"object"==typeof n&&"number"==typeof n.length?t+=ub.apply(null,n):t+="object"==typeof n?_d(n):n,t+=" "}return t};let hb=null,db=!0;function pb(t){return function(...e){wb(t,...e)}}function fb(...e){var t="FIREBASE INTERNAL ERROR: "+ub(...e);cb.error(t)}function gb(e,t){return e===t?0:e<t?-1:1}function mb(e,t){if(t&&e in t)return t[e];throw new Error("Missing required key ("+e+") in object: "+_d(t))}function vb(e){if("object"!=typeof e||null===e)return _d(e);const t=[];for(const r in e)t.push(r);t.sort();let n="{";for(let i=0;i<t.length;i++)0!==i&&(n+=","),n+=_d(t[i]),n+=":",n+=vb(e[t[i]]);return n+="}",n}function yb(e,t){var n=e.length;if(n<=t)return[e];const r=[];for(let i=0;i<n;i+=t)i+t>n?r.push(e.substring(i,n)):r.push(e.substring(i,i+t));return r}const _b=function(e,t){Xh(!t||!0===e||!1===e,"Can't turn on custom loggers persistently."),!0===e?(cb.logLevel=zh.VERBOSE,hb=cb.log.bind(cb),t&&ab.set("logging_enabled",!0)):"function"==typeof e?hb=e:(hb=null,ab.remove("logging_enabled"))},wb=function(...e){var t;!0===db&&(db=!1,null===hb&&!0===ab.get("logging_enabled")&&_b(!0)),hb&&(t=ub.apply(null,e),hb(t))},bb=function(...e){var t=`FIREBASE FATAL ERROR: ${ub(...e)}`;throw cb.error(t),new Error(t)},Ib=function(...e){var t="FIREBASE WARNING: "+ub(...e);cb.warn(t)},Tb=function(){"undefined"!=typeof window&&window.location&&window.location.protocol&&-1!==window.location.protocol.indexOf("https:")&&Ib("Insecure Firebase access from a secure page. Please use https in calls to new Firebase().")},Eb=function(e){return"number"==typeof e&&(e!=e||e===Number.POSITIVE_INFINITY||e===Number.NEGATIVE_INFINITY)},kb="[MIN_NAME]",Sb="[MAX_NAME]",Cb=function(e,t){if(e===t)return 0;if(e===kb||t===Sb)return-1;if(t===kb||e===Sb)return 1;var n=Db(e),r=Db(t);return null!==n?null!==r?n-r==0?e.length-t.length:n-r:-1:null===r&&e<t?-1:1};function Ab(e,t){for(const n in e)e.hasOwnProperty(n)&&t(n,e[n])}function Nb(e){Xh(!Eb(e),"Invalid JSON number");let t,n,r,i,s;0===e?(n=0,r=0,t=1/e==-1/0?1:0):(t=e<0,e=Math.abs(e),r=e>=Math.pow(2,-1022)?(i=Math.min(Math.floor(Math.log(e)/Math.LN2),1023),n=i+1023,Math.round(e*Math.pow(2,52-i)-Math.pow(2,52))):(n=0,Math.round(e/Math.pow(2,-1074))));const o=[];for(s=52;s;--s)o.push(r%2?1:0),r=Math.floor(r/2);for(s=11;s;--s)o.push(n%2?1:0),n=Math.floor(n/2);o.push(t?1:0),o.reverse();const a=o.join("");let c="";for(s=0;s<64;s+=8){let e=parseInt(a.substr(s,8),2).toString(16);1===e.length&&(e="0"+e),c+=e}return c.toLowerCase()}function Rb(e,t){const n=setTimeout(e,t);return"object"==typeof n&&n.unref&&n.unref(),n}const Pb=new RegExp("^-?(0*)\\d{1,10}$"),xb=-2147483648,Ob=2147483647,Db=function(e){if(Pb.test(e)){var t=Number(e);if(t>=xb&&t<=Ob)return t}return null},Lb=function(e){try{e()}catch(t){setTimeout(()=>{var e=t.stack||"";throw Ib("Exception was thrown by user callback.",e),t},Math.floor(0))}};class Mb{constructor(e,t){this.appName_=e,this.appCheckProvider=t,this.appCheck=null==t?void 0:t.getImmediate({optional:!0}),this.appCheck||null!=t&&t.get().then(e=>this.appCheck=e)}getToken(n){return this.appCheck?this.appCheck.getToken(n):new Promise((e,t)=>{setTimeout(()=>{this.appCheck?this.getToken(n).then(e,t):e(null)},0)})}addTokenChangeListener(t){var e;null!==(e=this.appCheckProvider)&&void 0!==e&&e.get().then(e=>e.addTokenListener(t))}notifyForInvalidToken(){Ib(`Provided AppCheck credentials for the app named "${this.appName_}" `+"are invalid. This usually indicates your app was not initialized correctly.")}}class Fb{constructor(e,t,n){this.appName_=e,this.firebaseOptions_=t,this.authProvider_=n,this.auth_=null,this.auth_=n.getImmediate({optional:!0}),this.auth_||n.onInit(e=>this.auth_=e)}getToken(n){return this.auth_?this.auth_.getToken(n).catch(e=>e&&"auth/token-not-initialized"===e.code?(wb("Got auth/token-not-initialized error.  Treating as null token."),null):Promise.reject(e)):new Promise((e,t)=>{setTimeout(()=>{this.auth_?this.getToken(n).then(e,t):e(null)},0)})}addTokenChangeListener(t){this.auth_?this.auth_.addAuthTokenListener(t):this.authProvider_.get().then(e=>e.addAuthTokenListener(t))}removeTokenChangeListener(t){this.authProvider_.get().then(e=>e.removeAuthTokenListener(t))}notifyForInvalidToken(){let e='Provided authentication credentials for the app named "'+this.appName_+'" are invalid. This usually indicates your app was not initialized correctly. ';"credential"in this.firebaseOptions_?e+='Make sure the "credential" property provided to initializeApp() is authorized to access the specified "databaseURL" and is from the correct project.':"serviceAccount"in this.firebaseOptions_?e+='Make sure the "serviceAccount" property provided to initializeApp() is authorized to access the specified "databaseURL" and is from the correct project.':e+='Make sure the "apiKey" and "databaseURL" properties provided to initializeApp() match the values provided for your app at https://console.firebase.google.com/.',Ib(e)}}class Ub{constructor(e){this.accessToken=e}getToken(e){return Promise.resolve({accessToken:this.accessToken})}addTokenChangeListener(e){e(this.accessToken)}removeTokenChangeListener(e){}notifyForInvalidToken(){}}Ub.OWNER="owner";const jb=/(console\.firebase|firebase-console-\w+\.corp|firebase\.corp)\.google\.com/,qb="websocket",Vb="long_polling";class Bb{constructor(e,t,n,r,i=!1,s="",o=!1){this.secure=t,this.namespace=n,this.webSocketOnly=r,this.nodeAdmin=i,this.persistenceKey=s,this.includeNamespaceInQueryParams=o,this._host=e.toLowerCase(),this._domain=this._host.substr(this._host.indexOf(".")+1),this.internalHost=ob.get("host:"+e)||this._host}isCacheableHost(){return"s-"===this.internalHost.substr(0,2)}isCustomHost(){return"firebaseio.com"!==this._domain&&"firebaseio-demo.com"!==this._domain}get host(){return this._host}set host(e){e!==this.internalHost&&(this.internalHost=e,this.isCacheableHost()&&ob.set("host:"+this._host,this.internalHost))}toString(){let e=this.toURLString();return this.persistenceKey&&(e+="<"+this.persistenceKey+">"),e}toURLString(){var e=this.secure?"https://":"http://",t=this.includeNamespaceInQueryParams?`?ns=${this.namespace}`:"";return`${e}${this.host}/${t}`}}function Wb(e,t,n){Xh("string"==typeof t,"typeof type must == string"),Xh("object"==typeof n,"typeof params must == object");let r;if(t===qb)r=(e.secure?"wss://":"ws://")+e.internalHost+"/.ws?";else{if(t!==Vb)throw new Error("Unknown connection type: "+t);r=(e.secure?"https://":"http://")+e.internalHost+"/.lp?"}((t=e).host!==t.internalHost||t.isCustomHost()||t.includeNamespaceInQueryParams)&&(n.ns=e.namespace);const i=[];return Ab(n,(e,t)=>{i.push(e+"="+t)}),r+i.join("&")}class zb{constructor(){this.counters_={}}incrementCounter(e,t=1){bd(this.counters_,e)||(this.counters_[e]=0),this.counters_[e]+=t}get(){return nd(void 0,this.counters_)}}const Kb={},$b={};function Hb(e){var t=e.toString();return Kb[t]||(Kb[t]=new zb),Kb[t]}class Gb{constructor(e){this.onMessage_=e,this.pendingResponses=[],this.currentResponseNum=0,this.closeAfterResponse=-1,this.onClose=null}closeAfter(e,t){this.closeAfterResponse=e,this.onClose=t,this.closeAfterResponse<this.currentResponseNum&&(this.onClose(),this.onClose=null)}handleResponse(e,t){for(this.pendingResponses[e]=t;this.pendingResponses[this.currentResponseNum];){const n=this.pendingResponses[this.currentResponseNum];delete this.pendingResponses[this.currentResponseNum];for(let e=0;e<n.length;++e)n[e]&&Lb(()=>{this.onMessage_(n[e])});if(this.currentResponseNum===this.closeAfterResponse){this.onClose&&(this.onClose(),this.onClose=null);break}this.currentResponseNum++}}}class Qb{constructor(e,t,n,r,i,s,o){this.connId=e,this.repoInfo=t,this.applicationId=n,this.appCheckToken=r,this.authToken=i,this.transportSessionId=s,this.lastSessionId=o,this.bytesSent=0,this.bytesReceived=0,this.everConnected_=!1,this.log_=pb(e),this.stats_=Hb(t),this.urlFn=e=>(this.appCheckToken&&(e.ac=this.appCheckToken),Wb(t,Vb,e))}open(e,t){this.curSegmentNum=0,this.onDisconnect_=t,this.myPacketOrderer=new Gb(e),this.isClosed_=!1,this.connectTimeoutTimer_=setTimeout(()=>{this.log_("Timed out trying to connect."),this.onClosed_(),this.connectTimeoutTimer_=null},Math.floor(3e4)),function(t){if("complete"===document.readyState)t();else{let e=!1;const n=function(){document.body?e||(e=!0,t()):setTimeout(n,Math.floor(10))};document.addEventListener?(document.addEventListener("DOMContentLoaded",n,!1),window.addEventListener("load",n,!1)):document.attachEvent&&(document.attachEvent("onreadystatechange",()=>{"complete"===document.readyState&&n()}),window.attachEvent("onload",n))}}(()=>{if(!this.isClosed_){this.scriptTagHolder=new Yb((...e)=>{var[t,n,r]=e;if(this.incrementIncomingBytes_(e),this.scriptTagHolder)if(this.connectTimeoutTimer_&&(clearTimeout(this.connectTimeoutTimer_),this.connectTimeoutTimer_=null),this.everConnected_=!0,"start"===t)this.id=n,this.password=r;else{if("close"!==t)throw new Error("Unrecognized command received: "+t);n?(this.scriptTagHolder.sendNewPolls=!1,this.myPacketOrderer.closeAfter(n,()=>{this.onClosed_()})):this.onClosed_()}},(...e)=>{var[t,n]=e;this.incrementIncomingBytes_(e),this.myPacketOrderer.handleResponse(t,n)},()=>{this.onClosed_()},this.urlFn);const t={start:"t"};t.ser=Math.floor(1e8*Math.random()),this.scriptTagHolder.uniqueCallbackIdentifier&&(t.cb=this.scriptTagHolder.uniqueCallbackIdentifier),t.v="5",this.transportSessionId&&(t.s=this.transportSessionId),this.lastSessionId&&(t.ls=this.lastSessionId),this.applicationId&&(t.p=this.applicationId),this.appCheckToken&&(t.ac=this.appCheckToken),"undefined"!=typeof location&&location.hostname&&jb.test(location.hostname)&&(t.r="f");var e=this.urlFn(t);this.log_("Connecting via long-poll to "+e),this.scriptTagHolder.addTag(e,()=>{})}})}start(){this.scriptTagHolder.startLongPoll(this.id,this.password),this.addDisconnectPingFrame(this.id,this.password)}static forceAllow(){Qb.forceAllow_=!0}static forceDisallow(){Qb.forceDisallow_=!0}static isAvailable(){return!!Qb.forceAllow_||!(Qb.forceDisallow_||"undefined"==typeof document||null==document.createElement||"object"==typeof window&&window.chrome&&window.chrome.extension&&!/^chrome/.test(window.location.href)||"object"==typeof Windows&&"object"==typeof Windows.UI)}markConnectionHealthy(){}shutdown_(){this.isClosed_=!0,this.scriptTagHolder&&(this.scriptTagHolder.close(),this.scriptTagHolder=null),this.myDisconnFrame&&(document.body.removeChild(this.myDisconnFrame),this.myDisconnFrame=null),this.connectTimeoutTimer_&&(clearTimeout(this.connectTimeoutTimer_),this.connectTimeoutTimer_=null)}onClosed_(){this.isClosed_||(this.log_("Longpoll is closing itself"),this.shutdown_(),this.onDisconnect_&&(this.onDisconnect_(this.everConnected_),this.onDisconnect_=null))}close(){this.isClosed_||(this.log_("Longpoll is being closed."),this.shutdown_())}send(e){var t=_d(e);this.bytesSent+=t.length,this.stats_.incrementCounter("bytes_sent",t.length);var t=Qh(t),n=yb(t,1840);for(let r=0;r<n.length;r++)this.scriptTagHolder.enqueueSegment(this.curSegmentNum,n.length,n[r]),this.curSegmentNum++}addDisconnectPingFrame(e,t){this.myDisconnFrame=document.createElement("iframe");const n={dframe:"t"};n.id=e,n.pw=t,this.myDisconnFrame.src=this.urlFn(n),this.myDisconnFrame.style.display="none",document.body.appendChild(this.myDisconnFrame)}incrementIncomingBytes_(e){var t=_d(e).length;this.bytesReceived+=t,this.stats_.incrementCounter("bytes_received",t)}}class Yb{constructor(t,n,e,r){this.onDisconnect=e,this.urlFn=r,this.outstandingRequests=new Set,this.pendingSegs=[],this.currentSerial=Math.floor(1e8*Math.random()),this.sendNewPolls=!0;{this.uniqueCallbackIdentifier=lb(),window["pLPCommand"+this.uniqueCallbackIdentifier]=t,window["pRTLPCB"+this.uniqueCallbackIdentifier]=n,this.myIFrame=Yb.createIFrame_();let e="";this.myIFrame.src&&"javascript:"===this.myIFrame.src.substr(0,"javascript:".length)&&(i=document.domain,e='<script>document.domain="'+i+'";<\/script>');var i="<html><body>"+e+"</body></html>";try{this.myIFrame.doc.open(),this.myIFrame.doc.write(i),this.myIFrame.doc.close()}catch(e){wb("frame writing exception"),e.stack&&wb(e.stack),wb(e)}}}static createIFrame_(){const t=document.createElement("iframe");if(t.style.display="none",!document.body)throw"Document body has not initialized. Wait to initialize Firebase until after the document is ready.";document.body.appendChild(t);try{t.contentWindow.document||wb("No IE domain setting required")}catch(e){var n=document.domain;t.src="javascript:void((function(){document.open();document.domain='"+n+"';document.close();})())"}return t.contentDocument?t.doc=t.contentDocument:t.contentWindow?t.doc=t.contentWindow.document:t.document&&(t.doc=t.document),t}close(){this.alive=!1,this.myIFrame&&(this.myIFrame.doc.body.innerHTML="",setTimeout(()=>{null!==this.myIFrame&&(document.body.removeChild(this.myIFrame),this.myIFrame=null)},Math.floor(0)));const e=this.onDisconnect;e&&(this.onDisconnect=null,e())}startLongPoll(e,t){for(this.myID=e,this.myPW=t,this.alive=!0;this.newRequest_(););}newRequest_(){if(this.alive&&this.sendNewPolls&&this.outstandingRequests.size<(0<this.pendingSegs.length?2:1)){this.currentSerial++;const i={};i.id=this.myID,i.pw=this.myPW,i.ser=this.currentSerial;var n=this.urlFn(i);let e="",t=0;for(;0<this.pendingSegs.length;){if(!(this.pendingSegs[0].d.length+30+e.length<=1870))break;var r=this.pendingSegs.shift();e=e+"&seg"+t+"="+r.seg+"&ts"+t+"="+r.ts+"&d"+t+"="+r.d,t++}return n+=e,this.addLongPollTag_(n,this.currentSerial),!0}return!1}enqueueSegment(e,t,n){this.pendingSegs.push({seg:e,ts:t,d:n}),this.alive&&this.newRequest_()}addLongPollTag_(e,t){this.outstandingRequests.add(t);const n=()=>{this.outstandingRequests.delete(t),this.newRequest_()},r=setTimeout(n,Math.floor(25e3));this.addTag(e,()=>{clearTimeout(r),n()})}addTag(e,n){setTimeout(()=>{try{if(!this.sendNewPolls)return;const t=this.myIFrame.doc.createElement("script");t.type="text/javascript",t.async=!0,t.src=e,t.onload=t.onreadystatechange=function(){var e=t.readyState;e&&"loaded"!==e&&"complete"!==e||(t.onload=t.onreadystatechange=null,t.parentNode&&t.parentNode.removeChild(t),n())},t.onerror=()=>{wb("Long-poll script failed to load: "+e),this.sendNewPolls=!1,this.close()},this.myIFrame.doc.body.appendChild(t)}catch(e){}},Math.floor(1))}}let Xb=null;"undefined"!=typeof MozWebSocket?Xb=MozWebSocket:"undefined"!=typeof WebSocket&&(Xb=WebSocket);class Jb{constructor(e,t,n,r,i,s,o){this.connId=e,this.applicationId=n,this.appCheckToken=r,this.authToken=i,this.keepaliveTimer=null,this.frames=null,this.totalFrames=0,this.bytesSent=0,this.bytesReceived=0,this.log_=pb(this.connId),this.stats_=Hb(t),this.connURL=Jb.connectionURL_(t,s,o,r),this.nodeAdmin=t.nodeAdmin}static connectionURL_(e,t,n,r){const i={v:"5"};return"undefined"!=typeof location&&location.hostname&&jb.test(location.hostname)&&(i.r="f"),t&&(i.s=t),n&&(i.ls=n),r&&(i.ac=r),Wb(e,qb,i)}open(e,t){this.onDisconnect=t,this.onMessage=e,this.log_("Websocket connecting to "+this.connURL),this.everConnected_=!1,ob.set("previous_websocket_failure",!0);try{hd()||(n={headers:{"X-Firebase-GMPID":this.applicationId||"","X-Firebase-AppCheck":this.appCheckToken||""}},this.mySock=new Xb(this.connURL,[],n))}catch(e){this.log_("Error instantiating WebSocket.");var n=e.message||e.data;return n&&this.log_(n),void this.onClosed_()}this.mySock.onopen=()=>{this.log_("Websocket connected."),this.everConnected_=!0},this.mySock.onclose=()=>{this.log_("Websocket connection was disconnected."),this.mySock=null,this.onClosed_()},this.mySock.onmessage=e=>{this.handleIncomingFrame(e)},this.mySock.onerror=e=>{this.log_("WebSocket error.  Closing connection.");var t=e.message||e.data;t&&this.log_(t),this.onClosed_()}}start(){}static forceDisallow(){Jb.forceDisallow_=!0}static isAvailable(){let e=!1;var t;return"undefined"==typeof navigator||!navigator.userAgent||(t=navigator.userAgent.match(/Android ([0-9]{0,}\.[0-9]{0,})/))&&1<t.length&&parseFloat(t[1])<4.4&&(e=!0),!e&&null!==Xb&&!Jb.forceDisallow_}static previouslyFailed(){return ob.isInMemoryStorage||!0===ob.get("previous_websocket_failure")}markConnectionHealthy(){ob.remove("previous_websocket_failure")}appendFrame_(e){var t;this.frames.push(e),this.frames.length===this.totalFrames&&(t=this.frames.join(""),this.frames=null,t=yd(t),this.onMessage(t))}handleNewFrameCount_(e){this.totalFrames=e,this.frames=[]}extractFrameCount_(e){if(Xh(null===this.frames,"We already have a frame buffer"),e.length<=6){var t=Number(e);if(!isNaN(t))return this.handleNewFrameCount_(t),null}return this.handleNewFrameCount_(1),e}handleIncomingFrame(e){var t;null!==this.mySock&&(t=e.data,this.bytesReceived+=t.length,this.stats_.incrementCounter("bytes_received",t.length),this.resetKeepAlive(),null!==this.frames?this.appendFrame_(t):null!==(t=this.extractFrameCount_(t))&&this.appendFrame_(t))}send(e){this.resetKeepAlive();var t=_d(e);this.bytesSent+=t.length,this.stats_.incrementCounter("bytes_sent",t.length);var n=yb(t,16384);1<n.length&&this.sendString_(String(n.length));for(let r=0;r<n.length;r++)this.sendString_(n[r])}shutdown_(){this.isClosed_=!0,this.keepaliveTimer&&(clearInterval(this.keepaliveTimer),this.keepaliveTimer=null),this.mySock&&(this.mySock.close(),this.mySock=null)}onClosed_(){this.isClosed_||(this.log_("WebSocket is closing itself"),this.shutdown_(),this.onDisconnect&&(this.onDisconnect(this.everConnected_),this.onDisconnect=null))}close(){this.isClosed_||(this.log_("WebSocket is being closed"),this.shutdown_())}resetKeepAlive(){clearInterval(this.keepaliveTimer),this.keepaliveTimer=setInterval(()=>{this.mySock&&this.sendString_("0"),this.resetKeepAlive()},Math.floor(45e3))}sendString_(e){try{this.mySock.send(e)}catch(e){this.log_("Exception thrown from WebSocket.send():",e.message||e.data,"Closing connection."),setTimeout(this.onClosed_.bind(this),0)}}}Jb.responsesRequiredToBeHealthy=2,Jb.healthyTimeout=3e4;class Zb{constructor(e){this.initTransports_(e)}static get ALL_TRANSPORTS(){return[Qb,Jb]}initTransports_(e){var t=Jb&&Jb.isAvailable();let n=t&&!Jb.previouslyFailed();if(e.webSocketOnly&&(t||Ib("wss:// URL used, but browser isn't known to support websockets.  Trying anyway."),n=!0),n)this.transports_=[Jb];else{const r=this.transports_=[];for(const i of Zb.ALL_TRANSPORTS)i&&i.isAvailable()&&r.push(i)}}initialTransport(){if(0<this.transports_.length)return this.transports_[0];throw new Error("No transports available")}upgradeTransport(){return 1<this.transports_.length?this.transports_[1]:null}}class eI{constructor(e,t,n,r,i,s,o,a,c,l){this.id=e,this.repoInfo_=t,this.applicationId_=n,this.appCheckToken_=r,this.authToken_=i,this.onMessage_=s,this.onReady_=o,this.onDisconnect_=a,this.onKill_=c,this.lastSessionId=l,this.connectionCount=0,this.pendingDataMessages=[],this.state_=0,this.log_=pb("c:"+this.id+":"),this.transportManager_=new Zb(t),this.log_("Connection created"),this.start_()}start_(){const e=this.transportManager_.initialTransport();this.conn_=new e(this.nextTransportId_(),this.repoInfo_,this.applicationId_,this.appCheckToken_,this.authToken_,null,this.lastSessionId),this.primaryResponsesRequired_=e.responsesRequiredToBeHealthy||0;const t=this.connReceiver_(this.conn_),n=this.disconnReceiver_(this.conn_);this.tx_=this.conn_,this.rx_=this.conn_,this.secondaryConn_=null,this.isHealthy_=!1,setTimeout(()=>{this.conn_&&this.conn_.open(t,n)},Math.floor(0));var r=e.healthyTimeout||0;0<r&&(this.healthyTimeout_=Rb(()=>{this.healthyTimeout_=null,this.isHealthy_||(this.conn_&&102400<this.conn_.bytesReceived?(this.log_("Connection exceeded healthy timeout but has received "+this.conn_.bytesReceived+" bytes.  Marking connection healthy."),this.isHealthy_=!0,this.conn_.markConnectionHealthy()):this.conn_&&10240<this.conn_.bytesSent?this.log_("Connection exceeded healthy timeout but has sent "+this.conn_.bytesSent+" bytes.  Leaving connection alive."):(this.log_("Closing unhealthy connection after timeout."),this.close()))},Math.floor(r)))}nextTransportId_(){return"c:"+this.id+":"+this.connectionCount++}disconnReceiver_(t){return e=>{t===this.conn_?this.onConnectionLost_(e):t===this.secondaryConn_?(this.log_("Secondary connection lost."),this.onSecondaryConnectionLost_()):this.log_("closing an old connection")}}connReceiver_(t){return e=>{2!==this.state_&&(t===this.rx_?this.onPrimaryMessageReceived_(e):t===this.secondaryConn_?this.onSecondaryMessageReceived_(e):this.log_("message on old connection"))}}sendRequest(e){this.sendData_({t:"d",d:e})}tryCleanupConnection(){this.tx_===this.secondaryConn_&&this.rx_===this.secondaryConn_&&(this.log_("cleaning up and promoting a connection: "+this.secondaryConn_.connId),this.conn_=this.secondaryConn_,this.secondaryConn_=null)}onSecondaryControl_(e){var t;"t"in e&&("a"===(t=e.t)?this.upgradeIfSecondaryHealthy_():"r"===t?(this.log_("Got a reset on secondary, closing it"),this.secondaryConn_.close(),this.tx_!==this.secondaryConn_&&this.rx_!==this.secondaryConn_||this.close()):"o"===t&&(this.log_("got pong on secondary."),this.secondaryResponsesRequired_--,this.upgradeIfSecondaryHealthy_()))}onSecondaryMessageReceived_(e){var t=mb("t",e),n=mb("d",e);if("c"===t)this.onSecondaryControl_(n);else{if("d"!==t)throw new Error("Unknown protocol layer: "+t);this.pendingDataMessages.push(n)}}upgradeIfSecondaryHealthy_(){this.secondaryResponsesRequired_<=0?(this.log_("Secondary connection is healthy."),this.isHealthy_=!0,this.secondaryConn_.markConnectionHealthy(),this.proceedWithUpgrade_()):(this.log_("sending ping on secondary."),this.secondaryConn_.send({t:"c",d:{t:"p",d:{}}}))}proceedWithUpgrade_(){this.secondaryConn_.start(),this.log_("sending client ack on secondary"),this.secondaryConn_.send({t:"c",d:{t:"a",d:{}}}),this.log_("Ending transmission on primary"),this.conn_.send({t:"c",d:{t:"n",d:{}}}),this.tx_=this.secondaryConn_,this.tryCleanupConnection()}onPrimaryMessageReceived_(e){var t=mb("t",e),n=mb("d",e);"c"===t?this.onControl_(n):"d"===t&&this.onDataMessage_(n)}onDataMessage_(e){this.onPrimaryResponse_(),this.onMessage_(e)}onPrimaryResponse_(){this.isHealthy_||(this.primaryResponsesRequired_--,this.primaryResponsesRequired_<=0&&(this.log_("Primary connection is healthy."),this.isHealthy_=!0,this.conn_.markConnectionHealthy()))}onControl_(e){var t=mb("t",e);if("d"in e){var n=e.d;if("h"===t)this.onHandshake_(n);else if("n"===t){this.log_("recvd end transmission on primary"),this.rx_=this.secondaryConn_;for(let e=0;e<this.pendingDataMessages.length;++e)this.onDataMessage_(this.pendingDataMessages[e]);this.pendingDataMessages=[],this.tryCleanupConnection()}else"s"===t?this.onConnectionShutdown_(n):"r"===t?this.onReset_(n):"e"===t?fb("Server Error: "+n):"o"===t?(this.log_("got pong on primary."),this.onPrimaryResponse_(),this.sendPingOnPrimaryIfNecessary_()):fb("Unknown control packet command: "+t)}}onHandshake_(e){var t=e.ts,n=e.v,r=e.h;this.sessionId=e.s,this.repoInfo_.host=r,0===this.state_&&(this.conn_.start(),this.onConnectionEstablished_(this.conn_,t),"5"!==n&&Ib("Protocol version mismatch detected"),this.tryStartUpgrade_())}tryStartUpgrade_(){var e=this.transportManager_.upgradeTransport();e&&this.startUpgrade_(e)}startUpgrade_(e){this.secondaryConn_=new e(this.nextTransportId_(),this.repoInfo_,this.applicationId_,this.appCheckToken_,this.authToken_,this.sessionId),this.secondaryResponsesRequired_=e.responsesRequiredToBeHealthy||0;var t=this.connReceiver_(this.secondaryConn_),n=this.disconnReceiver_(this.secondaryConn_);this.secondaryConn_.open(t,n),Rb(()=>{this.secondaryConn_&&(this.log_("Timed out trying to upgrade."),this.secondaryConn_.close())},Math.floor(6e4))}onReset_(e){this.log_("Reset packet received.  New host: "+e),this.repoInfo_.host=e,1===this.state_?this.close():(this.closeConnections_(),this.start_())}onConnectionEstablished_(e,t){this.log_("Realtime connection established."),this.conn_=e,this.state_=1,this.onReady_&&(this.onReady_(t,this.sessionId),this.onReady_=null),0===this.primaryResponsesRequired_?(this.log_("Primary connection is healthy."),this.isHealthy_=!0):Rb(()=>{this.sendPingOnPrimaryIfNecessary_()},Math.floor(5e3))}sendPingOnPrimaryIfNecessary_(){this.isHealthy_||1!==this.state_||(this.log_("sending ping on primary."),this.sendData_({t:"c",d:{t:"p",d:{}}}))}onSecondaryConnectionLost_(){var e=this.secondaryConn_;this.secondaryConn_=null,this.tx_!==e&&this.rx_!==e||this.close()}onConnectionLost_(e){this.conn_=null,e||0!==this.state_?1===this.state_&&this.log_("Realtime connection lost."):(this.log_("Realtime connection failed."),this.repoInfo_.isCacheableHost()&&(ob.remove("host:"+this.repoInfo_.host),this.repoInfo_.internalHost=this.repoInfo_.host)),this.close()}onConnectionShutdown_(e){this.log_("Connection shutdown command received. Shutting down..."),this.onKill_&&(this.onKill_(e),this.onKill_=null),this.onDisconnect_=null,this.close()}sendData_(e){if(1!==this.state_)throw"Connection is not connected";this.tx_.send(e)}close(){2!==this.state_&&(this.log_("Closing realtime connection."),this.state_=2,this.closeConnections_(),this.onDisconnect_&&(this.onDisconnect_(),this.onDisconnect_=null))}closeConnections_(){this.log_("Shutting down all connections"),this.conn_&&(this.conn_.close(),this.conn_=null),this.secondaryConn_&&(this.secondaryConn_.close(),this.secondaryConn_=null),this.healthyTimeout_&&(clearTimeout(this.healthyTimeout_),this.healthyTimeout_=null)}}class tI{put(e,t,n,r){}merge(e,t,n,r){}refreshAuthToken(e){}refreshAppCheckToken(e){}onDisconnectPut(e,t,n){}onDisconnectMerge(e,t,n){}onDisconnectCancel(e,t){}reportStats(e){}}class nI{constructor(e){this.allowedEvents_=e,this.listeners_={},Xh(Array.isArray(e)&&0<e.length,"Requires a non-empty array")}trigger(t,...n){if(Array.isArray(this.listeners_[t])){const r=[...this.listeners_[t]];for(let e=0;e<r.length;e++)r[e].callback.apply(r[e].context,n)}}on(e,t,n){this.validateEventType_(e),this.listeners_[e]=this.listeners_[e]||[],this.listeners_[e].push({callback:t,context:n});var r=this.getInitialEvent(e);r&&t.apply(n,r)}off(e,t,n){this.validateEventType_(e);const r=this.listeners_[e]||[];for(let i=0;i<r.length;i++)if(r[i].callback===t&&(!n||n===r[i].context))return void r.splice(i,1)}validateEventType_(t){Xh(this.allowedEvents_.find(e=>e===t),"Unknown event: "+t)}}class rI extends nI{constructor(){super(["online"]),this.online_=!0,"undefined"==typeof window||void 0===window.addEventListener||od()||(window.addEventListener("online",()=>{this.online_||(this.online_=!0,this.trigger("online",!0))},!1),window.addEventListener("offline",()=>{this.online_&&(this.online_=!1,this.trigger("online",!1))},!1))}static getInstance(){return new rI}getInitialEvent(e){return Xh("online"===e,"Unknown event type: "+e),[this.online_]}currentlyOnline(){return this.online_}}class iI{constructor(n,e){if(void 0===e){this.pieces_=n.split("/");let e=0;for(let t=0;t<this.pieces_.length;t++)0<this.pieces_[t].length&&(this.pieces_[e]=this.pieces_[t],e++);this.pieces_.length=e,this.pieceNum_=0}else this.pieces_=n,this.pieceNum_=e}toString(){let e="";for(let t=this.pieceNum_;t<this.pieces_.length;t++)""!==this.pieces_[t]&&(e+="/"+this.pieces_[t]);return e||"/"}}function sI(){return new iI("")}function oI(e){return e.pieceNum_>=e.pieces_.length?null:e.pieces_[e.pieceNum_]}function aI(e){return e.pieces_.length-e.pieceNum_}function cI(e){let t=e.pieceNum_;return t<e.pieces_.length&&t++,new iI(e.pieces_,t)}function lI(e){return e.pieceNum_<e.pieces_.length?e.pieces_[e.pieces_.length-1]:null}function uI(e,t=0){return e.pieces_.slice(e.pieceNum_+t)}function hI(e){if(e.pieceNum_>=e.pieces_.length)return null;const t=[];for(let n=e.pieceNum_;n<e.pieces_.length-1;n++)t.push(e.pieces_[n]);return new iI(t,0)}function dI(e,t){const n=[];for(let i=e.pieceNum_;i<e.pieces_.length;i++)n.push(e.pieces_[i]);if(t instanceof iI)for(let e=t.pieceNum_;e<t.pieces_.length;e++)n.push(t.pieces_[e]);else{var r=t.split("/");for(let e=0;e<r.length;e++)0<r[e].length&&n.push(r[e])}return new iI(n,0)}function pI(e){return e.pieceNum_>=e.pieces_.length}function fI(e,t){var n=oI(e),r=oI(t);if(null===n)return t;if(n===r)return fI(cI(e),cI(t));throw new Error("INTERNAL ERROR: innerPath ("+t+") is not within outerPath ("+e+")")}function gI(e,t){var n=uI(e,0),r=uI(t,0);for(let s=0;s<n.length&&s<r.length;s++){var i=Cb(n[s],r[s]);if(0!==i)return i}return n.length===r.length?0:n.length<r.length?-1:1}function mI(e,t){if(aI(e)!==aI(t))return!1;for(let n=e.pieceNum_,r=t.pieceNum_;n<=e.pieces_.length;n++,r++)if(e.pieces_[n]!==t.pieces_[r])return!1;return!0}function vI(e,t){let n=e.pieceNum_,r=t.pieceNum_;if(aI(e)>aI(t))return!1;for(;n<e.pieces_.length;){if(e.pieces_[n]!==t.pieces_[r])return!1;++n,++r}return!0}class yI{constructor(e,t){this.errorPrefix_=t,this.parts_=uI(e,0),this.byteLength_=Math.max(1,this.parts_.length);for(let n=0;n<this.parts_.length;n++)this.byteLength_+=Ud(this.parts_[n]);_I(this)}}function _I(e){if(768<e.byteLength_)throw new Error(e.errorPrefix_+"has a key path longer than 768 bytes ("+e.byteLength_+").");if(32<e.parts_.length)throw new Error(e.errorPrefix_+"path specified exceeds the maximum depth that can be written (32) or object contains a cycle "+wI(e))}function wI(e){return 0===e.parts_.length?"":"in property '"+e.parts_.join(".")+"'"}class bI extends nI{constructor(){super(["visible"]);let t,e;"undefined"!=typeof document&&void 0!==document.addEventListener&&(void 0!==document.hidden?(e="visibilitychange",t="hidden"):void 0!==document.mozHidden?(e="mozvisibilitychange",t="mozHidden"):void 0!==document.msHidden?(e="msvisibilitychange",t="msHidden"):void 0!==document.webkitHidden&&(e="webkitvisibilitychange",t="webkitHidden")),this.visible_=!0,e&&document.addEventListener(e,()=>{var e=!document[t];e!==this.visible_&&(this.visible_=e,this.trigger("visible",e))},!1)}static getInstance(){return new bI}getInitialEvent(e){return Xh("visible"===e,"Unknown event type: "+e),[this.visible_]}}class II extends tI{constructor(e,t,n,r,i,s,o,a){if(super(),this.repoInfo_=e,this.applicationId_=t,this.onDataUpdate_=n,this.onConnectStatus_=r,this.onServerInfoUpdate_=i,this.authTokenProvider_=s,this.appCheckTokenProvider_=o,this.authOverride_=a,this.id=II.nextPersistentConnectionId_++,this.log_=pb("p:"+this.id+":"),this.interruptReasons_={},this.listens=new Map,this.outstandingPuts_=[],this.outstandingGets_=[],this.outstandingPutCount_=0,this.outstandingGetCount_=0,this.onDisconnectRequestQueue_=[],this.connected_=!1,this.reconnectDelay_=1e3,this.maxReconnectDelay_=3e5,this.securityDebugCallback_=null,this.lastSessionId=null,this.establishConnectionTimer_=null,this.visible_=!1,this.requestCBHash_={},this.requestNumber_=0,this.realtime_=null,this.authToken_=null,this.appCheckToken_=null,this.forceTokenRefresh_=!1,this.invalidAuthTokenCount_=0,this.invalidAppCheckTokenCount_=0,this.firstConnection_=!0,this.lastConnectionAttemptTime_=null,this.lastConnectionEstablishedTime_=null,a&&!hd())throw new Error("Auth override specified in options, but not supported on non Node.js platforms");bI.getInstance().on("visible",this.onVisible_,this),-1===e.host.indexOf("fblocal")&&rI.getInstance().on("online",this.onOnline_,this)}sendRequest(e,t,n){var r=++this.requestNumber_,i={r:r,a:e,b:t};this.log_(_d(i)),Xh(this.connected_,"sendRequest call when we're not connected not allowed."),this.realtime_.sendRequest(i),n&&(this.requestCBHash_[r]=n)}get(e){this.initConnection_();const n=new rd,r={p:e._path.toString(),q:e._queryObject},t={action:"g",request:r,onComplete:e=>{var t=e.d;"ok"===e.s?(this.onDataUpdate_(r.p,t,!1,null),n.resolve(t)):n.reject(t)}};this.outstandingGets_.push(t),this.outstandingGetCount_++;const i=this.outstandingGets_.length-1;return this.connected_||setTimeout(()=>{var e=this.outstandingGets_[i];void 0!==e&&t===e&&(delete this.outstandingGets_[i],this.outstandingGetCount_--,0===this.outstandingGetCount_&&(this.outstandingGets_=[]),this.log_("get "+i+" timed out on connection"),n.reject(new Error("Client is offline.")))},3e3),this.connected_&&this.sendGet_(i),n.promise}listen(e,t,n,r){this.initConnection_();var i=e._queryIdentifier,s=e._path.toString();this.log_("Listen called for "+s+" "+i),this.listens.has(s)||this.listens.set(s,new Map),Xh(e._queryParams.isDefault()||!e._queryParams.loadsAllData(),"listen() called for non-default but complete query"),Xh(!this.listens.get(s).has(i),"listen() called twice for same path/queryId.");var o={onComplete:r,hashFn:t,query:e,tag:n};this.listens.get(s).set(i,o),this.connected_&&this.sendListen_(o)}sendGet_(t){const n=this.outstandingGets_[t];this.sendRequest("g",n.request,e=>{delete this.outstandingGets_[t],this.outstandingGetCount_--,0===this.outstandingGetCount_&&(this.outstandingGets_=[]),n.onComplete&&n.onComplete(e)})}sendListen_(r){const i=r.query,s=i._path.toString(),o=i._queryIdentifier;this.log_("Listen on "+s+" for "+o);const e={p:s};r.tag&&(e.q=i._queryObject,e.t=r.tag),e.h=r.hashFn(),this.sendRequest("q",e,e=>{var t=e.d,n=e.s;II.warnOnListenWarnings_(t,i),(this.listens.get(s)&&this.listens.get(s).get(o))===r&&(this.log_("listen response",e),"ok"!==n&&this.removeListen_(s,o),r.onComplete&&r.onComplete(n,t))})}static warnOnListenWarnings_(e,t){if(e&&"object"==typeof e&&bd(e,"w")){const i=Id(e,"w");var n,r;Array.isArray(i)&&~i.indexOf("no_index")&&(n='".indexOn": "'+t._queryParams.getIndex().toString()+'"',r=t._path.toString(),Ib("Using an unspecified index. Your data will be downloaded and "+`filtered on the client. Consider adding ${n} at `+`${r} to your security rules for better performance.`))}}refreshAuthToken(e){this.authToken_=e,this.log_("Auth token refreshed"),this.authToken_?this.tryAuth():this.connected_&&this.sendRequest("unauth",{},()=>{}),this.reduceReconnectDelayIfAdminCredential_(e)}reduceReconnectDelayIfAdminCredential_(e){var t;(e&&40===e.length||(e=e,"object"==typeof(t=wd(e).claims)&&!0===t.admin))&&(this.log_("Admin auth credential detected.  Reducing max reconnect time."),this.maxReconnectDelay_=3e4)}refreshAppCheckToken(e){this.appCheckToken_=e,this.log_("App check token refreshed"),this.appCheckToken_?this.tryAppCheck():this.connected_&&this.sendRequest("unappeck",{},()=>{})}tryAuth(){if(this.connected_&&this.authToken_){const r=this.authToken_;var e=function(e){const t=wd(e),n=t.claims;return!!n&&"object"==typeof n&&n.hasOwnProperty("iat")}(r)?"auth":"gauth";const t={cred:r};null===this.authOverride_?t.noauth=!0:"object"==typeof this.authOverride_&&(t.authvar=this.authOverride_),this.sendRequest(e,t,e=>{var t=e.s,n=e.d||"error";this.authToken_===r&&("ok"===t?this.invalidAuthTokenCount_=0:this.onAuthRevoked_(t,n))})}}tryAppCheck(){this.connected_&&this.appCheckToken_&&this.sendRequest("appcheck",{token:this.appCheckToken_},e=>{var t=e.s,n=e.d||"error";"ok"===t?this.invalidAppCheckTokenCount_=0:this.onAppCheckRevoked_(t,n)})}unlisten(e,t){var n=e._path.toString(),r=e._queryIdentifier;this.log_("Unlisten called for "+n+" "+r),Xh(e._queryParams.isDefault()||!e._queryParams.loadsAllData(),"unlisten() called for non-default but complete query"),this.removeListen_(n,r)&&this.connected_&&this.sendUnlisten_(n,r,e._queryObject,t)}sendUnlisten_(e,t,n,r){this.log_("Unlisten on "+e+" for "+t);const i={p:e};r&&(i.q=n,i.t=r),this.sendRequest("n",i)}onDisconnectPut(e,t,n){this.initConnection_(),this.connected_?this.sendOnDisconnect_("o",e,t,n):this.onDisconnectRequestQueue_.push({pathString:e,action:"o",data:t,onComplete:n})}onDisconnectMerge(e,t,n){this.initConnection_(),this.connected_?this.sendOnDisconnect_("om",e,t,n):this.onDisconnectRequestQueue_.push({pathString:e,action:"om",data:t,onComplete:n})}onDisconnectCancel(e,t){this.initConnection_(),this.connected_?this.sendOnDisconnect_("oc",e,null,t):this.onDisconnectRequestQueue_.push({pathString:e,action:"oc",data:null,onComplete:t})}sendOnDisconnect_(e,t,n,r){var i={p:t,d:n};this.log_("onDisconnect "+e,i),this.sendRequest(e,i,e=>{r&&setTimeout(()=>{r(e.s,e.d)},Math.floor(0))})}put(e,t,n,r){this.putInternal("p",e,t,n,r)}merge(e,t,n,r){this.putInternal("m",e,t,n,r)}putInternal(e,t,n,r,i){this.initConnection_();const s={p:t,d:n};void 0!==i&&(s.h=i),this.outstandingPuts_.push({action:e,request:s,onComplete:r}),this.outstandingPutCount_++;var o=this.outstandingPuts_.length-1;this.connected_?this.sendPut_(o):this.log_("Buffering put: "+t)}sendPut_(t){const n=this.outstandingPuts_[t].action;var e=this.outstandingPuts_[t].request;const r=this.outstandingPuts_[t].onComplete;this.outstandingPuts_[t].queued=this.connected_,this.sendRequest(n,e,e=>{this.log_(n+" response",e),delete this.outstandingPuts_[t],this.outstandingPutCount_--,0===this.outstandingPutCount_&&(this.outstandingPuts_=[]),r&&r(e.s,e.d)})}reportStats(e){var t;this.connected_&&(this.log_("reportStats",t={c:e}),this.sendRequest("s",t,e=>{var t;"ok"!==e.s&&(t=e.d,this.log_("reportStats","Error sending stats: "+t))}))}onDataMessage_(e){if("r"in e){this.log_("from server: "+_d(e));var t=e.r;const n=this.requestCBHash_[t];n&&(delete this.requestCBHash_[t],n(e.b))}else{if("error"in e)throw"A server-side error has occurred: "+e.error;"a"in e&&this.onDataPush_(e.a,e.b)}}onDataPush_(e,t){this.log_("handleServerMessage",e,t),"d"===e?this.onDataUpdate_(t.p,t.d,!1,t.t):"m"===e?this.onDataUpdate_(t.p,t.d,!0,t.t):"c"===e?this.onListenRevoked_(t.p,t.q):"ac"===e?this.onAuthRevoked_(t.s,t.d):"apc"===e?this.onAppCheckRevoked_(t.s,t.d):"sd"===e?this.onSecurityDebugPacket_(t):fb("Unrecognized action received from server: "+_d(e)+"\nAre you using the latest client?")}onReady_(e,t){this.log_("connection ready"),this.connected_=!0,this.lastConnectionEstablishedTime_=(new Date).getTime(),this.handleTimestamp_(e),this.lastSessionId=t,this.firstConnection_&&this.sendConnectStats_(),this.restoreState_(),this.firstConnection_=!1,this.onConnectStatus_(!0)}scheduleConnect_(e){Xh(!this.realtime_,"Scheduling a connect when we're already connected/ing?"),this.establishConnectionTimer_&&clearTimeout(this.establishConnectionTimer_),this.establishConnectionTimer_=setTimeout(()=>{this.establishConnectionTimer_=null,this.establishConnection_()},Math.floor(e))}initConnection_(){!this.realtime_&&this.firstConnection_&&this.scheduleConnect_(0)}onVisible_(e){e&&!this.visible_&&this.reconnectDelay_===this.maxReconnectDelay_&&(this.log_("Window became visible.  Reducing delay."),this.reconnectDelay_=1e3,this.realtime_||this.scheduleConnect_(0)),this.visible_=e}onOnline_(e){e?(this.log_("Browser went online."),this.reconnectDelay_=1e3,this.realtime_||this.scheduleConnect_(0)):(this.log_("Browser went offline.  Killing connection."),this.realtime_&&this.realtime_.close())}onRealtimeDisconnect_(){var e;this.log_("data client disconnected"),this.connected_=!1,this.realtime_=null,this.cancelSentTransactions_(),this.requestCBHash_={},this.shouldReconnect_()&&(this.visible_?this.lastConnectionEstablishedTime_&&(3e4<(new Date).getTime()-this.lastConnectionEstablishedTime_&&(this.reconnectDelay_=1e3),this.lastConnectionEstablishedTime_=null):(this.log_("Window isn't visible.  Delaying reconnect."),this.reconnectDelay_=this.maxReconnectDelay_,this.lastConnectionAttemptTime_=(new Date).getTime()),e=(new Date).getTime()-this.lastConnectionAttemptTime_,e=Math.max(0,this.reconnectDelay_-e),e=Math.random()*e,this.log_("Trying to reconnect in "+e+"ms"),this.scheduleConnect_(e),this.reconnectDelay_=Math.min(this.maxReconnectDelay_,1.3*this.reconnectDelay_)),this.onConnectStatus_(!1)}async establishConnection_(){if(this.shouldReconnect_()){this.log_("Making a connection attempt"),this.lastConnectionAttemptTime_=(new Date).getTime(),this.lastConnectionEstablishedTime_=null;var e=this.onDataMessage_.bind(this),r=this.onReady_.bind(this);const u=this.onRealtimeDisconnect_.bind(this);var i=this.id+":"+II.nextConnectionId_++,s=this.lastSessionId;let t=!1,n=null;var o=function(){n?n.close():(t=!0,u())};this.realtime_={close:o,sendRequest:function(e){Xh(n,"sendRequest call when we're not connected not allowed."),n.sendRequest(e)}};var a=this.forceTokenRefresh_;this.forceTokenRefresh_=!1;try{var[c,l]=await Promise.all([this.authTokenProvider_.getToken(a),this.appCheckTokenProvider_.getToken(a)]);t?wb("getToken() completed but was canceled"):(wb("getToken() completed. Creating connection."),this.authToken_=c&&c.accessToken,this.appCheckToken_=l&&l.token,n=new eI(i,this.repoInfo_,this.applicationId_,this.appCheckToken_,this.authToken_,e,r,u,e=>{Ib(e+" ("+this.repoInfo_.toString()+")"),this.interrupt("server_kill")},s))}catch(e){this.log_("Failed to get token: "+e),t||(this.repoInfo_.nodeAdmin&&Ib(e),o())}}}interrupt(e){wb("Interrupting connection for reason: "+e),this.interruptReasons_[e]=!0,this.realtime_?this.realtime_.close():(this.establishConnectionTimer_&&(clearTimeout(this.establishConnectionTimer_),this.establishConnectionTimer_=null),this.connected_&&this.onRealtimeDisconnect_())}resume(e){wb("Resuming connection for reason: "+e),delete this.interruptReasons_[e],Td(this.interruptReasons_)&&(this.reconnectDelay_=1e3,this.realtime_||this.scheduleConnect_(0))}handleTimestamp_(e){var t=e-(new Date).getTime();this.onServerInfoUpdate_({serverTimeOffset:t})}cancelSentTransactions_(){for(let e=0;e<this.outstandingPuts_.length;e++){const t=this.outstandingPuts_[e];t&&"h"in t.request&&t.queued&&(t.onComplete&&t.onComplete("disconnect"),delete this.outstandingPuts_[e],this.outstandingPutCount_--)}0===this.outstandingPutCount_&&(this.outstandingPuts_=[])}onListenRevoked_(e,t){let n;n=t?t.map(e=>vb(e)).join("$"):"default";const r=this.removeListen_(e,n);r&&r.onComplete&&r.onComplete("permission_denied")}removeListen_(e,t){var n=new iI(e).toString();let r;if(this.listens.has(n)){const i=this.listens.get(n);r=i.get(t),i.delete(t),0===i.size&&this.listens.delete(n)}else r=void 0;return r}onAuthRevoked_(e,t){wb("Auth token revoked: "+e+"/"+t),this.authToken_=null,this.forceTokenRefresh_=!0,this.realtime_.close(),"invalid_token"!==e&&"permission_denied"!==e||(this.invalidAuthTokenCount_++,3<=this.invalidAuthTokenCount_&&(this.reconnectDelay_=3e4,this.authTokenProvider_.notifyForInvalidToken()))}onAppCheckRevoked_(e,t){wb("App check token revoked: "+e+"/"+t),this.appCheckToken_=null,this.forceTokenRefresh_=!0,"invalid_token"!==e&&"permission_denied"!==e||(this.invalidAppCheckTokenCount_++,3<=this.invalidAppCheckTokenCount_&&this.appCheckTokenProvider_.notifyForInvalidToken())}onSecurityDebugPacket_(e){this.securityDebugCallback_?this.securityDebugCallback_(e):"msg"in e&&console.log("FIREBASE: "+e.msg.replace("\n","\nFIREBASE: "))}restoreState_(){this.tryAuth(),this.tryAppCheck();for(const t of this.listens.values())for(const n of t.values())this.sendListen_(n);for(let r=0;r<this.outstandingPuts_.length;r++)this.outstandingPuts_[r]&&this.sendPut_(r);for(;this.onDisconnectRequestQueue_.length;){var e=this.onDisconnectRequestQueue_.shift();this.sendOnDisconnect_(e.action,e.pathString,e.data,e.onComplete)}for(let i=0;i<this.outstandingGets_.length;i++)this.outstandingGets_[i]&&this.sendGet_(i)}sendConnectStats_(){const e={};e["sdk.js."+Qw.replace(/\./g,"-")]=1,od()?e["framework.cordova"]=1:ld()&&(e["framework.reactnative"]=1),this.reportStats(e)}shouldReconnect_(){var e=rI.getInstance().currentlyOnline();return Td(this.interruptReasons_)&&e}}II.nextPersistentConnectionId_=0,II.nextConnectionId_=0;class TI{constructor(e,t){this.name=e,this.node=t}static Wrap(e,t){return new TI(e,t)}}class EI{getCompare(){return this.compare.bind(this)}indexedValueChanged(e,t){var n=new TI(kb,e),r=new TI(kb,t);return 0!==this.compare(n,r)}minPost(){return TI.MIN}}let kI;class SI extends EI{static get __EMPTY_NODE(){return kI}static set __EMPTY_NODE(e){kI=e}compare(e,t){return Cb(e.name,t.name)}isDefinedOn(e){throw Jh("KeyIndex.isDefinedOn not expected to be called.")}indexedValueChanged(e,t){return!1}minPost(){return TI.MIN}maxPost(){return new TI(Sb,kI)}makePost(e,t){return Xh("string"==typeof e,"KeyIndex indexValue must always be a string."),new TI(e,kI)}toString(){return".key"}}const CI=new SI;class AI{constructor(e,t,n,r,i=null){this.isReverse_=r,this.resultGenerator_=i,this.nodeStack_=[];let s=1;for(;!e.isEmpty();)if(s=t?n(e.key,t):1,r&&(s*=-1),s<0)e=this.isReverse_?e.left:e.right;else{if(0===s){this.nodeStack_.push(e);break}this.nodeStack_.push(e),e=this.isReverse_?e.right:e.left}}getNext(){if(0===this.nodeStack_.length)return null;let e=this.nodeStack_.pop(),t;if(t=this.resultGenerator_?this.resultGenerator_(e.key,e.value):{key:e.key,value:e.value},this.isReverse_)for(e=e.left;!e.isEmpty();)this.nodeStack_.push(e),e=e.right;else for(e=e.right;!e.isEmpty();)this.nodeStack_.push(e),e=e.left;return t}hasNext(){return 0<this.nodeStack_.length}peek(){if(0===this.nodeStack_.length)return null;var e=this.nodeStack_[this.nodeStack_.length-1];return this.resultGenerator_?this.resultGenerator_(e.key,e.value):{key:e.key,value:e.value}}}class NI{constructor(e,t,n,r,i){this.key=e,this.value=t,this.color=null!=n?n:NI.RED,this.left=null!=r?r:RI.EMPTY_NODE,this.right=null!=i?i:RI.EMPTY_NODE}copy(e,t,n,r,i){return new NI(null!=e?e:this.key,null!=t?t:this.value,null!=n?n:this.color,null!=r?r:this.left,null!=i?i:this.right)}count(){return this.left.count()+1+this.right.count()}isEmpty(){return!1}inorderTraversal(e){return this.left.inorderTraversal(e)||!!e(this.key,this.value)||this.right.inorderTraversal(e)}reverseTraversal(e){return this.right.reverseTraversal(e)||e(this.key,this.value)||this.left.reverseTraversal(e)}min_(){return this.left.isEmpty()?this:this.left.min_()}minKey(){return this.min_().key}maxKey(){return this.right.isEmpty()?this.key:this.right.maxKey()}insert(e,t,n){let r=this;var i=n(e,r.key);return r=i<0?r.copy(null,null,null,r.left.insert(e,t,n),null):0===i?r.copy(null,t,null,null,null):r.copy(null,null,null,null,r.right.insert(e,t,n)),r.fixUp_()}removeMin_(){if(this.left.isEmpty())return RI.EMPTY_NODE;let e=this;return e.left.isRed_()||e.left.left.isRed_()||(e=e.moveRedLeft_()),e=e.copy(null,null,null,e.left.removeMin_(),null),e.fixUp_()}remove(e,t){let n,r;if(n=this,t(e,n.key)<0)n.left.isEmpty()||n.left.isRed_()||n.left.left.isRed_()||(n=n.moveRedLeft_()),n=n.copy(null,null,null,n.left.remove(e,t),null);else{if(n.left.isRed_()&&(n=n.rotateRight_()),n.right.isEmpty()||n.right.isRed_()||n.right.left.isRed_()||(n=n.moveRedRight_()),0===t(e,n.key)){if(n.right.isEmpty())return RI.EMPTY_NODE;r=n.right.min_(),n=n.copy(r.key,r.value,null,null,n.right.removeMin_())}n=n.copy(null,null,null,null,n.right.remove(e,t))}return n.fixUp_()}isRed_(){return this.color}fixUp_(){let e=this;return e.right.isRed_()&&!e.left.isRed_()&&(e=e.rotateLeft_()),e.left.isRed_()&&e.left.left.isRed_()&&(e=e.rotateRight_()),e.left.isRed_()&&e.right.isRed_()&&(e=e.colorFlip_()),e}moveRedLeft_(){let e=this.colorFlip_();return e.right.left.isRed_()&&(e=e.copy(null,null,null,null,e.right.rotateRight_()),e=e.rotateLeft_(),e=e.colorFlip_()),e}moveRedRight_(){let e=this.colorFlip_();return e.left.left.isRed_()&&(e=e.rotateRight_(),e=e.colorFlip_()),e}rotateLeft_(){var e=this.copy(null,null,NI.RED,null,this.right.left);return this.right.copy(null,null,this.color,e,null)}rotateRight_(){var e=this.copy(null,null,NI.RED,this.left.right,null);return this.left.copy(null,null,this.color,null,e)}colorFlip_(){var e=this.left.copy(null,null,!this.left.color,null,null),t=this.right.copy(null,null,!this.right.color,null,null);return this.copy(null,null,!this.color,e,t)}checkMaxDepth_(){var e=this.check_();return Math.pow(2,e)<=this.count()+1}check_(){if(this.isRed_()&&this.left.isRed_())throw new Error("Red node has red child("+this.key+","+this.value+")");if(this.right.isRed_())throw new Error("Right child of ("+this.key+","+this.value+") is red");var e=this.left.check_();if(e!==this.right.check_())throw new Error("Black depths differ");return e+(this.isRed_()?0:1)}}NI.RED=!0,NI.BLACK=!1;class RI{constructor(e,t=RI.EMPTY_NODE){this.comparator_=e,this.root_=t}insert(e,t){return new RI(this.comparator_,this.root_.insert(e,t,this.comparator_).copy(null,null,NI.BLACK,null,null))}remove(e){return new RI(this.comparator_,this.root_.remove(e,this.comparator_).copy(null,null,NI.BLACK,null,null))}get(e){var t;let n=this.root_;for(;!n.isEmpty();){if(0===(t=this.comparator_(e,n.key)))return n.value;t<0?n=n.left:0<t&&(n=n.right)}return null}getPredecessorKey(e){let t,n=this.root_,r=null;for(;!n.isEmpty();){if(0===(t=this.comparator_(e,n.key))){if(n.left.isEmpty())return r?r.key:null;for(n=n.left;!n.right.isEmpty();)n=n.right;return n.key}t<0?n=n.left:0<t&&(r=n,n=n.right)}throw new Error("Attempted to find predecessor key for a nonexistent key.  What gives?")}isEmpty(){return this.root_.isEmpty()}count(){return this.root_.count()}minKey(){return this.root_.minKey()}maxKey(){return this.root_.maxKey()}inorderTraversal(e){return this.root_.inorderTraversal(e)}reverseTraversal(e){return this.root_.reverseTraversal(e)}getIterator(e){return new AI(this.root_,null,this.comparator_,!1,e)}getIteratorFrom(e,t){return new AI(this.root_,e,this.comparator_,!1,t)}getReverseIteratorFrom(e,t){return new AI(this.root_,e,this.comparator_,!0,t)}getReverseIterator(e){return new AI(this.root_,null,this.comparator_,!0,e)}}function PI(e,t){return Cb(e.name,t.name)}function xI(e,t){return Cb(e,t)}RI.EMPTY_NODE=new class{copy(e,t,n,r,i){return this}insert(e,t,n){return new NI(e,t,null)}remove(e,t){return this}count(){return 0}isEmpty(){return!0}inorderTraversal(e){return!1}reverseTraversal(e){return!1}minKey(){return null}maxKey(){return null}check_(){return 0}isRed_(){return!1}};let OI;function DI(e){return"number"==typeof e?"number:"+Nb(e):"string:"+e}function LI(e){var t;e.isLeafNode()?(t=e.val(),Xh("string"==typeof t||"number"==typeof t||"object"==typeof t&&bd(t,".sv"),"Priority must be a string or number.")):Xh(e===OI||e.isEmpty(),"priority of unexpected type."),Xh(e===OI||e.getPriority().isEmpty(),"Priority nodes can't have a priority of their own.")}let MI;class FI{constructor(e,t=FI.__childrenNodeConstructor.EMPTY_NODE){this.value_=e,this.priorityNode_=t,this.lazyHash_=null,Xh(void 0!==this.value_&&null!==this.value_,"LeafNode shouldn't be created with null/undefined value."),LI(this.priorityNode_)}static set __childrenNodeConstructor(e){MI=e}static get __childrenNodeConstructor(){return MI}isLeafNode(){return!0}getPriority(){return this.priorityNode_}updatePriority(e){return new FI(this.value_,e)}getImmediateChild(e){return".priority"===e?this.priorityNode_:FI.__childrenNodeConstructor.EMPTY_NODE}getChild(e){return pI(e)?this:".priority"===oI(e)?this.priorityNode_:FI.__childrenNodeConstructor.EMPTY_NODE}hasChild(){return!1}getPredecessorChildName(e,t){return null}updateImmediateChild(e,t){return".priority"===e?this.updatePriority(t):t.isEmpty()&&".priority"!==e?this:FI.__childrenNodeConstructor.EMPTY_NODE.updateImmediateChild(e,t).updatePriority(this.priorityNode_)}updateChild(e,t){var n=oI(e);return null===n?t:t.isEmpty()&&".priority"!==n?this:(Xh(".priority"!==n||1===aI(e),".priority must be the last token in a path"),this.updateImmediateChild(n,FI.__childrenNodeConstructor.EMPTY_NODE.updateChild(cI(e),t)))}isEmpty(){return!1}numChildren(){return 0}forEachChild(e,t){return!1}val(e){return e&&!this.getPriority().isEmpty()?{".value":this.getValue(),".priority":this.getPriority().val()}:this.getValue()}hash(){if(null===this.lazyHash_){let e="";this.priorityNode_.isEmpty()||(e+="priority:"+DI(this.priorityNode_.val())+":");var t=typeof this.value_;e+=t+":",e+="number"==t?Nb(this.value_):this.value_,this.lazyHash_=sb(e)}return this.lazyHash_}getValue(){return this.value_}compareTo(e){return e===FI.__childrenNodeConstructor.EMPTY_NODE?1:e instanceof FI.__childrenNodeConstructor?-1:(Xh(e.isLeafNode(),"Unknown node type"),this.compareToLeafNode_(e))}compareToLeafNode_(e){var t=typeof e.value_,n=typeof this.value_,r=FI.VALUE_TYPE_ORDER.indexOf(t),i=FI.VALUE_TYPE_ORDER.indexOf(n);return Xh(0<=r,"Unknown leaf type: "+t),Xh(0<=i,"Unknown leaf type: "+n),r===i?"object"==n?0:this.value_<e.value_?-1:this.value_===e.value_?0:1:i-r}withIndex(){return this}isIndexed(){return!0}equals(e){return e===this||!!e.isLeafNode()&&(this.value_===e.value_&&this.priorityNode_.equals(e.priorityNode_))}}FI.VALUE_TYPE_ORDER=["object","boolean","number","string"];let UI,jI;const qI=new class extends EI{compare(e,t){const n=e.node.getPriority();var r=t.node.getPriority(),r=n.compareTo(r);return 0===r?Cb(e.name,t.name):r}isDefinedOn(e){return!e.getPriority().isEmpty()}indexedValueChanged(e,t){return!e.getPriority().equals(t.getPriority())}minPost(){return TI.MIN}maxPost(){return new TI(Sb,new FI("[PRIORITY-POST]",jI))}makePost(e,t){var n=UI(e);return new TI(t,new FI("[PRIORITY-POST]",n))}toString(){return".priority"}},VI=Math.log(2);class BI{constructor(e){var t;this.count=(t=e+1,parseInt(Math.log(t)/VI,10)),this.current_=this.count-1;var n,r=(n=this.count,parseInt(Array(n+1).join("1"),2));this.bits_=e+1&r}nextBitIsOne(){var e=!(this.bits_&1<<this.current_);return this.current_--,e}}function WI(c,e,l,t){c.sort(e);const u=function(e,t){var n=t-e;let r,i;if(0==n)return null;if(1==n)return r=c[e],i=l?l(r):r,new NI(i,r.node,NI.BLACK,null,null);var s=parseInt(n/2,10)+e,o=u(e,s),n=u(s+1,t);return r=c[s],i=l?l(r):r,new NI(i,r.node,NI.BLACK,o,n)};var n=function(e){let s=null,o=null,a=c.length;function t(e,t){var n=a-e,r=a;a-=e;var i=u(1+n,r),r=c[n],n=l?l(r):r;!function(e){if(s){s.left=e;s=e}else{o=e;s=e}}(new NI(n,r.node,t,null,i))}for(let i=0;i<e.count;++i){var n=e.nextBitIsOne(),r=Math.pow(2,e.count-(i+1));n?t(r,NI.BLACK):(t(r,NI.BLACK),t(r,NI.RED))}return o}(new BI(c.length));return new RI(t||e,n)}let zI;const KI={};class $I{constructor(e,t){this.indexes_=e,this.indexSet_=t}static get Default(){return Xh((KI,qI),"ChildrenNode.ts has not been loaded"),zI=zI||new $I({".priority":KI},{".priority":qI}),zI}get(e){var t=Id(this.indexes_,e);if(!t)throw new Error("No index defined for "+e);return t instanceof RI?t:null}hasIndex(e){return bd(this.indexSet_,e.toString())}addIndex(e,t){Xh(e!==CI,"KeyIndex always exists and isn't meant to be added to the IndexMap.");const n=[];let r=!1;const i=t.getIterator(TI.Wrap);let s=i.getNext();for(;s;)r=r||e.isDefinedOn(s.node),n.push(s),s=i.getNext();let o;o=r?WI(n,e.getCompare()):KI;var a=e.toString();const c=Object.assign({},this.indexSet_);c[a]=e;const l=Object.assign({},this.indexes_);return l[a]=o,new $I(l,c)}addToIndexes(o,a){var e=Ed(this.indexes_,(t,e)=>{const n=Id(this.indexSet_,e);if(Xh(n,"Missing index implementation for "+e),t===KI){if(n.isDefinedOn(o.node)){const i=[],s=a.getIterator(TI.Wrap);let e=s.getNext();for(;e;)e.name!==o.name&&i.push(e),e=s.getNext();return i.push(o),WI(i,n.getCompare())}return KI}{var r=a.get(o.name);let e=t;return r&&(e=e.remove(new TI(o.name,r))),e.insert(o,o.node)}});return new $I(e,this.indexSet_)}removeFromIndexes(n,r){var e=Ed(this.indexes_,e=>{if(e===KI)return e;var t=r.get(n.name);return t?e.remove(new TI(n.name,t)):e});return new $I(e,this.indexSet_)}}let HI;class GI{constructor(e,t,n){this.children_=e,this.priorityNode_=t,this.indexMap_=n,this.lazyHash_=null,this.priorityNode_&&LI(this.priorityNode_),this.children_.isEmpty()&&Xh(!this.priorityNode_||this.priorityNode_.isEmpty(),"An empty node cannot have a priority")}static get EMPTY_NODE(){return HI=HI||new GI(new RI(xI),null,$I.Default)}isLeafNode(){return!1}getPriority(){return this.priorityNode_||HI}updatePriority(e){return this.children_.isEmpty()?this:new GI(this.children_,e,this.indexMap_)}getImmediateChild(e){if(".priority"===e)return this.getPriority();var t=this.children_.get(e);return null===t?HI:t}getChild(e){var t=oI(e);return null===t?this:this.getImmediateChild(t).getChild(cI(e))}hasChild(e){return null!==this.children_.get(e)}updateImmediateChild(n,r){if(Xh(r,"We should always be passing snapshot nodes"),".priority"===n)return this.updatePriority(r);{var i=new TI(n,r);let e,t;t=r.isEmpty()?(e=this.children_.remove(n),this.indexMap_.removeFromIndexes(i,this.children_)):(e=this.children_.insert(n,r),this.indexMap_.addToIndexes(i,this.children_));i=e.isEmpty()?HI:this.priorityNode_;return new GI(e,i,t)}}updateChild(e,t){var n=oI(e);if(null===n)return t;Xh(".priority"!==oI(e)||1===aI(e),".priority must be the last token in a path");var r=this.getImmediateChild(n).updateChild(cI(e),t);return this.updateImmediateChild(n,r)}isEmpty(){return this.children_.isEmpty()}numChildren(){return this.children_.count()}val(n){if(this.isEmpty())return null;const r={};let i=0,s=0,o=!0;if(this.forEachChild(qI,(e,t)=>{r[e]=t.val(n),i++,o&&GI.INTEGER_REGEXP_.test(e)?s=Math.max(s,Number(e)):o=!1}),!n&&o&&s<2*i){const e=[];for(const t in r)e[t]=r[t];return e}return n&&!this.getPriority().isEmpty()&&(r[".priority"]=this.getPriority().val()),r}hash(){if(null===this.lazyHash_){let r="";this.getPriority().isEmpty()||(r+="priority:"+DI(this.getPriority().val())+":"),this.forEachChild(qI,(e,t)=>{var n=t.hash();""!==n&&(r+=":"+e+":"+n)}),this.lazyHash_=""===r?"":sb(r)}return this.lazyHash_}getPredecessorChildName(e,t,n){const r=this.resolveIndex_(n);if(r){var i=r.getPredecessorKey(new TI(e,t));return i?i.name:null}return this.children_.getPredecessorKey(e)}getFirstChildName(e){const t=this.resolveIndex_(e);if(t){var n=t.minKey();return n&&n.name}return this.children_.minKey()}getFirstChild(e){var t=this.getFirstChildName(e);return t?new TI(t,this.children_.get(t)):null}getLastChildName(e){const t=this.resolveIndex_(e);if(t){var n=t.maxKey();return n&&n.name}return this.children_.maxKey()}getLastChild(e){var t=this.getLastChildName(e);return t?new TI(t,this.children_.get(t)):null}forEachChild(e,t){const n=this.resolveIndex_(e);return n?n.inorderTraversal(e=>t(e.name,e.node)):this.children_.inorderTraversal(t)}getIterator(e){return this.getIteratorFrom(e.minPost(),e)}getIteratorFrom(t,n){const e=this.resolveIndex_(n);if(e)return e.getIteratorFrom(t,e=>e);{const r=this.children_.getIteratorFrom(t.name,TI.Wrap);let e=r.peek();for(;null!=e&&n.compare(e,t)<0;)r.getNext(),e=r.peek();return r}}getReverseIterator(e){return this.getReverseIteratorFrom(e.maxPost(),e)}getReverseIteratorFrom(t,n){const e=this.resolveIndex_(n);if(e)return e.getReverseIteratorFrom(t,e=>e);{const r=this.children_.getReverseIteratorFrom(t.name,TI.Wrap);let e=r.peek();for(;null!=e&&0<n.compare(e,t);)r.getNext(),e=r.peek();return r}}compareTo(e){return this.isEmpty()?e.isEmpty()?0:-1:e.isLeafNode()||e.isEmpty()?1:e===YI?-1:0}withIndex(e){if(e===CI||this.indexMap_.hasIndex(e))return this;var t=this.indexMap_.addIndex(e,this.children_);return new GI(this.children_,this.priorityNode_,t)}isIndexed(e){return e===CI||this.indexMap_.hasIndex(e)}equals(e){if(e===this)return!0;if(e.isLeafNode())return!1;{const n=e;if(this.getPriority().equals(n.getPriority())){if(this.children_.count()!==n.children_.count())return!1;{const r=this.getIterator(qI),i=n.getIterator(qI);let e=r.getNext(),t=i.getNext();for(;e&&t;){if(e.name!==t.name||!e.node.equals(t.node))return!1;e=r.getNext(),t=i.getNext()}return null===e&&null===t}}return!1}}resolveIndex_(e){return e===CI?null:this.indexMap_.get(e.toString())}}GI.INTEGER_REGEXP_=/^(0|[1-9]\d*)$/;class QI extends GI{constructor(){super(new RI(xI),GI.EMPTY_NODE,$I.Default)}compareTo(e){return e===this?0:1}equals(e){return e===this}getPriority(){return this}getImmediateChild(e){return GI.EMPTY_NODE}isEmpty(){return!1}}const YI=new QI;Object.defineProperties(TI,{MIN:{value:new TI(kb,GI.EMPTY_NODE)},MAX:{value:new TI(Sb,YI)}}),SI.__EMPTY_NODE=GI.EMPTY_NODE,FI.__childrenNodeConstructor=GI,Zw=YI,OI=Zw,eb=YI,jI=eb;const XI=!0;function JI(i,e=null){if(null===i)return GI.EMPTY_NODE;if("object"==typeof i&&".priority"in i&&(e=i[".priority"]),Xh(null===e||"string"==typeof e||"number"==typeof e||"object"==typeof e&&".sv"in e,"Invalid priority type found: "+typeof e),"object"!=typeof(i="object"==typeof i&&".value"in i&&null!==i[".value"]?i[".value"]:i)||".sv"in i){var t=i;return new FI(t,JI(e))}if(i instanceof Array||!XI){let r=GI.EMPTY_NODE;return Ab(i,(e,t)=>{if(bd(i,e)&&"."!==e.substring(0,1)){const n=JI(t);!n.isLeafNode()&&n.isEmpty()||(r=r.updateImmediateChild(e,n))}}),r.updatePriority(JI(e))}{const s=[];let r=!1;if(Ab(i,(e,t)=>{if("."!==e.substring(0,1)){const n=JI(t);n.isEmpty()||(r=r||!n.getPriority().isEmpty(),s.push(new TI(e,n)))}}),0===s.length)return GI.EMPTY_NODE;var n=WI(s,PI,e=>e.name,xI);if(r){t=WI(s,qI.getCompare());return new GI(n,JI(e),new $I({".priority":t},{".priority":qI}))}return new GI(n,JI(e),$I.Default)}}UI=JI;class ZI extends EI{constructor(e){super(),this.indexPath_=e,Xh(!pI(e)&&".priority"!==oI(e),"Can't create PathIndex with empty path or .priority key")}extractChild(e){return e.getChild(this.indexPath_)}isDefinedOn(e){return!e.getChild(this.indexPath_).isEmpty()}compare(e,t){const n=this.extractChild(e.node);var r=this.extractChild(t.node),r=n.compareTo(r);return 0===r?Cb(e.name,t.name):r}makePost(e,t){var n=JI(e),n=GI.EMPTY_NODE.updateChild(this.indexPath_,n);return new TI(t,n)}maxPost(){var e=GI.EMPTY_NODE.updateChild(this.indexPath_,YI);return new TI(Sb,e)}toString(){return uI(this.indexPath_,0).join("/")}}function eT(e){if(e===""+Ob)return iT;var t=Db(e);if(null!=t)return""+(t+1);const n=new Array(e.length);for(let i=0;i<n.length;i++)n[i]=e.charAt(i);if(n.length<oT)return n.push(iT),n.join("");let r=n.length-1;for(;0<=r&&n[r]===sT;)r--;return-1===r?Sb:(t=n[r],t=rT.charAt(rT.indexOf(t)+1),n[r]=t,n.slice(0,r+1).join(""))}function tT(e){if(e===""+xb)return kb;var t=Db(e);if(null!=t)return""+(t-1);const n=new Array(e.length);for(let r=0;r<n.length;r++)n[r]=e.charAt(r);return n[n.length-1]===iT?1===n.length?""+Ob:(delete n[n.length-1],n.join("")):(n[n.length-1]=rT.charAt(rT.indexOf(n[n.length-1])-1),n.join("")+sT.repeat(oT-n.length))}const nT=new class extends EI{compare(e,t){var n=e.node.compareTo(t.node);return 0===n?Cb(e.name,t.name):n}isDefinedOn(e){return!0}indexedValueChanged(e,t){return!e.equals(t)}minPost(){return TI.MIN}maxPost(){return TI.MAX}makePost(e,t){var n=JI(e);return new TI(t,n)}toString(){return".value"}},rT="-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz",iT="-",sT="z",oT=786,aT=function(){let s=0;const o=[];return function(e){var t=e===s;s=e;let n;const r=new Array(8);for(n=7;0<=n;n--)r[n]=rT.charAt(e%64),e=Math.floor(e/64);Xh(0===e,"Cannot push at time == 0");let i=r.join("");if(t){for(n=11;0<=n&&63===o[n];n--)o[n]=0;o[n]++}else for(n=0;n<12;n++)o[n]=Math.floor(64*Math.random());for(n=0;n<12;n++)i+=rT.charAt(o[n]);return Xh(20===i.length,"nextPushId: Length should be 20."),i}}();function cT(e){return{type:"value",snapshotNode:e}}function lT(e,t){return{type:"child_added",snapshotNode:t,childName:e}}function uT(e,t){return{type:"child_removed",snapshotNode:t,childName:e}}function hT(e,t,n){return{type:"child_changed",snapshotNode:t,childName:e,oldSnap:n}}class dT{constructor(e){this.index_=e}updateChild(e,t,n,r,i,s){Xh(e.isIndexed(this.index_),"A node must be indexed if only a child is updated");const o=e.getImmediateChild(t);return o.getChild(r).equals(n.getChild(r))&&o.isEmpty()===n.isEmpty()?e:(null!=s&&(n.isEmpty()?e.hasChild(t)?s.trackChildChange(uT(t,o)):Xh(e.isLeafNode(),"A child remove without an old child only makes sense on a leaf node"):o.isEmpty()?s.trackChildChange(lT(t,n)):s.trackChildChange(hT(t,n,o))),e.isLeafNode()&&n.isEmpty()?e:e.updateImmediateChild(t,n).withIndex(this.index_))}updateFullNode(r,n,i){return null!=i&&(r.isLeafNode()||r.forEachChild(qI,(e,t)=>{n.hasChild(e)||i.trackChildChange(uT(e,t))}),n.isLeafNode()||n.forEachChild(qI,(e,t)=>{if(r.hasChild(e)){const n=r.getImmediateChild(e);n.equals(t)||i.trackChildChange(hT(e,t,n))}else i.trackChildChange(lT(e,t))})),n.withIndex(this.index_)}updatePriority(e,t){return e.isEmpty()?GI.EMPTY_NODE:e.updatePriority(t)}filtersNodes(){return!1}getIndexedFilter(){return this}getIndex(){return this.index_}}class pT{constructor(e){this.indexedFilter_=new dT(e.getIndex()),this.index_=e.getIndex(),this.startPost_=pT.getStartPost_(e),this.endPost_=pT.getEndPost_(e)}getStartPost(){return this.startPost_}getEndPost(){return this.endPost_}matches(e){return this.index_.compare(this.getStartPost(),e)<=0&&this.index_.compare(e,this.getEndPost())<=0}updateChild(e,t,n,r,i,s){return this.matches(new TI(t,n))||(n=GI.EMPTY_NODE),this.indexedFilter_.updateChild(e,t,n,r,i,s)}updateFullNode(e,t,n){let r=(t=t.isLeafNode()?GI.EMPTY_NODE:t).withIndex(this.index_);r=r.updatePriority(GI.EMPTY_NODE);const i=this;return t.forEachChild(qI,(e,t)=>{i.matches(new TI(e,t))||(r=r.updateImmediateChild(e,GI.EMPTY_NODE))}),this.indexedFilter_.updateFullNode(e,r,n)}updatePriority(e,t){return e}filtersNodes(){return!0}getIndexedFilter(){return this.indexedFilter_}getIndex(){return this.index_}static getStartPost_(e){if(e.hasStart()){var t=e.getIndexStartName();return e.getIndex().makePost(e.getIndexStartValue(),t)}return e.getIndex().minPost()}static getEndPost_(e){if(e.hasEnd()){var t=e.getIndexEndName();return e.getIndex().makePost(e.getIndexEndValue(),t)}return e.getIndex().maxPost()}}class fT{constructor(e){this.rangedFilter_=new pT(e),this.index_=e.getIndex(),this.limit_=e.getLimit(),this.reverse_=!e.isViewFromLeft()}updateChild(e,t,n,r,i,s){return this.rangedFilter_.matches(new TI(t,n))||(n=GI.EMPTY_NODE),e.getImmediateChild(t).equals(n)?e:e.numChildren()<this.limit_?this.rangedFilter_.getIndexedFilter().updateChild(e,t,n,r,i,s):this.fullLimitUpdateChild_(e,t,n,i,s)}updateFullNode(e,o,t){let a;if(o.isLeafNode()||o.isEmpty())a=GI.EMPTY_NODE.withIndex(this.index_);else if(2*this.limit_<o.numChildren()&&o.isIndexed(this.index_)){a=GI.EMPTY_NODE.withIndex(this.index_);let t;t=this.reverse_?o.getReverseIteratorFrom(this.rangedFilter_.getEndPost(),this.index_):o.getIteratorFrom(this.rangedFilter_.getStartPost(),this.index_);let n=0;for(;t.hasNext()&&n<this.limit_;){var r=t.getNext();let e;if(e=this.reverse_?this.index_.compare(this.rangedFilter_.getStartPost(),r)<=0:this.index_.compare(r,this.rangedFilter_.getEndPost())<=0,!e)break;a=a.updateImmediateChild(r.name,r.node),n++}}else{a=o.withIndex(this.index_),a=a.updatePriority(GI.EMPTY_NODE);let e,t,n,r;if(this.reverse_){r=a.getReverseIterator(this.index_),e=this.rangedFilter_.getEndPost(),t=this.rangedFilter_.getStartPost();const l=this.index_.getCompare();n=(e,t)=>l(t,e)}else r=a.getIterator(this.index_),e=this.rangedFilter_.getStartPost(),t=this.rangedFilter_.getEndPost(),n=this.index_.getCompare();let i=0,s=!1;for(;r.hasNext();){var c=r.getNext();!s&&n(e,c)<=0&&(s=!0),s&&i<this.limit_&&n(c,t)<=0?i++:a=a.updateImmediateChild(c.name,GI.EMPTY_NODE)}}return this.rangedFilter_.getIndexedFilter().updateFullNode(e,a,t)}updatePriority(e,t){return e}filtersNodes(){return!0}getIndexedFilter(){return this.rangedFilter_.getIndexedFilter()}getIndex(){return this.index_}fullLimitUpdateChild_(e,t,n,r,i){let s;if(this.reverse_){const d=this.index_.getCompare();s=(e,t)=>d(t,e)}else s=this.index_.getCompare();const o=e;Xh(o.numChildren()===this.limit_,"");var a=new TI(t,n),c=this.reverse_?o.getFirstChild(this.index_):o.getLastChild(this.index_),l=this.rangedFilter_.matches(a);if(o.hasChild(t)){var u=o.getImmediateChild(t);let e=r.getChildAfterChild(this.index_,c,this.reverse_);for(;null!=e&&(e.name===t||o.hasChild(e.name));)e=r.getChildAfterChild(this.index_,e,this.reverse_);var h=null==e?1:s(e,a);if(l&&!n.isEmpty()&&0<=h)return null!=i&&i.trackChildChange(hT(t,n,u)),o.updateImmediateChild(t,n);{null!=i&&i.trackChildChange(uT(t,u));const p=o.updateImmediateChild(t,GI.EMPTY_NODE);return null!=e&&this.rangedFilter_.matches(e)?(null!=i&&i.trackChildChange(lT(e.name,e.node)),p.updateImmediateChild(e.name,e.node)):p}}return!n.isEmpty()&&l&&0<=s(c,a)?(null!=i&&(i.trackChildChange(uT(c.name,c.node)),i.trackChildChange(lT(t,n))),o.updateImmediateChild(t,n).updateImmediateChild(c.name,GI.EMPTY_NODE)):e}}class gT{constructor(){this.limitSet_=!1,this.startSet_=!1,this.startNameSet_=!1,this.startAfterSet_=!1,this.endSet_=!1,this.endNameSet_=!1,this.endBeforeSet_=!1,this.limit_=0,this.viewFrom_="",this.indexStartValue_=null,this.indexStartName_="",this.indexEndValue_=null,this.indexEndName_="",this.index_=qI}hasStart(){return this.startSet_}hasStartAfter(){return this.startAfterSet_}hasEndBefore(){return this.endBeforeSet_}isViewFromLeft(){return""===this.viewFrom_?this.startSet_:"l"===this.viewFrom_}getIndexStartValue(){return Xh(this.startSet_,"Only valid if start has been set"),this.indexStartValue_}getIndexStartName(){return Xh(this.startSet_,"Only valid if start has been set"),this.startNameSet_?this.indexStartName_:kb}hasEnd(){return this.endSet_}getIndexEndValue(){return Xh(this.endSet_,"Only valid if end has been set"),this.indexEndValue_}getIndexEndName(){return Xh(this.endSet_,"Only valid if end has been set"),this.endNameSet_?this.indexEndName_:Sb}hasLimit(){return this.limitSet_}hasAnchoredLimit(){return this.limitSet_&&""!==this.viewFrom_}getLimit(){return Xh(this.limitSet_,"Only valid if limit has been set"),this.limit_}getIndex(){return this.index_}loadsAllData(){return!(this.startSet_||this.endSet_||this.limitSet_)}isDefault(){return this.loadsAllData()&&this.index_===qI}copy(){const e=new gT;return e.limitSet_=this.limitSet_,e.limit_=this.limit_,e.startSet_=this.startSet_,e.indexStartValue_=this.indexStartValue_,e.startNameSet_=this.startNameSet_,e.indexStartName_=this.indexStartName_,e.endSet_=this.endSet_,e.indexEndValue_=this.indexEndValue_,e.endNameSet_=this.endNameSet_,e.indexEndName_=this.indexEndName_,e.index_=this.index_,e.viewFrom_=this.viewFrom_,e}}function mT(e,t,n){const r=e.copy();return r.startSet_=!0,void 0===t&&(t=null),r.indexStartValue_=t,null!=n?(r.startNameSet_=!0,r.indexStartName_=n):(r.startNameSet_=!1,r.indexStartName_=""),r}function vT(e,t,n){const r=e.copy();return r.endSet_=!0,void 0===t&&(t=null),r.indexEndValue_=t,void 0!==n?(r.endNameSet_=!0,r.indexEndName_=n):(r.endNameSet_=!1,r.indexEndName_=""),r}function yT(e,t){const n=e.copy();return n.index_=t,n}function _T(e){const t={};if(e.isDefault())return t;let n;return n=e.index_===qI?"$priority":e.index_===nT?"$value":e.index_===CI?"$key":(Xh(e.index_ instanceof ZI,"Unrecognized index type!"),e.index_.toString()),t.orderBy=_d(n),e.startSet_&&(t.startAt=_d(e.indexStartValue_),e.startNameSet_&&(t.startAt+=","+_d(e.indexStartName_))),e.endSet_&&(t.endAt=_d(e.indexEndValue_),e.endNameSet_&&(t.endAt+=","+_d(e.indexEndName_))),e.limitSet_&&(e.isViewFromLeft()?t.limitToFirst=e.limit_:t.limitToLast=e.limit_),t}function wT(t){const n={};if(t.startSet_&&(n.sp=t.indexStartValue_,t.startNameSet_&&(n.sn=t.indexStartName_)),t.endSet_&&(n.ep=t.indexEndValue_,t.endNameSet_&&(n.en=t.indexEndName_)),t.limitSet_){n.l=t.limit_;let e=t.viewFrom_;""===e&&(e=t.isViewFromLeft()?"l":"r"),n.vf=e}return t.index_!==qI&&(n.i=t.index_.toString()),n}class bT extends tI{constructor(e,t,n,r){super(),this.repoInfo_=e,this.onDataUpdate_=t,this.authTokenProvider_=n,this.appCheckTokenProvider_=r,this.log_=pb("p:rest:"),this.listens_={}}reportStats(e){throw new Error("Method not implemented.")}static getListenId_(e,t){return void 0!==t?"tag$"+t:(Xh(e._queryParams.isDefault(),"should have a tag if it's not a default query."),e._path.toString())}listen(e,t,r,i){const s=e._path.toString();this.log_("Listen called for "+s+" "+e._queryIdentifier);const o=bT.getListenId_(e,r),a={};this.listens_[o]=a;var n=_T(e._queryParams);this.restRequest_(s+".json",n,(t,e)=>{let n=e;if(null===(t=404===t?n=null:t)&&this.onDataUpdate_(s,n,!1,r),Id(this.listens_,o)===a){let e;e=t?401===t?"permission_denied":"rest_error:"+t:"ok",i(e,null)}})}unlisten(e,t){var n=bT.getListenId_(e,t);delete this.listens_[n]}get(e){var t=_T(e._queryParams);const r=e._path.toString(),i=new rd;return this.restRequest_(r+".json",t,(e,t)=>{let n=t;null===(e=404===e?n=null:e)?(this.onDataUpdate_(r,n,!1,null),i.resolve(n)):i.reject(new Error(n))}),i.promise}refreshAuthToken(e){}restRequest_(i,s={},o){return s.format="export",Promise.all([this.authTokenProvider_.getToken(!1),this.appCheckTokenProvider_.getToken(!1)]).then(([e,t])=>{e&&e.accessToken&&(s.auth=e.accessToken),t&&t.token&&(s.ac=t.token);const n=(this.repoInfo_.secure?"https://":"http://")+this.repoInfo_.host+i+"?ns="+this.repoInfo_.namespace+Cd(s);this.log_("Sending REST request for "+n);const r=new XMLHttpRequest;r.onreadystatechange=()=>{if(o&&4===r.readyState){this.log_("REST Response for "+n+" received. status:",r.status,"response:",r.responseText);let e=null;if(200<=r.status&&r.status<300){try{e=yd(r.responseText)}catch(e){Ib("Failed to parse JSON response for "+n+": "+r.responseText)}o(null,e)}else 401!==r.status&&404!==r.status&&Ib("Got unsuccessful REST response for "+n+" Status: "+r.status),o(r.status);o=null}},r.open("GET",n,!0),r.send()})}}class IT{constructor(){this.rootNode_=GI.EMPTY_NODE}getNode(e){return this.rootNode_.getChild(e)}updateSnapshot(e,t){this.rootNode_=this.rootNode_.updateChild(e,t)}}function TT(){return{value:null,children:new Map}}function ET(e,t,n){var r;pI(t)?(e.value=n,e.children.clear()):null!==e.value?e.value=e.value.updateChild(t,n):(r=oI(t),e.children.has(r)||e.children.set(r,TT()),ET(e.children.get(r),t=cI(t),n))}function kT(e,n,r){var i;null!==e.value?r(n,e.value):(i=(e,t)=>{kT(t,new iI(n.toString()+"/"+e),r)},e.children.forEach((e,t)=>{i(t,e)}))}class ST{constructor(e){this.collection_=e,this.last_=null}get(){var e=this.collection_.get();const n=Object.assign({},e);return this.last_&&Ab(this.last_,(e,t)=>{n[e]=n[e]-t}),this.last_=e,n}}class CT{constructor(e,t){this.server_=t,this.statsToReport_={},this.statsListener_=new ST(e);var n=1e4+2e4*Math.random();Rb(this.reportStats_.bind(this),Math.floor(n))}reportStats_(){var e=this.statsListener_.get();const n={};let r=!1;Ab(e,(e,t)=>{0<t&&bd(this.statsToReport_,e)&&(n[e]=t,r=!0)}),r&&this.server_.reportStats(n),Rb(this.reportStats_.bind(this),Math.floor(2*Math.random()*3e5))}}function AT(){return{fromUser:!0,fromServer:!1,queryId:null,tagged:!1}}function NT(){return{fromUser:!1,fromServer:!0,queryId:null,tagged:!1}}function RT(e){return{fromUser:!1,fromServer:!0,queryId:e,tagged:!0}}($=tb=tb||{})[$.OVERWRITE=0]="OVERWRITE",$[$.MERGE=1]="MERGE",$[$.ACK_USER_WRITE=2]="ACK_USER_WRITE",$[$.LISTEN_COMPLETE=3]="LISTEN_COMPLETE";class PT{constructor(e,t,n){this.path=e,this.affectedTree=t,this.revert=n,this.type=tb.ACK_USER_WRITE,this.source=AT()}operationForChild(e){if(pI(this.path)){if(null!=this.affectedTree.value)return Xh(this.affectedTree.children.isEmpty(),"affectedTree should not have overlapping affected paths."),this;var t=this.affectedTree.subtree(new iI(e));return new PT(sI(),t,this.revert)}return Xh(oI(this.path)===e,"operationForChild called for unrelated child."),new PT(cI(this.path),this.affectedTree,this.revert)}}class xT{constructor(e,t){this.source=e,this.path=t,this.type=tb.LISTEN_COMPLETE}operationForChild(e){return pI(this.path)?new xT(this.source,sI()):new xT(this.source,cI(this.path))}}class OT{constructor(e,t,n){this.source=e,this.path=t,this.snap=n,this.type=tb.OVERWRITE}operationForChild(e){return pI(this.path)?new OT(this.source,sI(),this.snap.getImmediateChild(e)):new OT(this.source,cI(this.path),this.snap)}}class DT{constructor(e,t,n){this.source=e,this.path=t,this.children=n,this.type=tb.MERGE}operationForChild(e){if(pI(this.path)){const t=this.children.subtree(new iI(e));return t.isEmpty()?null:t.value?new OT(this.source,sI(),t.value):new DT(this.source,sI(),t)}return Xh(oI(this.path)===e,"Can't get a merge for a child not on the path of the operation"),new DT(this.source,cI(this.path),this.children)}toString(){return"Operation("+this.path+": "+this.source.toString()+" merge: "+this.children.toString()+")"}}class LT{constructor(e,t,n){this.node_=e,this.fullyInitialized_=t,this.filtered_=n}isFullyInitialized(){return this.fullyInitialized_}isFiltered(){return this.filtered_}isCompleteForPath(e){if(pI(e))return this.isFullyInitialized()&&!this.filtered_;var t=oI(e);return this.isCompleteForChild(t)}isCompleteForChild(e){return this.isFullyInitialized()&&!this.filtered_||this.node_.hasChild(e)}getNode(){return this.node_}}class MT{constructor(e){this.query_=e,this.index_=this.query_._queryParams.getIndex()}}function FT(n,e,t,r){var i=[];const s=[];return e.forEach(e=>{var t;"child_changed"===e.type&&n.index_.indexedValueChanged(e.oldSnap,e.snapshotNode)&&s.push((t=e.childName,{type:"child_moved",snapshotNode:e.snapshotNode,childName:t}))}),UT(n,i,"child_removed",e,r,t),UT(n,i,"child_added",e,r,t),UT(n,i,"child_moved",s,r,t),UT(n,i,"child_changed",e,r,t),UT(n,i,"value",e,r,t),i}function UT(s,o,t,e,a,c){const n=e.filter(e=>e.type===t);n.sort((e,t)=>function(e,t,n){if(null==t.childName||null==n.childName)throw Jh("Should only compare child_ events.");var r=new TI(t.childName,t.snapshotNode),i=new TI(n.childName,n.snapshotNode);return e.index_.compare(r,i)}(s,e,t)),n.forEach(t=>{const n=(e=s,i=c,"value"===(r=t).type||"child_removed"===r.type||(r.prevName=i.getPredecessorChildName(r.childName,r.snapshotNode,e.index_)),r);var e,r,i;a.forEach(e=>{e.respondsTo(t.type)&&o.push(e.createEvent(n,s.query_))})})}function jT(e,t){return{eventCache:e,serverCache:t}}function qT(e,t,n,r){return jT(new LT(t,n,r),e.serverCache)}function VT(e,t,n,r){return jT(e.eventCache,new LT(t,n,r))}function BT(e){return e.eventCache.isFullyInitialized()?e.eventCache.getNode():null}function WT(e){return e.serverCache.isFullyInitialized()?e.serverCache.getNode():null}let zT;class KT{constructor(e,t=(zT=zT||new RI(gb),zT)){this.value=e,this.children=t}static fromObject(e){let n=new KT(null);return Ab(e,(e,t)=>{n=n.set(new iI(e),t)}),n}isEmpty(){return null===this.value&&this.children.isEmpty()}findRootMostMatchingPathAndValue(e,t){if(null!=this.value&&t(this.value))return{path:sI(),value:this.value};if(pI(e))return null;{var n=oI(e);const i=this.children.get(n);if(null===i)return null;var r=i.findRootMostMatchingPathAndValue(cI(e),t);return null==r?null:{path:dI(new iI(n),r.path),value:r.value}}}findRootMostValueAndPath(e){return this.findRootMostMatchingPathAndValue(e,()=>!0)}subtree(e){if(pI(e))return this;{var t=oI(e);const n=this.children.get(t);return null!==n?n.subtree(cI(e)):new KT(null)}}set(e,t){if(pI(e))return new KT(t,this.children);{var n=oI(e);const i=this.children.get(n)||new KT(null);var r=i.set(cI(e),t),r=this.children.insert(n,r);return new KT(this.value,r)}}remove(t){if(pI(t))return this.children.isEmpty()?new KT(null):new KT(null,this.children);{var n=oI(t);const r=this.children.get(n);if(r){const i=r.remove(cI(t));let e;return e=i.isEmpty()?this.children.remove(n):this.children.insert(n,i),null===this.value&&e.isEmpty()?new KT(null):new KT(this.value,e)}return this}}get(e){if(pI(e))return this.value;{var t=oI(e);const n=this.children.get(t);return n?n.get(cI(e)):null}}setTree(t,n){if(pI(t))return n;{var r=oI(t);const i=this.children.get(r)||new KT(null),s=i.setTree(cI(t),n);let e;return e=s.isEmpty()?this.children.remove(r):this.children.insert(r,s),new KT(this.value,e)}}fold(e){return this.fold_(sI(),e)}fold_(n,r){const i={};return this.children.inorderTraversal((e,t)=>{i[e]=t.fold_(dI(n,e),r)}),r(n,this.value,i)}findOnPath(e,t){return this.findOnPath_(e,sI(),t)}findOnPath_(e,t,n){var r=!!this.value&&n(t,this.value);if(r)return r;if(pI(e))return null;{r=oI(e);const i=this.children.get(r);return i?i.findOnPath_(cI(e),dI(t,r),n):null}}foreachOnPath(e,t){return this.foreachOnPath_(e,sI(),t)}foreachOnPath_(e,t,n){if(pI(e))return this;{this.value&&n(t,this.value);var r=oI(e);const i=this.children.get(r);return i?i.foreachOnPath_(cI(e),dI(t,r),n):new KT(null)}}foreach(e){this.foreach_(sI(),e)}foreach_(n,r){this.children.inorderTraversal((e,t)=>{t.foreach_(dI(n,e),r)}),this.value&&r(n,this.value)}foreachChild(n){this.children.inorderTraversal((e,t)=>{t.value&&n(e,t.value)})}}class $T{constructor(e){this.writeTree_=e}static empty(){return new $T(new KT(null))}}function HT(t,n,r){if(pI(n))return new $T(new KT(r));var i=t.writeTree_.findRootMostValueAndPath(n);if(null!=i){var s=i.path;let e=i.value;i=fI(s,n);return e=e.updateChild(i,r),new $T(t.writeTree_.set(s,e))}s=new KT(r),s=t.writeTree_.setTree(n,s);return new $T(s)}function GT(e,n,t){let r=e;return Ab(t,(e,t)=>{r=HT(r,dI(n,e),t)}),r}function QT(e,t){if(pI(t))return $T.empty();var n=e.writeTree_.setTree(t,new KT(null));return new $T(n)}function YT(e,t){return null!=XT(e,t)}function XT(e,t){var n=e.writeTree_.findRootMostValueAndPath(t);return null!=n?e.writeTree_.get(n.path).getChild(fI(n.path,t)):null}function JT(e){const n=[],t=e.writeTree_.value;return null!=t?t.isLeafNode()||t.forEachChild(qI,(e,t)=>{n.push(new TI(e,t))}):e.writeTree_.children.inorderTraversal((e,t)=>{null!=t.value&&n.push(new TI(e,t.value))}),n}function ZT(e,t){if(pI(t))return e;var n=XT(e,t);return null!=n?new $T(new KT(n)):new $T(e.writeTree_.subtree(t))}function e0(e){return e.writeTree_.isEmpty()}function t0(e,t){return function r(i,e,s){{if(null!=e.value)return s.updateChild(i,e.value);{let n=null;return e.children.inorderTraversal((e,t)=>{".priority"===e?(Xh(null!==t.value,"Priority writes must always be leaf nodes"),n=t.value):s=r(dI(i,e),t,s)}),s=!s.getChild(i).isEmpty()&&null!==n?s.updateChild(dI(i,".priority"),n):s}}}(sI(),e.writeTree_,t)}function n0(e,t){return f0(t,e)}function r0(t,n){var e,r=t.allWrites.findIndex(e=>e.writeId===n);Xh(0<=r,"removeWrite called with nonexistent writeId.");const i=t.allWrites[r];t.allWrites.splice(r,1);let s=i.visible,o=!1,a=t.allWrites.length-1;for(;s&&0<=a;){var c=t.allWrites[a];c.visible&&(a>=r&&function(e,t){{if(e.snap)return vI(e.path,t);for(const n in e.children)if(e.children.hasOwnProperty(n)&&vI(dI(e.path,n),t))return!0;return!1}}(c,i.path)?s=!1:vI(i.path,c.path)&&(o=!0)),a--}return!!s&&(o?((e=t).visibleWrites=s0(e.allWrites,i0,sI()),0<e.allWrites.length?e.lastWriteId=e.allWrites[e.allWrites.length-1].writeId:e.lastWriteId=-1):i.snap?t.visibleWrites=QT(t.visibleWrites,i.path):Ab(i.children,e=>{t.visibleWrites=QT(t.visibleWrites,dI(i.path,e))}),!0)}function i0(e){return e.visible}function s0(e,t,n){let r=$T.empty();for(let s=0;s<e.length;++s){const o=e[s];if(t(o)){var i=o.path;let e;if(o.snap)vI(n,i)?(e=fI(n,i),r=HT(r,e,o.snap)):vI(i,n)&&(e=fI(i,n),r=HT(r,sI(),o.snap.getChild(e)));else{if(!o.children)throw Jh("WriteRecord should have .snap or .children");if(vI(n,i))e=fI(n,i),r=GT(r,e,o.children);else if(vI(i,n))if(e=fI(i,n),pI(e))r=GT(r,sI(),o.children);else{const a=Id(o.children,oI(e));a&&(i=a.getChild(cI(e)),r=HT(r,sI(),i))}}}}return r}function o0(e,t,n,r,i){if(r||i){var s=ZT(e.visibleWrites,t);if(!i&&e0(s))return n;if(i||null!=n||YT(s,sI()))return t0(s0(e.allWrites,function(e){return(e.visible||i)&&(!r||!~r.indexOf(e.writeId))&&(vI(e.path,t)||vI(t,e.path))},t),n||GI.EMPTY_NODE);return null}s=XT(e.visibleWrites,t);if(null!=s)return s;s=ZT(e.visibleWrites,t);return e0(s)?n:null!=n||YT(s,sI())?t0(s,n||GI.EMPTY_NODE):null}function a0(e,t,n,r){return o0(e.writeTree,e.treePath,t,n,r)}function c0(e,t){return function(e,t,n){let r=GI.EMPTY_NODE;const i=XT(e.visibleWrites,t);if(i)return i.isLeafNode()||i.forEachChild(qI,(e,t)=>{r=r.updateImmediateChild(e,t)}),r;if(n){const s=ZT(e.visibleWrites,t);return n.forEachChild(qI,(e,t)=>{var n=t0(ZT(s,new iI(e)),t);r=r.updateImmediateChild(e,n)}),JT(s).forEach(e=>{r=r.updateImmediateChild(e.name,e.node)}),r}return JT(ZT(e.visibleWrites,t)).forEach(e=>{r=r.updateImmediateChild(e.name,e.node)}),r}(e.writeTree,e.treePath,t)}function l0(e,t,n,r){return function(e,t,n,r,i){Xh(r||i,"Either existingEventSnap or existingServerSnap must exist");var s=dI(t,n);return YT(e.visibleWrites,s)?null:e0(s=ZT(e.visibleWrites,s))?i.getChild(n):t0(s,i.getChild(n))}(e.writeTree,e.treePath,t,n,r)}function u0(e,t){return n=e.writeTree,t=dI(e.treePath,t),XT(n.visibleWrites,t);var n}function h0(e,t,n,r,i,s){return function(e,t,n,r,i,s,o){let a;var c=ZT(e.visibleWrites,t),l=XT(c,sI());if(null!=l)a=l;else{if(null==n)return[];a=t0(c,n)}if(a=a.withIndex(o),a.isEmpty()||a.isLeafNode())return[];{const u=[],h=o.getCompare(),d=s?a.getReverseIteratorFrom(r,o):a.getIteratorFrom(r,o);let e=d.getNext();for(;e&&u.length<i;)0!==h(e,r)&&u.push(e),e=d.getNext();return u}}(e.writeTree,e.treePath,t,n,r,i,s)}function d0(e,t,n){return r=e.writeTree,e=e.treePath,n=n,i=dI(e,t=t),null!=(s=XT(r.visibleWrites,i))?s:n.isCompleteForChild(t)?t0(ZT(r.visibleWrites,i),n.getNode().getImmediateChild(t)):null;var r,i,s}function p0(e,t){return f0(dI(e.treePath,t),e.writeTree)}function f0(e,t){return{treePath:e,writeTree:t}}class g0{constructor(){this.changeMap=new Map}trackChildChange(e){var t=e.type,n=e.childName;Xh("child_added"===t||"child_changed"===t||"child_removed"===t,"Only child changes supported for tracking"),Xh(".priority"!==n,"Only non-priority child changes can be tracked.");var r=this.changeMap.get(n);if(r){var i=r.type;if("child_added"===t&&"child_removed"===i)this.changeMap.set(n,hT(n,e.snapshotNode,r.snapshotNode));else if("child_removed"===t&&"child_added"===i)this.changeMap.delete(n);else if("child_removed"===t&&"child_changed"===i)this.changeMap.set(n,uT(n,r.oldSnap));else if("child_changed"===t&&"child_added"===i)this.changeMap.set(n,lT(n,e.snapshotNode));else{if("child_changed"!==t||"child_changed"!==i)throw Jh("Illegal combination of changes: "+e+" occurred after "+r);this.changeMap.set(n,hT(n,e.snapshotNode,r.oldSnap))}}else this.changeMap.set(n,e)}getChanges(){return Array.from(this.changeMap.values())}}const m0=new class{getCompleteChild(e){return null}getChildAfterChild(e,t,n){return null}};class v0{constructor(e,t,n=null){this.writes_=e,this.viewCache_=t,this.optCompleteServerCache_=n}getCompleteChild(e){const t=this.viewCache_.eventCache;if(t.isCompleteForChild(e))return t.getNode().getImmediateChild(e);var n=null!=this.optCompleteServerCache_?new LT(this.optCompleteServerCache_,!0,!1):this.viewCache_.serverCache;return d0(this.writes_,e,n)}getChildAfterChild(e,t,n){var r=null!=this.optCompleteServerCache_?this.optCompleteServerCache_:WT(this.viewCache_),r=h0(this.writes_,r,t,1,n,e);return 0===r.length?null:r[0]}}function y0(e,t,n,r,i){const s=new g0;let o,a;if(n.type===tb.OVERWRITE){var c=n;o=c.source.fromUser?b0(e,t,c.path,c.snap,r,i,s):(Xh(c.source.fromServer,"Unknown source."),a=c.source.tagged||t.serverCache.isFiltered()&&!pI(c.path),w0(e,t,c.path,c.snap,r,i,a,s))}else if(n.type===tb.MERGE){c=n;o=c.source.fromUser?function(r,i,s,e,o,a,c){let l=i;return e.foreach((e,t)=>{var n=dI(s,e);I0(i,oI(n))&&(l=b0(r,l,n,t,o,a,c))}),e.foreach((e,t)=>{var n=dI(s,e);I0(i,oI(n))||(l=b0(r,l,n,t,o,a,c))}),l}(e,t,c.path,c.children,r,i,s):(Xh(c.source.fromServer,"Unknown source."),a=c.source.tagged||t.serverCache.isFiltered(),E0(e,t,c.path,c.children,r,i,a,s))}else if(n.type===tb.ACK_USER_WRITE){var l=n;o=l.revert?function(n,r,i,s,e,o){let a;{if(null!=u0(s,i))return r;{var c=new v0(s,r,e);const u=r.eventCache.getNode();let t;if(pI(i)||".priority"===oI(i)){let e;e=r.serverCache.isFullyInitialized()?a0(s,WT(r)):(l=r.serverCache.getNode(),Xh(l instanceof GI,"serverChildren would be complete if leaf node"),c0(s,l)),e=e,t=n.filter.updateFullNode(u,e,o)}else{var l=oI(i);let e=d0(s,l,r.serverCache);null==e&&r.serverCache.isCompleteForChild(l)&&(e=u.getImmediateChild(l)),t=null!=e?n.filter.updateChild(u,l,e,cI(i),c,o):r.eventCache.getNode().hasChild(l)?n.filter.updateChild(u,l,GI.EMPTY_NODE,cI(i),c,o):u,t.isEmpty()&&r.serverCache.isFullyInitialized()&&(a=a0(s,WT(r)),a.isLeafNode()&&(t=n.filter.updateFullNode(t,a,o)))}return a=r.serverCache.isFullyInitialized()||null!=u0(s,sI()),qT(r,t,a,n.filter.filtersNodes())}}}(e,t,l.path,r,i,s):function(e,t,i,n,s,o,a){if(null!=u0(s,i))return t;const c=t.serverCache.isFiltered(),l=t.serverCache;{if(null!=n.value){if(pI(i)&&l.isFullyInitialized()||l.isCompleteForPath(i))return w0(e,t,i,l.getNode().getChild(i),s,o,c,a);if(pI(i)){let n=new KT(null);return l.getNode().forEachChild(CI,(e,t)=>{n=n.set(new iI(e),t)}),E0(e,t,i,n,s,o,c,a)}return t}{let r=new KT(null);return n.foreach((e,t)=>{var n=dI(i,e);l.isCompleteForPath(n)&&(r=r.set(e,l.getNode().getChild(n)))}),E0(e,t,i,r,s,o,c,a)}}}(e,t,l.path,l.affectedTree,r,i,s)}else{if(n.type!==tb.LISTEN_COMPLETE)throw Jh("Unknown operation type: "+n.type);o=function(e,t,n,r,i){const s=t.serverCache,o=VT(t,s.getNode(),s.isFullyInitialized()||pI(n),s.isFiltered());return _0(e,o,n,r,m0,i)}(e,t,n.path,r,s)}l=s.getChanges();return function(e,t,n){const r=t.eventCache;if(r.isFullyInitialized()){var i=r.getNode().isLeafNode()||r.getNode().isEmpty();const s=BT(e);(0<n.length||!e.eventCache.isFullyInitialized()||i&&!r.getNode().equals(s)||!r.getNode().getPriority().equals(s.getPriority()))&&n.push(cT(BT(t)))}}(t,o,l),{viewCache:o,changes:l}}function _0(r,i,s,o,a,c){const l=i.eventCache;if(null!=u0(o,s))return i;{let t,n;if(pI(s)){var e;Xh(i.serverCache.isFullyInitialized(),"If change path is empty, we must have complete server data"),t=i.serverCache.isFiltered()?(e=c0(o,(e=WT(i))instanceof GI?e:GI.EMPTY_NODE),r.filter.updateFullNode(i.eventCache.getNode(),e,c)):(u=a0(o,WT(i)),r.filter.updateFullNode(i.eventCache.getNode(),u,c))}else{var u=oI(s);if(".priority"===u){Xh(1===aI(s),"Can't have a priority with additional path components");var h=l.getNode();n=i.serverCache.getNode();var d=l0(o,s,h,n);t=null!=d?r.filter.updatePriority(h,d):l.getNode()}else{h=cI(s);let e;e=l.isCompleteForChild(u)?(n=i.serverCache.getNode(),null!=(d=l0(o,s,l.getNode(),n))?l.getNode().getImmediateChild(u).updateChild(h,d):l.getNode().getImmediateChild(u)):d0(o,u,i.serverCache),t=null!=e?r.filter.updateChild(l.getNode(),u,e,h,a,c):l.getNode()}}return qT(i,t,l.isFullyInitialized()||pI(s),r.filter.filtersNodes())}}function w0(e,t,n,r,i,s,o,a){const c=t.serverCache;let l;const u=o?e.filter:e.filter.getIndexedFilter();if(pI(n))l=u.updateFullNode(c.getNode(),r,null);else if(u.filtersNodes()&&!c.isFiltered()){var h=c.getNode().updateChild(n,r);l=u.updateFullNode(c.getNode(),h,null)}else{var d=oI(n);if(!c.isCompleteForPath(n)&&1<aI(n))return t;var p=cI(n);const f=c.getNode().getImmediateChild(d);h=f.updateChild(p,r);l=".priority"===d?u.updatePriority(c.getNode(),h):u.updateChild(c.getNode(),d,h,p,m0,null)}p=VT(t,l,c.isFullyInitialized()||pI(n),u.filtersNodes());return _0(e,p,n,i,new v0(i,p,s),a)}function b0(t,n,r,i,e,s,o){const a=n.eventCache;let c,l;const u=new v0(e,n,s);if(pI(r))l=t.filter.updateFullNode(n.eventCache.getNode(),i,o),c=qT(n,l,!0,t.filter.filtersNodes());else{var h=oI(r);if(".priority"===h)l=t.filter.updatePriority(n.eventCache.getNode(),i),c=qT(n,l,a.isFullyInitialized(),a.isFiltered());else{var d=cI(r);const p=a.getNode().getImmediateChild(h);let e;if(pI(d))e=i;else{const f=u.getCompleteChild(h);e=null!=f?".priority"===lI(d)&&f.getChild(hI(d)).isEmpty()?f:f.updateChild(d,i):GI.EMPTY_NODE}c=p.equals(e)?n:qT(n,t.filter.updateChild(a.getNode(),h,e,d,u,o),a.isFullyInitialized(),t.filter.filtersNodes())}}return c}function I0(e,t){return e.eventCache.isCompleteForChild(t)}function T0(e,n,t){return t.foreach((e,t)=>{n=n.updateChild(e,t)}),n}function E0(r,i,e,t,s,o,a,c){if(i.serverCache.getNode().isEmpty()&&!i.serverCache.isFullyInitialized())return i;let l=i,n;n=pI(e)?t:new KT(null).setTree(e,t);const u=i.serverCache.getNode();return n.children.inorderTraversal((e,t)=>{var n;u.hasChild(e)&&(n=T0(0,i.serverCache.getNode().getImmediateChild(e),t),l=w0(r,l,new iI(e),n,s,o,a,c))}),n.children.inorderTraversal((e,t)=>{var n=!i.serverCache.isCompleteForChild(e)&&void 0===t.value;u.hasChild(e)||n||(n=T0(0,i.serverCache.getNode().getImmediateChild(e),t),l=w0(r,l,new iI(e),n,s,o,a,c))}),l}class k0{constructor(e,t){this.query_=e,this.eventRegistrations_=[];const n=this.query_._queryParams,r=new dT(n.getIndex()),i=(e=n).loadsAllData()?new dT(e.getIndex()):new(e.hasLimit()?fT:pT)(e);this.processor_={filter:i};const s=t.serverCache,o=t.eventCache;var a=r.updateFullNode(GI.EMPTY_NODE,s.getNode(),null),c=i.updateFullNode(GI.EMPTY_NODE,o.getNode(),null),a=new LT(a,s.isFullyInitialized(),r.filtersNodes()),c=new LT(c,o.isFullyInitialized(),i.filtersNodes());this.viewCache_=jT(c,a),this.eventGenerator_=new MT(this.query_)}get query(){return this.query_}}function S0(e){return 0===e.eventRegistrations_.length}function C0(n,r,i){const s=[];if(i){Xh(null==r,"A cancel should cancel all event registrations.");const o=n.query._path;n.eventRegistrations_.forEach(e=>{var t=e.createCancelEvent(i,o);t&&s.push(t)})}if(r){let e=[];for(let t=0;t<n.eventRegistrations_.length;++t){const a=n.eventRegistrations_[t];if(a.matches(r)){if(r.hasAnyCallback()){e=e.concat(n.eventRegistrations_.slice(t+1));break}}else e.push(a)}n.eventRegistrations_=e}else n.eventRegistrations_=[];return s}function A0(e,t,n,r){t.type===tb.MERGE&&null!==t.source.queryId&&(Xh(WT(e.viewCache_),"We should always have a full cache before handling merges"),Xh(BT(e.viewCache_),"Missing event cache, even though we have a server cache"));const i=e.viewCache_,s=y0(e.processor_,i,t,n,r);return n=e.processor_,r=s.viewCache,Xh(r.eventCache.getNode().isIndexed(n.filter.getIndex()),"Event snap not indexed"),Xh(r.serverCache.getNode().isIndexed(n.filter.getIndex()),"Server snap not indexed"),Xh(s.viewCache.serverCache.isFullyInitialized()||!i.serverCache.isFullyInitialized(),"Once a server snap is complete, it should never go back"),e.viewCache_=s.viewCache,N0(e,s.changes,s.viewCache.eventCache.getNode(),null)}function N0(e,t,n,r){var i=r?[r]:e.eventRegistrations_;return FT(e.eventGenerator_,t,n,i)}let R0;class P0{constructor(){this.views=new Map}}function x0(t,n,r,i){var e=n.source.queryId;if(null!==e){e=t.views.get(e);return Xh(null!=e,"SyncTree gave us an op for an invalid query."),A0(e,n,r,i)}{let e=[];for(const s of t.views.values())e=e.concat(A0(s,n,r,i));return e}}function O0(e,n,r,i,s){var o=n._queryIdentifier,o=e.views.get(o);if(o)return o;{let e=a0(r,s?i:null),t=!1;t=!!e||(e=i instanceof GI?c0(r,i):GI.EMPTY_NODE,!1);o=jT(new LT(e,t,!1),new LT(i,s,!1));return new k0(n,o)}}function D0(e,t,n,r,i,s){var o=O0(e,t,r,i,s);return e.views.has(t._queryIdentifier)||e.views.set(t._queryIdentifier,o),o.eventRegistrations_.push(n),function(e,t){const n=e.viewCache_.eventCache,r=[];if(!n.getNode().isLeafNode()){const i=n.getNode();i.forEachChild(qI,(e,t)=>{r.push(lT(e,t))})}return n.isFullyInitialized()&&r.push(cT(n.getNode())),N0(e,r,n.getNode(),t)}(o,n)}function L0(e,t,n,r){var i=t._queryIdentifier;const s=[];let o=[];var a=q0(e);if("default"===i)for(var[c,l]of e.views.entries())o=o.concat(C0(l,n,r)),S0(l)&&(e.views.delete(c),l.query._queryParams.loadsAllData()||s.push(l.query));else{const u=e.views.get(i);u&&(o=o.concat(C0(u,n,r)),S0(u)&&(e.views.delete(i),u.query._queryParams.loadsAllData()||s.push(u.query)))}return a&&!q0(e)&&s.push((Xh(R0,"Reference.ts has not been loaded"),new R0(t._repo,t._path))),{removed:s,events:o}}function M0(e){const t=[];for(const n of e.views.values())n.query._queryParams.loadsAllData()||t.push(n);return t}function F0(e,t){let n=null;for(const r of e.views.values())n=n||function(e,t){const n=WT(e.viewCache_);return n&&(e.query._queryParams.loadsAllData()||!pI(t)&&!n.getImmediateChild(oI(t)).isEmpty())?n.getChild(t):null}(r,t);return n}function U0(e,t){const n=t._queryParams;if(n.loadsAllData())return V0(e);var r=t._queryIdentifier;return e.views.get(r)}function j0(e,t){return null!=U0(e,t)}function q0(e){return null!=V0(e)}function V0(e){for(const t of e.views.values())if(t.query._queryParams.loadsAllData())return t;return null}let B0;let W0=1;class z0{constructor(e){this.listenProvider_=e,this.syncPointTree_=new KT(null),this.pendingWriteTree_={visibleWrites:$T.empty(),allWrites:[],lastWriteId:-1},this.tagToQueryMap=new Map,this.queryToTagMap=new Map}}function K0(e,t,n,r,i){var s,o,a,c;return s=e.pendingWriteTree_,o=t,a=n,c=r,r=i,Xh(c>s.lastWriteId,"Stacking an older write on top of newer ones"),s.allWrites.push({path:o,snap:a,writeId:c,visible:r=void 0===r?!0:r}),r&&(s.visibleWrites=HT(s.visibleWrites,o,a)),s.lastWriteId=c,i?Z0(e,new OT(AT(),t,n)):[]}function $0(e,t,n,r){var i,s,o;i=e.pendingWriteTree_,s=t,o=n,r=r,Xh(r>i.lastWriteId,"Stacking an older merge on top of newer ones"),i.allWrites.push({path:s,children:o,writeId:r,visible:!0}),i.visibleWrites=GT(i.visibleWrites,s,o),i.lastWriteId=r;var a=KT.fromObject(n);return Z0(e,new DT(AT(),t,a))}function H0(e,t,n=!1){var r=function(e,t){for(let r=0;r<e.allWrites.length;r++){var n=e.allWrites[r];if(n.writeId===t)return n}return null}(e.pendingWriteTree_,t);if(r0(e.pendingWriteTree_,t)){let t=new KT(null);return null!=r.snap?t=t.set(sI(),!0):Ab(r.children,e=>{t=t.set(new iI(e),!0)}),Z0(e,new PT(r.path,t,n))}return[]}function G0(e,t,n){return Z0(e,new OT(NT(),t,n))}function Q0(n,e,t,r){var i=e._path,s=n.syncPointTree_.get(i);let o=[];if(s&&("default"===e._queryIdentifier||j0(s,e))){var a=L0(s,e,t,r);0===s.views.size&&(n.syncPointTree_=n.syncPointTree_.remove(i));const h=a.removed;o=a.events;s=-1!==h.findIndex(e=>e._queryParams.loadsAllData()),a=n.syncPointTree_.findOnPath(i,(e,t)=>q0(t));if(s&&!a){const d=n.syncPointTree_.subtree(i);if(!d.isEmpty()){var c=d.fold((e,t,r)=>{if(t&&q0(t))return[V0(t)];{let n=[];return t&&(n=M0(t)),Ab(r,(e,t)=>{n=n.concat(t)}),n}});for(let e=0;e<c.length;++e){var l=c[e],u=l.query,l=tE(n,l);n.listenProvider_.startListening(aE(u),nE(n,u),l.hashFn,l.onComplete)}}}!a&&0<h.length&&!r&&(s?n.listenProvider_.stopListening(aE(e),null):h.forEach(e=>{var t=n.queryToTagMap.get(rE(e));n.listenProvider_.stopListening(aE(e),t)})),function(e,t){for(let i=0;i<t.length;++i){const s=t[i];var n,r;s._queryParams.loadsAllData()||(n=rE(s),r=e.queryToTagMap.get(n),e.queryToTagMap.delete(n),e.tagToQueryMap.delete(r))}}(n,h)}return o}function Y0(e,t,n){const r=t._path;let i=null,s=!1;e.syncPointTree_.foreachOnPath(r,(e,t)=>{var n=fI(e,r);i=i||F0(t,n),s=s||q0(t)});let o=e.syncPointTree_.get(r);o?(s=s||q0(o),i=i||F0(o,sI())):(o=new P0,e.syncPointTree_=e.syncPointTree_.set(r,o));let a;if(null!=i)a=!0;else{a=!1,i=GI.EMPTY_NODE;const d=e.syncPointTree_.subtree(r);d.foreachChild((e,t)=>{var n=F0(t,sI());n&&(i=i.updateImmediateChild(e,n))})}var c,l=j0(o,t);l||t._queryParams.loadsAllData()||(u=rE(t),Xh(!e.queryToTagMap.has(u),"View does not exist, but we have a tag"),c=W0++,e.queryToTagMap.set(u,c),e.tagToQueryMap.set(c,u));var u=n0(e.pendingWriteTree_,r);let h=D0(o,t,n,u,i,a);return l||s||(l=U0(o,t),h=h.concat(function(t,e,n){const r=e._path,i=nE(t,e),s=tE(t,n),o=t.listenProvider_.startListening(aE(e),i,s.hashFn,s.onComplete),a=t.syncPointTree_.subtree(r);if(i)Xh(!q0(a.value),"If we're adding a query, it shouldn't be shadowed");else{var c=a.fold((e,t,r)=>{if(!pI(e)&&t&&q0(t))return[V0(t).query];{let n=[];return t&&(n=n.concat(M0(t).map(e=>e.query))),Ab(r,(e,t)=>{n=n.concat(t)}),n}});for(let e=0;e<c.length;++e){var l=c[e];t.listenProvider_.stopListening(aE(l),nE(t,l))}}return o}(e,t,l))),h}function X0(e,r,t){var n=e.pendingWriteTree_,i=e.syncPointTree_.findOnPath(r,(e,t)=>{var n=F0(t,fI(e,r));if(n)return n});return o0(n,r,i,t,!0)}function J0(e,t){const r=t._path;let i=null;e.syncPointTree_.foreachOnPath(r,(e,t)=>{var n=fI(e,r);i=i||F0(t,n)});let n=e.syncPointTree_.get(r);n?i=i||F0(n,sI()):(n=new P0,e.syncPointTree_=e.syncPointTree_.set(r,n));var s=null!=i;const o=s?new LT(i,!0,!1):null;var a=n0(e.pendingWriteTree_,t._path);return BT(O0(n,t,a,s?o.getNode():GI.EMPTY_NODE,s).viewCache_)}function Z0(e,t){return function t(n,r,i,s){{if(pI(n.path))return eE(n,r,i,s);{const o=r.get(sI());null==i&&null!=o&&(i=F0(o,sI()));let e=[];const a=oI(n.path),c=n.operationForChild(a),l=r.children.get(a);if(l&&c){const u=i?i.getImmediateChild(a):null,h=p0(s,a);e=e.concat(t(c,l,u,h))}return o&&(e=e.concat(x0(o,n,s,i))),e}}}(t,e.syncPointTree_,null,n0(e.pendingWriteTree_,sI()))}function eE(s,e,o,a){var t=e.get(sI());null==o&&null!=t&&(o=F0(t,sI()));let c=[];return e.children.inorderTraversal((e,t)=>{var n=o?o.getImmediateChild(e):null,r=p0(a,e),i=s.operationForChild(e);i&&(c=c.concat(eE(i,t,n,r)))}),t&&(c=c.concat(x0(t,s,a,o))),c}function tE(i,t){const s=t.query,o=nE(i,s);return{hashFn:()=>{const e=t.viewCache_.serverCache.getNode()||GI.EMPTY_NODE;return e.hash()},onComplete:e=>{if("ok"===e)return o?function(e,t,n){if(s=iE(e,n)){var r=sE(s),i=r.path,s=r.queryId,r=fI(i,t);return oE(e,i,new xT(RT(s),r))}return[]}(i,s._path,o):(t=i,n=s._path,Z0(t,new xT(NT(),n)));var t,n,r=function(e,t){let n="Unknown Error";"too_big"===e?n="The data requested exceeds the maximum size that can be accessed with a single request.":"permission_denied"===e?n="Client doesn't have permission to access the desired data.":"unavailable"===e&&(n="The service is unavailable");const r=new Error(e+" at "+t._path.toString()+": "+n);return r.code=e.toUpperCase(),r}(e,s);return Q0(i,s,null,r)}}}function nE(e,t){var n=rE(t);return e.queryToTagMap.get(n)}function rE(e){return e._path.toString()+"$"+e._queryIdentifier}function iE(e,t){return e.tagToQueryMap.get(t)}function sE(e){var t=e.indexOf("$");return Xh(-1!==t&&t<e.length-1,"Bad queryKey."),{queryId:e.substr(t+1),path:new iI(e.substr(0,t))}}function oE(e,t,n){var r=e.syncPointTree_.get(t);return Xh(r,"Missing sync point for query tag that we're tracking"),x0(r,n,n0(e.pendingWriteTree_,t),null)}function aE(e){return e._queryParams.loadsAllData()&&!e._queryParams.isDefault()?(Xh(B0,"Reference.ts has not been loaded"),new B0(e._repo,e._path)):e}class cE{constructor(e){this.node_=e}getImmediateChild(e){var t=this.node_.getImmediateChild(e);return new cE(t)}node(){return this.node_}}class lE{constructor(e,t){this.syncTree_=e,this.path_=t}getImmediateChild(e){var t=dI(this.path_,e);return new lE(this.syncTree_,t)}node(){return X0(this.syncTree_,this.path_)}}function uE(e){return(e=e||{}).timestamp=e.timestamp||(new Date).getTime(),e}function hE(e,t,n){return e&&"object"==typeof e?(Xh(".sv"in e,"Unexpected leaf node or priority contents"),"string"==typeof e[".sv"]?dE(e[".sv"],t,n):"object"==typeof e[".sv"]?pE(e[".sv"],t):void Xh(!1,"Unexpected server value: "+JSON.stringify(e,null,2))):e}const dE=function(e,t,n){if("timestamp"===e)return n.timestamp;Xh(!1,"Unexpected server value: "+e)},pE=function(e,t,n){e.hasOwnProperty("increment")||Xh(!1,"Unexpected server value: "+JSON.stringify(e,null,2));var r=e.increment;"number"!=typeof r&&Xh(!1,"Unexpected increment value: "+r);const i=t.node();if(Xh(null!==i&&void 0!==i,"Expected ChildrenNode.EMPTY_NODE for nulls"),!i.isLeafNode())return r;const s=i;var o=s.getValue();return"number"!=typeof o?r:o+r},fE=function(e,t,n,r){return mE(t,new lE(n,e),r)},gE=function(e,t,n){return mE(e,new cE(t),n)};function mE(e,r,i){var t=e.getPriority().val(),n=hE(t,r.getImmediateChild(".priority"),i);let s;if(e.isLeafNode()){const o=e;t=hE(o.getValue(),r,i);return t!==o.getValue()||n!==o.getPriority().val()?new FI(t,JI(n)):e}{const a=e;return s=a,n!==a.getPriority().val()&&(s=s.updatePriority(new FI(n))),a.forEachChild(qI,(e,t)=>{var n=mE(t,r.getImmediateChild(e),i);n!==t&&(s=s.updateImmediateChild(e,n))}),s}}class vE{constructor(e="",t=null,n={children:{},childCount:0}){this.name=e,this.parent=t,this.node=n}}function yE(e,t){let n=t instanceof iI?t:new iI(t),r=e,i=oI(n);for(;null!==i;){var s=Id(r.node.children,i)||{children:{},childCount:0};r=new vE(i,r,s),n=cI(n),i=oI(n)}return r}function _E(e){return e.node.value}function wE(e,t){e.node.value=t,EE(e)}function bE(e){return 0<e.node.childCount}function IE(n,r){Ab(n.node.children,(e,t)=>{r(new vE(e,n,t))})}function TE(e){return new iI(null===e.parent?e.name:TE(e.parent)+"/"+e.name)}function EE(e){var t,n,r,i;null!==e.parent&&(t=e.parent,n=e.name,r=function(e){return void 0===_E(e)&&!bE(e)}(e=e),i=bd(t.node.children,n),r&&i?(delete t.node.children[n],t.node.childCount--,EE(t)):r||i||(t.node.children[n]=e.node,t.node.childCount++,EE(t)))}function kE(e,t,n,r){r&&void 0===t||UE(Ld(e,"value"),t,n)}function SE(e,t,r,n){if(!n||void 0!==t){const i=Ld(e,"values");if(!t||"object"!=typeof t||Array.isArray(t))throw new Error(i+" must be an object containing the children to replace.");const s=[];Ab(t,(e,t)=>{const n=new iI(e);if(UE(i,t,dI(r,n)),".priority"===lI(n)&&!FE(t))throw new Error(i+"contains an invalid value for '"+n.toString()+"', which must be a valid Firebase priority (a string, finite number, server value, or null).");s.push(n)}),function(t,n){let r,i;for(r=0;r<n.length;r++){i=n[r];var s=uI(i);for(let e=0;e<s.length;e++)if((".priority"!==s[e]||e!==s.length-1)&&!DE(s[e]))throw new Error(t+"contains an invalid key ("+s[e]+") in path "+i.toString()+'. Keys must be non-empty strings and can\'t contain ".", "#", "$", "/", "[", or "]"')}n.sort(gI);let e=null;for(r=0;r<n.length;r++){if(i=n[r],null!==e&&vI(e,i))throw new Error(t+"contains a path "+e.toString()+" that is ancestor of another path "+i.toString());e=i}}(i,s)}}function CE(e,t,n){if(!n||void 0!==t){if(Eb(t))throw new Error(Ld(e,"priority")+"is "+t.toString()+", but must be a valid Firebase priority (a string, finite number, server value, or null).");if(!FE(t))throw new Error(Ld(e,"priority")+"must be a valid Firebase priority (a string, finite number, server value, or null).")}}function AE(e,t,n,r){if(!(r&&void 0===n||DE(n)))throw new Error(Ld(e,t)+'was an invalid key = "'+n+'".  Firebase keys must be non-empty strings and can\'t contain ".", "#", "$", "/", "[", or "]").')}function NE(e,t,n,r){n=n&&n.replace(/^\/*\.info(\/|$)/,"/"),jE(e,t,n,r)}function RE(e,t){if(".info"===oI(t))throw new Error(e+" failed = Can't modify data under /.info/")}const PE=/[\[\].#$\/\u0000-\u001F\u007F]/,xE=/[\[\].#$\u0000-\u001F\u007F]/,OE=10485760,DE=function(e){return"string"==typeof e&&0!==e.length&&!PE.test(e)},LE=function(e){return"string"==typeof e&&0!==e.length&&!xE.test(e)},ME=function(e){return e=e&&e.replace(/^\/*\.info(\/|$)/,"/"),LE(e)},FE=function(e){return null===e||"string"==typeof e||"number"==typeof e&&!Eb(e)||e&&"object"==typeof e&&bd(e,".sv")},UE=function(o,e,t){const a=t instanceof iI?new yI(t,o):t;if(void 0===e)throw new Error(o+"contains undefined "+wI(a));if("function"==typeof e)throw new Error(o+"contains a function "+wI(a)+" with contents = "+e.toString());if(Eb(e))throw new Error(o+"contains "+e.toString()+" "+wI(a));if("string"==typeof e&&e.length>OE/3&&Ud(e)>OE)throw new Error(o+"contains a string greater than "+OE+" utf8 bytes "+wI(a)+" ('"+e.substring(0,50)+"...')");if(e&&"object"==typeof e){let i=!1,s=!1;if(Ab(e,(e,t)=>{if(".value"===e)i=!0;else if(".priority"!==e&&".sv"!==e&&(s=!0,!DE(e)))throw new Error(o+" contains an invalid key ("+e+") "+wI(a)+'.  Keys must be non-empty strings and can\'t contain ".", "#", "$", "/", "[", or "]"');var n,r;n=a,e=e,0<n.parts_.length&&(n.byteLength_+=1),n.parts_.push(e),n.byteLength_+=Ud(e),_I(n),UE(o,t,a),t=a,r=t.parts_.pop(),t.byteLength_-=Ud(r),0<t.parts_.length&&--t.byteLength_}),i&&s)throw new Error(o+' contains ".value" child '+wI(a)+" in addition to actual children.")}},jE=function(e,t,n,r){if(!(r&&void 0===n||LE(n)))throw new Error(Ld(e,t)+'was an invalid path = "'+n+'". Paths must be non-empty strings and can\'t contain ".", "#", "$", "[", or "]"')},qE=function(e,t){var n=t.path.toString();if("string"!=typeof t.repoInfo.host||0===t.repoInfo.host.length||!DE(t.repoInfo.namespace)&&"localhost"!==t.repoInfo.host.split(":")[0]||0!==n.length&&!ME(n))throw new Error(Ld(e,"url")+'must be a valid firebase URL and the path can\'t contain ".", "#", "$", "[", or "]".')};class VE{constructor(){this.eventLists_=[],this.recursionDepth_=0}}function BE(e,t){let n=null;for(let i=0;i<t.length;i++){const s=t[i];var r=s.getPath();null===n||mI(r,n.path)||(e.eventLists_.push(n),n=null),null===n&&(n={events:[],path:r}),n.events.push(s)}n&&e.eventLists_.push(n)}function WE(e,t,n){BE(e,n),KE(e,e=>mI(e,t))}function zE(e,t,n){BE(e,n),KE(e,e=>vI(e,t)||vI(t,e))}function KE(e,t){e.recursionDepth_++;let n=!0;for(let i=0;i<e.eventLists_.length;i++){var r=e.eventLists_[i];r&&(t(r.path)?(function(e){for(let n=0;n<e.events.length;n++){const r=e.events[n];var t;null!==r&&(e.events[n]=null,t=r.getEventRunner(),hb&&wb("event: "+r.toString()),Lb(t))}}(e.eventLists_[i]),e.eventLists_[i]=null):n=!1)}n&&(e.eventLists_=[]),e.recursionDepth_--}const $E="repo_interrupt",HE=25;class GE{constructor(e,t,n,r){this.repoInfo_=e,this.forceRestClient_=t,this.authTokenProvider_=n,this.appCheckProvider_=r,this.dataUpdateCount=0,this.statsListener_=null,this.eventQueue_=new VE,this.nextWriteId_=1,this.interceptServerDataCallback_=null,this.onDisconnect_=TT(),this.transactionQueueTree_=new vE,this.persistentConnection_=null,this.key=this.repoInfo_.toURLString()}toString(){return(this.repoInfo_.secure?"https://":"http://")+this.repoInfo_.host}}function QE(o,e,t){if(o.stats_=Hb(o.repoInfo_),o.forceRestClient_||function(){const e="object"==typeof window&&window.navigator&&window.navigator.userAgent||"";return 0<=e.search(/googlebot|google webmaster tools|bingbot|yahoo! slurp|baiduspider|yandexbot|duckduckbot/i)}())o.server_=new bT(o.repoInfo_,(e,t,n,r)=>{JE(o,e,t,n,r)},o.authTokenProvider_,o.appCheckProvider_),setTimeout(()=>ZE(o,!0),0);else{if(null!=t){if("object"!=typeof t)throw new Error("Only objects are supported for option databaseAuthVariableOverride");try{_d(t)}catch(e){throw new Error("Invalid authOverride provided: "+e)}}o.persistentConnection_=new II(o.repoInfo_,e,(e,t,n,r)=>{JE(o,e,t,n,r)},e=>{ZE(o,e)},e=>{var n;n=o,Ab(e,(e,t)=>{ek(n,e,t)})},o.authTokenProvider_,o.appCheckProvider_,t),o.server_=o.persistentConnection_}var n;o.authTokenProvider_.addTokenChangeListener(e=>{o.server_.refreshAuthToken(e)}),o.appCheckProvider_.addTokenChangeListener(e=>{o.server_.refreshAppCheckToken(e.token)}),o.statsReporter_=(e=o.repoInfo_,t=()=>new CT(o.stats_,o.server_),n=e.toString(),$b[n]||($b[n]=t()),$b[n]),o.infoData_=new IT,o.infoSyncTree_=new z0({startListening:(e,t,n,r)=>{let i=[];const s=o.infoData_.getNode(e._path);return s.isEmpty()||(i=G0(o.infoSyncTree_,e._path,s),setTimeout(()=>{r("ok")},0)),i},stopListening:()=>{}}),ek(o,"connected",!1),o.serverSyncTree_=new z0({startListening:(r,e,t,i)=>(o.server_.listen(r,t,e,(e,t)=>{var n=i(e,t);zE(o.eventQueue_,r._path,n)}),[]),stopListening:(e,t)=>{o.server_.unlisten(e,t)}})}function YE(e){const t=e.infoData_.getNode(new iI(".info/serverTimeOffset"));var n=t.val()||0;return(new Date).getTime()+n}function XE(e){return uE({timestamp:YE(e)})}function JE(e,t,n,r,i){e.dataUpdateCount++;var s,o,a=new iI(t);n=e.interceptServerDataCallback_?e.interceptServerDataCallback_(t,n):n;let c=[];c=i?r?(s=Ed(n,e=>JI(e)),function(e,t,n,r){if(a=iE(e,r)){var i=sE(a),s=i.path,o=i.queryId,a=fI(s,t),i=KT.fromObject(n);return oE(e,s,new DT(RT(o),a,i))}return[]}(e.serverSyncTree_,a,s,i)):(s=JI(n),function(e,t,n,r){if(null==(s=iE(e,r)))return[];var i=(o=sE(s)).path,s=o.queryId,o=fI(i,t);return oE(e,i,new OT(RT(s),o,n))}(e.serverSyncTree_,a,s,i)):r?(o=Ed(n,e=>JI(e)),t=e.serverSyncTree_,i=a,r=o,o=KT.fromObject(r),Z0(t,new DT(NT(),i,o))):(o=JI(n),G0(e.serverSyncTree_,a,o));let l=a;0<c.length&&(l=hk(e,a)),zE(e.eventQueue_,l,c)}function ZE(e,t){ek(e,"connected",t),!1===t&&function(r){ak(r,"onDisconnectEvents");const i=XE(r),s=TT();kT(r.onDisconnect_,sI(),(e,t)=>{var n=fE(e,t,r.serverSyncTree_,i);ET(s,e,n)});let o=[];kT(s,sI(),(e,t)=>{o=o.concat(G0(r.serverSyncTree_,e,t));var n=gk(r,e);hk(r,n)}),r.onDisconnect_=TT(),zE(r.eventQueue_,sI(),o)}(e)}function ek(e,t,n){var r=new iI("/.info/"+t),i=JI(n);e.infoData_.updateSnapshot(r,i);i=G0(e.infoSyncTree_,r,i);zE(e.eventQueue_,r,i)}function tk(e){return e.nextWriteId_++}function nk(r,i,e,t,s){ak(r,"set",{path:i.toString(),value:e,priority:t});var n=XE(r);const o=JI(e,t);var a=X0(r.serverSyncTree_,i),n=gE(o,a,n);const c=tk(r);n=K0(r.serverSyncTree_,i,n,c,!0);BE(r.eventQueue_,n),r.server_.put(i.toString(),o.val(!0),(e,t)=>{var n="ok"===e;n||Ib("set at "+i+" failed: "+e);n=H0(r.serverSyncTree_,c,!n);zE(r.eventQueue_,i,n),ck(0,s,e,t)});n=gk(r,i);hk(r,n),zE(r.eventQueue_,n,[])}function rk(n,r,i){n.server_.onDisconnectCancel(r.toString(),(e,t)=>{"ok"===e&&!function e(n,t){if(pI(t))return n.value=null,n.children.clear(),!0;if(null!==n.value){if(n.value.isLeafNode())return!1;{const i=n.value;return n.value=null,i.forEachChild(qI,(e,t)=>{ET(n,new iI(e),t)}),e(n,t)}}if(0<n.children.size){var r=oI(t);return t=cI(t),n.children.has(r)&&e(n.children.get(r),t)&&n.children.delete(r),0===n.children.size}return!0}(n.onDisconnect_,r),ck(0,i,e,t)})}function ik(n,r,e,i){const s=JI(e);n.server_.onDisconnectPut(r.toString(),s.val(!0),(e,t)=>{"ok"===e&&ET(n.onDisconnect_,r,s),ck(0,i,e,t)})}function sk(e,t,n){let r;r=".info"===oI(t._path)?Q0(e.infoSyncTree_,t,n):Q0(e.serverSyncTree_,t,n),WE(e.eventQueue_,t._path,r)}function ok(e){e.persistentConnection_&&e.persistentConnection_.interrupt($E)}function ak(e,...t){let n="";e.persistentConnection_&&(n=e.persistentConnection_.id+":"),wb(n,...t)}function ck(e,r,i,s){r&&Lb(()=>{if("ok"===i)r(null);else{var t=(i||"error").toUpperCase();let e=t;s&&(e+=": "+s);const n=new Error(e);n.code=t,r(n)}})}function lk(e,t,n){return X0(e.serverSyncTree_,t,n)||GI.EMPTY_NODE}function uk(t,e=t.transactionQueueTree_){if(e||fk(t,e),_E(e)){const n=pk(t,e);Xh(0<n.length,"Sending zero length transaction queue"),n.every(e=>0===e.status)&&function(i,s,o){const e=o.map(e=>e.currentWriteId),t=lk(i,s,e);let n=t;var r=t.hash();for(let u=0;u<o.length;u++){const h=o[u];Xh(0===h.status,"tryToSendTransactionQueue_: items in queue should all be run."),h.status=1,h.retryCount++;var a=fI(s,h.path);n=n.updateChild(a,h.currentOutputSnapshotRaw)}const c=n.val(!0),l=s;i.server_.put(l.toString(),c,t=>{ak(i,"transaction put response",{path:l.toString(),status:t});let n=[];if("ok"===t){const r=[];for(let e=0;e<o.length;e++)o[e].status=2,n=n.concat(H0(i.serverSyncTree_,o[e].currentWriteId)),o[e].onComplete&&r.push(()=>o[e].onComplete(null,!0,o[e].currentOutputSnapshotResolved)),o[e].unwatcher();fk(i,yE(i.transactionQueueTree_,s)),uk(i,i.transactionQueueTree_),zE(i.eventQueue_,s,n);for(let t=0;t<r.length;t++)Lb(r[t])}else{if("datastale"===t)for(let e=0;e<o.length;e++)3===o[e].status?o[e].status=4:o[e].status=0;else{Ib("transaction at "+l.toString()+" failed: "+t);for(let e=0;e<o.length;e++)o[e].status=4,o[e].abortReason=t}hk(i,s)}},r)}(t,TE(e),n)}else bE(e)&&IE(e,e=>{uk(t,e)})}function hk(e,t){var n=dk(e,t),r=TE(n);return function(i,s,o){if(0!==s.length){const l=[];let n=[];const t=s.filter(e=>0===e.status),u=t.map(e=>e.currentWriteId);for(let r=0;r<s.length;r++){const h=s[r];var a=fI(o,h.path);let e=!1,t;if(Xh(null!==a,"rerunTransactionsUnderNode_: relativePath should not be null."),4===h.status)e=!0,t=h.abortReason,n=n.concat(H0(i.serverSyncTree_,h.currentWriteId,!0));else if(0===h.status)if(h.retryCount>=HE)e=!0,t="maxretry",n=n.concat(H0(i.serverSyncTree_,h.currentWriteId,!0));else{const d=lk(i,h.path,u);h.currentInputSnapshot=d;var c=s[r].update(d.val());if(void 0!==c){UE("transaction failed: Data returned ",c,h.path);let e=JI(c);"object"==typeof c&&null!=c&&bd(c,".priority")||(e=e.updatePriority(d.getPriority()));a=h.currentWriteId,c=XE(i),c=gE(e,d,c);h.currentOutputSnapshotRaw=e,h.currentOutputSnapshotResolved=c,h.currentWriteId=tk(i),u.splice(u.indexOf(a),1),n=n.concat(K0(i.serverSyncTree_,h.path,c,h.currentWriteId,h.applyLocally)),n=n.concat(H0(i.serverSyncTree_,a,!0))}else e=!0,t="nodata",n=n.concat(H0(i.serverSyncTree_,h.currentWriteId,!0))}zE(i.eventQueue_,o,n),n=[],e&&(s[r].status=2,function(e){setTimeout(e,Math.floor(0))}(s[r].unwatcher),s[r].onComplete&&("nodata"===t?l.push(()=>s[r].onComplete(null,!1,s[r].currentInputSnapshot)):l.push(()=>s[r].onComplete(new Error(t),!1,null))))}fk(i,i.transactionQueueTree_);for(let e=0;e<l.length;e++)Lb(l[e]);uk(i,i.transactionQueueTree_)}}(e,pk(e,n),r),r}function dk(e,t){let n,r=e.transactionQueueTree_;for(n=oI(t);null!==n&&void 0===_E(r);)r=yE(r,n),t=cI(t),n=oI(t);return r}function pk(e,t){const n=[];return function t(n,e,r){const i=_E(e);if(i)for(let e=0;e<i.length;e++)r.push(i[e]);IE(e,e=>{t(n,e,r)})}(e,t,n),n.sort((e,t)=>e.order-t.order),n}function fk(t,n){const r=_E(n);if(r){let e=0;for(let t=0;t<r.length;t++)2!==r[t].status&&(r[e]=r[t],e++);r.length=e,wE(n,0<r.length?r:void 0)}IE(n,e=>{fk(t,e)})}function gk(t,e){var n=TE(dk(t,e)),r=yE(t.transactionQueueTree_,e);return function(e,t,n){let r=n?e:e.parent;for(;null!==r;){if(t(r))return;r=r.parent}}(r,e=>{mk(t,e)}),mk(t,r),function t(e,n,r,i){r&&!i&&n(e),IE(e,e=>{t(e,n,!0,i)}),r&&i&&n(e)}(r,e=>{mk(t,e)}),n}function mk(i,s){const o=_E(s);if(o){const a=[];let e=[],t=-1;for(let n=0;n<o.length;n++)3===o[n].status||(1===o[n].status?(Xh(t===n-1,"All SENT items should be at beginning of queue."),t=n,o[n].status=3,o[n].abortReason="set"):(Xh(0===o[n].status,"Unexpected transaction status in abort"),o[n].unwatcher(),e=e.concat(H0(i.serverSyncTree_,o[n].currentWriteId,!0)),o[n].onComplete&&a.push(o[n].onComplete.bind(null,new Error("set"),!1,null))));-1===t?wE(s,void 0):o.length=t+1,zE(i.eventQueue_,TE(s),e);for(let r=0;r<a.length;r++)Lb(a[r])}}const vk=function(e,t){var n=yk(e),r=n.namespace;"firebase.com"===n.domain&&bb(n.host+" is no longer supported. Please use <YOUR FIREBASE>.firebaseio.com instead"),r&&"undefined"!==r||"localhost"===n.domain||bb("Cannot parse Firebase url. Please use https://<YOUR FIREBASE>.firebaseio.com"),n.secure||Tb();var i="ws"===n.scheme||"wss"===n.scheme;return{repoInfo:new Bb(n.host,n.secure,r,t,i,"",r!==n.subdomain),path:new iI(n.pathString)}},yk=function(r){let i="",s="",o="",a="",c="",l=!0,u="https",h=443;if("string"==typeof r){let e=r.indexOf("//");0<=e&&(u=r.substring(0,e-1),r=r.substring(e+2));let t=r.indexOf("/");-1===t&&(t=r.length);let n=r.indexOf("?");-1===n&&(n=r.length),i=r.substring(0,Math.min(t,n)),t<n&&(a=function(e){let t="";var n=e.split("/");for(let r=0;r<n.length;r++)if(0<n[r].length){let e=n[r];try{e=decodeURIComponent(e.replace(/\+/g," "))}catch(e){}t+="/"+e}return t}(r.substring(t,n)));var d,p=function(e){const t={};for(const r of(e="?"===e.charAt(0)?e.substring(1):e).split("&")){var n;0!==r.length&&(2===(n=r.split("=")).length?t[decodeURIComponent(n[0])]=decodeURIComponent(n[1]):Ib(`Invalid query segment '${r}' in query '${e}'`))}return t}(r.substring(Math.min(r.length,n)));e=i.indexOf(":"),0<=e?(l="https"===u||"wss"===u,h=parseInt(i.substring(e+1),10)):e=i.length;const f=i.slice(0,e);"localhost"===f.toLowerCase()?s="localhost":f.split(".").length<=2?s=f:(d=i.indexOf("."),o=i.substring(0,d).toLowerCase(),s=i.substring(d+1),c=o),"ns"in p&&(c=p.ns)}return{host:i,port:h,domain:s,subdomain:o,secure:l,scheme:u,pathString:a,namespace:c}};class _k{constructor(e,t,n,r){this.eventType=e,this.eventRegistration=t,this.snapshot=n,this.prevName=r}getPath(){var e=this.snapshot.ref;return("value"===this.eventType?e:e.parent)._path}getEventType(){return this.eventType}getEventRunner(){return this.eventRegistration.getEventRunner(this)}toString(){return this.getPath().toString()+":"+this.eventType+":"+_d(this.snapshot.exportVal())}}class wk{constructor(e,t,n){this.eventRegistration=e,this.error=t,this.path=n}getPath(){return this.path}getEventType(){return"cancel"}getEventRunner(){return this.eventRegistration.getEventRunner(this)}toString(){return this.path.toString()+":cancel"}}class bk{constructor(e,t){this.snapshotCallback=e,this.cancelCallback=t}onValue(e,t){this.snapshotCallback.call(null,e,t)}onCancel(e){return Xh(this.hasCancelCallback,"Raising a cancel event on a listener with no cancel callback"),this.cancelCallback.call(null,e)}get hasCancelCallback(){return!!this.cancelCallback}matches(e){return this.snapshotCallback===e.snapshotCallback||void 0!==this.snapshotCallback.userCallback&&this.snapshotCallback.userCallback===e.snapshotCallback.userCallback&&this.snapshotCallback.context===e.snapshotCallback.context}}class Ik{constructor(e,t){this._repo=e,this._path=t}cancel(){const e=new rd;return rk(this._repo,this._path,e.wrapCallback(()=>{})),e.promise}remove(){RE("OnDisconnect.remove",this._path);const e=new rd;return ik(this._repo,this._path,null,e.wrapCallback(()=>{})),e.promise}set(e){RE("OnDisconnect.set",this._path),kE("OnDisconnect.set",e,this._path,!1);const t=new rd;return ik(this._repo,this._path,e,t.wrapCallback(()=>{})),t.promise}setWithPriority(e,t){RE("OnDisconnect.setWithPriority",this._path),kE("OnDisconnect.setWithPriority",e,this._path,!1),CE("OnDisconnect.setWithPriority",t,!1);const n=new rd;return function(n,r,e,t,i){const s=JI(e,t);n.server_.onDisconnectPut(r.toString(),s.val(!0),(e,t)=>{"ok"===e&&ET(n.onDisconnect_,r,s),ck(0,i,e,t)})}(this._repo,this._path,e,t,n.wrapCallback(()=>{})),n.promise}update(e){RE("OnDisconnect.update",this._path),SE("OnDisconnect.update",e,this._path,!1);const t=new rd;return function(r,i,n,s){if(Td(n))return wb("onDisconnect().update() called with empty data.  Don't do anything."),ck(0,s,"ok",void 0);r.server_.onDisconnectMerge(i.toString(),n,(e,t)=>{"ok"===e&&Ab(n,(e,t)=>{var n=JI(t);ET(r.onDisconnect_,dI(i,e),n)}),ck(0,s,e,t)})}(this._repo,this._path,e,t.wrapCallback(()=>{})),t.promise}}class Tk{constructor(e,t,n,r){this._repo=e,this._path=t,this._queryParams=n,this._orderByCalled=r}get key(){return pI(this._path)?null:lI(this._path)}get ref(){return new Ck(this._repo,this._path)}get _queryIdentifier(){var e=wT(this._queryParams),e=vb(e);return"{}"===e?"default":e}get _queryObject(){return wT(this._queryParams)}isEqual(e){if(!((e=zd(e))instanceof Tk))return!1;var t=this._repo===e._repo,n=mI(this._path,e._path),r=this._queryIdentifier===e._queryIdentifier;return t&&n&&r}toJSON(){return this.toString()}toString(){return this._repo.toString()+function(e){let t="";for(let n=e.pieceNum_;n<e.pieces_.length;n++)""!==e.pieces_[n]&&(t+="/"+encodeURIComponent(String(e.pieces_[n])));return t||"/"}(this._path)}}function Ek(e,t){if(!0===e._orderByCalled)throw new Error(t+": You can't combine multiple orderBy calls.")}function kk(e){let t=null,n=null;if(e.hasStart()&&(t=e.getIndexStartValue()),e.hasEnd()&&(n=e.getIndexEndValue()),e.getIndex()===CI){var r="Query: When ordering by key, you may only pass one argument to startAt(), endAt(), or equalTo().",i="Query: When ordering by key, the argument passed to startAt(), startAfter(), endAt(), endBefore(), or equalTo() must be a string.";if(e.hasStart()){if(e.getIndexStartName()!==kb)throw new Error(r);if("string"!=typeof t)throw new Error(i)}if(e.hasEnd()){if(e.getIndexEndName()!==Sb)throw new Error(r);if("string"!=typeof n)throw new Error(i)}}else if(e.getIndex()===qI){if(null!=t&&!FE(t)||null!=n&&!FE(n))throw new Error("Query: When ordering by priority, the first argument passed to startAt(), startAfter() endAt(), endBefore(), or equalTo() must be a valid priority value (null, a number, or a string).")}else if(Xh(e.getIndex()instanceof ZI||e.getIndex()===nT,"unknown index type."),null!=t&&"object"==typeof t||null!=n&&"object"==typeof n)throw new Error("Query: First argument passed to startAt(), startAfter(), endAt(), endBefore(), or equalTo() cannot be an object.")}function Sk(e){if(e.hasStart()&&e.hasEnd()&&e.hasLimit()&&!e.hasAnchoredLimit())throw new Error("Query: Can't combine startAt(), startAfter(), endAt(), endBefore(), and limit(). Use limitToFirst() or limitToLast() instead.")}class Ck extends Tk{constructor(e,t){super(e,t,new gT,!1)}get parent(){var e=hI(this._path);return null===e?null:new Ck(this._repo,e)}get root(){let e=this;for(;null!==e.parent;)e=e.parent;return e}}class Ak{constructor(e,t,n){this._node=e,this.ref=t,this._index=n}get priority(){return this._node.getPriority().val()}get key(){return this.ref.key}get size(){return this._node.numChildren()}child(e){var t=new iI(e),n=Pk(this.ref,e);return new Ak(this._node.getChild(t),n,qI)}exists(){return!this._node.isEmpty()}exportVal(){return this._node.val(!0)}forEach(n){if(this._node.isLeafNode())return!1;const e=this._node;return!!e.forEachChild(this._index,(e,t)=>n(new Ak(t,Pk(this.ref,e),qI)))}hasChild(e){var t=new iI(e);return!this._node.getChild(t).isEmpty()}hasChildren(){return!this._node.isLeafNode()&&!this._node.isEmpty()}toJSON(){return this.exportVal()}val(){return this._node.val()}}function Nk(e,t){return(e=zd(e))._checkNotDeleted("ref"),void 0!==t?Pk(e._root,t):e._root}function Rk(e,t){(e=zd(e))._checkNotDeleted("refFromURL");const n=vk(t,e._repo.repoInfo_.nodeAdmin);qE("refFromURL",n);var r=n.repoInfo;return e._repo.repoInfo_.isCustomHost()||r.host===e._repo.repoInfo_.host||bb("refFromURL: Host name does not match the current database: (found "+r.host+" but expected "+e._repo.repoInfo_.host+")"),Nk(e,n.path.toString())}function Pk(e,t){return(null===oI((e=zd(e))._path)?NE:jE)("child","path",t,!1),new Ck(e._repo,dI(e._path,t))}function xk(e,t){e=zd(e),RE("set",e._path),kE("set",t,e._path,!1);const n=new rd;return nk(e._repo,e._path,t,null,n.wrapCallback(()=>{})),n.promise}function Ok(e,t){SE("update",t,e._path,!1);const n=new rd;return function(i,s,e,o){ak(i,"update",{path:s.toString(),value:e});let n=!0;const r=XE(i),a={};if(Ab(e,(e,t)=>{n=!1,a[e]=fE(dI(s,e),JI(t),i.serverSyncTree_,r)}),n)wb("update() called with empty data.  Don't do anything."),ck(0,o,"ok",void 0);else{const c=tk(i);var t=$0(i.serverSyncTree_,s,a,c);BE(i.eventQueue_,t),i.server_.merge(s.toString(),e,(e,t)=>{var n="ok"===e;n||Ib("update at "+s+" failed: "+e);var r=H0(i.serverSyncTree_,c,!n),n=0<r.length?hk(i,s):s;zE(i.eventQueue_,n,r),ck(0,o,e,t)}),Ab(e,e=>{var t=gk(i,dI(s,e));hk(i,t)}),zE(i.eventQueue_,s,[])}}(e._repo,e._path,t,n.wrapCallback(()=>{})),n.promise}function Dk(t){return t=zd(t),r=t._repo,i=t,(null!=(e=J0(r.serverSyncTree_,i))?Promise.resolve(e):r.server_.get(i).then(e=>{var t=JI(e).withIndex(i._queryParams.getIndex()),n=G0(r.serverSyncTree_,i._path,t);return WE(r.eventQueue_,i._path,n),Promise.resolve(t)},e=>(ak(r,"get for query "+_d(i)+" failed: "+e),Promise.reject(new Error(e))))).then(e=>new Ak(e,new Ck(t._repo,t._path),t._queryParams.getIndex()));var r,i,e}class Lk{constructor(e){this.callbackContext=e}respondsTo(e){return"value"===e}createEvent(e,t){var n=t._queryParams.getIndex();return new _k("value",this,new Ak(e.snapshotNode,new Ck(t._repo,t._path),n))}getEventRunner(e){return"cancel"===e.getEventType()?()=>this.callbackContext.onCancel(e.error):()=>this.callbackContext.onValue(e.snapshot,null)}createCancelEvent(e,t){return this.callbackContext.hasCancelCallback?new wk(this,e,t):null}matches(e){return e instanceof Lk&&(!e.callbackContext||!this.callbackContext||e.callbackContext.matches(this.callbackContext))}hasAnyCallback(){return null!==this.callbackContext}}class Mk{constructor(e,t){this.eventType=e,this.callbackContext=t}respondsTo(e){let t="children_added"===e?"child_added":e;return t="children_removed"===t?"child_removed":t,this.eventType===t}createCancelEvent(e,t){return this.callbackContext.hasCancelCallback?new wk(this,e,t):null}createEvent(e,t){Xh(null!=e.childName,"Child events should have a childName.");var n=Pk(new Ck(t._repo,t._path),e.childName),r=t._queryParams.getIndex();return new _k(e.type,this,new Ak(e.snapshotNode,n,r),e.prevName)}getEventRunner(e){return"cancel"===e.getEventType()?()=>this.callbackContext.onCancel(e.error):()=>this.callbackContext.onValue(e.snapshot,e.prevName)}matches(e){return e instanceof Mk&&(this.eventType===e.eventType&&(!this.callbackContext||!e.callbackContext||this.callbackContext.matches(e.callbackContext)))}hasAnyCallback(){return!!this.callbackContext}}function Fk(n,e,t,r,i){let s;if("object"==typeof r&&(s=void 0,i=r),"function"==typeof r&&(s=r),i&&i.onlyOnce){const c=t;var o=(e,t)=>{sk(n._repo,n,a),c(e,t)};o.userCallback=t.userCallback,o.context=t.context,t=o}o=new bk(t,s||void 0);const a="value"===e?new Lk(o):new Mk(e,o);return function(e,t,n){let r;r=".info"===oI(t._path)?Y0(e.infoSyncTree_,t,n):Y0(e.serverSyncTree_,t,n),WE(e.eventQueue_,t._path,r)}(n._repo,n,a),()=>sk(n._repo,n,a)}function Uk(e,t,n,r){return Fk(e,"value",t,n,r)}function jk(e,t,n,r){return Fk(e,"child_added",t,n,r)}function qk(e,t,n,r){return Fk(e,"child_changed",t,n,r)}function Vk(e,t,n,r){return Fk(e,"child_moved",t,n,r)}function Bk(e,t,n,r){return Fk(e,"child_removed",t,n,r)}function Wk(e,t,n){let r=null;var i=n?new bk(n):null;"value"===t?r=new Lk(i):t&&(r=new Mk(t,i)),sk(e._repo,e,r)}class zk{}class Kk extends zk{constructor(e,t){super(),this._value=e,this._key=t}_apply(e){kE("endAt",this._value,e._path,!0);var t=vT(e._queryParams,this._value,this._key);if(Sk(t),kk(t),e._queryParams.hasEnd())throw new Error("endAt: Starting point was already set (by another call to endAt, endBefore or equalTo).");return new Tk(e._repo,e._path,t,e._orderByCalled)}}class $k extends zk{constructor(e,t){super(),this._value=e,this._key=t}_apply(e){kE("endBefore",this._value,e._path,!1);var t=function(e,t,n){let r,i;return i=e.index_===CI?vT(e,t="string"==typeof t?tT(t):t,n):(r=null==n?kb:tT(n),vT(e,t,r)),i.endBeforeSet_=!0,i}(e._queryParams,this._value,this._key);if(Sk(t),kk(t),e._queryParams.hasEnd())throw new Error("endBefore: Starting point was already set (by another call to endAt, endBefore or equalTo).");return new Tk(e._repo,e._path,t,e._orderByCalled)}}class Hk extends zk{constructor(e,t){super(),this._value=e,this._key=t}_apply(e){kE("startAt",this._value,e._path,!0);var t=mT(e._queryParams,this._value,this._key);if(Sk(t),kk(t),e._queryParams.hasStart())throw new Error("startAt: Starting point was already set (by another call to startAt, startBefore or equalTo).");return new Tk(e._repo,e._path,t,e._orderByCalled)}}class Gk extends zk{constructor(e,t){super(),this._value=e,this._key=t}_apply(e){kE("startAfter",this._value,e._path,!1);var t=function(t,n,r){let i;if(t.index_===CI)"string"==typeof n&&(n=eT(n)),i=mT(t,n,r);else{let e;e=null==r?Sb:eT(r),i=mT(t,n,e)}return i.startAfterSet_=!0,i}(e._queryParams,this._value,this._key);if(Sk(t),kk(t),e._queryParams.hasStart())throw new Error("startAfter: Starting point was already set (by another call to startAt, startAfter, or equalTo).");return new Tk(e._repo,e._path,t,e._orderByCalled)}}class Qk extends zk{constructor(e){super(),this._limit=e}_apply(e){if(e._queryParams.hasLimit())throw new Error("limitToFirst: Limit was already set (by another call to limitToFirst or limitToLast).");return new Tk(e._repo,e._path,function(e,t){const n=e.copy();return n.limitSet_=!0,n.limit_=t,n.viewFrom_="l",n}(e._queryParams,this._limit),e._orderByCalled)}}class Yk extends zk{constructor(e){super(),this._limit=e}_apply(e){if(e._queryParams.hasLimit())throw new Error("limitToLast: Limit was already set (by another call to limitToFirst or limitToLast).");return new Tk(e._repo,e._path,function(e,t){const n=e.copy();return n.limitSet_=!0,n.limit_=t,n.viewFrom_="r",n}(e._queryParams,this._limit),e._orderByCalled)}}class Xk extends zk{constructor(e){super(),this._path=e}_apply(e){Ek(e,"orderByChild");var t=new iI(this._path);if(pI(t))throw new Error("orderByChild: cannot pass in empty path. Use orderByValue() instead.");t=new ZI(t),t=yT(e._queryParams,t);return kk(t),new Tk(e._repo,e._path,t,!0)}}class Jk extends zk{_apply(e){Ek(e,"orderByKey");var t=yT(e._queryParams,CI);return kk(t),new Tk(e._repo,e._path,t,!0)}}class Zk extends zk{_apply(e){Ek(e,"orderByPriority");var t=yT(e._queryParams,qI);return kk(t),new Tk(e._repo,e._path,t,!0)}}class eS extends zk{_apply(e){Ek(e,"orderByValue");var t=yT(e._queryParams,nT);return kk(t),new Tk(e._repo,e._path,t,!0)}}class tS extends zk{constructor(e,t){super(),this._value=e,this._key=t}_apply(e){if(kE("equalTo",this._value,e._path,!1),e._queryParams.hasStart())throw new Error("equalTo: Starting point was already set (by another call to startAt/startAfter or equalTo).");if(e._queryParams.hasEnd())throw new Error("equalTo: Ending point was already set (by another call to endAt/endBefore or equalTo).");return new Kk(this._value,this._key)._apply(new Hk(this._value,this._key)._apply(e))}}function nS(e,...t){let n=zd(e);for(const r of t)n=r._apply(n);return n}nb=Ck,Xh(!R0,"__referenceConstructor has already been defined"),R0=nb,rb=Ck,Xh(!B0,"__referenceConstructor has already been defined"),B0=rb;const rS="FIREBASE_DATABASE_EMULATOR_HOST",iS={};let sS=!1;function oS(e,t,n,r,i){let s=r||e.options.databaseURL;void 0===s&&(e.options.projectId||bb("Can't determine Firebase Database URL. Be sure to include  a Project ID when calling firebase.initializeApp()."),wb("Using default host for project ",e.options.projectId),s=`${e.options.projectId}-default-rtdb.firebaseio.com`);let o=vk(s,i),a=o.repoInfo,c,l=void 0;"undefined"!=typeof process&&(l=process.env[rS]),l?(c=!0,s=`http://${l}?ns=${a.namespace}`,o=vk(s,i),a=o.repoInfo):c=!o.repoInfo.secure;var u=i&&c?new Ub(Ub.OWNER):new Fb(e.name,e.options,t);qE("Invalid Firebase Database URL",o),pI(o.path)||bb("Database URL must point to the root of a Firebase Database (not including a child path).");u=function(e,t,n,r){let i=iS[t.name];i||(i={},iS[t.name]=i);var s=i[e.toURLString()];s&&bb("Database initialized multiple times. Please make sure the format of the database URL matches with each database() call.");return s=new GE(e,sS,n,r),i[e.toURLString()]=s}(a,e,u,new Mb(e.name,n));return new aS(u,e)}class aS{constructor(e,t){this._repoInternal=e,this.app=t,this.type="database",this._instanceStarted=!1}get _repo(){return this._instanceStarted||(QE(this._repoInternal,this.app.options.appId,this.app.options.databaseAuthVariableOverride),this._instanceStarted=!0),this._repoInternal}get _root(){return this._rootInternal||(this._rootInternal=new Ck(this._repo,sI())),this._rootInternal}_delete(){return null!==this._rootInternal&&(function(e,t){const n=iS[t];n&&n[e.key]===e||bb(`Database ${t}(${e.repoInfo_}) has already been deleted.`),ok(e),delete n[e.key]}(this._repo,this.app.name),this._repoInternal=null,this._rootInternal=null),Promise.resolve()}_checkNotDeleted(e){null===this._rootInternal&&bb("Cannot call "+e+" on a deleted database.")}}function cS(e,t,n,r={}){(e=zd(e))._checkNotDeleted("useEmulator"),e._instanceStarted&&bb("Cannot call useEmulator() after instance has already been initialized.");var i,s=e._repoInternal;let o=void 0;s.repoInfo_.nodeAdmin?(r.mockUserToken&&bb('mockUserToken is not supported by the Admin SDK. For client access with mock users, please use the "firebase" package instead of "firebase-admin".'),o=new Ub(Ub.OWNER)):r.mockUserToken&&(i="string"==typeof r.mockUserToken?r.mockUserToken:id(r.mockUserToken,e.app.options.projectId),o=new Ub(i)),r=s,e=t,t=n,n=o,r.repoInfo_=new Bb(`${e}:${t}`,!1,r.repoInfo_.namespace,r.repoInfo_.webSocketOnly,r.repoInfo_.nodeAdmin,r.repoInfo_.persistenceKey,r.repoInfo_.includeNamespaceInQueryParams),n&&(r.authTokenProvider_=n)}function lS(e){(e=zd(e))._checkNotDeleted("goOnline"),(e=e._repo).persistentConnection_&&e.persistentConnection_.resume($E)}function uS(e,t){_b(e,t)}const hS={".sv":"timestamp"};class dS{constructor(e,t){this.committed=e,this.snapshot=t}toJSON(){return{committed:this.committed,snapshot:this.snapshot.toJSON()}}}function pS(i,e,t){if(i=zd(i),RE("Reference.transaction",i._path),".length"===i.key||".keys"===i.key)throw"Reference.transaction failed: "+i.key+" is a read-only object.";var n=null===(r=null==t?void 0:t.applyLocally)||void 0===r||r;const s=new rd;var r=Uk(i,()=>{});return function(t,n,e,r,i,s){ak(t,"transaction on "+n);const o={path:n,update:e,onComplete:r,status:null,order:lb(),applyLocally:s,retryCount:0,unwatcher:i,abortReason:null,currentWriteId:null,currentInputSnapshot:null,currentOutputSnapshotRaw:null,currentOutputSnapshotResolved:null},a=lk(t,n,void 0);o.currentInputSnapshot=a;var c=o.update(a.val());if(void 0===c)o.unwatcher(),o.currentOutputSnapshotRaw=null,o.currentOutputSnapshotResolved=null,o.onComplete&&o.onComplete(null,!1,o.currentInputSnapshot);else{UE("transaction failed: Data returned ",c,o.path),o.status=0;var l=yE(t.transactionQueueTree_,n);const u=_E(l)||[];u.push(o),wE(l,u);let e;if("object"==typeof c&&null!==c&&bd(c,".priority"))e=Id(c,".priority"),Xh(FE(e),"Invalid priority returned by transaction. Priority must be a valid string, finite number, server value, or null.");else{const h=X0(t.serverSyncTree_,n)||GI.EMPTY_NODE;e=h.getPriority().val()}l=XE(t),c=JI(c,e),l=gE(c,a,l);o.currentOutputSnapshotRaw=c,o.currentOutputSnapshotResolved=l,o.currentWriteId=tk(t);l=K0(t.serverSyncTree_,n,l,o.currentWriteId,o.applyLocally);zE(t.eventQueue_,n,l),uk(t,t.transactionQueueTree_)}}(i._repo,i._path,e,(e,t,n)=>{var r;e?s.reject(e):(r=new Ak(n,new Ck(i._repo,i._path),qI),s.resolve(new dS(t,r)))},r,n),s.promise}II.prototype.simpleListen=function(e,t){this.sendRequest("q",{p:e},t)},II.prototype.echo=function(e,t){this.sendRequest("echo",{d:e},t)},Yw(gp),hp(new Kd("database",(e,{instanceIdentifier:t})=>{return oS(e.getProvider("app").getImmediate(),e.getProvider("auth-internal"),e.getProvider("app-check-internal"),t)},"PUBLIC").setMultipleInstances(!0)),_p(Gw,"0.12.5",ib),_p(Gw,"0.12.5","esm2017");function fS(e){var t="FIREBASE WARNING: "+e;gS.warn(t)}const gS=new ep("@firebase/database-compat");class mS{constructor(e){this._delegate=e}cancel(t){Dd("OnDisconnect.cancel",0,1,arguments.length),Md("OnDisconnect.cancel","onComplete",t,!0);const e=this._delegate.cancel();return t&&e.then(()=>t(null),e=>t(e)),e}remove(t){Dd("OnDisconnect.remove",0,1,arguments.length),Md("OnDisconnect.remove","onComplete",t,!0);const e=this._delegate.remove();return t&&e.then(()=>t(null),e=>t(e)),e}set(e,t){Dd("OnDisconnect.set",1,2,arguments.length),Md("OnDisconnect.set","onComplete",t,!0);const n=this._delegate.set(e);return t&&n.then(()=>t(null),e=>t(e)),n}setWithPriority(e,t,n){Dd("OnDisconnect.setWithPriority",2,3,arguments.length),Md("OnDisconnect.setWithPriority","onComplete",n,!0);const r=this._delegate.setWithPriority(e,t);return n&&r.then(()=>n(null),e=>n(e)),r}update(t,n){if(Dd("OnDisconnect.update",1,2,arguments.length),Array.isArray(t)){const r={};for(let e=0;e<t.length;++e)r[""+e]=t[e];t=r,fS("Passing an Array to firebase.database.onDisconnect().update() is deprecated. Use set() if you want to overwrite the existing data, or an Object with integer keys if you really do want to only update some of the children.")}Md("OnDisconnect.update","onComplete",n,!0);const e=this._delegate.update(t);return n&&e.then(()=>n(null),e=>n(e)),e}}class vS{constructor(e,t){this.committed=e,this.snapshot=t}toJSON(){return Dd("TransactionResult.toJSON",0,1,arguments.length),{committed:this.committed,snapshot:this.snapshot.toJSON()}}}class yS{constructor(e,t){this._database=e,this._delegate=t}val(){return Dd("DataSnapshot.val",0,0,arguments.length),this._delegate.val()}exportVal(){return Dd("DataSnapshot.exportVal",0,0,arguments.length),this._delegate.exportVal()}toJSON(){return Dd("DataSnapshot.toJSON",0,1,arguments.length),this._delegate.toJSON()}exists(){return Dd("DataSnapshot.exists",0,0,arguments.length),this._delegate.exists()}child(e){return Dd("DataSnapshot.child",0,1,arguments.length),e=String(e),jE("DataSnapshot.child","path",e,!1),new yS(this._database,this._delegate.child(e))}hasChild(e){return Dd("DataSnapshot.hasChild",1,1,arguments.length),jE("DataSnapshot.hasChild","path",e,!1),this._delegate.hasChild(e)}getPriority(){return Dd("DataSnapshot.getPriority",0,0,arguments.length),this._delegate.priority}forEach(t){return Dd("DataSnapshot.forEach",1,1,arguments.length),Md("DataSnapshot.forEach","action",t,!1),this._delegate.forEach(e=>t(new yS(this._database,e)))}hasChildren(){return Dd("DataSnapshot.hasChildren",0,0,arguments.length),this._delegate.hasChildren()}get key(){return this._delegate.key}numChildren(){return Dd("DataSnapshot.numChildren",0,0,arguments.length),this._delegate.size}getRef(){return Dd("DataSnapshot.ref",0,0,arguments.length),new wS(this._database,this._delegate.ref)}get ref(){return this.getRef()}}class _S{constructor(e,t){this.database=e,this._delegate=t}on(e,n,t,r){var i;Dd("Query.on",2,4,arguments.length),Md("Query.on","callback",n,!1);const s=_S.getCancelAndContextArgs_("Query.on",t,r);var o=(e,t)=>{n.call(s.context,new yS(this.database,e),t)};o.userCallback=n,o.context=s.context;var a=null===(i=s.cancel)||void 0===i?void 0:i.bind(s.context);switch(e){case"value":return Uk(this._delegate,o,a),n;case"child_added":return jk(this._delegate,o,a),n;case"child_removed":return Bk(this._delegate,o,a),n;case"child_changed":return qk(this._delegate,o,a),n;case"child_moved":return Vk(this._delegate,o,a),n;default:throw new Error(Ld("Query.on","eventType")+'must be a valid event type = "value", "child_added", "child_removed", "child_changed", or "child_moved".')}}off(e,t,n){var r;Dd("Query.off",0,3,arguments.length),function(e,t,n){if(!n||void 0!==t)switch(t){case"value":case"child_added":case"child_removed":case"child_changed":case"child_moved":break;default:throw new Error(Ld(e,"eventType")+'must be a valid event type = "value", "child_added", "child_removed", "child_changed", or "child_moved".')}}("Query.off",e,!0),Md("Query.off","callback",t,!0),Fd("Query.off","context",n,!0),t?((r=()=>{}).userCallback=t,r.context=n,Wk(this._delegate,e,r)):Wk(this._delegate,e)}get(){return Dk(this._delegate).then(e=>new yS(this.database,e))}once(e,r,t,n){Dd("Query.once",1,4,arguments.length),Md("Query.once","callback",r,!0);const i=_S.getCancelAndContextArgs_("Query.once",t,n),s=new rd;var o=(e,t)=>{var n=new yS(this.database,e);r&&r.call(i.context,n,t),s.resolve(n)};o.userCallback=r,o.context=i.context;var a=e=>{i.cancel&&i.cancel.call(i.context,e),s.reject(e)};switch(e){case"value":Uk(this._delegate,o,a,{onlyOnce:!0});break;case"child_added":jk(this._delegate,o,a,{onlyOnce:!0});break;case"child_removed":Bk(this._delegate,o,a,{onlyOnce:!0});break;case"child_changed":qk(this._delegate,o,a,{onlyOnce:!0});break;case"child_moved":Vk(this._delegate,o,a,{onlyOnce:!0});break;default:throw new Error(Ld("Query.once","eventType")+'must be a valid event type = "value", "child_added", "child_removed", "child_changed", or "child_moved".')}return s.promise}limitToFirst(e){return Dd("Query.limitToFirst",1,1,arguments.length),new _S(this.database,nS(this._delegate,function(e){if("number"!=typeof e||Math.floor(e)!==e||e<=0)throw new Error("limitToFirst: First argument must be a positive integer.");return new Qk(e)}(e)))}limitToLast(e){return Dd("Query.limitToLast",1,1,arguments.length),new _S(this.database,nS(this._delegate,function(e){if("number"!=typeof e||Math.floor(e)!==e||e<=0)throw new Error("limitToLast: First argument must be a positive integer.");return new Yk(e)}(e)))}orderByChild(e){return Dd("Query.orderByChild",1,1,arguments.length),new _S(this.database,nS(this._delegate,function(e){if("$key"===e)throw new Error('orderByChild: "$key" is invalid.  Use orderByKey() instead.');if("$priority"===e)throw new Error('orderByChild: "$priority" is invalid.  Use orderByPriority() instead.');if("$value"===e)throw new Error('orderByChild: "$value" is invalid.  Use orderByValue() instead.');return jE("orderByChild","path",e,!1),new Xk(e)}(e)))}orderByKey(){return Dd("Query.orderByKey",0,0,arguments.length),new _S(this.database,nS(this._delegate,new Jk))}orderByPriority(){return Dd("Query.orderByPriority",0,0,arguments.length),new _S(this.database,nS(this._delegate,new Zk))}orderByValue(){return Dd("Query.orderByValue",0,0,arguments.length),new _S(this.database,nS(this._delegate,new eS))}startAt(e=null,t){return Dd("Query.startAt",0,2,arguments.length),new _S(this.database,nS(this._delegate,([e=null,t]=[e,t],AE("startAt","key",t,!0),new Hk(e,t))))}startAfter(e=null,t){return Dd("Query.startAfter",0,2,arguments.length),new _S(this.database,nS(this._delegate,(e=e,t=t,AE("startAfter","key",t,!0),new Gk(e,t))))}endAt(e=null,t){return Dd("Query.endAt",0,2,arguments.length),new _S(this.database,nS(this._delegate,(e=e,t=t,AE("endAt","key",t,!0),new Kk(e,t))))}endBefore(e=null,t){return Dd("Query.endBefore",0,2,arguments.length),new _S(this.database,nS(this._delegate,(e=e,t=t,AE("endBefore","key",t,!0),new $k(e,t))))}equalTo(e,t){return Dd("Query.equalTo",1,2,arguments.length),new _S(this.database,nS(this._delegate,(e=e,t=t,AE("equalTo","key",t,!0),new tS(e,t))))}toString(){return Dd("Query.toString",0,0,arguments.length),this._delegate.toString()}toJSON(){return Dd("Query.toJSON",0,1,arguments.length),this._delegate.toJSON()}isEqual(e){if(Dd("Query.isEqual",1,1,arguments.length),e instanceof _S)return this._delegate.isEqual(e._delegate);throw new Error("Query.isEqual failed: First argument must be an instance of firebase.database.Query.")}static getCancelAndContextArgs_(e,t,n){const r={cancel:void 0,context:void 0};if(t&&n)r.cancel=t,Md(e,"cancel",r.cancel,!0),r.context=n,Fd(e,"context",r.context,!0);else if(t)if("object"==typeof t&&null!==t)r.context=t;else{if("function"!=typeof t)throw new Error(Ld(e,"cancelOrContext")+" must either be a cancel callback or a context object.");r.cancel=t}return r}get ref(){return new wS(this.database,new Ck(this._delegate._repo,this._delegate._path))}}class wS extends _S{constructor(e,t){super(e,new Tk(t._repo,t._path,new gT,!1)),this.database=e,this._delegate=t}getKey(){return Dd("Reference.key",0,0,arguments.length),this._delegate.key}child(e){return Dd("Reference.child",1,1,arguments.length),"number"==typeof e&&(e=String(e)),new wS(this.database,Pk(this._delegate,e))}getParent(){Dd("Reference.parent",0,0,arguments.length);var e=this._delegate.parent;return e?new wS(this.database,e):null}getRoot(){return Dd("Reference.root",0,0,arguments.length),new wS(this.database,this._delegate.root)}set(e,t){Dd("Reference.set",1,2,arguments.length),Md("Reference.set","onComplete",t,!0);const n=xk(this._delegate,e);return t&&n.then(()=>t(null),e=>t(e)),n}update(t,n){if(Dd("Reference.update",1,2,arguments.length),Array.isArray(t)){const r={};for(let e=0;e<t.length;++e)r[""+e]=t[e];t=r,fS("Passing an Array to Firebase.update() is deprecated. Use set() if you want to overwrite the existing data, or an Object with integer keys if you really do want to only update some of the children.")}RE("Reference.update",this._delegate._path),Md("Reference.update","onComplete",n,!0);const e=Ok(this._delegate,t);return n&&e.then(()=>n(null),e=>n(e)),e}setWithPriority(e,t,n){Dd("Reference.setWithPriority",2,3,arguments.length),Md("Reference.setWithPriority","onComplete",n,!0);const r=function(e,t,n){if(RE("setWithPriority",e._path),kE("setWithPriority",t,e._path,!1),CE("setWithPriority",n,!1),".length"===e.key||".keys"===e.key)throw"setWithPriority failed: "+e.key+" is a read-only object.";const r=new rd;return nk(e._repo,e._path,t,n,r.wrapCallback(()=>{})),r.promise}(this._delegate,e,t);return n&&r.then(()=>n(null),e=>n(e)),r}remove(t){Dd("Reference.remove",0,1,arguments.length),Md("Reference.remove","onComplete",t,!0);const e=(n=this._delegate,RE("remove",n._path),xk(n,null));var n;return t&&e.then(()=>t(null),e=>t(e)),e}transaction(e,t,n){Dd("Reference.transaction",1,3,arguments.length),Md("Reference.transaction","transactionUpdate",e,!1),Md("Reference.transaction","onComplete",t,!0),function(e,t,n,r){if((!r||void 0!==n)&&"boolean"!=typeof n)throw new Error(Ld(e,t)+"must be a boolean.")}("Reference.transaction","applyLocally",n,!0);const r=pS(this._delegate,e,{applyLocally:n}).then(e=>new vS(e.committed,new yS(this.database,e.snapshot)));return t&&r.then(e=>t(null,e.committed,e.snapshot),e=>t(e,!1,null)),r}setPriority(e,t){Dd("Reference.setPriority",1,2,arguments.length),Md("Reference.setPriority","onComplete",t,!0);const n=function(e,t){e=zd(e),RE("setPriority",e._path),CE("setPriority",t,!1);const n=new rd;return nk(e._repo,dI(e._path,".priority"),t,null,n.wrapCallback(()=>{})),n.promise}(this._delegate,e);return t&&n.then(()=>t(null),e=>t(e)),n}push(e,t){Dd("Reference.push",0,2,arguments.length),Md("Reference.push","onComplete",t,!0);const n=function(e,t){e=zd(e),RE("push",e._path),kE("push",t,e._path,!0);var n=YE(e._repo),n=aT(n);const r=Pk(e,n),i=Pk(e,n);let s;return s=null!=t?xk(i,t).then(()=>i):Promise.resolve(i),r.then=s.then.bind(s),r.catch=s.then.bind(s,void 0),r}(this._delegate,e),r=n.then(e=>new wS(this.database,e));t&&r.then(()=>t(null),e=>t(e));const i=new wS(this.database,n);return i.then=r.then.bind(r),i.catch=r.catch.bind(r,void 0),i}onDisconnect(){return RE("Reference.onDisconnect",this._delegate._path),new mS(new Ik(this._delegate._repo,this._delegate._path))}get key(){return this.getKey()}get parent(){return this.getParent()}get root(){return this.getRoot()}}class bS{constructor(e,t){this._delegate=e,this.app=t,this.INTERNAL={delete:()=>this._delegate._delete()}}useEmulator(e,t,n={}){cS(this._delegate,e,t,n)}ref(e){if(Dd("database.ref",0,1,arguments.length),e instanceof wS){var t=Rk(this._delegate,e.toString());return new wS(this,t)}t=Nk(this._delegate,e);return new wS(this,t)}refFromURL(e){Dd("database.refFromURL",1,1,arguments.length);var t=Rk(this._delegate,e);return new wS(this,t)}goOffline(){var e;Dd("database.goOffline",0,0,arguments.length),(e=zd(e=this._delegate))._checkNotDeleted("goOffline"),ok(e._repo)}goOnline(){return Dd("database.goOnline",0,0,arguments.length),lS(this._delegate)}}bS.ServerValue={TIMESTAMP:hS,increment:e=>({".sv":{increment:e}})};var IS,TS=Object.freeze({__proto__:null,initStandalone:function({app:e,url:t,version:n,customAuthImpl:r,namespace:i,nodeAdmin:s=!1}){Yw(n);const o=new Hd("auth-internal",new Gd("database-standalone"));return o.setComponent(new Kd("auth-internal",()=>r,"PRIVATE")),{instance:new bS(oS(e,o,void 0,t,s),e),namespace:i}}});const ES=bS.ServerValue;(IS=Cp).INTERNAL.registerComponent(new Kd("database-compat",(e,{instanceIdentifier:t})=>{var n=e.getProvider("app-compat").getImmediate(),r=e.getProvider("database").getImmediate({identifier:t});return new bS(r,n)},"PUBLIC").setServiceProps({Reference:wS,Query:_S,Database:bS,DataSnapshot:yS,enableLogging:uS,INTERNAL:TS,ServerValue:ES}).setMultipleInstances(!0)),IS.registerVersion("@firebase/database-compat","0.1.5");var l="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},kS={},SS=l||self;function CS(){}function AS(e){var t=typeof e;return"array"==(t="object"!=t?t:e?Array.isArray(e)?"array":t:"null")||"object"==t&&"number"==typeof e.length}function NS(e){var t=typeof e;return"object"==t&&null!=e||"function"==t}var RS="closure_uid_"+(1e9*Math.random()>>>0),PS=0;function xS(e,t,n){return e.call.apply(e.bind,arguments)}function OS(t,n,e){if(!t)throw Error();if(2<arguments.length){var r=Array.prototype.slice.call(arguments,2);return function(){var e=Array.prototype.slice.call(arguments);return Array.prototype.unshift.apply(e,r),t.apply(n,e)}}return function(){return t.apply(n,arguments)}}function DS(e,t,n){return(DS=Function.prototype.bind&&-1!=Function.prototype.bind.toString().indexOf("native code")?xS:OS).apply(null,arguments)}function LS(t){var n=Array.prototype.slice.call(arguments,1);return function(){var e=n.slice();return e.push.apply(e,arguments),t.apply(this,e)}}function MS(e,s){function t(){}t.prototype=s.prototype,e.Z=s.prototype,e.prototype=new t,(e.prototype.constructor=e).Vb=function(e,t,n){for(var r=Array(arguments.length-2),i=2;i<arguments.length;i++)r[i-2]=arguments[i];return s.prototype[t].apply(e,r)}}function FS(){this.s=this.s,this.o=this.o}var US={};FS.prototype.s=!1,FS.prototype.na=function(){var e,t;!this.s&&(this.s=!0,this.M(),0)&&(t=this,e=Object.prototype.hasOwnProperty.call(t,RS)&&t[RS]||(t[RS]=++PS),delete US[e])},FS.prototype.M=function(){if(this.o)for(;this.o.length;)this.o.shift()()};const jS=Array.prototype.indexOf?function(e,t){return Array.prototype.indexOf.call(e,t,void 0)}:function(e,t){if("string"==typeof e)return"string"!=typeof t||1!=t.length?-1:e.indexOf(t,0);for(let n=0;n<e.length;n++)if(n in e&&e[n]===t)return n;return-1},qS=Array.prototype.forEach?function(e,t,n){Array.prototype.forEach.call(e,t,n)}:function(e,t,n){var r=e.length,i="string"==typeof e?e.split(""):e;for(let s=0;s<r;s++)s in i&&t.call(n,i[s],s,e)};function VS(){return Array.prototype.concat.apply([],arguments)}function BS(t){var n=t.length;if(0<n){const r=Array(n);for(let e=0;e<n;e++)r[e]=t[e];return r}return[]}function WS(e){return/^[\s\xa0]*$/.test(e)}var zS,KS=String.prototype.trim?function(e){return e.trim()}:function(e){return/^[\s\xa0]*([\s\S]*?)[\s\xa0]*$/.exec(e)[1]};function $S(e,t){return-1!=e.indexOf(t)}function HS(e,t){return e<t?-1:t<e?1:0}e:{var GS=SS.navigator;if(GS){GS=GS.userAgent;if(GS){zS=GS;break e}}zS=""}function QS(e,t,n){for(const r in e)t.call(n,e[r],r,e)}function YS(e){const t={};for(const n in e)t[n]=e[n];return t}var XS="constructor hasOwnProperty isPrototypeOf propertyIsEnumerable toLocaleString toString valueOf".split(" ");function JS(t){let n,r;for(let i=1;i<arguments.length;i++){for(n in r=arguments[i])t[n]=r[n];for(let e=0;e<XS.length;e++)n=XS[e],Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=r[n])}}function ZS(e){return ZS[" "](e),e}ZS[" "]=CS;var eC,tC=$S(zS,"Opera"),nC=$S(zS,"Trident")||$S(zS,"MSIE"),rC=$S(zS,"Edge"),iC=rC||nC,sC=$S(zS,"Gecko")&&!($S(zS.toLowerCase(),"webkit")&&!$S(zS,"Edge"))&&!($S(zS,"Trident")||$S(zS,"MSIE"))&&!$S(zS,"Edge"),oC=$S(zS.toLowerCase(),"webkit")&&!$S(zS,"Edge");function aC(){var e=SS.document;return e?e.documentMode:void 0}e:{var cC="",lC=(lC=zS,sC?/rv:([^\);]+)(\)|;)/.exec(lC):rC?/Edge\/([\d\.]+)/.exec(lC):nC?/\b(?:MSIE|rv)[: ]([^\);]+)(\)|;)/.exec(lC):oC?/WebKit\/(\S+)/.exec(lC):tC?/(?:Version)[ \/]?(\S+)/.exec(lC):void 0);if(lC&&(cC=lC?lC[1]:""),nC){lC=aC();if(null!=lC&&lC>parseFloat(cC)){eC=String(lC);break e}}eC=cC}var uC={};function hC(){return e=function(){let e=0;var t=KS(String(eC)).split("."),n=KS("9").split("."),r=Math.max(t.length,n.length);for(let o=0;0==e&&o<r;o++)for(var i=t[o]||"",s=n[o]||"";i=/(\d*)(\D*)(.*)/.exec(i)||["","","",""],s=/(\d*)(\D*)(.*)/.exec(s)||["","","",""],(0!=i[0].length||0!=s[0].length)&&(e=HS(0==i[1].length?0:parseInt(i[1],10),0==s[1].length?0:parseInt(s[1],10))||HS(0==i[2].length,0==s[2].length)||HS(i[2],s[2]),i=i[3],s=s[3],0==e););return 0<=e},t=uC,Object.prototype.hasOwnProperty.call(t,9)?t[9]:t[9]=e(9);var e,t}var dC=SS.document&&nC&&(aC()||parseInt(eC,10))||void 0,pC=function(){if(!SS.addEventListener||!Object.defineProperty)return!1;var e=!1,t=Object.defineProperty({},"passive",{get:function(){e=!0}});try{SS.addEventListener("test",CS,t),SS.removeEventListener("test",CS,t)}catch(e){}return e}();function fC(e,t){this.type=e,this.g=this.target=t,this.defaultPrevented=!1}function gC(e,t){if(fC.call(this,e?e.type:""),this.relatedTarget=this.g=this.target=null,this.button=this.screenY=this.screenX=this.clientY=this.clientX=0,this.key="",this.metaKey=this.shiftKey=this.altKey=this.ctrlKey=!1,this.state=null,this.pointerId=0,this.pointerType="",this.i=null,e){var n=this.type=e.type,r=e.changedTouches&&e.changedTouches.length?e.changedTouches[0]:null;if(this.target=e.target||e.srcElement,this.g=t,t=e.relatedTarget){if(sC){e:{try{ZS(t.nodeName);var i=!0;break e}catch(e){}i=!1}i||(t=null)}}else"mouseover"==n?t=e.fromElement:"mouseout"==n&&(t=e.toElement);this.relatedTarget=t,r?(this.clientX=void 0!==r.clientX?r.clientX:r.pageX,this.clientY=void 0!==r.clientY?r.clientY:r.pageY,this.screenX=r.screenX||0,this.screenY=r.screenY||0):(this.clientX=void 0!==e.clientX?e.clientX:e.pageX,this.clientY=void 0!==e.clientY?e.clientY:e.pageY,this.screenX=e.screenX||0,this.screenY=e.screenY||0),this.button=e.button,this.key=e.key||"",this.ctrlKey=e.ctrlKey,this.altKey=e.altKey,this.shiftKey=e.shiftKey,this.metaKey=e.metaKey,this.pointerId=e.pointerId||0,this.pointerType="string"==typeof e.pointerType?e.pointerType:mC[e.pointerType]||"",this.state=e.state,(this.i=e).defaultPrevented&&gC.Z.h.call(this)}}fC.prototype.h=function(){this.defaultPrevented=!0},MS(gC,fC);var mC={2:"touch",3:"pen",4:"mouse"};gC.prototype.h=function(){gC.Z.h.call(this);var e=this.i;e.preventDefault?e.preventDefault():e.returnValue=!1};var vC="closure_listenable_"+(1e6*Math.random()|0),yC=0;function _C(e,t,n,r,i){this.listener=e,this.proxy=null,this.src=t,this.type=n,this.capture=!!r,this.ia=i,this.key=++yC,this.ca=this.fa=!1}function wC(e){e.ca=!0,e.listener=null,e.proxy=null,e.src=null,e.ia=null}function bC(e){this.src=e,this.g={},this.h=0}function IC(e,t){var n,r,i,s=t.type;s in e.g&&(n=e.g[s],(i=0<=(r=jS(n,t)))&&Array.prototype.splice.call(n,r,1),i&&(wC(t),0==e.g[s].length&&(delete e.g[s],e.h--)))}function TC(e,t,n,r){for(var i=0;i<e.length;++i){var s=e[i];if(!s.ca&&s.listener==t&&s.capture==!!n&&s.ia==r)return i}return-1}bC.prototype.add=function(e,t,n,r,i){var s=e.toString();(e=this.g[s])||(e=this.g[s]=[],this.h++);var o=TC(e,t,r,i);return-1<o?(t=e[o],n||(t.fa=!1)):((t=new _C(t,this.src,s,!!r,i)).fa=n,e.push(t)),t};var EC="closure_lm_"+(1e6*Math.random()|0),kC={};function SC(e,t,n,r,i){if(r&&r.once)return function e(t,n,r,i,s){if(Array.isArray(n)){for(var o=0;o<n.length;o++)e(t,n[o],r,i,s);return null}r=OC(r);return t&&t[vC]?t.O(n,r,NS(i)?!!i.capture:!!i,s):CC(t,n,r,!0,i,s)}(e,t,n,r,i);if(Array.isArray(t)){for(var s=0;s<t.length;s++)SC(e,t[s],n,r,i);return null}return n=OC(n),e&&e[vC]?e.N(t,n,NS(r)?!!r.capture:!!r,i):CC(e,t,n,!1,r,i)}function CC(e,t,n,r,i,s){if(!t)throw Error("Invalid event type");var o,a=NS(i)?!!i.capture:!!i,c=PC(e);if(c||(e[EC]=c=new bC(e)),(n=c.add(t,n,r,a,s)).proxy)return n;if(o=RC,r=function e(t){return o.call(e.src,e.listener,t)},(n.proxy=r).src=e,r.listener=n,e.addEventListener)void 0===(i=!pC?a:i)&&(i=!1),e.addEventListener(t.toString(),r,i);else if(e.attachEvent)e.attachEvent(NC(t.toString()),r);else{if(!e.addListener||!e.removeListener)throw Error("addEventListener and attachEvent are unavailable.");e.addListener(r)}return n}function AC(e){var t,n,r;"number"!=typeof e&&e&&!e.ca&&((t=e.src)&&t[vC]?IC(t.i,e):(n=e.type,r=e.proxy,t.removeEventListener?t.removeEventListener(n,r,e.capture):t.detachEvent?t.detachEvent(NC(n),r):t.addListener&&t.removeListener&&t.removeListener(r),(n=PC(t))?(IC(n,e),0==n.h&&(n.src=null,t[EC]=null)):wC(e)))}function NC(e){return e in kC?kC[e]:kC[e]="on"+e}function RC(e,t){var n,r;return e=!!e.ca||(t=new gC(t,this),n=e.listener,r=e.ia||e.src,e.fa&&AC(e),n.call(r,t))}function PC(e){return(e=e[EC])instanceof bC?e:null}var xC="__closure_events_fn_"+(1e9*Math.random()>>>0);function OC(t){return"function"==typeof t?t:(t[xC]||(t[xC]=function(e){return t.handleEvent(e)}),t[xC])}function DC(){FS.call(this),this.i=new bC(this),(this.P=this).I=null}function LC(e,t){var n,r=e.I;if(r)for(n=[];r;r=r.I)n.push(r);if(e=e.P,r=t.type||t,"string"==typeof t?t=new fC(t,e):t instanceof fC?t.target=t.target||e:(o=t,JS(t=new fC(r,e),o)),o=!0,n)for(var i=n.length-1;0<=i;i--)var s=t.g=n[i],o=MC(s,r,!0,t)&&o;if(o=MC(s=t.g=e,r,!0,t)&&o,o=MC(s,r,!1,t)&&o,n)for(i=0;i<n.length;i++)o=MC(s=t.g=n[i],r,!1,t)&&o}function MC(e,t,n,r){if(!(t=e.i.g[String(t)]))return!0;t=t.concat();for(var i=!0,s=0;s<t.length;++s){var o,a,c=t[s];c&&!c.ca&&c.capture==n&&(o=c.listener,a=c.ia||c.src,c.fa&&IC(e.i,c),i=!1!==o.call(a,r)&&i)}return i&&!r.defaultPrevented}MS(DC,FS),DC.prototype[vC]=!0,DC.prototype.removeEventListener=function(e,t,n,r){!function e(t,n,r,i,s){if(Array.isArray(n))for(var o=0;o<n.length;o++)e(t,n[o],r,i,s);else i=NS(i)?!!i.capture:!!i,r=OC(r),t&&t[vC]?(t=t.i,(n=String(n).toString())in t.g&&-1<(r=TC(o=t.g[n],r,i,s))&&(wC(o[r]),Array.prototype.splice.call(o,r,1),0==o.length&&(delete t.g[n],t.h--))):(t=t&&PC(t))&&(n=t.g[n.toString()],(r=(t=-1)<(t=n?TC(n,r,i,s):t)?n[t]:null)&&AC(r))}(this,e,t,n,r)},DC.prototype.M=function(){if(DC.Z.M.call(this),this.i){var e,t=this.i;for(e in t.g){for(var n=t.g[e],r=0;r<n.length;r++)wC(n[r]);delete t.g[e],t.h--}}this.I=null},DC.prototype.N=function(e,t,n,r){return this.i.add(String(e),t,!1,n,r)},DC.prototype.O=function(e,t,n,r){return this.i.add(String(e),t,!0,n,r)};var FC=SS.JSON.stringify;var UC,jC=new class{constructor(e,t){this.i=e,this.j=t,this.h=0,this.g=null}get(){let e;return 0<this.h?(this.h--,e=this.g,this.g=e.next,e.next=null):e=this.i(),e}}(()=>new qC,e=>e.reset());class qC{constructor(){this.next=this.g=this.h=null}set(e,t){this.h=e,this.g=t,this.next=null}reset(){this.next=this.g=this.h=null}}function VC(e,t){var n;UC||(n=SS.Promise.resolve(void 0),UC=function(){n.then(zC)}),BC||(UC(),BC=!0),WC.add(e,t)}var BC=!1,WC=new class{constructor(){this.h=this.g=null}add(e,t){const n=jC.get();n.set(e,t),this.h?this.h.next=n:this.g=n,this.h=n}};function zC(){for(var e;e=function(){var e=WC;let t=null;return e.g&&(t=e.g,e.g=e.g.next,e.g||(e.h=null),t.next=null),t}();){try{e.h.call(e.g)}catch(e){!function(e){SS.setTimeout(()=>{throw e},0)}(e)}var t=jC;t.j(e),t.h<100&&(t.h++,e.next=t.g,t.g=e)}BC=!1}function KC(e,t){DC.call(this),this.h=e||1,this.g=t||SS,this.j=DS(this.kb,this),this.l=Date.now()}function $C(e){e.da=!1,e.S&&(e.g.clearTimeout(e.S),e.S=null)}function HC(e,t,n){if("function"==typeof e)n&&(e=DS(e,n));else{if(!e||"function"!=typeof e.handleEvent)throw Error("Invalid listener argument");e=DS(e.handleEvent,e)}return 2147483647<Number(t)?-1:SS.setTimeout(e,t||0)}MS(KC,DC),($e=KC.prototype).da=!1,$e.S=null,$e.kb=function(){var e;this.da&&(0<(e=Date.now()-this.l)&&e<.8*this.h?this.S=this.g.setTimeout(this.j,this.h-e):(this.S&&(this.g.clearTimeout(this.S),this.S=null),LC(this,"tick"),this.da&&($C(this),this.start())))},$e.start=function(){this.da=!0,this.S||(this.S=this.g.setTimeout(this.j,this.h),this.l=Date.now())},$e.M=function(){KC.Z.M.call(this),$C(this),delete this.g};class GC extends FS{constructor(e,t){super(),this.m=e,this.j=t,this.h=null,this.i=!1,this.g=null}l(e){this.h=arguments,this.g?this.i=!0:function e(t){t.g=HC(()=>{t.g=null,t.i&&(t.i=!1,e(t))},t.j);var n=t.h;t.h=null,t.m.apply(null,n)}(this)}M(){super.M(),this.g&&(SS.clearTimeout(this.g),this.g=null,this.i=!1,this.h=null)}}function QC(e){FS.call(this),this.h=e,this.g={}}MS(QC,FS);var YC=[];function XC(e,t,n,r){Array.isArray(n)||(n&&(YC[0]=n.toString()),n=YC);for(var i=0;i<n.length;i++){var s=SC(t,n[i],r||e.handleEvent,!1,e.h||e);if(!s)break;e.g[s.key]=s}}function JC(e){QS(e.g,function(e,t){this.g.hasOwnProperty(t)&&AC(e)},e),e.g={}}function ZC(){this.g=!0}function eA(e,t,n,r){e.info(function(){return"XMLHTTP TEXT ("+t+"): "+function(e,t){if(!e.g)return t;if(!t)return null;try{var n=JSON.parse(t);if(n)for(e=0;e<n.length;e++)if(Array.isArray(n[e])){var r=n[e];if(!(r.length<2)){var i=r[1];if(Array.isArray(i)&&!(i.length<1)){var s=i[0];if("noop"!=s&&"stop"!=s&&"close"!=s)for(var o=1;o<i.length;o++)i[o]=""}}}return FC(n)}catch(e){return t}}(e,n)+(r?" "+r:"")})}QC.prototype.M=function(){QC.Z.M.call(this),JC(this)},QC.prototype.handleEvent=function(){throw Error("EventHandler.handleEvent not implemented")},ZC.prototype.Aa=function(){this.g=!1},ZC.prototype.info=function(){};var tA={},nA=null;function rA(){return nA=nA||new DC}function iA(e){fC.call(this,tA.Ma,e)}function sA(){var e=rA();LC(e,new iA(e))}function oA(e,t){fC.call(this,tA.STAT_EVENT,e),this.stat=t}function aA(e){var t=rA();LC(t,new oA(t,e))}function cA(e,t){fC.call(this,tA.Na,e),this.size=t}function lA(e,t){if("function"!=typeof e)throw Error("Fn must not be null and must be a function");return SS.setTimeout(function(){e()},t)}tA.Ma="serverreachability",MS(iA,fC),tA.STAT_EVENT="statevent",MS(oA,fC),tA.Na="timingevent",MS(cA,fC);c={NO_ERROR:0,lb:1,yb:2,xb:3,sb:4,wb:5,zb:6,Ja:7,TIMEOUT:8,Cb:9},yt={qb:"complete",Mb:"success",Ka:"error",Ja:"abort",Eb:"ready",Fb:"readystatechange",TIMEOUT:"timeout",Ab:"incrementaldata",Db:"progress",tb:"downloadprogress",Ub:"uploadprogress"};function uA(){}function hA(e){return e.h||(e.h=e.i())}function dA(){}uA.prototype.h=null;l={OPEN:"a",pb:"b",Ka:"c",Bb:"d"};function pA(){fC.call(this,"d")}function fA(){fC.call(this,"c")}function gA(){}function mA(e,t,n,r){this.l=e,this.j=t,this.m=n,this.X=r||1,this.V=new QC(this),this.P=_A,this.W=new KC(e=iC?125:void 0),this.H=null,this.i=!1,this.s=this.A=this.v=this.K=this.F=this.Y=this.B=null,this.D=[],this.g=null,this.C=0,this.o=this.u=null,this.N=-1,this.I=!1,this.O=0,this.L=null,this.aa=this.J=this.$=this.U=!1,this.h=new vA}function vA(){this.i=null,this.g="",this.h=!1}MS(pA,fC),MS(fA,fC),MS(gA,uA),gA.prototype.g=function(){return new XMLHttpRequest},gA.prototype.i=function(){return{}};var yA=new gA,_A=45e3,wA={},bA={};function IA(e,t,n){e.K=1,e.v=zA(UA(t)),e.s=n,e.U=!0,TA(e,null)}function TA(e,t){e.F=Date.now(),SA(e),e.A=UA(e.v);var o,a,c,l,u,h,n=e.A,r=e.X;Array.isArray(r)||(r=[String(r)]),rN(n.h,"t",r),e.C=0,n=e.l.H,e.h=new vA,e.g=rR(e.l,n?t:null,!e.s),0<e.O&&(e.L=new GC(DS(e.Ia,e,e.g),e.O)),XC(e.V,e.g,"readystatechange",e.gb),t=e.H?YS(e.H):{},e.s?(e.u||(e.u="POST"),t["Content-Type"]="application/x-www-form-urlencoded",e.g.ea(e.A,e.u,e.s,t)):(e.u="GET",e.g.ea(e.A,e.u,null,t)),sA(),o=e.j,a=e.u,c=e.A,l=e.m,u=e.X,h=e.s,o.info(function(){if(o.g)if(h)for(var e="",t=h.split("&"),n=0;n<t.length;n++){var r,i,s=t[n].split("=");1<s.length&&(r=s[0],s=s[1],e=2<=(i=r.split("_")).length&&"type"==i[1]?e+(r+"=")+s+"&":e+(r+"=redacted&"))}else e=null;else e=h;return"XMLHTTP REQ ("+l+") [attempt "+u+"]: "+a+"\n"+c+"\n"+e})}function EA(e){return e.g&&("GET"==e.u&&2!=e.K&&e.l.Ba)}function kA(e,t,n){let r=!0,i;for(;!e.I&&e.C<n.length;){if(i=(o=n,c=a=void 0,a=(s=e).C,-1==(c=o.indexOf("\n",a))?bA:(a=Number(o.substring(a,c)),isNaN(a)?wA:(c+=1)+a>o.length?bA:(o=o.substr(c,a),s.C=c+a,o))),i==bA){4==t&&(e.o=4,aA(14),r=!1),eA(e.j,e.m,null,"[Incomplete Response]");break}if(i==wA){e.o=4,aA(15),eA(e.j,e.m,n,"[Invalid Chunk]"),r=!1;break}eA(e.j,e.m,i,null),PA(e,i)}var s,o,a,c;EA(e)&&i!=bA&&i!=wA&&(e.h.g="",e.C=0),4!=t||0!=n.length||e.h.h||(e.o=1,aA(16),r=!1),e.i=e.i&&r,r?0<n.length&&!e.aa&&(e.aa=!0,(t=e.l).g==e&&t.$&&!t.L&&(t.h.info("Great, no buffering proxy detected. Bytes received: "+n.length),QN(t),t.L=!0,aA(11))):(eA(e.j,e.m,n,"[Invalid Chunked Response]"),RA(e),NA(e))}function SA(e){e.Y=Date.now()+e.P,CA(e,e.P)}function CA(e,t){if(null!=e.B)throw Error("WatchDog timer not null");e.B=lA(DS(e.eb,e),t)}function AA(e){e.B&&(SS.clearTimeout(e.B),e.B=null)}function NA(e){0==e.l.G||e.I||JN(e.l,e)}function RA(e){AA(e);var t=e.L;t&&"function"==typeof t.na&&t.na(),e.L=null,$C(e.W),JC(e.V),e.g&&(t=e.g,e.g=null,t.abort(),t.na())}function PA(e,t){try{var n=e.l;if(0!=n.G&&(n.g==e||uN(n.i,e)))if(n.I=e.N,!e.J&&uN(n.i,e)&&3==n.G){try{var r=n.Ca.g.parse(t)}catch(e){r=null}if(Array.isArray(r)&&3==r.length){var i=r;if(0==i[0]){e:if(!n.u){if(n.g){if(!(n.g.F+3e3<e.F))break e;XN(n),qN(n)}GN(n),aA(18)}}else n.ta=i[1],0<n.ta-n.U&&i[2]<37500&&n.N&&0==n.A&&!n.v&&(n.v=lA(DS(n.ab,n),6e3));if(lN(n.i)<=1&&n.ka){try{n.ka()}catch(e){}n.ka=void 0}}else eR(n,11)}else if(!e.J&&n.g!=e||XN(n),!WS(t))for(i=n.Ca.g.parse(t),t=0;t<i.length;t++){var s=i[t];if(n.U=s[0],s=s[1],2==n.G)if("c"==s[0]){n.J=s[1],n.la=s[2];var o=s[3];null!=o&&(n.ma=o,n.h.info("VER="+n.ma));var a=s[4];null!=a&&(n.za=a,n.h.info("SVER="+n.za));var c,l,u,h=s[5];null!=h&&"number"==typeof h&&0<h&&(r=1.5*h,n.K=r,n.h.info("backChannelRequestTimeoutMs_="+r)),r=n;const g=e.g;g&&(!(c=g.g?g.g.getResponseHeader("X-Client-Wire-Protocol"):null)||!(l=r.i).g&&($S(c,"spdy")||$S(c,"quic")||$S(c,"h2"))&&(l.j=l.l,l.g=new Set,l.h&&(hN(l,l.h),l.h=null)),!r.D||(u=g.g?g.g.getResponseHeader("X-HTTP-Session-Id"):null)&&(r.sa=u,WA(r.F,r.D,u))),n.G=3,n.j&&n.j.xa(),n.$&&(n.O=Date.now()-e.F,n.h.info("Handshake RTT: "+n.O+"ms"));var d,p,f=e;(r=n).oa=nR(r,r.H?r.la:null,r.W),f.J?(dN(r.i,f),d=f,(p=r.K)&&d.setTimeout(p),d.B&&(AA(d),SA(d)),r.g=f):HN(r),0<n.l.length&&WN(n)}else"stop"!=s[0]&&"close"!=s[0]||eR(n,7);else 3==n.G&&("stop"==s[0]||"close"==s[0]?"stop"==s[0]?eR(n,7):jN(n):"noop"!=s[0]&&n.j&&n.j.wa(s),n.A=0)}sA()}catch(e){}}function xA(e,t){if(e.forEach&&"function"==typeof e.forEach)e.forEach(t,void 0);else if(AS(e)||"string"==typeof e)qS(e,t,void 0);else{if(e.T&&"function"==typeof e.T)var n=e.T();else if(e.R&&"function"==typeof e.R)n=void 0;else if(AS(e)||"string"==typeof e)for(var n=[],r=e.length,i=0;i<r;i++)n.push(i);else for(i in n=[],r=0,e)n[r++]=i;for(var i=(r=function(e){if(e.R&&"function"==typeof e.R)return e.R();if("string"==typeof e)return e.split("");if(AS(e)){for(var t=[],n=e.length,r=0;r<n;r++)t.push(e[r]);return t}for(r in t=[],n=0,e)t[n++]=e[r];return t}(e)).length,s=0;s<i;s++)t.call(void 0,r[s],n&&n[s],e)}}function OA(e,t){this.h={},this.g=[],this.i=0;var n=arguments.length;if(1<n){if(n%2)throw Error("Uneven number of arguments");for(var r=0;r<n;r+=2)this.set(arguments[r],arguments[r+1])}else if(e)if(e instanceof OA)for(n=e.T(),r=0;r<n.length;r++)this.set(n[r],e.get(n[r]));else for(r in e)this.set(r,e[r])}function DA(e){if(e.i!=e.g.length){for(var t=0,n=0;t<e.g.length;){var r=e.g[t];LA(e.h,r)&&(e.g[n++]=r),t++}e.g.length=n}if(e.i!=e.g.length){for(var i={},n=t=0;t<e.g.length;)LA(i,r=e.g[t])||(i[e.g[n++]=r]=1),t++;e.g.length=n}}function LA(e,t){return Object.prototype.hasOwnProperty.call(e,t)}($e=mA.prototype).setTimeout=function(e){this.P=e},$e.gb=function(e){e=e.target;const t=this.L;t&&3==DN(e)?t.l():this.Ia(e)},$e.Ia=function(e){try{if(e==this.g)e:{var t=DN(this.g),n=this.g.Da();this.g.ba();if(!(t<3)&&(3!=t||iC||this.g&&(this.h.h||this.g.ga()||LN(this.g)))){this.I||4!=t||7==n||sA(),AA(this);var r=this.g.ba();this.N=r;t:if(EA(this)){var i=LN(this.g);e="";var s=i.length,o=4==DN(this.g);if(!this.h.i){if("undefined"==typeof TextDecoder){RA(this),NA(this);var a="";break t}this.h.i=new SS.TextDecoder}for(n=0;n<s;n++)this.h.h=!0,e+=this.h.i.decode(i[n],{stream:o&&n==s-1});i.splice(0,s),this.h.g+=e,this.C=0,a=this.h.g}else a=this.g.ga();if(this.i=200==r,h=this.j,d=this.u,p=this.A,f=this.m,g=this.X,m=t,v=r,h.info(function(){return"XMLHTTP RESP ("+f+") [ attempt "+g+"]: "+d+"\n"+p+"\n"+m+" "+v}),this.i){if(this.$&&!this.J){t:{if(this.g){var c,l=this.g;if((c=l.g?l.g.getResponseHeader("X-HTTP-Initial-Response"):null)&&!WS(c)){var u=c;break t}}u=null}if(!(r=u)){this.i=!1,this.o=3,aA(12),RA(this),NA(this);break e}eA(this.j,this.m,r,"Initial handshake response via X-HTTP-Initial-Response"),this.J=!0,PA(this,r)}this.U?(kA(this,t,a),iC&&this.i&&3==t&&(XC(this.V,this.W,"tick",this.fb),this.W.start())):(eA(this.j,this.m,a,null),PA(this,a)),4==t&&RA(this),this.i&&!this.I&&(4==t?JN(this.l,this):(this.i=!1,SA(this)))}else 400==r&&0<a.indexOf("Unknown SID")?(this.o=3,aA(12)):(this.o=0,aA(13)),RA(this),NA(this)}}}catch(e){}var h,d,p,f,g,m,v},$e.fb=function(){var e,t;this.g&&(e=DN(this.g),t=this.g.ga(),this.C<t.length&&(AA(this),kA(this,e,t),this.i&&4!=e&&SA(this)))},$e.cancel=function(){this.I=!0,RA(this)},$e.eb=function(){this.B=null;var e,t,n=Date.now();0<=n-this.Y?(e=this.j,t=this.A,e.info(function(){return"TIMEOUT: "+t}),2!=this.K&&(sA(),aA(17)),RA(this),this.o=2,NA(this)):CA(this,this.Y-n)},($e=OA.prototype).R=function(){DA(this);for(var e=[],t=0;t<this.g.length;t++)e.push(this.h[this.g[t]]);return e},$e.T=function(){return DA(this),this.g.concat()},$e.get=function(e,t){return LA(this.h,e)?this.h[e]:t},$e.set=function(e,t){LA(this.h,e)||(this.i++,this.g.push(e)),this.h[e]=t},$e.forEach=function(e,t){for(var n=this.T(),r=0;r<n.length;r++){var i=n[r],s=this.get(i);e.call(t,s,i,this)}};var MA=/^(?:([^:/?#.]+):)?(?:\/\/(?:([^\\/?#]*)@)?([^\\/?#]*?)(?::([0-9]+))?(?=[\\/?#]|$))?([^?#]+)?(?:\?([^#]*))?(?:#([\s\S]*))?$/;function FA(e,t){var n;this.i=this.s=this.j="",this.m=null,this.o=this.l="",this.g=!1,e instanceof FA?(this.g=void 0!==t?t:e.g,jA(this,e.j),this.s=e.s,qA(this,e.i),VA(this,e.m),this.l=e.l,t=e.h,(n=new ZA).i=t.i,t.g&&(n.g=new OA(t.g),n.h=t.h),BA(this,n),this.o=e.o):e&&(n=String(e).match(MA))?(this.g=!!t,jA(this,n[1]||"",!0),this.s=KA(n[2]||""),qA(this,n[3]||"",!0),VA(this,n[4]),this.l=KA(n[5]||"",!0),BA(this,n[6]||"",!0),this.o=KA(n[7]||"")):(this.g=!!t,this.h=new ZA(null,this.g))}function UA(e){return new FA(e)}function jA(e,t,n){e.j=n?KA(t,!0):t,e.j&&(e.j=e.j.replace(/:$/,""))}function qA(e,t,n){e.i=n?KA(t,!0):t}function VA(e,t){if(t){if(t=Number(t),isNaN(t)||t<0)throw Error("Bad port number "+t);e.m=t}else e.m=null}function BA(e,t,n){var r,i;t instanceof ZA?(e.h=t,r=e.h,(i=e.g)&&!r.j&&(eN(r),r.i=null,r.g.forEach(function(e,t){var n=t.toLowerCase();t!=n&&(tN(this,t),rN(this,n,e))},r)),r.j=i):(n||(t=$A(t,XA)),e.h=new ZA(t,e.g))}function WA(e,t,n){e.h.set(t,n)}function zA(e){return WA(e,"zx",Math.floor(2147483648*Math.random()).toString(36)+Math.abs(Math.floor(2147483648*Math.random())^Date.now()).toString(36)),e}function KA(e,t){return e?t?decodeURI(e.replace(/%25/g,"%2525")):decodeURIComponent(e):""}function $A(e,t,n){return"string"==typeof e?(e=encodeURI(e).replace(t,HA),e=n?e.replace(/%25([0-9a-fA-F]{2})/g,"%$1"):e):null}function HA(e){return"%"+((e=e.charCodeAt(0))>>4&15).toString(16)+(15&e).toString(16)}FA.prototype.toString=function(){var e=[],t=this.j;t&&e.push($A(t,GA,!0),":");var n=this.i;return!n&&"file"!=t||(e.push("//"),(t=this.s)&&e.push($A(t,GA,!0),"@"),e.push(encodeURIComponent(String(n)).replace(/%25([0-9a-fA-F]{2})/g,"%$1")),null!=(n=this.m)&&e.push(":",String(n))),(n=this.l)&&(this.i&&"/"!=n.charAt(0)&&e.push("/"),e.push($A(n,"/"==n.charAt(0)?YA:QA,!0))),(n=this.h.toString())&&e.push("?",n),(n=this.o)&&e.push("#",$A(n,JA)),e.join("")};var GA=/[#\/\?@]/g,QA=/[#\?:]/g,YA=/[#\?]/g,XA=/[#\?@]/g,JA=/#/g;function ZA(e,t){this.h=this.g=null,this.i=e||null,this.j=!!t}function eN(n){n.g||(n.g=new OA,n.h=0,n.i&&function(e,t){if(e){e=e.split("&");for(var n=0;n<e.length;n++){var r,i=e[n].indexOf("="),s=null;0<=i?(r=e[n].substring(0,i),s=e[n].substring(i+1)):r=e[n],t(r,s?decodeURIComponent(s.replace(/\+/g," ")):"")}}}(n.i,function(e,t){n.add(decodeURIComponent(e.replace(/\+/g," ")),t)}))}function tN(e,t){eN(e),t=iN(e,t),LA(e.g.h,t)&&(e.i=null,e.h-=e.g.get(t).length,LA((e=e.g).h,t)&&(delete e.h[t],e.i--,e.g.length>2*e.i&&DA(e)))}function nN(e,t){return eN(e),t=iN(e,t),LA(e.g.h,t)}function rN(e,t,n){tN(e,t),0<n.length&&(e.i=null,e.g.set(iN(e,t),BS(n)),e.h+=n.length)}function iN(e,t){return t=String(t),t=e.j?t.toLowerCase():t}($e=ZA.prototype).add=function(e,t){eN(this),this.i=null,e=iN(this,e);var n=this.g.get(e);return n||this.g.set(e,n=[]),n.push(t),this.h+=1,this},$e.forEach=function(n,r){eN(this),this.g.forEach(function(e,t){qS(e,function(e){n.call(r,e,t,this)},this)},this)},$e.T=function(){eN(this);for(var e=this.g.R(),t=this.g.T(),n=[],r=0;r<t.length;r++)for(var i=e[r],s=0;s<i.length;s++)n.push(t[r]);return n},$e.R=function(e){eN(this);var t=[];if("string"==typeof e)nN(this,e)&&(t=VS(t,this.g.get(iN(this,e))));else{e=this.g.R();for(var n=0;n<e.length;n++)t=VS(t,e[n])}return t},$e.set=function(e,t){return eN(this),this.i=null,nN(this,e=iN(this,e))&&(this.h-=this.g.get(e).length),this.g.set(e,[t]),this.h+=1,this},$e.get=function(e,t){return e&&0<(e=this.R(e)).length?String(e[0]):t},$e.toString=function(){if(this.i)return this.i;if(!this.g)return"";for(var e=[],t=this.g.T(),n=0;n<t.length;n++)for(var r=t[n],i=encodeURIComponent(String(r)),r=this.R(r),s=0;s<r.length;s++){var o=i;""!==r[s]&&(o+="="+encodeURIComponent(String(r[s]))),e.push(o)}return this.i=e.join("&")};var sN=class{constructor(e,t){this.h=e,this.g=t}};function oN(e){this.l=e||10,e=SS.PerformanceNavigationTiming?0<(e=SS.performance.getEntriesByType("navigation")).length&&("hq"==e[0].nextHopProtocol||"h2"==e[0].nextHopProtocol):!!(SS.g&&SS.g.Ea&&SS.g.Ea()&&SS.g.Ea().Zb),this.j=e?this.l:1,this.g=null,1<this.j&&(this.g=new Set),this.h=null,this.i=[]}var aN;function cN(e){return e.h||e.g&&e.g.size>=e.j}function lN(e){return e.h?1:e.g?e.g.size:0}function uN(e,t){return e.h?e.h==t:e.g&&e.g.has(t)}function hN(e,t){e.g?e.g.add(t):e.h=t}function dN(e,t){e.h&&e.h==t?e.h=null:e.g&&e.g.has(t)&&e.g.delete(t)}function pN(t){if(null!=t.h)return t.i.concat(t.h.D);if(null==t.g||0===t.g.size)return BS(t.i);{let e=t.i;for(const n of t.g.values())e=e.concat(n.D);return e}}function fN(){}function gN(){this.g=new fN}function mN(e,t,n,r,i){try{t.onload=null,t.onerror=null,t.onabort=null,t.ontimeout=null,i(r)}catch(e){}}function vN(e){this.l=e.$b||null,this.j=e.ib||!1}function yN(e,t){DC.call(this),this.D=e,this.u=t,this.m=void 0,this.readyState=_N,this.status=0,this.responseType=this.responseText=this.response=this.statusText="",this.onreadystatechange=null,this.v=new Headers,this.h=null,this.C="GET",this.B="",this.g=!1,this.A=this.j=this.l=null}oN.prototype.cancel=function(){if(this.i=pN(this),this.h)this.h.cancel(),this.h=null;else if(this.g&&0!==this.g.size){for(const e of this.g.values())e.cancel();this.g.clear()}},fN.prototype.stringify=function(e){return SS.JSON.stringify(e,void 0)},fN.prototype.parse=function(e){return SS.JSON.parse(e,void 0)},MS(vN,uA),vN.prototype.g=function(){return new yN(this.l,this.j)},vN.prototype.i=(aN={},function(){return aN}),MS(yN,DC);var _N=0;function wN(e){e.j.read().then(e.Sa.bind(e)).catch(e.ha.bind(e))}function bN(e){e.readyState=4,e.l=null,e.j=null,e.A=null,IN(e)}function IN(e){e.onreadystatechange&&e.onreadystatechange.call(e)}($e=yN.prototype).open=function(e,t){if(this.readyState!=_N)throw this.abort(),Error("Error reopening a connection");this.C=e,this.B=t,this.readyState=1,IN(this)},$e.send=function(e){if(1!=this.readyState)throw this.abort(),Error("need to call open() first. ");this.g=!0;const t={headers:this.v,method:this.C,credentials:this.m,cache:void 0};e&&(t.body=e),(this.D||SS).fetch(new Request(this.B,t)).then(this.Va.bind(this),this.ha.bind(this))},$e.abort=function(){this.response=this.responseText="",this.v=new Headers,this.status=0,this.j&&this.j.cancel("Request was aborted."),1<=this.readyState&&this.g&&4!=this.readyState&&(this.g=!1,bN(this)),this.readyState=_N},$e.Va=function(e){if(this.g&&(this.l=e,this.h||(this.status=this.l.status,this.statusText=this.l.statusText,this.h=e.headers,this.readyState=2,IN(this)),this.g&&(this.readyState=3,IN(this),this.g)))if("arraybuffer"===this.responseType)e.arrayBuffer().then(this.Ta.bind(this),this.ha.bind(this));else if(void 0!==SS.ReadableStream&&"body"in e){if(this.j=e.body.getReader(),this.u){if(this.responseType)throw Error('responseType must be empty for "streamBinaryChunks" mode responses.');this.response=[]}else this.response=this.responseText="",this.A=new TextDecoder;wN(this)}else e.text().then(this.Ua.bind(this),this.ha.bind(this))},$e.Sa=function(e){var t;this.g&&(this.u&&e.value?this.response.push(e.value):this.u||(t=e.value||new Uint8Array(0),(t=this.A.decode(t,{stream:!e.done}))&&(this.response=this.responseText+=t)),(e.done?bN:IN)(this),3==this.readyState&&wN(this))},$e.Ua=function(e){this.g&&(this.response=this.responseText=e,bN(this))},$e.Ta=function(e){this.g&&(this.response=e,bN(this))},$e.ha=function(){this.g&&bN(this)},$e.setRequestHeader=function(e,t){this.v.append(e,t)},$e.getResponseHeader=function(e){return this.h&&this.h.get(e.toLowerCase())||""},$e.getAllResponseHeaders=function(){if(!this.h)return"";const e=[],t=this.h.entries();for(var n=t.next();!n.done;)n=n.value,e.push(n[0]+": "+n[1]),n=t.next();return e.join("\r\n")},Object.defineProperty(yN.prototype,"withCredentials",{get:function(){return"include"===this.m},set:function(e){this.m=e?"include":"same-origin"}});var TN=SS.JSON.parse;function EN(e){DC.call(this),this.headers=new OA,this.u=e||null,this.h=!1,this.C=this.g=null,this.H="",this.m=0,this.j="",this.l=this.F=this.v=this.D=!1,this.B=0,this.A=null,this.J=kN,this.K=this.L=!1}MS(EN,DC);var kN="",SN=/^https?$/i,CN=["POST","PUT"];function AN(e){return"content-type"==e.toLowerCase()}function NN(e,t){e.h=!1,e.g&&(e.l=!0,e.g.abort(),e.l=!1),e.j=t,e.m=5,RN(e),xN(e)}function RN(e){e.D||(e.D=!0,LC(e,"complete"),LC(e,"error"))}function PN(e){if(e.h&&void 0!==kS&&(!e.C[1]||4!=DN(e)||2!=e.ba()))if(e.v&&4==DN(e))HC(e.Fa,0,e);else if(LC(e,"readystatechange"),4==DN(e)){e.h=!1;try{var t,n,r,i,s=e.ba();e:switch(s){case 200:case 201:case 202:case 204:case 206:case 304:case 1223:var o=!0;break e;default:o=!1}if((t=o)||((n=0===s)&&(!(i=String(e.H).match(MA)[1]||null)&&SS.self&&SS.self.location&&(i=(r=SS.self.location.protocol).substr(0,r.length-1)),n=!SN.test(i?i.toLowerCase():"")),t=n),t)LC(e,"complete"),LC(e,"success");else{e.m=6;try{var a=2<DN(e)?e.g.statusText:""}catch(e){a=""}e.j=a+" ["+e.ba()+"]",RN(e)}}finally{xN(e)}}}function xN(e,t){if(e.g){ON(e);const n=e.g,r=e.C[0]?CS:null;e.g=null,e.C=null,t||LC(e,"ready");try{n.onreadystatechange=r}catch(e){}}}function ON(e){e.g&&e.K&&(e.g.ontimeout=null),e.A&&(SS.clearTimeout(e.A),e.A=null)}function DN(e){return e.g?e.g.readyState:0}function LN(e){try{if(!e.g)return null;if("response"in e.g)return e.g.response;switch(e.J){case kN:case"text":return e.g.responseText;case"arraybuffer":if("mozResponseArrayBuffer"in e.g)return e.g.mozResponseArrayBuffer}return null}catch(e){return null}}function MN(e,t,n){e:{for(r in n){var r=!1;break e}r=!0}r||(n=function(e){let n="";return QS(e,function(e,t){n+=t,n+=":",n+=e,n+="\r\n"}),n}(n),"string"==typeof e?null!=n&&encodeURIComponent(String(n)):WA(e,t,n))}function FN(e,t,n){return n&&n.internalChannelParams&&n.internalChannelParams[e]||t}function UN(e){this.za=0,this.l=[],this.h=new ZC,this.la=this.oa=this.F=this.W=this.g=this.sa=this.D=this.aa=this.o=this.P=this.s=null,this.Za=this.V=0,this.Xa=FN("failFast",!1,e),this.N=this.v=this.u=this.m=this.j=null,this.X=!0,this.I=this.ta=this.U=-1,this.Y=this.A=this.C=0,this.Pa=FN("baseRetryDelayMs",5e3,e),this.$a=FN("retryDelaySeedMs",1e4,e),this.Ya=FN("forwardChannelMaxRetries",2,e),this.ra=FN("forwardChannelRequestTimeoutMs",2e4,e),this.qa=e&&e.xmlHttpFactory||void 0,this.Ba=e&&e.Yb||!1,this.K=void 0,this.H=e&&e.supportsCrossDomainXhr||!1,this.J="",this.i=new oN(e&&e.concurrentRequestLimit),this.Ca=new gN,this.ja=e&&e.fastHandshake||!1,this.Ra=e&&e.Wb||!1,e&&e.Aa&&this.h.Aa(),e&&e.forceLongPolling&&(this.X=!1),this.$=!this.ja&&this.X&&e&&e.detectBufferingProxy||!1,this.ka=void 0,this.O=0,this.L=!1,this.B=null,this.Wa=!e||!1!==e.Xb}function jN(e){var t,n;VN(e),3==e.G&&(t=e.V++,WA(n=UA(e.F),"SID",e.J),WA(n,"RID",t),WA(n,"TYPE","terminate"),KN(e,n),(t=new mA(e,e.h,t,void 0)).K=2,t.v=zA(UA(n)),n=!1,!(n=SS.navigator&&SS.navigator.sendBeacon?SS.navigator.sendBeacon(t.v.toString(),""):n)&&SS.Image&&((new Image).src=t.v,n=!0),n||(t.g=rR(t.l,null),t.g.ea(t.v)),t.F=Date.now(),SA(t)),tR(e)}function qN(e){e.g&&(QN(e),e.g.cancel(),e.g=null)}function VN(e){qN(e),e.u&&(SS.clearTimeout(e.u),e.u=null),XN(e),e.i.cancel(),e.m&&("number"==typeof e.m&&SS.clearTimeout(e.m),e.m=null)}function BN(e,t){e.l.push(new sN(e.Za++,t)),3==e.G&&WN(e)}function WN(e){cN(e.i)||e.m||(e.m=!0,VC(e.Ha,e),e.C=0)}function zN(e,t){var n=t?t.m:e.V++,r=UA(e.F);WA(r,"SID",e.J),WA(r,"RID",n),WA(r,"AID",e.U),KN(e,r),e.o&&e.s&&MN(r,e.o,e.s),n=new mA(e,e.h,n,e.C+1),null===e.o&&(n.H=e.s),t&&(e.l=t.D.concat(e.l)),t=$N(e,n,1e3),n.setTimeout(Math.round(.5*e.ra)+Math.round(.5*e.ra*Math.random())),hN(e.i,n),IA(n,r,t)}function KN(e,n){e.j&&xA({},function(e,t){WA(n,t,e)})}function $N(e,t,r){r=Math.min(e.l.length,r);var i=e.j?DS(e.j.Oa,e.j,e):null;e:{var s=e.l;let n=-1;for(;;){const c=["count="+r];-1==n?0<r?(n=s[0].h,c.push("ofs="+n)):n=0:c.push("ofs="+n);let e=!0;for(let t=0;t<r;t++){var o=s[t].h,a=s[t].g;if((o-=n)<0)n=Math.max(0,s[t].h-100),e=!1;else try{!function(e,r,t){const i=t||"";try{xA(e,function(e,t){let n=e;NS(e)&&(n=FC(e)),r.push(i+t+"="+encodeURIComponent(n))})}catch(e){throw r.push(i+"type="+encodeURIComponent("_badmap")),e}}(a,c,"req"+o+"_")}catch(e){i&&i(a)}}if(e){i=c.join("&");break e}}}return e=e.l.splice(0,r),t.D=e,i}function HN(e){e.g||e.u||(e.Y=1,VC(e.Ga,e),e.A=0)}function GN(e){return!(e.g||e.u||3<=e.A)&&(e.Y++,e.u=lA(DS(e.Ga,e),ZN(e,e.A)),e.A++,1)}function QN(e){null!=e.B&&(SS.clearTimeout(e.B),e.B=null)}function YN(e){e.g=new mA(e,e.h,"rpc",e.Y),null===e.o&&(e.g.H=e.s),e.g.O=0;var t=UA(e.oa);WA(t,"RID","rpc"),WA(t,"SID",e.J),WA(t,"CI",e.N?"0":"1"),WA(t,"AID",e.U),KN(e,t),WA(t,"TYPE","xmlhttp"),e.o&&e.s&&MN(t,e.o,e.s),e.K&&e.g.setTimeout(e.K);var n=e.g;e=e.la,n.K=1,n.v=zA(UA(t)),n.s=null,n.U=!0,TA(n,e)}function XN(e){null!=e.v&&(SS.clearTimeout(e.v),e.v=null)}function JN(e,t){var n,r,i,s=null;if(e.g==t){XN(e),QN(e),e.g=null;var o=2}else{if(!uN(e.i,t))return;s=t.D,dN(e.i,t),o=1}if(e.I=t.N,0!=e.G)if(t.i)1==o?(s=t.s?t.s.length:0,t=Date.now()-t.F,n=e.C,LC(o=rA(),new cA(o,s)),WN(e)):HN(e);else if(3==(n=t.o)||0==n&&0<e.I||(1!=o||(i=t,lN((r=e).i)>=r.i.j-(r.m?1:0)||(r.m?(r.l=i.D.concat(r.l),0):1==r.G||2==r.G||r.C>=(r.Xa?0:r.Ya)||(r.m=lA(DS(r.Ha,r,i),ZN(r,r.C)),r.C++,0))))&&(2!=o||!GN(e)))switch(s&&0<s.length&&(t=e.i,t.i=t.i.concat(s)),n){case 1:eR(e,5);break;case 4:eR(e,10);break;case 3:eR(e,6);break;default:eR(e,2)}}function ZN(e,t){let n=e.Pa+Math.floor(Math.random()*e.$a);return e.j||(n*=2),n*t}function eR(e,t){var n,r;e.h.info("Error code "+t),2==t?(n=null,e.j&&(n=null),r=DS(e.jb,e),n||(n=new FA("//www.google.com/images/cleardot.gif"),SS.location&&"http"==SS.location.protocol||jA(n,"https"),zA(n)),function(e,t){var n=new ZC;if(SS.Image){const r=new Image;r.onload=LS(mN,n,r,"TestLoadImage: loaded",!0,t),r.onerror=LS(mN,n,r,"TestLoadImage: error",!1,t),r.onabort=LS(mN,n,r,"TestLoadImage: abort",!1,t),r.ontimeout=LS(mN,n,r,"TestLoadImage: timeout",!1,t),SS.setTimeout(function(){r.ontimeout&&r.ontimeout()},1e4),r.src=e}else t(!1)}(n.toString(),r)):aA(2),e.G=0,e.j&&e.j.va(t),tR(e),VN(e)}function tR(e){e.G=0,e.I=-1,e.j&&(0==pN(e.i).length&&0==e.l.length||(e.i.i.length=0,BS(e.l),e.l.length=0),e.j.ua())}function nR(e,t,n){let r=(a=n)instanceof FA?UA(a):new FA(a,void 0);var i,s,o,a,c;return""!=r.i?(t&&qA(r,t+"."+r.i),VA(r,r.m)):(c=SS.location,r=(i=c.protocol,s=t?t+"."+c.hostname:c.hostname,o=+c.port,a=n,c=new FA(null,void 0),i&&jA(c,i),s&&qA(c,s),o&&VA(c,o),a&&(c.l=a),c)),e.aa&&QS(e.aa,function(e,t){WA(r,t,e)}),t=e.D,n=e.sa,t&&n&&WA(r,t,n),WA(r,"VER",e.ma),KN(e,r),r}function rR(e,t,n){if(t&&!e.H)throw Error("Can't create secondary domain capable XhrIo object.");return(t=n&&e.Ba&&!e.qa?new EN(new vN({ib:!0})):new EN(e.qa)).L=e.H,t}function iR(){}function sR(){if(nC&&!(10<=Number(dC)))throw Error("Environmental error: no available transport.")}function oR(e,t){DC.call(this),this.g=new UN(t),this.l=e,this.h=t&&t.messageUrlParams||null,e=t&&t.messageHeaders||null,t&&t.clientProtocolHeaderRequired&&(e?e["X-Client-Protocol"]="webchannel":e={"X-Client-Protocol":"webchannel"}),this.g.s=e,e=t&&t.initMessageHeaders||null,t&&t.messageContentType&&(e?e["X-WebChannel-Content-Type"]=t.messageContentType:e={"X-WebChannel-Content-Type":t.messageContentType}),t&&t.ya&&(e?e["X-WebChannel-Client-Profile"]=t.ya:e={"X-WebChannel-Client-Profile":t.ya}),this.g.P=e,(e=t&&t.httpHeadersOverwriteParam)&&!WS(e)&&(this.g.o=e),this.A=t&&t.supportsCrossDomainXhr||!1,this.v=t&&t.sendRawJson||!1,(t=t&&t.httpSessionIdParam)&&!WS(t)&&(this.g.D=t,null!==(e=this.h)&&t in e&&(t in(e=this.h)&&delete e[t])),this.j=new lR(this)}function aR(e){pA.call(this);var t=e.__sm__;if(t){e:{for(const n in t){e=n;break e}e=void 0}(this.i=e)&&(e=this.i,t=null!==t&&e in t?t[e]:void 0),this.data=t}else this.data=e}function cR(){fA.call(this),this.status=1}function lR(e){this.g=e}($e=EN.prototype).ea=function(e,t,n,r){if(this.g)throw Error("[goog.net.XhrIo] Object is active with another request="+this.H+"; newUri="+e);t=t?t.toUpperCase():"GET",this.H=e,this.j="",this.m=0,this.D=!1,this.h=!0,this.g=(this.u||yA).g(),this.C=this.u?hA(this.u):hA(yA),this.g.onreadystatechange=DS(this.Fa,this);try{this.F=!0,this.g.open(t,String(e),!0),this.F=!1}catch(e){return void NN(this,e)}e=n||"";const i=new OA(this.headers);r&&xA(r,function(e,t){i.set(t,e)}),r=function(t){e:{var n=AN,r=t.length,i="string"==typeof t?t.split(""):t;for(let e=0;e<r;e++)if(e in i&&n.call(void 0,i[e],e,t)){n=e;break e}n=-1}return n<0?null:"string"==typeof t?t.charAt(n):t[n]}(i.T()),n=SS.FormData&&e instanceof SS.FormData,0<=jS(CN,t)&&!r&&!n&&i.set("Content-Type","application/x-www-form-urlencoded;charset=utf-8"),i.forEach(function(e,t){this.g.setRequestHeader(t,e)},this),this.J&&(this.g.responseType=this.J),"withCredentials"in this.g&&this.g.withCredentials!==this.L&&(this.g.withCredentials=this.L);try{ON(this),0<this.B&&((this.K=(s=this.g,nC&&hC()&&"number"==typeof s.timeout&&void 0!==s.ontimeout))?(this.g.timeout=this.B,this.g.ontimeout=DS(this.pa,this)):this.A=HC(this.pa,this.B,this)),this.v=!0,this.g.send(e),this.v=!1}catch(e){NN(this,e)}var s},$e.pa=function(){void 0!==kS&&this.g&&(this.j="Timed out after "+this.B+"ms, aborting",this.m=8,LC(this,"timeout"),this.abort(8))},$e.abort=function(e){this.g&&this.h&&(this.h=!1,this.l=!0,this.g.abort(),this.l=!1,this.m=e||7,LC(this,"complete"),LC(this,"abort"),xN(this))},$e.M=function(){this.g&&(this.h&&(this.h=!1,this.l=!0,this.g.abort(),this.l=!1),xN(this,!0)),EN.Z.M.call(this)},$e.Fa=function(){this.s||(this.F||this.v||this.l?PN(this):this.cb())},$e.cb=function(){PN(this)},$e.ba=function(){try{return 2<DN(this)?this.g.status:-1}catch(e){return-1}},$e.ga=function(){try{return this.g?this.g.responseText:""}catch(e){return""}},$e.Qa=function(e){if(this.g){var t=this.g.responseText;return e&&0==t.indexOf(e)&&(t=t.substring(e.length)),TN(t)}},$e.Da=function(){return this.m},$e.La=function(){return"string"==typeof this.j?this.j:String(this.j)},($e=UN.prototype).ma=8,$e.G=1,$e.hb=function(e){try{this.h.info("Origin Trials invoked: "+e)}catch(e){}},$e.Ha=function(t){if(this.m)if(this.m=null,1==this.G){if(!t){this.V=Math.floor(1e5*Math.random()),t=this.V++;const s=new mA(this,this.h,t,void 0);let e=this.s;if(this.P&&(e?(e=YS(e),JS(e,this.P)):e=this.P),null===this.o&&(s.H=e),this.ja)e:{for(var n=0,r=0;r<this.l.length;r++){var i=this.l[r];if("__data__"in i.g&&"string"==typeof(i=i.g.__data__)?i=i.length:i=void 0,void 0===i)break;if(4096<(n+=i)){n=r;break e}if(4096===n||r===this.l.length-1){n=r+1;break e}}n=1e3}else n=1e3;n=$N(this,s,n),WA(r=UA(this.F),"RID",t),WA(r,"CVER",22),this.D&&WA(r,"X-HTTP-Session-Id",this.D),KN(this,r),this.o&&e&&MN(r,this.o,e),hN(this.i,s),this.Ra&&WA(r,"TYPE","init"),this.ja?(WA(r,"$req",n),WA(r,"SID","null"),s.$=!0,IA(s,r,null)):IA(s,r,n),this.G=2}}else 3==this.G&&(t?zN(this,t):0==this.l.length||cN(this.i)||zN(this))},$e.Ga=function(){var e;this.u=null,YN(this),this.$&&!(this.L||null==this.g||this.O<=0)&&(e=2*this.O,this.h.info("BP detection timer enabled: "+e),this.B=lA(DS(this.bb,this),e))},$e.bb=function(){this.B&&(this.B=null,this.h.info("BP detection timeout reached."),this.h.info("Buffering proxy detected and switch to long-polling!"),this.N=!1,this.L=!0,aA(10),qN(this),YN(this))},$e.ab=function(){null!=this.v&&(this.v=null,qN(this),GN(this),aA(19))},$e.jb=function(e){e?(this.h.info("Successfully pinged google.com"),aA(2)):(this.h.info("Failed to ping google.com"),aA(1))},($e=iR.prototype).xa=function(){},$e.wa=function(){},$e.va=function(){},$e.ua=function(){},$e.Oa=function(){},sR.prototype.g=function(e,t){return new oR(e,t)},MS(oR,DC),oR.prototype.m=function(){this.g.j=this.j,this.A&&(this.g.H=!0);var e=this.g,t=this.l,n=this.h||void 0;e.Wa&&(e.h.info("Origin Trials enabled."),VC(DS(e.hb,e,t))),aA(0),e.W=t,e.aa=n||{},e.N=e.X,e.F=nR(e,null,e.W),WN(e)},oR.prototype.close=function(){jN(this.g)},oR.prototype.u=function(e){var t;"string"==typeof e?((t={}).__data__=e,BN(this.g,t)):this.v?((t={}).__data__=FC(e),BN(this.g,t)):BN(this.g,e)},oR.prototype.M=function(){this.g.j=null,delete this.j,jN(this.g),delete this.g,oR.Z.M.call(this)},MS(aR,pA),MS(cR,fA),MS(lR,iR),lR.prototype.xa=function(){LC(this.g,"a")},lR.prototype.wa=function(e){LC(this.g,new aR(e))},lR.prototype.va=function(e){LC(this.g,new cR)},lR.prototype.ua=function(){LC(this.g,"b")},sR.prototype.createWebChannel=sR.prototype.g,oR.prototype.send=oR.prototype.u,oR.prototype.open=oR.prototype.m,c.NO_ERROR=0,c.TIMEOUT=8,c.HTTP_ERROR=6,yt.COMPLETE="complete",(dA.EventType=l).OPEN="a",l.CLOSE="b",l.ERROR="c",l.MESSAGE="d",DC.prototype.listen=DC.prototype.N,EN.prototype.listenOnce=EN.prototype.O,EN.prototype.getLastError=EN.prototype.La,EN.prototype.getLastErrorCode=EN.prototype.Da,EN.prototype.getStatus=EN.prototype.ba,EN.prototype.getResponseJson=EN.prototype.Qa,EN.prototype.getResponseText=EN.prototype.ga,EN.prototype.send=EN.prototype.ea;var uR,hR=rA,dR=c,pR=yt,fR=tA,gR=10,mR=11,vR=vN,yR=dA,_R=EN;const wR="@firebase/firestore";class bR{constructor(e){this.uid=e}isAuthenticated(){return null!=this.uid}toKey(){return this.isAuthenticated()?"uid:"+this.uid:"anonymous-user"}isEqual(e){return e.uid===this.uid}}bR.UNAUTHENTICATED=new bR(null),bR.GOOGLE_CREDENTIALS=new bR("google-credentials-uid"),bR.FIRST_PARTY=new bR("first-party-uid"),bR.MOCK_USER=new bR("mock-user");let IR="9.6.6";const TR=new ep("@firebase/firestore");function ER(){return TR.logLevel}function kR(e,...t){var n;TR.logLevel<=zh.DEBUG&&(n=t.map(AR),TR.debug(`Firestore (${IR}): ${e}`,...n))}function SR(e,...t){var n;TR.logLevel<=zh.ERROR&&(n=t.map(AR),TR.error(`Firestore (${IR}): ${e}`,...n))}function CR(e,...t){var n;TR.logLevel<=zh.WARN&&(n=t.map(AR),TR.warn(`Firestore (${IR}): ${e}`,...n))}function AR(t){if("string"==typeof t)return t;try{return JSON.stringify(t)}catch(e){return t}}function NR(e="Unexpected state"){var t=`FIRESTORE (${IR}) INTERNAL ASSERTION FAILED: `+e;throw SR(t),new Error(t)}function RR(e){e||NR()}const PR={OK:"ok",CANCELLED:"cancelled",UNKNOWN:"unknown",INVALID_ARGUMENT:"invalid-argument",DEADLINE_EXCEEDED:"deadline-exceeded",NOT_FOUND:"not-found",ALREADY_EXISTS:"already-exists",PERMISSION_DENIED:"permission-denied",UNAUTHENTICATED:"unauthenticated",RESOURCE_EXHAUSTED:"resource-exhausted",FAILED_PRECONDITION:"failed-precondition",ABORTED:"aborted",OUT_OF_RANGE:"out-of-range",UNIMPLEMENTED:"unimplemented",INTERNAL:"internal",UNAVAILABLE:"unavailable",DATA_LOSS:"data-loss"};class xR extends gd{constructor(e,t){super(e,t),this.code=e,this.message=t,this.toString=()=>`${this.name}: [code=${this.code}]: ${this.message}`}}class OR{constructor(){this.promise=new Promise((e,t)=>{this.resolve=e,this.reject=t})}}class DR{constructor(e,t){this.user=t,this.type="OAuth",this.headers=new Map,this.headers.set("Authorization",`Bearer ${e}`)}}class LR{getToken(){return Promise.resolve(null)}invalidateToken(){}start(e,t){e.enqueueRetryable(()=>t(bR.UNAUTHENTICATED))}shutdown(){}}class MR{constructor(e){this.token=e,this.changeListener=null}getToken(){return Promise.resolve(this.token)}invalidateToken(){}start(e,t){this.changeListener=t,e.enqueueRetryable(()=>t(this.token.user))}shutdown(){this.changeListener=null}}class FR{constructor(e){this.t=e,this.currentUser=bR.UNAUTHENTICATED,this.i=0,this.forceRefresh=!1,this.auth=null}start(t,n){let r=this.i;const i=e=>this.i!==r?(r=this.i,n(e)):Promise.resolve();let s=new OR;this.o=()=>{this.i++,this.currentUser=this.u(),s.resolve(),s=new OR,t.enqueueRetryable(()=>i(this.currentUser))};const o=()=>{const e=s;t.enqueueRetryable(async()=>{await e.promise,await i(this.currentUser)})},a=e=>{kR("FirebaseAuthCredentialsProvider","Auth detected"),this.auth=e,this.auth.addAuthTokenListener(this.o),o()};this.t.onInit(e=>a(e)),setTimeout(()=>{var e;this.auth||((e=this.t.getImmediate({optional:!0}))?a(e):(kR("FirebaseAuthCredentialsProvider","Auth not yet detected"),s.resolve(),s=new OR))},0),o()}getToken(){const t=this.i,e=this.forceRefresh;return this.forceRefresh=!1,this.auth?this.auth.getToken(e).then(e=>this.i!==t?(kR("FirebaseAuthCredentialsProvider","getToken aborted due to token change."),this.getToken()):e?(RR("string"==typeof e.accessToken),new DR(e.accessToken,this.currentUser)):null):Promise.resolve(null)}invalidateToken(){this.forceRefresh=!0}shutdown(){this.auth&&this.auth.removeAuthTokenListener(this.o)}u(){var e=this.auth&&this.auth.getUid();return RR(null===e||"string"==typeof e),new bR(e)}}class UR{constructor(e,t,n){this.type="FirstParty",this.user=bR.FIRST_PARTY,this.headers=new Map,this.headers.set("X-Goog-AuthUser",t);var r=e.auth.getAuthHeaderValueForFirstParty([]);r&&this.headers.set("Authorization",r),n&&this.headers.set("X-Goog-Iam-Authorization-Token",n)}}class jR{constructor(e,t,n){this.h=e,this.l=t,this.m=n}getToken(){return Promise.resolve(new UR(this.h,this.l,this.m))}start(e,t){e.enqueueRetryable(()=>t(bR.FIRST_PARTY))}shutdown(){}invalidateToken(){}}class qR{constructor(e){this.value=e,this.type="AppCheck",this.headers=new Map,e&&0<e.length&&this.headers.set("x-firebase-appcheck",this.value)}}class VR{constructor(e){this.g=e,this.forceRefresh=!1,this.appCheck=null}start(t,n){this.o=e=>{t.enqueueRetryable(()=>(e=>(null!=e.error&&kR("FirebaseAppCheckTokenProvider",`Error getting App Check token; using placeholder token instead. Error: ${e.error.message}`),n(e.token)))(e))};const r=e=>{kR("FirebaseAppCheckTokenProvider","AppCheck detected"),this.appCheck=e,this.appCheck.addTokenListener(this.o)};this.g.onInit(e=>r(e)),setTimeout(()=>{var e;this.appCheck||((e=this.g.getImmediate({optional:!0}))?r(e):kR("FirebaseAppCheckTokenProvider","AppCheck not yet detected"))},0)}getToken(){var e=this.forceRefresh;return this.forceRefresh=!1,this.appCheck?this.appCheck.getToken(e).then(e=>e?(RR("string"==typeof e.token),new qR(e.token)):null):Promise.resolve(null)}invalidateToken(){this.forceRefresh=!0}shutdown(){this.appCheck&&this.appCheck.removeTokenListener(this.o)}}class BR{constructor(e,t){this.previousValue=e,t&&(t.sequenceNumberHandler=e=>this.p(e),this.T=e=>t.writeSequenceNumber(e))}p(e){return this.previousValue=Math.max(e,this.previousValue),this.previousValue}next(){var e=++this.previousValue;return this.T&&this.T(e),e}}BR.I=-1;class WR{static A(){var t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",n=Math.floor(256/t.length)*t.length;let r="";for(;r.length<20;){var i=function(t){const n="undefined"!=typeof self&&(self.crypto||self.msCrypto),r=new Uint8Array(t);if(n&&"function"==typeof n.getRandomValues)n.getRandomValues(r);else for(let e=0;e<t;e++)r[e]=Math.floor(256*Math.random());return r}(40);for(let e=0;e<i.length;++e)r.length<20&&i[e]<n&&(r+=t.charAt(i[e]%t.length))}return r}}function zR(e,t){return e<t?-1:t<e?1:0}function KR(e,n,r){return e.length===n.length&&e.every((e,t)=>r(e,n[t]))}function $R(e){return e+"\0"}class HR{constructor(e,t){if(this.seconds=e,(this.nanoseconds=t)<0)throw new xR(PR.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+t);if(1e9<=t)throw new xR(PR.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+t);if(e<-62135596800)throw new xR(PR.INVALID_ARGUMENT,"Timestamp seconds out of range: "+e);if(253402300800<=e)throw new xR(PR.INVALID_ARGUMENT,"Timestamp seconds out of range: "+e)}static now(){return HR.fromMillis(Date.now())}static fromDate(e){return HR.fromMillis(e.getTime())}static fromMillis(e){var t=Math.floor(e/1e3),n=Math.floor(1e6*(e-1e3*t));return new HR(t,n)}toDate(){return new Date(this.toMillis())}toMillis(){return 1e3*this.seconds+this.nanoseconds/1e6}_compareTo(e){return this.seconds===e.seconds?zR(this.nanoseconds,e.nanoseconds):zR(this.seconds,e.seconds)}isEqual(e){return e.seconds===this.seconds&&e.nanoseconds===this.nanoseconds}toString(){return"Timestamp(seconds="+this.seconds+", nanoseconds="+this.nanoseconds+")"}toJSON(){return{seconds:this.seconds,nanoseconds:this.nanoseconds}}valueOf(){var e=this.seconds- -62135596800;return String(e).padStart(12,"0")+"."+String(this.nanoseconds).padStart(9,"0")}}class GR{constructor(e){this.timestamp=e}static fromTimestamp(e){return new GR(e)}static min(){return new GR(new HR(0,0))}compareTo(e){return this.timestamp._compareTo(e.timestamp)}isEqual(e){return this.timestamp.isEqual(e.timestamp)}toMicroseconds(){return 1e6*this.timestamp.seconds+this.timestamp.nanoseconds/1e3}toString(){return"SnapshotVersion("+this.timestamp.toString()+")"}toTimestamp(){return this.timestamp}}function QR(e){let t=0;for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&t++;return t}function YR(e,t){for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&t(n,e[n])}function XR(e){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}class JR{constructor(e,t,n){void 0===t?t=0:t>e.length&&NR(),void 0===n?n=e.length-t:n>e.length-t&&NR(),this.segments=e,this.offset=t,this.len=n}get length(){return this.len}isEqual(e){return 0===JR.comparator(this,e)}child(e){const t=this.segments.slice(this.offset,this.limit());return e instanceof JR?e.forEach(e=>{t.push(e)}):t.push(e),this.construct(t)}limit(){return this.offset+this.length}popFirst(e){return this.construct(this.segments,this.offset+(e=void 0===e?1:e),this.length-e)}popLast(){return this.construct(this.segments,this.offset,this.length-1)}firstSegment(){return this.segments[this.offset]}lastSegment(){return this.get(this.length-1)}get(e){return this.segments[this.offset+e]}isEmpty(){return 0===this.length}isPrefixOf(e){if(e.length<this.length)return!1;for(let t=0;t<this.length;t++)if(this.get(t)!==e.get(t))return!1;return!0}isImmediateParentOf(e){if(this.length+1!==e.length)return!1;for(let t=0;t<this.length;t++)if(this.get(t)!==e.get(t))return!1;return!0}forEach(e){for(let t=this.offset,n=this.limit();t<n;t++)e(this.segments[t])}toArray(){return this.segments.slice(this.offset,this.limit())}static comparator(e,t){const n=Math.min(e.length,t.length);for(let r=0;r<n;r++){const n=e.get(r),i=t.get(r);if(n<i)return-1;if(n>i)return 1}return e.length<t.length?-1:e.length>t.length?1:0}}class ZR extends JR{construct(e,t,n){return new ZR(e,t,n)}canonicalString(){return this.toArray().join("/")}toString(){return this.canonicalString()}static fromString(...e){const t=[];for(const n of e){if(0<=n.indexOf("//"))throw new xR(PR.INVALID_ARGUMENT,`Invalid segment (${n}). Paths must not contain // in them.`);t.push(...n.split("/").filter(e=>0<e.length))}return new ZR(t)}static emptyPath(){return new ZR([])}}const eP=/^[_a-zA-Z][_a-zA-Z0-9]*$/;class tP extends JR{construct(e,t,n){return new tP(e,t,n)}static isValidIdentifier(e){return eP.test(e)}canonicalString(){return this.toArray().map(e=>(e=e.replace(/\\/g,"\\\\").replace(/`/g,"\\`"),e=!tP.isValidIdentifier(e)?"`"+e+"`":e)).join(".")}toString(){return this.canonicalString()}isKeyField(){return 1===this.length&&"__name__"===this.get(0)}static keyField(){return new tP(["__name__"])}static fromServerFormat(e){const t=[];let n="",r=0;var i=()=>{if(0===n.length)throw new xR(PR.INVALID_ARGUMENT,`Invalid field path (${e}). Paths must not be empty, begin with '.', end with '.', or contain '..'`);t.push(n),n=""};let s=!1;for(;r<e.length;){const t=e[r];if("\\"===t){if(r+1===e.length)throw new xR(PR.INVALID_ARGUMENT,"Path has trailing escape character: "+e);const t=e[r+1];if("\\"!==t&&"."!==t&&"`"!==t)throw new xR(PR.INVALID_ARGUMENT,"Path has invalid escape sequence: "+e);n+=t,r+=2}else"`"===t?s=!s:"."!==t||s?n+=t:i(),r++}if(i(),s)throw new xR(PR.INVALID_ARGUMENT,"Unterminated ` in path: "+e);return new tP(t)}static emptyPath(){return new tP([])}}class nP{constructor(e){(this.fields=e).sort(tP.comparator)}covers(e){for(const t of this.fields)if(t.isPrefixOf(e))return!0;return!1}isEqual(e){return KR(this.fields,e.fields,(e,t)=>e.isEqual(t))}}class rP{constructor(e){this.binaryString=e}static fromBase64String(e){var t=atob(e);return new rP(t)}static fromUint8Array(e){var t=function(e){let t="";for(let n=0;n<e.length;++n)t+=String.fromCharCode(e[n]);return t}(e);return new rP(t)}[Symbol.iterator](){let e=0;return{next:()=>e<this.binaryString.length?{value:this.binaryString.charCodeAt(e++),done:!1}:{value:void 0,done:!0}}}toBase64(){return e=this.binaryString,btoa(e);var e}toUint8Array(){return function(e){const t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t}(this.binaryString)}approximateByteSize(){return 2*this.binaryString.length}compareTo(e){return zR(this.binaryString,e.binaryString)}isEqual(e){return this.binaryString===e.binaryString}}rP.EMPTY_BYTE_STRING=new rP("");const iP=new RegExp(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.(\d+))?Z$/);function sP(t){if(RR(!!t),"string"!=typeof t)return{seconds:oP(t.seconds),nanos:oP(t.nanos)};{let e=0;var n=iP.exec(t);RR(!!n),n[1]&&(n=((n=n[1])+"000000000").substr(0,9),e=Number(n));const r=new Date(t);return{seconds:Math.floor(r.getTime()/1e3),nanos:e}}}function oP(e){return"number"==typeof e?e:"string"==typeof e?Number(e):0}function aP(e){return"string"==typeof e?rP.fromBase64String(e):rP.fromUint8Array(e)}function cP(e){var t;return"server_timestamp"===(null===(t=((null===(t=null==e?void 0:e.mapValue)||void 0===t?void 0:t.fields)||{}).__type__)||void 0===t?void 0:t.stringValue)}function lP(e){var t=sP(e.mapValue.fields.__local_write_time__.timestampValue);return new HR(t.seconds,t.nanos)}class uP{constructor(e,t,n,r,i,s,o,a){this.databaseId=e,this.appId=t,this.persistenceKey=n,this.host=r,this.ssl=i,this.forceLongPolling=s,this.autoDetectLongPolling=o,this.useFetchStreams=a}}class hP{constructor(e,t){this.projectId=e,this.database=t||"(default)"}static empty(){return new hP("","")}get isDefaultDatabase(){return"(default)"===this.database}isEqual(e){return e instanceof hP&&e.projectId===this.projectId&&e.database===this.database}}function dP(e){return null==e}function pP(e){return 0===e&&1/e==-1/0}function fP(e){return"number"==typeof e&&Number.isInteger(e)&&!pP(e)&&e<=Number.MAX_SAFE_INTEGER&&e>=Number.MIN_SAFE_INTEGER}class gP{constructor(e){this.path=e}static fromPath(e){return new gP(ZR.fromString(e))}static fromName(e){return new gP(ZR.fromString(e).popFirst(5))}static empty(){return new gP(ZR.emptyPath())}hasCollectionId(e){return 2<=this.path.length&&this.path.get(this.path.length-2)===e}isEqual(e){return null!==e&&0===ZR.comparator(this.path,e.path)}toString(){return this.path.toString()}static comparator(e,t){return ZR.comparator(e.path,t.path)}static isDocumentKey(e){return e.length%2==0}static fromSegments(e){return new gP(new ZR(e.slice()))}}function mP(e){return"nullValue"in e?0:"booleanValue"in e?1:"integerValue"in e||"doubleValue"in e?2:"timestampValue"in e?3:"stringValue"in e?5:"bytesValue"in e?6:"referenceValue"in e?7:"geoPointValue"in e?8:"arrayValue"in e?9:"mapValue"in e?cP(e)?4:10:NR()}function vP(r,i){if(r===i)return!0;var e,t,n=mP(r);if(n!==mP(i))return!1;switch(n){case 0:return!0;case 1:return r.booleanValue===i.booleanValue;case 4:return lP(r).isEqual(lP(i));case 3:return function(e){if("string"==typeof r.timestampValue&&"string"==typeof e.timestampValue&&r.timestampValue.length===e.timestampValue.length)return r.timestampValue===e.timestampValue;var t=sP(r.timestampValue),n=sP(e.timestampValue);return t.seconds===n.seconds&&t.nanos===n.nanos}(i);case 5:return r.stringValue===i.stringValue;case 6:return t=i,aP(r.bytesValue).isEqual(aP(t.bytesValue));case 7:return r.referenceValue===i.referenceValue;case 8:return e=i,oP((t=r).geoPointValue.latitude)===oP(e.geoPointValue.latitude)&&oP(t.geoPointValue.longitude)===oP(e.geoPointValue.longitude);case 2:return function(e,t){if("integerValue"in e&&"integerValue"in t)return oP(e.integerValue)===oP(t.integerValue);if("doubleValue"in e&&"doubleValue"in t){var n=oP(e.doubleValue),r=oP(t.doubleValue);return n===r?pP(n)===pP(r):isNaN(n)&&isNaN(r)}return!1}(r,i);case 9:return KR(r.arrayValue.values||[],i.arrayValue.values||[],vP);case 10:return function(e){const t=e.mapValue.fields||{},n=i.mapValue.fields||{};if(QR(t)!==QR(n))return!1;for(const e in t)if(t.hasOwnProperty(e)&&(void 0===n[e]||!vP(t[e],n[e])))return!1;return!0}(r);default:return NR()}}function yP(e,t){return void 0!==(e.values||[]).find(e=>vP(e,t))}function _P(e,t){if(e===t)return 0;var n,r,i,s,o=mP(e),a=mP(t);if(o!==a)return zR(o,a);switch(o){case 0:return 0;case 1:return zR(e.booleanValue,t.booleanValue);case 2:return r=t,i=oP(e.integerValue||e.doubleValue),s=oP(r.integerValue||r.doubleValue),i<s?-1:s<i?1:i===s?0:isNaN(i)?isNaN(s)?0:-1:1;case 3:return wP(e.timestampValue,t.timestampValue);case 4:return wP(lP(e),lP(t));case 5:return zR(e.stringValue,t.stringValue);case 6:return function(e,t){const n=aP(e),r=aP(t);return n.compareTo(r)}(e.bytesValue,t.bytesValue);case 7:return function(e,t){var n=e.split("/"),r=t.split("/");for(let i=0;i<n.length&&i<r.length;i++){const t=zR(n[i],r[i]);if(0!==t)return t}return zR(n.length,r.length)}(e.referenceValue,t.referenceValue);case 8:return n=e.geoPointValue,r=t.geoPointValue,0!==(s=zR(oP(n.latitude),oP(r.latitude)))?s:zR(oP(n.longitude),oP(r.longitude));case 9:return function(e,t){var n=e.values||[],r=t.values||[];for(let i=0;i<n.length&&i<r.length;++i){const t=_P(n[i],r[i]);if(t)return t}return zR(n.length,r.length)}(e.arrayValue,t.arrayValue);case 10:return function(e,t){const n=e.fields||{},r=Object.keys(n),i=t.fields||{},s=Object.keys(i);r.sort(),s.sort();for(let a=0;a<r.length&&a<s.length;++a){const t=zR(r[a],s[a]);if(0!==t)return t;var o=_P(n[r[a]],i[s[a]]);if(0!==o)return o}return zR(r.length,s.length)}(e.mapValue,t.mapValue);default:throw NR()}}function wP(e,t){if("string"==typeof e&&"string"==typeof t&&e.length===t.length)return zR(e,t);var n=sP(e),r=sP(t),i=zR(n.seconds,r.seconds);return 0!==i?i:zR(n.nanos,r.nanos)}function bP(e){return function s(e){return"nullValue"in e?"null":"booleanValue"in e?""+e.booleanValue:"integerValue"in e?""+e.integerValue:"doubleValue"in e?""+e.doubleValue:"timestampValue"in e?function(e){const t=sP(e);return`time(${t.seconds},${t.nanos})`}(e.timestampValue):"stringValue"in e?e.stringValue:"bytesValue"in e?aP(e.bytesValue).toBase64():"referenceValue"in e?(t=e.referenceValue,gP.fromName(t).toString()):"geoPointValue"in e?`geo(${(t=e.geoPointValue).latitude},${t.longitude})`:"arrayValue"in e?function(e){let t="[",n=!0;for(const r of e.values||[])n?n=!1:t+=",",t+=s(r);return t+"]"}(e.arrayValue):"mapValue"in e?function(e){const t=Object.keys(e.fields||{}).sort();let n="{",r=!0;for(const i of t)r?r=!1:n+=",",n+=`${i}:${s(e.fields[i])}`;return n+"}"}(e.mapValue):NR();var t}(e)}function IP(e,t){return{referenceValue:`projects/${e.projectId}/databases/${e.database}/documents/${t.path.canonicalString()}`}}function TP(e){return e&&"integerValue"in e}function EP(e){return!!e&&"arrayValue"in e}function kP(e){return e&&"nullValue"in e}function SP(e){return e&&"doubleValue"in e&&isNaN(Number(e.doubleValue))}function CP(e){return e&&"mapValue"in e}function AP(t){if(t.geoPointValue)return{geoPointValue:Object.assign({},t.geoPointValue)};if(t.timestampValue&&"object"==typeof t.timestampValue)return{timestampValue:Object.assign({},t.timestampValue)};if(t.mapValue){const n={mapValue:{fields:{}}};return YR(t.mapValue.fields,(e,t)=>n.mapValue.fields[e]=AP(t)),n}if(t.arrayValue){const r={arrayValue:{values:[]}};for(let e=0;e<(t.arrayValue.values||[]).length;++e)r.arrayValue.values[e]=AP(t.arrayValue.values[e]);return r}return Object.assign({},t)}class NP{constructor(e){this.value=e}static empty(){return new NP({mapValue:{}})}field(n){if(n.isEmpty())return this.value;{let e=this.value;for(let t=0;t<n.length-1;++t)if(e=(e.mapValue.fields||{})[n.get(t)],!CP(e))return null;return e=(e.mapValue.fields||{})[n.lastSegment()],e||null}}set(e,t){this.getFieldsMap(e.popLast())[e.lastSegment()]=AP(t)}setAll(e){let n=tP.emptyPath(),r={},i=[];e.forEach((e,t)=>{if(!n.isImmediateParentOf(t)){const e=this.getFieldsMap(n);this.applyChanges(e,r,i),r={},i=[],n=t.popLast()}e?r[t.lastSegment()]=AP(e):i.push(t.lastSegment())});var t=this.getFieldsMap(n);this.applyChanges(t,r,i)}delete(e){const t=this.field(e.popLast());CP(t)&&t.mapValue.fields&&delete t.mapValue.fields[e.lastSegment()]}isEqual(e){return vP(this.value,e.value)}getFieldsMap(t){let n=this.value;n.mapValue.fields||(n.mapValue={fields:{}});for(let r=0;r<t.length;++r){let e=n.mapValue.fields[t.get(r)];CP(e)&&e.mapValue.fields||(e={mapValue:{fields:{}}},n.mapValue.fields[t.get(r)]=e),n=e}return n.mapValue.fields}applyChanges(n,e,t){YR(e,(e,t)=>n[e]=t);for(const e of t)delete n[e]}clone(){return new NP(AP(this.value))}}class RP{constructor(e,t,n,r,i,s){this.key=e,this.documentType=t,this.version=n,this.readTime=r,this.data=i,this.documentState=s}static newInvalidDocument(e){return new RP(e,0,GR.min(),GR.min(),NP.empty(),0)}static newFoundDocument(e,t,n){return new RP(e,1,t,GR.min(),n,0)}static newNoDocument(e,t){return new RP(e,2,t,GR.min(),NP.empty(),0)}static newUnknownDocument(e,t){return new RP(e,3,t,GR.min(),NP.empty(),2)}convertToFoundDocument(e,t){return this.version=e,this.documentType=1,this.data=t,this.documentState=0,this}convertToNoDocument(e){return this.version=e,this.documentType=2,this.data=NP.empty(),this.documentState=0,this}convertToUnknownDocument(e){return this.version=e,this.documentType=3,this.data=NP.empty(),this.documentState=2,this}setHasCommittedMutations(){return this.documentState=2,this}setHasLocalMutations(){return this.documentState=1,this}setReadTime(e){return this.readTime=e,this}get hasLocalMutations(){return 1===this.documentState}get hasCommittedMutations(){return 2===this.documentState}get hasPendingWrites(){return this.hasLocalMutations||this.hasCommittedMutations}isValidDocument(){return 0!==this.documentType}isFoundDocument(){return 1===this.documentType}isNoDocument(){return 2===this.documentType}isUnknownDocument(){return 3===this.documentType}isEqual(e){return e instanceof RP&&this.key.isEqual(e.key)&&this.version.isEqual(e.version)&&this.documentType===e.documentType&&this.documentState===e.documentState&&this.data.isEqual(e.data)}mutableCopy(){return new RP(this.key,this.documentType,this.version,this.readTime,this.data.clone(),this.documentState)}toString(){return`Document(${this.key}, ${this.version}, ${JSON.stringify(this.data.value)}, {documentType: ${this.documentType}}), {documentState: ${this.documentState}})`}}class PP{constructor(e,t=null,n=[],r=[],i=null,s=null,o=null){this.path=e,this.collectionGroup=t,this.orderBy=n,this.filters=r,this.limit=i,this.startAt=s,this.endAt=o,this.v=null}}function xP(e,t=null,n=[],r=[],i=null,s=null,o=null){return new PP(e,t,n,r,i,s,o)}function OP(e){const t=e;if(null===t.v){let e=t.path.canonicalString();null!==t.collectionGroup&&(e+="|cg:"+t.collectionGroup),e+="|f:",e+=t.filters.map(e=>function(e){return e.field.canonicalString()+e.op.toString()+bP(e.value)}(e)).join(","),e+="|ob:",e+=t.orderBy.map(e=>function(e){return e.field.canonicalString()+e.dir}(e)).join(","),dP(t.limit)||(e+="|l:",e+=t.limit),t.startAt&&(e+="|lb:",e+=$P(t.startAt)),t.endAt&&(e+="|ub:",e+=$P(t.endAt)),t.v=e}return t.v}function DP(e,t){if(e.limit!==t.limit)return!1;if(e.orderBy.length!==t.orderBy.length)return!1;for(let o=0;o<e.orderBy.length;o++)if(n=e.orderBy[o],r=t.orderBy[o],n.dir!==r.dir||!n.field.isEqual(r.field))return!1;var n,r,i,s;if(e.filters.length!==t.filters.length)return!1;for(let a=0;a<e.filters.length;a++)if(i=e.filters[a],s=t.filters[a],i.op!==s.op||!i.field.isEqual(s.field)||!vP(i.value,s.value))return!1;return e.collectionGroup===t.collectionGroup&&!!e.path.isEqual(t.path)&&!!QP(e.startAt,t.startAt)&&QP(e.endAt,t.endAt)}function LP(e){return gP.isDocumentKey(e.path)&&null===e.collectionGroup&&0===e.filters.length}class MP extends class{}{constructor(e,t,n){super(),this.field=e,this.op=t,this.value=n}static create(e,t,n){return e.isKeyField()?"in"===t||"not-in"===t?this.V(e,t,n):new FP(e,t,n):"array-contains"===t?new VP(e,n):"in"===t?new BP(e,n):"not-in"===t?new WP(e,n):"array-contains-any"===t?new zP(e,n):new MP(e,t,n)}static V(e,t,n){return new("in"===t?UP:jP)(e,n)}matches(e){var t=e.data.field(this.field);return"!="===this.op?null!==t&&this.S(_P(t,this.value)):null!==t&&mP(this.value)===mP(t)&&this.S(_P(t,this.value))}S(e){switch(this.op){case"<":return e<0;case"<=":return e<=0;case"==":return 0===e;case"!=":return 0!==e;case">":return 0<e;case">=":return 0<=e;default:return NR()}}D(){return 0<=["<","<=",">",">=","!=","not-in"].indexOf(this.op)}}class FP extends MP{constructor(e,t,n){super(e,t,n),this.key=gP.fromName(n.referenceValue)}matches(e){var t=gP.comparator(e.key,this.key);return this.S(t)}}class UP extends MP{constructor(e,t){super(e,"in",t),this.keys=qP(0,t)}matches(t){return this.keys.some(e=>e.isEqual(t.key))}}class jP extends MP{constructor(e,t){super(e,"not-in",t),this.keys=qP(0,t)}matches(t){return!this.keys.some(e=>e.isEqual(t.key))}}function qP(e,t){var n;return((null===(n=t.arrayValue)||void 0===n?void 0:n.values)||[]).map(e=>gP.fromName(e.referenceValue))}class VP extends MP{constructor(e,t){super(e,"array-contains",t)}matches(e){var t=e.data.field(this.field);return EP(t)&&yP(t.arrayValue,this.value)}}class BP extends MP{constructor(e,t){super(e,"in",t)}matches(e){var t=e.data.field(this.field);return null!==t&&yP(this.value.arrayValue,t)}}class WP extends MP{constructor(e,t){super(e,"not-in",t)}matches(e){if(yP(this.value.arrayValue,{nullValue:"NULL_VALUE"}))return!1;var t=e.data.field(this.field);return null!==t&&!yP(this.value.arrayValue,t)}}class zP extends MP{constructor(e,t){super(e,"array-contains-any",t)}matches(e){const t=e.data.field(this.field);return!(!EP(t)||!t.arrayValue.values)&&t.arrayValue.values.some(e=>yP(this.value.arrayValue,e))}}class KP{constructor(e,t){this.position=e,this.before=t}}function $P(e){return`${e.before?"b":"a"}:${e.position.map(e=>bP(e)).join(",")}`}class HP{constructor(e,t="asc"){this.field=e,this.dir=t}}function GP(e,t,n){let r=0;for(let i=0;i<e.position.length;i++){const s=t[i],o=e.position[i];if(r=s.field.isKeyField()?gP.comparator(gP.fromName(o.referenceValue),n.key):_P(o,n.data.field(s.field)),"desc"===s.dir&&(r*=-1),0!==r)break}return e.before?r<=0:r<0}function QP(e,t){if(null===e)return null===t;if(null===t)return!1;if(e.before!==t.before||e.position.length!==t.position.length)return!1;for(let n=0;n<e.position.length;n++)if(!vP(e.position[n],t.position[n]))return!1;return!0}class YP{constructor(e,t=null,n=[],r=[],i=null,s="F",o=null,a=null){this.path=e,this.collectionGroup=t,this.explicitOrderBy=n,this.filters=r,this.limit=i,this.limitType=s,this.startAt=o,this.endAt=a,this.C=null,this.N=null,this.startAt,this.endAt}}function XP(e,t,n,r,i,s,o,a){return new YP(e,t,n,r,i,s,o,a)}function JP(e){return new YP(e)}function ZP(e){return!dP(e.limit)&&"F"===e.limitType}function ex(e){return!dP(e.limit)&&"L"===e.limitType}function tx(e){return 0<e.explicitOrderBy.length?e.explicitOrderBy[0].field:null}function nx(e){for(const t of e.filters)if(t.D())return t.field;return null}function rx(e){return null!==e.collectionGroup}function ix(t){const n=t;if(null===n.C){n.C=[];const t=nx(n),e=tx(n);if(null!==t&&null===e)t.isKeyField()||n.C.push(new HP(t)),n.C.push(new HP(tP.keyField(),"asc"));else{let e=!1;for(const r of n.explicitOrderBy)n.C.push(r),r.field.isKeyField()&&(e=!0);if(!e){const t=0<n.explicitOrderBy.length?n.explicitOrderBy[n.explicitOrderBy.length-1].dir:"asc";n.C.push(new HP(tP.keyField(),t))}}}return n.C}function sx(e){const t=e;if(!t.N)if("F"===t.limitType)t.N=xP(t.path,t.collectionGroup,ix(t),t.filters,t.limit,t.startAt,t.endAt);else{const e=[];for(const i of ix(t)){const t="desc"===i.dir?"asc":"desc";e.push(new HP(i.field,t))}var n=t.endAt?new KP(t.endAt.position,!t.endAt.before):null,r=t.startAt?new KP(t.startAt.position,!t.startAt.before):null;t.N=xP(t.path,t.collectionGroup,e,t.filters,t.limit,n,r)}return t.N}function ox(e,t,n){return new YP(e.path,e.collectionGroup,e.explicitOrderBy.slice(),e.filters.slice(),t,n,e.startAt,e.endAt)}function ax(e,t){return DP(sx(e),sx(t))&&e.limitType===t.limitType}function cx(e){return`${OP(sx(e))}|lt:${e.limitType}`}function lx(e){return`Query(target=${function(e){let t=e.path.canonicalString();return null!==e.collectionGroup&&(t+=" collectionGroup="+e.collectionGroup),0<e.filters.length&&(t+=`, filters: [${e.filters.map(e=>{return`${(t=e).field.canonicalString()} ${t.op} ${bP(t.value)}`;var t}).join(", ")}]`),dP(e.limit)||(t+=", limit: "+e.limit),0<e.orderBy.length&&(t+=`, orderBy: [${e.orderBy.map(e=>function(e){return`${e.field.canonicalString()} (${e.dir})`}(e)).join(", ")}]`),e.startAt&&(t+=", startAt: "+$P(e.startAt)),e.endAt&&(t+=", endAt: "+$P(e.endAt)),`Target(${t})`}(sx(e))}; limitType=${e.limitType})`}function ux(n,e){return e.isFoundDocument()&&(t=n,i=(r=e).key.path,null!==t.collectionGroup?r.key.hasCollectionId(t.collectionGroup)&&t.path.isPrefixOf(i):gP.isDocumentKey(t.path)?t.path.isEqual(i):t.path.isImmediateParentOf(i))&&function(e){for(const t of n.explicitOrderBy)if(!t.field.isKeyField()&&null===e.data.field(t.field))return;return 1}(e)&&function(e){for(const t of n.filters)if(!t.matches(e))return;return 1}(e)&&(t=e,(!(e=n).startAt||GP(e.startAt,ix(e),t))&&(!e.endAt||!GP(e.endAt,ix(e),t)));var t,r,i}function hx(i){return(e,t)=>{let n=!1;for(const r of ix(i)){const i=function(e,i,t){var n=e.field.isKeyField()?gP.comparator(i.key,t.key):function(e,t){var n=i.data.field(e),r=t.data.field(e);return null!==n&&null!==r?_P(n,r):NR()}(e.field,t);switch(e.dir){case"asc":return n;case"desc":return-1*n;default:return NR()}}(r,e,t);if(0!==i)return i;n=n||r.field.isKeyField()}return 0}}function dx(e,t){if(e.k){if(isNaN(t))return{doubleValue:"NaN"};if(t===1/0)return{doubleValue:"Infinity"};if(t===-1/0)return{doubleValue:"-Infinity"}}return{doubleValue:pP(t)?"-0":t}}function px(e){return{integerValue:""+e}}function fx(e,t){return fP(t)?px(t):dx(e,t)}class gx{constructor(){this._=void 0}}function mx(e,t){return e instanceof Ix?TP(n=t)||n&&"doubleValue"in n?t:{integerValue:0}:null;var n}class vx extends gx{}class yx extends gx{constructor(e){super(),this.elements=e}}function _x(e,t){const n=Ex(t);for(const t of e.elements)n.some(e=>vP(e,t))||n.push(t);return{arrayValue:{values:n}}}class wx extends gx{constructor(e){super(),this.elements=e}}function bx(e,t){let n=Ex(t);for(const t of e.elements)n=n.filter(e=>!vP(e,t));return{arrayValue:{values:n}}}class Ix extends gx{constructor(e,t){super(),this.O=e,this.$=t}}function Tx(e){return oP(e.integerValue||e.doubleValue)}function Ex(e){return EP(e)&&e.arrayValue.values?e.arrayValue.values.slice():[]}class kx{constructor(e,t){this.field=e,this.transform=t}}class Sx{constructor(e,t){this.version=e,this.transformResults=t}}class Cx{constructor(e,t){this.updateTime=e,this.exists=t}static none(){return new Cx}static exists(e){return new Cx(void 0,e)}static updateTime(e){return new Cx(e)}get isNone(){return void 0===this.updateTime&&void 0===this.exists}isEqual(e){return this.exists===e.exists&&(this.updateTime?!!e.updateTime&&this.updateTime.isEqual(e.updateTime):!e.updateTime)}}function Ax(e,t){return void 0!==e.updateTime?t.isFoundDocument()&&t.version.isEqual(e.updateTime):void 0===e.exists||e.exists===t.isFoundDocument()}class Nx{}function Rx(e,t,n){e instanceof Dx?function(e,t,n){const r=e.value.clone(),i=Fx(e.fieldTransforms,t,n.transformResults);r.setAll(i),t.convertToFoundDocument(n.version,r).setHasCommittedMutations()}(e,t,n):e instanceof Lx?function(e,t,n){if(!Ax(e.precondition,t))return t.convertToUnknownDocument(n.version);const r=Fx(e.fieldTransforms,t,n.transformResults),i=t.data;i.setAll(Mx(e)),i.setAll(r),t.convertToFoundDocument(n.version,i).setHasCommittedMutations()}(e,t,n):t.convertToNoDocument(n.version).setHasCommittedMutations()}function Px(e,t,n){e instanceof Dx?function(e,t,n){if(Ax(e.precondition,t)){const r=e.value.clone(),i=Ux(e.fieldTransforms,n,t);r.setAll(i),t.convertToFoundDocument(Ox(t),r).setHasLocalMutations()}}(e,t,n):e instanceof Lx?function(e,t,n){if(Ax(e.precondition,t)){const r=Ux(e.fieldTransforms,n,t),i=t.data;i.setAll(Mx(e)),i.setAll(r),t.convertToFoundDocument(Ox(t),i).setHasLocalMutations()}}(e,t,n):(t=t,Ax(e.precondition,t)&&t.convertToNoDocument(GR.min()))}function xx(e,t){return e.type===t.type&&!!e.key.isEqual(t.key)&&!!e.precondition.isEqual(t.precondition)&&(n=e.fieldTransforms,r=t.fieldTransforms,!!(void 0===n&&void 0===r||n&&r&&KR(n,r,(e,t)=>function(e,t){return e.field.isEqual(t.field)&&(e=e.transform,t=t.transform,e instanceof yx&&t instanceof yx||e instanceof wx&&t instanceof wx?KR(e.elements,t.elements,vP):e instanceof Ix&&t instanceof Ix?vP(e.$,t.$):e instanceof vx&&t instanceof vx)}(e,t)))&&(0===e.type?e.value.isEqual(t.value):1!==e.type||e.data.isEqual(t.data)&&e.fieldMask.isEqual(t.fieldMask)));var n,r}function Ox(e){return e.isFoundDocument()?e.version:GR.min()}class Dx extends Nx{constructor(e,t,n,r=[]){super(),this.key=e,this.value=t,this.precondition=n,this.fieldTransforms=r,this.type=0}}class Lx extends Nx{constructor(e,t,n,r,i=[]){super(),this.key=e,this.data=t,this.fieldMask=n,this.precondition=r,this.fieldTransforms=i,this.type=1}}function Mx(n){const r=new Map;return n.fieldMask.fields.forEach(e=>{var t;e.isEmpty()||(t=n.data.field(e),r.set(e,t))}),r}function Fx(e,t,n){const r=new Map;RR(e.length===n.length);for(let u=0;u<n.length;u++){var i=e[u],s=i.transform,o=t.data.field(i.field);r.set(i.field,(a=s,c=o,l=n[u],a instanceof yx?_x(a,c):a instanceof wx?bx(a,c):l))}var a,c,l;return r}function Ux(e,t,n){const r=new Map;for(const l of e){const e=l.transform,u=n.data.field(l.field);r.set(l.field,(i=e,s=u,o=t,c=a=void 0,i instanceof vx?function(){const e={fields:{__type__:{stringValue:"server_timestamp"},__local_write_time__:{timestampValue:{seconds:o.seconds,nanos:o.nanoseconds}}}};return s&&(e.fields.__previous_value__=s),{mapValue:e}}():i instanceof yx?_x(i,s):i instanceof wx?bx(i,s):(a=mx(i=i,s),c=Tx(a)+Tx(i.$),TP(a)&&TP(i.$)?px(c):dx(i.O,c))))}var i,s,o,a,c;return r}class jx extends Nx{constructor(e,t){super(),this.key=e,this.precondition=t,this.type=2,this.fieldTransforms=[]}}class qx extends Nx{constructor(e,t){super(),this.key=e,this.precondition=t,this.type=3,this.fieldTransforms=[]}}class Vx{constructor(e){this.count=e}}function Bx(e){switch(e){default:return NR(),0;case PR.CANCELLED:case PR.UNKNOWN:case PR.DEADLINE_EXCEEDED:case PR.RESOURCE_EXHAUSTED:case PR.INTERNAL:case PR.UNAVAILABLE:case PR.UNAUTHENTICATED:return;case PR.INVALID_ARGUMENT:case PR.NOT_FOUND:case PR.ALREADY_EXISTS:case PR.PERMISSION_DENIED:case PR.FAILED_PRECONDITION:case PR.ABORTED:case PR.OUT_OF_RANGE:case PR.UNIMPLEMENTED:case PR.DATA_LOSS:return 1}}function Wx(e){if(void 0===e)return SR("GRPC error has no .code"),PR.UNKNOWN;switch(e){case uR.OK:return PR.OK;case uR.CANCELLED:return PR.CANCELLED;case uR.UNKNOWN:return PR.UNKNOWN;case uR.DEADLINE_EXCEEDED:return PR.DEADLINE_EXCEEDED;case uR.RESOURCE_EXHAUSTED:return PR.RESOURCE_EXHAUSTED;case uR.INTERNAL:return PR.INTERNAL;case uR.UNAVAILABLE:return PR.UNAVAILABLE;case uR.UNAUTHENTICATED:return PR.UNAUTHENTICATED;case uR.INVALID_ARGUMENT:return PR.INVALID_ARGUMENT;case uR.NOT_FOUND:return PR.NOT_FOUND;case uR.ALREADY_EXISTS:return PR.ALREADY_EXISTS;case uR.PERMISSION_DENIED:return PR.PERMISSION_DENIED;case uR.FAILED_PRECONDITION:return PR.FAILED_PRECONDITION;case uR.ABORTED:return PR.ABORTED;case uR.OUT_OF_RANGE:return PR.OUT_OF_RANGE;case uR.UNIMPLEMENTED:return PR.UNIMPLEMENTED;case uR.DATA_LOSS:return PR.DATA_LOSS;default:return NR()}}(c=uR=uR||{})[c.OK=0]="OK",c[c.CANCELLED=1]="CANCELLED",c[c.UNKNOWN=2]="UNKNOWN",c[c.INVALID_ARGUMENT=3]="INVALID_ARGUMENT",c[c.DEADLINE_EXCEEDED=4]="DEADLINE_EXCEEDED",c[c.NOT_FOUND=5]="NOT_FOUND",c[c.ALREADY_EXISTS=6]="ALREADY_EXISTS",c[c.PERMISSION_DENIED=7]="PERMISSION_DENIED",c[c.UNAUTHENTICATED=16]="UNAUTHENTICATED",c[c.RESOURCE_EXHAUSTED=8]="RESOURCE_EXHAUSTED",c[c.FAILED_PRECONDITION=9]="FAILED_PRECONDITION",c[c.ABORTED=10]="ABORTED",c[c.OUT_OF_RANGE=11]="OUT_OF_RANGE",c[c.UNIMPLEMENTED=12]="UNIMPLEMENTED",c[c.INTERNAL=13]="INTERNAL",c[c.UNAVAILABLE=14]="UNAVAILABLE",c[c.DATA_LOSS=15]="DATA_LOSS";class zx{constructor(e,t){this.comparator=e,this.root=t||$x.EMPTY}insert(e,t){return new zx(this.comparator,this.root.insert(e,t,this.comparator).copy(null,null,$x.BLACK,null,null))}remove(e){return new zx(this.comparator,this.root.remove(e,this.comparator).copy(null,null,$x.BLACK,null,null))}get(e){let t=this.root;for(;!t.isEmpty();){var n=this.comparator(e,t.key);if(0===n)return t.value;n<0?t=t.left:0<n&&(t=t.right)}return null}indexOf(e){let t=0,n=this.root;for(;!n.isEmpty();){var r=this.comparator(e,n.key);if(0===r)return t+n.left.size;n=r<0?n.left:(t+=n.left.size+1,n.right)}return-1}isEmpty(){return this.root.isEmpty()}get size(){return this.root.size}minKey(){return this.root.minKey()}maxKey(){return this.root.maxKey()}inorderTraversal(e){return this.root.inorderTraversal(e)}forEach(n){this.inorderTraversal((e,t)=>(n(e,t),!1))}toString(){const n=[];return this.inorderTraversal((e,t)=>(n.push(`${e}:${t}`),!1)),`{${n.join(", ")}}`}reverseTraversal(e){return this.root.reverseTraversal(e)}getIterator(){return new Kx(this.root,null,this.comparator,!1)}getIteratorFrom(e){return new Kx(this.root,e,this.comparator,!1)}getReverseIterator(){return new Kx(this.root,null,this.comparator,!0)}getReverseIteratorFrom(e){return new Kx(this.root,e,this.comparator,!0)}}class Kx{constructor(e,t,n,r){this.isReverse=r,this.nodeStack=[];let i=1;for(;!e.isEmpty();)if(i=t?n(e.key,t):1,r&&(i*=-1),i<0)e=this.isReverse?e.left:e.right;else{if(0===i){this.nodeStack.push(e);break}this.nodeStack.push(e),e=this.isReverse?e.right:e.left}}getNext(){let e=this.nodeStack.pop();var t={key:e.key,value:e.value};if(this.isReverse)for(e=e.left;!e.isEmpty();)this.nodeStack.push(e),e=e.right;else for(e=e.right;!e.isEmpty();)this.nodeStack.push(e),e=e.left;return t}hasNext(){return 0<this.nodeStack.length}peek(){if(0===this.nodeStack.length)return null;var e=this.nodeStack[this.nodeStack.length-1];return{key:e.key,value:e.value}}}class $x{constructor(e,t,n,r,i){this.key=e,this.value=t,this.color=null!=n?n:$x.RED,this.left=null!=r?r:$x.EMPTY,this.right=null!=i?i:$x.EMPTY,this.size=this.left.size+1+this.right.size}copy(e,t,n,r,i){return new $x(null!=e?e:this.key,null!=t?t:this.value,null!=n?n:this.color,null!=r?r:this.left,null!=i?i:this.right)}isEmpty(){return!1}inorderTraversal(e){return this.left.inorderTraversal(e)||e(this.key,this.value)||this.right.inorderTraversal(e)}reverseTraversal(e){return this.right.reverseTraversal(e)||e(this.key,this.value)||this.left.reverseTraversal(e)}min(){return this.left.isEmpty()?this:this.left.min()}minKey(){return this.min().key}maxKey(){return this.right.isEmpty()?this.key:this.right.maxKey()}insert(e,t,n){let r=this;var i=n(e,r.key);return r=i<0?r.copy(null,null,null,r.left.insert(e,t,n),null):0===i?r.copy(null,t,null,null,null):r.copy(null,null,null,null,r.right.insert(e,t,n)),r.fixUp()}removeMin(){if(this.left.isEmpty())return $x.EMPTY;let e=this;return e.left.isRed()||e.left.left.isRed()||(e=e.moveRedLeft()),e=e.copy(null,null,null,e.left.removeMin(),null),e.fixUp()}remove(e,t){let n,r=this;if(t(e,r.key)<0)r.left.isEmpty()||r.left.isRed()||r.left.left.isRed()||(r=r.moveRedLeft()),r=r.copy(null,null,null,r.left.remove(e,t),null);else{if(r.left.isRed()&&(r=r.rotateRight()),r.right.isEmpty()||r.right.isRed()||r.right.left.isRed()||(r=r.moveRedRight()),0===t(e,r.key)){if(r.right.isEmpty())return $x.EMPTY;n=r.right.min(),r=r.copy(n.key,n.value,null,null,r.right.removeMin())}r=r.copy(null,null,null,null,r.right.remove(e,t))}return r.fixUp()}isRed(){return this.color}fixUp(){let e=this;return e.right.isRed()&&!e.left.isRed()&&(e=e.rotateLeft()),e.left.isRed()&&e.left.left.isRed()&&(e=e.rotateRight()),e.left.isRed()&&e.right.isRed()&&(e=e.colorFlip()),e}moveRedLeft(){let e=this.colorFlip();return e.right.left.isRed()&&(e=e.copy(null,null,null,null,e.right.rotateRight()),e=e.rotateLeft(),e=e.colorFlip()),e}moveRedRight(){let e=this.colorFlip();return e.left.left.isRed()&&(e=e.rotateRight(),e=e.colorFlip()),e}rotateLeft(){var e=this.copy(null,null,$x.RED,null,this.right.left);return this.right.copy(null,null,this.color,e,null)}rotateRight(){var e=this.copy(null,null,$x.RED,this.left.right,null);return this.left.copy(null,null,this.color,null,e)}colorFlip(){var e=this.left.copy(null,null,!this.left.color,null,null),t=this.right.copy(null,null,!this.right.color,null,null);return this.copy(null,null,!this.color,e,t)}checkMaxDepth(){var e=this.check();return Math.pow(2,e)<=this.size+1}check(){if(this.isRed()&&this.left.isRed())throw NR();if(this.right.isRed())throw NR();var e=this.left.check();if(e!==this.right.check())throw NR();return e+(this.isRed()?0:1)}}$x.EMPTY=null,$x.RED=!0,$x.BLACK=!1,$x.EMPTY=new class{constructor(){this.size=0}get key(){throw NR()}get value(){throw NR()}get color(){throw NR()}get left(){throw NR()}get right(){throw NR()}copy(e,t,n,r,i){return this}insert(e,t,n){return new $x(e,t)}remove(e,t){return this}isEmpty(){return!0}inorderTraversal(e){return!1}reverseTraversal(e){return!1}minKey(){return null}maxKey(){return null}isRed(){return!1}checkMaxDepth(){return!0}check(){return 0}};class Hx{constructor(e){this.comparator=e,this.data=new zx(this.comparator)}has(e){return null!==this.data.get(e)}first(){return this.data.minKey()}last(){return this.data.maxKey()}get size(){return this.data.size}indexOf(e){return this.data.indexOf(e)}forEach(n){this.data.inorderTraversal((e,t)=>(n(e),!1))}forEachInRange(e,t){const n=this.data.getIteratorFrom(e[0]);for(;n.hasNext();){var r=n.getNext();if(0<=this.comparator(r.key,e[1]))return;t(r.key)}}forEachWhile(e,t){let n;for(n=void 0!==t?this.data.getIteratorFrom(t):this.data.getIterator();n.hasNext();)if(!e(n.getNext().key))return}firstAfterOrEqual(e){const t=this.data.getIteratorFrom(e);return t.hasNext()?t.getNext().key:null}getIterator(){return new Gx(this.data.getIterator())}getIteratorFrom(e){return new Gx(this.data.getIteratorFrom(e))}add(e){return this.copy(this.data.remove(e).insert(e,!0))}delete(e){return this.has(e)?this.copy(this.data.remove(e)):this}isEmpty(){return this.data.isEmpty()}unionWith(e){let t=this;return t.size<e.size&&(t=e,e=this),e.forEach(e=>{t=t.add(e)}),t}isEqual(e){if(!(e instanceof Hx))return!1;if(this.size!==e.size)return!1;const t=this.data.getIterator(),n=e.data.getIterator();for(;t.hasNext();){const e=t.getNext().key,r=n.getNext().key;if(0!==this.comparator(e,r))return!1}return!0}toArray(){const t=[];return this.forEach(e=>{t.push(e)}),t}toString(){const t=[];return this.forEach(e=>t.push(e)),"SortedSet("+t.toString()+")"}copy(e){const t=new Hx(this.comparator);return t.data=e,t}}class Gx{constructor(e){this.iter=e}getNext(){return this.iter.getNext().key}hasNext(){return this.iter.hasNext()}}const Qx=new zx(gP.comparator);const Yx=new zx(gP.comparator);const Xx=new zx(gP.comparator),Jx=new Hx(gP.comparator);function Zx(...e){let t=Jx;for(const n of e)t=t.add(n);return t}const eO=new Hx(zR);class tO{constructor(e,t,n,r,i){this.snapshotVersion=e,this.targetChanges=t,this.targetMismatches=n,this.documentUpdates=r,this.resolvedLimboDocuments=i}static createSynthesizedRemoteEventForCurrentChange(e,t){const n=new Map;return n.set(e,nO.createSynthesizedTargetChangeForCurrentChange(e,t)),new tO(GR.min(),n,eO,Qx,Zx())}}class nO{constructor(e,t,n,r,i){this.resumeToken=e,this.current=t,this.addedDocuments=n,this.modifiedDocuments=r,this.removedDocuments=i}static createSynthesizedTargetChangeForCurrentChange(e,t){return new nO(rP.EMPTY_BYTE_STRING,t,Zx(),Zx(),Zx())}}class rO{constructor(e,t,n,r){this.M=e,this.removedTargetIds=t,this.key=n,this.F=r}}class iO{constructor(e,t){this.targetId=e,this.L=t}}class sO{constructor(e,t,n=rP.EMPTY_BYTE_STRING,r=null){this.state=e,this.targetIds=t,this.resumeToken=n,this.cause=r}}class oO{constructor(){this.B=0,this.U=lO(),this.q=rP.EMPTY_BYTE_STRING,this.K=!1,this.j=!0}get current(){return this.K}get resumeToken(){return this.q}get W(){return 0!==this.B}get G(){return this.j}H(e){0<e.approximateByteSize()&&(this.j=!0,this.q=e)}J(){let n=Zx(),r=Zx(),i=Zx();return this.U.forEach((e,t)=>{switch(t){case 0:n=n.add(e);break;case 2:r=r.add(e);break;case 1:i=i.add(e);break;default:NR()}}),new nO(this.q,this.K,n,r,i)}Y(){this.j=!1,this.U=lO()}X(e,t){this.j=!0,this.U=this.U.insert(e,t)}Z(e){this.j=!0,this.U=this.U.remove(e)}tt(){this.B+=1}et(){--this.B}nt(){this.j=!0,this.K=!0}}class aO{constructor(e){this.st=e,this.it=new Map,this.rt=Qx,this.ot=cO(),this.ct=new Hx(zR)}at(e){for(const t of e.M)e.F&&e.F.isFoundDocument()?this.ut(t,e.F):this.ht(t,e.key,e.F);for(const n of e.removedTargetIds)this.ht(n,e.key,e.F)}lt(n){this.forEachTarget(n,e=>{const t=this.ft(e);switch(n.state){case 0:this.dt(e)&&t.H(n.resumeToken);break;case 1:t.et(),t.W||t.Y(),t.H(n.resumeToken);break;case 2:t.et(),t.W||this.removeTarget(e);break;case 3:this.dt(e)&&(t.nt(),t.H(n.resumeToken));break;case 4:this.dt(e)&&(this.wt(e),t.H(n.resumeToken));break;default:NR()}})}forEachTarget(e,n){0<e.targetIds.length?e.targetIds.forEach(n):this.it.forEach((e,t)=>{this.dt(t)&&n(t)})}_t(e){const t=e.targetId,n=e.L.count,r=this.gt(t);if(r){const e=r.target;if(LP(e))if(0===n){const n=new gP(e.path);this.ht(t,n,RP.newNoDocument(n,GR.min()))}else RR(1===n);else this.yt(t)!==n&&(this.wt(t),this.ct=this.ct.add(t))}}Tt(r){const i=new Map;this.it.forEach((e,t)=>{var n=this.gt(t);if(n){if(e.current&&LP(n.target)){const i=new gP(n.target.path);null!==this.rt.get(i)||this.Et(t,i)||this.ht(t,i,RP.newNoDocument(i,r))}e.G&&(i.set(t,e.J()),e.Y())}});let s=Zx();this.ot.forEach((e,t)=>{let n=!0;t.forEachWhile(e=>{var t=this.gt(e);return!t||2===t.purpose||(n=!1)}),n&&(s=s.add(e))}),this.rt.forEach((e,t)=>t.setReadTime(r));var e=new tO(r,i,this.ct,this.rt,s);return this.rt=Qx,this.ot=cO(),this.ct=new Hx(zR),e}ut(e,t){var n;this.dt(e)&&(n=this.Et(e,t.key)?2:0,this.ft(e).X(t.key,n),this.rt=this.rt.insert(t.key,t),this.ot=this.ot.insert(t.key,this.It(t.key).add(e)))}ht(e,t,n){if(this.dt(e)){const r=this.ft(e);this.Et(e,t)?r.X(t,1):r.Z(t),this.ot=this.ot.insert(t,this.It(t).delete(e)),n&&(this.rt=this.rt.insert(t,n))}}removeTarget(e){this.it.delete(e)}yt(e){var t=this.ft(e).J();return this.st.getRemoteKeysForTarget(e).size+t.addedDocuments.size-t.removedDocuments.size}tt(e){this.ft(e).tt()}ft(e){let t=this.it.get(e);return t||(t=new oO,this.it.set(e,t)),t}It(e){let t=this.ot.get(e);return t||(t=new Hx(zR),this.ot=this.ot.insert(e,t)),t}dt(e){var t=null!==this.gt(e);return t||kR("WatchChangeAggregator","Detected inactive target",e),t}gt(e){var t=this.it.get(e);return t&&t.W?null:this.st.At(e)}wt(t){this.it.set(t,new oO),this.st.getRemoteKeysForTarget(t).forEach(e=>{this.ht(t,e,null)})}Et(e,t){return this.st.getRemoteKeysForTarget(e).has(t)}}function cO(){return new zx(gP.comparator)}function lO(){return new zx(gP.comparator)}const uO={asc:"ASCENDING",desc:"DESCENDING"},hO={"<":"LESS_THAN","<=":"LESS_THAN_OR_EQUAL",">":"GREATER_THAN",">=":"GREATER_THAN_OR_EQUAL","==":"EQUAL","!=":"NOT_EQUAL","array-contains":"ARRAY_CONTAINS",in:"IN","not-in":"NOT_IN","array-contains-any":"ARRAY_CONTAINS_ANY"};class dO{constructor(e,t){this.databaseId=e,this.k=t}}function pO(e,t){return e.k?`${new Date(1e3*t.seconds).toISOString().replace(/\.\d*/,"").replace("Z","")}.${("000000000"+t.nanoseconds).slice(-9)}Z`:{seconds:""+t.seconds,nanos:t.nanoseconds}}function fO(e,t){return e.k?t.toBase64():t.toUint8Array()}function gO(e){return RR(!!e),GR.fromTimestamp((t=sP(e),new HR(t.seconds,t.nanos)));var t}function mO(e,t){return e=e,new ZR(["projects",e.projectId,"databases",e.database]).child("documents").child(t).canonicalString()}function vO(e){var t=ZR.fromString(e);return RR(FO(t)),t}function yO(e,t){return mO(e.databaseId,t.path)}function _O(e,t){const n=vO(t);if(n.get(1)!==e.databaseId.projectId)throw new xR(PR.INVALID_ARGUMENT,"Tried to deserialize key from different project: "+n.get(1)+" vs "+e.databaseId.projectId);if(n.get(3)!==e.databaseId.database)throw new xR(PR.INVALID_ARGUMENT,"Tried to deserialize key from different database: "+n.get(3)+" vs "+e.databaseId.database);return new gP(TO(n))}function wO(e,t){return mO(e.databaseId,t)}function bO(e){var t=vO(e);return 4===t.length?ZR.emptyPath():TO(t)}function IO(e){return new ZR(["projects",e.databaseId.projectId,"databases",e.databaseId.database]).canonicalString()}function TO(e){return RR(4<e.length&&"documents"===e.get(4)),e.popFirst(5)}function EO(e,t,n){return{name:yO(e,t),fields:n.value.mapValue.fields}}function kO(e,t,n){const r=_O(e,t.name),i=gO(t.updateTime),s=new NP({mapValue:{fields:t.fields}}),o=RP.newFoundDocument(r,i,s);return n&&o.setHasCommittedMutations(),n?o.setHasCommittedMutations():o}function SO(e,t){let n;if(t instanceof Dx)n={update:EO(e,t.key,t.value)};else if(t instanceof jx)n={delete:yO(e,t.key)};else if(t instanceof Lx)n={update:EO(e,t.key,t.data),updateMask:function(e){const t=[];return e.fields.forEach(e=>t.push(e.canonicalString())),{fieldPaths:t}}(t.fieldMask)};else{if(!(t instanceof qx))return NR();n={verify:yO(e,t.key)}}return 0<t.fieldTransforms.length&&(n.updateTransforms=t.fieldTransforms.map(e=>function(e){var t=e.transform;if(t instanceof vx)return{fieldPath:e.field.canonicalString(),setToServerValue:"REQUEST_TIME"};if(t instanceof yx)return{fieldPath:e.field.canonicalString(),appendMissingElements:{values:t.elements}};if(t instanceof wx)return{fieldPath:e.field.canonicalString(),removeAllFromArray:{values:t.elements}};if(t instanceof Ix)return{fieldPath:e.field.canonicalString(),increment:t.$};throw NR()}(e))),t.precondition.isNone||(n.currentDocument=void 0!==(r=t.precondition).updateTime?{updateTime:(t=r.updateTime,pO(e,t.toTimestamp()))}:void 0!==r.exists?{exists:r.exists}:NR()),n;var r}function CO(t,n){const e=n.currentDocument?void 0!==(i=n.currentDocument).updateTime?Cx.updateTime(gO(i.updateTime)):void 0!==i.exists?Cx.exists(i.exists):Cx.none():Cx.none(),r=n.updateTransforms?n.updateTransforms.map(e=>function(e,t){let n=null;if("setToServerValue"in t)RR("REQUEST_TIME"===t.setToServerValue),n=new vx;else if("appendMissingElements"in t){const e=t.appendMissingElements.values||[];n=new yx(e)}else if("removeAllFromArray"in t){const e=t.removeAllFromArray.values||[];n=new wx(e)}else"increment"in t?n=new Ix(e,t.increment):NR();var r=tP.fromServerFormat(t.fieldPath);return new kx(r,n)}(t,e)):[];var i;if(n.update){n.update.name;var s=_O(t,n.update.name),o=new NP({mapValue:{fields:n.update.fields}});if(n.updateMask){const t=function(){const e=n.updateMask.fieldPaths||[];return new nP(e.map(e=>tP.fromServerFormat(e)))}();return new Lx(s,o,t,e,r)}return new Dx(s,o,e,r)}if(n.delete){const r=_O(t,n.delete);return new jx(r,e)}if(n.verify){const r=_O(t,n.verify);return new qx(r,e)}return NR()}function AO(e,t){return{documents:[wO(e,t.path)]}}function NO(e,t){const n={structuredQuery:{}},r=t.path;null!==t.collectionGroup?(n.parent=wO(e,r),n.structuredQuery.from=[{collectionId:t.collectionGroup,allDescendants:!0}]):(n.parent=wO(e,r.popLast()),n.structuredQuery.from=[{collectionId:r.lastSegment()}]);var i=function(e){if(0!==e.length){var t=e.map(e=>function(e){if("=="===e.op){if(SP(e.value))return{unaryFilter:{field:OO(e.field),op:"IS_NAN"}};if(kP(e.value))return{unaryFilter:{field:OO(e.field),op:"IS_NULL"}}}else if("!="===e.op){if(SP(e.value))return{unaryFilter:{field:OO(e.field),op:"IS_NOT_NAN"}};if(kP(e.value))return{unaryFilter:{field:OO(e.field),op:"IS_NOT_NULL"}}}return{fieldFilter:{field:OO(e.field),op:(t=e.op,hO[t]),value:e.value}};var t}(e));return 1===t.length?t[0]:{compositeFilter:{op:"AND",filters:t}}}}(t.filters);i&&(n.structuredQuery.where=i);i=function(e){if(0!==e.length)return e.map(e=>function(e){return{field:OO(e.field),direction:(e=e.dir,uO[e])}}(e))}(t.orderBy);i&&(n.structuredQuery.orderBy=i);var s,i=(s=t.limit,e.k||dP(s)?s:{value:s});return null!==i&&(n.structuredQuery.limit=i),t.startAt&&(n.structuredQuery.startAt=PO(t.startAt)),t.endAt&&(n.structuredQuery.endAt=PO(t.endAt)),n}function RO(e){let t=bO(e.parent);const n=e.structuredQuery,r=n.from?n.from.length:0;let i=null;if(0<r){RR(1===r);const h=n.from[0];h.allDescendants?i=h.collectionId:t=t.child(h.collectionId)}let s=[];n.where&&(s=function t(e){return e?void 0!==e.unaryFilter?[MO(e)]:void 0!==e.fieldFilter?[LO(e)]:void 0!==e.compositeFilter?e.compositeFilter.filters.map(e=>t(e)).reduce((e,t)=>e.concat(t)):NR():[]}(n.where));let o=[];n.orderBy&&(o=n.orderBy.map(e=>function(e){return new HP(DO(e.field),function(){switch(e.direction){case"ASCENDING":return"asc";case"DESCENDING":return"desc";default:return}}())}(e)));let a=null;var c;n.limit&&(a=(e=n.limit,dP(c="object"==typeof e?e.value:e)?null:c));let l=null;n.startAt&&(l=xO(n.startAt));let u=null;return n.endAt&&(u=xO(n.endAt)),XP(t,i,o,s,a,"F",l,u)}function PO(e){return{before:e.before,values:e.position}}function xO(e){var t=!!e.before,n=e.values||[];return new KP(n,t)}function OO(e){return{fieldPath:e.canonicalString()}}function DO(e){return tP.fromServerFormat(e.fieldPath)}function LO(e){return MP.create(DO(e.fieldFilter.field),function(){switch(e.fieldFilter.op){case"EQUAL":return"==";case"NOT_EQUAL":return"!=";case"GREATER_THAN":return">";case"GREATER_THAN_OR_EQUAL":return">=";case"LESS_THAN":return"<";case"LESS_THAN_OR_EQUAL":return"<=";case"ARRAY_CONTAINS":return"array-contains";case"IN":return"in";case"NOT_IN":return"not-in";case"ARRAY_CONTAINS_ANY":return"array-contains-any";default:return NR()}}(),e.fieldFilter.value)}function MO(e){switch(e.unaryFilter.op){case"IS_NAN":var t=DO(e.unaryFilter.field);return MP.create(t,"==",{doubleValue:NaN});case"IS_NULL":t=DO(e.unaryFilter.field);return MP.create(t,"==",{nullValue:"NULL_VALUE"});case"IS_NOT_NAN":var n=DO(e.unaryFilter.field);return MP.create(n,"!=",{doubleValue:NaN});case"IS_NOT_NULL":n=DO(e.unaryFilter.field);return MP.create(n,"!=",{nullValue:"NULL_VALUE"});default:return NR()}}function FO(e){return 4<=e.length&&"projects"===e.get(0)&&"databases"===e.get(2)}function UO(e){let t="";for(let n=0;n<e.length;n++)0<t.length&&(t=jO(t)),t=function(e,t){let n=t;const r=e.length;for(let i=0;i<r;i++){const r=e.charAt(i);switch(r){case"\0":n+="";break;case"":n+="";break;default:n+=r}}return n}(e.get(n),t);return jO(t)}function jO(e){return e+""}function qO(t){const n=t.length;if(RR(2<=n),2===n)return RR(""===t.charAt(0)&&""===t.charAt(1)),ZR.emptyPath();const r=n-2,i=[];let s="";for(let o=0;o<n;){const n=t.indexOf("",o);switch((n<0||n>r)&&NR(),t.charAt(n+1)){case"":const r=t.substring(o,n);let e;0===s.length?e=r:(s+=r,e=s,s=""),i.push(e);break;case"":s+=t.substring(o,n),s+="\0";break;case"":s+=t.substring(o,n+1);break;default:NR()}o=n+2}return new ZR(i)}class VO{constructor(e,t){this.seconds=e,this.nanoseconds=t}}class BO{constructor(e,t,n){this.ownerId=e,this.allowTabSynchronization=t,this.leaseTimestampMs=n}}BO.store="owner",BO.key="owner";class WO{constructor(e,t,n){this.userId=e,this.lastAcknowledgedBatchId=t,this.lastStreamToken=n}}WO.store="mutationQueues",WO.keyPath="userId";class zO{constructor(e,t,n,r,i){this.userId=e,this.batchId=t,this.localWriteTimeMs=n,this.baseMutations=r,this.mutations=i}}zO.store="mutations",zO.keyPath="batchId",zO.userMutationsIndex="userMutationsIndex",zO.userMutationsKeyPath=["userId","batchId"];class KO{constructor(){}static prefixForUser(e){return[e]}static prefixForPath(e,t){return[e,UO(t)]}static key(e,t,n){return[e,UO(t),n]}}KO.store="documentMutations",KO.PLACEHOLDER=new KO;class $O{constructor(e,t){this.path=e,this.readTime=t}}class HO{constructor(e,t){this.path=e,this.version=t}}class GO{constructor(e,t,n,r,i,s){this.unknownDocument=e,this.noDocument=t,this.document=n,this.hasCommittedMutations=r,this.readTime=i,this.parentPath=s}}GO.store="remoteDocuments",GO.readTimeIndex="readTimeIndex",GO.readTimeIndexPath="readTime",GO.collectionReadTimeIndex="collectionReadTimeIndex",GO.collectionReadTimeIndexPath=["parentPath","readTime"];class QO{constructor(e){this.byteSize=e}}QO.store="remoteDocumentGlobal",QO.key="remoteDocumentGlobalKey";class YO{constructor(e,t,n,r,i,s,o){this.targetId=e,this.canonicalId=t,this.readTime=n,this.resumeToken=r,this.lastListenSequenceNumber=i,this.lastLimboFreeSnapshotVersion=s,this.query=o}}YO.store="targets",YO.keyPath="targetId",YO.queryTargetsIndexName="queryTargetsIndex",YO.queryTargetsKeyPath=["canonicalId","targetId"];class XO{constructor(e,t,n){this.targetId=e,this.path=t,this.sequenceNumber=n}}XO.store="targetDocuments",XO.keyPath=["targetId","path"],XO.documentTargetsIndex="documentTargetsIndex",XO.documentTargetsKeyPath=["path","targetId"];class JO{constructor(e,t,n,r){this.highestTargetId=e,this.highestListenSequenceNumber=t,this.lastRemoteSnapshotVersion=n,this.targetCount=r}}JO.key="targetGlobalKey",JO.store="targetGlobal";class ZO{constructor(e,t){this.collectionId=e,this.parent=t}}ZO.store="collectionParents",ZO.keyPath=["collectionId","parent"];class eD{constructor(e,t,n,r){this.clientId=e,this.updateTimeMs=t,this.networkEnabled=n,this.inForeground=r}}eD.store="clientMetadata",eD.keyPath="clientId";class tD{constructor(e,t,n){this.bundleId=e,this.createTime=t,this.version=n}}tD.store="bundles",tD.keyPath="bundleId";class nD{constructor(e,t,n){this.name=e,this.readTime=t,this.bundledQuery=n}}nD.store="namedQueries",nD.keyPath="name";class rD{constructor(e,t,n){this.indexId=e,this.collectionGroup=t,this.fields=n}}rD.store="indexConfiguration",rD.keyPath="indexId";class iD{constructor(e,t,n,r,i,s){this.indexId=e,this.uid=t,this.sequenceNumber=n,this.readTime=r,this.documentKey=i,this.largestBatchId=s}}iD.store="indexState",iD.keyPath=["indexId","uid"];class sD{constructor(e,t,n,r,i){this.indexId=e,this.uid=t,this.arrayValue=n,this.directionalValue=r,this.documentKey=i}}sD.store="indexEntries",sD.keyPath=["indexId","uid","arrayValue","directionalValue","documentKey"];const oD=[WO.store,zO.store,KO.store,GO.store,YO.store,BO.store,JO.store,XO.store,eD.store,QO.store,ZO.store,tD.store,nD.store],aD="The current tab is not in the required state to perform this operation. It might be necessary to refresh the browser tab.";class cD{constructor(){this.onCommittedListeners=[]}addOnCommittedListener(e){this.onCommittedListeners.push(e)}raiseOnCommittedEvent(){this.onCommittedListeners.forEach(e=>e())}}class lD{constructor(e){this.nextCallback=null,this.catchCallback=null,this.result=void 0,this.error=void 0,this.isDone=!1,this.callbackAttached=!1,e(e=>{this.isDone=!0,this.result=e,this.nextCallback&&this.nextCallback(e)},e=>{this.isDone=!0,this.error=e,this.catchCallback&&this.catchCallback(e)})}catch(e){return this.next(void 0,e)}next(r,i){return this.callbackAttached&&NR(),this.callbackAttached=!0,this.isDone?this.error?this.wrapFailure(i,this.error):this.wrapSuccess(r,this.result):new lD((t,n)=>{this.nextCallback=e=>{this.wrapSuccess(r,e).next(t,n)},this.catchCallback=e=>{this.wrapFailure(i,e).next(t,n)}})}toPromise(){return new Promise((e,t)=>{this.next(e,t)})}wrapUserFunction(e){try{var t=e();return t instanceof lD?t:lD.resolve(t)}catch(e){return lD.reject(e)}}wrapSuccess(e,t){return e?this.wrapUserFunction(()=>e(t)):lD.resolve(t)}wrapFailure(e,t){return e?this.wrapUserFunction(()=>e(t)):lD.reject(t)}static resolve(n){return new lD((e,t)=>{e(n)})}static reject(n){return new lD((e,t)=>{t(n)})}static waitFor(e){return new lD((t,n)=>{let r=0,i=0,s=!1;e.forEach(e=>{++r,e.next(()=>{++i,s&&i===r&&t()},e=>n(e))}),s=!0,i===r&&t()})}static or(e){let t=lD.resolve(!1);for(const n of e)t=t.next(e=>e?lD.resolve(e):n());return t}static forEach(e,n){const r=[];return e.forEach((e,t)=>{r.push(n.call(this,e,t))}),this.waitFor(r)}}class uD{constructor(n,e){this.action=n,this.transaction=e,this.aborted=!1,this.Rt=new OR,this.transaction.oncomplete=()=>{this.Rt.resolve()},this.transaction.onabort=()=>{e.error?this.Rt.reject(new pD(n,e.error)):this.Rt.resolve()},this.transaction.onerror=e=>{var t=yD(e.target.error);this.Rt.reject(new pD(n,t))}}static open(e,t,n,r){try{return new uD(t,e.transaction(r,n))}catch(e){throw new pD(t,e)}}get bt(){return this.Rt.promise}abort(e){e&&this.Rt.reject(e),this.aborted||(kR("SimpleDb","Aborting transaction:",e?e.message:"Client-initiated abort"),this.aborted=!0,this.transaction.abort())}store(e){var t=this.transaction.objectStore(e);return new gD(t)}}class hD{constructor(e,t,n){this.name=e,this.version=t,this.Pt=n,12.2===hD.vt(sd())&&SR("Firestore persistence suffers from a bug in iOS 12.2 Safari that may cause your app to stop working. See https://stackoverflow.com/q/56496296/110915 for details and a potential workaround.")}static delete(e){return kR("SimpleDb","Removing database:",e),mD(window.indexedDB.deleteDatabase(e)).toPromise()}static Vt(){if(!dd())return!1;if(hD.St())return!0;const e=sd(),t=hD.vt(e),n=0<t&&t<10,r=hD.Dt(e),i=0<r&&r<4.5;return!(0<e.indexOf("MSIE ")||0<e.indexOf("Trident/")||0<e.indexOf("Edge/")||n||i)}static St(){var e;return"undefined"!=typeof process&&"YES"===(null===(e=process.env)||void 0===e?void 0:e.Ct)}static Nt(e,t){return e.store(t)}static vt(e){const t=e.match(/i(?:phone|pad|pod) os ([\d_]+)/i),n=t?t[1].split("_").slice(0,2).join("."):"-1";return Number(n)}static Dt(e){const t=e.match(/Android ([\d.]+)/i),n=t?t[1].split(".").slice(0,2).join("."):"-1";return Number(n)}async kt(s){return this.db||(kR("SimpleDb","Opening database:",this.name),this.db=await new Promise((n,r)=>{const i=indexedDB.open(this.name,this.version);i.onsuccess=e=>{var t=e.target.result;n(t)},i.onblocked=()=>{r(new pD(s,"Cannot upgrade IndexedDB schema while another tab is open. Close all tabs that access Firestore and reload this page to proceed."))},i.onerror=e=>{var t=e.target.error;"VersionError"===t.name?r(new xR(PR.FAILED_PRECONDITION,"A newer version of the Firestore SDK was previously used and so the persisted data is not compatible with the version of the SDK you are now using. The SDK will operate with persistence disabled. If you need persistence, please re-upgrade to a newer version of the SDK or else clear the persisted IndexedDB data for your app to start fresh.")):"InvalidStateError"===t.name?r(new xR(PR.FAILED_PRECONDITION,"Unable to open an IndexedDB connection. This could be due to running in a private browsing session on a browser whose private browsing sessions do not support IndexedDB: "+t)):r(new pD(s,t))},i.onupgradeneeded=e=>{kR("SimpleDb",'Database "'+this.name+'" requires upgrade from version:',e.oldVersion);var t=e.target.result;this.Pt.xt(t,i.transaction,e.oldVersion,this.version).next(()=>{kR("SimpleDb","Database upgrade to version "+this.version+" complete")})}})),this.$t&&(this.db.onversionchange=e=>this.$t(e)),this.db}Ot(t){this.$t=t,this.db&&(this.db.onversionchange=e=>t(e))}async runTransaction(e,t,n,r){var i="readonly"===t;let s=0;for(;;){++s;try{this.db=await this.kt(e);const t=uD.open(this.db,e,i?"readonly":"readwrite",n),s=r(t).catch(e=>(t.abort(e),lD.reject(e))).toPromise();return s.catch(()=>{}),await t.bt,s}catch(e){const t="FirebaseError"!==e.name&&s<3;if(kR("SimpleDb","Transaction failed with error:",e.message,"Retrying:",t),this.close(),!t)return Promise.reject(e)}}}close(){this.db&&this.db.close(),this.db=void 0}}class dD{constructor(e){this.Mt=e,this.Ft=!1,this.Lt=null}get isDone(){return this.Ft}get Bt(){return this.Lt}set cursor(e){this.Mt=e}done(){this.Ft=!0}Ut(e){this.Lt=e}delete(){return mD(this.Mt.delete())}}class pD extends xR{constructor(e,t){super(PR.UNAVAILABLE,`IndexedDB transaction '${e}' failed: ${t}`),this.name="IndexedDbTransactionError"}}function fD(e){return"IndexedDbTransactionError"===e.name}class gD{constructor(e){this.store=e}put(e,t){let n;return n=void 0!==t?(kR("SimpleDb","PUT",this.store.name,e,t),this.store.put(t,e)):(kR("SimpleDb","PUT",this.store.name,"<auto-key>",e),this.store.put(e)),mD(n)}add(e){return kR("SimpleDb","ADD",this.store.name,e,e),mD(this.store.add(e))}get(t){return mD(this.store.get(t)).next(e=>(kR("SimpleDb","GET",this.store.name,t,e=void 0===e?null:e),e))}delete(e){return kR("SimpleDb","DELETE",this.store.name,e),mD(this.store.delete(e))}count(){return kR("SimpleDb","COUNT",this.store.name),mD(this.store.count())}qt(e,t){const n=this.cursor(this.options(e,t)),r=[];return this.Kt(n,(e,t)=>{r.push(t)}).next(()=>r)}jt(e,t){kR("SimpleDb","DELETE ALL",this.store.name);const n=this.options(e,t);n.Qt=!1;var r=this.cursor(n);return this.Kt(r,(e,t,n)=>n.delete())}Wt(e,t){let n;t?n=e:(n={},t=e);var r=this.cursor(n);return this.Kt(r,t)}Gt(i){const e=this.cursor({});return new lD((n,r)=>{e.onerror=e=>{var t=yD(e.target.error);r(t)},e.onsuccess=e=>{const t=e.target.result;t?i(t.primaryKey,t.value).next(e=>{e?t.continue():n()}):n()}})}Kt(e,s){const o=[];return new lD((i,t)=>{e.onerror=e=>{t(e.target.error)},e.onsuccess=e=>{const t=e.target.result;if(t){const n=new dD(t),r=s(t.primaryKey,t.value,n);if(r instanceof lD){const e=r.catch(e=>(n.done(),lD.reject(e)));o.push(e)}n.isDone?i():null===n.Bt?t.continue():t.continue(n.Bt)}else i()}}).next(()=>lD.waitFor(o))}options(e,t){let n;return void 0!==e&&("string"==typeof e?n=e:t=e),{index:n,range:t}}cursor(e){let t="next";if(e.reverse&&(t="prev"),e.index){const n=this.store.index(e.index);return e.Qt?n.openKeyCursor(e.range,t):n.openCursor(e.range,t)}return this.store.openCursor(e.range,t)}}function mD(e){return new lD((n,r)=>{e.onsuccess=e=>{var t=e.target.result;n(t)},e.onerror=e=>{var t=yD(e.target.error);r(t)}})}let vD=!1;function yD(e){const t=hD.vt(sd());if(12.2<=t&&t<13){const t="An internal error was encountered in the Indexed Database server";if(0<=e.message.indexOf(t)){const e=new xR("internal",`IOS_INDEXEDDB_BUG1: IndexedDb has thrown '${t}'. This is likely due to an unavoidable bug in iOS. See https://stackoverflow.com/q/56496296/110915 for details and a potential workaround.`);return vD||(vD=!0,setTimeout(()=>{throw e},0)),e}}return e}class _D extends cD{constructor(e,t){super(),this.zt=e,this.currentSequenceNumber=t}}function wD(e,t){var n=e;return hD.Nt(n.zt,t)}class bD{constructor(e,t,n,r){this.batchId=e,this.localWriteTime=t,this.baseMutations=n,this.mutations=r}applyToRemoteDocument(e,t){var n=t.mutationResults;for(let r=0;r<this.mutations.length;r++){const i=this.mutations[r];i.key.isEqual(e.key)&&Rx(i,e,n[r])}}applyToLocalView(e){for(const t of this.baseMutations)t.key.isEqual(e.key)&&Px(t,e,this.localWriteTime);for(const n of this.mutations)n.key.isEqual(e.key)&&Px(n,e,this.localWriteTime)}applyToLocalDocumentSet(r){this.mutations.forEach(e=>{const t=r.get(e.key),n=t;this.applyToLocalView(n),t.isValidDocument()||n.convertToNoDocument(GR.min())})}keys(){return this.mutations.reduce((e,t)=>e.add(t.key),Zx())}isEqual(e){return this.batchId===e.batchId&&KR(this.mutations,e.mutations,(e,t)=>xx(e,t))&&KR(this.baseMutations,e.baseMutations,(e,t)=>xx(e,t))}}class ID{constructor(e,t,n,r){this.batch=e,this.commitVersion=t,this.mutationResults=n,this.docVersions=r}static from(e,t,n){RR(e.mutations.length===n.length);let r=Xx;var i=e.mutations;for(let s=0;s<i.length;s++)r=r.insert(i[s].key,n[s].version);return new ID(e,t,n,r)}}class TD{constructor(e,t,n,r,i=GR.min(),s=GR.min(),o=rP.EMPTY_BYTE_STRING){this.target=e,this.targetId=t,this.purpose=n,this.sequenceNumber=r,this.snapshotVersion=i,this.lastLimboFreeSnapshotVersion=s,this.resumeToken=o}withSequenceNumber(e){return new TD(this.target,this.targetId,this.purpose,e,this.snapshotVersion,this.lastLimboFreeSnapshotVersion,this.resumeToken)}withResumeToken(e,t){return new TD(this.target,this.targetId,this.purpose,this.sequenceNumber,t,this.lastLimboFreeSnapshotVersion,e)}withLastLimboFreeSnapshotVersion(e){return new TD(this.target,this.targetId,this.purpose,this.sequenceNumber,this.snapshotVersion,e,this.resumeToken)}}class ED{constructor(e){this.Ht=e}}function kD(e,t){let n;if(t.document)n=kO(e.Ht,t.document,!!t.hasCommittedMutations);else if(t.noDocument){const e=gP.fromSegments(t.noDocument.path),r=RD(t.noDocument.readTime);n=RP.newNoDocument(e,r),t.hasCommittedMutations&&n.setHasCommittedMutations()}else{if(!t.unknownDocument)return NR();{const e=gP.fromSegments(t.unknownDocument.path),i=RD(t.unknownDocument.version);n=RP.newUnknownDocument(e,i)}}return t.readTime&&n.setReadTime(AD(t.readTime)),n}function SD(e,t){var n,r=CD(t.readTime),i=t.key.path.popLast().toArray();if(t.isFoundDocument()){var s={name:yO(n=e.Ht,(e=t).key),fields:e.data.value.mapValue.fields,updateTime:pO(n,e.version.toTimestamp())},o=t.hasCommittedMutations;return new GO(null,null,s,o,r,i)}if(t.isNoDocument()){const a=t.key.path.toArray(),c=ND(t.version),l=t.hasCommittedMutations;return new GO(null,new $O(a,c),null,l,r,i)}if(t.isUnknownDocument()){const a=t.key.path.toArray(),u=ND(t.version);return new GO(new HO(a,u),null,null,!0,r,i)}return NR()}function CD(e){var t=e.toTimestamp();return[t.seconds,t.nanoseconds]}function AD(e){var t=new HR(e[0],e[1]);return GR.fromTimestamp(t)}function ND(e){var t=e.toTimestamp();return new VO(t.seconds,t.nanoseconds)}function RD(e){var t=new HR(e.seconds,e.nanoseconds);return GR.fromTimestamp(t)}function PD(t,e){const n=(e.baseMutations||[]).map(e=>CO(t.Ht,e));for(let s=0;s<e.mutations.length-1;++s){const n=e.mutations[s];if(s+1<e.mutations.length&&void 0!==e.mutations[s+1].transform){const r=e.mutations[s+1];n.updateTransforms=r.transform.fieldTransforms,e.mutations.splice(s+1,1),++s}}const r=e.mutations.map(e=>CO(t.Ht,e)),i=HR.fromMillis(e.localWriteTimeMs);return new bD(e.batchId,i,n,r)}function xD(e){var t,n=RD(e.readTime),r=void 0!==e.lastLimboFreeSnapshotVersion?RD(e.lastLimboFreeSnapshotVersion):GR.min();let i;return i=void 0!==e.query.documents?(RR(1===(t=e.query).documents.length),sx(JP(bO(t.documents[0])))):sx(RO(e.query)),new TD(i,e.targetId,0,e.lastListenSequenceNumber,n,r,rP.fromBase64String(e.resumeToken))}function OD(e,t){var n=ND(t.snapshotVersion),r=ND(t.lastLimboFreeSnapshotVersion),i=(LP(t.target)?AO:NO)(e.Ht,t.target),s=t.resumeToken.toBase64();return new YO(t.targetId,OP(t.target),n,s,t.sequenceNumber,r,i)}function DD(e){var t=RO({parent:e.parent,structuredQuery:e.structuredQuery});return"LAST"===e.limitType?ox(t,t.limit,"L"):t}class LD{getBundleMetadata(e,t){return MD(e).get(t).next(e=>{if(e)return{id:(t=e).bundleId,createTime:RD(t.createTime),version:t.version};var t})}saveBundleMetadata(e,t){return MD(e).put({bundleId:(n=t).id,createTime:ND(gO(n.createTime)),version:n.version});var n}getNamedQuery(e,t){return FD(e).get(t).next(e=>{if(e)return{name:(t=e).name,query:DD(t.bundledQuery),readTime:RD(t.readTime)};var t})}saveNamedQuery(e,t){return FD(e).put({name:(t=t).name,readTime:ND(gO(t.readTime)),bundledQuery:t.bundledQuery})}}function MD(e){return wD(e,tD.store)}function FD(e){return wD(e,nD.store)}class UD{constructor(){this.Jt=new jD}addToCollectionParentIndex(e,t){return this.Jt.add(t),lD.resolve()}getCollectionParents(e,t){return lD.resolve(this.Jt.getEntries(t))}}class jD{constructor(){this.index={}}add(e){const t=e.lastSegment(),n=e.popLast(),r=this.index[t]||new Hx(ZR.comparator),i=!r.has(n);return this.index[t]=r.add(n),i}has(e){const t=e.lastSegment(),n=e.popLast(),r=this.index[t];return r&&r.has(n)}getEntries(e){return(this.index[e]||new Hx(ZR.comparator)).toArray()}}class qD{constructor(){this.Yt=new jD}addToCollectionParentIndex(e,t){if(this.Yt.has(t))return lD.resolve();var n=t.lastSegment(),r=t.popLast();e.addOnCommittedListener(()=>{this.Yt.add(t)});r={collectionId:n,parent:UO(r)};return VD(e).put(r)}getCollectionParents(e,n){const r=[],t=IDBKeyRange.bound([n,""],[$R(n),""],!1,!0);return VD(e).qt(t).next(e=>{for(const t of e){if(t.collectionId!==n)break;r.push(qO(t.parent))}return r})}}function VD(e){return wD(e,ZO.store)}const BD={didRun:!1,sequenceNumbersCollected:0,targetsRemoved:0,documentsRemoved:0};class WD{constructor(e,t,n){this.cacheSizeCollectionThreshold=e,this.percentileToCollect=t,this.maximumSequenceNumbersToCollect=n}static withCacheSize(e){return new WD(e,WD.DEFAULT_COLLECTION_PERCENTILE,WD.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT)}}function zD(e,t,n){const r=e.store(zO.store),i=e.store(KO.store),s=[],o=IDBKeyRange.only(n.batchId);let a=0;const c=r.Wt({range:o},(e,t,n)=>(a++,n.delete()));s.push(c.next(()=>{RR(1===a)}));const l=[];for(const e of n.mutations){const r=KO.key(t,e.key.path,n.batchId);s.push(i.delete(r)),l.push(e.key)}return lD.waitFor(s).next(()=>l)}function KD(e){if(!e)return 0;let t;if(e.document)t=e.document;else if(e.unknownDocument)t=e.unknownDocument;else{if(!e.noDocument)throw NR();t=e.noDocument}return JSON.stringify(t).length}WD.DEFAULT_COLLECTION_PERCENTILE=10,WD.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT=1e3,WD.DEFAULT=new WD(41943040,WD.DEFAULT_COLLECTION_PERCENTILE,WD.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT),WD.DISABLED=new WD(-1,0,0);class $D{constructor(e,t,n,r){this.userId=e,this.O=t,this.Xt=n,this.referenceDelegate=r,this.Zt={}}static te(e,t,n,r){RR(""!==e.uid);var i=e.isAuthenticated()?e.uid:"";return new $D(i,t,n,r)}checkEmpty(e){let r=!0;var t=IDBKeyRange.bound([this.userId,Number.NEGATIVE_INFINITY],[this.userId,Number.POSITIVE_INFINITY]);return GD(e).Wt({index:zO.userMutationsIndex,range:t},(e,t,n)=>{r=!1,n.done()}).next(()=>r)}addMutationBatch(u,h,d,p){const f=QD(u),g=GD(u);return g.add({}).next(e=>{RR("number"==typeof e);const t=new bD(e,h,d,p),n=(i=this.O,s=this.userId,o=t,a=o.baseMutations.map(e=>SO(i.Ht,e)),c=o.mutations.map(e=>SO(i.Ht,e)),new zO(s,o.batchId,o.localWriteTime.toMillis(),a,c)),r=[];var i,s,o,a,c;let l=new Hx((e,t)=>zR(e.canonicalString(),t.canonicalString()));for(const u of p){const h=KO.key(this.userId,u.key.path,e);l=l.add(u.key.path.popLast()),r.push(g.put(n)),r.push(f.put(h,KO.PLACEHOLDER))}return l.forEach(e=>{r.push(this.Xt.addToCollectionParentIndex(u,e))}),u.addOnCommittedListener(()=>{this.Zt[e]=t.keys()}),lD.waitFor(r).next(()=>t)})}lookupMutationBatch(e,t){return GD(e).get(t).next(e=>e?(RR(e.userId===this.userId),PD(this.O,e)):null)}ee(e,n){return this.Zt[n]?lD.resolve(this.Zt[n]):this.lookupMutationBatch(e,n).next(e=>{if(e){var t=e.keys();return this.Zt[n]=t}return null})}getNextMutationBatchAfterBatchId(e,t){const r=t+1,n=IDBKeyRange.lowerBound([this.userId,r]);let i=null;return GD(e).Wt({index:zO.userMutationsIndex,range:n},(e,t,n)=>{t.userId===this.userId&&(RR(t.batchId>=r),i=PD(this.O,t)),n.done()}).next(()=>i)}getHighestUnacknowledgedBatchId(e){var t=IDBKeyRange.upperBound([this.userId,Number.POSITIVE_INFINITY]);let r=-1;return GD(e).Wt({index:zO.userMutationsIndex,range:t,reverse:!0},(e,t,n)=>{r=t.batchId,n.done()}).next(()=>r)}getAllMutationBatches(e){var t=IDBKeyRange.bound([this.userId,-1],[this.userId,Number.POSITIVE_INFINITY]);return GD(e).qt(zO.userMutationsIndex,t).next(e=>e.map(e=>PD(this.O,e)))}getAllMutationBatchesAffectingDocumentKey(o,a){const e=KO.prefixForPath(this.userId,a.path),t=IDBKeyRange.lowerBound(e),c=[];return QD(o).Wt({range:t},(e,t,n)=>{var[r,i,s]=e,i=qO(i);if(r===this.userId&&a.path.isEqual(i))return GD(o).get(s).next(e=>{if(!e)throw NR();RR(e.userId===this.userId),c.push(PD(this.O,e))});n.done()}).next(()=>c)}getAllMutationBatchesAffectingDocumentKeys(t,e){let a=new Hx(zR);const n=[];return e.forEach(o=>{var e=KO.prefixForPath(this.userId,o.path),e=IDBKeyRange.lowerBound(e),e=QD(t).Wt({range:e},(e,t,n)=>{var[r,i,s]=e,i=qO(i);r===this.userId&&o.path.isEqual(i)?a=a.add(s):n.done()});n.push(e)}),lD.waitFor(n).next(()=>this.ne(t,a))}getAllMutationBatchesAffectingQuery(e,t){const o=t.path,a=o.length+1,n=KO.prefixForPath(this.userId,o),r=IDBKeyRange.lowerBound(n);let c=new Hx(zR);return QD(e).Wt({range:r},(e,t,n)=>{var[r,i,s]=e,i=qO(i);r===this.userId&&o.isPrefixOf(i)?i.length===a&&(c=c.add(s)):n.done()}).next(()=>this.ne(e,c))}ne(t,e){const n=[],r=[];return e.forEach(e=>{r.push(GD(t).get(e).next(e=>{if(null===e)throw NR();RR(e.userId===this.userId),n.push(PD(this.O,e))}))}),lD.waitFor(r).next(()=>n)}removeMutationBatch(t,n){return zD(t.zt,this.userId,n).next(e=>(t.addOnCommittedListener(()=>{this.se(n.batchId)}),lD.forEach(e,e=>this.referenceDelegate.markPotentiallyOrphaned(t,e))))}se(e){delete this.Zt[e]}performConsistencyCheck(n){return this.checkEmpty(n).next(e=>{if(!e)return lD.resolve();const t=IDBKeyRange.lowerBound(KO.prefixForUser(this.userId)),r=[];return QD(n).Wt({range:t},(e,t,n)=>{if(e[0]===this.userId){const t=qO(e[1]);r.push(t)}else n.done()}).next(()=>{RR(0===r.length)})})}containsKey(e,t){return HD(e,this.userId,t)}ie(e){return YD(e).get(this.userId).next(e=>e||new WO(this.userId,-1,""))}}function HD(e,s,t){const n=KO.prefixForPath(s,t.path),o=n[1],r=IDBKeyRange.lowerBound(n);let a=!1;return QD(e).Wt({range:r,Qt:!0},(e,t,n)=>{var[r,i]=e;r===s&&i===o&&(a=!0),n.done()}).next(()=>a)}function GD(e){return wD(e,zO.store)}function QD(e){return wD(e,KO.store)}function YD(e){return wD(e,WO.store)}class XD{constructor(e){this.re=e}next(){return this.re+=2,this.re}static oe(){return new XD(0)}static ce(){return new XD(-1)}}class JD{constructor(e,t){this.referenceDelegate=e,this.O=t}allocateTargetId(n){return this.ae(n).next(e=>{const t=new XD(e.highestTargetId);return e.highestTargetId=t.next(),this.ue(n,e).next(()=>e.highestTargetId)})}getLastRemoteSnapshotVersion(e){return this.ae(e).next(e=>GR.fromTimestamp(new HR(e.lastRemoteSnapshotVersion.seconds,e.lastRemoteSnapshotVersion.nanoseconds)))}getHighestSequenceNumber(e){return this.ae(e).next(e=>e.highestListenSequenceNumber)}setTargetsMetadata(t,n,r){return this.ae(t).next(e=>(e.highestListenSequenceNumber=n,r&&(e.lastRemoteSnapshotVersion=r.toTimestamp()),n>e.highestListenSequenceNumber&&(e.highestListenSequenceNumber=n),this.ue(t,e)))}addTargetData(t,n){return this.he(t,n).next(()=>this.ae(t).next(e=>(e.targetCount+=1,this.le(n,e),this.ue(t,e))))}updateTargetData(e,t){return this.he(e,t)}removeTargetData(t,e){return this.removeMatchingKeysForTargetId(t,e.targetId).next(()=>ZD(t).delete(e.targetId)).next(()=>this.ae(t)).next(e=>(RR(0<e.targetCount),--e.targetCount,this.ue(t,e)))}removeTargets(r,i,s){let o=0;const a=[];return ZD(r).Wt((e,t)=>{var n=xD(t);n.sequenceNumber<=i&&null===s.get(n.targetId)&&(o++,a.push(this.removeTargetData(r,n)))}).next(()=>lD.waitFor(a)).next(()=>o)}forEachTarget(e,r){return ZD(e).Wt((e,t)=>{var n=xD(t);r(n)})}ae(e){return e1(e).get(JO.key).next(e=>(RR(null!==e),e))}ue(e,t){return e1(e).put(JO.key,t)}he(e,t){return ZD(e).put(OD(this.O,t))}le(e,t){let n=!1;return e.targetId>t.highestTargetId&&(t.highestTargetId=e.targetId,n=!0),e.sequenceNumber>t.highestListenSequenceNumber&&(t.highestListenSequenceNumber=e.sequenceNumber,n=!0),n}getTargetCount(e){return this.ae(e).next(e=>e.targetCount)}getTargetData(e,i){var t=OP(i),t=IDBKeyRange.bound([t,Number.NEGATIVE_INFINITY],[t,Number.POSITIVE_INFINITY]);let s=null;return ZD(e).Wt({range:t,index:YO.queryTargetsIndexName},(e,t,n)=>{var r=xD(t);DP(i,r.target)&&(s=r,n.done())}).next(()=>s)}addMatchingKeys(n,e,r){const i=[],s=t1(n);return e.forEach(e=>{var t=UO(e.path);i.push(s.put(new XO(r,t))),i.push(this.referenceDelegate.addReference(n,r,e))}),lD.waitFor(i)}removeMatchingKeys(n,e,r){const i=t1(n);return lD.forEach(e,e=>{var t=UO(e.path);return lD.waitFor([i.delete([r,t]),this.referenceDelegate.removeReference(n,r,e)])})}removeMatchingKeysForTargetId(e,t){const n=t1(e),r=IDBKeyRange.bound([t],[t+1],!1,!0);return n.delete(r)}getMatchingKeysForTargetId(e,t){const n=IDBKeyRange.bound([t],[t+1],!1,!0),r=t1(e);let i=Zx();return r.Wt({range:n,Qt:!0},(e,t,n)=>{var r=qO(e[1]),r=new gP(r);i=i.add(r)}).next(()=>i)}containsKey(e,t){var n=UO(t.path),n=IDBKeyRange.bound([n],[$R(n)],!1,!0);let r=0;return t1(e).Wt({index:XO.documentTargetsIndex,Qt:!0,range:n},([e],t,n)=>{0!==e&&(r++,n.done())}).next(()=>0<r)}At(e,t){return ZD(e).get(t).next(e=>e?xD(e):null)}}function ZD(e){return wD(e,YO.store)}function e1(e){return wD(e,JO.store)}function t1(e){return wD(e,XO.store)}async function n1(e){if(e.code!==PR.FAILED_PRECONDITION||e.message!==aD)throw e;kR("LocalStore","Unexpectedly lost primary lease")}function r1([e,t],[n,r]){var i=zR(e,n);return 0===i?zR(t,r):i}class i1{constructor(e){this.fe=e,this.buffer=new Hx(r1),this.de=0}we(){return++this.de}_e(e){var t=[e,this.we()];if(this.buffer.size<this.fe)this.buffer=this.buffer.add(t);else{const e=this.buffer.last();r1(t,e)<0&&(this.buffer=this.buffer.delete(e).add(t))}}get maxValue(){return this.buffer.last()[0]}}class s1{constructor(e,t){this.garbageCollector=e,this.asyncQueue=t,this.me=!1,this.ge=null}start(e){-1!==this.garbageCollector.params.cacheSizeCollectionThreshold&&this.ye(e)}stop(){this.ge&&(this.ge.cancel(),this.ge=null)}get started(){return null!==this.ge}ye(e){var t=this.me?3e5:6e4;kR("LruGarbageCollector",`Garbage collection scheduled in ${t}ms`),this.ge=this.asyncQueue.enqueueAfterDelay("lru_garbage_collection",t,async()=>{this.ge=null,this.me=!0;try{await e.collectGarbage(this.garbageCollector)}catch(e){fD(e)?kR("LruGarbageCollector","Ignoring IndexedDB error during garbage collection: ",e):await n1(e)}await this.ye(e)})}}class o1{constructor(e,t){this.pe=e,this.params=t}calculateTargetCount(e,t){return this.pe.Te(e).next(e=>Math.floor(t/100*e))}nthSequenceNumber(e,t){if(0===t)return lD.resolve(BR.I);const n=new i1(t);return this.pe.forEachTarget(e,e=>n._e(e.sequenceNumber)).next(()=>this.pe.Ee(e,e=>n._e(e))).next(()=>n.maxValue)}removeTargets(e,t,n){return this.pe.removeTargets(e,t,n)}removeOrphanedDocuments(e,t){return this.pe.removeOrphanedDocuments(e,t)}collect(t,n){return-1===this.params.cacheSizeCollectionThreshold?(kR("LruGarbageCollector","Garbage collection skipped; disabled"),lD.resolve(BD)):this.getCacheSize(t).next(e=>e<this.params.cacheSizeCollectionThreshold?(kR("LruGarbageCollector",`Garbage collection skipped; Cache size ${e} is lower than threshold ${this.params.cacheSizeCollectionThreshold}`),BD):this.Ie(t,n))}getCacheSize(e){return this.pe.getCacheSize(e)}Ie(t,n){let r,i,s,o,a,c,l;const u=Date.now();return this.calculateTargetCount(t,this.params.percentileToCollect).next(e=>(i=e>this.params.maximumSequenceNumbersToCollect?(kR("LruGarbageCollector",`Capping sequence numbers to collect down to the maximum of ${this.params.maximumSequenceNumbersToCollect} from ${e}`),this.params.maximumSequenceNumbersToCollect):e,o=Date.now(),this.nthSequenceNumber(t,i))).next(e=>(r=e,a=Date.now(),this.removeTargets(t,r,n))).next(e=>(s=e,c=Date.now(),this.removeOrphanedDocuments(t,r))).next(e=>(l=Date.now(),ER()<=zh.DEBUG&&kR("LruGarbageCollector",`LRU Garbage Collection\n\tCounted targets in ${o-u}ms\n\tDetermined least recently used ${i} in `+(a-o)+"ms\n"+`\tRemoved ${s} targets in `+(c-a)+"ms\n"+`\tRemoved ${e} documents in `+(l-c)+"ms\n"+`Total Duration: ${l-u}ms`),lD.resolve({didRun:!0,sequenceNumbersCollected:i,targetsRemoved:s,documentsRemoved:e})))}}class a1{constructor(e,t){this.db=e,this.garbageCollector=(e=this,t=t,new o1(e,t))}Te(e){const n=this.Ae(e);return this.db.getTargetCache().getTargetCount(e).next(t=>n.next(e=>t+e))}Ae(e){let t=0;return this.Ee(e,e=>{t++}).next(()=>t)}forEachTarget(e,t){return this.db.getTargetCache().forEachTarget(e,t)}Ee(e,n){return this.Re(e,(e,t)=>n(t))}addReference(e,t,n){return c1(e,n)}removeReference(e,t,n){return c1(e,n)}removeTargets(e,t,n){return this.db.getTargetCache().removeTargets(e,t,n)}markPotentiallyOrphaned(e,t){return c1(e,t)}be(t,n){let r=!1;return YD(t).Gt(e=>HD(t,e,n).next(e=>(e&&(r=!0),lD.resolve(!e)))).next(()=>r)}removeOrphanedDocuments(n,r){const i=this.db.getRemoteDocumentCache().newChangeBuffer(),s=[];let o=0;return this.Re(n,(t,e)=>{if(e<=r){const r=this.be(n,t).next(e=>{if(!e)return o++,i.getEntry(n,t).next(()=>(i.removeEntry(t,GR.min()),t1(n).delete([0,UO(t.path)])))});s.push(r)}}).next(()=>lD.waitFor(s)).next(()=>i.apply(n)).next(()=>o)}removeTarget(e,t){var n=t.withSequenceNumber(e.currentSequenceNumber);return this.db.getTargetCache().updateTargetData(e,n)}updateLimboDocument(e,t){return c1(e,t)}Re(e,r){const t=t1(e);let i,s=BR.I;return t.Wt({index:XO.documentTargetsIndex},([e],{path:t,sequenceNumber:n})=>{0===e?(s!==BR.I&&r(new gP(qO(i)),s),s=n,i=t):s=BR.I}).next(()=>{s!==BR.I&&r(new gP(qO(i)),s)})}getCacheSize(e){return this.db.getRemoteDocumentCache().getSize(e)}}function c1(e,t){return t1(e).put((t=t,e=e.currentSequenceNumber,new XO(0,UO(t.path),e)))}class l1{constructor(e,t){this.mapKeyFn=e,this.equalsFn=t,this.inner={}}get(e){const t=this.mapKeyFn(e),n=this.inner[t];if(void 0!==n)for(const[t,r]of n)if(this.equalsFn(t,e))return r}has(e){return void 0!==this.get(e)}set(t,n){const e=this.mapKeyFn(t),r=this.inner[e];if(void 0!==r){for(let e=0;e<r.length;e++)if(this.equalsFn(r[e][0],t))return void(r[e]=[t,n]);r.push([t,n])}else this.inner[e]=[[t,n]]}delete(e){const t=this.mapKeyFn(e),n=this.inner[t];if(void 0===n)return!1;for(let r=0;r<n.length;r++)if(this.equalsFn(n[r][0],e))return 1===n.length?delete this.inner[t]:n.splice(r,1),!0;return!1}forEach(r){YR(this.inner,(e,t)=>{for(const[e,n]of t)r(e,n)})}isEmpty(){return XR(this.inner)}}class u1{constructor(){this.changes=new l1(e=>e.toString(),(e,t)=>e.isEqual(t)),this.changesApplied=!1}addEntry(e){this.assertNotApplied(),this.changes.set(e.key,e)}removeEntry(e,t){this.assertNotApplied(),this.changes.set(e,RP.newInvalidDocument(e).setReadTime(t))}getEntry(e,t){this.assertNotApplied();var n=this.changes.get(t);return void 0!==n?lD.resolve(n):this.getFromCache(e,t)}getEntries(e,t){return this.getAllFromCache(e,t)}apply(e){return this.assertNotApplied(),this.changesApplied=!0,this.applyChanges(e)}assertNotApplied(){}}class h1{constructor(e,t){this.O=e,this.Xt=t}addEntry(e,t,n){return f1(e).put(g1(t),n)}removeEntry(e,t){const n=f1(e),r=g1(t);return n.delete(r)}updateMetadata(t,n){return this.getMetadata(t).next(e=>(e.byteSize+=n,this.Pe(t,e)))}getEntry(e,t){return f1(e).get(g1(t)).next(e=>this.ve(t,e))}Ve(e,t){return f1(e).get(g1(t)).next(e=>({document:this.ve(t,e),size:KD(e)}))}getEntries(e,t){let r=Qx;return this.Se(e,t,(e,t)=>{var n=this.ve(e,t);r=r.insert(e,n)}).next(()=>r)}De(e,t){let r=Qx,i=new zx(gP.comparator);return this.Se(e,t,(e,t)=>{var n=this.ve(e,t);r=r.insert(e,n),i=i.insert(e,KD(t))}).next(()=>({documents:r,Ce:i}))}Se(e,t,i){if(t.isEmpty())return lD.resolve();const n=IDBKeyRange.bound(t.first().path.toArray(),t.last().path.toArray()),s=t.getIterator();let o=s.getNext();return f1(e).Wt({range:n},(e,t,n)=>{for(var r=gP.fromSegments(e);o&&gP.comparator(o,r)<0;)i(o,null),o=s.getNext();o&&o.isEqual(r)&&(i(o,t),o=s.hasNext()?s.getNext():null),o?n.Ut(o.path.toArray()):n.done()}).next(()=>{for(;o;)i(o,null),o=s.hasNext()?s.getNext():null})}getDocumentsMatchingQuery(e,i,t){let s=Qx;const o=i.path.length+1,n={};if(t.isEqual(GR.min())){const e=i.path.toArray();n.range=IDBKeyRange.lowerBound(e)}else{const e=i.path.toArray(),s=CD(t);n.range=IDBKeyRange.lowerBound([e,s],!0),n.index=GO.collectionReadTimeIndex}return f1(e).Wt(n,(e,t,n)=>{var r;e.length===o&&(r=this.ve(gP.fromSegments(e),t),i.path.isPrefixOf(r.key.path)?ux(i,r)&&(s=s.insert(r.key,r)):n.done())}).next(()=>s)}newChangeBuffer(e){return new d1(this,!!e&&e.trackRemovals)}getSize(e){return this.getMetadata(e).next(e=>e.byteSize)}getMetadata(e){return p1(e).get(QO.key).next(e=>(RR(!!e),e))}Pe(e,t){return p1(e).put(QO.key,t)}ve(e,t){if(t){const e=kD(this.O,t);if(!e.isNoDocument()||!e.version.isEqual(GR.min()))return e}return RP.newInvalidDocument(e)}}class d1 extends u1{constructor(e,t){super(),this.Ne=e,this.trackRemovals=t,this.ke=new l1(e=>e.toString(),(e,t)=>e.isEqual(t))}applyChanges(s){const o=[];let a=0,c=new Hx((e,t)=>zR(e.canonicalString(),t.canonicalString()));return this.changes.forEach((e,t)=>{var n=this.ke.get(e);if(t.isValidDocument()){var r=SD(this.Ne.O,t);c=c.add(e.path.popLast());var i=KD(r);a+=i-n,o.push(this.Ne.addEntry(s,e,r))}else if(a-=n,this.trackRemovals){const a=SD(this.Ne.O,t.convertToNoDocument(GR.min()));o.push(this.Ne.addEntry(s,e,a))}else o.push(this.Ne.removeEntry(s,e))}),c.forEach(e=>{o.push(this.Ne.Xt.addToCollectionParentIndex(s,e))}),o.push(this.Ne.updateMetadata(s,a)),lD.waitFor(o)}getFromCache(e,t){return this.Ne.Ve(e,t).next(e=>(this.ke.set(t,e.size),e.document))}getAllFromCache(e,t){return this.Ne.De(e,t).next(({documents:e,Ce:t})=>(t.forEach((e,t)=>{this.ke.set(e,t)}),e))}}function p1(e){return wD(e,QO.store)}function f1(e){return wD(e,GO.store)}function g1(e){return e.path.toArray()}class m1{constructor(e){this.O=e}xt(t,n,e,r){const i=new uD("createOrUpgrade",n);var s;e<1&&1<=r&&(t.createObjectStore(BO.store),(s=t).createObjectStore(WO.store,{keyPath:WO.keyPath}),s.createObjectStore(zO.store,{keyPath:zO.keyPath,autoIncrement:!0}).createIndex(zO.userMutationsIndex,zO.userMutationsKeyPath,{unique:!0}),s.createObjectStore(KO.store),v1(t),t.createObjectStore(GO.store));let o=lD.resolve();return e<3&&3<=r&&(0!==e&&((s=t).deleteObjectStore(XO.store),s.deleteObjectStore(YO.store),s.deleteObjectStore(JO.store),v1(t)),o=o.next(()=>function(){const e=i.store(JO.store),t=new JO(0,0,GR.min().toTimestamp(),0);return e.put(JO.key,t)}())),e<4&&4<=r&&(0!==e&&(o=o.next(()=>function(r,i){return i.store(zO.store).qt().next(e=>{r.deleteObjectStore(zO.store),r.createObjectStore(zO.store,{keyPath:zO.keyPath,autoIncrement:!0}).createIndex(zO.userMutationsIndex,zO.userMutationsKeyPath,{unique:!0});const t=i.store(zO.store),n=e.map(e=>t.put(e));return lD.waitFor(n)})}(t,i))),o=o.next(()=>{t.createObjectStore(eD.store,{keyPath:eD.keyPath})})),e<5&&5<=r&&(o=o.next(()=>this.xe(i))),e<6&&6<=r&&(o=o.next(()=>(t.createObjectStore(QO.store),this.$e(i)))),e<7&&7<=r&&(o=o.next(()=>this.Oe(i))),e<8&&8<=r&&(o=o.next(()=>this.Me(t,i))),e<9&&9<=r&&(o=o.next(()=>{var e;(e=t).objectStoreNames.contains("remoteDocumentChanges")&&e.deleteObjectStore("remoteDocumentChanges"),function(){const e=n.objectStore(GO.store);e.createIndex(GO.readTimeIndex,GO.readTimeIndexPath,{unique:!1}),e.createIndex(GO.collectionReadTimeIndex,GO.collectionReadTimeIndexPath,{unique:!1})}()})),e<10&&10<=r&&(o=o.next(()=>this.Fe(i))),e<11&&11<=r&&(o=o.next(()=>{t.createObjectStore(tD.store,{keyPath:tD.keyPath}),t.createObjectStore(nD.store,{keyPath:nD.keyPath})})),e<12&&12<=r&&(o=o.next(()=>{var e;(e=t).createObjectStore(rD.store,{keyPath:rD.keyPath}),e.createObjectStore(iD.store,{keyPath:iD.keyPath}),e.createObjectStore(sD.store,{keyPath:sD.keyPath})})),o}$e(t){let n=0;return t.store(GO.store).Wt((e,t)=>{n+=KD(t)}).next(()=>{var e=new QO(n);return t.store(QO.store).put(QO.key,e)})}xe(r){const e=r.store(WO.store),t=r.store(zO.store);return e.qt().next(e=>lD.forEach(e,n=>{var e=IDBKeyRange.bound([n.userId,-1],[n.userId,n.lastAcknowledgedBatchId]);return t.qt(zO.userMutationsIndex,e).next(e=>lD.forEach(e,e=>{RR(e.userId===n.userId);var t=PD(this.O,e);return zD(r,n.userId,t).next(()=>{})}))}))}Oe(e){const o=e.store(XO.store),t=e.store(GO.store);return e.store(JO.store).get(JO.key).next(i=>{const s=[];return t.Wt((e,t)=>{const n=new ZR(e),r=[0,UO(n)];s.push(o.get(r).next(e=>e?lD.resolve():(e=>o.put(new XO(0,UO(e),i.highestListenSequenceNumber)))(n)))}).next(()=>lD.waitFor(s))})}Me(e,t){e.createObjectStore(ZO.store,{keyPath:ZO.keyPath});const n=t.store(ZO.store),r=new jD,i=e=>{if(r.add(e)){const t=e.lastSegment(),r=e.popLast();return n.put({collectionId:t,parent:UO(r)})}};return t.store(GO.store).Wt({Qt:!0},(e,t)=>{const n=new ZR(e);return i(n.popLast())}).next(()=>t.store(KO.store).Wt({Qt:!0},([,e],t)=>{const n=qO(e);return i(n.popLast())}))}Fe(e){const r=e.store(YO.store);return r.Wt((e,t)=>{var n=xD(t),n=OD(this.O,n);return r.put(n)})}}function v1(e){e.createObjectStore(XO.store,{keyPath:XO.keyPath}).createIndex(XO.documentTargetsIndex,XO.documentTargetsKeyPath,{unique:!0}),e.createObjectStore(YO.store,{keyPath:YO.keyPath}).createIndex(YO.queryTargetsIndexName,YO.queryTargetsKeyPath,{unique:!0}),e.createObjectStore(JO.store)}const y1="Failed to obtain exclusive access to the persistence layer. To allow shared access, multi-tab synchronization has to be enabled in all tabs. If you are using `experimentalForceOwningTab:true`, make sure that only one tab has persistence enabled at any given time.";class _1{constructor(e,t,n,r,i,s,o,a,c,l){if(this.allowTabSynchronization=e,this.persistenceKey=t,this.clientId=n,this.Le=i,this.window=s,this.document=o,this.Be=c,this.Ue=l,this.qe=null,this.Ke=!1,this.isPrimary=!1,this.networkEnabled=!0,this.je=null,this.inForeground=!1,this.Qe=null,this.We=null,this.Ge=Number.NEGATIVE_INFINITY,this.ze=e=>Promise.resolve(),!_1.Vt())throw new xR(PR.UNIMPLEMENTED,"This platform is either missing IndexedDB or is known to have an incomplete implementation. Offline persistence has been disabled.");this.referenceDelegate=new a1(this,r),this.He=t+"main",this.O=new ED(a),this.Je=new hD(this.He,11,new m1(this.O)),this.Ye=new JD(this.referenceDelegate,this.O),this.Xt=new qD,this.Xe=(t=this.O,a=this.Xt,new h1(t,a)),this.Ze=new LD,this.window&&this.window.localStorage?this.tn=this.window.localStorage:(this.tn=null,!1===l&&SR("IndexedDbPersistence","LocalStorage is unavailable. As a result, persistence may not work reliably. In particular enablePersistence() could fail immediately after refreshing the page."))}start(){return this.en().then(()=>{if(!this.isPrimary&&!this.allowTabSynchronization)throw new xR(PR.FAILED_PRECONDITION,y1);return this.nn(),this.sn(),this.rn(),this.runTransaction("getHighestListenSequenceNumber","readonly",e=>this.Ye.getHighestSequenceNumber(e))}).then(e=>{this.qe=new BR(e,this.Be)}).then(()=>{this.Ke=!0}).catch(e=>(this.Je&&this.Je.close(),Promise.reject(e)))}on(t){return this.ze=async e=>{if(this.started)return t(e)},t(this.isPrimary)}setDatabaseDeletedListener(t){this.Je.Ot(async e=>{null===e.newVersion&&await t()})}setNetworkEnabled(e){this.networkEnabled!==e&&(this.networkEnabled=e,this.Le.enqueueAndForget(async()=>{this.started&&await this.en()}))}en(){return this.runTransaction("updateClientMetadataAndTryBecomePrimary","readwrite",t=>b1(t).put(new eD(this.clientId,Date.now(),this.networkEnabled,this.inForeground)).next(()=>{if(this.isPrimary)return this.cn(t).next(e=>{e||(this.isPrimary=!1,this.Le.enqueueRetryable(()=>this.ze(!1)))})}).next(()=>this.an(t)).next(e=>this.isPrimary&&!e?this.un(t).next(()=>!1):!!e&&this.hn(t).next(()=>!0))).catch(e=>{if(fD(e))return kR("IndexedDbPersistence","Failed to extend owner lease: ",e),this.isPrimary;if(!this.allowTabSynchronization)throw e;return kR("IndexedDbPersistence","Releasing owner lease after error during lease refresh",e),!1}).then(e=>{this.isPrimary!==e&&this.Le.enqueueRetryable(()=>this.ze(e)),this.isPrimary=e})}cn(e){return w1(e).get(BO.key).next(e=>lD.resolve(this.ln(e)))}fn(e){return b1(e).delete(this.clientId)}async dn(){if(this.isPrimary&&!this.wn(this.Ge,18e5)){this.Ge=Date.now();var e=await this.runTransaction("maybeGarbageCollectMultiClientState","readwrite-primary",e=>{const r=wD(e,eD.store);return r.qt().next(e=>{const t=this._n(e,18e5),n=e.filter(e=>-1===t.indexOf(e));return lD.forEach(n,e=>r.delete(e.clientId)).next(()=>n)})}).catch(()=>[]);if(this.tn)for(const t of e)this.tn.removeItem(this.mn(t.clientId))}}rn(){this.We=this.Le.enqueueAfterDelay("client_metadata_refresh",4e3,()=>this.en().then(()=>this.dn()).then(()=>this.rn()))}ln(e){return!!e&&e.ownerId===this.clientId}an(t){return this.Ue?lD.resolve(!0):w1(t).get(BO.key).next(e=>{if(null!==e&&this.wn(e.leaseTimestampMs,5e3)&&!this.gn(e.ownerId)){if(this.ln(e)&&this.networkEnabled)return!0;if(!this.ln(e)){if(!e.allowTabSynchronization)throw new xR(PR.FAILED_PRECONDITION,y1);return!1}}return!(!this.networkEnabled||!this.inForeground)||b1(t).qt().next(e=>void 0===this._n(e,5e3).find(e=>{if(this.clientId!==e.clientId){var t=!this.networkEnabled&&e.networkEnabled,n=!this.inForeground&&e.inForeground,r=this.networkEnabled===e.networkEnabled;if(t||n&&r)return!0}return!1}))}).next(e=>(this.isPrimary!==e&&kR("IndexedDbPersistence",`Client ${e?"is":"is not"} eligible for a primary lease.`),e))}async shutdown(){this.Ke=!1,this.yn(),this.We&&(this.We.cancel(),this.We=null),this.pn(),this.Tn(),await this.Je.runTransaction("shutdown","readwrite",[BO.store,eD.store],e=>{const t=new _D(e,BR.I);return this.un(t).next(()=>this.fn(t))}),this.Je.close(),this.En()}_n(e,t){return e.filter(e=>this.wn(e.updateTimeMs,t)&&!this.gn(e.clientId))}In(){return this.runTransaction("getActiveClients","readonly",e=>b1(e).qt().next(e=>this._n(e,18e5).map(e=>e.clientId)))}get started(){return this.Ke}getMutationQueue(e){return $D.te(e,this.O,this.Xt,this.referenceDelegate)}getTargetCache(){return this.Ye}getRemoteDocumentCache(){return this.Xe}getIndexManager(){return this.Xt}getBundleCache(){return this.Ze}runTransaction(t,n,r){kR("IndexedDbPersistence","Starting transaction:",t);let i;return this.Je.runTransaction(t,"readonly"===n?"readonly":"readwrite",oD,e=>(i=new _D(e,this.qe?this.qe.next():BR.I),"readwrite-primary"===n?this.cn(i).next(e=>!!e||this.an(i)).next(e=>{if(!e)throw SR(`Failed to obtain primary lease for action '${t}'.`),this.isPrimary=!1,this.Le.enqueueRetryable(()=>this.ze(!1)),new xR(PR.FAILED_PRECONDITION,aD);return r(i)}).next(e=>this.hn(i).next(()=>e)):this.An(i).next(()=>r(i)))).then(e=>(i.raiseOnCommittedEvent(),e))}An(e){return w1(e).get(BO.key).next(e=>{if(null!==e&&this.wn(e.leaseTimestampMs,5e3)&&!this.gn(e.ownerId)&&!this.ln(e)&&!(this.Ue||this.allowTabSynchronization&&e.allowTabSynchronization))throw new xR(PR.FAILED_PRECONDITION,y1)})}hn(e){var t=new BO(this.clientId,this.allowTabSynchronization,Date.now());return w1(e).put(BO.key,t)}static Vt(){return hD.Vt()}un(e){const t=w1(e);return t.get(BO.key).next(e=>this.ln(e)?(kR("IndexedDbPersistence","Releasing primary lease."),t.delete(BO.key)):lD.resolve())}wn(e,t){var n=Date.now();return!(e<n-t||n<e&&(SR(`Detected an update time that is in the future: ${e} > ${n}`),1))}nn(){null!==this.document&&"function"==typeof this.document.addEventListener&&(this.Qe=()=>{this.Le.enqueueAndForget(()=>(this.inForeground="visible"===this.document.visibilityState,this.en()))},this.document.addEventListener("visibilitychange",this.Qe),this.inForeground="visible"===this.document.visibilityState)}pn(){this.Qe&&(this.document.removeEventListener("visibilitychange",this.Qe),this.Qe=null)}sn(){var e;"function"==typeof(null===(e=this.window)||void 0===e?void 0:e.addEventListener)&&(this.je=()=>{this.yn(),!ad()&&navigator.userAgent.includes("Safari")&&!navigator.userAgent.includes("Chrome")&&navigator.appVersion.match(/Version\/1[45]/)&&this.Le.enterRestrictedMode(!0),this.Le.enqueueAndForget(()=>this.shutdown())},this.window.addEventListener("pagehide",this.je))}Tn(){this.je&&(this.window.removeEventListener("pagehide",this.je),this.je=null)}gn(e){var t;try{var n=null!==(null===(t=this.tn)||void 0===t?void 0:t.getItem(this.mn(e)));return kR("IndexedDbPersistence",`Client '${e}' ${n?"is":"is not"} zombied in LocalStorage`),n}catch(e){return SR("IndexedDbPersistence","Failed to get zombied client id.",e),!1}}yn(){if(this.tn)try{this.tn.setItem(this.mn(this.clientId),String(Date.now()))}catch(e){SR("Failed to set zombie client id.",e)}}En(){if(this.tn)try{this.tn.removeItem(this.mn(this.clientId))}catch(e){}}mn(e){return`firestore_zombie_${this.persistenceKey}_${e}`}}function w1(e){return wD(e,BO.store)}function b1(e){return wD(e,eD.store)}function I1(e,t){let n=e.projectId;return e.isDefaultDatabase||(n+="."+e.database),"firestore/"+t+"/"+n+"/"}class T1{constructor(e,t){this.progress=e,this.Rn=t}}class E1{constructor(e,t,n){this.Xe=e,this.bn=t,this.Xt=n}Pn(t,n){return this.bn.getAllMutationBatchesAffectingDocumentKey(t,n).next(e=>this.vn(t,n,e))}vn(e,t,n){return this.Xe.getEntry(e,t).next(e=>{for(const t of n)t.applyToLocalView(e);return e})}Vn(e,n){e.forEach((e,t)=>{for(const e of n)e.applyToLocalView(t)})}Sn(t,e){return this.Xe.getEntries(t,e).next(e=>this.Dn(t,e).next(()=>e))}Dn(e,t){return this.bn.getAllMutationBatchesAffectingDocumentKeys(e,t).next(e=>this.Vn(t,e))}getDocumentsMatchingQuery(e,t,n){return r=t,gP.isDocumentKey(r.path)&&null===r.collectionGroup&&0===r.filters.length?this.Cn(e,t.path):rx(t)?this.Nn(e,t,n):this.kn(e,t,n);var r}Cn(e,t){return this.Pn(e,new gP(t)).next(e=>{let t=Yx;return e.isFoundDocument()&&(t=t.insert(e.key,e)),t})}Nn(r,i,s){const o=i.collectionGroup;let a=Yx;return this.Xt.getCollectionParents(r,o).next(e=>lD.forEach(e,e=>{var t,n=(t=i,e=e.child(o),new YP(e,null,t.explicitOrderBy.slice(),t.filters.slice(),t.limit,t.limitType,t.startAt,t.endAt));return this.kn(r,n,s).next(e=>{e.forEach((e,t)=>{a=a.insert(e,t)})})}).next(()=>a))}kn(t,n,e){let i,s;return this.Xe.getDocumentsMatchingQuery(t,n,e).next(e=>(i=e,this.bn.getAllMutationBatchesAffectingQuery(t,n))).next(e=>(s=e,this.xn(t,s,i).next(t=>{i=t;for(const t of s)for(const r of t.mutations){var n=r.key;let e=i.get(n);null==e&&(e=RP.newInvalidDocument(n),i=i.insert(n,e)),Px(r,e,t.localWriteTime),e.isFoundDocument()||(i=i.remove(n))}}))).next(()=>(i.forEach((e,t)=>{ux(n,t)||(i=i.remove(e))}),i))}xn(e,t,n){let r=Zx();for(const e of t)for(const t of e.mutations)t instanceof Lx&&null===n.get(t.key)&&(r=r.add(t.key));let i=n;return this.Xe.getEntries(e,r).next(e=>(e.forEach((e,t)=>{t.isFoundDocument()&&(i=i.insert(e,t))}),i))}}class k1{constructor(e,t,n,r){this.targetId=e,this.fromCache=t,this.$n=n,this.On=r}static Mn(e,t){let n=Zx(),r=Zx();for(const e of t.docChanges)switch(e.type){case 0:n=n.add(e.doc.key);break;case 1:r=r.add(e.doc.key)}return new k1(e,t.fromCache,n,r)}}class S1{Fn(e){this.Ln=e}getDocumentsMatchingQuery(t,r,i,s){return 0===(e=r).filters.length&&null===e.limit&&null==e.startAt&&null==e.endAt&&(0===e.explicitOrderBy.length||1===e.explicitOrderBy.length&&e.explicitOrderBy[0].field.isKeyField())||i.isEqual(GR.min())?this.Bn(t,r):this.Ln.Sn(t,s).next(e=>{const n=this.Un(r,e);return(ZP(r)||ex(r))&&this.qn(r.limitType,n,s,i)?this.Bn(t,r):(ER()<=zh.DEBUG&&kR("QueryEngine","Re-using previous result from %s to execute query: %s",i.toString(),lx(r)),this.Ln.getDocumentsMatchingQuery(t,r,i).next(t=>(n.forEach(e=>{t=t.insert(e.key,e)}),t)))});var e}Un(n,e){let r=new Hx(hx(n));return e.forEach((e,t)=>{ux(n,t)&&(r=r.add(t))}),r}qn(e,t,n,r){if(n.size!==t.size)return!0;const i="F"===e?t.last():t.first();return!!i&&(i.hasPendingWrites||0<i.version.compareTo(r))}Bn(e,t){return ER()<=zh.DEBUG&&kR("QueryEngine","Using full collection scan to execute query:",lx(t)),this.Ln.getDocumentsMatchingQuery(e,t,GR.min())}}class C1{constructor(e,t,n,r){this.persistence=e,this.Kn=t,this.O=r,this.jn=new zx(zR),this.Qn=new l1(e=>OP(e),DP),this.Wn=GR.min(),this.bn=e.getMutationQueue(n),this.Gn=e.getRemoteDocumentCache(),this.Ye=e.getTargetCache(),this.zn=new E1(this.Gn,this.bn,this.persistence.getIndexManager()),this.Ze=e.getBundleCache(),this.Kn.Fn(this.zn)}collectGarbage(t){return this.persistence.runTransaction("Collect garbage","readwrite-primary",e=>t.collect(e,this.jn))}}function A1(e,t,n,r){return new C1(e,t,n,r)}async function N1(e,t){const n=e;let r=n.bn,o=n.zn;var i=await n.persistence.runTransaction("Handle user change","readonly",i=>{let s;return n.bn.getAllMutationBatches(i).next(e=>(s=e,r=n.persistence.getMutationQueue(t),o=new E1(n.Gn,r,n.persistence.getIndexManager()),r.getAllMutationBatches(i))).next(e=>{const t=[],n=[];let r=Zx();for(const i of s){t.push(i.batchId);for(const e of i.mutations)r=r.add(e.key)}for(const i of e){n.push(i.batchId);for(const e of i.mutations)r=r.add(e.key)}return o.Sn(i,r).next(e=>({Hn:e,removedBatchIds:t,addedBatchIds:n}))})});return n.bn=r,n.zn=o,n.Kn.Fn(n.zn),i}function R1(e){const t=e;return t.persistence.runTransaction("Get last remote snapshot version","readonly",e=>t.Ye.getLastRemoteSnapshotVersion(e))}function P1(e,l){const u=e,h=l.snapshotVersion;let d=u.jn;return u.persistence.runTransaction("Apply remote event","readwrite-primary",a=>{const e=u.Gn.newChangeBuffer({trackRemovals:!0});d=u.jn;const c=[];l.targetChanges.forEach((t,n)=>{const r=d.get(n);if(r){c.push(u.Ye.removeMatchingKeys(a,t.removedDocuments,n).next(()=>u.Ye.addMatchingKeys(a,t.addedDocuments,n)));let e=r.withSequenceNumber(a.currentSequenceNumber);var i,s,o;l.targetMismatches.has(n)?e=e.withResumeToken(rP.EMPTY_BYTE_STRING,GR.min()).withLastLimboFreeSnapshotVersion(GR.min()):0<t.resumeToken.approximateByteSize()&&(e=e.withResumeToken(t.resumeToken,h)),d=d.insert(n,e),i=r,s=e,o=t,0!==i.resumeToken.approximateByteSize()&&!(3e8<=s.snapshotVersion.toMicroseconds()-i.snapshotVersion.toMicroseconds()||0<o.addedDocuments.size+o.modifiedDocuments.size+o.removedDocuments.size)||c.push(u.Ye.updateTargetData(a,e))}});let t=Qx;if(l.documentUpdates.forEach(e=>{l.resolvedLimboDocuments.has(e)&&c.push(u.persistence.referenceDelegate.updateLimboDocument(a,e))}),c.push(x1(a,e,l.documentUpdates).next(e=>{t=e})),!h.isEqual(GR.min())){const l=u.Ye.getLastRemoteSnapshotVersion(a).next(e=>u.Ye.setTargetsMetadata(a,a.currentSequenceNumber,h));c.push(l)}return lD.waitFor(c).next(()=>e.apply(a)).next(()=>u.zn.Dn(a,t)).next(()=>t)}).then(e=>(u.jn=d,e))}function x1(e,s,t){let n=Zx();return t.forEach(e=>n=n.add(e)),s.getEntries(e,n).next(r=>{let i=Qx;return t.forEach((e,t)=>{const n=r.get(e);t.isNoDocument()&&t.version.isEqual(GR.min())?(s.removeEntry(e,t.readTime),i=i.insert(e,t)):!n.isValidDocument()||0<t.version.compareTo(n.version)||0===t.version.compareTo(n.version)&&n.hasPendingWrites?(s.addEntry(t),i=i.insert(e,t)):kR("LocalStore","Ignoring outdated watch update for ",e,". Current version:",n.version," Watch version:",t.version)}),i})}function O1(e,r){const i=e;return i.persistence.runTransaction("Allocate target","readwrite",t=>{let n;return i.Ye.getTargetData(t,r).next(e=>e?(n=e,lD.resolve(n)):i.Ye.allocateTargetId(t).next(e=>(n=new TD(r,e,0,t.currentSequenceNumber),i.Ye.addTargetData(t,n).next(()=>n))))}).then(e=>{var t=i.jn.get(e.targetId);return(null===t||0<e.snapshotVersion.compareTo(t.snapshotVersion))&&(i.jn=i.jn.insert(e.targetId,e),i.Qn.set(r,e.targetId)),e})}async function D1(e,t,n){const r=e,i=r.jn.get(t),s=n?"readwrite":"readwrite-primary";try{n||await r.persistence.runTransaction("Release target",s,e=>r.persistence.referenceDelegate.removeTarget(e,i))}catch(e){if(!fD(e))throw e;kR("LocalStore",`Failed to update sequence numbers for target ${t}: ${e}`)}r.jn=r.jn.remove(t),r.Qn.delete(i.target)}function L1(e,n,r){const i=e;let s=GR.min(),o=Zx();return i.persistence.runTransaction("Execute query","readonly",t=>function(e,t,n){const r=e,i=r.Qn.get(n);return void 0!==i?lD.resolve(r.jn.get(i)):r.Ye.getTargetData(t,n)}(i,t,sx(n)).next(e=>{if(e)return s=e.lastLimboFreeSnapshotVersion,i.Ye.getMatchingKeysForTargetId(t,e.targetId).next(e=>{o=e})}).next(()=>i.Kn.getDocumentsMatchingQuery(t,n,r?s:GR.min(),r?o:Zx())).next(e=>({documents:e,Jn:o})))}function M1(e,t){const n=e,r=n.Ye,i=n.jn.get(t);return i?Promise.resolve(i.target):n.persistence.runTransaction("Get target data","readonly",e=>r.At(e,t).next(e=>e?e.target:null))}function F1(e){const n=e;return n.persistence.runTransaction("Get new document changes","readonly",e=>function(e,t,n){const r=e;let i=Qx,s=CD(n);const o=f1(t),a=IDBKeyRange.lowerBound(s,!0);return o.Wt({index:GO.readTimeIndex,range:a},(e,t)=>{var n=kD(r.O,t);i=i.insert(n.key,n),s=t.readTime}).next(()=>({Rn:i,readTime:AD(s)}))}(n.Gn,e,n.Wn)).then(({Rn:e,readTime:t})=>(n.Wn=t,e))}class U1{constructor(e){this.O=e,this.ts=new Map,this.es=new Map}getBundleMetadata(e,t){return lD.resolve(this.ts.get(t))}saveBundleMetadata(e,t){return this.ts.set(t.id,{id:t.id,version:t.version,createTime:gO(t.createTime)}),lD.resolve()}getNamedQuery(e,t){return lD.resolve(this.es.get(t))}saveNamedQuery(e,t){return this.es.set(t.name,{name:(t=t).name,query:DD(t.bundledQuery),readTime:gO(t.readTime)}),lD.resolve()}}class j1{constructor(){this.ns=new Hx(q1.ss),this.rs=new Hx(q1.os)}isEmpty(){return this.ns.isEmpty()}addReference(e,t){var n=new q1(e,t);this.ns=this.ns.add(n),this.rs=this.rs.add(n)}cs(e,t){e.forEach(e=>this.addReference(e,t))}removeReference(e,t){this.us(new q1(e,t))}hs(e,t){e.forEach(e=>this.removeReference(e,t))}ls(e){const t=new gP(new ZR([])),n=new q1(t,e),r=new q1(t,e+1),i=[];return this.rs.forEachInRange([n,r],e=>{this.us(e),i.push(e.key)}),i}fs(){this.ns.forEach(e=>this.us(e))}us(e){this.ns=this.ns.delete(e),this.rs=this.rs.delete(e)}ds(e){var t=new gP(new ZR([])),n=new q1(t,e),t=new q1(t,e+1);let r=Zx();return this.rs.forEachInRange([n,t],e=>{r=r.add(e.key)}),r}containsKey(e){var t=new q1(e,0),t=this.ns.firstAfterOrEqual(t);return null!==t&&e.isEqual(t.key)}}class q1{constructor(e,t){this.key=e,this.ws=t}static ss(e,t){return gP.comparator(e.key,t.key)||zR(e.ws,t.ws)}static os(e,t){return zR(e.ws,t.ws)||gP.comparator(e.key,t.key)}}class V1{constructor(e,t){this.Xt=e,this.referenceDelegate=t,this.bn=[],this._s=1,this.gs=new Hx(q1.ss)}checkEmpty(e){return lD.resolve(0===this.bn.length)}addMutationBatch(e,t,n,r){var i=this._s;this._s++,0<this.bn.length&&this.bn[this.bn.length-1];var s=new bD(i,t,n,r);this.bn.push(s);for(const t of r)this.gs=this.gs.add(new q1(t.key,i)),this.Xt.addToCollectionParentIndex(e,t.key.path.popLast());return lD.resolve(s)}lookupMutationBatch(e,t){return lD.resolve(this.ys(t))}getNextMutationBatchAfterBatchId(e,t){var n=this.ps(t+1),n=n<0?0:n;return lD.resolve(this.bn.length>n?this.bn[n]:null)}getHighestUnacknowledgedBatchId(){return lD.resolve(0===this.bn.length?-1:this._s-1)}getAllMutationBatches(e){return lD.resolve(this.bn.slice())}getAllMutationBatchesAffectingDocumentKey(e,t){const n=new q1(t,0),r=new q1(t,Number.POSITIVE_INFINITY),i=[];return this.gs.forEachInRange([n,r],e=>{var t=this.ys(e.ws);i.push(t)}),lD.resolve(i)}getAllMutationBatchesAffectingDocumentKeys(e,t){let r=new Hx(zR);return t.forEach(e=>{var t=new q1(e,0),n=new q1(e,Number.POSITIVE_INFINITY);this.gs.forEachInRange([t,n],e=>{r=r.add(e.ws)})}),lD.resolve(this.Ts(r))}getAllMutationBatchesAffectingQuery(e,t){const n=t.path,r=n.length+1;let i=n;gP.isDocumentKey(i)||(i=i.child(""));var s=new q1(new gP(i),0);let o=new Hx(zR);return this.gs.forEachWhile(e=>{var t=e.key.path;return!!n.isPrefixOf(t)&&(t.length===r&&(o=o.add(e.ws)),!0)},s),lD.resolve(this.Ts(o))}Ts(e){const n=[];return e.forEach(e=>{var t=this.ys(e);null!==t&&n.push(t)}),n}removeMutationBatch(n,r){RR(0===this.Es(r.batchId,"removed")),this.bn.shift();let i=this.gs;return lD.forEach(r.mutations,e=>{var t=new q1(e.key,r.batchId);return i=i.delete(t),this.referenceDelegate.markPotentiallyOrphaned(n,e.key)}).next(()=>{this.gs=i})}se(e){}containsKey(e,t){var n=new q1(t,0),n=this.gs.firstAfterOrEqual(n);return lD.resolve(t.isEqual(n&&n.key))}performConsistencyCheck(e){return this.bn.length,lD.resolve()}Es(e,t){return this.ps(e)}ps(e){return 0===this.bn.length?0:e-this.bn[0].batchId}ys(e){var t=this.ps(e);return t<0||t>=this.bn.length?null:this.bn[t]}}class B1{constructor(e,t){this.Xt=e,this.Is=t,this.docs=new zx(gP.comparator),this.size=0}addEntry(e,t){const n=t.key,r=this.docs.get(n),i=r?r.size:0,s=this.Is(t);return this.docs=this.docs.insert(n,{document:t.mutableCopy(),size:s}),this.size+=s-i,this.Xt.addToCollectionParentIndex(e,n.path.popLast())}removeEntry(e){var t=this.docs.get(e);t&&(this.docs=this.docs.remove(e),this.size-=t.size)}getEntry(e,t){const n=this.docs.get(t);return lD.resolve(n?n.document.mutableCopy():RP.newInvalidDocument(t))}getEntries(e,t){let n=Qx;return t.forEach(e=>{const t=this.docs.get(e);n=n.insert(e,t?t.document.mutableCopy():RP.newInvalidDocument(e))}),lD.resolve(n)}getDocumentsMatchingQuery(e,t,n){let r=Qx;const i=new gP(t.path.child("")),s=this.docs.getIteratorFrom(i);for(;s.hasNext();){const{key:e,value:{document:i}}=s.getNext();if(!t.path.isPrefixOf(e.path))break;i.readTime.compareTo(n)<=0||ux(t,i)&&(r=r.insert(i.key,i.mutableCopy()))}return lD.resolve(r)}As(e,t){return lD.forEach(this.docs,e=>t(e))}newChangeBuffer(e){return new W1(this)}getSize(e){return lD.resolve(this.size)}}class W1 extends u1{constructor(e){super(),this.Ne=e}applyChanges(n){const r=[];return this.changes.forEach((e,t)=>{t.isValidDocument()?r.push(this.Ne.addEntry(n,t)):this.Ne.removeEntry(e)}),lD.waitFor(r)}getFromCache(e,t){return this.Ne.getEntry(e,t)}getAllFromCache(e,t){return this.Ne.getEntries(e,t)}}class z1{constructor(e){this.persistence=e,this.Rs=new l1(e=>OP(e),DP),this.lastRemoteSnapshotVersion=GR.min(),this.highestTargetId=0,this.bs=0,this.Ps=new j1,this.targetCount=0,this.vs=XD.oe()}forEachTarget(e,n){return this.Rs.forEach((e,t)=>n(t)),lD.resolve()}getLastRemoteSnapshotVersion(e){return lD.resolve(this.lastRemoteSnapshotVersion)}getHighestSequenceNumber(e){return lD.resolve(this.bs)}allocateTargetId(e){return this.highestTargetId=this.vs.next(),lD.resolve(this.highestTargetId)}setTargetsMetadata(e,t,n){return n&&(this.lastRemoteSnapshotVersion=n),t>this.bs&&(this.bs=t),lD.resolve()}he(e){this.Rs.set(e.target,e);var t=e.targetId;t>this.highestTargetId&&(this.vs=new XD(t),this.highestTargetId=t),e.sequenceNumber>this.bs&&(this.bs=e.sequenceNumber)}addTargetData(e,t){return this.he(t),this.targetCount+=1,lD.resolve()}updateTargetData(e,t){return this.he(t),lD.resolve()}removeTargetData(e,t){return this.Rs.delete(t.target),this.Ps.ls(t.targetId),--this.targetCount,lD.resolve()}removeTargets(n,r,i){let s=0;const o=[];return this.Rs.forEach((e,t)=>{t.sequenceNumber<=r&&null===i.get(t.targetId)&&(this.Rs.delete(e),o.push(this.removeMatchingKeysForTargetId(n,t.targetId)),s++)}),lD.waitFor(o).next(()=>s)}getTargetCount(e){return lD.resolve(this.targetCount)}getTargetData(e,t){var n=this.Rs.get(t)||null;return lD.resolve(n)}addMatchingKeys(e,t,n){return this.Ps.cs(t,n),lD.resolve()}removeMatchingKeys(t,e,n){this.Ps.hs(e,n);const r=this.persistence.referenceDelegate,i=[];return r&&e.forEach(e=>{i.push(r.markPotentiallyOrphaned(t,e))}),lD.waitFor(i)}removeMatchingKeysForTargetId(e,t){return this.Ps.ls(t),lD.resolve()}getMatchingKeysForTargetId(e,t){var n=this.Ps.ds(t);return lD.resolve(n)}containsKey(e,t){return lD.resolve(this.Ps.containsKey(t))}}class K1{constructor(e,t){var n;this.Vs={},this.qe=new BR(0),this.Ke=!1,this.Ke=!0,this.referenceDelegate=e(this),this.Ye=new z1(this),this.Xt=new UD,this.Xe=(n=this.Xt,e=e=>this.referenceDelegate.Ss(e),new B1(n,e)),this.O=new ED(t),this.Ze=new U1(this.O)}start(){return Promise.resolve()}shutdown(){return this.Ke=!1,Promise.resolve()}get started(){return this.Ke}setDatabaseDeletedListener(){}setNetworkEnabled(){}getIndexManager(){return this.Xt}getMutationQueue(e){let t=this.Vs[e.toKey()];return t||(t=new V1(this.Xt,this.referenceDelegate),this.Vs[e.toKey()]=t),t}getTargetCache(){return this.Ye}getRemoteDocumentCache(){return this.Xe}getBundleCache(){return this.Ze}runTransaction(e,t,n){kR("MemoryPersistence","Starting transaction:",e);const r=new $1(this.qe.next());return this.referenceDelegate.Ds(),n(r).next(e=>this.referenceDelegate.Cs(r).next(()=>e)).toPromise().then(e=>(r.raiseOnCommittedEvent(),e))}Ns(t,n){return lD.or(Object.values(this.Vs).map(e=>()=>e.containsKey(t,n)))}}class $1 extends cD{constructor(e){super(),this.currentSequenceNumber=e}}class H1{constructor(e){this.persistence=e,this.ks=new j1,this.xs=null}static $s(e){return new H1(e)}get Os(){if(this.xs)return this.xs;throw NR()}addReference(e,t,n){return this.ks.addReference(n,t),this.Os.delete(n.toString()),lD.resolve()}removeReference(e,t,n){return this.ks.removeReference(n,t),this.Os.add(n.toString()),lD.resolve()}markPotentiallyOrphaned(e,t){return this.Os.add(t.toString()),lD.resolve()}removeTarget(e,t){this.ks.ls(t.targetId).forEach(e=>this.Os.add(e.toString()));const n=this.persistence.getTargetCache();return n.getMatchingKeysForTargetId(e,t.targetId).next(e=>{e.forEach(e=>this.Os.add(e.toString()))}).next(()=>n.removeTargetData(e,t))}Ds(){this.xs=new Set}Cs(n){const r=this.persistence.getRemoteDocumentCache().newChangeBuffer();return lD.forEach(this.Os,e=>{const t=gP.fromPath(e);return this.Ms(n,t).next(e=>{e||r.removeEntry(t,GR.min())})}).next(()=>(this.xs=null,r.apply(n)))}updateLimboDocument(e,t){return this.Ms(e,t).next(e=>{e?this.Os.delete(t.toString()):this.Os.add(t.toString())})}Ss(e){return 0}Ms(e,t){return lD.or([()=>lD.resolve(this.ks.containsKey(t)),()=>this.persistence.getTargetCache().containsKey(e,t),()=>this.persistence.Ns(e,t)])}}function G1(e,t){return`firestore_clients_${e}_${t}`}function Q1(e,t,n){let r=`firestore_mutations_${e}_${n}`;return t.isAuthenticated()&&(r+=`_${t.uid}`),r}function Y1(e,t){return`firestore_targets_${e}_${t}`}class X1{constructor(e,t,n,r){this.user=e,this.batchId=t,this.state=n,this.error=r}static Fs(e,t,n){var r=JSON.parse(n);let i,s="object"==typeof r&&-1!==["pending","acknowledged","rejected"].indexOf(r.state)&&(void 0===r.error||"object"==typeof r.error);return s&&r.error&&(s="string"==typeof r.error.message&&"string"==typeof r.error.code,s&&(i=new xR(r.error.code,r.error.message))),s?new X1(e,t,r.state,i):(SR("SharedClientState",`Failed to parse mutation state for ID '${t}': ${n}`),null)}Ls(){const e={state:this.state,updateTimeMs:Date.now()};return this.error&&(e.error={code:this.error.code,message:this.error.message}),JSON.stringify(e)}}class J1{constructor(e,t,n){this.targetId=e,this.state=t,this.error=n}static Fs(e,t){var n=JSON.parse(t);let r,i="object"==typeof n&&-1!==["not-current","current","rejected"].indexOf(n.state)&&(void 0===n.error||"object"==typeof n.error);return i&&n.error&&(i="string"==typeof n.error.message&&"string"==typeof n.error.code,i&&(r=new xR(n.error.code,n.error.message))),i?new J1(e,n.state,r):(SR("SharedClientState",`Failed to parse target state for ID '${e}': ${t}`),null)}Ls(){const e={state:this.state,updateTimeMs:Date.now()};return this.error&&(e.error={code:this.error.code,message:this.error.message}),JSON.stringify(e)}}class Z1{constructor(e,t){this.clientId=e,this.activeTargetIds=t}static Fs(e,t){var n=JSON.parse(t);let r="object"==typeof n&&n.activeTargetIds instanceof Array,i=eO;for(let s=0;r&&s<n.activeTargetIds.length;++s)r=fP(n.activeTargetIds[s]),i=i.add(n.activeTargetIds[s]);return r?new Z1(e,i):(SR("SharedClientState",`Failed to parse client data for instance '${e}': ${t}`),null)}}class eL{constructor(e,t){this.clientId=e,this.onlineState=t}static Fs(e){var t=JSON.parse(e);return"object"==typeof t&&-1!==["Unknown","Online","Offline"].indexOf(t.onlineState)&&"string"==typeof t.clientId?new eL(t.clientId,t.onlineState):(SR("SharedClientState",`Failed to parse online state: ${e}`),null)}}class tL{constructor(){this.activeTargetIds=eO}Bs(e){this.activeTargetIds=this.activeTargetIds.add(e)}Us(e){this.activeTargetIds=this.activeTargetIds.delete(e)}Ls(){var e={activeTargetIds:this.activeTargetIds.toArray(),updateTimeMs:Date.now()};return JSON.stringify(e)}}class nL{constructor(e,t,n,r,i){this.window=e,this.Le=t,this.persistenceKey=n,this.qs=r,this.syncEngine=null,this.onlineStateHandler=null,this.sequenceNumberHandler=null,this.Ks=this.js.bind(this),this.Qs=new zx(zR),this.started=!1,this.Ws=[];var s=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");this.storage=this.window.localStorage,this.currentUser=i,this.Gs=G1(this.persistenceKey,this.qs),this.zs=`firestore_sequence_number_${this.persistenceKey}`,this.Qs=this.Qs.insert(this.qs,new tL),this.Hs=new RegExp(`^firestore_clients_${s}_([^_]*)$`),this.Js=new RegExp(`^firestore_mutations_${s}_(\\d+)(?:_(.*))?$`),this.Ys=new RegExp(`^firestore_targets_${s}_(\\d+)$`),this.Xs=`firestore_online_state_${this.persistenceKey}`,this.Zs=`firestore_bundle_loaded_${this.persistenceKey}`,this.window.addEventListener("storage",this.Ks)}static Vt(e){return!(!e||!e.localStorage)}async start(){const e=await this.syncEngine.In();for(const n of e)if(n!==this.qs){const e=this.getItem(G1(this.persistenceKey,n));var t;!e||(t=Z1.Fs(n,e))&&(this.Qs=this.Qs.insert(t.clientId,t))}this.ti();const n=this.storage.getItem(this.Xs);if(n){const e=this.ei(n);e&&this.ni(e)}for(const e of this.Ws)this.js(e);this.Ws=[],this.window.addEventListener("pagehide",()=>this.shutdown()),this.started=!0}writeSequenceNumber(e){this.setItem(this.zs,JSON.stringify(e))}getAllActiveQueryTargets(){return this.si(this.Qs)}isActiveQueryTarget(n){let r=!1;return this.Qs.forEach((e,t)=>{t.activeTargetIds.has(n)&&(r=!0)}),r}addPendingMutation(e){this.ii(e,"pending")}updateMutationState(e,t,n){this.ii(e,t,n),this.ri(e)}addLocalQueryTarget(e){let t="not-current";var n;return this.isActiveQueryTarget(e)&&(!(n=this.storage.getItem(Y1(this.persistenceKey,e)))||(n=J1.Fs(e,n))&&(t=n.state)),this.oi.Bs(e),this.ti(),t}removeLocalQueryTarget(e){this.oi.Us(e),this.ti()}isLocalQueryTarget(e){return this.oi.activeTargetIds.has(e)}clearQueryState(e){this.removeItem(Y1(this.persistenceKey,e))}updateQueryState(e,t,n){this.ci(e,t,n)}handleUserChange(e,t,n){t.forEach(e=>{this.ri(e)}),this.currentUser=e,n.forEach(e=>{this.addPendingMutation(e)})}setOnlineState(e){this.ai(e)}notifyBundleLoaded(){this.ui()}shutdown(){this.started&&(this.window.removeEventListener("storage",this.Ks),this.removeItem(this.Gs),this.started=!1)}getItem(e){var t=this.storage.getItem(e);return kR("SharedClientState","READ",e,t),t}setItem(e,t){kR("SharedClientState","SET",e,t),this.storage.setItem(e,t)}removeItem(e){kR("SharedClientState","REMOVE",e),this.storage.removeItem(e)}js(e){const r=e;r.storageArea===this.storage&&(kR("SharedClientState","EVENT",r.key,r.newValue),r.key!==this.Gs?this.Le.enqueueRetryable(async()=>{if(this.started){if(null!==r.key)if(this.Hs.test(r.key)){if(null==r.newValue){var e=this.hi(r.key);return this.li(e,null)}e=this.fi(r.key,r.newValue);if(e)return this.li(e.clientId,e)}else if(this.Js.test(r.key)){if(null!==r.newValue){var t=this.di(r.key,r.newValue);if(t)return this.wi(t)}}else if(this.Ys.test(r.key)){if(null!==r.newValue){t=this._i(r.key,r.newValue);if(t)return this.mi(t)}}else if(r.key===this.Xs){if(null!==r.newValue){var n=this.ei(r.newValue);if(n)return this.ni(n)}}else if(r.key===this.zs){n=function(e){let t=BR.I;if(null!=e)try{var n=JSON.parse(e);RR("number"==typeof n),t=n}catch(e){SR("SharedClientState","Failed to read sequence number from WebStorage",e)}return t}(r.newValue);n!==BR.I&&this.sequenceNumberHandler(n)}else if(r.key===this.Zs)return this.syncEngine.gi()}else this.Ws.push(r)}):SR("Received WebStorage notification for local change. Another client might have garbage-collected our state"))}get oi(){return this.Qs.get(this.qs)}ti(){this.setItem(this.Gs,this.oi.Ls())}ii(e,t,n){const r=new X1(this.currentUser,e,t,n),i=Q1(this.persistenceKey,this.currentUser,e);this.setItem(i,r.Ls())}ri(e){var t=Q1(this.persistenceKey,this.currentUser,e);this.removeItem(t)}ai(e){var t={clientId:this.qs,onlineState:e};this.storage.setItem(this.Xs,JSON.stringify(t))}ci(e,t,n){const r=Y1(this.persistenceKey,e),i=new J1(e,t,n);this.setItem(r,i.Ls())}ui(){this.setItem(this.Zs,"value-not-used")}hi(e){var t=this.Hs.exec(e);return t?t[1]:null}fi(e,t){var n=this.hi(e);return Z1.Fs(n,t)}di(e,t){var n=this.Js.exec(e),r=Number(n[1]),n=void 0!==n[2]?n[2]:null;return X1.Fs(new bR(n),r,t)}_i(e,t){var n=this.Ys.exec(e),n=Number(n[1]);return J1.Fs(n,t)}ei(e){return eL.Fs(e)}async wi(e){if(e.user.uid===this.currentUser.uid)return this.syncEngine.yi(e.batchId,e.state,e.error);kR("SharedClientState",`Ignoring mutation for non-active user ${e.user.uid}`)}mi(e){return this.syncEngine.pi(e.targetId,e.state,e.error)}li(e,t){const n=t?this.Qs.insert(e,t):this.Qs.remove(e),r=this.si(this.Qs),i=this.si(n),s=[],o=[];return i.forEach(e=>{r.has(e)||s.push(e)}),r.forEach(e=>{i.has(e)||o.push(e)}),this.syncEngine.Ti(s,o).then(()=>{this.Qs=n})}ni(e){this.Qs.get(e.clientId)&&this.onlineStateHandler(e.onlineState)}si(e){let n=eO;return e.forEach((e,t)=>{n=n.unionWith(t.activeTargetIds)}),n}}class rL{constructor(){this.Ei=new tL,this.Ii={},this.onlineStateHandler=null,this.sequenceNumberHandler=null}addPendingMutation(e){}updateMutationState(e,t,n){}addLocalQueryTarget(e){return this.Ei.Bs(e),this.Ii[e]||"not-current"}updateQueryState(e,t,n){this.Ii[e]=t}removeLocalQueryTarget(e){this.Ei.Us(e)}isLocalQueryTarget(e){return this.Ei.activeTargetIds.has(e)}clearQueryState(e){delete this.Ii[e]}getAllActiveQueryTargets(){return this.Ei.activeTargetIds}isActiveQueryTarget(e){return this.Ei.activeTargetIds.has(e)}start(){return this.Ei=new tL,Promise.resolve()}handleUserChange(e,t,n){}setOnlineState(e){}shutdown(){}writeSequenceNumber(e){}notifyBundleLoaded(){}}class iL{Ai(e){}shutdown(){}}class sL{constructor(){this.Ri=()=>this.bi(),this.Pi=()=>this.vi(),this.Vi=[],this.Si()}Ai(e){this.Vi.push(e)}shutdown(){window.removeEventListener("online",this.Ri),window.removeEventListener("offline",this.Pi)}Si(){window.addEventListener("online",this.Ri),window.addEventListener("offline",this.Pi)}bi(){kR("ConnectivityMonitor","Network connectivity changed: AVAILABLE");for(const e of this.Vi)e(0)}vi(){kR("ConnectivityMonitor","Network connectivity changed: UNAVAILABLE");for(const e of this.Vi)e(1)}static Vt(){return"undefined"!=typeof window&&void 0!==window.addEventListener&&void 0!==window.removeEventListener}}const oL={BatchGetDocuments:"batchGet",Commit:"commit",RunQuery:"runQuery"};class aL{constructor(e){this.Di=e.Di,this.Ci=e.Ci}Ni(e){this.ki=e}xi(e){this.$i=e}onMessage(e){this.Oi=e}close(){this.Ci()}send(e){this.Di(e)}Mi(){this.ki()}Fi(e){this.$i(e)}Li(e){this.Oi(e)}}class cL extends class{constructor(e){this.databaseInfo=e,this.databaseId=e.databaseId;var t=e.ssl?"https":"http";this.Bi=t+"://"+e.host,this.Ui="projects/"+this.databaseId.projectId+"/databases/"+this.databaseId.database+"/documents"}qi(t,e,n,r,i){const s=this.Ki(t,e);kR("RestConnection","Sending: ",s,n);var o={};return this.ji(o,r,i),this.Qi(t,s,o,n).then(e=>(kR("RestConnection","Received: ",e),e),e=>{throw CR("RestConnection",`${t} failed with error: `,e,"url: ",s,"request:",n),e})}Wi(e,t,n,r,i){return this.qi(e,t,n,r,i)}ji(n,e,t){n["X-Goog-Api-Client"]="gl-js/ fire/"+IR,n["Content-Type"]="text/plain",this.databaseInfo.appId&&(n["X-Firebase-GMPID"]=this.databaseInfo.appId),e&&e.headers.forEach((e,t)=>n[t]=e),t&&t.headers.forEach((e,t)=>n[t]=e)}Ki(e,t){var n=oL[e];return`${this.Bi}/v1/${t}:${n}`}}{constructor(e){super(e),this.forceLongPolling=e.forceLongPolling,this.autoDetectLongPolling=e.autoDetectLongPolling,this.useFetchStreams=e.useFetchStreams}Qi(a,t,n,r){return new Promise((i,s)=>{const o=new _R;o.listenOnce(pR.COMPLETE,()=>{try{switch(o.getLastErrorCode()){case dR.NO_ERROR:var e=o.getResponseJson();kR("Connection","XHR received:",JSON.stringify(e)),i(e);break;case dR.TIMEOUT:kR("Connection",'RPC "'+a+'" timed out'),s(new xR(PR.DEADLINE_EXCEEDED,"Request time out"));break;case dR.HTTP_ERROR:var t,n=o.getStatus();if(kR("Connection",'RPC "'+a+'" failed with status:',n,"response text:",o.getResponseText()),0<n){const a=o.getResponseJson().error;a&&a.status&&a.message?(r=a.status.toLowerCase().replace(/_/g,"-"),t=0<=Object.values(PR).indexOf(r)?r:PR.UNKNOWN,s(new xR(t,a.message))):s(new xR(PR.UNKNOWN,"Server responded with status "+o.getStatus()))}else s(new xR(PR.UNAVAILABLE,"Connection failed."));break;default:NR()}}finally{kR("Connection",'RPC "'+a+'" completed.')}var r});var e=JSON.stringify(r);o.send(t,"POST",e,n,15)})}Gi(e,t,n){const r=[this.Bi,"/","google.firestore.v1.Firestore","/",e,"/channel"],i=new sR,s=hR(),o={httpSessionIdParam:"gsessionid",initMessageHeaders:{},messageUrlParams:{database:`projects/${this.databaseId.projectId}/databases/${this.databaseId.database}`},sendRawJson:!0,supportsCrossDomainXhr:!0,internalChannelParams:{forwardChannelRequestTimeoutMs:6e5},forceLongPolling:this.forceLongPolling,detectBufferingProxy:this.autoDetectLongPolling};this.useFetchStreams&&(o.xmlHttpFactory=new vR({})),this.ji(o.initMessageHeaders,t,n),od()||ld()||0<=sd().indexOf("Electron/")||ud()||0<=sd().indexOf("MSAppHost/")||cd()||(o.httpHeadersOverwriteParam="$httpHeaders");var a=r.join("");kR("Connection","Creating WebChannel: "+a,o);const c=i.createWebChannel(a,o);let l=!1,u=!1;const h=new aL({Di:e=>{u?kR("Connection","Not sending because WebChannel is closed:",e):(l||(kR("Connection","Opening WebChannel transport."),c.open(),l=!0),kR("Connection","WebChannel sending:",e),c.send(e))},Ci:()=>c.close()}),d=(e,t,n)=>{e.listen(t,e=>{try{n(e)}catch(e){setTimeout(()=>{throw e},0)}})};return d(c,yR.EventType.OPEN,()=>{u||kR("Connection","WebChannel transport opened.")}),d(c,yR.EventType.CLOSE,()=>{u||(u=!0,kR("Connection","WebChannel transport closed"),h.Fi())}),d(c,yR.EventType.ERROR,e=>{u||(u=!0,CR("Connection","WebChannel transport errored:",e),h.Fi(new xR(PR.UNAVAILABLE,"The operation could not be completed")))}),d(c,yR.EventType.MESSAGE,n=>{if(!u){var e=n.data[0];RR(!!e);var r=e.error||(null===(r=e[0])||void 0===r?void 0:r.error);if(r){kR("Connection","WebChannel received error:",r);const n=r.status;let e=function(e){var t=uR[e];if(void 0!==t)return Wx(t)}(n),t=r.message;void 0===e&&(e=PR.INTERNAL,t="Unknown error status: "+n+" with message "+r.message),u=!0,h.Fi(new xR(e,t)),c.close()}else kR("Connection","WebChannel received:",e),h.Li(e)}}),d(s,fR.STAT_EVENT,e=>{e.stat===gR?kR("Connection","Detected buffering proxy"):e.stat===mR&&kR("Connection","Detected no buffering proxy")}),setTimeout(()=>{h.Mi()},0),h}}function lL(){return"undefined"!=typeof window?window:null}function uL(){return"undefined"!=typeof document?document:null}function hL(e){return new dO(e,!0)}class dL{constructor(e,t,n=1e3,r=1.5,i=6e4){this.Le=e,this.timerId=t,this.zi=n,this.Hi=r,this.Ji=i,this.Yi=0,this.Xi=null,this.Zi=Date.now(),this.reset()}reset(){this.Yi=0}tr(){this.Yi=this.Ji}er(e){this.cancel();var t=Math.floor(this.Yi+this.nr()),n=Math.max(0,Date.now()-this.Zi),r=Math.max(0,t-n);0<r&&kR("ExponentialBackoff",`Backing off for ${r} ms (base delay: ${this.Yi} ms, delay with jitter: ${t} ms, last attempt: ${n} ms ago)`),this.Xi=this.Le.enqueueAfterDelay(this.timerId,r,()=>(this.Zi=Date.now(),e())),this.Yi*=this.Hi,this.Yi<this.zi&&(this.Yi=this.zi),this.Yi>this.Ji&&(this.Yi=this.Ji)}sr(){null!==this.Xi&&(this.Xi.skipDelay(),this.Xi=null)}cancel(){null!==this.Xi&&(this.Xi.cancel(),this.Xi=null)}nr(){return(Math.random()-.5)*this.Yi}}class pL{constructor(e,t,n,r,i,s,o,a){this.Le=e,this.ir=n,this.rr=r,this.cr=i,this.authCredentialsProvider=s,this.appCheckCredentialsProvider=o,this.listener=a,this.state=0,this.ar=0,this.ur=null,this.hr=null,this.stream=null,this.lr=new dL(e,t)}dr(){return 1===this.state||5===this.state||this.wr()}wr(){return 2===this.state||3===this.state}start(){4!==this.state?this.auth():this._r()}async stop(){this.dr()&&await this.close(0)}mr(){this.state=0,this.lr.reset()}gr(){this.wr()&&null===this.ur&&(this.ur=this.Le.enqueueAfterDelay(this.ir,6e4,()=>this.yr()))}pr(e){this.Tr(),this.stream.send(e)}async yr(){if(this.wr())return this.close(0)}Tr(){this.ur&&(this.ur.cancel(),this.ur=null)}Er(){this.hr&&(this.hr.cancel(),this.hr=null)}async close(e,t){this.Tr(),this.Er(),this.lr.cancel(),this.ar++,4!==e?this.lr.reset():t&&t.code===PR.RESOURCE_EXHAUSTED?(SR(t.toString()),SR("Using maximum backoff delay to prevent overloading the backend."),this.lr.tr()):t&&t.code===PR.UNAUTHENTICATED&&3!==this.state&&(this.authCredentialsProvider.invalidateToken(),this.appCheckCredentialsProvider.invalidateToken()),null!==this.stream&&(this.Ir(),this.stream.close(),this.stream=null),this.state=e,await this.listener.xi(t)}Ir(){}auth(){this.state=1;const e=this.Ar(this.ar),n=this.ar;Promise.all([this.authCredentialsProvider.getToken(),this.appCheckCredentialsProvider.getToken()]).then(([e,t])=>{this.ar===n&&this.Rr(e,t)},t=>{e(()=>{var e=new xR(PR.UNKNOWN,"Fetching auth token failed: "+t.message);return this.br(e)})})}Rr(e,t){const n=this.Ar(this.ar);this.stream=this.Pr(e,t),this.stream.Ni(()=>{n(()=>(this.state=2,this.hr=this.Le.enqueueAfterDelay(this.rr,1e4,()=>(this.wr()&&(this.state=3),Promise.resolve())),this.listener.Ni()))}),this.stream.xi(e=>{n(()=>this.br(e))}),this.stream.onMessage(e=>{n(()=>this.onMessage(e))})}_r(){this.state=5,this.lr.er(async()=>{this.state=0,this.start()})}br(e){return kR("PersistentStream",`close with error: ${e}`),this.stream=null,this.close(4,e)}Ar(t){return e=>{this.Le.enqueueAndForget(()=>this.ar===t?e():(kR("PersistentStream","stream callback skipped by getCloseGuardedDispatcher."),Promise.resolve()))}}}class fL extends pL{constructor(e,t,n,r,i,s){super(e,"listen_stream_connection_backoff","listen_stream_idle","health_check_timeout",t,n,r,s),this.O=i}Pr(e,t){return this.cr.Gi("Listen",e,t)}onMessage(e){this.lr.reset();var t=function(e,t){let n;if("targetChange"in t){t.targetChange;var r="NO_CHANGE"===(p=t.targetChange.targetChangeType||"NO_CHANGE")?0:"ADD"===p?1:"REMOVE"===p?2:"CURRENT"===p?3:"RESET"===p?4:NR(),i=t.targetChange.targetIds||[],s=(p=t.targetChange.resumeToken,e.k?(RR(void 0===p||"string"==typeof p),rP.fromBase64String(p||"")):(RR(void 0===p||p instanceof Uint8Array),rP.fromUint8Array(p||new Uint8Array))),o=t.targetChange.cause,a=o&&(a=void 0===(p=o).code?PR.UNKNOWN:Wx(p.code),new xR(a,p.message||""));n=new sO(r,i,s,a||null)}else if("documentChange"in t){t.documentChange;var c=t.documentChange;c.document,c.document.name,c.document.updateTime;var a=_O(e,c.document.name),l=gO(c.document.updateTime),u=new NP({mapValue:{fields:c.document.fields}}),l=RP.newFoundDocument(a,l,u),u=c.targetIds||[],c=c.removedTargetIds||[];n=new rO(u,c,l.key,l)}else if("documentDelete"in t){t.documentDelete;u=t.documentDelete;u.document;c=_O(e,u.document),l=u.readTime?gO(u.readTime):GR.min(),l=RP.newNoDocument(c,l),u=u.removedTargetIds||[];n=new rO([],u,l.key,l)}else if("documentRemove"in t){t.documentRemove;var h=t.documentRemove;h.document;var d=_O(e,h.document),h=h.removedTargetIds||[];n=new rO([],h,d,null)}else{if(!("filter"in t))return NR();{t.filter;const e=t.filter;e.targetId;h=e.count||0,d=new Vx(h),h=e.targetId;n=new iO(h,d)}}var a,p;return n}(this.O,e),n=function(e){if(!("targetChange"in e))return GR.min();var t=e.targetChange;return(!t.targetIds||!t.targetIds.length)&&t.readTime?gO(t.readTime):GR.min()}(e);return this.listener.vr(t,n)}Vr(e){const t={};t.database=IO(this.O),t.addTarget=function(e,t){let n;var r=t.target;return n=LP(r)?{documents:AO(e,r)}:{query:NO(e,r)},n.targetId=t.targetId,0<t.resumeToken.approximateByteSize()?n.resumeToken=fO(e,t.resumeToken):0<t.snapshotVersion.compareTo(GR.min())&&(n.readTime=pO(e,t.snapshotVersion.toTimestamp())),n}(this.O,e);var n,r,r=(this.O,n=e,null==(r=function(){switch(n.purpose){case 0:return null;case 1:return"existence-filter-mismatch";case 2:return"limbo-document";default:return NR()}}())?null:{"goog-listen-tags":r});r&&(t.labels=r),this.pr(t)}Sr(e){const t={};t.database=IO(this.O),t.removeTarget=e,this.pr(t)}}class gL extends pL{constructor(e,t,n,r,i,s){super(e,"write_stream_connection_backoff","write_stream_idle","health_check_timeout",t,n,r,s),this.O=i,this.Dr=!1}get Cr(){return this.Dr}start(){this.Dr=!1,this.lastStreamToken=void 0,super.start()}Ir(){this.Dr&&this.Nr([])}Pr(e,t){return this.cr.Gi("Write",e,t)}onMessage(e){if(RR(!!e.streamToken),this.lastStreamToken=e.streamToken,this.Dr){this.lr.reset();var t=(r=e.writeResults,i=e.commitTime,r&&0<r.length?(RR(void 0!==i),r.map(e=>function(e,t){let n=e.updateTime?gO(e.updateTime):gO(t);return n.isEqual(GR.min())&&(n=gO(t)),new Sx(n,e.transformResults||[])}(e,i))):[]),n=gO(e.commitTime);return this.listener.kr(n,t)}var r,i;return RR(!e.writeResults||0===e.writeResults.length),this.Dr=!0,this.listener.$r()}Or(){const e={};e.database=IO(this.O),this.pr(e)}Nr(e){var t={streamToken:this.lastStreamToken,writes:e.map(e=>SO(this.O,e))};this.pr(t)}}class mL extends class{}{constructor(e,t,n,r){super(),this.authCredentials=e,this.appCheckCredentials=t,this.cr=n,this.O=r,this.Mr=!1}Fr(){if(this.Mr)throw new xR(PR.FAILED_PRECONDITION,"The client has already been terminated.")}qi(n,r,i){return this.Fr(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then(([e,t])=>this.cr.qi(n,r,i,e,t)).catch(e=>{throw"FirebaseError"===e.name?(e.code===PR.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),e):new xR(PR.UNKNOWN,e.toString())})}Wi(n,r,i){return this.Fr(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then(([e,t])=>this.cr.Wi(n,r,i,e,t)).catch(e=>{throw"FirebaseError"===e.name?(e.code===PR.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),e):new xR(PR.UNKNOWN,e.toString())})}terminate(){this.Mr=!0}}class vL{constructor(e,t){this.asyncQueue=e,this.onlineStateHandler=t,this.state="Unknown",this.Lr=0,this.Br=null,this.Ur=!0}qr(){0===this.Lr&&(this.Kr("Unknown"),this.Br=this.asyncQueue.enqueueAfterDelay("online_state_timeout",1e4,()=>(this.Br=null,this.jr("Backend didn't respond within 10 seconds."),this.Kr("Offline"),Promise.resolve())))}Qr(e){"Online"===this.state?this.Kr("Unknown"):(this.Lr++,1<=this.Lr&&(this.Wr(),this.jr(`Connection failed 1 times. Most recent error: ${e.toString()}`),this.Kr("Offline")))}set(e){this.Wr(),this.Lr=0,"Online"===e&&(this.Ur=!1),this.Kr(e)}Kr(e){e!==this.state&&(this.state=e,this.onlineStateHandler(e))}jr(e){var t=`Could not reach Cloud Firestore backend. ${e}\nThis typically indicates that your device does not have a healthy Internet connection at the moment. The client will operate in offline mode until it is able to successfully connect to the backend.`;this.Ur?(SR(t),this.Ur=!1):kR("OnlineStateTracker",t)}Wr(){null!==this.Br&&(this.Br.cancel(),this.Br=null)}}class yL{constructor(e,t,n,r,i){this.localStore=e,this.datastore=t,this.asyncQueue=n,this.remoteSyncer={},this.Gr=[],this.zr=new Map,this.Hr=new Set,this.Jr=[],this.Yr=i,this.Yr.Ai(e=>{n.enqueueAndForget(async()=>{CL(this)&&(kR("RemoteStore","Restarting streams for network reachability change."),await async function(e){const t=e;t.Hr.add(4),await wL(t),t.Xr.set("Unknown"),t.Hr.delete(4),await _L(t)}(this))})}),this.Xr=new vL(n,r)}}async function _L(e){if(CL(e))for(const t of e.Jr)await t(!0)}async function wL(e){for(const t of e.Jr)await t(!1)}function bL(e,t){const n=e;n.zr.has(t.targetId)||(n.zr.set(t.targetId,t),SL(n)?kL(n):ML(n).wr()&&TL(n,t))}function IL(e,t){const n=e,r=ML(n);n.zr.delete(t),r.wr()&&EL(n,t),0===n.zr.size&&(r.wr()?r.gr():CL(n)&&n.Xr.set("Unknown"))}function TL(e,t){e.Zr.tt(t.targetId),ML(e).Vr(t)}function EL(e,t){e.Zr.tt(t),ML(e).Sr(t)}function kL(t){t.Zr=new aO({getRemoteKeysForTarget:e=>t.remoteSyncer.getRemoteKeysForTarget(e),At:e=>t.zr.get(e)||null}),ML(t).start(),t.Xr.qr()}function SL(e){return CL(e)&&!ML(e).dr()&&0<e.zr.size}function CL(e){return 0===e.Hr.size}function AL(e){e.Zr=void 0}async function NL(e,t,n){if(!fD(t))throw t;e.Hr.add(1),await wL(e),e.Xr.set("Offline"),n=n||(()=>R1(e.localStore)),e.asyncQueue.enqueueRetryable(async()=>{kR("RemoteStore","Retrying IndexedDB access"),await n(),e.Hr.delete(1),await _L(e)})}function RL(t,n){return n().catch(e=>NL(t,e,n))}async function PL(e){const t=e,n=FL(t);let r=0<t.Gr.length?t.Gr[t.Gr.length-1].batchId:-1;for(;CL(i=t)&&i.Gr.length<10;)try{const e=await function(e,t){const n=e;return n.persistence.runTransaction("Get next mutation batch","readonly",e=>(void 0===t&&(t=-1),n.bn.getNextMutationBatchAfterBatchId(e,t)))}(t.localStore,r);if(null===e){0===t.Gr.length&&n.gr();break}r=e.batchId,function(e,t){e.Gr.push(t);const n=FL(e);n.wr()&&n.Cr&&n.Nr(t.mutations)}(t,e)}catch(e){await NL(t,e)}var i;xL(t)&&OL(t)}function xL(e){return CL(e)&&!FL(e).dr()&&0<e.Gr.length}function OL(e){FL(e).start()}async function DL(e,t){const n=e;n.asyncQueue.verifyOperationInProgress(),kR("RemoteStore","RemoteStore received new credentials");var r=CL(n);n.Hr.add(3),await wL(n),r&&n.Xr.set("Unknown"),await n.remoteSyncer.handleCredentialChange(t),n.Hr.delete(3),await _L(n)}async function LL(e,t){const n=e;t?(n.Hr.delete(2),await _L(n)):(n.Hr.add(2),await wL(n),n.Xr.set("Unknown"))}function ML(t){return t.eo||(t.eo=function(e,t,n){const r=e;return r.Fr(),new fL(t,r.cr,r.authCredentials,r.appCheckCredentials,r.O,n)}(t.datastore,t.asyncQueue,{Ni:(async function(n){n.zr.forEach((e,t)=>{TL(n,e)})}).bind(null,t),xi:(async function(e,t){AL(e),SL(e)?(e.Xr.Qr(t),kL(e)):e.Xr.set("Unknown")}).bind(null,t),vr:(async function(e,r,t){if(e.Xr.set("Online"),r instanceof sO&&2===r.state&&r.cause)try{await async function(e){var t=r.cause;for(const n of r.targetIds)e.zr.has(n)&&(await e.remoteSyncer.rejectListen(n,t),e.zr.delete(n),e.Zr.removeTarget(n))}(e)}catch(t){kR("RemoteStore","Failed to remove targets %s: %s ",r.targetIds.join(","),t),await NL(e,t)}else if(r instanceof rO?e.Zr.at(r):r instanceof iO?e.Zr._t(r):e.Zr.lt(r),!t.isEqual(GR.min()))try{const r=await R1(e.localStore);0<=t.compareTo(r)&&await function(r,i){const e=r.Zr.Tt(i);return e.targetChanges.forEach((e,t)=>{if(0<e.resumeToken.approximateByteSize()){const n=r.zr.get(t);n&&r.zr.set(t,n.withResumeToken(e.resumeToken,i))}}),e.targetMismatches.forEach(e=>{const t=r.zr.get(e);var n;t&&(r.zr.set(e,t.withResumeToken(rP.EMPTY_BYTE_STRING,t.snapshotVersion)),EL(r,e),n=new TD(t.target,e,1,t.sequenceNumber),TL(r,n))}),r.remoteSyncer.applyRemoteEvent(e)}(e,t)}catch(r){kR("RemoteStore","Failed to raise snapshot:",r),await NL(e,r)}}).bind(null,t)}),t.Jr.push(async e=>{e?(t.eo.mr(),SL(t)?kL(t):t.Xr.set("Unknown")):(await t.eo.stop(),AL(t))})),t.eo}function FL(t){return t.no||(t.no=function(e,t,n){const r=e;return r.Fr(),new gL(t,r.cr,r.authCredentials,r.appCheckCredentials,r.O,n)}(t.datastore,t.asyncQueue,{Ni:(async function(e){FL(e).Or()}).bind(null,t),xi:(async function(e,t){t&&FL(e).Cr&&await async function(e,t){if(Bx(n=t.code)&&n!==PR.ABORTED){const n=e.Gr.shift();FL(e).mr(),await RL(e,()=>e.remoteSyncer.rejectFailedWrite(n.batchId,t)),await PL(e)}var n}(e,t),xL(e)&&OL(e)}).bind(null,t),$r:(async function(e){const t=FL(e);for(const n of e.Gr)t.Nr(n.mutations)}).bind(null,t),kr:(async function(e,t,n){const r=e.Gr.shift(),i=ID.from(r,t,n);await RL(e,()=>e.remoteSyncer.applySuccessfulWrite(i)),await PL(e)}).bind(null,t)}),t.Jr.push(async e=>{e?(t.no.mr(),await PL(t)):(await t.no.stop(),0<t.Gr.length&&(kR("RemoteStore",`Stopping write stream with ${t.Gr.length} pending writes`),t.Gr=[]))})),t.no}class UL{constructor(e,t,n,r,i){this.asyncQueue=e,this.timerId=t,this.targetTimeMs=n,this.op=r,this.removalCallback=i,this.deferred=new OR,this.then=this.deferred.promise.then.bind(this.deferred.promise),this.deferred.promise.catch(e=>{})}static createAndSchedule(e,t,n,r,i){const s=Date.now()+n,o=new UL(e,t,s,r,i);return o.start(n),o}start(e){this.timerHandle=setTimeout(()=>this.handleDelayElapsed(),e)}skipDelay(){return this.handleDelayElapsed()}cancel(e){null!==this.timerHandle&&(this.clearTimeout(),this.deferred.reject(new xR(PR.CANCELLED,"Operation cancelled"+(e?": "+e:""))))}handleDelayElapsed(){this.asyncQueue.enqueueAndForget(()=>null!==this.timerHandle?(this.clearTimeout(),this.op().then(e=>this.deferred.resolve(e))):Promise.resolve())}clearTimeout(){null!==this.timerHandle&&(this.removalCallback(this),clearTimeout(this.timerHandle),this.timerHandle=null)}}function jL(e,t){if(SR("AsyncQueue",`${t}: ${e}`),fD(e))return new xR(PR.UNAVAILABLE,`${t}: ${e}`);throw e}class qL{constructor(n){this.comparator=n?(e,t)=>n(e,t)||gP.comparator(e.key,t.key):(e,t)=>gP.comparator(e.key,t.key),this.keyedMap=Yx,this.sortedSet=new zx(this.comparator)}static emptySet(e){return new qL(e.comparator)}has(e){return null!=this.keyedMap.get(e)}get(e){return this.keyedMap.get(e)}first(){return this.sortedSet.minKey()}last(){return this.sortedSet.maxKey()}isEmpty(){return this.sortedSet.isEmpty()}indexOf(e){var t=this.keyedMap.get(e);return t?this.sortedSet.indexOf(t):-1}get size(){return this.sortedSet.size}forEach(n){this.sortedSet.inorderTraversal((e,t)=>(n(e),!1))}add(e){const t=this.delete(e.key);return t.copy(t.keyedMap.insert(e.key,e),t.sortedSet.insert(e,null))}delete(e){var t=this.get(e);return t?this.copy(this.keyedMap.remove(e),this.sortedSet.remove(t)):this}isEqual(e){if(!(e instanceof qL))return!1;if(this.size!==e.size)return!1;const t=this.sortedSet.getIterator(),n=e.sortedSet.getIterator();for(;t.hasNext();){const e=t.getNext().key,r=n.getNext().key;if(!e.isEqual(r))return!1}return!0}toString(){const t=[];return this.forEach(e=>{t.push(e.toString())}),0===t.length?"DocumentSet ()":"DocumentSet (\n  "+t.join("  \n")+"\n)"}copy(e,t){const n=new qL;return n.comparator=this.comparator,n.keyedMap=e,n.sortedSet=t,n}}class VL{constructor(){this.so=new zx(gP.comparator)}track(e){var t=e.doc.key,n=this.so.get(t);!n||0!==e.type&&3===n.type?this.so=this.so.insert(t,e):3===e.type&&1!==n.type?this.so=this.so.insert(t,{type:n.type,doc:e.doc}):2===e.type&&2===n.type?this.so=this.so.insert(t,{type:2,doc:e.doc}):2===e.type&&0===n.type?this.so=this.so.insert(t,{type:0,doc:e.doc}):1===e.type&&0===n.type?this.so=this.so.remove(t):1===e.type&&2===n.type?this.so=this.so.insert(t,{type:1,doc:n.doc}):0===e.type&&1===n.type?this.so=this.so.insert(t,{type:2,doc:e.doc}):NR()}io(){const n=[];return this.so.inorderTraversal((e,t)=>{n.push(t)}),n}}class BL{constructor(e,t,n,r,i,s,o,a){this.query=e,this.docs=t,this.oldDocs=n,this.docChanges=r,this.mutatedKeys=i,this.fromCache=s,this.syncStateChanged=o,this.excludesMetadataChanges=a}static fromInitialDocuments(e,t,n,r){const i=[];return t.forEach(e=>{i.push({type:0,doc:e})}),new BL(e,t,qL.emptySet(t),i,n,r,!0,!1)}get hasPendingWrites(){return!this.mutatedKeys.isEmpty()}isEqual(e){if(!(this.fromCache===e.fromCache&&this.syncStateChanged===e.syncStateChanged&&this.mutatedKeys.isEqual(e.mutatedKeys)&&ax(this.query,e.query)&&this.docs.isEqual(e.docs)&&this.oldDocs.isEqual(e.oldDocs)))return!1;const t=this.docChanges,n=e.docChanges;if(t.length!==n.length)return!1;for(let r=0;r<t.length;r++)if(t[r].type!==n[r].type||!t[r].doc.isEqual(n[r].doc))return!1;return!0}}class WL{constructor(){this.ro=void 0,this.listeners=[]}}class zL{constructor(){this.queries=new l1(e=>cx(e),ax),this.onlineState="Unknown",this.oo=new Set}}async function KL(e,t){const n=e,r=t.query;let i=!1,s=n.queries.get(r);if(s||(i=!0,s=new WL),i)try{s.ro=await n.onListen(r)}catch(e){const n=jL(e,`Initialization of query '${lx(t.query)}' failed`);return void t.onError(n)}n.queries.set(r,s),s.listeners.push(t),t.co(n.onlineState),!s.ro||t.ao(s.ro)&&HL(n)}async function $L(e,t){const n=e,r=t.query;let i=!1;const s=n.queries.get(r);if(s){const e=s.listeners.indexOf(t);0<=e&&(s.listeners.splice(e,1),i=0===s.listeners.length)}if(i)return n.queries.delete(r),n.onUnlisten(r)}function HL(e){e.oo.forEach(e=>{e.next()})}class GL{constructor(e,t,n){this.query=e,this.uo=t,this.ho=!1,this.lo=null,this.onlineState="Unknown",this.options=n||{}}ao(e){if(!this.options.includeMetadataChanges){const t=[];for(const n of e.docChanges)3!==n.type&&t.push(n);e=new BL(e.query,e.docs,e.oldDocs,t,e.mutatedKeys,e.fromCache,e.syncStateChanged,!0)}let t=!1;return this.ho?this.fo(e)&&(this.uo.next(e),t=!0):this.wo(e,this.onlineState)&&(this._o(e),t=!0),this.lo=e,t}onError(e){this.uo.error(e)}co(e){this.onlineState=e;let t=!1;return this.lo&&!this.ho&&this.wo(this.lo,e)&&(this._o(this.lo),t=!0),t}wo(e,t){return!e.fromCache||!(this.options.mo&&"Offline"!==t||e.docs.isEmpty()&&"Offline"!==t)}fo(e){if(0<e.docChanges.length)return!0;var t=this.lo&&this.lo.hasPendingWrites!==e.hasPendingWrites;return!(!e.syncStateChanged&&!t)&&!0===this.options.includeMetadataChanges}_o(e){e=BL.fromInitialDocuments(e.query,e.docs,e.mutatedKeys,e.fromCache),this.ho=!0,this.uo.next(e)}}class QL{constructor(e,t){this.payload=e,this.byteLength=t}yo(){return"metadata"in this.payload}}class YL{constructor(e){this.O=e}Yn(e){return _O(this.O,e)}Xn(e){return e.metadata.exists?kO(this.O,e.document,!1):RP.newNoDocument(this.Yn(e.metadata.name),this.Zn(e.metadata.readTime))}Zn(e){return gO(e)}}class XL{constructor(e,t,n){this.po=e,this.localStore=t,this.O=n,this.queries=[],this.documents=[],this.progress=JL(e)}To(e){this.progress.bytesLoaded+=e.byteLength;let t=this.progress.documentsLoaded;return e.payload.namedQuery?this.queries.push(e.payload.namedQuery):e.payload.documentMetadata?(this.documents.push({metadata:e.payload.documentMetadata}),e.payload.documentMetadata.exists||++t):e.payload.document&&(this.documents[this.documents.length-1].document=e.payload.document,++t),t!==this.progress.documentsLoaded?(this.progress.documentsLoaded=t,Object.assign({},this.progress)):null}Eo(e){const t=new Map,n=new YL(this.O);for(const i of e)if(i.metadata.queries){const e=n.Yn(i.metadata.name);for(const n of i.metadata.queries){var r=(t.get(n)||Zx()).add(e);t.set(n,r)}}return t}async complete(){const e=await async function(e,t,n,r){const i=e;let s=Zx(),o=Qx;for(const e of n){const n=t.Yn(e.metadata.name);e.document&&(s=s.add(n));const l=t.Xn(e);l.setReadTime(t.Zn(e.metadata.readTime)),o=o.insert(n,l)}const a=i.Gn.newChangeBuffer({trackRemovals:!0}),c=await O1(i,(r=r,sx(JP(ZR.fromString(`__bundle__/docs/${r}`)))));return i.persistence.runTransaction("Apply bundle documents","readwrite",t=>x1(t,a,o).next(e=>(a.apply(t),e)).next(e=>i.Ye.removeMatchingKeysForTargetId(t,c.targetId).next(()=>i.Ye.addMatchingKeys(t,s,c.targetId)).next(()=>i.zn.Dn(t,e)).next(()=>e)))}(this.localStore,new YL(this.O),this.documents,this.po.id),t=this.Eo(this.documents);for(const e of this.queries)await async function(e,n,r=Zx()){const i=await O1(e,sx(DD(n.bundledQuery))),s=e;return s.persistence.runTransaction("Save named query","readwrite",e=>{var t=gO(n.readTime);if(0<=i.snapshotVersion.compareTo(t))return s.Ze.saveNamedQuery(e,n);t=i.withResumeToken(rP.EMPTY_BYTE_STRING,t);return s.jn=s.jn.insert(t.targetId,t),s.Ye.updateTargetData(e,t).next(()=>s.Ye.removeMatchingKeysForTargetId(e,i.targetId)).next(()=>s.Ye.addMatchingKeys(e,r,i.targetId)).next(()=>s.Ze.saveNamedQuery(e,n))})}(this.localStore,e,t.get(e.name));return this.progress.taskState="Success",new T1(Object.assign({},this.progress),e)}}function JL(e){return{taskState:"Running",documentsLoaded:0,bytesLoaded:0,totalDocuments:e.totalDocuments,totalBytes:e.totalBytes}}class ZL{constructor(e){this.key=e}}class eM{constructor(e){this.key=e}}class tM{constructor(e,t){this.query=e,this.Io=t,this.Ao=null,this.current=!1,this.Ro=Zx(),this.mutatedKeys=Zx(),this.bo=hx(e),this.Po=new qL(this.bo)}get vo(){return this.Io}Vo(e,t){const a=t?t.So:new VL,c=(t||this).Po;let l=(t||this).mutatedKeys,u=c,h=!1;const d=ZP(this.query)&&c.size===this.query.limit?c.last():null,p=ex(this.query)&&c.size===this.query.limit?c.first():null;if(e.inorderTraversal((e,t)=>{const n=c.get(e),r=ux(this.query,t)?t:null,i=!!n&&this.mutatedKeys.has(n.key),s=!!r&&(r.hasLocalMutations||this.mutatedKeys.has(r.key)&&r.hasCommittedMutations);let o=!1;n&&r?n.data.isEqual(r.data)?i!==s&&(a.track({type:3,doc:r}),o=!0):this.Do(n,r)||(a.track({type:2,doc:r}),o=!0,(d&&0<this.bo(r,d)||p&&this.bo(r,p)<0)&&(h=!0)):!n&&r?(a.track({type:0,doc:r}),o=!0):n&&!r&&(a.track({type:1,doc:n}),o=!0,(d||p)&&(h=!0)),o&&(l=r?(u=u.add(r),s?l.add(e):l.delete(e)):(u=u.delete(e),l.delete(e)))}),ZP(this.query)||ex(this.query))for(;u.size>this.query.limit;){const e=ZP(this.query)?u.last():u.first();u=u.delete(e.key),l=l.delete(e.key),a.track({type:1,doc:e})}return{Po:u,So:a,qn:h,mutatedKeys:l}}Do(e,t){return e.hasLocalMutations&&t.hasCommittedMutations&&!t.hasLocalMutations}applyChanges(e,t,n){var r=this.Po;this.Po=e.Po,this.mutatedKeys=e.mutatedKeys;const i=e.So.io();i.sort((e,t)=>function(e,t){var n=e=>{switch(e){case 0:return 1;case 2:case 3:return 2;case 1:return 0;default:return NR()}};return n(e)-n(t)}(e.type,t.type)||this.bo(e.doc,t.doc)),this.Co(n);var s=t?this.No():[],o=0===this.Ro.size&&this.current?1:0,a=o!==this.Ao;return this.Ao=o,0!==i.length||a?{snapshot:new BL(this.query,e.Po,r,i,e.mutatedKeys,0==o,a,!1),ko:s}:{ko:s}}co(e){return this.current&&"Offline"===e?(this.current=!1,this.applyChanges({Po:this.Po,So:new VL,mutatedKeys:this.mutatedKeys,qn:!1},!1)):{ko:[]}}xo(e){return!this.Io.has(e)&&!!this.Po.has(e)&&!this.Po.get(e).hasLocalMutations}Co(e){e&&(e.addedDocuments.forEach(e=>this.Io=this.Io.add(e)),e.modifiedDocuments.forEach(e=>{}),e.removedDocuments.forEach(e=>this.Io=this.Io.delete(e)),this.current=e.current)}No(){if(!this.current)return[];const t=this.Ro;this.Ro=Zx(),this.Po.forEach(e=>{this.xo(e.key)&&(this.Ro=this.Ro.add(e.key))});const n=[];return t.forEach(e=>{this.Ro.has(e)||n.push(new eM(e))}),this.Ro.forEach(e=>{t.has(e)||n.push(new ZL(e))}),n}$o(e){this.Io=e.Jn,this.Ro=Zx();var t=this.Vo(e.documents);return this.applyChanges(t,!0)}Oo(){return BL.fromInitialDocuments(this.query,this.Po,this.mutatedKeys,0===this.Ao)}}class nM{constructor(e,t,n){this.query=e,this.targetId=t,this.view=n}}class rM{constructor(e){this.key=e,this.Mo=!1}}class iM{constructor(e,t,n,r,i,s){this.localStore=e,this.remoteStore=t,this.eventManager=n,this.sharedClientState=r,this.currentUser=i,this.maxConcurrentLimboResolutions=s,this.Fo={},this.Lo=new l1(e=>cx(e),ax),this.Bo=new Map,this.Uo=new Set,this.qo=new zx(gP.comparator),this.Ko=new Map,this.jo=new j1,this.Qo={},this.Wo=new Map,this.Go=XD.ce(),this.onlineState="Unknown",this.zo=void 0}get isPrimaryClient(){return!0===this.zo}}async function sM(n,e,t,r){n.Ho=(e,s,t)=>async function(e,t,n){let r=t.view.Vo(s);r.qn&&(r=await L1(e.localStore,t.query,!1).then(({documents:e})=>t.view.Vo(e,r)));var i=n&&n.targetChanges.get(t.targetId),i=t.view.applyChanges(r,e.isPrimaryClient,i);return fM(e,t.targetId,i.ko),i.snapshot}(n,e,t);const i=await L1(n.localStore,e,!0),s=new tM(e,i.Jn),o=s.Vo(i.documents),a=nO.createSynthesizedTargetChangeForCurrentChange(t,r&&"Offline"!==n.onlineState),c=s.applyChanges(o,n.isPrimaryClient,a);fM(n,t,c.ko);var l=new nM(e,t,s);return n.Lo.set(e,l),n.Bo.has(t)?n.Bo.get(t).push(e):n.Bo.set(t,[e]),c.snapshot}async function oM(e,t,n){const r=bM(e);try{const e=await function(e,r){const i=e,s=HR.now(),t=r.reduce((e,t)=>e.add(t.key),Zx());let o;return i.persistence.runTransaction("Locally write mutations","readwrite",n=>i.zn.Sn(n,t).next(e=>{o=e;const t=[];for(const n of r){const r=function(e,t){let n=null;for(const r of e.fieldTransforms){const e=t.data.field(r.field),i=mx(r.transform,e||null);null!=i&&(null==n&&(n=NP.empty()),n.set(r.field,i))}return n||null}(n,o.get(n.key));null!=r&&t.push(new Lx(n.key,r,function r(e){const i=[];return YR(e.fields,(e,t)=>{const n=new tP([e]);if(CP(t)){const e=r(t.mapValue).fields;if(0===e.length)i.push(n);else for(const t of e)i.push(n.child(t))}else i.push(n)}),new nP(i)}(r.value.mapValue),Cx.exists(!0)))}return i.bn.addMutationBatch(n,s,t,r)})).then(e=>(e.applyToLocalDocumentSet(o),{batchId:e.batchId,changes:o}))}(r.localStore,t);r.sharedClientState.addPendingMutation(e.batchId),function(e,t,n){let r=e.Qo[e.currentUser.toKey()];r=r||new zx(zR),r=r.insert(t,n),e.Qo[e.currentUser.toKey()]=r}(r,e.batchId,n),await mM(r,e.changes),await PL(r.remoteStore)}catch(e){const t=jL(e,"Failed to persist write");n.reject(t)}}async function aM(e,t){const r=e;try{const e=await P1(r.localStore,t);t.targetChanges.forEach((e,t)=>{const n=r.Ko.get(t);n&&(RR(e.addedDocuments.size+e.modifiedDocuments.size+e.removedDocuments.size<=1),0<e.addedDocuments.size?n.Mo=!0:0<e.modifiedDocuments.size?RR(n.Mo):0<e.removedDocuments.size&&(RR(n.Mo),n.Mo=!1))}),await mM(r,e,t)}catch(e){await n1(e)}}function cM(r,i,e){const t=r;if(t.isPrimaryClient&&0===e||!t.isPrimaryClient&&1===e){const r=[];t.Lo.forEach((e,t)=>{var n=t.view.co(i);n.snapshot&&r.push(n.snapshot)}),function(e,n){const t=e;t.onlineState=n;let r=!1;t.queries.forEach((e,t)=>{for(const e of t.listeners)e.co(n)&&(r=!0)}),r&&HL(t)}(t.eventManager,i),r.length&&t.Fo.vr(r),t.onlineState=i,t.isPrimaryClient&&t.sharedClientState.setOnlineState(i)}}async function lM(e,t){const n=e,r=t.batch.batchId;try{const e=await function(e,r){const i=e;return i.persistence.runTransaction("Acknowledge batch","readwrite-primary",e=>{const t=r.batch.keys(),n=i.Gn.newChangeBuffer({trackRemovals:!0});return function(e,t,r,i){const s=r.batch,n=s.keys();let o=lD.resolve();return n.forEach(n=>{o=o.next(()=>i.getEntry(t,n)).next(e=>{var t=r.docVersions.get(n);RR(null!==t),e.version.compareTo(t)<0&&(s.applyToRemoteDocument(e,r),e.isValidDocument()&&(e.setReadTime(r.commitVersion),i.addEntry(e)))})}),o.next(()=>e.bn.removeMutationBatch(t,s))}(i,e,r,n).next(()=>n.apply(e)).next(()=>i.bn.performConsistencyCheck(e)).next(()=>i.zn.Sn(e,t))})}(n.localStore,t);hM(n,r,null),uM(n,r),n.sharedClientState.updateMutationState(r,"acknowledged"),await mM(n,e)}catch(e){await n1(e)}}function uM(e,t){(e.Wo.get(t)||[]).forEach(e=>{e.resolve()}),e.Wo.delete(t)}function hM(e,t,n){const r=e;let i=r.Qo[r.currentUser.toKey()];if(i){const e=i.get(t);e&&(n?e.reject(n):e.resolve(),i=i.remove(t)),r.Qo[r.currentUser.toKey()]=i}}function dM(t,e,n=null){t.sharedClientState.removeLocalQueryTarget(e);for(const r of t.Bo.get(e))t.Lo.delete(r),n&&t.Fo.Jo(r,n);t.Bo.delete(e),t.isPrimaryClient&&t.jo.ls(e).forEach(e=>{t.jo.containsKey(e)||pM(t,e)})}function pM(e,t){e.Uo.delete(t.path.canonicalString());var n=e.qo.get(t);null!==n&&(IL(e.remoteStore,n),e.qo=e.qo.remove(t),e.Ko.delete(n),gM(e))}function fM(e,t,n){for(const r of n)r instanceof ZL?(e.jo.addReference(r.key,t),function(e,t){const n=t.key,r=n.path.canonicalString();e.qo.get(n)||e.Uo.has(r)||(kR("SyncEngine","New document in limbo: "+n),e.Uo.add(r),gM(e))}(e,r)):r instanceof eM?(kR("SyncEngine","Document no longer in limbo: "+r.key),e.jo.removeReference(r.key,t),e.jo.containsKey(r.key)||pM(e,r.key)):NR()}function gM(e){for(;0<e.Uo.size&&e.qo.size<e.maxConcurrentLimboResolutions;){var t=e.Uo.values().next().value;e.Uo.delete(t);var n=new gP(ZR.fromString(t)),t=e.Go.next();e.Ko.set(t,new rM(n)),e.qo=e.qo.insert(n,t),bL(e.remoteStore,new TD(sx(JP(n.path)),t,2,BR.I))}}async function mM(e,t,r){const i=e,s=[],o=[],a=[];i.Lo.isEmpty()||(i.Lo.forEach((e,n)=>{a.push(i.Ho(n,t,r).then(e=>{var t;e&&(i.isPrimaryClient&&i.sharedClientState.updateQueryState(n.targetId,e.fromCache?"not-current":"current"),s.push(e),t=k1.Mn(n.targetId,e),o.push(t))}))}),await Promise.all(a),i.Fo.vr(s),await async function(e,t){const r=e;try{await r.persistence.runTransaction("notifyLocalViewChanges","readwrite",n=>lD.forEach(t,t=>lD.forEach(t.$n,e=>r.persistence.referenceDelegate.addReference(n,t.targetId,e)).next(()=>lD.forEach(t.On,e=>r.persistence.referenceDelegate.removeReference(n,t.targetId,e)))))}catch(e){if(!fD(e))throw e;kR("LocalStore","Failed to update sequence numbers: "+e)}for(const e of t){const t=e.targetId;if(!e.fromCache){const e=r.jn.get(t),n=e.snapshotVersion,i=e.withLastLimboFreeSnapshotVersion(n);r.jn=r.jn.insert(t,i)}}}(i.localStore,o))}async function vM(r,e){const i=r;if(wM(i),bM(i),!0===e&&!0!==i.zo){const r=i.sharedClientState.getAllActiveQueryTargets(),e=await yM(i,r.toArray());i.zo=!0,await LL(i.remoteStore,!0);for(const r of e)bL(i.remoteStore,r)}else if(!1===e&&!1!==i.zo){const r=[];let n=Promise.resolve();i.Bo.forEach((e,t)=>{i.sharedClientState.isLocalQueryTarget(t)?r.push(t):n=n.then(()=>(dM(i,t),D1(i.localStore,t,!0))),IL(i.remoteStore,t)}),await n,await yM(i,r),function(){const n=i;n.Ko.forEach((e,t)=>{IL(n.remoteStore,t)}),n.jo.fs(),n.Ko=new Map,n.qo=new zx(gP.comparator)}(),i.zo=!1,await LL(i.remoteStore,!1)}}async function yM(t,n){const r=t,i=[],s=[];for(const t of n){let e;const u=r.Bo.get(t);if(u&&0!==u.length){e=await O1(r.localStore,sx(u[0]));for(const t of u){const n=r.Lo.get(t),u=(o=r,a=n,l=c=void 0,l=await L1((c=o).localStore,a.query,!0),l=a.view.$o(l),c.isPrimaryClient&&fM(c,a.targetId,l.ko),await l);u.snapshot&&s.push(u.snapshot)}}else{const u=await M1(r.localStore,t);e=await O1(r.localStore,u),await sM(r,_M(u),t,!1)}i.push(e)}var o,a,c,l;return r.Fo.vr(s),i}function _M(e){return XP(e.path,e.collectionGroup,e.orderBy,e.filters,e.limit,"F",e.startAt,e.endAt)}function wM(e){const t=e;return t.remoteStore.remoteSyncer.applyRemoteEvent=aM.bind(null,t),t.remoteStore.remoteSyncer.getRemoteKeysForTarget=(function(e,t){const n=e,r=n.Ko.get(t);if(r&&r.Mo)return Zx().add(r.key);{let e=Zx();const r=n.Bo.get(t);if(!r)return e;for(const t of r){const r=n.Lo.get(t);e=e.unionWith(r.view.vo)}return e}}).bind(null,t),t.remoteStore.remoteSyncer.rejectListen=(async function(e,t,n){const r=e;r.sharedClientState.updateQueryState(t,"rejected",n);const i=r.Ko.get(t),s=i&&i.key;if(s){let e=new zx(gP.comparator);e=e.insert(s,RP.newNoDocument(s,GR.min()));const n=Zx().add(s),i=new tO(GR.min(),new Map,new Hx(zR),e,n);await aM(r,i),r.qo=r.qo.remove(s),r.Ko.delete(t),gM(r)}else await D1(r.localStore,t,!1).then(()=>dM(r,t,n)).catch(n1)}).bind(null,t),t.Fo.vr=(function(e,t){const n=e;let r=!1;for(const e of t){const t=e.query,i=n.queries.get(t);if(i){for(const t of i.listeners)t.ao(e)&&(r=!0);i.ro=e}}r&&HL(n)}).bind(null,t.eventManager),t.Fo.Jo=(function(e,t,n){const r=e,i=r.queries.get(t);if(i)for(const e of i.listeners)e.onError(n);r.queries.delete(t)}).bind(null,t.eventManager),t}function bM(e){const t=e;return t.remoteStore.remoteSyncer.applySuccessfulWrite=lM.bind(null,t),t.remoteStore.remoteSyncer.rejectFailedWrite=(async function(e,t,n){const r=e;try{const e=await function(e,r){const i=e;return i.persistence.runTransaction("Reject batch","readwrite-primary",t=>{let n;return i.bn.lookupMutationBatch(t,r).next(e=>(RR(null!==e),n=e.keys(),i.bn.removeMutationBatch(t,e))).next(()=>i.bn.performConsistencyCheck(t)).next(()=>i.zn.Sn(t,n))})}(r.localStore,t);hM(r,t,n),uM(r,t),r.sharedClientState.updateMutationState(t,"rejected",n),await mM(r,e)}catch(n){await n1(n)}}).bind(null,t),t}class IM{constructor(){this.synchronizeTabs=!1}async initialize(e){this.O=hL(e.databaseInfo.databaseId),this.sharedClientState=this.Xo(e),this.persistence=this.Zo(e),await this.persistence.start(),this.gcScheduler=this.tc(e),this.localStore=this.ec(e)}tc(e){return null}ec(e){return A1(this.persistence,new S1,e.initialUser,this.O)}Zo(e){return new K1(H1.$s,this.O)}Xo(e){return new rL}async terminate(){this.gcScheduler&&this.gcScheduler.stop(),await this.sharedClientState.shutdown(),await this.persistence.shutdown()}}class TM extends IM{constructor(e,t,n){super(),this.nc=e,this.cacheSizeBytes=t,this.forceOwnership=n,this.synchronizeTabs=!1}async initialize(e){await super.initialize(e),await async function(e){const t=e;return t.persistence.runTransaction("Synchronize last document change read time","readonly",t=>function(){const e=f1(t);let r=GR.min();return e.Wt({index:GO.readTimeIndex,reverse:!0},(e,t,n)=>{t.readTime&&(r=AD(t.readTime)),n.done()}).next(()=>r)}()).then(e=>{t.Wn=e})}(this.localStore),await this.nc.initialize(this,e),await bM(this.nc.syncEngine),await PL(this.nc.remoteStore),await this.persistence.on(()=>(this.gcScheduler&&!this.gcScheduler.started&&this.gcScheduler.start(this.localStore),Promise.resolve()))}ec(e){return A1(this.persistence,new S1,e.initialUser,this.O)}tc(e){var t=this.persistence.referenceDelegate.garbageCollector;return new s1(t,e.asyncQueue)}Zo(e){var t=I1(e.databaseInfo.databaseId,e.databaseInfo.persistenceKey),n=void 0!==this.cacheSizeBytes?WD.withCacheSize(this.cacheSizeBytes):WD.DEFAULT;return new _1(this.synchronizeTabs,t,e.clientId,n,e.asyncQueue,lL(),uL(),this.O,this.sharedClientState,!!this.forceOwnership)}Xo(e){return new rL}}class EM extends TM{constructor(e,t){super(e,t,!1),this.nc=e,this.cacheSizeBytes=t,this.synchronizeTabs=!0}async initialize(e){await super.initialize(e);var t=this.nc.syncEngine;this.sharedClientState instanceof nL&&(this.sharedClientState.syncEngine={yi:(async function(e,t,n,r){var i=e,s=await function(e,n){const r=e,i=r.bn;return r.persistence.runTransaction("Lookup mutation documents","readonly",t=>i.ee(t,n).next(e=>e?r.zn.Sn(t,e):lD.resolve(null)))}(i.localStore,t);null!==s?("pending"===n?await PL(i.remoteStore):"acknowledged"===n||"rejected"===n?(hM(i,t,r||null),uM(i,t),i.localStore.bn.se(t)):NR(),await mM(i,s)):kR("SyncEngine","Cannot apply mutation batch with id: "+t)}).bind(null,t),pi:(async function(e,t,n,r){const i=e;if(i.zo)kR("SyncEngine","Ignoring unexpected query state notification.");else if(i.Bo.has(t))switch(n){case"current":case"not-current":{const e=await F1(i.localStore),r=tO.createSynthesizedRemoteEventForCurrentChange(t,"current"===n);await mM(i,e,r);break}case"rejected":await D1(i.localStore,t,!0),dM(i,t,r);break;default:NR()}}).bind(null,t),Ti:(async function(e,t,n){const r=wM(e);if(r.zo){for(const e of t)if(r.Bo.has(e))kR("SyncEngine","Adding an already active target "+e);else{const t=await M1(r.localStore,e),n=await O1(r.localStore,t);await sM(r,_M(t),n.targetId,!1),bL(r.remoteStore,n)}for(const e of n)r.Bo.has(e)&&await D1(r.localStore,e,!1).then(()=>{IL(r.remoteStore,e),dM(r,e)}).catch(n1)}}).bind(null,t),In:(function(e){return e.localStore.persistence.In()}).bind(null,t),gi:(async function(e){const t=e;return F1(t.localStore).then(e=>mM(t,e))}).bind(null,t)},await this.sharedClientState.start()),await this.persistence.on(async e=>{await vM(this.nc.syncEngine,e),this.gcScheduler&&(e&&!this.gcScheduler.started?this.gcScheduler.start(this.localStore):e||this.gcScheduler.stop())})}Xo(e){var t=lL();if(!nL.Vt(t))throw new xR(PR.UNIMPLEMENTED,"IndexedDB persistence is only available on platforms that support LocalStorage.");var n=I1(e.databaseInfo.databaseId,e.databaseInfo.persistenceKey);return new nL(t,e.asyncQueue,n,e.clientId,e.initialUser)}}class kM{async initialize(e,t){this.localStore||(this.localStore=e.localStore,this.sharedClientState=e.sharedClientState,this.datastore=this.createDatastore(t),this.remoteStore=this.createRemoteStore(t),this.eventManager=this.createEventManager(t),this.syncEngine=this.createSyncEngine(t,!e.synchronizeTabs),this.sharedClientState.onlineStateHandler=e=>cM(this.syncEngine,e,1),this.remoteStore.remoteSyncer.handleCredentialChange=(async function(e,t){const n=e;if(!n.currentUser.isEqual(t)){kR("SyncEngine","User change. New user:",t.toKey());const r=await N1(n.localStore,t);n.currentUser=t,(e=n).Wo.forEach(e=>{e.forEach(e=>{e.reject(new xR(PR.CANCELLED,"'waitForPendingWrites' promise is rejected due to a user change."))})}),e.Wo.clear(),n.sharedClientState.handleUserChange(t,r.removedBatchIds,r.addedBatchIds),await mM(n,r.Hn)}}).bind(null,this.syncEngine),await LL(this.remoteStore,this.syncEngine.isPrimaryClient))}createEventManager(e){return new zL}createDatastore(e){var t,n,r,i,s=hL(e.databaseInfo.databaseId),t=(t=e.databaseInfo,new cL(t));return n=e.authCredentials,r=e.appCheckCredentials,i=t,e=s,new mL(n,r,i,e)}createRemoteStore(e){return t=this.localStore,n=this.datastore,r=e.asyncQueue,i=e=>cM(this.syncEngine,e,0),s=new(sL.Vt()?sL:iL),new yL(t,n,r,i,s);var t,n,r,i,s}createSyncEngine(e,t){return function(e,t,n,r,i,s,o){const a=new iM(e,t,n,r,i,s);return o&&(a.zo=!0),a}(this.localStore,this.remoteStore,this.eventManager,this.sharedClientState,e.initialUser,e.maxConcurrentLimboResolutions,t)}terminate(){return async function(e){const t=e;kR("RemoteStore","RemoteStore shutting down."),t.Hr.add(5),await wL(t),t.Yr.shutdown(),t.Xr.set("Unknown")}(this.remoteStore)}}function SM(t,n=10240){let r=0;return{async read(){if(r<t.byteLength){var e={value:t.slice(r,r+n),done:!1};return r+=n,e}return{done:!0}},async cancel(){},releaseLock(){},closed:Promise.reject("unimplemented")}}class CM{constructor(e){this.observer=e,this.muted=!1}next(e){this.observer.next&&this.sc(this.observer.next,e)}error(e){this.observer.error?this.sc(this.observer.error,e):console.error("Uncaught Error in snapshot listener:",e)}ic(){this.muted=!0}sc(e,t){this.muted||setTimeout(()=>{this.muted||e(t)},0)}}class AM{constructor(e,t){this.rc=e,this.O=t,this.metadata=new OR,this.buffer=new Uint8Array,this.oc=new TextDecoder("utf-8"),this.cc().then(e=>{e&&e.yo()?this.metadata.resolve(e.payload.metadata):this.metadata.reject(new Error(`The first element of the bundle is not a metadata, it is\n             ${JSON.stringify(null==e?void 0:e.payload)}`))},e=>this.metadata.reject(e))}close(){return this.rc.cancel()}async getMetadata(){return this.metadata.promise}async Yo(){return await this.getMetadata(),this.cc()}async cc(){var e=await this.ac();if(null===e)return null;var t=this.oc.decode(e),n=Number(t);isNaN(n)&&this.uc(`length string (${t}) is not valid number`);t=await this.hc(n);return new QL(JSON.parse(t),e.length+n)}lc(){return this.buffer.findIndex(e=>e==="{".charCodeAt(0))}async ac(){for(;this.lc()<0&&!await this.fc(););if(0===this.buffer.length)return null;var e=this.lc();e<0&&this.uc("Reached the end of bundle when a length string is expected.");var t=this.buffer.slice(0,e);return this.buffer=this.buffer.slice(e),t}async hc(e){for(;this.buffer.length<e;)await this.fc()&&this.uc("Reached the end of bundle when more is expected.");var t=this.oc.decode(this.buffer.slice(0,e));return this.buffer=this.buffer.slice(e),t}uc(e){throw this.rc.cancel(),new Error(`Invalid bundle format: ${e}`)}async fc(){var e=await this.rc.read();if(!e.done){const t=new Uint8Array(this.buffer.length+e.value.length);t.set(this.buffer),t.set(e.value,this.buffer.length),this.buffer=t}return e.done}}class NM{constructor(e){this.datastore=e,this.readVersions=new Map,this.mutations=[],this.committed=!1,this.lastWriteError=null,this.writtenDocs=new Set}async lookup(e){if(this.ensureCommitNotCalled(),0<this.mutations.length)throw new xR(PR.INVALID_ARGUMENT,"Firestore transactions require all reads to be executed before all writes.");const t=await async function(e,t){const r=e,n=IO(r.O)+"/documents",i={documents:t.map(e=>yO(r.O,e))},s=await r.Wi("BatchGetDocuments",n,i),o=new Map;s.forEach(e=>{const t=(n=r.O,"found"in(e=e)?function(e,t){RR(!!t.found),t.found.name,t.found.updateTime;var n=_O(e,t.found.name),r=gO(t.found.updateTime),i=new NP({mapValue:{fields:t.found.fields}});return RP.newFoundDocument(n,r,i)}(n,e):"missing"in e?function(e,t){RR(!!t.missing),RR(!!t.readTime);var n=_O(e,t.missing),r=gO(t.readTime);return RP.newNoDocument(n,r)}(n,e):NR());var n;o.set(t.key.toString(),t)});const a=[];return t.forEach(e=>{var t=o.get(e.toString());RR(!!t),a.push(t)}),a}(this.datastore,e);return t.forEach(e=>this.recordVersion(e)),t}set(e,t){this.write(t.toMutation(e,this.precondition(e))),this.writtenDocs.add(e.toString())}update(e,t){try{this.write(t.toMutation(e,this.preconditionForUpdate(e)))}catch(e){this.lastWriteError=e}this.writtenDocs.add(e.toString())}delete(e){this.write(new jx(e,this.precondition(e))),this.writtenDocs.add(e.toString())}async commit(){if(this.ensureCommitNotCalled(),this.lastWriteError)throw this.lastWriteError;const t=this.readVersions;this.mutations.forEach(e=>{t.delete(e.key.toString())}),t.forEach((e,t)=>{var n=gP.fromPath(t);this.mutations.push(new qx(n,this.precondition(n)))}),await async function(e,t){const n=e,r=IO(n.O)+"/documents",i={writes:t.map(e=>SO(n.O,e))};await n.qi("Commit",r,i)}(this.datastore,this.mutations),this.committed=!0}recordVersion(e){let t;if(e.isFoundDocument())t=e.version;else{if(!e.isNoDocument())throw NR();t=GR.min()}var n=this.readVersions.get(e.key.toString());if(n){if(!t.isEqual(n))throw new xR(PR.ABORTED,"Document version changed between two reads.")}else this.readVersions.set(e.key.toString(),t)}precondition(e){var t=this.readVersions.get(e.toString());return!this.writtenDocs.has(e.toString())&&t?Cx.updateTime(t):Cx.none()}preconditionForUpdate(e){const t=this.readVersions.get(e.toString());if(this.writtenDocs.has(e.toString())||!t)return Cx.exists(!0);if(t.isEqual(GR.min()))throw new xR(PR.INVALID_ARGUMENT,"Can't update a document that doesn't exist.");return Cx.updateTime(t)}write(e){this.ensureCommitNotCalled(),this.mutations.push(e)}ensureCommitNotCalled(){}}class RM{constructor(e,t,n,r){this.asyncQueue=e,this.datastore=t,this.updateFunction=n,this.deferred=r,this.dc=5,this.lr=new dL(this.asyncQueue,"transaction_retry")}run(){--this.dc,this.wc()}wc(){this.lr.er(async()=>{const t=new NM(this.datastore),e=this._c(t);e&&e.then(e=>{this.asyncQueue.enqueueAndForget(()=>t.commit().then(()=>{this.deferred.resolve(e)}).catch(e=>{this.mc(e)}))}).catch(e=>{this.mc(e)})})}_c(e){try{var t=this.updateFunction(e);return!dP(t)&&t.catch&&t.then?t:(this.deferred.reject(Error("Transaction callback must return a Promise")),null)}catch(e){return this.deferred.reject(e),null}}mc(e){0<this.dc&&this.gc(e)?(--this.dc,this.asyncQueue.enqueueAndForget(()=>(this.wc(),Promise.resolve()))):this.deferred.reject(e)}gc(e){if("FirebaseError"!==e.name)return!1;var t=e.code;return"aborted"===t||"failed-precondition"===t||!Bx(t)}}class PM{constructor(e,t,n,r){this.authCredentials=e,this.appCheckCredentials=t,this.asyncQueue=n,this.databaseInfo=r,this.user=bR.UNAUTHENTICATED,this.clientId=WR.A(),this.authCredentialListener=()=>Promise.resolve(),this.appCheckCredentialListener=()=>Promise.resolve(),this.authCredentials.start(n,async e=>{kR("FirestoreClient","Received user=",e.uid),await this.authCredentialListener(e),this.user=e}),this.appCheckCredentials.start(n,e=>(kR("FirestoreClient","Received new app check token=",e),this.appCheckCredentialListener(e,this.user)))}async getConfiguration(){return{asyncQueue:this.asyncQueue,databaseInfo:this.databaseInfo,clientId:this.clientId,authCredentials:this.authCredentials,appCheckCredentials:this.appCheckCredentials,initialUser:this.user,maxConcurrentLimboResolutions:100}}setCredentialChangeListener(e){this.authCredentialListener=e}setAppCheckTokenChangeListener(e){this.appCheckCredentialListener=e}verifyNotTerminated(){if(this.asyncQueue.isShuttingDown)throw new xR(PR.FAILED_PRECONDITION,"The client has already been terminated.")}terminate(){this.asyncQueue.enterRestrictedMode();const n=new OR;return this.asyncQueue.enqueueAndForgetEvenWhileRestricted(async()=>{try{this.onlineComponents&&await this.onlineComponents.terminate(),this.offlineComponents&&await this.offlineComponents.terminate(),this.authCredentials.shutdown(),this.appCheckCredentials.shutdown(),n.resolve()}catch(e){var t=jL(e,"Failed to shutdown persistence");n.reject(t)}}),n.promise}}async function xM(e,t){e.asyncQueue.verifyOperationInProgress(),kR("FirestoreClient","Initializing OfflineComponentProvider");var n=await e.getConfiguration();await t.initialize(n);let r=n.initialUser;e.setCredentialChangeListener(async e=>{r.isEqual(e)||(await N1(t.localStore,e),r=e)}),t.persistence.setDatabaseDeletedListener(()=>e.terminate()),e.offlineComponents=t}async function OM(e,n){e.asyncQueue.verifyOperationInProgress();var t=await DM(e);kR("FirestoreClient","Initializing OnlineComponentProvider");var r=await e.getConfiguration();await n.initialize(t,r),e.setCredentialChangeListener(e=>DL(n.remoteStore,e)),e.setAppCheckTokenChangeListener((e,t)=>DL(n.remoteStore,t)),e.onlineComponents=n}async function DM(e){return e.offlineComponents||(kR("FirestoreClient","Using default OfflineComponentProvider"),await xM(e,new IM)),e.offlineComponents}async function LM(e){return e.onlineComponents||(kR("FirestoreClient","Using default OnlineComponentProvider"),await OM(e,new kM)),e.onlineComponents}function MM(e){return DM(e).then(e=>e.persistence)}function FM(e){return DM(e).then(e=>e.localStore)}function UM(e){return LM(e).then(e=>e.remoteStore)}function jM(e){return LM(e).then(e=>e.syncEngine)}async function qM(e){const t=await LM(e),n=t.eventManager;return n.onListen=(async function(e,t){const n=wM(e);let r,i;const s=n.Lo.get(t);if(s)r=s.targetId,n.sharedClientState.addLocalQueryTarget(r),i=s.view.Oo();else{const e=await O1(n.localStore,sx(t)),s=n.sharedClientState.addLocalQueryTarget(e.targetId);r=e.targetId,i=await sM(n,t,r,"current"===s),n.isPrimaryClient&&bL(n.remoteStore,e)}return i}).bind(null,t.syncEngine),n.onUnlisten=(async function(e,t){const n=e,r=n.Lo.get(t),i=n.Bo.get(r.targetId);if(1<i.length)return n.Bo.set(r.targetId,i.filter(e=>!ax(e,t))),void n.Lo.delete(t);n.isPrimaryClient?(n.sharedClientState.removeLocalQueryTarget(r.targetId),n.sharedClientState.isActiveQueryTarget(r.targetId)||await D1(n.localStore,r.targetId,!1).then(()=>{n.sharedClientState.clearQueryState(r.targetId),IL(n.remoteStore,r.targetId),dM(n,r.targetId)}).catch(n1)):(dM(n,r.targetId),await D1(n.localStore,r.targetId,!0))}).bind(null,t.syncEngine),n}function VM(e,t,n={}){const r=new OR;return e.asyncQueue.enqueueAndForget(async()=>function(n,r,i,s,o){const e=new CM({next:e=>{r.enqueueAndForget(()=>$L(n,a));var t=e.docs.has(i);!t&&e.fromCache?o.reject(new xR(PR.UNAVAILABLE,"Failed to get document because the client is offline.")):t&&e.fromCache&&s&&"server"===s.source?o.reject(new xR(PR.UNAVAILABLE,'Failed to get document from server. (However, this document does exist in the local cache. Run again without setting source to "server" to retrieve the cached document.)')):o.resolve(e)},error:e=>o.reject(e)}),a=new GL(JP(i.path),e,{includeMetadataChanges:!0,mo:!0});return KL(n,a)}(await qM(e),e.asyncQueue,t,n,r)),r.promise}function BM(e,t,n={}){const r=new OR;return e.asyncQueue.enqueueAndForget(async()=>function(t,n,e,r,i){const s=new CM({next:e=>{n.enqueueAndForget(()=>$L(t,o)),e.fromCache&&"server"===r.source?i.reject(new xR(PR.UNAVAILABLE,'Failed to get documents from server. (However, these documents may exist in the local cache. Run again without setting source to "server" to retrieve the cached documents.)')):i.resolve(e)},error:e=>i.reject(e)}),o=new GL(e,s,{includeMetadataChanges:!0,mo:!0});return KL(t,o)}(await qM(e),e.asyncQueue,t,n,r)),r.promise}function WM(e,t,n,r){const i=(n=n,t=hL(t),s="string"==typeof n?(new TextEncoder).encode(n):n,n=function(e){if(e instanceof Uint8Array)return SM(e,void 0);if(e instanceof ArrayBuffer)return SM(new Uint8Array(e),void 0);if(e instanceof ReadableStream)return e.getReader();throw new Error("Source of `toByteStreamReader` has to be a ArrayBuffer or ReadableStream")}(s),t=t,new AM(n,t));var s;e.asyncQueue.enqueueAndForget(async()=>{!function(e,t,n){const r=e;!async function(t,n,r){try{var i=await n.getMetadata();if(await function(e,t){const n=e,r=gO(t.createTime);return n.persistence.runTransaction("hasNewerBundle","readonly",e=>n.Ze.getBundleMetadata(e,t.id)).then(e=>!!e&&0<=e.createTime.compareTo(r))}(t.localStore,i))return await n.close(),void r._completeWith({taskState:"Success",documentsLoaded:i.totalDocuments,bytesLoaded:i.totalBytes,totalDocuments:i.totalDocuments,totalBytes:i.totalBytes});r._updateProgress(JL(i));const o=new XL(i,t.localStore,n.O);let e=await n.Yo();for(;e;){const t=await o.To(e);t&&r._updateProgress(t),e=await n.Yo()}var s=await o.complete();await mM(t,s.Rn,void 0),await function(e,t){const n=e;return n.persistence.runTransaction("Save bundle","readwrite",e=>n.Ze.saveBundleMetadata(e,t))}(t.localStore,i),r._completeWith(s.progress)}catch(t){CR("SyncEngine",`Loading bundle failed with ${t}`),r._failWith(t)}}(r,t,n).then(()=>{r.sharedClientState.notifyBundleLoaded()})}(await jM(e),i,r)})}const zM=new Map;function KM(e,t,n){if(!n)throw new xR(PR.INVALID_ARGUMENT,`Function ${e}() cannot be called with an empty ${t}.`)}function $M(e,t,n,r){if(!0===t&&!0===r)throw new xR(PR.INVALID_ARGUMENT,`${e} and ${n} cannot be used together.`)}function HM(e){if(!gP.isDocumentKey(e))throw new xR(PR.INVALID_ARGUMENT,`Invalid document reference. Document references must have an even number of segments, but ${e} has ${e.length}.`)}function GM(e){if(gP.isDocumentKey(e))throw new xR(PR.INVALID_ARGUMENT,`Invalid collection reference. Collection references must have an odd number of segments, but ${e} has ${e.length}.`)}function QM(e){if(void 0===e)return"undefined";if(null===e)return"null";if("string"==typeof e)return 20<e.length&&(e=`${e.substring(0,20)}...`),JSON.stringify(e);if("number"==typeof e||"boolean"==typeof e)return""+e;if("object"!=typeof e)return"function"==typeof e?"a function":NR();if(e instanceof Array)return"an array";var t=(e=e).constructor?e.constructor.name:null;return t?`a custom ${t} object`:"an object"}function YM(e,t){if((e="_delegate"in e?e._delegate:e)instanceof t)return e;if(t.name===e.constructor.name)throw new xR(PR.INVALID_ARGUMENT,"Type does not match the expected instance. Did you pass a reference from a different Firestore SDK?");var n=QM(e);throw new xR(PR.INVALID_ARGUMENT,`Expected type '${t.name}', but it was: ${n}`)}function XM(e,t){if(t<=0)throw new xR(PR.INVALID_ARGUMENT,`Function ${e}() requires a positive number, but it was: ${t}.`)}class JM{constructor(e){var t;if(void 0===e.host){if(void 0!==e.ssl)throw new xR(PR.INVALID_ARGUMENT,"Can't provide ssl option if host option is not set");this.host="firestore.googleapis.com",this.ssl=!0}else this.host=e.host,this.ssl=null===(t=e.ssl)||void 0===t||t;if(this.credentials=e.credentials,this.ignoreUndefinedProperties=!!e.ignoreUndefinedProperties,void 0===e.cacheSizeBytes)this.cacheSizeBytes=41943040;else{if(-1!==e.cacheSizeBytes&&e.cacheSizeBytes<1048576)throw new xR(PR.INVALID_ARGUMENT,"cacheSizeBytes must be at least 1048576");this.cacheSizeBytes=e.cacheSizeBytes}this.experimentalForceLongPolling=!!e.experimentalForceLongPolling,this.experimentalAutoDetectLongPolling=!!e.experimentalAutoDetectLongPolling,this.useFetchStreams=!!e.useFetchStreams,$M("experimentalForceLongPolling",e.experimentalForceLongPolling,"experimentalAutoDetectLongPolling",e.experimentalAutoDetectLongPolling)}isEqual(e){return this.host===e.host&&this.ssl===e.ssl&&this.credentials===e.credentials&&this.cacheSizeBytes===e.cacheSizeBytes&&this.experimentalForceLongPolling===e.experimentalForceLongPolling&&this.experimentalAutoDetectLongPolling===e.experimentalAutoDetectLongPolling&&this.ignoreUndefinedProperties===e.ignoreUndefinedProperties&&this.useFetchStreams===e.useFetchStreams}}class ZM{constructor(e,t,n){this._authCredentials=t,this._appCheckCredentials=n,this.type="firestore-lite",this._persistenceKey="(lite)",this._settings=new JM({}),this._settingsFrozen=!1,e instanceof hP?this._databaseId=e:(this._app=e,this._databaseId=function(e){if(!Object.prototype.hasOwnProperty.apply(e.options,["projectId"]))throw new xR(PR.INVALID_ARGUMENT,'"projectId" not provided in firebase.initializeApp.');return new hP(e.options.projectId)}(e))}get app(){if(!this._app)throw new xR(PR.FAILED_PRECONDITION,"Firestore was not initialized using the Firebase SDK. 'app' is not available");return this._app}get _initialized(){return this._settingsFrozen}get _terminated(){return void 0!==this._terminateTask}_setSettings(e){if(this._settingsFrozen)throw new xR(PR.FAILED_PRECONDITION,"Firestore has already been started and its settings can no longer be changed. You can only modify settings before calling any other methods on a Firestore object.");this._settings=new JM(e),void 0!==e.credentials&&(this._authCredentials=function(e){if(!e)return new LR;switch(e.type){case"gapi":var t=e.client;return RR(!("object"!=typeof t||null===t||!t.auth||!t.auth.getAuthHeaderValueForFirstParty)),new jR(t,e.sessionIndex||"0",e.iamToken||null);case"provider":return e.client;default:throw new xR(PR.INVALID_ARGUMENT,"makeAuthCredentialsProvider failed due to invalid credential type")}}(e.credentials))}_getSettings(){return this._settings}_freezeSettings(){return this._settingsFrozen=!0,this._settings}_delete(){return this._terminateTask||(this._terminateTask=this._terminate()),this._terminateTask}toJSON(){return{app:this._app,databaseId:this._databaseId,settings:this._settings}}_terminate(){return function(e){const t=zM.get(e);t&&(kR("ComponentProvider","Removing Datastore"),zM.delete(e),t.terminate())}(this),Promise.resolve()}}class eF{constructor(e,t,n){this.converter=t,this._key=n,this.type="document",this.firestore=e}get _path(){return this._key.path}get id(){return this._key.path.lastSegment()}get path(){return this._key.path.canonicalString()}get parent(){return new nF(this.firestore,this.converter,this._key.path.popLast())}withConverter(e){return new eF(this.firestore,e,this._key)}}class tF{constructor(e,t,n){this.converter=t,this._query=n,this.type="query",this.firestore=e}withConverter(e){return new tF(this.firestore,e,this._query)}}class nF extends tF{constructor(e,t,n){super(e,t,JP(n)),this._path=n,this.type="collection"}get id(){return this._query.path.lastSegment()}get path(){return this._query.path.canonicalString()}get parent(){const e=this._path.popLast();return e.isEmpty()?null:new eF(this.firestore,null,new gP(e))}withConverter(e){return new nF(this.firestore,e,this._path)}}function rF(e,t,...n){if(e=zd(e),KM("collection","path",t),e instanceof ZM){var r=ZR.fromString(t,...n);return GM(r),new nF(e,null,r)}if(!(e instanceof eF||e instanceof nF))throw new xR(PR.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");r=e._path.child(ZR.fromString(t,...n));return GM(r),new nF(e.firestore,null,r)}function iF(e,t,...n){if(e=zd(e),KM("doc","path",t=1===arguments.length?WR.A():t),e instanceof ZM){var r=ZR.fromString(t,...n);return HM(r),new eF(e,null,new gP(r))}if(!(e instanceof eF||e instanceof nF))throw new xR(PR.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");r=e._path.child(ZR.fromString(t,...n));return HM(r),new eF(e.firestore,e instanceof nF?e.converter:null,new gP(r))}function sF(e,t){return e=zd(e),t=zd(t),(e instanceof eF||e instanceof nF)&&(t instanceof eF||t instanceof nF)&&e.firestore===t.firestore&&e.path===t.path&&e.converter===t.converter}function oF(e,t){return e=zd(e),t=zd(t),e instanceof tF&&t instanceof tF&&e.firestore===t.firestore&&ax(e._query,t._query)&&e.converter===t.converter}class aF{constructor(){this.yc=Promise.resolve(),this.Tc=[],this.Ec=!1,this.Ic=[],this.Ac=null,this.Rc=!1,this.bc=!1,this.Pc=[],this.lr=new dL(this,"async_queue_retry"),this.vc=()=>{var e=uL();e&&kR("AsyncQueue","Visibility state changed to "+e.visibilityState),this.lr.sr()};const e=uL();e&&"function"==typeof e.addEventListener&&e.addEventListener("visibilitychange",this.vc)}get isShuttingDown(){return this.Ec}enqueueAndForget(e){this.enqueue(e)}enqueueAndForgetEvenWhileRestricted(e){this.Vc(),this.Sc(e)}enterRestrictedMode(e){if(!this.Ec){this.Ec=!0,this.bc=e||!1;const t=uL();t&&"function"==typeof t.removeEventListener&&t.removeEventListener("visibilitychange",this.vc)}}enqueue(e){if(this.Vc(),this.Ec)return new Promise(()=>{});const t=new OR;return this.Sc(()=>this.Ec&&this.bc?Promise.resolve():(e().then(t.resolve,t.reject),t.promise)).then(()=>t.promise)}enqueueRetryable(e){this.enqueueAndForget(()=>(this.Tc.push(e),this.Dc()))}async Dc(){if(0!==this.Tc.length){try{await this.Tc[0](),this.Tc.shift(),this.lr.reset()}catch(e){if(!fD(e))throw e;kR("AsyncQueue","Operation failed with retryable error: "+e)}0<this.Tc.length&&this.lr.er(()=>this.Dc())}}Sc(e){var t=this.yc.then(()=>(this.Rc=!0,e().catch(e=>{throw this.Ac=e,this.Rc=!1,SR("INTERNAL UNHANDLED ERROR: ",function(e){let t=e.message||"";return e.stack&&(t=e.stack.includes(e.message)?e.stack:e.message+"\n"+e.stack),t}(e)),e}).then(e=>(this.Rc=!1,e))));return this.yc=t}enqueueAfterDelay(e,t,n){this.Vc(),-1<this.Pc.indexOf(e)&&(t=0);var r=UL.createAndSchedule(this,e,t,n,e=>this.Cc(e));return this.Ic.push(r),r}Vc(){this.Ac&&NR()}verifyOperationInProgress(){}async Nc(){for(var e;await(e=this.yc),e!==this.yc;);}kc(e){for(const t of this.Ic)if(t.timerId===e)return!0;return!1}xc(t){return this.Nc().then(()=>{this.Ic.sort((e,t)=>e.targetTimeMs-t.targetTimeMs);for(const e of this.Ic)if(e.skipDelay(),"all"!==t&&e.timerId===t)break;return this.Nc()})}$c(e){this.Pc.push(e)}Cc(e){var t=this.Ic.indexOf(e);this.Ic.splice(t,1)}}function cF(e){return function(e){if("object"==typeof e&&null!==e){var t=e;for(const e of["next","error","complete"])if(e in t&&"function"==typeof t[e])return 1}}(e)}class lF{constructor(){this._progressObserver={},this._taskCompletionResolver=new OR,this._lastProgress={taskState:"Running",totalBytes:0,totalDocuments:0,bytesLoaded:0,documentsLoaded:0}}onProgress(e,t,n){this._progressObserver={next:e,error:t,complete:n}}catch(e){return this._taskCompletionResolver.promise.catch(e)}then(e,t){return this._taskCompletionResolver.promise.then(e,t)}_completeWith(e){this._updateProgress(e),this._progressObserver.complete&&this._progressObserver.complete(),this._taskCompletionResolver.resolve(e)}_failWith(e){this._lastProgress.taskState="Error",this._progressObserver.next&&this._progressObserver.next(this._lastProgress),this._progressObserver.error&&this._progressObserver.error(e),this._taskCompletionResolver.reject(e)}_updateProgress(e){this._lastProgress=e,this._progressObserver.next&&this._progressObserver.next(e)}}var uF,hF,dF,pF;class fF extends ZM{constructor(e,t,n){super(e,t,n),this.type="firestore",this._queue=new aF,this._persistenceKey="name"in e?e.name:"[DEFAULT]"}_terminate(){return this._firestoreClient||mF(this),this._firestoreClient.terminate()}}function gF(e){return e._firestoreClient||mF(e),e._firestoreClient.verifyNotTerminated(),e._firestoreClient}function mF(e){var t,n,r,i,s,o=e._freezeSettings(),o=(n=e._databaseId,r=(null===(t=e._app)||void 0===t?void 0:t.options.appId)||"",i=e._persistenceKey,s=o,new uP(n,r,i,s.host,s.ssl,s.experimentalForceLongPolling,s.experimentalAutoDetectLongPolling,s.useFetchStreams));e._firestoreClient=new PM(e._authCredentials,e._appCheckCredentials,e._queue,o)}function vF(e,n,r){const i=new OR;return e.asyncQueue.enqueue(async()=>{try{await xM(e,r),await OM(e,n),i.resolve()}catch(e){if(!("FirebaseError"===(t=e).name?t.code===PR.FAILED_PRECONDITION||t.code===PR.UNIMPLEMENTED:!("undefined"!=typeof DOMException&&t instanceof DOMException)||(22===t.code||20===t.code||11===t.code)))throw e;console.warn("Error enabling offline persistence. Falling back to persistence disabled: "+e),i.reject(e)}var t}).then(()=>i.promise)}function yF(e){return function(e){const t=new OR;return e.asyncQueue.enqueueAndForget(async()=>async function(e,t){const n=e;CL(n.remoteStore)||kR("SyncEngine","The network is disabled. The task returned by 'awaitPendingWrites()' will not complete until the network is enabled.");try{const e=await function(){const t=n.localStore;return t.persistence.runTransaction("Get highest unacknowledged batch id","readonly",e=>t.bn.getHighestUnacknowledgedBatchId(e))}();if(-1===e)return void t.resolve();const r=n.Wo.get(e)||[];r.push(t),n.Wo.set(e,r)}catch(e){const n=jL(e,"Initialization of waitForPendingWrites() operation failed");t.reject(n)}}(await jM(e),t)),t.promise}(gF(e=YM(e,fF)))}function _F(e){return(n=gF(e=YM(e,fF))).asyncQueue.enqueue(async()=>{const e=await MM(n),t=await UM(n);return e.setNetworkEnabled(!0),function(){const e=t;return e.Hr.delete(0),_L(e)}()});var n}function wF(e){return(n=gF(e=YM(e,fF))).asyncQueue.enqueue(async()=>{const e=await MM(n),t=await UM(n);return e.setNetworkEnabled(!1),async function(){const e=t;e.Hr.add(0),await wL(e),e.Xr.set("Offline")}()});var n}function bF(t,e){return n=gF(t=YM(t,fF)),r=e,n.asyncQueue.enqueue(async()=>function(e,t){const n=e;return n.persistence.runTransaction("Get named query","readonly",e=>n.Ze.getNamedQuery(e,t))}(await FM(n),r)).then(e=>e?new tF(t,null,e.query):null);var n,r}function IF(e){if(e._initialized||e._terminated)throw new xR(PR.FAILED_PRECONDITION,"Firestore has already been started and persistence can no longer be enabled. You can only enable persistence before calling any other methods on a Firestore object.")}class TF{constructor(...e){for(let t=0;t<e.length;++t)if(0===e[t].length)throw new xR(PR.INVALID_ARGUMENT,"Invalid field name at argument $(i + 1). Field names must not be empty.");this._internalPath=new tP(e)}isEqual(e){return this._internalPath.isEqual(e._internalPath)}}class EF{constructor(e){this._byteString=e}static fromBase64String(e){try{return new EF(rP.fromBase64String(e))}catch(e){throw new xR(PR.INVALID_ARGUMENT,"Failed to construct data from Base64 string: "+e)}}static fromUint8Array(e){return new EF(rP.fromUint8Array(e))}toBase64(){return this._byteString.toBase64()}toUint8Array(){return this._byteString.toUint8Array()}toString(){return"Bytes(base64: "+this.toBase64()+")"}isEqual(e){return this._byteString.isEqual(e._byteString)}}class kF{constructor(e){this._methodName=e}}class SF{constructor(e,t){if(!isFinite(e)||e<-90||90<e)throw new xR(PR.INVALID_ARGUMENT,"Latitude must be a number between -90 and 90, but was: "+e);if(!isFinite(t)||t<-180||180<t)throw new xR(PR.INVALID_ARGUMENT,"Longitude must be a number between -180 and 180, but was: "+t);this._lat=e,this._long=t}get latitude(){return this._lat}get longitude(){return this._long}isEqual(e){return this._lat===e._lat&&this._long===e._long}toJSON(){return{latitude:this._lat,longitude:this._long}}_compareTo(e){return zR(this._lat,e._lat)||zR(this._long,e._long)}}const CF=/^__.*__$/;class AF{constructor(e,t,n){this.data=e,this.fieldMask=t,this.fieldTransforms=n}toMutation(e,t){return null!==this.fieldMask?new Lx(e,this.data,this.fieldMask,t,this.fieldTransforms):new Dx(e,this.data,t,this.fieldTransforms)}}class NF{constructor(e,t,n){this.data=e,this.fieldMask=t,this.fieldTransforms=n}toMutation(e,t){return new Lx(e,this.data,this.fieldMask,t,this.fieldTransforms)}}function RF(e){switch(e){case 0:case 2:case 1:return 1;case 3:case 4:return;default:throw NR()}}class PF{constructor(e,t,n,r,i,s){this.settings=e,this.databaseId=t,this.O=n,this.ignoreUndefinedProperties=r,void 0===i&&this.Oc(),this.fieldTransforms=i||[],this.fieldMask=s||[]}get path(){return this.settings.path}get Mc(){return this.settings.Mc}Fc(e){return new PF(Object.assign(Object.assign({},this.settings),e),this.databaseId,this.O,this.ignoreUndefinedProperties,this.fieldTransforms,this.fieldMask)}Lc(e){var t;const n=null===(t=this.path)||void 0===t?void 0:t.child(e),r=this.Fc({path:n,Bc:!1});return r.Uc(e),r}qc(e){var t;const n=null===(t=this.path)||void 0===t?void 0:t.child(e),r=this.Fc({path:n,Bc:!1});return r.Oc(),r}Kc(e){return this.Fc({path:void 0,Bc:!0})}jc(e){return XF(e,this.settings.methodName,this.settings.Qc||!1,this.path,this.settings.Wc)}contains(t){return void 0!==this.fieldMask.find(e=>t.isPrefixOf(e))||void 0!==this.fieldTransforms.find(e=>t.isPrefixOf(e.field))}Oc(){if(this.path)for(let e=0;e<this.path.length;e++)this.Uc(this.path.get(e))}Uc(e){if(0===e.length)throw this.jc("Document fields must not be empty");if(RF(this.Mc)&&CF.test(e))throw this.jc('Document fields cannot begin and end with "__"')}}class xF{constructor(e,t,n){this.databaseId=e,this.ignoreUndefinedProperties=t,this.O=n||hL(e)}Gc(e,t,n,r=!1){return new PF({Mc:e,methodName:t,Wc:n,path:tP.emptyPath(),Bc:!1,Qc:r},this.databaseId,this.O,this.ignoreUndefinedProperties)}}function OF(e){var t=e._freezeSettings(),n=hL(e._databaseId);return new xF(e._databaseId,!!t.ignoreUndefinedProperties,n)}function DF(e,t,n,r,i,s={}){const o=e.Gc(s.merge||s.mergeFields?2:0,t,n,i);HF("Data must be an object, but it was:",o,r);var a=KF(r,o);let c,l;if(s.merge)c=new nP(o.fieldMask),l=o.fieldTransforms;else if(s.mergeFields){const e=[];for(const r of s.mergeFields){const i=GF(t,r,n);if(!o.contains(i))throw new xR(PR.INVALID_ARGUMENT,`Field '${i}' is specified in your field mask but missing from your input data.`);JF(e,i)||e.push(i)}c=new nP(e),l=o.fieldTransforms.filter(e=>c.covers(e.field))}else c=null,l=o.fieldTransforms;return new AF(new NP(a),c,l)}class LF extends kF{_toFieldTransform(e){if(2!==e.Mc)throw 1===e.Mc?e.jc(`${this._methodName}() can only appear at the top level of your update data`):e.jc(`${this._methodName}() cannot be used with set() unless you pass {merge:true}`);return e.fieldMask.push(e.path),null}isEqual(e){return e instanceof LF}}function MF(e,t,n){return new PF({Mc:3,Wc:t.settings.Wc,methodName:e._methodName,Bc:n},t.databaseId,t.O,t.ignoreUndefinedProperties)}class FF extends kF{_toFieldTransform(e){return new kx(e.path,new vx)}isEqual(e){return e instanceof FF}}class UF extends kF{constructor(e,t){super(e),this.zc=t}_toFieldTransform(e){const t=MF(this,e,!0),n=this.zc.map(e=>zF(e,t)),r=new yx(n);return new kx(e.path,r)}isEqual(e){return this===e}}class jF extends kF{constructor(e,t){super(e),this.zc=t}_toFieldTransform(e){const t=MF(this,e,!0),n=this.zc.map(e=>zF(e,t)),r=new wx(n);return new kx(e.path,r)}isEqual(e){return this===e}}class qF extends kF{constructor(e,t){super(e),this.Hc=t}_toFieldTransform(e){var t=new Ix(e.O,fx(e.O,this.Hc));return new kx(e.path,t)}isEqual(e){return this===e}}function VF(e,i,s,t){const o=e.Gc(1,i,s);HF("Data must be an object, but it was:",o,t);const a=[],c=NP.empty();YR(t,(e,t)=>{var n=YF(i,e,s);t=zd(t);var r=o.qc(n);if(t instanceof LF)a.push(n);else{const e=zF(t,r);null!=e&&(a.push(n),c.set(n,e))}});var n=new nP(a);return new NF(c,n,o.fieldTransforms)}function BF(e,t,n,r,i,s){const o=e.Gc(1,t,n),a=[GF(t,r,n)],c=[i];if(s.length%2!=0)throw new xR(PR.INVALID_ARGUMENT,`Function ${t}() needs to be called with an even number of arguments that alternate between field names and values.`);for(let p=0;p<s.length;p+=2)a.push(GF(t,s[p])),c.push(s[p+1]);const l=[],u=NP.empty();for(let f=a.length-1;0<=f;--f)if(!JF(l,a[f])){const t=a[f];var h=zd(h=c[f]);const r=o.qc(t);if(h instanceof LF)l.push(t);else{const e=zF(h,r);null!=e&&(l.push(t),u.set(t,e))}}var d=new nP(l);return new NF(u,d,o.fieldTransforms)}function WF(e,t,n,r=!1){return zF(n,e.Gc(r?4:3,t))}function zF(s,e){if($F(s=zd(s)))return HF("Unsupported field value:",e,s),KF(s,e);if(s instanceof kF)return function(e,t){if(!RF(t.Mc))throw t.jc(`${e._methodName}() can only be used with update() and set()`);if(!t.path)throw t.jc(`${e._methodName}() is not currently supported inside arrays`);var n=e._toFieldTransform(t);n&&t.fieldTransforms.push(n)}(s,e),null;if(void 0===s&&e.ignoreUndefinedProperties)return null;if(e.path&&e.fieldMask.push(e.path),s instanceof Array){if(e.settings.Bc&&4!==e.Mc)throw e.jc("Nested arrays are not supported");return function(t){const n=[];let r=0;for(const i of s){let e=zF(i,t.Kc(r));null==e&&(e={nullValue:"NULL_VALUE"}),n.push(e),r++}return{arrayValue:{values:n}}}(e)}return function(e,t){if(null===(e=zd(s)))return{nullValue:"NULL_VALUE"};if("number"==typeof e)return fx(t.O,e);if("boolean"==typeof e)return{booleanValue:e};if("string"==typeof e)return{stringValue:e};if(e instanceof Date){var n=HR.fromDate(e);return{timestampValue:pO(t.O,n)}}if(e instanceof HR){n=new HR(e.seconds,1e3*Math.floor(e.nanoseconds/1e3));return{timestampValue:pO(t.O,n)}}if(e instanceof SF)return{geoPointValue:{latitude:e.latitude,longitude:e.longitude}};if(e instanceof EF)return{bytesValue:fO(t.O,e._byteString)};if(e instanceof eF){const r=t.databaseId,i=e.firestore._databaseId;if(!i.isEqual(r))throw t.jc(`Document reference is for database ${i.projectId}/${i.database} but should be for database ${r.projectId}/${r.database}`);return{referenceValue:mO(e.firestore._databaseId||t.databaseId,e._key.path)}}throw t.jc(`Unsupported field value: ${QM(e)}`)}(0,e)}function KF(e,r){const i={};return XR(e)?r.path&&0<r.path.length&&r.fieldMask.push(r.path):YR(e,(e,t)=>{var n=zF(t,r.Lc(e));null!=n&&(i[e]=n)}),{mapValue:{fields:i}}}function $F(e){return!("object"!=typeof e||null===e||e instanceof Array||e instanceof Date||e instanceof HR||e instanceof SF||e instanceof EF||e instanceof eF||e instanceof kF)}function HF(e,t,n){if(!$F(n)||("object"!=typeof(i=n)||null===i||Object.getPrototypeOf(i)!==Object.prototype&&null!==Object.getPrototypeOf(i))){var r=QM(n);throw"an object"===r?t.jc(e+" a custom object"):t.jc(e+" "+r)}var i}function GF(e,t,n){if((t=zd(t))instanceof TF)return t._internalPath;if("string"==typeof t)return YF(e,t);throw XF("Field path arguments must be of type string or ",e,!1,void 0,n)}const QF=new RegExp("[~\\*/\\[\\]]");function YF(t,n,r){if(0<=n.search(QF))throw XF(`Invalid field path (${n}). Paths must not contain '~', '*', '/', '[', or ']'`,t,!1,void 0,r);try{return new TF(...n.split("."))._internalPath}catch(e){throw XF(`Invalid field path (${n}). Paths must not be empty, begin with '.', end with '.', or contain '..'`,t,!1,void 0,r)}}function XF(e,t,n,r,i){var s=r&&!r.isEmpty(),o=void 0!==i;let a=`Function ${t}() called with invalid data`;n&&(a+=" (via `toFirestore()`)"),a+=". ";let c="";return(s||o)&&(c+=" (found",s&&(c+=` in field ${r}`),o&&(c+=` in document ${i}`),c+=")"),new xR(PR.INVALID_ARGUMENT,a+e+c)}function JF(e,t){return e.some(e=>e.isEqual(t))}class ZF{constructor(e,t,n,r,i){this._firestore=e,this._userDataWriter=t,this._key=n,this._document=r,this._converter=i}get id(){return this._key.path.lastSegment()}get ref(){return new eF(this._firestore,this._converter,this._key)}exists(){return null!==this._document}data(){if(this._document){if(this._converter){var e=new eU(this._firestore,this._userDataWriter,this._key,this._document,null);return this._converter.fromFirestore(e)}return this._userDataWriter.convertValue(this._document.data.value)}}get(e){if(this._document){var t=this._document.data.field(tU("DocumentSnapshot.get",e));if(null!==t)return this._userDataWriter.convertValue(t)}}}class eU extends ZF{data(){return super.data()}}function tU(e,t){return"string"==typeof t?YF(e,t):(t instanceof TF?t:t._delegate)._internalPath}class nU{constructor(e,t){this.hasPendingWrites=e,this.fromCache=t}isEqual(e){return this.hasPendingWrites===e.hasPendingWrites&&this.fromCache===e.fromCache}}class rU extends ZF{constructor(e,t,n,r,i,s){super(e,t,n,r,s),this._firestore=e,this._firestoreImpl=e,this.metadata=i}exists(){return super.exists()}data(e={}){if(this._document){if(this._converter){var t=new iU(this._firestore,this._userDataWriter,this._key,this._document,this.metadata,null);return this._converter.fromFirestore(t,e)}return this._userDataWriter.convertValue(this._document.data.value,e.serverTimestamps)}}get(e,t={}){if(this._document){var n=this._document.data.field(tU("DocumentSnapshot.get",e));if(null!==n)return this._userDataWriter.convertValue(n,t.serverTimestamps)}}}class iU extends rU{data(e={}){return super.data(e)}}class sU{constructor(e,t,n,r){this._firestore=e,this._userDataWriter=t,this._snapshot=r,this.metadata=new nU(r.hasPendingWrites,r.fromCache),this.query=n}get docs(){const t=[];return this.forEach(e=>t.push(e)),t}get size(){return this._snapshot.docs.size}get empty(){return 0===this.size}forEach(t,n){this._snapshot.docs.forEach(e=>{t.call(n,new iU(this._firestore,this._userDataWriter,e.key,e,new nU(this._snapshot.mutatedKeys.has(e.key),this._snapshot.fromCache),this.query.converter))})}docChanges(e={}){var t=!!e.includeMetadataChanges;if(t&&this._snapshot.excludesMetadataChanges)throw new xR(PR.INVALID_ARGUMENT,"To include metadata changes with your document changes, you must also pass { includeMetadataChanges:true } to onSnapshot().");return this._cachedChanges&&this._cachedChangesIncludeMetadataChanges===t||(this._cachedChanges=function(s,t){if(s._snapshot.oldDocs.isEmpty()){let t=0;return s._snapshot.docChanges.map(e=>({type:"added",doc:new iU(s._firestore,s._userDataWriter,e.doc.key,e.doc,new nU(s._snapshot.mutatedKeys.has(e.doc.key),s._snapshot.fromCache),s.query.converter),oldIndex:-1,newIndex:t++}))}{let i=s._snapshot.oldDocs;return s._snapshot.docChanges.filter(e=>t||3!==e.type).map(e=>{var t=new iU(s._firestore,s._userDataWriter,e.doc.key,e.doc,new nU(s._snapshot.mutatedKeys.has(e.doc.key),s._snapshot.fromCache),s.query.converter);let n=-1,r=-1;return 0!==e.type&&(n=i.indexOf(e.doc.key),i=i.delete(e.doc.key)),1!==e.type&&(i=i.add(e.doc),r=i.indexOf(e.doc.key)),{type:function(e){switch(e){case 0:return"added";case 2:case 3:return"modified";case 1:return"removed";default:return NR()}}(e.type),doc:t,oldIndex:n,newIndex:r}})}}(this,t),this._cachedChangesIncludeMetadataChanges=t),this._cachedChanges}}function oU(e,t){return e instanceof rU&&t instanceof rU?e._firestore===t._firestore&&e._key.isEqual(t._key)&&(null===e._document?null===t._document:e._document.isEqual(t._document))&&e._converter===t._converter:e instanceof sU&&t instanceof sU&&e._firestore===t._firestore&&oF(e.query,t.query)&&e.metadata.isEqual(t.metadata)&&e._snapshot.isEqual(t._snapshot)}function aU(e){if(ex(e)&&0===e.explicitOrderBy.length)throw new xR(PR.UNIMPLEMENTED,"limitToLast() queries require specifying at least one orderBy() clause")}class cU{}function lU(e,...t){for(const n of t)e=n._apply(e);return e}class uU extends cU{constructor(e,t,n){super(),this.Jc=e,this.Yc=t,this.Xc=n,this.type="where"}_apply(e){var t=OF(e.firestore),t=function(e,t,n,r,i,s,o){let a;if(i.isKeyField()){if("array-contains"===s||"array-contains-any"===s)throw new xR(PR.INVALID_ARGUMENT,`Invalid Query. You can't perform '${s}' queries on documentId().`);if("in"===s||"not-in"===s){vU(o,s);const t=[];for(const n of o)t.push(mU(r,e,n));a={arrayValue:{values:t}}}else a=mU(r,e,o)}else"in"!==s&&"not-in"!==s&&"array-contains-any"!==s||vU(o,s),a=WF(n,t,o,"in"===s||"not-in"===s);var c=MP.create(i,s,a);return function(e,t){if(t.D()){const r=nx(e);if(null!==r&&!r.isEqual(t.field))throw new xR(PR.INVALID_ARGUMENT,`Invalid query. All where filters with an inequality (<, <=, !=, not-in, >, or >=) must be on the same field. But you have inequality filters on '${r.toString()}' and '${t.field.toString()}'`);var n=tx(e);null!==n&&yU(0,t.field,n)}const r=function(e,t){for(const n of e.filters)if(0<=t.indexOf(n.op))return n.op;return null}(e,function(){switch(t.op){case"!=":return["!=","not-in"];case"array-contains":return["array-contains","array-contains-any","not-in"];case"in":return["array-contains-any","in","not-in"];case"array-contains-any":return["array-contains","array-contains-any","in","not-in"];case"not-in":return["array-contains","array-contains-any","in","not-in","!="];default:return[]}}());if(null!==r)throw r===t.op?new xR(PR.INVALID_ARGUMENT,`Invalid query. You cannot use more than one '${t.op.toString()}' filter.`):new xR(PR.INVALID_ARGUMENT,`Invalid query. You cannot use '${t.op.toString()}' filters with '${r.toString()}' filters.`)}(e,c),c}(e._query,"where",t,e.firestore._databaseId,this.Jc,this.Yc,this.Xc);return new tF(e.firestore,e.converter,(e=e._query,t=e.filters.concat([t]),new YP(e.path,e.collectionGroup,e.explicitOrderBy.slice(),t,e.limit,e.limitType,e.startAt,e.endAt)))}}class hU extends cU{constructor(e,t){super(),this.Jc=e,this.Zc=t,this.type="orderBy"}_apply(e){var t=function(e,t,n){if(null!==e.startAt)throw new xR(PR.INVALID_ARGUMENT,"Invalid query. You must not call startAt() or startAfter() before calling orderBy().");if(null!==e.endAt)throw new xR(PR.INVALID_ARGUMENT,"Invalid query. You must not call endAt() or endBefore() before calling orderBy().");var r,i=new HP(t,n);return n=i,null!==tx(e=e)||null!==(r=nx(e))&&yU(0,r,n.field),i}(e._query,this.Jc,this.Zc);return new tF(e.firestore,e.converter,(e=e._query,t=e.explicitOrderBy.concat([t]),new YP(e.path,e.collectionGroup,t,e.filters.slice(),e.limit,e.limitType,e.startAt,e.endAt)))}}class dU extends cU{constructor(e,t,n){super(),this.type=e,this.ta=t,this.ea=n}_apply(e){return new tF(e.firestore,e.converter,ox(e._query,this.ta,this.ea))}}class pU extends cU{constructor(e,t,n){super(),this.type=e,this.na=t,this.sa=n}_apply(e){var t,n=gU(e,this.type,this.na,this.sa);return new tF(e.firestore,e.converter,(t=e._query,e=n,new YP(t.path,t.collectionGroup,t.explicitOrderBy.slice(),t.filters.slice(),t.limit,t.limitType,e,t.endAt)))}}class fU extends cU{constructor(e,t,n){super(),this.type=e,this.na=t,this.sa=n}_apply(e){var t,n=gU(e,this.type,this.na,this.sa);return new tF(e.firestore,e.converter,(t=e._query,e=n,new YP(t.path,t.collectionGroup,t.explicitOrderBy.slice(),t.filters.slice(),t.limit,t.limitType,t.startAt,e)))}}function gU(e,t,n,r){if(n[0]=zd(n[0]),n[0]instanceof ZF)return function(e,t,n,r,i){if(!r)throw new xR(PR.NOT_FOUND,`Can't use a DocumentSnapshot that doesn't exist for ${n}().`);const s=[];for(const n of ix(e))if(n.field.isKeyField())s.push(IP(t,r.key));else{const e=r.data.field(n.field);if(cP(e))throw new xR(PR.INVALID_ARGUMENT,'Invalid query. You are trying to start or end a query using a document for which the field "'+n.field+'" is an uncommitted server timestamp. (Since the value of this field is unknown, you cannot start/end a query with it.)');if(null===e){const e=n.field.canonicalString();throw new xR(PR.INVALID_ARGUMENT,`Invalid query. You are trying to start or end a query using a document for which the field '${e}' (used as the orderBy) does not exist.`)}s.push(e)}return new KP(s,i)}(e._query,e.firestore._databaseId,t,n[0]._document,r);var i=OF(e.firestore);return function(e,t,n,r,i,s){const o=e.explicitOrderBy;if(i.length>o.length)throw new xR(PR.INVALID_ARGUMENT,`Too many arguments provided to ${r}(). The number of arguments must be less than or equal to the number of orderBy() clauses`);const a=[];for(let c=0;c<i.length;c++){const l=i[c];if(o[c].field.isKeyField()){if("string"!=typeof l)throw new xR(PR.INVALID_ARGUMENT,`Invalid query. Expected a string for document ID in ${r}(), but got a ${typeof l}`);if(!rx(e)&&-1!==l.indexOf("/"))throw new xR(PR.INVALID_ARGUMENT,`Invalid query. When querying a collection and ordering by documentId(), the value passed to ${r}() must be a plain document ID, but '${l}' contains a slash.`);const n=e.path.child(ZR.fromString(l));if(!gP.isDocumentKey(n))throw new xR(PR.INVALID_ARGUMENT,`Invalid query. When querying a collection group and ordering by documentId(), the value passed to ${r}() must result in a valid document path, but '${n}' is not because it contains an odd number of segments.`);const i=new gP(n);a.push(IP(t,i))}else{const e=WF(n,r,l);a.push(e)}}return new KP(a,s)}(e._query,e.firestore._databaseId,i,t,n,r)}function mU(e,t,n){if("string"==typeof(n=zd(n))){if(""===n)throw new xR(PR.INVALID_ARGUMENT,"Invalid query. When querying with documentId(), you must provide a valid document ID, but it was an empty string.");if(!rx(t)&&-1!==n.indexOf("/"))throw new xR(PR.INVALID_ARGUMENT,`Invalid query. When querying a collection by documentId(), you must provide a plain document ID, but '${n}' contains a '/' character.`);var r=t.path.child(ZR.fromString(n));if(!gP.isDocumentKey(r))throw new xR(PR.INVALID_ARGUMENT,`Invalid query. When querying a collection group by documentId(), the value provided must result in a valid document path, but '${r}' is not because it has an odd number of segments (${r.length}).`);return IP(e,new gP(r))}if(n instanceof eF)return IP(e,n._key);throw new xR(PR.INVALID_ARGUMENT,`Invalid query. When querying with documentId(), you must provide a valid string or a DocumentReference, but it was: ${QM(n)}.`)}function vU(e,t){if(!Array.isArray(e)||0===e.length)throw new xR(PR.INVALID_ARGUMENT,`Invalid Query. A non-empty array is required for '${t.toString()}' filters.`);if(10<e.length)throw new xR(PR.INVALID_ARGUMENT,`Invalid Query. '${t.toString()}' filters support a maximum of 10 elements in the value array.`)}function yU(e,t,n){if(!n.isEqual(t))throw new xR(PR.INVALID_ARGUMENT,`Invalid query. You have a where filter with an inequality (<, <=, !=, not-in, >, or >=) on field '${t.toString()}' and so you must also use '${t.toString()}' as your first argument to orderBy(), but your first orderBy() is on field '${n.toString()}' instead.`)}class _U{convertValue(e,t="none"){switch(mP(e)){case 0:return null;case 1:return e.booleanValue;case 2:return oP(e.integerValue||e.doubleValue);case 3:return this.convertTimestamp(e.timestampValue);case 4:return this.convertServerTimestamp(e,t);case 5:return e.stringValue;case 6:return this.convertBytes(aP(e.bytesValue));case 7:return this.convertReference(e.referenceValue);case 8:return this.convertGeoPoint(e.geoPointValue);case 9:return this.convertArray(e.arrayValue,t);case 10:return this.convertObject(e.mapValue,t);default:throw NR()}}convertObject(e,n){const r={};return YR(e.fields,(e,t)=>{r[e]=this.convertValue(t,n)}),r}convertGeoPoint(e){return new SF(oP(e.latitude),oP(e.longitude))}convertArray(e,t){return(e.values||[]).map(e=>this.convertValue(e,t))}convertServerTimestamp(e,t){switch(t){case"previous":var n=function e(t){var n=t.mapValue.fields.__previous_value__;return cP(n)?e(n):n}(e);return null==n?null:this.convertValue(n,t);case"estimate":return this.convertTimestamp(lP(e));default:return null}}convertTimestamp(e){var t=sP(e);return new HR(t.seconds,t.nanos)}convertDocumentKey(e,t){const n=ZR.fromString(e);RR(FO(n));const r=new hP(n.get(1),n.get(3)),i=new gP(n.popFirst(5));return r.isEqual(t)||SR(`Document ${i} contains a document reference within a different database (${r.projectId}/${r.database}) which is not supported. It will be treated as a reference in the current database (${t.projectId}/${t.database}) instead.`),i}}function wU(e,t,n){return e?n&&(n.merge||n.mergeFields)?e.toFirestore(t,n):e.toFirestore(t):t}class bU extends _U{constructor(e){super(),this.firestore=e}convertBytes(e){return new EF(e)}convertReference(e){var t=this.convertDocumentKey(e,this.firestore._databaseId);return new eF(this.firestore,null,t)}}class IU{constructor(e,t){this._firestore=e,this._commitHandler=t,this._mutations=[],this._committed=!1,this._dataReader=OF(e)}set(e,t,n){this._verifyNotCommitted();const r=TU(e,this._firestore),i=wU(r.converter,t,n),s=DF(this._dataReader,"WriteBatch.set",r._key,i,null!==r.converter,n);return this._mutations.push(s.toMutation(r._key,Cx.none())),this}update(e,t,n,...r){this._verifyNotCommitted();var i=TU(e,this._firestore);let s;return s="string"==typeof(t=zd(t))||t instanceof TF?BF(this._dataReader,"WriteBatch.update",i._key,t,n,r):VF(this._dataReader,"WriteBatch.update",i._key,t),this._mutations.push(s.toMutation(i._key,Cx.exists(!0))),this}delete(e){this._verifyNotCommitted();var t=TU(e,this._firestore);return this._mutations=this._mutations.concat(new jx(t._key,Cx.none())),this}commit(){return this._verifyNotCommitted(),this._committed=!0,0<this._mutations.length?this._commitHandler(this._mutations):Promise.resolve()}_verifyNotCommitted(){if(this._committed)throw new xR(PR.FAILED_PRECONDITION,"A write batch can no longer be used after commit() has been called.")}}function TU(e,t){if((e=zd(e)).firestore!==t)throw new xR(PR.INVALID_ARGUMENT,"Provided document reference is from a different Firestore instance.");return e}class EU extends _U{constructor(e){super(),this.firestore=e}convertBytes(e){return new EF(e)}convertReference(e){var t=this.convertDocumentKey(e,this.firestore._databaseId);return new eF(this.firestore,null,t)}}function kU(t){t=YM(t,eF);const n=YM(t.firestore,fF),e=gF(n),r=new EU(n);return function(e,t){const n=new OR;return e.asyncQueue.enqueueAndForget(async()=>async function(e,t,n){try{const i=await function(t){const n=e;return n.persistence.runTransaction("read document","readonly",e=>n.zn.Pn(e,t))}(t);i.isFoundDocument()?n.resolve(i):i.isNoDocument()?n.resolve(null):n.reject(new xR(PR.UNAVAILABLE,"Failed to get document from cache. (However, this document may exist on the server. Run again without setting 'source' in the GetOptions to attempt to retrieve the document from the server.)"))}catch(e){var r=jL(e,`Failed to get document '${t} from cache`);n.reject(r)}}(await FM(e),t,n)),n.promise}(e,t._key).then(e=>new rU(n,r,t._key,e,new nU(null!==e&&e.hasLocalMutations,!0),t.converter))}function SU(t){t=YM(t,tF);const n=YM(t.firestore,fF),e=gF(n),r=new EU(n);return function(e,t){const n=new OR;return e.asyncQueue.enqueueAndForget(async()=>async function(e,t,n){try{const i=await L1(e,t,!0),s=new tM(t,i.Jn),o=s.Vo(i.documents),a=s.applyChanges(o,!1);n.resolve(a.snapshot)}catch(e){var r=jL(e,`Failed to execute query '${t} against cache`);n.reject(r)}}(await FM(e),t,n)),n.promise}(e,t._query).then(e=>new sU(n,r,t,e))}function CU(e,t,n){e=YM(e,eF);var r=YM(e.firestore,fF),i=wU(e.converter,t,n);return PU(r,[DF(OF(r),"setDoc",e._key,i,null!==e.converter,n).toMutation(e._key,Cx.none())])}function AU(e,t,n,...r){e=YM(e,eF);var i=YM(e.firestore,fF),s=OF(i);let o;return o="string"==typeof(t=zd(t))||t instanceof TF?BF(s,"updateDoc",e._key,t,n,r):VF(s,"updateDoc",e._key,t),PU(i,[o.toMutation(e._key,Cx.exists(!0))])}function NU(t,...n){var e;t=zd(t);let r={includeMetadataChanges:!1},i=0;"object"!=typeof n[i]||cF(n[i])||(r=n[i],i++);var s={includeMetadataChanges:r.includeMetadataChanges};if(cF(n[i])){const t=n[i];n[i]=null===(e=t.next)||void 0===e?void 0:e.bind(t),n[i+1]=null===(e=t.error)||void 0===e?void 0:e.bind(t),n[i+2]=null===(e=t.complete)||void 0===e?void 0:e.bind(t)}let o,a,c;if(t instanceof eF)a=YM(t.firestore,fF),c=JP(t._key.path),o={next:e=>{n[i]&&n[i](xU(a,t,e))},error:n[i+1],complete:n[i+2]};else{const l=YM(t,tF);a=YM(l.firestore,fF),c=l._query;const u=new EU(a);o={next:e=>{n[i]&&n[i](new sU(a,u,l,e))},error:n[i+1],complete:n[i+2]},aU(t._query)}return function(e,t,n,r){const i=new CM(r),s=new GL(t,i,n);return e.asyncQueue.enqueueAndForget(async()=>KL(await qM(e),s)),()=>{i.ic(),e.asyncQueue.enqueueAndForget(async()=>$L(await qM(e),s))}}(gF(a),c,s,o)}function RU(e,t){return function(e,t){const n=new CM(t);return e.asyncQueue.enqueueAndForget(async()=>function(e,t){e.oo.add(t),t.next()}(await qM(e),n)),()=>{n.ic(),e.asyncQueue.enqueueAndForget(async()=>function(e,t){e.oo.delete(t)}(await qM(e),n))}}(gF(e=YM(e,fF)),cF(t)?t:{next:t})}function PU(e,t){return function(e,t){const n=new OR;return e.asyncQueue.enqueueAndForget(async()=>oM(await jM(e),t,n)),n.promise}(gF(e),t)}function xU(e,t,n){var r=n.docs.get(t._key),i=new EU(e);return new rU(e,i,t._key,r,new nU(n.hasPendingWrites,n.fromCache),t.converter)}class OU extends class{constructor(e,t){this._firestore=e,this._transaction=t,this._dataReader=OF(e)}get(e){const n=TU(e,this._firestore),r=new bU(this._firestore);return this._transaction.lookup([n._key]).then(e=>{if(!e||1!==e.length)return NR();const t=e[0];if(t.isFoundDocument())return new ZF(this._firestore,r,t.key,t,n.converter);if(t.isNoDocument())return new ZF(this._firestore,r,n._key,null,n.converter);throw NR()})}set(e,t,n){var r=TU(e,this._firestore),i=wU(r.converter,t,n),i=DF(this._dataReader,"Transaction.set",r._key,i,null!==r.converter,n);return this._transaction.set(r._key,i),this}update(e,t,n,...r){var i=TU(e,this._firestore),s="string"==typeof(t=zd(t))||t instanceof TF?BF(this._dataReader,"Transaction.update",i._key,t,n,r):VF(this._dataReader,"Transaction.update",i._key,t);return this._transaction.update(i._key,s),this}delete(e){var t=TU(e,this._firestore);return this._transaction.delete(t._key),this}}{constructor(e,t){super(e,t),this._firestore=e}get(e){const t=TU(e,this._firestore),n=new EU(this._firestore);return super.get(e).then(e=>new rU(this._firestore,n,t._key,e._document,new nU(!1,!1),t.converter))}}function DU(t,n){return function(t,n){const r=new OR;return t.asyncQueue.enqueueAndForget(async()=>{var e=await LM(t).then(e=>e.datastore);new RM(t.asyncQueue,e,n,r).run()}),r.promise}(gF(t=YM(t,fF)),e=>n(new OU(t,e)))}$=gp,IR=$,hp(new Kd("firestore",(e,{options:t})=>{const n=e.getProvider("app").getImmediate(),r=new fF(n,new FR(e.getProvider("auth-internal")),new VR(e.getProvider("app-check-internal")));return t=Object.assign({useFetchStreams:!0},t),r._setSettings(t),r},"PUBLIC")),_p(wR,"3.4.4",void 0),_p(wR,"3.4.4","esm2017");function LU(e,t){if(void 0===t)return{merge:!1};if(void 0!==t.mergeFields&&void 0!==t.merge)throw new xR("invalid-argument",`Invalid options passed to function ${e}(): You cannot `+'specify both "merge" and "mergeFields".');return t}function MU(){if("undefined"==typeof Uint8Array)throw new xR("unimplemented","Uint8Arrays are not available in this environment.")}function FU(){if("undefined"==typeof atob)throw new xR("unimplemented","Blobs are unavailable in Firestore in this environment.")}class UU{constructor(e){this._delegate=e}static fromBase64String(e){return FU(),new UU(EF.fromBase64String(e))}static fromUint8Array(e){return MU(),new UU(EF.fromUint8Array(e))}toBase64(){return FU(),this._delegate.toBase64()}toUint8Array(){return MU(),this._delegate.toUint8Array()}isEqual(e){return this._delegate.isEqual(e._delegate)}toString(){return"Blob(base64: "+this.toBase64()+")"}}function jU(e){return function(e,t){if("object"!=typeof e||null===e)return;var n=e;for(const r of t)if(r in n&&"function"==typeof n[r])return 1;return}(e,["next","error","complete"])}class qU{enableIndexedDbPersistence(e,t){return function(e,t){IF(e=YM(e,fF));var n=gF(e),r=e._freezeSettings(),i=new kM;return vF(n,i,new TM(i,r.cacheSizeBytes,null==t?void 0:t.forceOwnership))}(e._delegate,{forceOwnership:t})}enableMultiTabIndexedDbPersistence(e){return function(e){IF(e=YM(e,fF));var t=gF(e),n=e._freezeSettings(),r=new kM;return vF(t,r,new EM(r,n.cacheSizeBytes))}(e._delegate)}clearIndexedDbPersistence(e){return function(e){if(e._initialized&&!e._terminated)throw new xR(PR.FAILED_PRECONDITION,"Persistence can only be cleared before a Firestore instance is initialized or after it is terminated.");const t=new OR;return e._queue.enqueueAndForgetEvenWhileRestricted(async()=>{try{await async function(e){if(!hD.Vt())return Promise.resolve();var t=e+"main";await hD.delete(t)}(I1(e._databaseId,e._persistenceKey)),t.resolve()}catch(e){t.reject(e)}}),t.promise}(e._delegate)}}class VU{constructor(e,t,n){this._delegate=t,this._persistenceProvider=n,this.INTERNAL={delete:()=>this.terminate()},e instanceof hP||(this._appCompat=e)}get _databaseId(){return this._delegate._databaseId}settings(e){var t=this._delegate._getSettings();e.merge||t.host===e.host||CR("You are overriding the original host. If you did not intend to override your settings, use {merge: true}."),e.merge&&delete(e=Object.assign(Object.assign({},t),e)).merge,this._delegate._setSettings(e)}useEmulator(e,t,n={}){!function(n,e,t,r={}){var i;const s=(n=YM(n,ZM))._getSettings();if("firestore.googleapis.com"!==s.host&&s.host!==e&&CR("Host has been set in both settings() and useEmulator(), emulator host will be used"),n._setSettings(Object.assign(Object.assign({},s),{host:`${e}:${t}`,ssl:!1})),r.mockUserToken){let e,t;if("string"==typeof r.mockUserToken)e=r.mockUserToken,t=bR.MOCK_USER;else{e=id(r.mockUserToken,null===(i=n._app)||void 0===i?void 0:i.options.projectId);const s=r.mockUserToken.sub||r.mockUserToken.user_id;if(!s)throw new xR(PR.INVALID_ARGUMENT,"mockUserToken must contain 'sub' or 'user_id' field!");t=new bR(s)}n._authCredentials=new MR(new DR(e,t))}}(this._delegate,e,t,n)}enableNetwork(){return _F(this._delegate)}disableNetwork(){return wF(this._delegate)}enablePersistence(e){let t=!1,n=!1;return e&&(t=!!e.synchronizeTabs,n=!!e.experimentalForceOwningTab,$M("synchronizeTabs",t,"experimentalForceOwningTab",n)),t?this._persistenceProvider.enableMultiTabIndexedDbPersistence(this):this._persistenceProvider.enableIndexedDbPersistence(this,n)}clearPersistence(){return this._persistenceProvider.clearIndexedDbPersistence(this)}terminate(){return this._appCompat&&(this._appCompat._removeServiceInstance("firestore-compat"),this._appCompat._removeServiceInstance("firestore")),this._delegate._delete()}waitForPendingWrites(){return yF(this._delegate)}onSnapshotsInSync(e){return RU(this._delegate,e)}get app(){if(!this._appCompat)throw new xR("failed-precondition","Firestore was not initialized using the Firebase SDK. 'app' is not available");return this._appCompat}collection(e){try{return new tj(this,rF(this._delegate,e))}catch(e){throw HU(e,"collection()","Firestore.collection()")}}doc(e){try{return new $U(this,iF(this._delegate,e))}catch(e){throw HU(e,"doc()","Firestore.doc()")}}collectionGroup(e){try{return new JU(this,function(e,t){if(e=YM(e,ZM),KM("collectionGroup","collection id",t),0<=t.indexOf("/"))throw new xR(PR.INVALID_ARGUMENT,`Invalid collection ID '${t}' passed to function collectionGroup(). Collection IDs must not contain '/'.`);return new tF(e,null,(t=t,new YP(ZR.emptyPath(),t)))}(this._delegate,e))}catch(e){throw HU(e,"collectionGroup()","Firestore.collectionGroup()")}}runTransaction(t){return DU(this._delegate,e=>t(new WU(this,e)))}batch(){return gF(this._delegate),new zU(new IU(this._delegate,e=>PU(this._delegate,e)))}loadBundle(e){return t=this._delegate,e=e,n=gF(t=YM(t,fF)),r=new lF,WM(n,t._databaseId,e,r),r;var t,n,r}namedQuery(e){return bF(this._delegate,e).then(e=>e?new JU(this,e):null)}}class BU extends _U{constructor(e){super(),this.firestore=e}convertBytes(e){return new UU(new EF(e))}convertReference(e){var t=this.convertDocumentKey(e,this.firestore._databaseId);return $U.forKey(t,this.firestore,null)}}class WU{constructor(e,t){this._firestore=e,this._delegate=t,this._userDataWriter=new BU(e)}get(e){const t=nj(e);return this._delegate.get(t).then(e=>new YU(this._firestore,new rU(this._firestore._delegate,this._userDataWriter,e._key,e._document,e.metadata,t.converter)))}set(e,t,n){var r=nj(e);return n?(LU("Transaction.set",n),this._delegate.set(r,t,n)):this._delegate.set(r,t),this}update(e,t,n,...r){var i=nj(e);return 2===arguments.length?this._delegate.update(i,t):this._delegate.update(i,t,n,...r),this}delete(e){var t=nj(e);return this._delegate.delete(t),this}}class zU{constructor(e){this._delegate=e}set(e,t,n){var r=nj(e);return n?(LU("WriteBatch.set",n),this._delegate.set(r,t,n)):this._delegate.set(r,t),this}update(e,t,n,...r){var i=nj(e);return 2===arguments.length?this._delegate.update(i,t):this._delegate.update(i,t,n,...r),this}delete(e){var t=nj(e);return this._delegate.delete(t),this}commit(){return this._delegate.commit()}}class KU{constructor(e,t,n){this._firestore=e,this._userDataWriter=t,this._delegate=n}fromFirestore(e,t){var n=new iU(this._firestore._delegate,this._userDataWriter,e._key,e._document,e.metadata,null);return this._delegate.fromFirestore(new XU(this._firestore,n),null!=t?t:{})}toFirestore(e,t){return t?this._delegate.toFirestore(e,t):this._delegate.toFirestore(e)}static getInstance(e,t){const n=KU.INSTANCES;let r=n.get(e);r||(r=new WeakMap,n.set(e,r));let i=r.get(t);return i||(i=new KU(e,new BU(e),t),r.set(t,i)),i}}KU.INSTANCES=new WeakMap;class $U{constructor(e,t){this.firestore=e,this._delegate=t,this._userDataWriter=new BU(e)}static forPath(e,t,n){if(e.length%2!=0)throw new xR("invalid-argument","Invalid document reference. Document references must have an even number of segments, but "+`${e.canonicalString()} has ${e.length}`);return new $U(t,new eF(t._delegate,n,new gP(e)))}static forKey(e,t,n){return new $U(t,new eF(t._delegate,n,e))}get id(){return this._delegate.id}get parent(){return new tj(this.firestore,this._delegate.parent)}get path(){return this._delegate.path}collection(e){try{return new tj(this.firestore,rF(this._delegate,e))}catch(e){throw HU(e,"collection()","DocumentReference.collection()")}}isEqual(e){return(e=zd(e))instanceof eF&&sF(this._delegate,e)}set(e,t){t=LU("DocumentReference.set",t);try{return t?CU(this._delegate,e,t):CU(this._delegate,e)}catch(e){throw HU(e,"setDoc()","DocumentReference.set()")}}update(e,t,...n){try{return 1===arguments.length?AU(this._delegate,e):AU(this._delegate,e,t,...n)}catch(e){throw HU(e,"updateDoc()","DocumentReference.update()")}}delete(){return PU(YM((e=this._delegate).firestore,fF),[new jx(e._key,Cx.none())]);var e}onSnapshot(...e){var t=GU(e),n=QU(e,e=>new YU(this.firestore,new rU(this.firestore._delegate,this._userDataWriter,e._key,e._document,e.metadata,this._delegate.converter)));return NU(this._delegate,t,n)}get(e){let t;return t=("cache"===(null==e?void 0:e.source)?kU:"server"===(null==e?void 0:e.source)?function(t){t=YM(t,eF);const n=YM(t.firestore,fF);return VM(gF(n),t._key,{source:"server"}).then(e=>xU(n,t,e))}:function(t){t=YM(t,eF);const n=YM(t.firestore,fF);return VM(gF(n),t._key).then(e=>xU(n,t,e))})(this._delegate),t.then(e=>new YU(this.firestore,new rU(this.firestore._delegate,this._userDataWriter,e._key,e._document,e.metadata,this._delegate.converter)))}withConverter(e){return new $U(this.firestore,e?this._delegate.withConverter(KU.getInstance(this.firestore,e)):this._delegate.withConverter(null))}}function HU(e,t,n){return e.message=e.message.replace(t,n),e}function GU(e){for(const t of e)if("object"==typeof t&&!jU(t))return t;return{}}function QU(e,t){var n;let r;return r=jU(e[0])?e[0]:jU(e[1])?e[1]:"function"==typeof e[0]?{next:e[0],error:e[1],complete:e[2]}:{next:e[1],error:e[2],complete:e[3]},{next:e=>{r.next&&r.next(t(e))},error:null===(n=r.error)||void 0===n?void 0:n.bind(r),complete:null===(n=r.complete)||void 0===n?void 0:n.bind(r)}}class YU{constructor(e,t){this._firestore=e,this._delegate=t}get ref(){return new $U(this._firestore,this._delegate.ref)}get id(){return this._delegate.id}get metadata(){return this._delegate.metadata}get exists(){return this._delegate.exists()}data(e){return this._delegate.data(e)}get(e,t){return this._delegate.get(e,t)}isEqual(e){return oU(this._delegate,e._delegate)}}class XU extends YU{data(e){var t=this._delegate.data(e);return void 0!==t||NR(),t}}class JU{constructor(e,t){this.firestore=e,this._delegate=t,this._userDataWriter=new BU(e)}where(e,t,n){try{return new JU(this.firestore,lU(this._delegate,(r=n,i=t,s=tU("where",e),new uU(s,i,r))))}catch(e){throw HU(e,/(orderBy|where)\(\)/,"Query.$1()")}var r,i,s}orderBy(e,t){try{return new JU(this.firestore,lU(this._delegate,([n,r="asc"]=[e,t],i=r,s=tU("orderBy",n),new hU(s,i))))}catch(e){throw HU(e,/(orderBy|where)\(\)/,"Query.$1()")}var n,r,i,s}limit(e){try{return new JU(this.firestore,lU(this._delegate,(XM("limit",t=e),new dU("limit",t,"F"))))}catch(e){throw HU(e,"limit()","Query.limit()")}var t}limitToLast(e){try{return new JU(this.firestore,lU(this._delegate,(XM("limitToLast",t=e),new dU("limitToLast",t,"L"))))}catch(e){throw HU(e,"limitToLast()","Query.limitToLast()")}var t}startAt(...e){try{return new JU(this.firestore,lU(this._delegate,function(...e){return new pU("startAt",e,!0)}(...e)))}catch(e){throw HU(e,"startAt()","Query.startAt()")}}startAfter(...e){try{return new JU(this.firestore,lU(this._delegate,function(...e){return new pU("startAfter",e,!1)}(...e)))}catch(e){throw HU(e,"startAfter()","Query.startAfter()")}}endBefore(...e){try{return new JU(this.firestore,lU(this._delegate,function(...e){return new fU("endBefore",e,!0)}(...e)))}catch(e){throw HU(e,"endBefore()","Query.endBefore()")}}endAt(...e){try{return new JU(this.firestore,lU(this._delegate,function(...e){return new fU("endAt",e,!1)}(...e)))}catch(e){throw HU(e,"endAt()","Query.endAt()")}}isEqual(e){return oF(this._delegate,e._delegate)}get(e){let t;return t=("cache"===(null==e?void 0:e.source)?SU:"server"===(null==e?void 0:e.source)?function(t){t=YM(t,tF);const n=YM(t.firestore,fF),e=gF(n),r=new EU(n);return BM(e,t._query,{source:"server"}).then(e=>new sU(n,r,t,e))}:function(t){t=YM(t,tF);const n=YM(t.firestore,fF),e=gF(n),r=new EU(n);return aU(t._query),BM(e,t._query).then(e=>new sU(n,r,t,e))})(this._delegate),t.then(e=>new ej(this.firestore,new sU(this.firestore._delegate,this._userDataWriter,this._delegate,e._snapshot)))}onSnapshot(...e){var t=GU(e),n=QU(e,e=>new ej(this.firestore,new sU(this.firestore._delegate,this._userDataWriter,this._delegate,e._snapshot)));return NU(this._delegate,t,n)}withConverter(e){return new JU(this.firestore,e?this._delegate.withConverter(KU.getInstance(this.firestore,e)):this._delegate.withConverter(null))}}class ZU{constructor(e,t){this._firestore=e,this._delegate=t}get type(){return this._delegate.type}get doc(){return new XU(this._firestore,this._delegate.doc)}get oldIndex(){return this._delegate.oldIndex}get newIndex(){return this._delegate.newIndex}}class ej{constructor(e,t){this._firestore=e,this._delegate=t}get query(){return new JU(this._firestore,this._delegate.query)}get metadata(){return this._delegate.metadata}get size(){return this._delegate.size}get empty(){return this._delegate.empty}get docs(){return this._delegate.docs.map(e=>new XU(this._firestore,e))}docChanges(e){return this._delegate.docChanges(e).map(e=>new ZU(this._firestore,e))}forEach(t,n){this._delegate.forEach(e=>{t.call(n,new XU(this._firestore,e))})}isEqual(e){return oU(this._delegate,e._delegate)}}class tj extends JU{constructor(e,t){super(e,t),this.firestore=e,this._delegate=t}get id(){return this._delegate.id}get path(){return this._delegate.path}get parent(){var e=this._delegate.parent;return e?new $U(this.firestore,e):null}doc(e){try{return void 0===e?new $U(this.firestore,iF(this._delegate)):new $U(this.firestore,iF(this._delegate,e))}catch(e){throw HU(e,"doc()","CollectionReference.doc()")}}add(e){return function(e,t){const n=YM(e.firestore,fF),r=iF(e),i=wU(e.converter,t);return PU(n,[DF(OF(e.firestore),"addDoc",r._key,i,null!==e.converter,{}).toMutation(r._key,Cx.exists(!1))]).then(()=>r)}(this._delegate,e).then(e=>new $U(this.firestore,e))}isEqual(e){return sF(this._delegate,e._delegate)}withConverter(e){return new tj(this.firestore,e?this._delegate.withConverter(KU.getInstance(this.firestore,e)):this._delegate.withConverter(null))}}function nj(e){return YM(e,eF)}const rj={Firestore:VU,GeoPoint:SF,Timestamp:HR,Blob:UU,Transaction:WU,WriteBatch:zU,DocumentReference:$U,DocumentSnapshot:YU,Query:JU,QueryDocumentSnapshot:XU,QuerySnapshot:ej,CollectionReference:tj,FieldPath:class tz{constructor(...e){this._delegate=new TF(...e)}static documentId(){return new tz(tP.keyField().canonicalString())}isEqual(e){return(e=zd(e))instanceof TF&&this._delegate._internalPath.isEqual(e._internalPath)}},FieldValue:class nz{constructor(e){this._delegate=e}static serverTimestamp(){const e=new FF("serverTimestamp");return e._methodName="FieldValue.serverTimestamp",new nz(e)}static delete(){const e=new LF("deleteField");return e._methodName="FieldValue.delete",new nz(e)}static arrayUnion(...e){const t=function(...e){return new UF("arrayUnion",e)}(...e);return t._methodName="FieldValue.arrayUnion",new nz(t)}static arrayRemove(...e){const t=function(...e){return new jF("arrayRemove",e)}(...e);return t._methodName="FieldValue.arrayRemove",new nz(t)}static increment(e){const t=new qF("increment",e);return t._methodName="FieldValue.increment",new nz(t)}isEqual(e){return this._delegate.isEqual(e._delegate)}},setLogLevel:function(e){e=e,TR.setLogLevel(e)},CACHE_SIZE_UNLIMITED:-1};uF=Cp,hF=(e,t)=>new VU(e,t,new qU),uF.INTERNAL.registerComponent(new Kd("firestore-compat",e=>{var t=e.getProvider("app-compat").getImmediate(),n=e.getProvider("firestore").getImmediate();return hF(t,n)},"PUBLIC").setServiceProps(Object.assign({},rj))),uF.registerVersion("@firebase/firestore-compat","0.1.13");function ij(e,t){const n={};for(const r in e)e.hasOwnProperty(r)&&(n[r]=t(e[r]));return n}function sj(e){if(null==e)return e;if(e["@type"])switch(e["@type"]){case"type.googleapis.com/google.protobuf.Int64Value":case"type.googleapis.com/google.protobuf.UInt64Value":var t=Number(e.value);if(isNaN(t))throw new Error("Data cannot be decoded from JSON: "+e);return t;default:throw new Error("Data cannot be decoded from JSON: "+e)}return Array.isArray(e)?e.map(e=>sj(e)):"function"==typeof e||"object"==typeof e?ij(e,e=>sj(e)):e}const oj="functions",aj={OK:"ok",CANCELLED:"cancelled",UNKNOWN:"unknown",INVALID_ARGUMENT:"invalid-argument",DEADLINE_EXCEEDED:"deadline-exceeded",NOT_FOUND:"not-found",ALREADY_EXISTS:"already-exists",PERMISSION_DENIED:"permission-denied",UNAUTHENTICATED:"unauthenticated",RESOURCE_EXHAUSTED:"resource-exhausted",FAILED_PRECONDITION:"failed-precondition",ABORTED:"aborted",OUT_OF_RANGE:"out-of-range",UNIMPLEMENTED:"unimplemented",INTERNAL:"internal",UNAVAILABLE:"unavailable",DATA_LOSS:"data-loss"};class cj extends gd{constructor(e,t,n){super(`${oj}/${e}`,t||""),this.details=n}}function lj(e,t){let n=function(e){if(200<=e&&e<300)return"ok";switch(e){case 0:return"internal";case 400:return"invalid-argument";case 401:return"unauthenticated";case 403:return"permission-denied";case 404:return"not-found";case 409:return"aborted";case 429:return"resource-exhausted";case 499:return"cancelled";case 500:return"internal";case 501:return"unimplemented";case 503:return"unavailable";case 504:return"deadline-exceeded"}return"unknown"}(e),r=n,i=void 0;try{var s=t&&t.error;if(s){const e=s.status;if("string"==typeof e){if(!aj[e])return new cj("internal","internal");n=aj[e],r=e}var o=s.message;"string"==typeof o&&(r=o),i=s.details,void 0!==i&&(i=sj(i))}}catch(e){}return"ok"===n?null:new cj(n,r,i)}class uj{constructor(e,t,n){this.auth=null,this.messaging=null,this.appCheck=null,this.auth=e.getImmediate({optional:!0}),this.messaging=t.getImmediate({optional:!0}),this.auth||e.get().then(e=>this.auth=e,()=>{}),this.messaging||t.get().then(e=>this.messaging=e,()=>{}),this.appCheck||n.get().then(e=>this.appCheck=e,()=>{})}async getAuthToken(){if(this.auth)try{var e=await this.auth.getToken();return null==e?void 0:e.accessToken}catch(e){return}}async getMessagingToken(){if(this.messaging&&"Notification"in self&&"granted"===Notification.permission)try{return this.messaging.getToken()}catch(e){return}}async getAppCheckToken(){if(this.appCheck){var e=await this.appCheck.getToken();return e.error?null:e.token}return null}async getContext(){return{authToken:await this.getAuthToken(),messagingToken:await this.getMessagingToken(),appCheckToken:await this.getAppCheckToken()}}}const hj="us-central1";class dj{constructor(e,t,n,r,i=hj,s){this.app=e,this.fetchImpl=s,this.emulatorOrigin=null,this.contextProvider=new uj(t,n,r),this.cancelAllRequests=new Promise(e=>{this.deleteService=()=>Promise.resolve(e())});try{var o=new URL(i);this.customDomain=o.origin,this.region=hj}catch(e){this.customDomain=null,this.region=i}}_delete(){return this.deleteService()}_url(e){var t=this.app.options.projectId;return null===this.emulatorOrigin?null!==this.customDomain?`${this.customDomain}/${e}`:`https://${this.region}-${t}.cloudfunctions.net/${e}`:`${this.emulatorOrigin}/${t}/${this.region}/${e}`}}function pj(t,n,r){return e=>async function(e,t,n,r){const i=e._url(t),s={data:n=function t(e){if(null==e)return null;if("number"==typeof(e=e instanceof Number?e.valueOf():e)&&isFinite(e))return e;if(!0===e||!1===e)return e;if("[object String]"===Object.prototype.toString.call(e))return e;if(e instanceof Date)return e.toISOString();if(Array.isArray(e))return e.map(e=>t(e));if("function"==typeof e||"object"==typeof e)return ij(e,e=>t(e));throw new Error("Data cannot be encoded in JSON: "+e)}(n)},o={},a=await e.contextProvider.getContext();a.authToken&&(o.Authorization="Bearer "+a.authToken);a.messagingToken&&(o["Firebase-Instance-ID-Token"]=a.messagingToken);null!==a.appCheckToken&&(o["X-Firebase-AppCheck"]=a.appCheckToken);const c=r.timeout||7e4,l=function(n){let r=null;return{promise:new Promise((e,t)=>{r=setTimeout(()=>{t(new cj("deadline-exceeded","deadline-exceeded"))},n)}),cancel:()=>{r&&clearTimeout(r)}}}(c),u=await Promise.race([async function(e,t,n,r){n["Content-Type"]="application/json";let i;try{i=await r(e,{method:"POST",body:JSON.stringify(t),headers:n})}catch(e){return{status:0,json:null}}let s=null;try{s=await i.json()}catch(e){}return{status:i.status,json:s}}(i,s,o,e.fetchImpl),l.promise,e.cancelAllRequests]);if(l.cancel(),!u)throw new cj("cancelled","Firebase Functions instance was deleted.");var h=lj(u.status,u.json);if(h)throw h;if(!u.json)throw new cj("internal","Response is not valid JSON object.");let d=u.json.data;void 0===d&&(d=u.json.result);if(void 0===d)throw new cj("internal","Response is missing data field.");h=sj(d);return{data:h}}(t,n,e,r||{})}const fj="@firebase/functions";function gj(e,t,n){zd(e).emulatorOrigin=`http://${t}:${n}`}dF=fetch.bind(self),hp(new Kd(oj,(e,{instanceIdentifier:t})=>{var n=e.getProvider("app").getImmediate(),r=e.getProvider("auth-internal"),i=e.getProvider("messaging-internal"),s=e.getProvider("app-check-internal");return new dj(n,r,i,s,t,dF)},"PUBLIC").setMultipleInstances(!0)),_p(fj,"0.7.8",pF),_p(fj,"0.7.8","esm2017");var mj,vj,yj,_j;class wj{constructor(e,t){this.app=e,this._delegate=t,this._region=this._delegate.region,this._customDomain=this._delegate.customDomain}httpsCallable(e,t){return pj(zd(this._delegate),e,t)}useFunctionsEmulator(e){var t=e.match("[a-zA-Z]+://([a-zA-Z0-9.-]+)(?::([0-9]+))?");if(null==t)throw new gd("functions","No origin provided to useFunctionsEmulator()");if(null==t[2])throw new gd("functions","Port missing in origin provided to useFunctionsEmulator()");return gj(this._delegate,t[1],Number(t[2]))}useEmulator(e,t){return gj(this._delegate,e,t)}}const bj="us-central1",Ij=(e,{instanceIdentifier:t})=>{var n=e.getProvider("app-compat").getImmediate(),r=e.getProvider("functions").getImmediate({identifier:null!=t?t:bj});return new wj(n,r)};mj={Functions:wj},Cp.INTERNAL.registerComponent(new Kd("functions-compat",Ij,"PUBLIC").setServiceProps(mj).setMultipleInstances(!0)),Cp.registerVersion("@firebase/functions-compat","0.1.9");const Tj="/firebase-messaging-sw.js",Ej="/firebase-cloud-messaging-push-scope",kj="BDOU99-h67HcA6JeFXHbSNMu7e2yNNu3RzoMj8TM4W88jITfq7ZmPvIM1Iv-4_l2LxQcYwhqby2xGpWwzjfAnG4",Sj="https://fcmregistrations.googleapis.com/v1",Cj="google.c.a.c_id",Aj="google.c.a.e";function Nj(e){var t=new Uint8Array(e);const n=btoa(String.fromCharCode(...t));return n.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}(yt=FB=FB||{})[yt.DATA_MESSAGE=1]="DATA_MESSAGE",yt[yt.DISPLAY_NOTIFICATION=3]="DISPLAY_NOTIFICATION",(yt=vj=vj||{}).PUSH_RECEIVED="push-received",yt.NOTIFICATION_CLICKED="notification-clicked";const Rj="fcm_token_details_db",Pj="fcm_token_object_Store";async function xj(s){if("databases"in indexedDB){const t=await indexedDB.databases(),n=t.map(e=>e.name);if(!n.includes(Rj))return null}let o=null;const e=await qp(Rj,5,async e=>{var t;if(!(e.oldVersion<2)&&e.objectStoreNames.contains(Pj)){const i=e.transaction.objectStore(Pj);var n,r=await i.index("fcmSenderId").get(s);await i.clear(),r&&(2===e.oldVersion?(n=r).auth&&n.p256dh&&n.endpoint&&(o={token:n.fcmToken,createTime:null!==(t=n.createTime)&&void 0!==t?t:Date.now(),subscriptionOptions:{auth:n.auth,p256dh:n.p256dh,endpoint:n.endpoint,swScope:n.swScope,vapidKey:"string"==typeof n.vapidKey?n.vapidKey:Nj(n.vapidKey)}}):3===e.oldVersion?(n=r,o={token:n.fcmToken,createTime:n.createTime,subscriptionOptions:{auth:Nj(n.auth),p256dh:Nj(n.p256dh),endpoint:n.endpoint,swScope:n.swScope,vapidKey:Nj(n.vapidKey)}}):4===e.oldVersion&&(r=r,o={token:r.fcmToken,createTime:r.createTime,subscriptionOptions:{auth:Nj(r.auth),p256dh:Nj(r.p256dh),endpoint:r.endpoint,swScope:r.swScope,vapidKey:Nj(r.vapidKey)}}))}});return e.close(),await Vp(Rj),await Vp("fcm_vapid_details_db"),await Vp("undefined"),function(e){if(!e||!e.subscriptionOptions)return!1;var t=e["subscriptionOptions"];return"number"==typeof e.createTime&&0<e.createTime&&"string"==typeof e.token&&0<e.token.length&&"string"==typeof t.auth&&0<t.auth.length&&"string"==typeof t.p256dh&&0<t.p256dh.length&&"string"==typeof t.endpoint&&0<t.endpoint.length&&"string"==typeof t.swScope&&0<t.swScope.length&&"string"==typeof t.vapidKey&&0<t.vapidKey.length}(o)?o:null}const Oj="firebase-messaging-database",Dj=1,Lj="firebase-messaging-store";let Mj=null;function Fj(){return Mj=Mj||qp(Oj,Dj,e=>{0===e.oldVersion&&e.createObjectStore(Lj)}),Mj}async function Uj(e){var t=qj(e);const n=await Fj();t=await n.transaction(Lj).objectStore(Lj).get(t);if(t)return t;t=await xj(e.appConfig.senderId);return t?(await jj(e,t),t):void 0}async function jj(e,t){var n=qj(e);const r=await Fj(),i=r.transaction(Lj,"readwrite");return await i.objectStore(Lj).put(t,n),await i.complete,t}function qj({appConfig:e}){return e.appId}const Vj=new md("messaging","Messaging",{"missing-app-config-values":'Missing App configuration value: "{$valueName}"',"only-available-in-window":"This method is available in a Window context.","only-available-in-sw":"This method is available in a service worker context.","permission-default":"The notification permission was not granted and dismissed instead.","permission-blocked":"The notification permission was not granted and blocked instead.","unsupported-browser":"This browser doesn't support the API's required to use the Firebase SDK.","indexed-db-unsupported":"This browser doesn't support indexedDb.open() (ex. Safari iFrame, Firefox Private Browsing, etc)","failed-service-worker-registration":"We are unable to register the default service worker. {$browserErrorMessage}","token-subscribe-failed":"A problem occurred while subscribing the user to FCM: {$errorInfo}","token-subscribe-no-token":"FCM returned no token when subscribing the user to push.","token-unsubscribe-failed":"A problem occurred while unsubscribing the user from FCM: {$errorInfo}","token-update-failed":"A problem occurred while updating the user from FCM: {$errorInfo}","token-update-no-token":"FCM returned no token when updating the user to push.","use-sw-after-get-token":"The useServiceWorker() method may only be called once and must be called before calling getToken() to ensure your service worker is used.","invalid-sw-registration":"The input to useServiceWorker() must be a ServiceWorkerRegistration.","invalid-bg-handler":"The input to setBackgroundMessageHandler() must be a function.","invalid-vapid-key":"The public VAPID key must be a string.","use-vapid-key-after-get-token":"The usePublicVapidKey() method may only be called once and must be called before calling getToken() to ensure your VAPID key is used."});async function Bj(e,t){var n={method:"DELETE",headers:await zj(e)};try{const s=await fetch(`${Wj(e.appConfig)}/${t}`,n);var r=await s.json();if(r.error){var i=r.error.message;throw Vj.create("token-unsubscribe-failed",{errorInfo:i})}}catch(e){throw Vj.create("token-unsubscribe-failed",{errorInfo:e})}}function Wj({projectId:e}){return`${Sj}/projects/${e}/registrations`}async function zj({appConfig:e,installations:t}){var n=await t.getToken();return new Headers({"Content-Type":"application/json",Accept:"application/json","x-goog-api-key":e.apiKey,"x-goog-firebase-installations-auth":`FIS ${n}`})}function Kj({p256dh:e,auth:t,endpoint:n,vapidKey:r}){const i={web:{endpoint:n,auth:t,p256dh:e}};return r!==kj&&(i.web.applicationPubKey=r),i}const $j=6048e5;async function Hj(e){const t=await async function(e,t){var n=await e.pushManager.getSubscription();if(n)return n;return e.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:function(e){var t=(e+"=".repeat((4-e.length%4)%4)).replace(/\-/g,"+").replace(/_/g,"/");const n=atob(t),r=new Uint8Array(n.length);for(let i=0;i<n.length;++i)r[i]=n.charCodeAt(i);return r}(t)})}(e.swRegistration,e.vapidKey);var n,r,i,s,o,a={vapidKey:e.vapidKey,swScope:e.swRegistration.scope,endpoint:t.endpoint,auth:Nj(t.getKey("auth")),p256dh:Nj(t.getKey("p256dh"))},c=await Uj(e.firebaseDependencies);if(c){if(n=c.subscriptionOptions,r=a.vapidKey===n.vapidKey,i=a.endpoint===n.endpoint,s=a.auth===n.auth,o=a.p256dh===n.p256dh,r&&i&&s&&o)return Date.now()>=c.createTime+$j?async function(t,e){try{var n=await async function(e,t){var n=await zj(e),r=Kj(t.subscriptionOptions),r={method:"PATCH",headers:n,body:JSON.stringify(r)};let i;try{const s=await fetch(`${Wj(e.appConfig)}/${t.token}`,r);i=await s.json()}catch(e){throw Vj.create("token-update-failed",{errorInfo:e})}if(i.error){r=i.error.message;throw Vj.create("token-update-failed",{errorInfo:r})}if(!i.token)throw Vj.create("token-update-no-token");return i.token}(t.firebaseDependencies,e),r=Object.assign(Object.assign({},e),{token:n,createTime:Date.now()});return await jj(t.firebaseDependencies,r),n}catch(e){throw await Gj(t),e}}(e,{token:c.token,createTime:Date.now(),subscriptionOptions:a}):c.token;try{await Bj(e.firebaseDependencies,c.token)}catch(e){console.warn(e)}return Qj(e.firebaseDependencies,a)}return Qj(e.firebaseDependencies,a)}async function Gj(e){var t=await Uj(e.firebaseDependencies);t&&(await Bj(e.firebaseDependencies,t.token),await async function(e){var t=qj(e);const n=await Fj(),r=n.transaction(Lj,"readwrite");await r.objectStore(Lj).delete(t),await r.complete}(e.firebaseDependencies));const n=await e.swRegistration.pushManager.getSubscription();return!n||n.unsubscribe()}async function Qj(e,t){var n={token:await async function(e,t){var n=await zj(e),r=Kj(t),r={method:"POST",headers:n,body:JSON.stringify(r)};let i;try{const s=await fetch(Wj(e.appConfig),r);i=await s.json()}catch(e){throw Vj.create("token-subscribe-failed",{errorInfo:e})}if(i.error){r=i.error.message;throw Vj.create("token-subscribe-failed",{errorInfo:r})}if(!i.token)throw Vj.create("token-subscribe-no-token");return i.token}(e,t),createTime:Date.now(),subscriptionOptions:t};return await jj(e,n),n.token}function Yj(e){var t,n,r,i={from:e.from,collapseKey:e.collapse_key,messageId:e.fcmMessageId};return n=i,(t=e).notification&&(n.notification={},(r=t.notification.title)&&(n.notification.title=r),(r=t.notification.body)&&(n.notification.body=r),(r=t.notification.image)&&(n.notification.image=r)),t=i,(n=e).data&&(t.data=n.data),n=i,(e=e).fcmOptions&&(n.fcmOptions={},(r=e.fcmOptions.link)&&(n.fcmOptions.link=r),(r=e.fcmOptions.analytics_label)&&(n.fcmOptions.analyticsLabel=r)),i}function Xj(e,t){const n=[];for(let r=0;r<e.length;r++)n.push(e.charAt(r)),r<t.length&&n.push(t.charAt(r));return n.join("")}function Jj(e){return Vj.create("missing-app-config-values",{valueName:e})}Xj("hts/frbslgigp.ogepscmv/ieo/eaylg","tp:/ieaeogn-agolai.o/1frlglgc/o"),Xj("AzSCbw63g1R0nCw85jG8","Iaya3yLKwmgvh7cF0q4");class Zj{constructor(e,t,n){this.deliveryMetricsExportedToBigQueryEnabled=!1,this.onBackgroundMessageHandler=null,this.onMessageHandler=null,this.logEvents=[],this.isLogServiceStarted=!1;var r=function(e){if(!e||!e.options)throw Jj("App Configuration Object");if(!e.name)throw Jj("App Name");var t=e["options"];for(const n of["projectId","apiKey","appId","messagingSenderId"])if(!t[n])throw Jj(n);return{appName:e.name,projectId:t.projectId,apiKey:t.apiKey,appId:t.appId,senderId:t.messagingSenderId}}(e);this.firebaseDependencies={app:e,appConfig:r,installations:t,analyticsProvider:n}}_delete(){return Promise.resolve()}}async function eq(e){try{e.swRegistration=await navigator.serviceWorker.register(Tj,{scope:Ej}),e.swRegistration.update().catch(()=>{})}catch(e){throw Vj.create("failed-service-worker-registration",{browserErrorMessage:e.message})}}async function tq(e,t){if(!navigator)throw Vj.create("only-available-in-window");if("default"===Notification.permission&&await Notification.requestPermission(),"granted"!==Notification.permission)throw Vj.create("permission-blocked");var n,r;return n=e,await((r=null==t?void 0:t.vapidKey)?n.vapidKey=r:n.vapidKey||(n.vapidKey=kj)),await async function(e,t){if(t||e.swRegistration||await eq(e),t||!e.swRegistration){if(!(t instanceof ServiceWorkerRegistration))throw Vj.create("invalid-sw-registration");e.swRegistration=t}}(e,null==t?void 0:t.serviceWorkerRegistration),Hj(e)}async function nq(e,t,n){var r=function(e){switch(e){case vj.NOTIFICATION_CLICKED:return"notification_open";case vj.PUSH_RECEIVED:return"notification_foreground";default:throw new Error}}(t);const i=await e.firebaseDependencies.analyticsProvider.get();i.logEvent(r,{message_id:n[Cj],message_name:n["google.c.a.c_l"],message_time:n["google.c.a.ts"],message_device_time:Math.floor(Date.now()/1e3)})}async function rq(e,t){var n,r=t.data;r.isFirebaseMessaging&&(e.onMessageHandler&&r.messageType===vj.PUSH_RECEIVED&&("function"==typeof e.onMessageHandler?e.onMessageHandler(Yj(r)):e.onMessageHandler.next(Yj(r))),n=r.data,"object"==typeof(t=n)&&t&&Cj in t&&"1"===n[Aj]&&await nq(e,r.messageType,n))}const iq="@firebase/messaging",sq=e=>{const t=new Zj(e.getProvider("app").getImmediate(),e.getProvider("installations-internal").getImmediate(),e.getProvider("analytics-internal"));return navigator.serviceWorker.addEventListener("message",e=>rq(t,e)),t},oq=e=>{const t=e.getProvider("messaging").getImmediate();return{getToken:e=>tq(t,e)}};function aq(e){return async function(e){if(!navigator)throw Vj.create("only-available-in-window");return e.swRegistration||await eq(e),Gj(e)}(e=zd(e))}function cq(e,t){return function(e,t){if(!navigator)throw Vj.create("only-available-in-window");return e.onMessageHandler=t,()=>{e.onMessageHandler=null}}(e=zd(e),t)}hp(new Kd("messaging",sq,"PUBLIC")),hp(new Kd("messaging-internal",oq,"PRIVATE")),_p(iq,"0.9.8"),_p(iq,"0.9.8","esm2017");const lq="BDOU99-h67HcA6JeFXHbSNMu7e2yNNu3RzoMj8TM4W88jITfq7ZmPvIM1Iv-4_l2LxQcYwhqby2xGpWwzjfAnG4",uq="https://fcmregistrations.googleapis.com/v1",hq="FCM_MSG",dq="google.c.a.c_id",pq=3,fq=1;function gq(e){var t=new Uint8Array(e);const n=btoa(String.fromCharCode(...t));return n.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}(yt=yj=yj||{})[yt.DATA_MESSAGE=1]="DATA_MESSAGE",yt[yt.DISPLAY_NOTIFICATION=3]="DISPLAY_NOTIFICATION",(c=_j=_j||{}).PUSH_RECEIVED="push-received",c.NOTIFICATION_CLICKED="notification-clicked";const mq="fcm_token_details_db",vq="fcm_token_object_Store";async function yq(s){if("databases"in indexedDB){const t=await indexedDB.databases(),n=t.map(e=>e.name);if(!n.includes(mq))return null}let o=null;const e=await qp(mq,5,async e=>{var t;if(!(e.oldVersion<2)&&e.objectStoreNames.contains(vq)){const i=e.transaction.objectStore(vq);var n,r=await i.index("fcmSenderId").get(s);await i.clear(),r&&(2===e.oldVersion?(n=r).auth&&n.p256dh&&n.endpoint&&(o={token:n.fcmToken,createTime:null!==(t=n.createTime)&&void 0!==t?t:Date.now(),subscriptionOptions:{auth:n.auth,p256dh:n.p256dh,endpoint:n.endpoint,swScope:n.swScope,vapidKey:"string"==typeof n.vapidKey?n.vapidKey:gq(n.vapidKey)}}):3===e.oldVersion?(n=r,o={token:n.fcmToken,createTime:n.createTime,subscriptionOptions:{auth:gq(n.auth),p256dh:gq(n.p256dh),endpoint:n.endpoint,swScope:n.swScope,vapidKey:gq(n.vapidKey)}}):4===e.oldVersion&&(r=r,o={token:r.fcmToken,createTime:r.createTime,subscriptionOptions:{auth:gq(r.auth),p256dh:gq(r.p256dh),endpoint:r.endpoint,swScope:r.swScope,vapidKey:gq(r.vapidKey)}}))}});return e.close(),await Vp(mq),await Vp("fcm_vapid_details_db"),await Vp("undefined"),function(e){if(!e||!e.subscriptionOptions)return!1;var t=e["subscriptionOptions"];return"number"==typeof e.createTime&&0<e.createTime&&"string"==typeof e.token&&0<e.token.length&&"string"==typeof t.auth&&0<t.auth.length&&"string"==typeof t.p256dh&&0<t.p256dh.length&&"string"==typeof t.endpoint&&0<t.endpoint.length&&"string"==typeof t.swScope&&0<t.swScope.length&&"string"==typeof t.vapidKey&&0<t.vapidKey.length}(o)?o:null}const _q="firebase-messaging-database",wq=1,bq="firebase-messaging-store";let Iq=null;function Tq(){return Iq=Iq||qp(_q,wq,e=>{0===e.oldVersion&&e.createObjectStore(bq)}),Iq}async function Eq(e){var t=Sq(e);const n=await Tq();t=await n.transaction(bq).objectStore(bq).get(t);if(t)return t;t=await yq(e.appConfig.senderId);return t?(await kq(e,t),t):void 0}async function kq(e,t){var n=Sq(e);const r=await Tq(),i=r.transaction(bq,"readwrite");return await i.objectStore(bq).put(t,n),await i.complete,t}function Sq({appConfig:e}){return e.appId}const Cq=new md("messaging","Messaging",{"missing-app-config-values":'Missing App configuration value: "{$valueName}"',"only-available-in-window":"This method is available in a Window context.","only-available-in-sw":"This method is available in a service worker context.","permission-default":"The notification permission was not granted and dismissed instead.","permission-blocked":"The notification permission was not granted and blocked instead.","unsupported-browser":"This browser doesn't support the API's required to use the Firebase SDK.","indexed-db-unsupported":"This browser doesn't support indexedDb.open() (ex. Safari iFrame, Firefox Private Browsing, etc)","failed-service-worker-registration":"We are unable to register the default service worker. {$browserErrorMessage}","token-subscribe-failed":"A problem occurred while subscribing the user to FCM: {$errorInfo}","token-subscribe-no-token":"FCM returned no token when subscribing the user to push.","token-unsubscribe-failed":"A problem occurred while unsubscribing the user from FCM: {$errorInfo}","token-update-failed":"A problem occurred while updating the user from FCM: {$errorInfo}","token-update-no-token":"FCM returned no token when updating the user to push.","use-sw-after-get-token":"The useServiceWorker() method may only be called once and must be called before calling getToken() to ensure your service worker is used.","invalid-sw-registration":"The input to useServiceWorker() must be a ServiceWorkerRegistration.","invalid-bg-handler":"The input to setBackgroundMessageHandler() must be a function.","invalid-vapid-key":"The public VAPID key must be a string.","use-vapid-key-after-get-token":"The usePublicVapidKey() method may only be called once and must be called before calling getToken() to ensure your VAPID key is used."});async function Aq(e,t){var n={method:"DELETE",headers:await Rq(e)};try{const s=await fetch(`${Nq(e.appConfig)}/${t}`,n);var r=await s.json();if(r.error){var i=r.error.message;throw Cq.create("token-unsubscribe-failed",{errorInfo:i})}}catch(e){throw Cq.create("token-unsubscribe-failed",{errorInfo:e})}}function Nq({projectId:e}){return`${uq}/projects/${e}/registrations`}async function Rq({appConfig:e,installations:t}){var n=await t.getToken();return new Headers({"Content-Type":"application/json",Accept:"application/json","x-goog-api-key":e.apiKey,"x-goog-firebase-installations-auth":`FIS ${n}`})}function Pq({p256dh:e,auth:t,endpoint:n,vapidKey:r}){const i={web:{endpoint:n,auth:t,p256dh:e}};return r!==lq&&(i.web.applicationPubKey=r),i}async function xq(e){const t=await async function(e,t){var n=await e.pushManager.getSubscription();if(n)return n;return e.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:function(e){var t=(e+"=".repeat((4-e.length%4)%4)).replace(/\-/g,"+").replace(/_/g,"/");const n=atob(t),r=new Uint8Array(n.length);for(let i=0;i<n.length;++i)r[i]=n.charCodeAt(i);return r}(t)})}(e.swRegistration,e.vapidKey);var n,r,i,s,o,a={vapidKey:e.vapidKey,swScope:e.swRegistration.scope,endpoint:t.endpoint,auth:gq(t.getKey("auth")),p256dh:gq(t.getKey("p256dh"))},c=await Eq(e.firebaseDependencies);if(c){if(n=c.subscriptionOptions,r=a.vapidKey===n.vapidKey,i=a.endpoint===n.endpoint,s=a.auth===n.auth,o=a.p256dh===n.p256dh,r&&i&&s&&o)return Date.now()>=c.createTime+6048e5?async function(t,e){try{var n=await async function(e,t){var n=await Rq(e),r=Pq(t.subscriptionOptions),r={method:"PATCH",headers:n,body:JSON.stringify(r)};let i;try{const s=await fetch(`${Nq(e.appConfig)}/${t.token}`,r);i=await s.json()}catch(e){throw Cq.create("token-update-failed",{errorInfo:e})}if(i.error){r=i.error.message;throw Cq.create("token-update-failed",{errorInfo:r})}if(!i.token)throw Cq.create("token-update-no-token");return i.token}(t.firebaseDependencies,e),r=Object.assign(Object.assign({},e),{token:n,createTime:Date.now()});return await kq(t.firebaseDependencies,r),n}catch(e){throw await Oq(t),e}}(e,{token:c.token,createTime:Date.now(),subscriptionOptions:a}):c.token;try{await Aq(e.firebaseDependencies,c.token)}catch(e){console.warn(e)}return Dq(e.firebaseDependencies,a)}return Dq(e.firebaseDependencies,a)}async function Oq(e){var t=await Eq(e.firebaseDependencies);t&&(await Aq(e.firebaseDependencies,t.token),await async function(e){var t=Sq(e);const n=await Tq(),r=n.transaction(bq,"readwrite");await r.objectStore(bq).delete(t),await r.complete}(e.firebaseDependencies));const n=await e.swRegistration.pushManager.getSubscription();return!n||n.unsubscribe()}async function Dq(e,t){var n={token:await async function(e,t){var n=await Rq(e),r=Pq(t),r={method:"POST",headers:n,body:JSON.stringify(r)};let i;try{const s=await fetch(Nq(e.appConfig),r);i=await s.json()}catch(e){throw Cq.create("token-subscribe-failed",{errorInfo:e})}if(i.error){r=i.error.message;throw Cq.create("token-subscribe-failed",{errorInfo:r})}if(!i.token)throw Cq.create("token-subscribe-no-token");return i.token}(e,t),createTime:Date.now(),subscriptionOptions:t};return await kq(e,n),n.token}async function Lq(e,t){var n=function(e,t){var n;const r={};e.from&&(r.project_number=e.from);e.fcmMessageId&&(r.message_id=e.fcmMessageId);r.instance_id=t,e.notification?r.message_type=yj.DISPLAY_NOTIFICATION.toString():r.message_type=yj.DATA_MESSAGE.toString();r.sdk_platform=pq.toString(),r.package_name=self.origin.replace(/(^\w+:|^)\/\//,""),e.collapse_key&&(r.collapse_key=e.collapse_key);r.event=fq.toString(),null!==(n=e.fcmOptions)&&void 0!==n&&n.analytics_label&&(r.analytics_label=null===(n=e.fcmOptions)||void 0===n?void 0:n.analytics_label);return r}(t,await e.firebaseDependencies.installations.getId());!function(e,t){const n={};n.event_time_ms=Math.floor(Date.now()).toString(),n.source_extension_json_proto3=JSON.stringify(t),e.logEvents.push(n)}(e,n)}function Mq(e,t){const n=[];for(let r=0;r<e.length;r++)n.push(e.charAt(r)),r<t.length&&n.push(t.charAt(r));return n.join("")}async function Fq(e,t){var n=function({data:e}){if(!e)return null;try{return e.json()}catch(e){return null}}(e);if(n){t.deliveryMetricsExportedToBigQueryEnabled&&await Lq(t,n);var r,i,s=await jq();if(s.some(e=>"visible"===e.visibilityState&&!e.url.startsWith("chrome-extension://")))return function(e,t){t.isFirebaseMessaging=!0,t.messageType=_j.PUSH_RECEIVED;for(const n of e)n.postMessage(t)}(s,n);n.notification&&await function(e){var t=e["actions"],n=Notification["maxActions"];t&&n&&t.length>n&&console.warn(`This browser only supports ${n} actions. The remaining actions will not be displayed.`);return self.registration.showNotification(null!==(n=e.title)&&void 0!==n?n:"",e)}(function(e){const t=Object.assign({},e.notification);return t.data={[hq]:e},t}(n)),t&&t.onBackgroundMessageHandler&&(s={from:(r=n).from,collapseKey:r.collapse_key,messageId:r.fcmMessageId},n=s,(e=r).notification&&(n.notification={},(i=e.notification.title)&&(n.notification.title=i),(i=e.notification.body)&&(n.notification.body=i),(i=e.notification.image)&&(n.notification.image=i)),e=s,(n=r).data&&(e.data=n.data),n=s,(r=r).fcmOptions&&(n.fcmOptions={},(i=r.fcmOptions.link)&&(n.fcmOptions.link=i),(i=r.fcmOptions.analytics_label)&&(n.fcmOptions.analyticsLabel=i)),s=s,"function"==typeof t.onBackgroundMessageHandler?t.onBackgroundMessageHandler(s):t.onBackgroundMessageHandler.next(s))}}async function Uq(e){const t=null===(s=null===(i=e.notification)||void 0===i?void 0:i.data)||void 0===s?void 0:s[hq];if(t&&!e.action){e.stopImmediatePropagation(),e.notification.close();var n=function(e){var t;var n=null!==(t=null===(t=e.fcmOptions)||void 0===t?void 0:t.link)&&void 0!==t?t:null===(n=e.notification)||void 0===n?void 0:n.click_action;if(n)return n;return function(e){return"object"==typeof e&&e&&dq in e}(e.data)?self.location.origin:null}(t);if(n){var r,i=new URL(n,self.location.href),s=new URL(self.location.origin);if(i.host===s.host){let e=await async function(e){var t=await jq();for(const r of t){var n=new URL(r.url,self.location.href);if(e.host===n.host)return r}return null}(i);if(e?e=await e.focus():(e=await self.clients.openWindow(n),r=3e3,await new Promise(e=>{setTimeout(e,r)})),e)return t.messageType=_j.NOTIFICATION_CLICKED,t.isFirebaseMessaging=!0,e.postMessage(t)}}}}function jq(){return self.clients.matchAll({type:"window",includeUncontrolled:!0})}function qq(e){return Cq.create("missing-app-config-values",{valueName:e})}Mq("hts/frbslgigp.ogepscmv/ieo/eaylg","tp:/ieaeogn-agolai.o/1frlglgc/o"),Mq("AzSCbw63g1R0nCw85jG8","Iaya3yLKwmgvh7cF0q4");class Vq{constructor(e,t,n){this.deliveryMetricsExportedToBigQueryEnabled=!1,this.onBackgroundMessageHandler=null,this.onMessageHandler=null,this.logEvents=[],this.isLogServiceStarted=!1;var r=function(e){if(!e||!e.options)throw qq("App Configuration Object");if(!e.name)throw qq("App Name");var t=e["options"];for(const n of["projectId","apiKey","appId","messagingSenderId"])if(!t[n])throw qq(n);return{appName:e.name,projectId:t.projectId,apiKey:t.apiKey,appId:t.appId,senderId:t.messagingSenderId}}(e);this.firebaseDependencies={app:e,appConfig:r,installations:t,analyticsProvider:n}}_delete(){return Promise.resolve()}}const Bq=e=>{const t=new Vq(e.getProvider("app").getImmediate(),e.getProvider("installations-internal").getImmediate(),e.getProvider("analytics-internal"));return self.addEventListener("push",e=>{e.waitUntil(Fq(e,t))}),self.addEventListener("pushsubscriptionchange",e=>{e.waitUntil(async function(e,t){var n;(n=e["newSubscription"])?(n=await Eq(t.firebaseDependencies),await Oq(t),t.vapidKey=null!==(n=null===(n=null==n?void 0:n.subscriptionOptions)||void 0===n?void 0:n.vapidKey)&&void 0!==n?n:lq,await xq(t)):await Oq(t)}(e,t))}),self.addEventListener("notificationclick",e=>{e.waitUntil(Uq(e))}),t};function Wq(e,t){return function(e,t){if(void 0!==self.document)throw Cq.create("only-available-in-sw");return e.onBackgroundMessageHandler=t,()=>{e.onBackgroundMessageHandler=null}}(e=zd(e),t)}hp(new Kd("messaging-sw",Bq,"PUBLIC"));var zq,Kq,$q;class Hq{constructor(e,t){this.app=e,this._delegate=t,this.app=e,this._delegate=t}async getToken(e){return async function(e,t){return tq(e=zd(e),t)}(this._delegate,e)}async deleteToken(){return aq(this._delegate)}onMessage(e){return cq(this._delegate,e)}onBackgroundMessage(e){return Wq(this._delegate,e)}}const Gq=e=>self&&"ServiceWorkerGlobalScope"in self?new Hq(e.getProvider("app-compat").getImmediate(),e.getProvider("messaging-sw").getImmediate()):new Hq(e.getProvider("app-compat").getImmediate(),e.getProvider("messaging").getImmediate()),Qq={isSupported:function(){return self&&"ServiceWorkerGlobalScope"in self?dd()&&"PushManager"in self&&"Notification"in self&&ServiceWorkerRegistration.prototype.hasOwnProperty("showNotification")&&PushSubscription.prototype.hasOwnProperty("getKey"):"undefined"!=typeof window&&dd()&&fd()&&"serviceWorker"in navigator&&"PushManager"in window&&"Notification"in window&&"fetch"in window&&ServiceWorkerRegistration.prototype.hasOwnProperty("showNotification")&&PushSubscription.prototype.hasOwnProperty("getKey")}};Cp.INTERNAL.registerComponent(new Kd("messaging-compat",Gq,"PUBLIC").setServiceProps(Qq)),Cp.registerVersion("@firebase/messaging-compat","0.1.8");const Yq="firebasestorage.googleapis.com",Xq="storageBucket";class Jq extends gd{constructor(e,t){super(Zq(e),`Firebase Storage: ${t} (${Zq(e)})`),this.customData={serverResponse:null},this._baseMessage=this.message,Object.setPrototypeOf(this,Jq.prototype)}_codeEquals(e){return Zq(e)===this.code}get serverResponse(){return this.customData.serverResponse}set serverResponse(e){this.customData.serverResponse=e,this.customData.serverResponse?this.message=`${this._baseMessage}\n${this.customData.serverResponse}`:this.message=this._baseMessage}}function Zq(e){return"storage/"+e}function eV(){return new Jq("unknown","An unknown error occurred, please check the error payload for server response.")}function tV(){return new Jq("canceled","User canceled the upload/download.")}function nV(){return new Jq("cannot-slice-blob","Cannot slice blob for upload. Please retry the upload.")}function rV(e){return new Jq("invalid-argument",e)}function iV(){return new Jq("app-deleted","The Firebase app was deleted.")}function sV(e){return new Jq("invalid-root-operation","The operation '"+e+"' cannot be performed on a root reference, create a non-root reference using child, such as .child('file.png').")}function oV(e,t){return new Jq("invalid-format","String does not match format '"+e+"': "+t)}function aV(e){throw new Jq("internal-error","Internal error: "+e)}class cV{constructor(e,t){this.bucket=e,this.path_=t}get path(){return this.path_}get isRoot(){return 0===this.path.length}fullServerUrl(){const e=encodeURIComponent;return"/b/"+e(this.bucket)+"/o/"+e(this.path)}bucketOnlyServerUrl(){const e=encodeURIComponent;return"/b/"+e(this.bucket)+"/o"}static makeFromBucketSpec(t,e){let n;try{n=cV.makeFromUrl(t,e)}catch(e){return new cV(t,"")}if(""===n.path)return n;throw t=t,new Jq("invalid-default-bucket","Invalid default bucket '"+t+"'.")}static makeFromUrl(e,t){let n=null;var r="([A-Za-z0-9.\\-_]+)";var i=new RegExp("^gs://"+r+"(/(.*))?$","i");function s(e){e.path_=decodeURIComponent(e.path)}var o=t.replace(/[.]/g,"\\."),a=new RegExp(`^https?://${o}/v[A-Za-z0-9_]+/b/${r}/o(/([^?#]*).*)?$`,"i"),o=t===Yq?"(?:storage.googleapis.com|storage.cloud.google.com)":t,c=[{regex:i,indices:{bucket:1,path:3},postModify:function(e){"/"===e.path.charAt(e.path.length-1)&&(e.path_=e.path_.slice(0,-1))}},{regex:a,indices:{bucket:1,path:3},postModify:s},{regex:new RegExp(`^https?://${o}/${r}/([^?#]*)`,"i"),indices:{bucket:1,path:2},postModify:s}];for(let h=0;h<c.length;h++){const d=c[h];var l=d.regex.exec(e);if(l){var u=l[d.indices.bucket];let e=l[d.indices.path];e=e||"",n=new cV(u,e),d.postModify(n);break}}if(null==n)throw t=e,new Jq("invalid-url","Invalid URL '"+t+"'.");return n}}class lV{constructor(e){this.promise_=Promise.reject(e)}getPromise(){return this.promise_}cancel(e=0){}}function uV(e){return"string"==typeof e||e instanceof String}function hV(e){return dV()&&e instanceof Blob}function dV(){return"undefined"!=typeof Blob}function pV(e,t,n,r){if(r<t)throw rV(`Invalid value for '${e}'. Expected ${t} or greater.`);if(n<r)throw rV(`Invalid value for '${e}'. Expected ${n} or less.`)}function fV(e,t,n){let r=null==n?`https://${t}`:t;return`${n}://${r}/v0${e}`}function gV(e){const t=encodeURIComponent;let n="?";for(const i in e){var r;e.hasOwnProperty(i)&&(r=t(i)+"="+t(e[i]),n=n+r+"&")}return n=n.slice(0,-1),n}(c=zq=zq||{})[c.NO_ERROR=0]="NO_ERROR",c[c.NETWORK_ERROR=1]="NETWORK_ERROR",c[c.ABORT=2]="ABORT";class mV{constructor(e,t,n,r,i,s,o,a,c,l,u){this.url_=e,this.method_=t,this.headers_=n,this.body_=r,this.successCodes_=i,this.additionalRetryCodes_=s,this.callback_=o,this.errorCallback_=a,this.timeout_=c,this.progressCallback_=l,this.connectionFactory_=u,this.pendingConnection_=null,this.backoffId_=null,this.canceled_=!1,this.appDelete_=!1,this.promise_=new Promise((e,t)=>{this.resolve_=e,this.reject_=t,this.start_()})}start_(){var e=(r,e)=>{if(e)r(!1,new vV(!1,null,!0));else{const i=this.connectionFactory_();this.pendingConnection_=i;const s=e=>{var t=e.loaded,n=e.lengthComputable?e.total:-1;null!==this.progressCallback_&&this.progressCallback_(t,n)};null!==this.progressCallback_&&i.addUploadProgressListener(s),i.send(this.url_,this.method_,this.body_,this.headers_).then(()=>{null!==this.progressCallback_&&i.removeUploadProgressListener(s),this.pendingConnection_=null;var e,t=i.getErrorCode()===zq.NO_ERROR,n=i.getStatus();t&&!this.isRetryStatusCode_(n)?(e=-1!==this.successCodes_.indexOf(n),r(!0,new vV(e,i))):(e=i.getErrorCode()===zq.ABORT,r(!1,new vV(!1,null,e)))})}},t=(e,t)=>{const n=this.resolve_,r=this.reject_,i=t.connection;if(t.wasSuccessCode)try{var s=this.callback_(i,i.getResponse());void 0!==s?n(s):n()}catch(e){r(e)}else if(null!==i){const a=eV();a.serverResponse=i.getErrorText(),this.errorCallback_?r(this.errorCallback_(i,a)):r(a)}else{var o;t.canceled?(o=(this.appDelete_?iV:tV)(),r(o)):(o=new Jq("retry-limit-exceeded","Max retry time for operation exceeded, please try again."),r(o))}};this.canceled_?t(0,new vV(!1,null,!0)):this.backoffId_=function(t,n,e){let r=1,i=null,s=null,o=!1,a=0;function c(){return 2===a}let l=!1;function u(...e){l||(l=!0,n.apply(null,e))}function h(e){i=setTimeout(()=>{i=null,t(p,c())},e)}function d(){s&&clearTimeout(s)}function p(t,...n){if(l)d();else{if(t)return d(),void u.call(null,t,...n);if(c()||o)return d(),void u.call(null,t,...n);r<64&&(r*=2);let e;e=1===a?(a=2,0):1e3*(r+Math.random()),h(e)}}let f=!1;function g(e){f||(f=!0,d(),l||(null!==i?(e||(a=2),clearTimeout(i),h(0)):e||(a=1)))}return h(0),s=setTimeout(()=>{g(o=!0)},e),g}(e,t,this.timeout_)}getPromise(){return this.promise_}cancel(e){this.canceled_=!0,this.appDelete_=e||!1,null!==this.backoffId_&&(0,this.backoffId_)(!1),null!==this.pendingConnection_&&this.pendingConnection_.abort()}isRetryStatusCode_(e){var t=500<=e&&e<600,n=-1!==[408,429].indexOf(e),r=-1!==this.additionalRetryCodes_.indexOf(e);return t||n||r}}class vV{constructor(e,t,n){this.wasSuccessCode=e,this.connection=t,this.canceled=!!n}}function yV(...t){const n="undefined"!=typeof BlobBuilder?BlobBuilder:"undefined"!=typeof WebKitBlobBuilder?WebKitBlobBuilder:void 0;if(void 0!==n){const r=new n;for(let e=0;e<t.length;e++)r.append(t[e]);return r.getBlob()}if(dV())return new Blob(t);throw new Jq("unsupported-environment","This browser doesn't seem to support creating Blobs")}const _V={RAW:"raw",BASE64:"base64",BASE64URL:"base64url",DATA_URL:"data_url"};class wV{constructor(e,t){this.data=e,this.contentType=t||null}}function bV(e,t){switch(e){case _V.RAW:return new wV(IV(t));case _V.BASE64:case _V.BASE64URL:return new wV(TV(e,t));case _V.DATA_URL:return new wV((n=t,(r=new EV(n)).base64?TV(_V.BASE64,r.rest):function(e){let t;try{t=decodeURIComponent(e)}catch(e){throw oV(_V.DATA_URL,"Malformed data URL.")}return IV(t)}(r.rest)),(n=t,new EV(n).contentType))}var n,r;throw eV()}function IV(t){const n=[];for(let s=0;s<t.length;s++){let e=t.charCodeAt(s);var r,i;e<=127?n.push(e):e<=2047?n.push(192|e>>6,128|63&e):55296==(64512&e)?s<t.length-1&&56320==(64512&t.charCodeAt(s+1))?(r=e,i=t.charCodeAt(++s),e=65536|(1023&r)<<10|1023&i,n.push(240|e>>18,128|e>>12&63,128|e>>6&63,128|63&e)):n.push(239,191,189):56320==(64512&e)?n.push(239,191,189):n.push(224|e>>12,128|e>>6&63,128|63&e)}return new Uint8Array(n)}function TV(t,e){switch(t){case _V.BASE64:var n=-1!==e.indexOf("-"),r=-1!==e.indexOf("_");if(n||r)throw oV(t,"Invalid character '"+(n?"-":"_")+"' found: is it base64url encoded?");break;case _V.BASE64URL:r=-1!==e.indexOf("+"),n=-1!==e.indexOf("/");if(r||n)throw oV(t,"Invalid character '"+(r?"+":"/")+"' found: is it base64 encoded?");e=e.replace(/-/g,"+").replace(/_/g,"/")}let i;try{i=atob(e)}catch(e){throw oV(t,"Invalid character found")}const s=new Uint8Array(i.length);for(let o=0;o<i.length;o++)s[o]=i.charCodeAt(o);return s}class EV{constructor(e){this.base64=!1,this.contentType=null;var t,n,r=e.match(/^data:([^,]+)?,/);if(null===r)throw oV(_V.DATA_URL,"Must be formatted 'data:[<mediatype>][;base64],<data>");const i=r[1]||null;null!=i&&(this.base64=(t=i,n=";base64",t.length>=n.length&&t.substring(t.length-n.length)===n),this.contentType=this.base64?i.substring(0,i.length-";base64".length):i),this.rest=e.substring(e.indexOf(",")+1)}}class kV{constructor(e,t){let n=0,r="";hV(e)?(this.data_=e,n=e.size,r=e.type):e instanceof ArrayBuffer?(t?this.data_=new Uint8Array(e):(this.data_=new Uint8Array(e.byteLength),this.data_.set(new Uint8Array(e))),n=this.data_.length):e instanceof Uint8Array&&(t?this.data_=e:(this.data_=new Uint8Array(e.length),this.data_.set(e)),n=e.length),this.size_=n,this.type_=r}size(){return this.size_}type(){return this.type_}slice(e,t){if(hV(this.data_)){var n=this.data_,n=(i=e,s=t,(r=n).webkitSlice?r.webkitSlice(i,s):r.mozSlice?r.mozSlice(i,s):r.slice?r.slice(i,s):null);return null===n?null:new kV(n)}var r,i,s,n=new Uint8Array(this.data_.buffer,e,t-e);return new kV(n,!0)}static getBlob(...e){if(dV()){var t=e.map(e=>e instanceof kV?e.data_:e);return new kV(yV.apply(null,t))}{const r=e.map(e=>uV(e)?bV(_V.RAW,e).data:e.data_);let t=0;r.forEach(e=>{t+=e.byteLength});const i=new Uint8Array(t);let n=0;return r.forEach(e=>{for(let t=0;t<e.length;t++)i[n++]=e[t]}),new kV(i,!0)}}uploadData(){return this.data_}}function SV(e){let t;try{t=JSON.parse(e)}catch(e){return null}return"object"!=typeof(e=t)||Array.isArray(e)?null:t}function CV(e){var t=e.lastIndexOf("/",e.length-2);return-1===t?e:e.slice(t+1)}function AV(e,t){return t}class NV{constructor(e,t,n,r){this.server=e,this.local=t||e,this.writable=!!n,this.xform=r||AV}}let RV=null;function PV(){if(RV)return RV;const e=[];e.push(new NV("bucket")),e.push(new NV("generation")),e.push(new NV("metageneration")),e.push(new NV("name","fullPath",!0));const t=new NV("name");t.xform=function(e,t){return!uV(t=t)||t.length<2?t:CV(t)},e.push(t);const n=new NV("size");return n.xform=function(e,t){return void 0!==t?Number(t):t},e.push(n),e.push(new NV("timeCreated")),e.push(new NV("updated")),e.push(new NV("md5Hash",null,!0)),e.push(new NV("cacheControl",null,!0)),e.push(new NV("contentDisposition",null,!0)),e.push(new NV("contentEncoding",null,!0)),e.push(new NV("contentLanguage",null,!0)),e.push(new NV("contentType",null,!0)),e.push(new NV("metadata","customMetadata",!0)),RV=e,RV}function xV(n,r){Object.defineProperty(n,"ref",{get:function(){var e=n.bucket,t=n.fullPath,t=new cV(e,t);return r._makeStorageReference(t)}})}function OV(e,t,n){var r=SV(t);return null===r?null:function(e,t,n){const r={type:"file"};var i=n.length;for(let s=0;s<i;s++){const o=n[s];r[o.local]=o.xform(r,t[o.server])}return xV(r,e),r}(e,r,n)}function DV(e,t){const n={};var r=t.length;for(let s=0;s<r;s++){var i=t[s];i.writable&&(n[i.server]=e[i.local])}return JSON.stringify(n)}function LV(e,t,n){var r=SV(n);return null===r?null:function(e,t,n){const r={prefixes:[],items:[],nextPageToken:n.nextPageToken};if(n.prefixes)for(const o of n.prefixes){var i=o.replace(/\/$/,""),i=e._makeStorageReference(new cV(t,i));r.prefixes.push(i)}if(n.items)for(const a of n.items){var s=e._makeStorageReference(new cV(t,a.name));r.items.push(s)}return r}(e,t,r)}class MV{constructor(e,t,n,r){this.url=e,this.method=t,this.handler=n,this.timeout=r,this.urlParams={},this.headers={},this.body=null,this.errorHandler=null,this.progressCallback=null,this.successCodes=[200],this.additionalRetryCodes=[]}}function FV(e){if(!e)throw eV()}function UV(r,i){return function(e,t){var n=OV(r,t,i);return FV(null!==n),n}}function jV(r,i){return function(e,t){var n=LV(r,i,t);return FV(null!==n),n}}function qV(r,i){return function(e,t){var n=OV(r,t,i);return FV(null!==n),function(r,e,i,s){var t=SV(e);if(null===t)return null;if(!uV(t.downloadTokens))return null;const n=t.downloadTokens;if(0===n.length)return null;const o=encodeURIComponent,a=n.split(",");return a.map(e=>{var t=r.bucket,n=r.fullPath;return fV("/b/"+o(t)+"/o/"+o(n),i,s)+gV({alt:"media",token:e})})[0]}(n,t,r.host,r._protocol)}}function VV(i){return function(e,t){let n;var r;return n=401===e.getStatus()?e.getErrorText().includes("Firebase App Check token is invalid")?new Jq("unauthorized-app","This app does not have permission to access Firebase Storage on this project."):new Jq("unauthenticated","User is not authenticated, please authenticate using Firebase Authentication and try again."):402===e.getStatus()?(r=i.bucket,new Jq("quota-exceeded","Quota for bucket '"+r+"' exceeded, please view quota on https://firebase.google.com/pricing/.")):403===e.getStatus()?(e=i.path,new Jq("unauthorized","User does not have permission to access '"+e+"'.")):t,n.serverResponse=t.serverResponse,n}}function BV(r){const i=VV(r);return function(e,t){let n=i(e,t);return 404===e.getStatus()&&(n=(e=r.path,new Jq("object-not-found","Object '"+e+"' does not exist."))),n.serverResponse=t.serverResponse,n}}function WV(e,t,n){var r=fV(t.fullServerUrl(),e.host,e._protocol),i=e.maxOperationRetryTime;const s=new MV(r,"GET",UV(e,n),i);return s.errorHandler=BV(t),s}function zV(e,t,n){const r=Object.assign({},n);return r.fullPath=e.path,r.size=t.size(),r.contentType||(r.contentType=(e=t,(t=null)&&t.contentType||e&&e.type()||"application/octet-stream")),r}function KV(e,t,n,r,i){var s=t.bucketOnlyServerUrl();const o={"X-Goog-Upload-Protocol":"multipart"};var a=function(){let e="";for(let t=0;t<2;t++)e+=Math.random().toString().slice(2);return e}();o["Content-Type"]="multipart/related; boundary="+a;var c=zV(t,r,i),l="--"+a+"\r\nContent-Type: application/json; charset=utf-8\r\n\r\n"+DV(c,n)+"\r\n--"+a+"\r\nContent-Type: "+c.contentType+"\r\n\r\n",a="\r\n--"+a+"--";const u=kV.getBlob(l,r,a);if(null===u)throw nV();a={name:c.fullPath},c=fV(s,e.host,e._protocol),s=e.maxUploadRetryTime;const h=new MV(c,"POST",UV(e,n),s);return h.urlParams=a,h.headers=o,h.body=u.uploadData(),h.errorHandler=VV(t),h}class $V{constructor(e,t,n,r){this.current=e,this.total=t,this.finalized=!!n,this.metadata=r||null}}function HV(e,t){let n=null;try{n=e.getResponseHeader("X-Goog-Upload-Status")}catch(e){FV(!1)}const r=t||["active"];return FV(!!n&&-1!==r.indexOf(n)),n}function GV(e,t,n,r,i){var s=t.bucketOnlyServerUrl(),o=zV(t,r,i),a={name:o.fullPath},c=fV(s,e.host,e._protocol),l={"X-Goog-Upload-Protocol":"resumable","X-Goog-Upload-Command":"start","X-Goog-Upload-Header-Content-Length":`${r.size()}`,"X-Goog-Upload-Header-Content-Type":o.contentType,"Content-Type":"application/json; charset=utf-8"},s=DV(o,n),o=e.maxUploadRetryTime;const u=new MV(c,"POST",function(e){HV(e);let t;try{t=e.getResponseHeader("X-Goog-Upload-URL")}catch(e){FV(!1)}return FV(uV(t)),t},o);return u.urlParams=a,u.headers=l,u.body=s,u.errorHandler=VV(t),u}function QV(e,t,n,i){var r=e.maxUploadRetryTime;const s=new MV(n,"POST",function(e){var t=HV(e,["active","final"]);let n=null;try{n=e.getResponseHeader("X-Goog-Upload-Size-Received")}catch(e){FV(!1)}n||FV(!1);var r=Number(n);return FV(!isNaN(r)),new $V(r,i.size(),"final"===t)},r);return s.headers={"X-Goog-Upload-Command":"query"},s.errorHandler=VV(t),s}function YV(e,o,t,a,n,c,r,i){const l=new $V(0,0);if(r?(l.current=r.current,l.total=r.total):(l.current=0,l.total=a.size()),a.size()!==l.total)throw new Jq("server-file-wrong-size","Server recorded incorrect upload file size, please retry the upload.");var s=l.total-l.current;let u=s;0<n&&(u=Math.min(u,n));var h=l.current,d=h+u,s={"X-Goog-Upload-Command":u===s?"upload, finalize":"upload","X-Goog-Upload-Offset":`${l.current}`};const p=a.slice(h,d);if(null===p)throw nV();d=o.maxUploadRetryTime;const f=new MV(t,"POST",function(e,t){var n=HV(e,["active","final"]),r=l.current+u,i=a.size();let s;return s="final"===n?UV(o,c)(e,t):null,new $V(r,i,"final"===n,s)},d);return f.headers=s,f.body=p.uploadData(),f.progressCallback=i||null,f.errorHandler=VV(e),f}const XV={STATE_CHANGED:"state_changed"},JV={RUNNING:"running",PAUSED:"paused",SUCCESS:"success",CANCELED:"canceled",ERROR:"error"};function ZV(e){switch(e){case"running":case"pausing":case"canceling":return JV.RUNNING;case"paused":return JV.PAUSED;case"success":return JV.SUCCESS;case"canceled":return JV.CANCELED;default:return JV.ERROR}}class eB{constructor(e,t,n){var r;"function"==typeof e||null!=t||null!=n?(this.next=e,this.error=null!=t?t:void 0,this.complete=null!=n?n:void 0):(this.next=(r=e).next,this.error=r.error,this.complete=r.complete)}}function tB(t){return(...e)=>{Promise.resolve().then(()=>t(...e))}}class nB extends class{constructor(){this.sent_=!1,this.xhr_=new XMLHttpRequest,this.initXhr(),this.errorCode_=zq.NO_ERROR,this.sendPromise_=new Promise(e=>{this.xhr_.addEventListener("abort",()=>{this.errorCode_=zq.ABORT,e()}),this.xhr_.addEventListener("error",()=>{this.errorCode_=zq.NETWORK_ERROR,e()}),this.xhr_.addEventListener("load",()=>{e()})})}send(e,t,n,r){if(this.sent_)throw aV("cannot .send() more than once");if(this.sent_=!0,this.xhr_.open(t,e,!0),void 0!==r)for(const i in r)r.hasOwnProperty(i)&&this.xhr_.setRequestHeader(i,r[i].toString());return void 0!==n?this.xhr_.send(n):this.xhr_.send(),this.sendPromise_}getErrorCode(){if(!this.sent_)throw aV("cannot .getErrorCode() before sending");return this.errorCode_}getStatus(){if(!this.sent_)throw aV("cannot .getStatus() before sending");try{return this.xhr_.status}catch(e){return-1}}getResponse(){if(!this.sent_)throw aV("cannot .getResponse() before sending");return this.xhr_.response}getErrorText(){if(!this.sent_)throw aV("cannot .getErrorText() before sending");return this.xhr_.statusText}abort(){this.xhr_.abort()}getResponseHeader(e){return this.xhr_.getResponseHeader(e)}addUploadProgressListener(e){null!=this.xhr_.upload&&this.xhr_.upload.addEventListener("progress",e)}removeUploadProgressListener(e){null!=this.xhr_.upload&&this.xhr_.upload.removeEventListener("progress",e)}}{initXhr(){this.xhr_.responseType="text"}}function rB(){return new nB}class iB{constructor(e,t,n=null){this._transferred=0,this._needToFetchStatus=!1,this._needToFetchMetadata=!1,this._observers=[],this._error=void 0,this._uploadUrl=void 0,this._request=void 0,this._chunkMultiplier=1,this._resolve=void 0,this._reject=void 0,this._ref=e,this._blob=t,this._metadata=n,this._mappings=PV(),this._resumable=this._shouldDoResumable(this._blob),this._state="running",this._errorHandler=e=>{this._request=void 0,this._chunkMultiplier=1,e._codeEquals("canceled")?(this._needToFetchStatus=!0,this.completeTransitions_()):(this._error=e,this._transition("error"))},this._metadataErrorHandler=e=>{this._request=void 0,e._codeEquals("canceled")?this.completeTransitions_():(this._error=e,this._transition("error"))},this._promise=new Promise((e,t)=>{this._resolve=e,this._reject=t,this._start()}),this._promise.then(null,()=>{})}_makeProgressCallback(){const t=this._transferred;return e=>this._updateProgress(t+e)}_shouldDoResumable(e){return 262144<e.size()}_start(){"running"===this._state&&void 0===this._request&&(this._resumable?void 0===this._uploadUrl?this._createResumable():this._needToFetchStatus?this._fetchStatus():this._needToFetchMetadata?this._fetchMetadata():this._continueUpload():this._oneShotUpload())}_resolveToken(n){Promise.all([this._ref.storage._getAuthToken(),this._ref.storage._getAppCheckToken()]).then(([e,t])=>{switch(this._state){case"running":n(e,t);break;case"canceling":this._transition("canceled");break;case"pausing":this._transition("paused")}})}_createResumable(){this._resolveToken((e,t)=>{var n=GV(this._ref.storage,this._ref._location,this._mappings,this._blob,this._metadata);const r=this._ref.storage._makeRequest(n,rB,e,t);this._request=r,r.getPromise().then(e=>{this._request=void 0,this._uploadUrl=e,this._needToFetchStatus=!1,this.completeTransitions_()},this._errorHandler)})}_fetchStatus(){const i=this._uploadUrl;this._resolveToken((e,t)=>{var n=QV(this._ref.storage,this._ref._location,i,this._blob);const r=this._ref.storage._makeRequest(n,rB,e,t);this._request=r,r.getPromise().then(e=>{this._request=void 0,this._updateProgress(e.current),this._needToFetchStatus=!1,e.finalized&&(this._needToFetchMetadata=!0),this.completeTransitions_()},this._errorHandler)})}_continueUpload(){const i=262144*this._chunkMultiplier,s=new $V(this._transferred,this._blob.size()),o=this._uploadUrl;this._resolveToken((e,t)=>{let n;try{n=YV(this._ref._location,this._ref.storage,o,this._blob,i,this._mappings,s,this._makeProgressCallback())}catch(e){return this._error=e,void this._transition("error")}const r=this._ref.storage._makeRequest(n,rB,e,t);this._request=r,r.getPromise().then(e=>{this._increaseMultiplier(),this._request=void 0,this._updateProgress(e.current),e.finalized?(this._metadata=e.metadata,this._transition("success")):this.completeTransitions_()},this._errorHandler)})}_increaseMultiplier(){262144*this._chunkMultiplier<33554432&&(this._chunkMultiplier*=2)}_fetchMetadata(){this._resolveToken((e,t)=>{var n=WV(this._ref.storage,this._ref._location,this._mappings);const r=this._ref.storage._makeRequest(n,rB,e,t);this._request=r,r.getPromise().then(e=>{this._request=void 0,this._metadata=e,this._transition("success")},this._metadataErrorHandler)})}_oneShotUpload(){this._resolveToken((e,t)=>{var n=KV(this._ref.storage,this._ref._location,this._mappings,this._blob,this._metadata);const r=this._ref.storage._makeRequest(n,rB,e,t);this._request=r,r.getPromise().then(e=>{this._request=void 0,this._metadata=e,this._updateProgress(this._blob.size()),this._transition("success")},this._errorHandler)})}_updateProgress(e){var t=this._transferred;this._transferred=e,this._transferred!==t&&this._notifyObservers()}_transition(e){if(this._state!==e)switch(e){case"canceling":case"pausing":this._state=e,void 0!==this._request&&this._request.cancel();break;case"running":var t="paused"===this._state;this._state=e,t&&(this._notifyObservers(),this._start());break;case"paused":this._state=e,this._notifyObservers();break;case"canceled":this._error=tV(),this._state=e,this._notifyObservers();break;case"error":case"success":this._state=e,this._notifyObservers()}}completeTransitions_(){switch(this._state){case"pausing":this._transition("paused");break;case"canceling":this._transition("canceled");break;case"running":this._start()}}get snapshot(){var e=ZV(this._state);return{bytesTransferred:this._transferred,totalBytes:this._blob.size(),state:e,metadata:this._metadata,task:this,ref:this._ref}}on(e,t,n,r){const i=new eB(t||void 0,n||void 0,r||void 0);return this._addObserver(i),()=>{this._removeObserver(i)}}then(e,t){return this._promise.then(e,t)}catch(e){return this.then(null,e)}_addObserver(e){this._observers.push(e),this._notifyObserver(e)}_removeObserver(e){var t=this._observers.indexOf(e);-1!==t&&this._observers.splice(t,1)}_notifyObservers(){this._finishPromise();const e=this._observers.slice();e.forEach(e=>{this._notifyObserver(e)})}_finishPromise(){if(void 0!==this._resolve){let e=!0;switch(ZV(this._state)){case JV.SUCCESS:tB(this._resolve.bind(null,this.snapshot))();break;case JV.CANCELED:case JV.ERROR:const t=this._reject;tB(t.bind(null,this._error))();break;default:e=!1}e&&(this._resolve=void 0,this._reject=void 0)}}_notifyObserver(e){switch(ZV(this._state)){case JV.RUNNING:case JV.PAUSED:e.next&&tB(e.next.bind(e,this.snapshot))();break;case JV.SUCCESS:e.complete&&tB(e.complete.bind(e))();break;case JV.CANCELED:case JV.ERROR:default:e.error&&tB(e.error.bind(e,this._error))()}}resume(){var e="paused"===this._state||"pausing"===this._state;return e&&this._transition("running"),e}pause(){var e="running"===this._state;return e&&this._transition("pausing"),e}cancel(){var e="running"===this._state||"pausing"===this._state;return e&&this._transition("canceling"),e}}class sB{constructor(e,t){this._service=e,t instanceof cV?this._location=t:this._location=cV.makeFromUrl(t,e.host)}toString(){return"gs://"+this._location.bucket+"/"+this._location.path}_newRef(e,t){return new sB(e,t)}get root(){var e=new cV(this._location.bucket,"");return this._newRef(this._service,e)}get bucket(){return this._location.bucket}get fullPath(){return this._location.path}get name(){return CV(this._location.path)}get storage(){return this._service}get parent(){var e=function(e){if(0===e.length)return null;var t=e.lastIndexOf("/");return-1===t?"":e.slice(0,t)}(this._location.path);if(null===e)return null;e=new cV(this._location.bucket,e);return new sB(this._service,e)}_throwIfRoot(e){if(""===this._location.path)throw sV(e)}}function oB(e){const t={prefixes:[],items:[]};return async function e(t,n,r){const i={pageToken:r};const s=await aB(t,i);n.prefixes.push(...s.prefixes);n.items.push(...s.items);null!=s.nextPageToken&&await e(t,n,s.nextPageToken)}(e,t).then(()=>t)}function aB(e,t){null!=t&&"number"==typeof t.maxResults&&pV("options.maxResults",1,1e3,t.maxResults);var n=t||{},n=function(e,t,n,r,i){const s={};t.isRoot?s.prefix="":s.prefix=t.path+"/",n&&0<n.length&&(s.delimiter=n),r&&(s.pageToken=r),i&&(s.maxResults=i);var o=fV(t.bucketOnlyServerUrl(),e.host,e._protocol),a=e.maxOperationRetryTime;const c=new MV(o,"GET",jV(e,t.bucket),a);return c.urlParams=s,c.errorHandler=VV(t),c}(e.storage,e._location,"/",n.pageToken,n.maxResults);return e.storage.makeRequestWithTokens(n,rB)}function cB(e,t){e._throwIfRoot("updateMetadata");var n=function(e,t,n,r){var i=fV(t.fullServerUrl(),e.host,e._protocol),s=DV(n,r),o=e.maxOperationRetryTime;const a=new MV(i,"PATCH",UV(e,r),o);return a.headers={"Content-Type":"application/json; charset=utf-8"},a.body=s,a.errorHandler=BV(t),a}(e.storage,e._location,t,PV());return e.storage.makeRequestWithTokens(n,rB)}function lB(e){e._throwIfRoot("getDownloadURL");var t=function(e,t,n){var r=fV(t.fullServerUrl(),e.host,e._protocol),i=e.maxOperationRetryTime;const s=new MV(r,"GET",qV(e,n),i);return s.errorHandler=BV(t),s}(e.storage,e._location,PV());return e.storage.makeRequestWithTokens(t,rB).then(e=>{if(null===e)throw new Jq("no-download-url","The given file does not have any download URLs.");return e})}function uB(e){e._throwIfRoot("deleteObject");var t=function(e,t){var n=fV(t.fullServerUrl(),e.host,e._protocol),r=e.maxOperationRetryTime;const i=new MV(n,"DELETE",function(e,t){},r);return i.successCodes=[200,204],i.errorHandler=BV(t),i}(e.storage,e._location);return e.storage.makeRequestWithTokens(t,rB)}function hB(e,t){var n,r=(n=e._location.path,r=t.split("/").filter(e=>0<e.length).join("/"),0===n.length?r:n+"/"+r),r=new cV(e._location.bucket,r);return new sB(e.storage,r)}function dB(e,t){if(e instanceof gB){var n=e;if(null==n._bucket)throw new Jq("no-default-bucket","No default bucket found. Did you set the '"+Xq+"' property when initializing the app?");n=new sB(n,n._bucket);return null!=t?dB(n,t):n}return void 0!==t?hB(e,t):e}function pB(e,t){if(t&&/^[A-Za-z]+:\/\//.test(t)){if(e instanceof gB)return n=e,r=t,new sB(n,r);throw rV("To use ref(service, url), the first argument must be a Storage instance.")}return dB(e,t);var n,r}function fB(e,t){var n=null==t?void 0:t[Xq];return null==n?null:cV.makeFromBucketSpec(n,e)}class gB{constructor(e,t,n,r,i){this.app=e,this._authProvider=t,this._appCheckProvider=n,this._url=r,this._firebaseVersion=i,this._bucket=null,this._host=Yq,this._protocol="https",this._appId=null,this._deleted=!1,this._maxOperationRetryTime=12e4,this._maxUploadRetryTime=6e5,this._requests=new Set,this._bucket=null!=r?cV.makeFromBucketSpec(r,this._host):fB(this._host,this.app.options)}get host(){return this._host}set host(e){this._host=e,null!=this._url?this._bucket=cV.makeFromBucketSpec(this._url,e):this._bucket=fB(e,this.app.options)}get maxUploadRetryTime(){return this._maxUploadRetryTime}set maxUploadRetryTime(e){pV("time",0,Number.POSITIVE_INFINITY,e),this._maxUploadRetryTime=e}get maxOperationRetryTime(){return this._maxOperationRetryTime}set maxOperationRetryTime(e){pV("time",0,Number.POSITIVE_INFINITY,e),this._maxOperationRetryTime=e}async _getAuthToken(){if(this._overrideAuthToken)return this._overrideAuthToken;const e=this._authProvider.getImmediate({optional:!0});if(e){var t=await e.getToken();if(null!==t)return t.accessToken}return null}async _getAppCheckToken(){const e=this._appCheckProvider.getImmediate({optional:!0});return e?(await e.getToken()).token:null}_delete(){return this._deleted||(this._deleted=!0,this._requests.forEach(e=>e.cancel()),this._requests.clear()),Promise.resolve()}_makeStorageReference(e){return new sB(this,e)}_makeRequest(e,t,n,r){if(this._deleted)return new lV(iV());{const l=(i=e,s=this._appId,o=n,e=r,n=t,r=this._firebaseVersion,a=gV(i.urlParams),c=i.url+a,a=Object.assign({},i.headers),t=a,(s=s)&&(t["X-Firebase-GMPID"]=s),s=a,null!==(o=o)&&0<o.length&&(s.Authorization="Firebase "+o),r=r,a["X-Firebase-Storage-Version"]="webjs/"+(null!=r?r:"AppManager"),r=a,null!==(e=e)&&(r["X-Firebase-AppCheck"]=e),new mV(c,i.method,a,i.body,i.successCodes,i.additionalRetryCodes,i.handler,i.errorHandler,i.timeout,i.progressCallback,n));return this._requests.add(l),l.getPromise().then(()=>this._requests.delete(l),()=>this._requests.delete(l)),l}var i,s,o,a,c}async makeRequestWithTokens(e,t){var[n,r]=await Promise.all([this._getAuthToken(),this._getAppCheckToken()]);return this._makeRequest(e,t,n,r).getPromise()}}const mB="@firebase/storage";function vB(e,t,n){return e=zd(e),t=t,n=n,(e=e)._throwIfRoot("uploadBytesResumable"),new iB(e,new kV(t),n)}function yB(e){return function(e){e._throwIfRoot("getMetadata");var t=WV(e.storage,e._location,PV());return e.storage.makeRequestWithTokens(t,rB)}(e=zd(e))}function _B(e,t){return pB(e=zd(e),t)}function wB(e,t,n,r={}){!function(e,t,n,r={}){e.host=`${t}:${n}`,e._protocol="http";var i=r["mockUserToken"];i&&(e._overrideAuthToken="string"==typeof i?i:id(i,e.app.options.projectId))}(e,t,n,r)}function bB(e,{instanceIdentifier:t}){var n=e.getProvider("app").getImmediate(),r=e.getProvider("auth-internal"),i=e.getProvider("app-check-internal");return new gB(n,r,i,t,gp)}hp(new Kd("storage",bB,"PUBLIC").setMultipleInstances(!0)),_p(mB,"0.9.2",""),_p(mB,"0.9.2","esm2017");class IB{constructor(e,t,n){this._delegate=e,this.task=t,this.ref=n}get bytesTransferred(){return this._delegate.bytesTransferred}get metadata(){return this._delegate.metadata}get state(){return this._delegate.state}get totalBytes(){return this._delegate.totalBytes}}class TB{constructor(e,t){this._delegate=e,this._ref=t,this.cancel=this._delegate.cancel.bind(this._delegate),this.catch=this._delegate.catch.bind(this._delegate),this.pause=this._delegate.pause.bind(this._delegate),this.resume=this._delegate.resume.bind(this._delegate)}get snapshot(){return new IB(this._delegate.snapshot,this,this._ref)}then(t,e){return this._delegate.then(e=>{if(t)return t(new IB(e,this,this._ref))},e)}on(e,t,n,r){let i=void 0;return t&&(i="function"==typeof t?e=>t(new IB(e,this,this._ref)):{next:t.next?e=>t.next(new IB(e,this,this._ref)):void 0,complete:t.complete||void 0,error:t.error||void 0}),this._delegate.on(e,i,n||void 0,r||void 0)}}class EB{constructor(e,t){this._delegate=e,this._service=t}get prefixes(){return this._delegate.prefixes.map(e=>new kB(e,this._service))}get items(){return this._delegate.items.map(e=>new kB(e,this._service))}get nextPageToken(){return this._delegate.nextPageToken||null}}class kB{constructor(e,t){this._delegate=e,this.storage=t}get name(){return this._delegate.name}get bucket(){return this._delegate.bucket}get fullPath(){return this._delegate.fullPath}toString(){return this._delegate.toString()}child(e){var t=hB(this._delegate,e);return new kB(t,this.storage)}get root(){return new kB(this._delegate.root,this.storage)}get parent(){var e=this._delegate.parent;return null==e?null:new kB(e,this.storage)}put(e,t){return this._throwIfRoot("put"),new TB(vB(this._delegate,e,t),this)}putString(e,t=_V.RAW,n){this._throwIfRoot("putString");var r=bV(t,e);const i=Object.assign({},n);return null==i.contentType&&null!=r.contentType&&(i.contentType=r.contentType),new TB(new iB(this._delegate,new kV(r.data,!0),i),this)}listAll(){return oB(zd(this._delegate)).then(e=>new EB(e,this.storage))}list(e){return t=this._delegate,e=e||void 0,aB(t=zd(t),e).then(e=>new EB(e,this.storage));var t}getMetadata(){return yB(this._delegate)}updateMetadata(e){return cB(zd(this._delegate),e)}getDownloadURL(){return lB(zd(this._delegate))}delete(){return this._throwIfRoot("delete"),uB(zd(this._delegate))}_throwIfRoot(e){if(""===this._delegate._location.path)throw sV(e)}}class SB{constructor(e,t){this.app=e,this._delegate=t}get maxOperationRetryTime(){return this._delegate.maxOperationRetryTime}get maxUploadRetryTime(){return this._delegate.maxUploadRetryTime}ref(e){if(CB(e))throw rV("ref() expected a child path but got a URL, use refFromURL instead.");return new kB(_B(this._delegate,e),this)}refFromURL(e){if(!CB(e))throw rV("refFromURL() expected a full URL but got a child path, use ref() instead.");try{cV.makeFromUrl(e,this._delegate.host)}catch(e){throw rV("refFromUrl() expected a valid full URL but got an invalid one.")}return new kB(_B(this._delegate,e),this)}setMaxUploadRetryTime(e){this._delegate.maxUploadRetryTime=e}setMaxOperationRetryTime(e){this._delegate.maxOperationRetryTime=e}useEmulator(e,t,n={}){wB(this._delegate,e,t,n)}}function CB(e){return/^[A-Za-z]+:\/\//.test(e)}function AB(e,{instanceIdentifier:t}){var n=e.getProvider("app-compat").getImmediate(),r=e.getProvider("storage").getImmediate({identifier:t});return new SB(n,r)}Kq=Cp,$q={TaskState:JV,TaskEvent:XV,StringFormat:_V,Storage:SB,Reference:kB},Kq.INTERNAL.registerComponent(new Kd("storage-compat",AB,"PUBLIC").setServiceProps($q).setMultipleInstances(!0)),Kq.registerVersion("@firebase/storage-compat","0.1.10");const NB="@firebase/performance",RB="0.5.5",PB="FB-PERF-TRACE-MEASURE",xB="@firebase/performance/config",OB="@firebase/performance/configexpire";var DB,LB,MB,FB="Performance";const UB=new md("performance",FB,{"trace started":"Trace {$traceName} was started before.","trace stopped":"Trace {$traceName} is not running.","nonpositive trace startTime":"Trace {$traceName} startTime should be positive.","nonpositive trace duration":"Trace {$traceName} duration should be positive.","no window":"Window is not available.","no app id":"App id is not available.","no project id":"Project id is not available.","no api key":"Api key is not available.","invalid cc log":"Attempted to queue invalid cc event","FB not default":"Performance can only start when Firebase app instance is the default one.","RC response not ok":"RC response is not ok","invalid attribute name":"Attribute name {$attributeName} is invalid.","invalid attribute value":"Attribute value {$attributeValue} is invalid.","invalid custom metric name":"Custom metric name {$customMetricName} is invalid","invalid String merger input":"Input for String merger is invalid, contact support team to resolve.","already initialized":"initializePerformance() has already been called with different options. To avoid this error, call initializePerformance() with the same options as when it was originally called, or call getPerformance() to return the already initialized instance."}),jB=new ep(FB);jB.logLevel=zh.INFO;let qB,VB;class BB{constructor(e){if(!(this.window=e))throw UB.create("no window");this.performance=e.performance,this.PerformanceObserver=e.PerformanceObserver,this.windowLocation=e.location,this.navigator=e.navigator,this.document=e.document,this.navigator&&this.navigator.cookieEnabled&&(this.localStorage=e.localStorage),e.perfMetrics&&e.perfMetrics.onFirstInputDelay&&(this.onFirstInputDelay=e.perfMetrics.onFirstInputDelay)}getUrl(){return this.windowLocation.href.split("?")[0]}mark(e){this.performance&&this.performance.mark&&this.performance.mark(e)}measure(e,t,n){this.performance&&this.performance.measure&&this.performance.measure(e,t,n)}getEntriesByType(e){return this.performance&&this.performance.getEntriesByType?this.performance.getEntriesByType(e):[]}getEntriesByName(e){return this.performance&&this.performance.getEntriesByName?this.performance.getEntriesByName(e):[]}getTimeOrigin(){return this.performance&&(this.performance.timeOrigin||this.performance.timing.navigationStart)}requiredApisAvailable(){return fetch&&Promise&&fd()?!!dd()||(jB.info("IndexedDB is not supported by current browswer"),!1):(jB.info("Firebase Performance cannot start if browser does not support fetch and Promise or cookie is disabled."),!1)}setupObserver(e,n){if(this.PerformanceObserver){const t=new this.PerformanceObserver(e=>{for(const t of e.getEntries())n(t)});t.observe({entryTypes:[e]})}}static getInstance(){return void 0===qB&&(qB=new BB(VB)),qB}}let WB;function zB(e,t){var n=e.length-t.length;if(n<0||1<n)throw UB.create("invalid String merger input");const r=[];for(let i=0;i<e.length;i++)r.push(e.charAt(i)),t.length>i&&r.push(t.charAt(i));return r.join("")}let KB;class $B{constructor(){this.instrumentationEnabled=!0,this.dataCollectionEnabled=!0,this.loggingEnabled=!1,this.tracesSamplingRate=1,this.networkRequestsSamplingRate=1,this.logEndPointUrl="https://firebaselogging.googleapis.com/v0cc/log?format=json_proto",this.flTransportEndpointUrl=zB("hts/frbslgigp.ogepscmv/ieo/eaylg","tp:/ieaeogn-agolai.o/1frlglgc/o"),this.transportKey=zB("AzSC8r6ReiGqFMyfvgow","Iayx0u-XT3vksVM-pIV"),this.logSource=462,this.logTraceAfterSampling=!1,this.logNetworkAfterSampling=!1,this.configTimeToLive=12}getFlTransportFullUrl(){return this.flTransportEndpointUrl.concat("?key=",this.transportKey)}static getInstance(){return void 0===KB&&(KB=new $B),KB}}(c=DB=DB||{})[c.UNKNOWN=0]="UNKNOWN",c[c.VISIBLE=1]="VISIBLE",c[c.HIDDEN=2]="HIDDEN";const HB=["firebase_","google_","ga_"],GB=new RegExp("^[a-zA-Z]\\w*$");function QB(){switch(BB.getInstance().document.visibilityState){case"visible":return DB.VISIBLE;case"hidden":return DB.HIDDEN;default:return DB.UNKNOWN}}function YB(e){var t=null===(t=e.options)||void 0===t?void 0:t.appId;if(!t)throw UB.create("no app id");return t}const XB="0.0.1",JB={loggingEnabled:!0},ZB="FIREBASE_INSTALLATIONS_AUTH";function eW(e,t){var r,i,n=function(){const e=BB.getInstance().localStorage;if(e){var t=e.getItem(OB);if(t&&function(e){return Number(e)>Date.now()}(t)){t=e.getItem(xB);if(t)try{return JSON.parse(t)}catch(e){return}}}}();return n?(nW(n),Promise.resolve()):(i=t,function(e){const t=e.getToken();return t.then(e=>{}),t}((r=e).installations).then(e=>{var t=function(e){var t=null===(t=e.options)||void 0===t?void 0:t.projectId;if(!t)throw UB.create("no project id");return t}(r.app),n=function(e){var t=null===(t=e.options)||void 0===t?void 0:t.apiKey;if(!t)throw UB.create("no api key");return t}(r.app),n=new Request(`https://firebaseremoteconfig.googleapis.com/v1/projects/${t}/namespaces/fireperf:fetch?key=${n}`,{method:"POST",headers:{Authorization:`${ZB} ${e}`},body:JSON.stringify({app_instance_id:i,app_instance_id_token:e,app_id:YB(r.app),app_version:RB,sdk_version:XB})});return fetch(n).then(e=>{if(e.ok)return e.json();throw UB.create("RC response not ok")})}).catch(()=>{jB.info(tW)}).then(nW).then(e=>function(e){const t=BB.getInstance().localStorage;e&&t&&(t.setItem(xB,JSON.stringify(e)),t.setItem(OB,String(Date.now()+60*$B.getInstance().configTimeToLive*60*1e3)))}(e),()=>{}))}const tW="Could not fetch config, will use default configs";function nW(e){if(!e)return e;const t=$B.getInstance();var n=e.entries||{};return void 0!==n.fpr_enabled?t.loggingEnabled="true"===String(n.fpr_enabled):t.loggingEnabled=JB.loggingEnabled,n.fpr_log_source&&(t.logSource=Number(n.fpr_log_source)),n.fpr_log_endpoint_url&&(t.logEndPointUrl=n.fpr_log_endpoint_url),n.fpr_log_transport_key&&(t.transportKey=n.fpr_log_transport_key),void 0!==n.fpr_vc_network_request_sampling_rate&&(t.networkRequestsSamplingRate=Number(n.fpr_vc_network_request_sampling_rate)),void 0!==n.fpr_vc_trace_sampling_rate&&(t.tracesSamplingRate=Number(n.fpr_vc_trace_sampling_rate)),t.logTraceAfterSampling=rW(t.tracesSamplingRate),t.logNetworkAfterSampling=rW(t.networkRequestsSamplingRate),e}function rW(e){return Math.random()<=e}let iW=1,sW;function oW(e){var t;return iW=2,sW=sW||(t=e,function(){const n=BB.getInstance().document;return new Promise(e=>{if(n&&"complete"!==n.readyState){const t=()=>{"complete"===n.readyState&&(n.removeEventListener("readystatechange",t),e())};n.addEventListener("readystatechange",t)}else e()})}().then(()=>function(e){const t=e.getId();return t.then(e=>{WB=e}),t}(t.installations)).then(e=>eW(t,e)).then(()=>aW(),()=>aW())),sW}function aW(){iW=3}const cW=1e4,lW=3,uW=1e3;let hW=lW,dW=[],pW=!1;function fW(e){setTimeout(()=>{if(0!==hW)return dW.length?void function(){const e=dW.splice(0,uW),t=e.map(e=>({source_extension_json_proto3:e.message,event_time_ms:String(e.eventTime)})),n={request_time_ms:String(Date.now()),client_info:{client_type:1,js_client_info:{}},log_source:$B.getInstance().logSource,log_event:t};!function(e,r){return function(e){var t=$B.getInstance().getFlTransportFullUrl();return fetch(t,{method:"POST",body:JSON.stringify(e)})}(e).then(e=>(e.ok||jB.info("Call to Firebase backend failed."),e.json())).then(e=>{var t=Number(e.nextRequestWaitMillis);let n=cW;isNaN(t)||(n=Math.max(t,n));t=e.logResponseDetails;Array.isArray(t)&&0<t.length&&"RETRY_REQUEST_LATER"===t[0].responseAction&&(dW=[...r,...dW],jB.info("Retry transport request later.")),hW=lW,fW(n)})}(n,e).catch(()=>{dW=[...e,...dW],hW--,jB.info(`Tries left: ${hW}.`),fW(cW)})}():fW(cW)},e)}function gW(t){return(...e)=>{!function(e){if(!e.eventTime||!e.message)throw UB.create("invalid cc log");dW=[...dW,e]}({message:t(...e),eventTime:Date.now()})}}let mW;function vW(e,t){mW=mW||gW(wW),mW(e,t)}function yW(e){var t=$B.getInstance();!t.instrumentationEnabled&&e.isAuto||(t.dataCollectionEnabled||e.isAuto)&&BB.getInstance().requiredApisAvailable()&&(e.isAuto&&QB()!==DB.VISIBLE||(3===iW?_W(e):oW(e.performanceController).then(()=>_W(e),()=>_W(e))))}function _W(e){var t;!WB||(t=$B.getInstance()).loggingEnabled&&t.logTraceAfterSampling&&setTimeout(()=>vW(e,1),0)}function wW(e,t){return 0===t?(n={url:e.url,http_method:e.httpMethod||0,http_response_code:200,response_payload_bytes:e.responsePayloadBytes,client_start_time_us:e.startTimeUs,time_to_response_initiated_us:e.timeToResponseInitiatedUs,time_to_response_completed_us:e.timeToResponseCompletedUs},n={application_info:bW(e.performanceController.app),network_request_metric:n},JSON.stringify(n)):function(e){const t={name:e.name,is_auto:e.isAuto,client_start_time_us:e.startTimeUs,duration_us:e.durationUs};0!==Object.keys(e.counters).length&&(t.counters=e.counters);var n=e.getAttributes();0!==Object.keys(n).length&&(t.custom_attributes=n);n={application_info:bW(e.performanceController.app),trace_metric:t};return JSON.stringify(n)}(e);var n}function bW(e){return{google_app_id:YB(e),app_instance_id:WB,web_app_info:{sdk_version:RB,page_url:BB.getInstance().getUrl(),service_worker_status:"serviceWorker"in(t=BB.getInstance().navigator)?t.serviceWorker.controller?2:3:1,visibility_state:QB(),effective_connection_type:function(){var e=BB.getInstance().navigator.connection;switch(e&&e.effectiveType){case"slow-2g":return 1;case"2g":return 2;case"3g":return 3;case"4g":return 4;default:return 0}}()},application_process_state:0};var t}const IW=["_fp","_fcp","_fid"];class TW{constructor(e,t,n=!1,r){this.performanceController=e,this.name=t,this.isAuto=n,this.state=1,this.customAttributes={},this.counters={},this.api=BB.getInstance(),this.randomId=Math.floor(1e6*Math.random()),this.isAuto||(this.traceStartMark=`FB-PERF-TRACE-START-${this.randomId}-${this.name}`,this.traceStopMark=`FB-PERF-TRACE-STOP-${this.randomId}-${this.name}`,this.traceMeasure=r||`${PB}-${this.randomId}-${this.name}`,r&&this.calculateTraceMetrics())}start(){if(1!==this.state)throw UB.create("trace started",{traceName:this.name});this.api.mark(this.traceStartMark),this.state=2}stop(){if(2!==this.state)throw UB.create("trace stopped",{traceName:this.name});this.state=3,this.api.mark(this.traceStopMark),this.api.measure(this.traceMeasure,this.traceStartMark,this.traceStopMark),this.calculateTraceMetrics(),yW(this)}record(e,t,n){if(e<=0)throw UB.create("nonpositive trace startTime",{traceName:this.name});if(t<=0)throw UB.create("nonpositive trace duration",{traceName:this.name});if(this.durationUs=Math.floor(1e3*t),this.startTimeUs=Math.floor(1e3*e),n&&n.attributes&&(this.customAttributes=Object.assign({},n.attributes)),n&&n.metrics)for(const r of Object.keys(n.metrics))isNaN(Number(n.metrics[r]))||(this.counters[r]=Math.floor(Number(n.metrics[r])));yW(this)}incrementMetric(e,t=1){void 0===this.counters[e]?this.putMetric(e,t):this.putMetric(e,this.counters[e]+t)}putMetric(e,t){if(r=e,i=this.name,0===r.length||100<r.length||!(i&&i.startsWith("_wt_")&&-1<IW.indexOf(r))&&r.startsWith("_"))throw UB.create("invalid custom metric name",{customMetricName:e});var n,r,i;this.counters[e]=(t=null!=t?t:0,(n=Math.floor(t))<t&&jB.info(`Metric value should be an Integer, setting the value as : ${n}.`),n)}getMetric(e){return this.counters[e]||0}putAttribute(e,t){var n,r,i=!(0===(n=e).length||40<n.length)&&(!HB.some(e=>n.startsWith(e))&&!!n.match(GB)),s=0!==(r=t).length&&r.length<=100;if(i&&s)this.customAttributes[e]=t;else{if(!i)throw UB.create("invalid attribute name",{attributeName:e});if(!s)throw UB.create("invalid attribute value",{attributeValue:t})}}getAttribute(e){return this.customAttributes[e]}removeAttribute(e){void 0!==this.customAttributes[e]&&delete this.customAttributes[e]}getAttributes(){return Object.assign({},this.customAttributes)}setStartTime(e){this.startTimeUs=e}setDuration(e){this.durationUs=e}calculateTraceMetrics(){var e=this.api.getEntriesByName(this.traceMeasure),e=e&&e[0];e&&(this.durationUs=Math.floor(1e3*e.duration),this.startTimeUs=Math.floor(1e3*(e.startTime+this.api.getTimeOrigin())))}static createOobTrace(e,t,n,r){var i=BB.getInstance().getUrl();if(i){const s=new TW(e,"_wt_"+i,!0);i=Math.floor(1e3*BB.getInstance().getTimeOrigin());s.setStartTime(i),t&&t[0]&&(s.setDuration(Math.floor(1e3*t[0].duration)),s.putMetric("domInteractive",Math.floor(1e3*t[0].domInteractive)),s.putMetric("domContentLoadedEventEnd",Math.floor(1e3*t[0].domContentLoadedEventEnd)),s.putMetric("loadEventEnd",Math.floor(1e3*t[0].loadEventEnd)));n&&((i=n.find(e=>"first-paint"===e.name))&&i.startTime&&s.putMetric("_fp",Math.floor(1e3*i.startTime)),(i=n.find(e=>"first-contentful-paint"===e.name))&&i.startTime&&s.putMetric("_fcp",Math.floor(1e3*i.startTime)),r&&s.putMetric("_fid",Math.floor(1e3*r))),yW(s)}}static createUserTimingTrace(e,t){yW(new TW(e,t,!1,t))}}function EW(e,t){const n=t;var r,i,s;n&&void 0!==n.responseStart&&(s=BB.getInstance().getTimeOrigin(),r=Math.floor(1e3*(n.startTime+s)),i=n.responseStart?Math.floor(1e3*(n.responseStart-n.startTime)):void 0,s=Math.floor(1e3*(n.responseEnd-n.startTime)),function(e){const t=$B.getInstance();var n,r,i;t.instrumentationEnabled&&(n=e.url,r=t.logEndPointUrl.split("?")[0],i=t.flTransportEndpointUrl.split("?")[0],n!==r&&n!==i&&t.loggingEnabled&&t.logNetworkAfterSampling&&setTimeout(()=>vW(e,0),0))}({performanceController:e,url:n.name&&n.name.split("?")[0],responsePayloadBytes:n.transferSize,startTimeUs:r,timeToResponseInitiatedUs:i,timeToResponseCompletedUs:s}))}const kW=5e3;function SW(e){WB&&(setTimeout(()=>function(n){const e=BB.getInstance(),r=e.getEntriesByType("navigation"),i=e.getEntriesByType("paint");if(e.onFirstInputDelay){let t=setTimeout(()=>{TW.createOobTrace(n,r,i),t=void 0},kW);e.onFirstInputDelay(e=>{t&&(clearTimeout(t),TW.createOobTrace(n,r,i,e))})}else TW.createOobTrace(n,r,i)}(e),0),setTimeout(()=>function(t){const e=BB.getInstance(),n=e.getEntriesByType("resource");for(const r of n)EW(t,r);e.setupObserver("resource",e=>EW(t,e))}(e),0),setTimeout(()=>function(t){const e=BB.getInstance(),n=e.getEntriesByType("measure");for(const r of n)CW(t,r);e.setupObserver("measure",e=>CW(t,e))}(e),0))}function CW(e,t){const n=t.name;n.substring(0,PB.length)!==PB&&TW.createUserTimingTrace(e,n)}class AW{constructor(e,t){this.app=e,this.installations=t,this.initialized=!1}_init(e){this.initialized||(void 0!==(null==e?void 0:e.dataCollectionEnabled)&&(this.dataCollectionEnabled=e.dataCollectionEnabled),void 0!==(null==e?void 0:e.instrumentationEnabled)&&(this.instrumentationEnabled=e.instrumentationEnabled),BB.getInstance().requiredApisAvailable()?pd().then(e=>{e&&(pW||(fW(5500),pW=!0),oW(this).then(()=>SW(this),()=>SW(this)),this.initialized=!0)}).catch(e=>{jB.info(`Environment doesn't support IndexedDB: ${e}`)}):jB.info('Firebase Performance cannot start if the browser does not support "Fetch" and "Promise", or cookies are disabled.'))}set instrumentationEnabled(e){$B.getInstance().instrumentationEnabled=e}get instrumentationEnabled(){return $B.getInstance().instrumentationEnabled}set dataCollectionEnabled(e){$B.getInstance().dataCollectionEnabled=e}get dataCollectionEnabled(){return $B.getInstance().dataCollectionEnabled}}const NW="[DEFAULT]";const RW=(e,{options:t})=>{var n=e.getProvider("app").getImmediate(),r=e.getProvider("installations-internal").getImmediate();if(n.name!==NW)throw UB.create("FB not default");if("undefined"==typeof window)throw UB.create("no window");e=window,VB=e;const i=new AW(n,r);return i._init(t),i};hp(new Kd("performance",RW,"PUBLIC")),_p(NB,"0.5.5"),_p(NB,"0.5.5","esm2017");class PW{constructor(e,t){this.app=e,this._delegate=t}get instrumentationEnabled(){return this._delegate.instrumentationEnabled}set instrumentationEnabled(e){this._delegate.instrumentationEnabled=e}get dataCollectionEnabled(){return this._delegate.dataCollectionEnabled}set dataCollectionEnabled(e){this._delegate.dataCollectionEnabled=e}trace(e){return t=this._delegate,e=e,t=zd(t),new TW(t,e);var t}}function xW(e){var t=e.getProvider("app-compat").getImmediate(),n=e.getProvider("performance").getImmediate();return new PW(t,n)}(LB=Cp).INTERNAL.registerComponent(new Kd("performance-compat",xW,"PUBLIC")),LB.registerVersion("@firebase/performance-compat","0.1.5");const OW="@firebase/remote-config";class DW{constructor(){this.listeners=[]}addEventListener(e){this.listeners.push(e)}abort(){this.listeners.forEach(e=>e())}}const LW=new md("remoteconfig","Remote Config",{"registration-window":"Undefined window object. This SDK only supports usage in a browser environment.","registration-project-id":"Undefined project identifier. Check Firebase app initialization.","registration-api-key":"Undefined API key. Check Firebase app initialization.","registration-app-id":"Undefined app identifier. Check Firebase app initialization.","storage-open":"Error thrown when opening storage. Original error: {$originalErrorMessage}.","storage-get":"Error thrown when reading from storage. Original error: {$originalErrorMessage}.","storage-set":"Error thrown when writing to storage. Original error: {$originalErrorMessage}.","storage-delete":"Error thrown when deleting from storage. Original error: {$originalErrorMessage}.","fetch-client-network":"Fetch client failed to connect to a network. Check Internet connection. Original error: {$originalErrorMessage}.","fetch-timeout":'The config fetch request timed out.  Configure timeout using "fetchTimeoutMillis" SDK setting.',"fetch-throttle":'The config fetch request timed out while in an exponential backoff state. Configure timeout using "fetchTimeoutMillis" SDK setting. Unix timestamp in milliseconds when fetch request throttling ends: {$throttleEndTimeMillis}.',"fetch-client-parse":"Fetch client could not parse response. Original error: {$originalErrorMessage}.","fetch-status":"Fetch server returned an HTTP error status. HTTP status: {$httpStatus}.","indexed-db-unavailable":"Indexed DB is not supported by current browser"});const MW=["1","true","t","yes","y","on"];class FW{constructor(e,t=""){this._source=e,this._value=t}asString(){return this._value}asBoolean(){return"static"!==this._source&&0<=MW.indexOf(this._value.toLowerCase())}asNumber(){if("static"===this._source)return 0;let e=Number(this._value);return isNaN(e)&&(e=0),e}getSource(){return this._source}}async function UW(e){const t=zd(e);var[n,r]=await Promise.all([t._storage.getLastSuccessfulFetchResponse(),t._storage.getActiveConfigEtag()]);return!!(n&&n.config&&n.eTag&&n.eTag!==r)&&(await Promise.all([t._storageCache.setActiveConfig(n.config),t._storage.setActiveConfigEtag(n.eTag)]),!0)}function jW(e){const t=zd(e);return t._initializePromise||(t._initializePromise=t._storageCache.loadFromStorage().then(()=>{t._isInitializationComplete=!0})),t._initializePromise}async function qW(t){const n=zd(t),e=new DW;setTimeout(async()=>{e.abort()},n.settings.fetchTimeoutMillis);try{await n._client.fetch({cacheMaxAgeMillis:n.settings.minimumFetchIntervalMillis,signal:e}),await n._storageCache.setLastFetchStatus("success")}catch(e){var r=(i="fetch-throttle",(t=e)instanceof gd&&-1!==t.code.indexOf(i)?"throttle":"failure");throw await n._storageCache.setLastFetchStatus(r),e}var i}function VW(n){const e=zd(n);return[t={},r={}]=[e._storageCache.getActiveConfig(),e.defaultConfig],Object.keys(Object.assign(Object.assign({},t),r)).reduce((e,t)=>(e[t]=BW(n,t),e),{});var t,r}function BW(e,t){const n=zd(e);n._isInitializationComplete||n._logger.debug(`A value was requested for key "${t}" before SDK initialization completed.`+" Await on ensureInitialized if the intent was to get a previously activated value.");var r=n._storageCache.getActiveConfig();return r&&void 0!==r[t]?new FW("remote",r[t]):n.defaultConfig&&void 0!==n.defaultConfig[t]?new FW("default",String(n.defaultConfig[t])):(n._logger.debug(`Returning static value for key "${t}".`+" Define a default or remote value if this is unintentional."),new FW("static"))}class WW{constructor(e,t,n,r){this.client=e,this.storage=t,this.storageCache=n,this.logger=r}isCachedDataFresh(e,t){if(!t)return this.logger.debug("Config fetch cache check. Cache unpopulated."),!1;var n=Date.now()-t,r=n<=e;return this.logger.debug("Config fetch cache check."+` Cache age millis: ${n}.`+` Cache max age millis (minimumFetchIntervalMillis setting): ${e}.`+` Is cache hit: ${r}.`),r}async fetch(e){var[t,n]=await Promise.all([this.storage.getLastSuccessfulFetchTimestampMillis(),this.storage.getLastSuccessfulFetchResponse()]);if(n&&this.isCachedDataFresh(e.cacheMaxAgeMillis,t))return n;e.eTag=n&&n.eTag;n=await this.client.fetch(e);const r=[this.storageCache.setLastSuccessfulFetchTimestampMillis(Date.now())];return 200===n.status&&r.push(this.storage.setLastSuccessfulFetchResponse(n)),await Promise.all(r),n}}class zW{constructor(e,t,n,r,i,s){this.firebaseInstallations=e,this.sdkVersion=t,this.namespace=n,this.projectId=r,this.apiKey=i,this.appId=s}async fetch(n){var e,[t,r]=await Promise.all([this.firebaseInstallations.getId(),this.firebaseInstallations.getToken()]),i=`${window.FIREBASE_REMOTE_CONFIG_URL_BASE||"https://firebaseremoteconfig.googleapis.com"}/v1/projects/${this.projectId}/namespaces/${this.namespace}:fetch?key=${this.apiKey}`,s={"Content-Type":"application/json","Content-Encoding":"gzip","If-None-Match":n.eTag||"*"},r={sdk_version:this.sdkVersion,app_instance_id:t,app_instance_id_token:r,app_id:this.appId,language_code:(e=navigator).languages&&e.languages[0]||e.language},r={method:"POST",headers:s,body:JSON.stringify(r)},i=fetch(i,r),r=new Promise((e,t)=>{n.signal.addEventListener(()=>{const e=new Error("The operation was aborted.");e.name="AbortError",t(e)})});let o;try{await Promise.race([i,r]),o=await i}catch(e){let t="fetch-client-network";throw"AbortError"===e.name&&(t="fetch-timeout"),LW.create(t,{originalErrorMessage:e.message})}let a=o.status;i=o.headers.get("ETag")||void 0;let c,l;if(200===o.status){let e;try{e=await o.json()}catch(e){throw LW.create("fetch-client-parse",{originalErrorMessage:e.message})}c=e.entries,l=e.state}if("INSTANCE_STATE_UNSPECIFIED"===l?a=500:"NO_CHANGE"===l?a=304:"NO_TEMPLATE"!==l&&"EMPTY_CONFIG"!==l||(c={}),304!==a&&200!==a)throw LW.create("fetch-status",{httpStatus:a});return{status:a,eTag:i,config:c}}}class KW{constructor(e,t){this.client=e,this.storage=t}async fetch(e){var t=await this.storage.getThrottleMetadata()||{backoffCount:0,throttleEndTimeMillis:Date.now()};return this.attemptFetch(e,t)}async attemptFetch(t,{throttleEndTimeMillis:e,backoffCount:n}){var i,s;i=t.signal,s=e,await new Promise((e,t)=>{var n=Math.max(s-Date.now(),0);const r=setTimeout(e,n);i.addEventListener(()=>{clearTimeout(r),t(LW.create("fetch-throttle",{throttleEndTimeMillis:s}))})});try{var r=await this.client.fetch(t);return await this.storage.deleteThrottleMetadata(),r}catch(e){if(!function(e){if(e instanceof gd&&e.customData){var t=Number(e.customData.httpStatus);return 429===t||500===t||503===t||504===t}}(e))throw e;r={throttleEndTimeMillis:Date.now()+Wd(n),backoffCount:n+1};return await this.storage.setThrottleMetadata(r),this.attemptFetch(t,r)}}}class $W{constructor(e,t,n,r,i){this.app=e,this._client=t,this._storageCache=n,this._storage=r,this._logger=i,this._isInitializationComplete=!1,this.settings={fetchTimeoutMillis:6e4,minimumFetchIntervalMillis:432e5},this.defaultConfig={}}get fetchTimeMillis(){return this._storageCache.getLastSuccessfulFetchTimestampMillis()||-1}get lastFetchStatus(){return this._storageCache.getLastFetchStatus()||"no-fetch-yet"}}function HW(e,t){var n=e.target.error||void 0;return LW.create(t,{originalErrorMessage:n&&n.message})}const GW="app_namespace_store";class QW{constructor(e,t,n,r=function(){return new Promise((t,n)=>{try{const e=indexedDB.open("firebase_remote_config",1);e.onerror=e=>{n(HW(e,"storage-open"))},e.onsuccess=e=>{t(e.target.result)},e.onupgradeneeded=e=>{const t=e.target.result;0===e.oldVersion&&t.createObjectStore(GW,{keyPath:"compositeKey"})}}catch(e){n(LW.create("storage-open",{originalErrorMessage:e}))}})}()){this.appId=e,this.appName=t,this.namespace=n,this.openDbPromise=r}getLastFetchStatus(){return this.get("last_fetch_status")}setLastFetchStatus(e){return this.set("last_fetch_status",e)}getLastSuccessfulFetchTimestampMillis(){return this.get("last_successful_fetch_timestamp_millis")}setLastSuccessfulFetchTimestampMillis(e){return this.set("last_successful_fetch_timestamp_millis",e)}getLastSuccessfulFetchResponse(){return this.get("last_successful_fetch_response")}setLastSuccessfulFetchResponse(e){return this.set("last_successful_fetch_response",e)}getActiveConfig(){return this.get("active_config")}setActiveConfig(e){return this.set("active_config",e)}getActiveConfigEtag(){return this.get("active_config_etag")}setActiveConfigEtag(e){return this.set("active_config_etag",e)}getThrottleMetadata(){return this.get("throttle_metadata")}setThrottleMetadata(e){return this.set("throttle_metadata",e)}deleteThrottleMetadata(){return this.delete("throttle_metadata")}async get(o){const a=await this.openDbPromise;return new Promise((n,t)=>{const e=a.transaction([GW],"readonly"),r=e.objectStore(GW);var i=this.createCompositeKey(o);try{const s=r.get(i);s.onerror=e=>{t(HW(e,"storage-get"))},s.onsuccess=e=>{var t=e.target.result;n(t?t.value:void 0)}}catch(e){t(LW.create("storage-get",{originalErrorMessage:e&&e.message}))}})}async set(o,a){const c=await this.openDbPromise;return new Promise((e,t)=>{const n=c.transaction([GW],"readwrite"),r=n.objectStore(GW);var i=this.createCompositeKey(o);try{const s=r.put({compositeKey:i,value:a});s.onerror=e=>{t(HW(e,"storage-set"))},s.onsuccess=()=>{e()}}catch(e){t(LW.create("storage-set",{originalErrorMessage:e&&e.message}))}})}async delete(o){const a=await this.openDbPromise;return new Promise((e,t)=>{const n=a.transaction([GW],"readwrite"),r=n.objectStore(GW);var i=this.createCompositeKey(o);try{const s=r.delete(i);s.onerror=e=>{t(HW(e,"storage-delete"))},s.onsuccess=()=>{e()}}catch(e){t(LW.create("storage-delete",{originalErrorMessage:e&&e.message}))}})}createCompositeKey(e){return[this.appId,this.appName,this.namespace,e].join()}}class YW{constructor(e){this.storage=e}getLastFetchStatus(){return this.lastFetchStatus}getLastSuccessfulFetchTimestampMillis(){return this.lastSuccessfulFetchTimestampMillis}getActiveConfig(){return this.activeConfig}async loadFromStorage(){var e=this.storage.getLastFetchStatus(),t=this.storage.getLastSuccessfulFetchTimestampMillis(),n=this.storage.getActiveConfig(),e=await e;e&&(this.lastFetchStatus=e);t=await t;t&&(this.lastSuccessfulFetchTimestampMillis=t);n=await n;n&&(this.activeConfig=n)}setLastFetchStatus(e){return this.lastFetchStatus=e,this.storage.setLastFetchStatus(e)}setLastSuccessfulFetchTimestampMillis(e){return this.lastSuccessfulFetchTimestampMillis=e,this.storage.setLastSuccessfulFetchTimestampMillis(e)}setActiveConfig(e){return this.activeConfig=e,this.storage.setActiveConfig(e)}}async function XW(){if(!dd())return!1;try{return await pd()}catch(e){return!1}}hp(new Kd("remote-config",function(e,{instanceIdentifier:t}){var n=e.getProvider("app").getImmediate(),r=e.getProvider("installations-internal").getImmediate();if("undefined"==typeof window)throw LW.create("registration-window");if(!dd())throw LW.create("indexed-db-unavailable");var{projectId:i,apiKey:s,appId:o}=n.options;if(!i)throw LW.create("registration-project-id");if(!s)throw LW.create("registration-api-key");if(!o)throw LW.create("registration-app-id");t=t||"firebase";const a=new QW(o,n.name,t),c=new YW(a),l=new ep(OW);l.logLevel=zh.ERROR;o=new zW(r,gp,t,i,s,o),o=new KW(o,a),o=new WW(o,a,c,l),o=new $W(n,o,c,a,l);return jW(o),o},"PUBLIC").setMultipleInstances(!0)),_p(OW,"0.3.4"),_p(OW,"0.3.4","esm2017");class JW{constructor(e,t){this.app=e,this._delegate=t}get defaultConfig(){return this._delegate.defaultConfig}set defaultConfig(e){this._delegate.defaultConfig=e}get fetchTimeMillis(){return this._delegate.fetchTimeMillis}get lastFetchStatus(){return this._delegate.lastFetchStatus}get settings(){return this._delegate.settings}set settings(e){this._delegate.settings=e}activate(){return UW(this._delegate)}ensureInitialized(){return jW(this._delegate)}fetch(){return qW(this._delegate)}fetchAndActivate(){return async function(e){return await qW(e=zd(e)),UW(e)}(this._delegate)}getAll(){return VW(this._delegate)}getBoolean(e){return BW(zd(this._delegate),e).asBoolean()}getNumber(e){return BW(zd(this._delegate),e).asNumber()}getString(e){return BW(zd(this._delegate),e).asString()}getValue(e){return BW(this._delegate,e)}setLogLevel(e){!function(e,t){const n=zd(e);switch(t){case"debug":n._logger.logLevel=zh.DEBUG;break;case"silent":n._logger.logLevel=zh.SILENT;break;default:n._logger.logLevel=zh.ERROR}}(this._delegate,e)}}function ZW(e,{instanceIdentifier:t}){var n=e.getProvider("app-compat").getImmediate(),r=e.getProvider("remote-config").getImmediate({identifier:t});return new JW(n,r)}return(MB=Cp).INTERNAL.registerComponent(new Kd("remoteConfig-compat",ZW,"PUBLIC").setMultipleInstances(!0).setServiceProps({isSupported:XW})),MB.registerVersion("@firebase/remote-config-compat","0.1.5"),console.warn("\nIt looks like you're using the development build of the Firebase JS SDK.\nWhen deploying Firebase apps to production, it is advisable to only import\nthe individual SDK components you intend to use.\n\nFor the CDN builds, these are available in the following manner\n(replace <PACKAGE> with the name of a component - i.e. auth, database, etc):\n\nhttps://www.gstatic.com/firebasejs/5.0.0/firebase-<PACKAGE>.js\n"),Cp.registerVersion("firebase","9.6.6","compat-cdn"),Cp});
//# sourceMappingURL=firebase-compat.js.map
