firebase 9.4.1 → 9.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/app/dist/index.cjs.js +1 -1
  3. package/app/dist/index.esm.js +1 -1
  4. package/app/dist/index.mjs +1 -1
  5. package/compat/app/dist/index.cjs.js +1 -1
  6. package/compat/app/dist/index.esm.js +1 -1
  7. package/compat/app/dist/index.mjs +1 -1
  8. package/compat/dist/index.esm.js +2 -2
  9. package/compat/dist/index.node.cjs +2 -2
  10. package/compat/dist/index.rn.cjs.js +2 -2
  11. package/firebase-analytics.js +3 -3
  12. package/firebase-app-check-compat.js +2 -2
  13. package/firebase-app-check-compat.js.map +1 -1
  14. package/firebase-app-check.js +285 -50
  15. package/firebase-app-check.js.map +1 -1
  16. package/firebase-app-compat.js +2 -2
  17. package/firebase-app-compat.js.map +1 -1
  18. package/firebase-app.js +9 -9
  19. package/firebase-auth.js +2 -2
  20. package/firebase-compat.js +4 -4
  21. package/firebase-compat.js.map +1 -1
  22. package/firebase-database.js +4 -4
  23. package/firebase-firestore-compat.js +1 -1
  24. package/firebase-firestore-compat.js.map +1 -1
  25. package/firebase-firestore-lite.js +7 -7
  26. package/firebase-firestore-lite.js.map +1 -1
  27. package/firebase-firestore.js +12 -12
  28. package/firebase-firestore.js.map +1 -1
  29. package/firebase-functions.js +2 -2
  30. package/firebase-messaging-sw.js +1 -1
  31. package/firebase-messaging.js +1 -1
  32. package/firebase-performance-standalone-compat.es2017.js +5 -5
  33. package/firebase-performance-standalone-compat.es2017.js.map +1 -1
  34. package/firebase-performance-standalone-compat.js +1 -1
  35. package/firebase-performance-standalone-compat.js.map +1 -1
  36. package/firebase-performance.js +3 -3
  37. package/firebase-remote-config.js +2 -2
  38. package/firebase-storage-compat.js +1 -1
  39. package/firebase-storage-compat.js.map +1 -1
  40. package/firebase-storage.js +177 -24
  41. package/firebase-storage.js.map +1 -1
  42. package/package.json +9 -9
@@ -1,10 +1,10 @@
1
- !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 f(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 p(t){this.map={},t instanceof p?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 p(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 p(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 p(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))}),p.prototype.append=function(e,t){e=h(e),t=d(t);var n=this.map[e];this.map[e]=n?n+","+t:t},p.prototype.delete=function(e){delete this.map[h(e)]},p.prototype.get=function(e){return e=h(e),this.has(e)?this.map[e]:null},p.prototype.has=function(e){return this.map.hasOwnProperty(h(e))},p.prototype.set=function(e,t){this.map[h(e)]=d(t)},p.prototype.forEach=function(e,t){for(var n in this.map)this.map.hasOwnProperty(n)&&e.call(t,this.map[n],n,this)},p.prototype.keys=function(){var n=[];return this.forEach(function(e,t){n.push(t)}),f(n)},p.prototype.values=function(){var t=[];return this.forEach(function(e){t.push(e)}),f(t)},p.prototype.entries=function(){var n=[];return this.forEach(function(e,t){n.push([t,e])}),f(n)},n&&(p.prototype[Symbol.iterator]=p.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 p(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=p,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 p,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):{}},f=d,p=!o&&!e(function(){return 7!=Object.defineProperty(f("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=p,_=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,S=o?function(e,t,n){return T.f(e,t,E(1,n))}:function(e,t,n){return e[t]=n,e},k=i,C=S,A=function(t,n){try{C(k,t,n)}catch(e){k[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,$=O,K=D,z=j,W=q,H=B("wks"),G=V.Symbol,Q=W?G:G&&G.withoutSetter||K,Y=function(e){return $(H,e)||(z&&$(G,e)?H[e]=G[e]:H[e]=Q("Symbol."+e)),H[e]},J={};J[Y("toStringTag")]="z";var X="[object z]"===String(J),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,fe="function"==typeof de&&/native code/.test(he(de)),pe=s.exports,ge=D,me=pe("keys"),ve=function(e){return me[e]||(me[e]=ge(e))},ye={},_e=c,we=S,be=O,Ie=ve,Te=ye,Ee=i.WeakMap;ce=fe?(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 Se={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}}},ke=i,Ce=S,Ae=O,Ne=A,Re=ue,Pe=Se.get,xe=Se.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!==ke?(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=X,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;X||Be(Object.prototype,"toString",X?{}.toString:function(){return"[object "+Ve(this)+"]"},{unsafe:!0});var $e=Math.ceil,Ke=Math.floor,ze=function(e){return isNaN(e=+e)?0:(0<e?Ke:$e)(e)},We=function(e){if(null==e)throw TypeError("Can't call method on "+e);return e},He=ze,Ge=We,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)},Je={},Xe={},Ze={}.propertyIsEnumerable,et=Object.getOwnPropertyDescriptor,tt=et&&!Ze.call({1:2},1);Xe.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=We,lt=Xe,ut=I,ht=nt,dt=v,ft=O,pt=p,gt=Object.getOwnPropertyDescriptor;Je.f=o?gt:function(e,t){if(e=ht(e),t=dt(t,!0),pt)try{return gt(e,t)}catch(e){}if(ft(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=ze,Tt=Math.min,Et=function(e){return 0<e?Tt(It(e),9007199254740991):0},St=ze,kt=Math.max,Ct=Math.min,At=nt,Nt=Et,Rt=function(e,t){var n=St(e);return n<0?kt(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,$t=Je,Kt=a,U=function(e,t){for(var n=Bt(t),r=Kt.f,i=$t.f,s=0;s<n.length;s++){var o=n[s];Vt(e,o)||r(e,o,i(t,o))}},zt=e,Wt=/#|\.prototype\./,B=function(e,t){var n=Gt[Ht(e)];return n==Yt||n!=Qt&&("function"==typeof t?zt(t):!!t)},Ht=B.normalize=function(e){return String(e).replace(Wt,".").toLowerCase()},Gt=B.data={},Qt=B.NATIVE="N",Yt=B.POLYFILL="P",V=B,Jt=i,Xt=Je.f,Zt=S,en=Z.exports,tn=A,nn=U,rn=V,W=function(e,t){var n,r,i,s=e.target,o=e.global,a=e.stat,c=o?Jt:a?Jt[s]||tn(s,{}):(Jt[s]||{}).prototype;if(c)for(n in t){if(r=t[n],i=e.noTargetGet?(i=Xt(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=We,K=function(e){return Object(sn(e))},J=!e(function(){function e(){}return e.prototype.constructor=null,Object.getPrototypeOf(new e)!==e.prototype}),on=O,an=K,P=J,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=S,pe=O,fe=Y("iterator"),Ee=!1;[].keys&&("next"in(or=[].keys())?(ar=he(he(or)))!==Object.prototype&&(Er=ar):Ee=!0),pe(Er=null==Er?{}:Er,fe)||de(Er,fe,function(){return this});function un(){}var hn,Te={IteratorPrototype:Er,BUGGY_SAFARI_ITERATORS:Ee},dn=n,fn=l,Ie=Object.keys||function(e){return dn(e,fn)},pn=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;)pn.f(e,n=r[s++],t[n]);return e},Be=vt("document","documentElement"),vn=t,yn=Me,_n=l,X=ye,wn=Be,bn=d,In="prototype",Tn="script",En=ve("IE_PROTO"),Sn=function(e){return"<"+Tn+">"+e+"</"+Tn+">"},kn=function(){try{hn=document.domain&&new ActiveXObject("htmlfile")}catch(e){}var e,t;kn=hn?function(e){e.write(Sn("")),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(Sn("document.F=Object")),e.close(),e.F);for(var n=_n.length;n--;)delete kn[In][_n[n]];return kn()};X[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=kn(),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=W,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,$n=rt,Kn=tt,zn=S,Wn=Z.exports,p=Y,Hn=Ze,Gn=Te.IteratorPrototype,Qn=Te.BUGGY_SAFARI_ITERATORS,Yn=p("iterator"),Jn="values",Xn="entries",Pt=function(e,t,n,r,i,s,o){Vn(n,t,r);function a(e){if(e===i&&p)return p;if(!Qn&&e in d)return d[e];switch(e){case"keys":case Jn:case Xn:return function(){return new n(this,e)}}return function(){return new n(this)}}var c,l,u=t+" Iterator",h=!1,d=e.prototype,f=d[Yn]||d["@@iterator"]||i&&d[i],p=!Qn&&f||a(i),g="Array"==t&&d.entries||f;if(g&&(g=Bn(g.call(new e)),Gn!==Object.prototype&&g.next&&(Bn(g)!==Gn&&($n?$n(g,Gn):"function"!=typeof g[Yn]&&zn(g,Yn,An)),Kn(g,u,!0))),i==Jn&&f&&f.name!==Jn&&(h=!0,p=function(){return f.call(this)}),d[Yn]!==p&&zn(d,Yn,p),Hn[t]=p,i)if(c={values:a(Jn),keys:s?p:a("keys"),entries:a(Xn)},o)for(l in c)!Qn&&!h&&l in d||Wn(d,l,c[l]);else qn({target:t,proto:!0,forced:Qn||h},c);return c},Zn=Ye.charAt,r=Se,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 J=function(e){ir[rr][e]=!0},sr=nt,P=J,he=Ze,or=Se,ar=Pt,cr="Array Iterator",lr=or.set,ur=or.getterFor(cr),pe=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,fr={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},pr=pe,gr=S,de=Y,mr=de("iterator"),vr=de("toStringTag"),yr=pr.values;for(hr in fr){var _r=dr[hr],wr=_r&&_r.prototype;if(wr){if(wr[mr]!==yr)try{gr(wr,mr,yr)}catch(lb){wr[mr]=yr}if(wr[vr]||gr(wr,vr,hr),fr[hr])for(var br in pr)if(wr[br]!==pr[br])try{gr(wr,br,pr[br])}catch(lb){wr[br]=pr[br]}}}function Ir(e,t){this.stopped=e,this.result=t}var fe=i.Promise,Tr=Z.exports,Er=function(e,t,n){for(var r in t)Tr(e,r,t[r],n);return e},Sr=vt,kr=a,Cr=o,Ar=Y("species"),Ee=function(e){var t=Sr(e),n=kr.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,X=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"),p=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=X,jr=Et,qr=Te,Vr=p,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 $r=Y("iterator"),Kr=!1;try{var zr=0,Wr={next:function(){return{done:!!zr++}},return:function(){Kr=!0}};Wr[$r]=function(){return this},Array.from(Wr,function(){throw 2})}catch(lb){}function Hr(e){return function(){ai(e)}}var Gr,r=function(e,t){if(!t&&!Kr)return!1;var n=!1;try{var r={};r[$r]=function(){return{next:function(){return{done:n=!0}}}},e(r)}catch(e){}return n},Qr=t,Yr=n,Jr=Y("species"),R=function(e,t){var n,r=Qr(e).constructor;return void 0===r||null==(n=Qr(r)[Jr])?t:Yr(n)},A=vt("navigator","userAgent")||"",B=/(iphone|ipod|ipad).*applewebkit/i.test(A),Xr=i,or=e,ar=Le,he=Te,Zr=Be,ei=d,P=B,ti=Xr.location,de=Xr.setImmediate,Ze=Xr.clearImmediate,ni=Xr.process,Wr=Xr.MessageChannel,ri=Xr.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){Xr.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))}:Wr&&!P?(wi=(yi=new Wr).port2,yi.port1.onmessage=Be,Gr=he(wi.postMessage,wi,1)):!Xr.addEventListener||"function"!=typeof postMessage||Xr.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,Xr.addEventListener("message",Be,!1)));var ci,li,ui,hi,di,fi,pi,gi,ar={set:de,clear:Ze},mi=i,P=Je.f,Wr=Le,vi=ar.set,yi=B,he=mi.MutationObserver||mi.WebKitMutationObserver,_i=mi.process,wi=mi.Promise,bi="process"==Wr(_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,fi=document.createTextNode(""),new he(ci).observe(fi,{characterData:!0}),function(){fi.data=di=!di}):wi&&wi.resolve?(pi=wi.resolve(void 0),gi=pi.then,function(){gi.call(pi,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,Si=c,ki=de,Ze=function(e,t){if(Ei(e),Si(t)&&t.constructor===e)return t;var n=ki.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}}},Wr=A,P=i.process,or=P&&P.versions,yi=or&&or.v8;yi?ji=(Mi=yi.split("."))[0]+Mi[1]:Wr&&(!(Mi=Wr.match(/Edge\/(\d+)/))||74<=Mi[1])&&(Mi=Wr.match(/Chrome\/(\d+)/))&&(ji=Mi[1]);var Ai,Ni,Ri,Pi,he=ji&&+ji,wi=W,xi=i,d=vt,A=fe,P=Z.exports,or=Er,yi=tt,Wr=Ee,Oi=c,Di=n,Li=Me,Mi=Le,Fi=ue,Ui=l.exports,ji=r,qi=R,Vi=ar.set,Bi=Be,$i=Ze,Ki=function(e,t){var n=Ci.console;n&&n.error&&(1===arguments.length?n.error(e):n.error(e,t))},ue=de,zi=B,ar=Se,Be=V,Wi=he,Hi=Y("species"),Gi="Promise",Qi=ar.get,Yi=ar.set,Ji=ar.getterFor(Gi),Xi=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(Xi)!==String(Xi))){if(66===Wi)return!0;if(!ss&&"function"!=typeof PromiseRejectionEvent)return!0}if(51<=Wi&&/native code/.test(Xi))return!1;function e(e){e(function(){},function(){})}var t=Xi.resolve(1);return(t.constructor={})[Hi]=e,!(t.then(function(){})instanceof e)}),ji=Be||!ji(function(e){Xi.all(e).catch(function(){})}),fs=function(e){var t;return!(!Oi(e)||"function"!=typeof(t=e.then))&&t},ps=function(f,p,g){var m;p.notified||(p.notified=!0,m=p.reactions,Bi(function(){for(var r,i,e=p.value,t=p.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||(p.rejection===ds&&function(e,t){Vi.call(xi,function(){if(ss)ts.emit("rejectionHandled",e);else gs(cs,e,t.value)})}(f,p),p.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=fs(s))?o.call(s,u,h):u(s)):h(e)}catch(e){d&&!a&&d.exit(),h(e)}}p.reactions=[],p.notified=!1,g&&!p.rejection&&(r=f,i=p,Vi.call(xi,function(){var e,t=i.value,n=ms(i);if(n&&(e=zi(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&&Ki("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,ps(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=fs(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,ps(n,r,!1))}catch(e){ys(n,{done:!1},e,r)}}};Be&&(Xi=function(e){Li(this,Xi,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(Xi.prototype,{then:function(e,t){var n=Ji(this),r=rs(qi(this,Xi));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&&ps(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===Xi||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 Xi(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 $i(Xi,ns.apply(xi,arguments))}}))),wi({global:!0,wrap:!0,forced:Be},{Promise:Xi}),yi(Xi,Gi,!1),Wr(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 $i(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=zi(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=zi(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=W,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=W,Es=fe,wi=e,Ss=vt,ks=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=ks(this,Ss("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",Ss("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=W,Ns=o,Rs=ee,Ps=rt,fe=Qe,Ze=a,Be=I,xs=l.exports,Os=S,wi=Se,Ds=wi.set,Ls=wi.getterFor("AggregateError");As.prototype=fe(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;W({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=W,Us=n,js=vt,qs=de,Vs=B,Bs=l.exports,$s="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,$s)))})}),--o||u(new(js("AggregateError"))(i,$s))});return n.error&&u(n.value),t.promise}});function Ks(e){throw e}var zs=Le,wi=Array.isArray||function(e){return"Array"==zs(e)},Ws=c,Hs=wi,Gs=Y("species"),fe=function(e,t){var n;return new(void 0===(n=Hs(e)&&("function"==typeof(n=e.constructor)&&(n===Array||Hs(n.prototype))||Ws(n)&&null===(n=n[Gs]))?void 0:n)?Array:n)(0===t?0:t)},Qs=Te,Ys=ot,Js=K,Xs=Et,Zs=fe,eo=[].push,Be=function(f){var p=1==f,g=2==f,m=3==f,v=4==f,y=6==f,_=5==f||y;return function(e,t,n,r){for(var i,s,o=Js(e),a=Ys(o),c=Qs(t,n,3),l=Xs(a.length),u=0,h=r||Zs,d=p?h(e,l):g?h(e,0):void 0;u<l;u++)if((_||u in a)&&(s=c(i=a[u],u,o),f))if(p)d[u]=s;else if(s)switch(f){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]:Ks,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:Ks}):e[1]=1,n.call(e,i,s)})},de=W,oo=Ze.find,B=J,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=W,ho=Ze.findIndex,B=J,ji="findIndex",fo=!0,J=d(ji);ji in[]&&Array(1)[ji](function(){fo=!1}),Be({target:"Array",proto:!0,forced:fo||!J},{findIndex:function(e){return ho(this,e,1<arguments.length?arguments[1]:void 0)}}),B(ji),de("Array","findIndex");var po=v,go=a,mo=I,J=function(e,t,n){var r=po(t);r in e?go.f(e,r,mo(0,n)):e[r]=n},vo=Te,yo=K,_o=Ye,wo=X,bo=Et,Io=J,To=p,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),f=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));f<t;f++)o=h?u(a[f],f):a[f],Io(n,f,o);else for(s=(i=d.call(a)).next,n=new c;!(r=s.call(i)).done;f++)o=h?_o(i,u,[r.value,f],!0):r.value,Io(n,f,o);return n.length=f,n};W({target:"Array",stat:!0,forced:!r(function(e){Array.from(e)})},{from:B}),yt.Array.from;var Eo=e,ji=W,So=Ze.some,Ye=d,X=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:!X||!B},{some:function(e){return So(this,e,1<arguments.length?arguments[1]:void 0)}}),de("Array","some");function ko(e){return Ro(e)&&Po($o,xo(e))}var Co,d="undefined"!=typeof ArrayBuffer&&"undefined"!=typeof DataView,Ao=o,No=i,Ro=c,Po=O,xo=qe,Oo=S,Do=Z.exports,Ye=a.f,ji=ee,Lo=rt,X=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,X=X("toStringTag"),Vo=B("TYPED_ARRAY_TAG"),Bo=d&&!!Lo&&"Opera"!==xo(No.opera),d=!1,$o={Int8Array:1,Uint8Array:1,Uint8ClampedArray:1,Int16Array:2,Uint16Array:2,Int32Array:4,Uint32Array:4,Float32Array:4,Float64Array:8};for(Co in $o)No[Co]||(Bo=!1);if((!Bo||"function"!=typeof Uo||Uo===Function.prototype)&&(Uo=function(){throw TypeError("Incorrect invocation")},Bo))for(Co in $o)No[Co]&&Lo(No[Co],Uo);if((!Bo||!jo||jo===qe)&&(jo=Uo.prototype,Bo))for(Co in $o)No[Co]&&Lo(No[Co].prototype,jo);if(Bo&&ji(ee)!==jo&&Lo(ee,jo),Ao&&!Po(jo,X))for(Co in d=!0,Ye(jo,X,{get:function(){return Ro(this)?this[Vo]:void 0}}),$o)No[Co]&&Oo(No[Co],Vo,Co);var Ye=i,X={NATIVE_ARRAY_BUFFER_VIEWS:Bo,TYPED_ARRAY_TAG:d&&Vo,aTypedArray:function(e){if(ko(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 $o)if(Po($o,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 $o){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 $o)(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 $o)!(i=No[r])||i[e]&&!n||Do(i,e,t)}},isView:function(e){var t=xo(e);return"DataView"===t||Po($o,t)},isTypedArray:ko,TypedArray:Uo,TypedArrayPrototype:jo},d=pe,pe=Y("iterator"),Ye=Ye.Uint8Array,Ko=d.values,zo=d.keys,Wo=d.entries,Ho=X.aTypedArray,d=X.exportTypedArrayMethod,X=Ye&&Ye.prototype[pe],Ye=!!X&&("values"==X.name||null==X.name),X=function(){return Ko.call(Ho(this))};d("entries",function(){return Wo.call(Ho(this))}),d("keys",function(){return zo.call(Ho(this))}),d("values",X,!Ye),d(pe,X,!Ye);var Go=o,X=e,Qo=Ie,Yo=N,Jo=Xe,Xo=K,Zo=ot,ea=Object.assign,ta=Object.defineProperty,Ye=!ea||X(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=Xo(e),r=arguments.length,i=1,s=Yo.f,o=Jo.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;W({target:"Object",stat:!0,forced:Object.assign!==Ye},{assign:Ye}),yt.Object.assign;var na=o,ra=Ie,ia=nt,sa=Xe.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}},X={entries:ot(!0),values:ot(!1)},Ye=W,oa=X.entries;Ye({target:"Object",stat:!0},{entries:function(e){return oa(e)}}),yt.Object.entries;var ot=W,aa=X.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"),X=function(t){var n=/./;try{"/./"[t](n)}catch(e){try{return n[da]=!1,"/./"[t](n)}catch(e){}}return!1},fa=Ye,pa=We;W({target:"String",proto:!0,forced:!X("includes")},{includes:function(e){return!!~String(pa(this)).indexOf(fa(e),1<arguments.length?arguments[1]:void 0)}}),de("String","includes");var ot=W,Le=Je.f,ga=Et,ma=Ye,va=We,X=X,ya="".startsWith,_a=Math.min,X=X("startsWith");ot({target:"String",proto:!0,forced:!!(X||(!(Le=Le(String.prototype,"startsWith"))||Le.writable))&&!X},{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=ze,ba=We;W({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"),ze=W,We=e,Sa=wi,ka=c,Ca=K,Aa=Et,Na=J,Ra=fe,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",J=51<=Et||!We(function(){var e=[];return e[Pa]=!1,e.concat()[0]!==e}),fe=de("concat");ze({target:"Array",proto:!0,forced:!J||!fe},{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(!ka(e))return!1;var t=e[Pa];return void 0!==t?!!t:Sa(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(fc[lc]);return uc(n,{type:cc,tag:e,description:t}),Ka||(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){Ka&&!Cc.call(n,e)||kc(t,e,n[e])}),t}var qa=yt,Va=O,Ba=Et,$a=a.f,We=function(e){var t=qa.Symbol||(qa.Symbol={});Va(t,e)||$a(t,e,{value:Ba.f(e)})},de=W,ze=i,J=vt,Ka=o,fe=j,j=q,q=e,za=O,Wa=wi,Ha=c,Ga=t,Qa=K,Ya=nt,Ja=v,Xa=I,Za=Qe,ec=Ie,v=bt,I=he,tc=N,Ie=Je,bt=a,he=Xe,N=S,Je=Z.exports,Xe=s.exports,S=ve,nc=ye,rc=D,ic=Y,s=Et,sc=We,ve=tt,Y=Se,oc=Ze.forEach,ac=S("hidden"),cc="Symbol",lc="prototype",S=ic("toPrimitive"),uc=Y.set,hc=Y.getterFor(cc),dc=Object[lc],fc=ze.Symbol,pc=J("JSON","stringify"),gc=Ie.f,mc=bt.f,vc=I.f,yc=he.f,_c=Xe("symbols"),wc=Xe("op-symbols"),bc=Xe("string-to-symbol-registry"),Ic=Xe("symbol-to-string-registry"),Xe=Xe("wks"),ze=ze.QObject,Tc=!ze||!ze[lc]||!ze[lc].findChild,Ec=Ka&&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,Sc=j?function(e){return"symbol"==typeof e}:function(e){return Object(e)instanceof fc},kc=function(e,t,n){e===dc&&kc(wc,t,n),Ga(e);var r=Ja(t,!0);return Ga(n),za(_c,r)?(n.enumerable?(za(e,ac)&&e[ac][r]&&(e[ac][r]=!1),n=Za(n,{enumerable:Xa(0,!1)})):(za(e,ac)||mc(e,ac,Xa(1,{})),e[ac][r]=!0),Ec(e,r,n)):mc(e,r,n)},Cc=function(e){var t=Ja(e,!0),n=yc.call(this,t);return!(this===dc&&za(_c,t)&&!za(wc,t))&&(!(n||!za(this,t)||!za(_c,t)||za(this,ac)&&this[ac][t])||n)},ze=function(e,t){var n=Ya(e),r=Ja(t,!0);if(n!==dc||!za(_c,r)||za(wc,r)){var i=gc(n,r);return!i||!za(_c,r)||za(n,ac)&&n[ac][r]||(i.enumerable=!0),i}},j=function(e){var t=vc(Ya(e)),n=[];return oc(t,function(e){za(_c,e)||za(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){!za(_c,e)||t&&!za(dc,e)||r.push(_c[e])}),r};fe||(Je((fc=function(){if(this instanceof fc)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),za(this,ac)&&za(this[ac],t)&&(this[ac][t]=!1),Ec(this,t,Xa(1,e))};return Ka&&Tc&&Ec(dc,t,{configurable:!0,set:n}),Ua(t,e)})[lc],"toString",function(){return hc(this).tag}),Je(fc,"withoutSetter",function(e){return Ua(rc(e),e)}),he.f=Cc,bt.f=kc,Ie.f=ze,v.f=I.f=j,tc.f=Ac,s.f=function(e){return Ua(ic(e),e)},Ka&&(mc(fc[lc],"description",{configurable:!0,get:function(){return hc(this).description}}),Je(dc,"propertyIsEnumerable",Cc,{unsafe:!0}))),de({global:!0,wrap:!0,forced:!fe,sham:!fe},{Symbol:fc}),oc(ec(Xe),function(e){sc(e)}),de({target:cc,stat:!0,forced:!fe},{for:function(e){var t=String(e);if(za(bc,t))return bc[t];var n=fc(t);return bc[t]=n,Ic[n]=t,n},keyFor:function(e){if(!Sc(e))throw TypeError(e+" is not a symbol");if(za(Ic,e))return Ic[e]},useSetter:function(){Tc=!0},useSimple:function(){Tc=!1}}),de({target:"Object",stat:!0,forced:!fe,sham:!Ka},{create:function(e,t){return void 0===t?Za(e):ja(Za(e),t)},defineProperty:kc,defineProperties:ja,getOwnPropertyDescriptor:ze}),de({target:"Object",stat:!0,forced:!fe},{getOwnPropertyNames:j,getOwnPropertySymbols:Ac}),de({target:"Object",stat:!0,forced:q(function(){tc.f(1)})},{getOwnPropertySymbols:function(e){return tc.f(Qa(e))}}),pc&&de({target:"JSON",stat:!0,forced:!fe||q(function(){var e=fc();return"[null]"!=pc([e])||"{}"!=pc({a:e})||"{}"!=pc(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)&&!Sc(e))return Wa(t)||(t=function(e,t){if("function"==typeof r&&(t=r.call(this,e,t)),!Sc(t))return t}),i[1]=t,pc.apply(null,i)}}),fc[lc][S]||N(fc[lc],S,fc[lc].valueOf),ve(fc,cc),nc[ac]=!0,We("asyncIterator");var Nc,Rc,Pc,xc,Oc,S=W,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}}),S({global:!0,forced:!0},{Symbol:Rc})),We("hasInstance"),We("isConcatSpreadable"),We("iterator"),We("match"),We("matchAll"),We("replace"),We("search"),We("species"),We("split"),We("toPrimitive"),We("toStringTag"),We("unscopables"),tt(Math,"Math",!0),tt(i.JSON,"JSON",!0),yt.Symbol,We("asyncDispose"),We("dispose"),We("observable"),We("patternMatch"),We("replaceAll"),Et.f("iterator");function Fc(e){qc(e,Bc,{value:{objectID:"O"+ ++$c,weakData:{}}})}var We={exports:{}},Et=!e(function(){return Object.isExtensible(Object.preventExtensions({}))}),ye=ye,Uc=c,jc=O,qc=a.f,Vc=Et,Bc=D("meta"),$c=0,Kc=Object.isExtensible||function(){return!0},zc=We.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(!Kc(e))return"F";if(!t)return"E";Fc(e)}return e[Bc].objectID},getWeakData:function(e,t){if(!jc(e,Bc)){if(!Kc(e))return!0;if(!t)return!1;Fc(e)}return e[Bc].weakData},onFreeze:function(e){return Vc&&zc.REQUIRED&&Kc(e)&&!jc(e,Bc)&&Fc(e),e}};ye[Bc]=!0;var Wc=c,Hc=rt,Gc=W,Qc=i,Yc=V,Jc=Z.exports,Xc=We.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&&Wc(i=r.prototype)&&i!==n.prototype&&Hc(e,i),e},tt=function(r,e,t){function n(e){var n=f[e];Jc(f,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],f=d&&d.prototype,p=d,g={};return Yc(r,"function"!=typeof d||!(u||f.forEach&&!nl(function(){(new d).entries().next()})))?(p=t.getConstructor(e,r,l,h),Xc.REQUIRED=!0):Yc(r,!0)&&(s=(i=new p)[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||(((p=e(function(e,t){el(e,p,r);var n=sl(new d,e,p);return null!=t&&Zc(t,n[h],n,l),n})).prototype=f).constructor=p),(o||c)&&(n("delete"),n("has"),l&&n("get")),(c||s)&&n(h),u&&f.clear&&delete f.clear),g[r]=p,Gc({global:!0,forced:p!=d},g),il(p,r),u||t.setStrong(p,r,l),p},ol=a.f,al=Qe,cl=Er,ll=Te,ul=Me,hl=l.exports,dl=Pt,fl=Ee,pl=o,gl=We.exports.fastKey,ml=Se.set,vl=Se.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),pl?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}),pl||(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,pl?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),pl?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)}}),pl&&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),fl(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))};W({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)};W({target:"Map",stat:!0},{of:o});var bl=t,Il=n,We=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=We;W({target:"Map",proto:!0,real:!0,forced:!1},{deleteAll:function(){return Tl.apply(this,arguments)}});var El=t,Sl=p,Se=function(e){return Map.prototype.entries.call(e)},p=W,kl=t,Cl=Te,Al=Se,Nl=l.exports;p({target:"Map",proto:!0,real:!0,forced:!1},{every:function(e){var n=kl(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 p=W,Rl=vt,Pl=t,xl=n,Ol=Te,Dl=R,Ll=Se,Ml=l.exports;p({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 p=W,Fl=t,Ul=Te,jl=Se,ql=l.exports;p({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 p=W,Vl=t,Bl=Te,$l=Se,Kl=l.exports;p({target:"Map",proto:!0,real:!0,forced:!1},{findKey:function(e){var n=Vl(this),t=$l(n),r=Bl(e,1<arguments.length?arguments[1]:void 0,3);return Kl(t,function(e,t){if(r(t,e,n))return Kl.stop(e)},void 0,!0,!0).result}});var p=W,zl=l.exports,Wl=n;p({target:"Map",stat:!0},{groupBy:function(e,n){var r=new this;Wl(n);var i=Wl(r.has),s=Wl(r.get),o=Wl(r.set);return zl(e,function(e){var t=n(e);i.call(r,t)?s.call(r,t).push(e):o.call(r,t,[e])}),r}});var p=W,Hl=t,Gl=Se,Ql=function(e,t){return e===t||e!=e&&t!=t},Yl=l.exports;p({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 p=W,Jl=l.exports,Xl=n;p({target:"Map",stat:!0},{keyBy:function(e,t){var n=new this;Xl(t);var r=Xl(n.set);return Jl(e,function(e){r.call(n,t(e),e)}),n}});var p=W,Zl=t,eu=Se,tu=l.exports;p({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 p=W,nu=vt,ru=t,iu=n,su=Te,ou=R,au=Se,cu=l.exports;p({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 p=W,lu=vt,uu=t,hu=n,du=Te,fu=R,pu=Se,gu=l.exports;p({target:"Map",proto:!0,real:!0,forced:!1},{mapValues:function(e){var n=uu(this),t=pu(n),r=du(e,1<arguments.length?arguments[1]:void 0,3),i=new(fu(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 p=W,mu=t,vu=n,yu=l.exports;p({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 p=W,_u=t,wu=n,bu=Se,Iu=l.exports;p({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 p=W,Tu=t,Eu=Te,Su=Se,ku=l.exports;p({target:"Map",proto:!0,real:!0,forced:!1},{some:function(e){var n=Tu(this),t=Su(n),r=Eu(e,1<arguments.length?arguments[1]:void 0,3);return ku(t,function(e,t){if(r(t,e,n))return ku.stop()},void 0,!0,!0).stopped}});var Cu=t,Au=n;W({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,p=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};W({target:"Map",proto:!0,real:!0,forced:!1},{upsert:p});W({target:"Map",proto:!0,real:!0,forced:!1},{updateOrInsert:p}),tt("Set",function(e){return function(){return e(this,arguments.length?arguments[0]:void 0)}},Pt),yt.Set,W({target:"Set",stat:!0},{from:Ee}),W({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};W({target:"Set",proto:!0,real:!0,forced:!1},{addAll:function(){return xu.apply(this,arguments)}});var Ou=We;W({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)},We=W,Du=t,Lu=Te,Mu=o,Fu=l.exports;We({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 We=W,Uu=vt,ju=t,qu=n,Vu=R,Bu=l.exports;We({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 We=W,$u=vt,Ku=t,zu=n,Wu=Te,Hu=R,Gu=o,Qu=l.exports;We({target:"Set",proto:!0,real:!0,forced:!1},{filter:function(e){var t=Ku(this),n=Gu(t),r=Wu(e,1<arguments.length?arguments[1]:void 0,3),i=new(Hu(t,$u("Set"))),s=zu(i.add);return Qu(n,function(e){r(e,e,t)&&s.call(i,e)},void 0,!1,!0),i}});var We=W,Yu=t,Ju=Te,Xu=o,Zu=l.exports;We({target:"Set",proto:!0,real:!0,forced:!1},{find:function(e){var t=Yu(this),n=Xu(t),r=Ju(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 We=W,eh=vt,th=t,nh=n,rh=R,ih=l.exports;We({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 We=W,sh=t,oh=n,ah=l.exports;We({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 We=W,ch=vt,lh=t,uh=n,hh=function(e){var t=Sl(e);if("function"!=typeof t)throw TypeError(String(e)+" is not iterable");return El(t.call(e))},dh=l.exports;We({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 We=W,fh=t,ph=n,gh=l.exports;We({target:"Set",proto:!0,real:!0,forced:!1},{isSupersetOf:function(e){var t=fh(this),n=ph(t.has);return!gh(e,function(e){if(!1===n.call(t,e))return gh.stop()}).stopped}});var We=W,mh=t,vh=o,yh=l.exports;We({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 We=W,_h=vt,wh=t,bh=n,Ih=Te,Th=R,Eh=o,Sh=l.exports;We({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 Sh(n,function(e){s.call(i,r(e,e,t))},void 0,!1,!0),i}});var We=W,kh=t,Ch=n,Ah=o,Nh=l.exports;We({target:"Set",proto:!0,real:!0,forced:!1},{reduce:function(t){var n=kh(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 We=W,Rh=t,Ph=Te,xh=o,Oh=l.exports;We({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 We=W,Dh=vt,Lh=t,Mh=n,Fh=R,Uh=l.exports;We({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 We=W,jh=vt,qh=t,Vh=n,Bh=R,$h=l.exports;We({target:"Set",proto:!0,real:!0,forced:!1},{union:function(e){var t=qh(this),t=new(Bh(t,jh("Set")))(t);return $h(e,Vh(t.add),t),t}});var Kh,zh,Wh=c,Hh=Math.floor;W({target:"Number",stat:!0},{isInteger:function(e){return!Wh(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}"},Jh=function(e,t){if(!e)throw Xh(t)},Xh=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 fd(){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 pd(){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 Sd(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(kd(i)&&kd(s)){if(!Sd(i,s))return}else if(i!==s)return}for(const a of r)if(!n.includes(a))return;return 1}function kd(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 f=0;f<80;f++){u=f<40?f<20?(l=a^s&(o^a),1518500249):(l=s^o^a,1859775393):f<60?(l=s&o|a&(s|o),2400959708):(l=s^o^a,3395469782);var h=(t<<5|t>>>27)+l+c+u+i[f]&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 $d(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 Kd(e){return e&&e._delegate?e._delegate:e}class zd{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 Wd="[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:Wd})}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=Wd){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=Wd){return this.instances.has(e)}getOptions(e=Wd){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)===Wd?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=Wd){return!this.component||this.component.multipleInstances?e:Wd}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=[];(zh=Kh=Kh||{})[zh.DEBUG=0]="DEBUG",zh[zh.VERBOSE=1]="VERBOSE",zh[zh.INFO=2]="INFO",zh[zh.WARN=3]="WARN",zh[zh.ERROR=4]="ERROR",zh[zh.SILENT=5]="SILENT";const Yd={debug:Kh.DEBUG,verbose:Kh.VERBOSE,info:Kh.INFO,warn:Kh.WARN,error:Kh.ERROR,silent:Kh.SILENT},Jd=Kh.INFO,Xd={[Kh.DEBUG]:"log",[Kh.VERBOSE]:"log",[Kh.INFO]:"info",[Kh.WARN]:"warn",[Kh.ERROR]:"error"},Zd=(e,t,...n)=>{if(!(t<e.logLevel)){var r=(new Date).toISOString(),i=Xd[t];if(!i)throw new Error(`Attempted to log a message with an invalid logType (value: ${t})`);console[i](`[${r}] ${e.name}:`,...n)}};class ef{constructor(e){this.name=e,this._logLevel=Jd,this._logHandler=Zd,this._userLogHandler=null,Qd.push(this)}get logLevel(){return this._logLevel}set logLevel(e){if(!(e in Kh))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,Kh.DEBUG,...e),this._logHandler(this,Kh.DEBUG,...e)}log(...e){this._userLogHandler&&this._userLogHandler(this,Kh.VERBOSE,...e),this._logHandler(this,Kh.VERBOSE,...e)}info(...e){this._userLogHandler&&this._userLogHandler(this,Kh.INFO,...e),this._logHandler(this,Kh.INFO,...e)}warn(...e){this._userLogHandler&&this._userLogHandler(this,Kh.WARN,...e),this._logHandler(this,Kh.WARN,...e)}error(...e){this._userLogHandler&&this._userLogHandler(this,Kh.ERROR,...e),this._logHandler(this,Kh.ERROR,...e)}}class tf{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 nf="@firebase/app",rf=new ef("@firebase/app");var sf;const of="[DEFAULT]",af={"@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"},cf=new Map,lf=new Map;function uf(t,n){try{t.container.addComponent(n)}catch(e){rf.debug(`Component ${n.name} failed to register with FirebaseApp ${t.name}`,e)}}function hf(e,t){e.container.addOrOverwriteComponent(t)}function df(e){var t=e.name;if(lf.has(t))return rf.debug(`There were multiple attempts to register component ${t}.`),!1;lf.set(t,e);for(const n of cf.values())uf(n,e);return!0}function ff(e,t){return e.container.getProvider(t)}const pf=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 gf{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 zd("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 pf.create("app-deleted",{appName:this._name})}}const mf="9.4.1";function vf(e,t={}){if("object"!=typeof t){const r=t;t={name:r}}var n=Object.assign({name:of,automaticDataCollectionEnabled:!1},t);const r=n.name;if("string"!=typeof r||!r)throw pf.create("bad-app-name",{appName:String(r)});var i=cf.get(r);if(i){if(Sd(e,i.options)&&Sd(n,i.config))return i;throw pf.create("duplicate-app",{appName:r})}const s=new Gd(r);for(const o of lf.values())s.addComponent(o);n=new gf(e,n,s);return cf.set(r,n),n}function yf(e=of){var t=cf.get(e);if(!t)throw pf.create("no-app",{appName:e});return t}async function _f(e){var t=e.name;cf.has(t)&&(cf.delete(t),await Promise.all(e.container.getProviders().map(e=>e.delete())),e.isDeleted=!0)}function wf(e,t,n){let r=null!==(s=af[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 rf.warn(o.join(" "))}df(new zd(`${r}-version`,()=>({library:r,version:t}),"VERSION"))}function bf(e,t){if(null!==e&&"function"!=typeof e)throw pf.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:Kh[t].toLowerCase(),message:r,args:n,type:e.name})}}}(e,t)}function If(e){var t;t=e,Qd.forEach(e=>{e.setLogLevel(t)})}sf="",df(new zd("platform-logger",e=>new tf(e),"PRIVATE")),wf(nf,"0.7.8",sf),wf(nf,"0.7.8","esm2017"),wf("fire-js","");var Tf=Object.freeze({__proto__:null,SDK_VERSION:mf,_DEFAULT_ENTRY_NAME:of,_addComponent:uf,_addOrOverwriteComponent:hf,_apps:cf,_clearComponents:function(){lf.clear()},_components:lf,_getProvider:ff,_registerComponent:df,_removeServiceInstance:function(e,t,n=of){ff(e,t).clearInstance(n)},deleteApp:_f,getApp:yf,getApps:function(){return Array.from(cf.values())},initializeApp:vf,onLog:bf,registerVersion:wf,setLogLevel:If,FirebaseError:gd});class Ef{constructor(e,t){this._delegate=e,this.firebase=t,uf(e,new zd("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),_f(this._delegate)))}_getService(e,t=of){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=of){this._delegate.container.getProvider(e).clearInstance(t)}_addComponent(e){uf(this._delegate,e)}_addOrOverwriteComponent(e){hf(this._delegate,e)}toJSON(){return{name:this.name,automaticDataCollectionEnabled:this.automaticDataCollectionEnabled,options:this.options}}}const Sf=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 kf(i){const s={},o={__esModule:!0,initializeApp:function(e,t={}){var n=vf(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:wf,setLogLevel:If,onLog:bf,apps:null,SDK_VERSION:mf,INTERNAL:{registerComponent:function(n){const r=n.name,t=r.replace("-compat","");{var e;df(n)&&"PUBLIC"===n.type&&(e=(e=a())=>{if("function"!=typeof e[t])throw Sf.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:Tf}};function a(e){if(e=e||of,!bd(s,e))throw Sf.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=kf(Ef);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 Cf=new ef("@firebase/app-compat");if("object"==typeof self&&self.self===self&&void 0!==self.firebase){Cf.warn(`
1
+ !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 f(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 p(t){this.map={},t instanceof p?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 p(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 p(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 p(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))}),p.prototype.append=function(e,t){e=h(e),t=d(t);var n=this.map[e];this.map[e]=n?n+","+t:t},p.prototype.delete=function(e){delete this.map[h(e)]},p.prototype.get=function(e){return e=h(e),this.has(e)?this.map[e]:null},p.prototype.has=function(e){return this.map.hasOwnProperty(h(e))},p.prototype.set=function(e,t){this.map[h(e)]=d(t)},p.prototype.forEach=function(e,t){for(var n in this.map)this.map.hasOwnProperty(n)&&e.call(t,this.map[n],n,this)},p.prototype.keys=function(){var n=[];return this.forEach(function(e,t){n.push(t)}),f(n)},p.prototype.values=function(){var t=[];return this.forEach(function(e){t.push(e)}),f(t)},p.prototype.entries=function(){var n=[];return this.forEach(function(e,t){n.push([t,e])}),f(n)},n&&(p.prototype[Symbol.iterator]=p.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 p(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=p,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 p,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):{}},f=d,p=!o&&!e(function(){return 7!=Object.defineProperty(f("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=p,_=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,S=o?function(e,t,n){return T.f(e,t,E(1,n))}:function(e,t,n){return e[t]=n,e},k=i,C=S,A=function(t,n){try{C(k,t,n)}catch(e){k[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 D(e,t){return L.call(e,t)}function O(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,$=D,K=O,z=j,W=q,H=B("wks"),G=V.Symbol,Q=W?G:G&&G.withoutSetter||K,Y=function(e){return $(H,e)||(z&&$(G,e)?H[e]=G[e]:H[e]=Q("Symbol."+e)),H[e]},J={};J[Y("toStringTag")]="z";var X="[object z]"===String(J),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,fe="function"==typeof de&&/native code/.test(he(de)),pe=s.exports,ge=O,me=pe("keys"),ve=function(e){return me[e]||(me[e]=ge(e))},ye={},_e=c,we=S,be=D,Ie=ve,Te=ye,Ee=i.WeakMap;ce=fe?(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 Se={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}}},ke=i,Ce=S,Ae=D,Ne=A,Re=ue,Pe=Se.get,xe=Se.enforce,De=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=De.join("string"==typeof t?t:"")),e!==ke?(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 Oe={}.toString,Le=function(e){return Oe.call(e).slice(8,-1)},Me=X,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;X||Be(Object.prototype,"toString",X?{}.toString:function(){return"[object "+Ve(this)+"]"},{unsafe:!0});var $e=Math.ceil,Ke=Math.floor,ze=function(e){return isNaN(e=+e)?0:(0<e?Ke:$e)(e)},We=function(e){if(null==e)throw TypeError("Can't call method on "+e);return e},He=ze,Ge=We,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)},Je={},Xe={},Ze={}.propertyIsEnumerable,et=Object.getOwnPropertyDescriptor,tt=et&&!Ze.call({1:2},1);Xe.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=We,lt=Xe,ut=I,ht=nt,dt=v,ft=D,pt=p,gt=Object.getOwnPropertyDescriptor;Je.f=o?gt:function(e,t){if(e=ht(e),t=dt(t,!0),pt)try{return gt(e,t)}catch(e){}if(ft(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=ze,Tt=Math.min,Et=function(e){return 0<e?Tt(It(e),9007199254740991):0},St=ze,kt=Math.max,Ct=Math.min,At=nt,Nt=Et,Rt=function(e,t){var n=St(e);return n<0?kt(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=D,Dt=nt,Ot=r.indexOf,Lt=ye,n=function(e,t){var n,r=Dt(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++])&&(~Ot(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=D,Bt=R,$t=Je,Kt=a,U=function(e,t){for(var n=Bt(t),r=Kt.f,i=$t.f,s=0;s<n.length;s++){var o=n[s];Vt(e,o)||r(e,o,i(t,o))}},zt=e,Wt=/#|\.prototype\./,B=function(e,t){var n=Gt[Ht(e)];return n==Yt||n!=Qt&&("function"==typeof t?zt(t):!!t)},Ht=B.normalize=function(e){return String(e).replace(Wt,".").toLowerCase()},Gt=B.data={},Qt=B.NATIVE="N",Yt=B.POLYFILL="P",V=B,Jt=i,Xt=Je.f,Zt=S,en=Z.exports,tn=A,nn=U,rn=V,W=function(e,t){var n,r,i,s=e.target,o=e.global,a=e.stat,c=o?Jt:a?Jt[s]||tn(s,{}):(Jt[s]||{}).prototype;if(c)for(n in t){if(r=t[n],i=e.noTargetGet?(i=Xt(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=We,K=function(e){return Object(sn(e))},J=!e(function(){function e(){}return e.prototype.constructor=null,Object.getPrototypeOf(new e)!==e.prototype}),on=D,an=K,P=J,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=S,pe=D,fe=Y("iterator"),Ee=!1;[].keys&&("next"in(or=[].keys())?(ar=he(he(or)))!==Object.prototype&&(Er=ar):Ee=!0),pe(Er=null==Er?{}:Er,fe)||de(Er,fe,function(){return this});function un(){}var hn,Te={IteratorPrototype:Er,BUGGY_SAFARI_ITERATORS:Ee},dn=n,fn=l,Ie=Object.keys||function(e){return dn(e,fn)},pn=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;)pn.f(e,n=r[s++],t[n]);return e},Be=vt("document","documentElement"),vn=t,yn=Me,_n=l,X=ye,wn=Be,bn=d,In="prototype",Tn="script",En=ve("IE_PROTO"),Sn=function(e){return"<"+Tn+">"+e+"</"+Tn+">"},kn=function(){try{hn=document.domain&&new ActiveXObject("htmlfile")}catch(e){}var e,t;kn=hn?function(e){e.write(Sn("")),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(Sn("document.F=Object")),e.close(),e.F);for(var n=_n.length;n--;)delete kn[In][_n[n]];return kn()};X[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=kn(),void 0===t?n:yn(n,t)},Nn=a.f,Rn=D,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,Dn=Qe,On=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=W,Vn=function(e,t,n){var r=t+" Iterator";return e.prototype=Dn(xn,{next:On(1,n)}),Ln(e,r,!1),Mn[r]=Cn,e},Bn=ee,$n=rt,Kn=tt,zn=S,Wn=Z.exports,p=Y,Hn=Ze,Gn=Te.IteratorPrototype,Qn=Te.BUGGY_SAFARI_ITERATORS,Yn=p("iterator"),Jn="values",Xn="entries",Pt=function(e,t,n,r,i,s,o){Vn(n,t,r);function a(e){if(e===i&&p)return p;if(!Qn&&e in d)return d[e];switch(e){case"keys":case Jn:case Xn:return function(){return new n(this,e)}}return function(){return new n(this)}}var c,l,u=t+" Iterator",h=!1,d=e.prototype,f=d[Yn]||d["@@iterator"]||i&&d[i],p=!Qn&&f||a(i),g="Array"==t&&d.entries||f;if(g&&(g=Bn(g.call(new e)),Gn!==Object.prototype&&g.next&&(Bn(g)!==Gn&&($n?$n(g,Gn):"function"!=typeof g[Yn]&&zn(g,Yn,An)),Kn(g,u,!0))),i==Jn&&f&&f.name!==Jn&&(h=!0,p=function(){return f.call(this)}),d[Yn]!==p&&zn(d,Yn,p),Hn[t]=p,i)if(c={values:a(Jn),keys:s?p:a("keys"),entries:a(Xn)},o)for(l in c)!Qn&&!h&&l in d||Wn(d,l,c[l]);else qn({target:t,proto:!0,forced:Qn||h},c);return c},Zn=Ye.charAt,r=Se,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 J=function(e){ir[rr][e]=!0},sr=nt,P=J,he=Ze,or=Se,ar=Pt,cr="Array Iterator",lr=or.set,ur=or.getterFor(cr),pe=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,fr={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},pr=pe,gr=S,de=Y,mr=de("iterator"),vr=de("toStringTag"),yr=pr.values;for(hr in fr){var _r=dr[hr],wr=_r&&_r.prototype;if(wr){if(wr[mr]!==yr)try{gr(wr,mr,yr)}catch(pb){wr[mr]=yr}if(wr[vr]||gr(wr,vr,hr),fr[hr])for(var br in pr)if(wr[br]!==pr[br])try{gr(wr,br,pr[br])}catch(pb){wr[br]=pr[br]}}}function Ir(e,t){this.stopped=e,this.result=t}var fe=i.Promise,Tr=Z.exports,Er=function(e,t,n){for(var r in t)Tr(e,r,t[r],n);return e},Sr=vt,kr=a,Cr=o,Ar=Y("species"),Ee=function(e){var t=Sr(e),n=kr.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,X=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)}},Dr=qe,Or=Ze,Lr=Y("iterator"),p=function(e){if(null!=e)return e[Lr]||e["@@iterator"]||Or[Dr(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=X,jr=Et,qr=Te,Vr=p,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 $r=Y("iterator"),Kr=!1;try{var zr=0,Wr={next:function(){return{done:!!zr++}},return:function(){Kr=!0}};Wr[$r]=function(){return this},Array.from(Wr,function(){throw 2})}catch(pb){}function Hr(e){return function(){ai(e)}}var Gr,r=function(e,t){if(!t&&!Kr)return!1;var n=!1;try{var r={};r[$r]=function(){return{next:function(){return{done:n=!0}}}},e(r)}catch(e){}return n},Qr=t,Yr=n,Jr=Y("species"),R=function(e,t){var n,r=Qr(e).constructor;return void 0===r||null==(n=Qr(r)[Jr])?t:Yr(n)},A=vt("navigator","userAgent")||"",B=/(iphone|ipod|ipad).*applewebkit/i.test(A),Xr=i,or=e,ar=Le,he=Te,Zr=Be,ei=d,P=B,ti=Xr.location,de=Xr.setImmediate,Ze=Xr.clearImmediate,ni=Xr.process,Wr=Xr.MessageChannel,ri=Xr.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){Xr.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))}:Wr&&!P?(wi=(yi=new Wr).port2,yi.port1.onmessage=Be,Gr=he(wi.postMessage,wi,1)):!Xr.addEventListener||"function"!=typeof postMessage||Xr.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,Xr.addEventListener("message",Be,!1)));var ci,li,ui,hi,di,fi,pi,gi,ar={set:de,clear:Ze},mi=i,P=Je.f,Wr=Le,vi=ar.set,yi=B,he=mi.MutationObserver||mi.WebKitMutationObserver,_i=mi.process,wi=mi.Promise,bi="process"==Wr(_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,fi=document.createTextNode(""),new he(ci).observe(fi,{characterData:!0}),function(){fi.data=di=!di}):wi&&wi.resolve?(pi=wi.resolve(void 0),gi=pi.then,function(){gi.call(pi,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,Si=c,ki=de,Ze=function(e,t){if(Ei(e),Si(t)&&t.constructor===e)return t;var n=ki.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}}},Wr=A,P=i.process,or=P&&P.versions,yi=or&&or.v8;yi?ji=(Mi=yi.split("."))[0]+Mi[1]:Wr&&(!(Mi=Wr.match(/Edge\/(\d+)/))||74<=Mi[1])&&(Mi=Wr.match(/Chrome\/(\d+)/))&&(ji=Mi[1]);var Ai,Ni,Ri,Pi,he=ji&&+ji,wi=W,xi=i,d=vt,A=fe,P=Z.exports,or=Er,yi=tt,Wr=Ee,Di=c,Oi=n,Li=Me,Mi=Le,Fi=ue,Ui=l.exports,ji=r,qi=R,Vi=ar.set,Bi=Be,$i=Ze,Ki=function(e,t){var n=Ci.console;n&&n.error&&(1===arguments.length?n.error(e):n.error(e,t))},ue=de,zi=B,ar=Se,Be=V,Wi=he,Hi=Y("species"),Gi="Promise",Qi=ar.get,Yi=ar.set,Ji=ar.getterFor(Gi),Xi=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(Xi)!==String(Xi))){if(66===Wi)return!0;if(!ss&&"function"!=typeof PromiseRejectionEvent)return!0}if(51<=Wi&&/native code/.test(Xi))return!1;function e(e){e(function(){},function(){})}var t=Xi.resolve(1);return(t.constructor={})[Hi]=e,!(t.then(function(){})instanceof e)}),ji=Be||!ji(function(e){Xi.all(e).catch(function(){})}),fs=function(e){var t;return!(!Di(e)||"function"!=typeof(t=e.then))&&t},ps=function(f,p,g){var m;p.notified||(p.notified=!0,m=p.reactions,Bi(function(){for(var r,i,e=p.value,t=p.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||(p.rejection===ds&&function(e,t){Vi.call(xi,function(){if(ss)ts.emit("rejectionHandled",e);else gs(cs,e,t.value)})}(f,p),p.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=fs(s))?o.call(s,u,h):u(s)):h(e)}catch(e){d&&!a&&d.exit(),h(e)}}p.reactions=[],p.notified=!1,g&&!p.rejection&&(r=f,i=p,Vi.call(xi,function(){var e,t=i.value,n=ms(i);if(n&&(e=zi(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&&Ki("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,ps(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=fs(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,ps(n,r,!1))}catch(e){ys(n,{done:!1},e,r)}}};Be&&(Xi=function(e){Li(this,Xi,Gi),Oi(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(Xi.prototype,{then:function(e,t){var n=Ji(this),r=rs(qi(this,Xi));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&&ps(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===Xi||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 Xi(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 $i(Xi,ns.apply(xi,arguments))}}))),wi({global:!0,wrap:!0,forced:Be},{Promise:Xi}),yi(Xi,Gi,!1),Wr(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 $i(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=zi(function(){var r=Oi(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=zi(function(){var t=Oi(n.resolve);Ui(e,function(e){t.call(n,e).then(r.resolve,i)})});return t.error&&i(t.value),r.promise}});var d=W,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=W,Es=fe,wi=e,Ss=vt,ks=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=ks(this,Ss("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",Ss("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?Os(n,{errors:r,type:"AggregateError"}):n.errors=r,void 0!==t&&Ds(n,"message",String(t)),n}var d=W,Ns=o,Rs=ee,Ps=rt,fe=Qe,Ze=a,Be=I,xs=l.exports,Ds=S,wi=Se,Os=wi.set,Ls=wi.getterFor("AggregateError");As.prototype=fe(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;W({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=W,Us=n,js=vt,qs=de,Vs=B,Bs=l.exports,$s="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,$s)))})}),--o||u(new(js("AggregateError"))(i,$s))});return n.error&&u(n.value),t.promise}});function Ks(e){throw e}var zs=Le,wi=Array.isArray||function(e){return"Array"==zs(e)},Ws=c,Hs=wi,Gs=Y("species"),fe=function(e,t){var n;return new(void 0===(n=Hs(e)&&("function"==typeof(n=e.constructor)&&(n===Array||Hs(n.prototype))||Ws(n)&&null===(n=n[Gs]))?void 0:n)?Array:n)(0===t?0:t)},Qs=Te,Ys=ot,Js=K,Xs=Et,Zs=fe,eo=[].push,Be=function(f){var p=1==f,g=2==f,m=3==f,v=4==f,y=6==f,_=5==f||y;return function(e,t,n,r){for(var i,s,o=Js(e),a=Ys(o),c=Qs(t,n,3),l=Xs(a.length),u=0,h=r||Zs,d=p?h(e,l):g?h(e,0):void 0;u<l;u++)if((_||u in a)&&(s=c(i=a[u],u,o),f))if(p)d[u]=s;else if(s)switch(f){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=D,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]:Ks,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:Ks}):e[1]=1,n.call(e,i,s)})},de=W,oo=Ze.find,B=J,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=W,ho=Ze.findIndex,B=J,ji="findIndex",fo=!0,J=d(ji);ji in[]&&Array(1)[ji](function(){fo=!1}),Be({target:"Array",proto:!0,forced:fo||!J},{findIndex:function(e){return ho(this,e,1<arguments.length?arguments[1]:void 0)}}),B(ji),de("Array","findIndex");var po=v,go=a,mo=I,J=function(e,t,n){var r=po(t);r in e?go.f(e,r,mo(0,n)):e[r]=n},vo=Te,yo=K,_o=Ye,wo=X,bo=Et,Io=J,To=p,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),f=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));f<t;f++)o=h?u(a[f],f):a[f],Io(n,f,o);else for(s=(i=d.call(a)).next,n=new c;!(r=s.call(i)).done;f++)o=h?_o(i,u,[r.value,f],!0):r.value,Io(n,f,o);return n.length=f,n};W({target:"Array",stat:!0,forced:!r(function(e){Array.from(e)})},{from:B}),yt.Array.from;var Eo=e,ji=W,So=Ze.some,Ye=d,X=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:!X||!B},{some:function(e){return So(this,e,1<arguments.length?arguments[1]:void 0)}}),de("Array","some");function ko(e){return Ro(e)&&Po($o,xo(e))}var Co,d="undefined"!=typeof ArrayBuffer&&"undefined"!=typeof DataView,Ao=o,No=i,Ro=c,Po=D,xo=qe,Do=S,Oo=Z.exports,Ye=a.f,ji=ee,Lo=rt,X=Y,B=O,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,X=X("toStringTag"),Vo=B("TYPED_ARRAY_TAG"),Bo=d&&!!Lo&&"Opera"!==xo(No.opera),d=!1,$o={Int8Array:1,Uint8Array:1,Uint8ClampedArray:1,Int16Array:2,Uint16Array:2,Int32Array:4,Uint32Array:4,Float32Array:4,Float64Array:8};for(Co in $o)No[Co]||(Bo=!1);if((!Bo||"function"!=typeof Uo||Uo===Function.prototype)&&(Uo=function(){throw TypeError("Incorrect invocation")},Bo))for(Co in $o)No[Co]&&Lo(No[Co],Uo);if((!Bo||!jo||jo===qe)&&(jo=Uo.prototype,Bo))for(Co in $o)No[Co]&&Lo(No[Co].prototype,jo);if(Bo&&ji(ee)!==jo&&Lo(ee,jo),Ao&&!Po(jo,X))for(Co in d=!0,Ye(jo,X,{get:function(){return Ro(this)?this[Vo]:void 0}}),$o)No[Co]&&Do(No[Co],Vo,Co);var Ye=i,X={NATIVE_ARRAY_BUFFER_VIEWS:Bo,TYPED_ARRAY_TAG:d&&Vo,aTypedArray:function(e){if(ko(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 $o)if(Po($o,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 $o){r=No[r];r&&Po(r.prototype,e)&&delete r.prototype[e]}jo[e]&&!n||Oo(jo,e,!n&&Bo&&Fo[e]||t)}},exportTypedArrayStaticMethod:function(e,t,n){var r,i;if(Ao){if(Lo){if(n)for(r in $o)(i=No[r])&&Po(i,e)&&delete i[e];if(Uo[e]&&!n)return;try{return Oo(Uo,e,!n&&Bo&&Mo[e]||t)}catch(e){}}for(r in $o)!(i=No[r])||i[e]&&!n||Oo(i,e,t)}},isView:function(e){var t=xo(e);return"DataView"===t||Po($o,t)},isTypedArray:ko,TypedArray:Uo,TypedArrayPrototype:jo},d=pe,pe=Y("iterator"),Ye=Ye.Uint8Array,Ko=d.values,zo=d.keys,Wo=d.entries,Ho=X.aTypedArray,d=X.exportTypedArrayMethod,X=Ye&&Ye.prototype[pe],Ye=!!X&&("values"==X.name||null==X.name),X=function(){return Ko.call(Ho(this))};d("entries",function(){return Wo.call(Ho(this))}),d("keys",function(){return zo.call(Ho(this))}),d("values",X,!Ye),d(pe,X,!Ye);var Go=o,X=e,Qo=Ie,Yo=N,Jo=Xe,Xo=K,Zo=ot,ea=Object.assign,ta=Object.defineProperty,Ye=!ea||X(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=Xo(e),r=arguments.length,i=1,s=Yo.f,o=Jo.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;W({target:"Object",stat:!0,forced:Object.assign!==Ye},{assign:Ye}),yt.Object.assign;var na=o,ra=Ie,ia=nt,sa=Xe.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}},X={entries:ot(!0),values:ot(!1)},Ye=W,oa=X.entries;Ye({target:"Object",stat:!0},{entries:function(e){return oa(e)}}),yt.Object.entries;var ot=W,aa=X.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"),X=function(t){var n=/./;try{"/./"[t](n)}catch(e){try{return n[da]=!1,"/./"[t](n)}catch(e){}}return!1},fa=Ye,pa=We;W({target:"String",proto:!0,forced:!X("includes")},{includes:function(e){return!!~String(pa(this)).indexOf(fa(e),1<arguments.length?arguments[1]:void 0)}}),de("String","includes");var ot=W,Le=Je.f,ga=Et,ma=Ye,va=We,X=X,ya="".startsWith,_a=Math.min,X=X("startsWith");ot({target:"String",proto:!0,forced:!!(X||(!(Le=Le(String.prototype,"startsWith"))||Le.writable))&&!X},{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=ze,ba=We;W({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"),ze=W,We=e,Sa=wi,ka=c,Ca=K,Aa=Et,Na=J,Ra=fe,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,Da="Maximum allowed index exceeded",J=51<=Et||!We(function(){var e=[];return e[Pa]=!1,e.concat()[0]!==e}),fe=de("concat");ze({target:"Array",proto:!0,forced:!J||!fe},{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(!ka(e))return!1;var t=e[Pa];return void 0!==t?!!t:Sa(e)}(r=-1===a?i:arguments[a])){if(n=Aa(r.length),xa<o+n)throw TypeError(Da);for(t=0;t<n;t++,o++)t in r&&Na(s,o,r[t])}else{if(xa<=o)throw TypeError(Da);Na(s,o++,r)}return s.length=o,s}});var he={},Oa=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(Oa(e))};Et={};Et.f=Y;function Ua(e,t){var n=_c[e]=Za(fc[lc]);return uc(n,{type:cc,tag:e,description:t}),Ka||(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){Ka&&!Cc.call(n,e)||kc(t,e,n[e])}),t}var qa=yt,Va=D,Ba=Et,$a=a.f,We=function(e){var t=qa.Symbol||(qa.Symbol={});Va(t,e)||$a(t,e,{value:Ba.f(e)})},de=W,ze=i,J=vt,Ka=o,fe=j,j=q,q=e,za=D,Wa=wi,Ha=c,Ga=t,Qa=K,Ya=nt,Ja=v,Xa=I,Za=Qe,ec=Ie,v=bt,I=he,tc=N,Ie=Je,bt=a,he=Xe,N=S,Je=Z.exports,Xe=s.exports,S=ve,nc=ye,rc=O,ic=Y,s=Et,sc=We,ve=tt,Y=Se,oc=Ze.forEach,ac=S("hidden"),cc="Symbol",lc="prototype",S=ic("toPrimitive"),uc=Y.set,hc=Y.getterFor(cc),dc=Object[lc],fc=ze.Symbol,pc=J("JSON","stringify"),gc=Ie.f,mc=bt.f,vc=I.f,yc=he.f,_c=Xe("symbols"),wc=Xe("op-symbols"),bc=Xe("string-to-symbol-registry"),Ic=Xe("symbol-to-string-registry"),Xe=Xe("wks"),ze=ze.QObject,Tc=!ze||!ze[lc]||!ze[lc].findChild,Ec=Ka&&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,Sc=j?function(e){return"symbol"==typeof e}:function(e){return Object(e)instanceof fc},kc=function(e,t,n){e===dc&&kc(wc,t,n),Ga(e);var r=Ja(t,!0);return Ga(n),za(_c,r)?(n.enumerable?(za(e,ac)&&e[ac][r]&&(e[ac][r]=!1),n=Za(n,{enumerable:Xa(0,!1)})):(za(e,ac)||mc(e,ac,Xa(1,{})),e[ac][r]=!0),Ec(e,r,n)):mc(e,r,n)},Cc=function(e){var t=Ja(e,!0),n=yc.call(this,t);return!(this===dc&&za(_c,t)&&!za(wc,t))&&(!(n||!za(this,t)||!za(_c,t)||za(this,ac)&&this[ac][t])||n)},ze=function(e,t){var n=Ya(e),r=Ja(t,!0);if(n!==dc||!za(_c,r)||za(wc,r)){var i=gc(n,r);return!i||!za(_c,r)||za(n,ac)&&n[ac][r]||(i.enumerable=!0),i}},j=function(e){var t=vc(Ya(e)),n=[];return oc(t,function(e){za(_c,e)||za(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){!za(_c,e)||t&&!za(dc,e)||r.push(_c[e])}),r};fe||(Je((fc=function(){if(this instanceof fc)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),za(this,ac)&&za(this[ac],t)&&(this[ac][t]=!1),Ec(this,t,Xa(1,e))};return Ka&&Tc&&Ec(dc,t,{configurable:!0,set:n}),Ua(t,e)})[lc],"toString",function(){return hc(this).tag}),Je(fc,"withoutSetter",function(e){return Ua(rc(e),e)}),he.f=Cc,bt.f=kc,Ie.f=ze,v.f=I.f=j,tc.f=Ac,s.f=function(e){return Ua(ic(e),e)},Ka&&(mc(fc[lc],"description",{configurable:!0,get:function(){return hc(this).description}}),Je(dc,"propertyIsEnumerable",Cc,{unsafe:!0}))),de({global:!0,wrap:!0,forced:!fe,sham:!fe},{Symbol:fc}),oc(ec(Xe),function(e){sc(e)}),de({target:cc,stat:!0,forced:!fe},{for:function(e){var t=String(e);if(za(bc,t))return bc[t];var n=fc(t);return bc[t]=n,Ic[n]=t,n},keyFor:function(e){if(!Sc(e))throw TypeError(e+" is not a symbol");if(za(Ic,e))return Ic[e]},useSetter:function(){Tc=!0},useSimple:function(){Tc=!1}}),de({target:"Object",stat:!0,forced:!fe,sham:!Ka},{create:function(e,t){return void 0===t?Za(e):ja(Za(e),t)},defineProperty:kc,defineProperties:ja,getOwnPropertyDescriptor:ze}),de({target:"Object",stat:!0,forced:!fe},{getOwnPropertyNames:j,getOwnPropertySymbols:Ac}),de({target:"Object",stat:!0,forced:q(function(){tc.f(1)})},{getOwnPropertySymbols:function(e){return tc.f(Qa(e))}}),pc&&de({target:"JSON",stat:!0,forced:!fe||q(function(){var e=fc();return"[null]"!=pc([e])||"{}"!=pc({a:e})||"{}"!=pc(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)&&!Sc(e))return Wa(t)||(t=function(e,t){if("function"==typeof r&&(t=r.call(this,e,t)),!Sc(t))return t}),i[1]=t,pc.apply(null,i)}}),fc[lc][S]||N(fc[lc],S,fc[lc].valueOf),ve(fc,cc),nc[ac]=!0,We("asyncIterator");var Nc,Rc,Pc,xc,Dc,S=W,Oc=D,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")),Dc=/^Symbol\((.*)\)[^)]+$/,ve(U,"description",{configurable:!0,get:function(){var e=Lc(this)?this.valueOf():this,t=Pc.call(e);if(Oc(Nc,e))return"";t=xc?t.slice(7,-1):t.replace(Dc,"$1");return""===t?void 0:t}}),S({global:!0,forced:!0},{Symbol:Rc})),We("hasInstance"),We("isConcatSpreadable"),We("iterator"),We("match"),We("matchAll"),We("replace"),We("search"),We("species"),We("split"),We("toPrimitive"),We("toStringTag"),We("unscopables"),tt(Math,"Math",!0),tt(i.JSON,"JSON",!0),yt.Symbol,We("asyncDispose"),We("dispose"),We("observable"),We("patternMatch"),We("replaceAll"),Et.f("iterator");function Fc(e){qc(e,Bc,{value:{objectID:"O"+ ++$c,weakData:{}}})}var We={exports:{}},Et=!e(function(){return Object.isExtensible(Object.preventExtensions({}))}),ye=ye,Uc=c,jc=D,qc=a.f,Vc=Et,Bc=O("meta"),$c=0,Kc=Object.isExtensible||function(){return!0},zc=We.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(!Kc(e))return"F";if(!t)return"E";Fc(e)}return e[Bc].objectID},getWeakData:function(e,t){if(!jc(e,Bc)){if(!Kc(e))return!0;if(!t)return!1;Fc(e)}return e[Bc].weakData},onFreeze:function(e){return Vc&&zc.REQUIRED&&Kc(e)&&!jc(e,Bc)&&Fc(e),e}};ye[Bc]=!0;var Wc=c,Hc=rt,Gc=W,Qc=i,Yc=V,Jc=Z.exports,Xc=We.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&&Wc(i=r.prototype)&&i!==n.prototype&&Hc(e,i),e},tt=function(r,e,t){function n(e){var n=f[e];Jc(f,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],f=d&&d.prototype,p=d,g={};return Yc(r,"function"!=typeof d||!(u||f.forEach&&!nl(function(){(new d).entries().next()})))?(p=t.getConstructor(e,r,l,h),Xc.REQUIRED=!0):Yc(r,!0)&&(s=(i=new p)[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||(((p=e(function(e,t){el(e,p,r);var n=sl(new d,e,p);return null!=t&&Zc(t,n[h],n,l),n})).prototype=f).constructor=p),(o||c)&&(n("delete"),n("has"),l&&n("get")),(c||s)&&n(h),u&&f.clear&&delete f.clear),g[r]=p,Gc({global:!0,forced:p!=d},g),il(p,r),u||t.setStrong(p,r,l),p},ol=a.f,al=Qe,cl=Er,ll=Te,ul=Me,hl=l.exports,dl=Pt,fl=Ee,pl=o,gl=We.exports.fastKey,ml=Se.set,vl=Se.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),pl?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}),pl||(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,pl?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),pl?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)}}),pl&&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),fl(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))};W({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)};W({target:"Map",stat:!0},{of:o});var bl=t,Il=n,We=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=We;W({target:"Map",proto:!0,real:!0,forced:!1},{deleteAll:function(){return Tl.apply(this,arguments)}});var El=t,Sl=p,Se=function(e){return Map.prototype.entries.call(e)},p=W,kl=t,Cl=Te,Al=Se,Nl=l.exports;p({target:"Map",proto:!0,real:!0,forced:!1},{every:function(e){var n=kl(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 p=W,Rl=vt,Pl=t,xl=n,Dl=Te,Ol=R,Ll=Se,Ml=l.exports;p({target:"Map",proto:!0,real:!0,forced:!1},{filter:function(e){var n=Pl(this),t=Ll(n),r=Dl(e,1<arguments.length?arguments[1]:void 0,3),i=new(Ol(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 p=W,Fl=t,Ul=Te,jl=Se,ql=l.exports;p({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 p=W,Vl=t,Bl=Te,$l=Se,Kl=l.exports;p({target:"Map",proto:!0,real:!0,forced:!1},{findKey:function(e){var n=Vl(this),t=$l(n),r=Bl(e,1<arguments.length?arguments[1]:void 0,3);return Kl(t,function(e,t){if(r(t,e,n))return Kl.stop(e)},void 0,!0,!0).result}});var p=W,zl=l.exports,Wl=n;p({target:"Map",stat:!0},{groupBy:function(e,n){var r=new this;Wl(n);var i=Wl(r.has),s=Wl(r.get),o=Wl(r.set);return zl(e,function(e){var t=n(e);i.call(r,t)?s.call(r,t).push(e):o.call(r,t,[e])}),r}});var p=W,Hl=t,Gl=Se,Ql=function(e,t){return e===t||e!=e&&t!=t},Yl=l.exports;p({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 p=W,Jl=l.exports,Xl=n;p({target:"Map",stat:!0},{keyBy:function(e,t){var n=new this;Xl(t);var r=Xl(n.set);return Jl(e,function(e){r.call(n,t(e),e)}),n}});var p=W,Zl=t,eu=Se,tu=l.exports;p({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 p=W,nu=vt,ru=t,iu=n,su=Te,ou=R,au=Se,cu=l.exports;p({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 p=W,lu=vt,uu=t,hu=n,du=Te,fu=R,pu=Se,gu=l.exports;p({target:"Map",proto:!0,real:!0,forced:!1},{mapValues:function(e){var n=uu(this),t=pu(n),r=du(e,1<arguments.length?arguments[1]:void 0,3),i=new(fu(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 p=W,mu=t,vu=n,yu=l.exports;p({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 p=W,_u=t,wu=n,bu=Se,Iu=l.exports;p({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 p=W,Tu=t,Eu=Te,Su=Se,ku=l.exports;p({target:"Map",proto:!0,real:!0,forced:!1},{some:function(e){var n=Tu(this),t=Su(n),r=Eu(e,1<arguments.length?arguments[1]:void 0,3);return ku(t,function(e,t){if(r(t,e,n))return ku.stop()},void 0,!0,!0).stopped}});var Cu=t,Au=n;W({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,p=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};W({target:"Map",proto:!0,real:!0,forced:!1},{upsert:p});W({target:"Map",proto:!0,real:!0,forced:!1},{updateOrInsert:p}),tt("Set",function(e){return function(){return e(this,arguments.length?arguments[0]:void 0)}},Pt),yt.Set,W({target:"Set",stat:!0},{from:Ee}),W({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};W({target:"Set",proto:!0,real:!0,forced:!1},{addAll:function(){return xu.apply(this,arguments)}});var Du=We;W({target:"Set",proto:!0,real:!0,forced:!1},{deleteAll:function(){return Du.apply(this,arguments)}});var o=function(e){return Set.prototype.values.call(e)},We=W,Ou=t,Lu=Te,Mu=o,Fu=l.exports;We({target:"Set",proto:!0,real:!0,forced:!1},{every:function(e){var t=Ou(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 We=W,Uu=vt,ju=t,qu=n,Vu=R,Bu=l.exports;We({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 We=W,$u=vt,Ku=t,zu=n,Wu=Te,Hu=R,Gu=o,Qu=l.exports;We({target:"Set",proto:!0,real:!0,forced:!1},{filter:function(e){var t=Ku(this),n=Gu(t),r=Wu(e,1<arguments.length?arguments[1]:void 0,3),i=new(Hu(t,$u("Set"))),s=zu(i.add);return Qu(n,function(e){r(e,e,t)&&s.call(i,e)},void 0,!1,!0),i}});var We=W,Yu=t,Ju=Te,Xu=o,Zu=l.exports;We({target:"Set",proto:!0,real:!0,forced:!1},{find:function(e){var t=Yu(this),n=Xu(t),r=Ju(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 We=W,eh=vt,th=t,nh=n,rh=R,ih=l.exports;We({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 We=W,sh=t,oh=n,ah=l.exports;We({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 We=W,ch=vt,lh=t,uh=n,hh=function(e){var t=Sl(e);if("function"!=typeof t)throw TypeError(String(e)+" is not iterable");return El(t.call(e))},dh=l.exports;We({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 We=W,fh=t,ph=n,gh=l.exports;We({target:"Set",proto:!0,real:!0,forced:!1},{isSupersetOf:function(e){var t=fh(this),n=ph(t.has);return!gh(e,function(e){if(!1===n.call(t,e))return gh.stop()}).stopped}});var We=W,mh=t,vh=o,yh=l.exports;We({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 We=W,_h=vt,wh=t,bh=n,Ih=Te,Th=R,Eh=o,Sh=l.exports;We({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 Sh(n,function(e){s.call(i,r(e,e,t))},void 0,!1,!0),i}});var We=W,kh=t,Ch=n,Ah=o,Nh=l.exports;We({target:"Set",proto:!0,real:!0,forced:!1},{reduce:function(t){var n=kh(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 We=W,Rh=t,Ph=Te,xh=o,Dh=l.exports;We({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 Dh(n,function(e){if(r(e,e,t))return Dh.stop()},void 0,!1,!0).stopped}});var We=W,Oh=vt,Lh=t,Mh=n,Fh=R,Uh=l.exports;We({target:"Set",proto:!0,real:!0,forced:!1},{symmetricDifference:function(e){var t=Lh(this),n=new(Fh(t,Oh("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 We=W,jh=vt,qh=t,Vh=n,Bh=R,$h=l.exports;We({target:"Set",proto:!0,real:!0,forced:!1},{union:function(e){var t=qh(this),t=new(Bh(t,jh("Set")))(t);return $h(e,Vh(t.add),t),t}});var Kh,zh,Wh=c,Hh=Math.floor;W({target:"Number",stat:!0},{isInteger:function(e){return!Wh(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}"},Jh=function(e,t){if(!e)throw Xh(t)},Xh=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 fd(){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 pd(){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 Sd(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(kd(i)&&kd(s)){if(!Sd(i,s))return}else if(i!==s)return}for(const a of r)if(!n.includes(a))return;return 1}function kd(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 f=0;f<80;f++){u=f<40?f<20?(l=a^s&(o^a),1518500249):(l=s^o^a,1859775393):f<60?(l=s&o|a&(s|o),2400959708):(l=s^o^a,3395469782);var h=(t<<5|t>>>27)+l+c+u+i[f]&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=Dd),void 0===r.error&&(r.error=Dd),void 0===r.complete&&(r.complete=Dd);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 Dd(){}function Od(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 $d(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 Kd(e){return e&&e._delegate?e._delegate:e}class zd{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 Wd="[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:Wd})}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=Wd){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=Wd){return this.instances.has(e)}getOptions(e=Wd){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)===Wd?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=Wd){return!this.component||this.component.multipleInstances?e:Wd}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=[];(zh=Kh=Kh||{})[zh.DEBUG=0]="DEBUG",zh[zh.VERBOSE=1]="VERBOSE",zh[zh.INFO=2]="INFO",zh[zh.WARN=3]="WARN",zh[zh.ERROR=4]="ERROR",zh[zh.SILENT=5]="SILENT";const Yd={debug:Kh.DEBUG,verbose:Kh.VERBOSE,info:Kh.INFO,warn:Kh.WARN,error:Kh.ERROR,silent:Kh.SILENT},Jd=Kh.INFO,Xd={[Kh.DEBUG]:"log",[Kh.VERBOSE]:"log",[Kh.INFO]:"info",[Kh.WARN]:"warn",[Kh.ERROR]:"error"},Zd=(e,t,...n)=>{if(!(t<e.logLevel)){var r=(new Date).toISOString(),i=Xd[t];if(!i)throw new Error(`Attempted to log a message with an invalid logType (value: ${t})`);console[i](`[${r}] ${e.name}:`,...n)}};class ef{constructor(e){this.name=e,this._logLevel=Jd,this._logHandler=Zd,this._userLogHandler=null,Qd.push(this)}get logLevel(){return this._logLevel}set logLevel(e){if(!(e in Kh))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,Kh.DEBUG,...e),this._logHandler(this,Kh.DEBUG,...e)}log(...e){this._userLogHandler&&this._userLogHandler(this,Kh.VERBOSE,...e),this._logHandler(this,Kh.VERBOSE,...e)}info(...e){this._userLogHandler&&this._userLogHandler(this,Kh.INFO,...e),this._logHandler(this,Kh.INFO,...e)}warn(...e){this._userLogHandler&&this._userLogHandler(this,Kh.WARN,...e),this._logHandler(this,Kh.WARN,...e)}error(...e){this._userLogHandler&&this._userLogHandler(this,Kh.ERROR,...e),this._logHandler(this,Kh.ERROR,...e)}}class tf{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 nf="@firebase/app",rf=new ef("@firebase/app");var sf;const of="[DEFAULT]",af={"@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"},cf=new Map,lf=new Map;function uf(t,n){try{t.container.addComponent(n)}catch(e){rf.debug(`Component ${n.name} failed to register with FirebaseApp ${t.name}`,e)}}function hf(e,t){e.container.addOrOverwriteComponent(t)}function df(e){var t=e.name;if(lf.has(t))return rf.debug(`There were multiple attempts to register component ${t}.`),!1;lf.set(t,e);for(const n of cf.values())uf(n,e);return!0}function ff(e,t){return e.container.getProvider(t)}const pf=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 gf{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 zd("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 pf.create("app-deleted",{appName:this._name})}}const mf="9.5.0";function vf(e,t={}){if("object"!=typeof t){const r=t;t={name:r}}var n=Object.assign({name:of,automaticDataCollectionEnabled:!1},t);const r=n.name;if("string"!=typeof r||!r)throw pf.create("bad-app-name",{appName:String(r)});var i=cf.get(r);if(i){if(Sd(e,i.options)&&Sd(n,i.config))return i;throw pf.create("duplicate-app",{appName:r})}const s=new Gd(r);for(const o of lf.values())s.addComponent(o);n=new gf(e,n,s);return cf.set(r,n),n}function yf(e=of){var t=cf.get(e);if(!t)throw pf.create("no-app",{appName:e});return t}async function _f(e){var t=e.name;cf.has(t)&&(cf.delete(t),await Promise.all(e.container.getProviders().map(e=>e.delete())),e.isDeleted=!0)}function wf(e,t,n){let r=null!==(s=af[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 rf.warn(o.join(" "))}df(new zd(`${r}-version`,()=>({library:r,version:t}),"VERSION"))}function bf(e,t){if(null!==e&&"function"!=typeof e)throw pf.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:Kh[t].toLowerCase(),message:r,args:n,type:e.name})}}}(e,t)}function If(e){var t;t=e,Qd.forEach(e=>{e.setLogLevel(t)})}sf="",df(new zd("platform-logger",e=>new tf(e),"PRIVATE")),wf(nf,"0.7.9",sf),wf(nf,"0.7.9","esm2017"),wf("fire-js","");var Tf=Object.freeze({__proto__:null,SDK_VERSION:mf,_DEFAULT_ENTRY_NAME:of,_addComponent:uf,_addOrOverwriteComponent:hf,_apps:cf,_clearComponents:function(){lf.clear()},_components:lf,_getProvider:ff,_registerComponent:df,_removeServiceInstance:function(e,t,n=of){ff(e,t).clearInstance(n)},deleteApp:_f,getApp:yf,getApps:function(){return Array.from(cf.values())},initializeApp:vf,onLog:bf,registerVersion:wf,setLogLevel:If,FirebaseError:gd});class Ef{constructor(e,t){this._delegate=e,this.firebase=t,uf(e,new zd("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),_f(this._delegate)))}_getService(e,t=of){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=of){this._delegate.container.getProvider(e).clearInstance(t)}_addComponent(e){uf(this._delegate,e)}_addOrOverwriteComponent(e){hf(this._delegate,e)}toJSON(){return{name:this.name,automaticDataCollectionEnabled:this.automaticDataCollectionEnabled,options:this.options}}}const Sf=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 kf(i){const s={},o={__esModule:!0,initializeApp:function(e,t={}){var n=vf(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:wf,setLogLevel:If,onLog:bf,apps:null,SDK_VERSION:mf,INTERNAL:{registerComponent:function(n){const r=n.name,t=r.replace("-compat","");{var e;df(n)&&"PUBLIC"===n.type&&(e=(e=a())=>{if("function"!=typeof e[t])throw Sf.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:Tf}};function a(e){if(e=e||of,!bd(s,e))throw Sf.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=kf(Ef);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 Cf=new ef("@firebase/app-compat");if("object"==typeof self&&self.self===self&&void 0!==self.firebase){Cf.warn(`
2
2
  Warning: Firebase is already defined in the global scope. Please make sure
3
3
  Firebase library is only loaded once.
4
- `);const $$=self.firebase.SDK_VERSION;$$&&0<=$$.indexOf("LITE")&&Cf.warn(`
4
+ `);const G$=self.firebase.SDK_VERSION;G$&&0<=G$.indexOf("LITE")&&Cf.warn(`
5
5
  Warning: You are trying to load Firebase while using Firebase Performance standalone script.
6
6
  You should load Firebase Performance with this instance of Firebase to avoid loading duplicate code.
7
- `)}const Af=l;wf("@firebase/app-compat","0.1.9",void 0);Af.registerVersion("firebase","9.4.1","app-compat");function Nf(n){return new Promise(function(e,t){n.onsuccess=function(){e(n.result)},n.onerror=function(){t(n.error)}})}function Rf(n,r,i){var s,e=new Promise(function(e,t){Nf(s=n[r].apply(n,i)).then(e,t)});return e.request=s,e}function Pf(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 xf(t,n,r,e){e.forEach(function(e){e in r.prototype&&(t.prototype[e]=function(){return Rf(this[n],e,arguments)})})}function Of(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 Df(e,r,t,n){n.forEach(function(n){n in t.prototype&&(e.prototype[n]=function(){return e=this[r],(t=Rf(e,n,arguments)).then(function(e){if(e)return new Mf(e,t.request)});var e,t})})}function Lf(e){this._index=e}function Mf(e,t){this._cursor=e,this._request=t}function Ff(e){this._store=e}function Uf(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 jf(e,t,n){this._db=e,this.oldVersion=t,this.transaction=new Uf(n)}function qf(e){this._db=e}function Vf(e,t,n){var r=Rf(indexedDB,"open",[e,t]),i=r.request;return i&&(i.onupgradeneeded=function(e){n&&n(new jf(i.result,e.oldVersion,i.transaction))}),r.then(function(e){return new qf(e)})}function Bf(e){return Rf(indexedDB,"deleteDatabase",[e])}Pf(Lf,"_index",["name","keyPath","multiEntry","unique"]),xf(Lf,"_index",IDBIndex,["get","getKey","getAll","getAllKeys","count"]),Df(Lf,"_index",IDBIndex,["openCursor","openKeyCursor"]),Pf(Mf,"_cursor",["direction","key","primaryKey","value"]),xf(Mf,"_cursor",IDBCursor,["update","delete"]),["advance","continue","continuePrimaryKey"].forEach(function(n){n in IDBCursor.prototype&&(Mf.prototype[n]=function(){var t=this,e=arguments;return Promise.resolve().then(function(){return t._cursor[n].apply(t._cursor,e),Nf(t._request).then(function(e){if(e)return new Mf(e,t._request)})})})}),Ff.prototype.createIndex=function(){return new Lf(this._store.createIndex.apply(this._store,arguments))},Ff.prototype.index=function(){return new Lf(this._store.index.apply(this._store,arguments))},Pf(Ff,"_store",["name","keyPath","indexNames","autoIncrement"]),xf(Ff,"_store",IDBObjectStore,["put","add","delete","clear","get","getAll","getKey","getAllKeys","count"]),Df(Ff,"_store",IDBObjectStore,["openCursor","openKeyCursor"]),Of(Ff,"_store",IDBObjectStore,["deleteIndex"]),Uf.prototype.objectStore=function(){return new Ff(this._tx.objectStore.apply(this._tx,arguments))},Pf(Uf,"_tx",["objectStoreNames","mode"]),Of(Uf,"_tx",IDBTransaction,["abort"]),jf.prototype.createObjectStore=function(){return new Ff(this._db.createObjectStore.apply(this._db,arguments))},Pf(jf,"_db",["name","version","objectStoreNames"]),Of(jf,"_db",IDBDatabase,["deleteObjectStore","close"]),qf.prototype.transaction=function(){return new Uf(this._db.transaction.apply(this._db,arguments))},Pf(qf,"_db",["name","version","objectStoreNames"]),Of(qf,"_db",IDBDatabase,["close"]),["openCursor","openKeyCursor"].forEach(function(s){[Ff,Lf].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)}})})}),[Lf,Ff].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)})})})});We="@firebase/installations",c="0.5.4";const $f=1e4,Kf="w:0.5.4",zf="FIS_v2",Wf="https://firebaseinstallations.googleapis.com/v1",Hf=36e5;const Gf=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 Qf(e){return e instanceof gd&&e.code.includes("request-failed")}function Yf({projectId:e}){return`${Wf}/projects/${e}/installations`}function Jf(e){return{token:e.token,requestStatus:2,expiresIn:(e=e.expiresIn,Number(e.replace("s","000"))),creationTime:Date.now()}}async function Xf(e,t){var n=(await t.json()).error;return Gf.create("request-failed",{requestName:e,serverCode:n.code,serverMessage:n.message,serverStatus:n.status})}function Zf({apiKey:e}){return new Headers({"Content-Type":"application/json",Accept:"application/json","x-goog-api-key":e})}function ep(e,{refreshToken:t}){const n=Zf(e);return n.append("Authorization",(t=t,`${zf} ${t}`)),n}async function tp(e){var t=await e();return 500<=t.status&&t.status<600?e():t}function np(t){return new Promise(e=>{setTimeout(e,t)})}const rp=/^[cdef][\w-]{21}$/,ip="";function sp(){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 rp.test(e)?e:ip}catch(e){return ip}}function op(e){return`${e.appName}!${e.appId}`}const ap=new Map;function cp(e,t){var n=op(e);lp(n,t),function(e,t){const n=function(){!up&&"BroadcastChannel"in self&&(up=new BroadcastChannel("[Firebase] FID Change"),up.onmessage=e=>{lp(e.data.key,e.data.fid)});return up}();n&&n.postMessage({key:e,fid:t});0===ap.size&&up&&(up.close(),up=null)}(n,t)}function lp(e,t){var n=ap.get(e);if(n)for(const r of n)r(t)}let up=null;const hp="firebase-installations-store";let dp=null;function fp(){return dp=dp||Vf("firebase-installations-database",1,e=>{0===e.oldVersion&&e.createObjectStore(hp)}),dp}async function pp(e,t){var n=op(e);const r=await fp(),i=r.transaction(hp,"readwrite"),s=i.objectStore(hp);var o=await s.get(n);return await s.put(t,n),await i.complete,o&&o.fid===t.fid||cp(e,t.fid),t}async function gp(e){var t=op(e);const n=await fp(),r=n.transaction(hp,"readwrite");await r.objectStore(hp).delete(t),await r.complete}async function mp(e,t){var n=op(e);const r=await fp(),i=r.transaction(hp,"readwrite"),s=i.objectStore(hp);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||cp(e,a.fid),a}async function vp(n){let r;var e=await mp(n,e=>{var t=_p(e||{fid:sp(),registrationStatus:0}),t=function(e,t){{if(0!==t.registrationStatus)return 1===t.registrationStatus?{installationEntry:t,registrationPromise:async function(e){let t=await yp(e);for(;1===t.registrationStatus;)await np(100),t=await yp(e);if(0!==t.registrationStatus)return t;{var{installationEntry:n,registrationPromise:r}=await vp(e);return r||n}}(e)}:{installationEntry:t};if(!navigator.onLine){var n=Promise.reject(Gf.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=Yf(e);var r=Zf(e),i={fid:t,authVersion:zf,appId:e.appId,sdkVersion:Kf};const s={method:"POST",headers:r,body:JSON.stringify(i)},o=await tp(()=>fetch(n,s));if(o.ok){i=await o.json();return{fid:i.fid||t,registrationStatus:2,refreshToken:i.refreshToken,authToken:Jf(i.authToken)}}throw await Xf("Create Installation",o)}(t,n);return pp(t,e)}catch(e){throw Qf(e)&&409===e.customData.serverCode?await gp(t):await pp(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===ip?{installationEntry:await r}:{installationEntry:e,registrationPromise:r}}function yp(e){return mp(e,e=>{if(!e)throw Gf.create("installation-not-found");return _p(e)})}function _p(e){return 1===(t=e).registrationStatus&&t.registrationTime+$f<Date.now()?{fid:e.fid,registrationStatus:0}:e;var t}async function wp({appConfig:e,platformLoggerProvider:t},n){const r=([i,s]=[e,n["fid"]],`${Yf(i)}/${s}/authTokens:generate`);var i,s;const o=ep(e,n),a=t.getImmediate({optional:!0});a&&o.append("x-firebase-client",a.getPlatformInfoString());var c={installation:{sdkVersion:Kf}};const l={method:"POST",headers:o,body:JSON.stringify(c)},u=await tp(()=>fetch(r,l));if(u.ok)return Jf(await u.json());throw await Xf("Generate Auth Token",u)}async function bp(r,i=!1){let s;var e=await mp(r.appConfig,e=>{if(!Tp(e))throw Gf.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+Hf}(t)){if(1===n.requestStatus)return s=async function(e,t){let n=await Ip(e.appConfig);for(;1===n.authToken.requestStatus;)await np(100),n=await Ip(e.appConfig);var r=n.authToken;return 0===r.requestStatus?bp(e,t):r}(r,i),e;if(!navigator.onLine)throw Gf.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 wp(t,n),e=Object.assign(Object.assign({},n),{authToken:r});return await pp(t.appConfig,e),r}catch(e){throw!Qf(e)||401!==e.customData.serverCode&&404!==e.customData.serverCode?(r=Object.assign(Object.assign({},n),{authToken:{requestStatus:0}}),await pp(t.appConfig,r)):await gp(t.appConfig),e}}(r,n),n}return e});return s?await s:e.authToken}function Ip(e){return mp(e,e=>{if(!Tp(e))throw Gf.create("not-registered");var t,n=e.authToken;return 1===(t=n).requestStatus&&t.requestTime+$f<Date.now()?Object.assign(Object.assign({},e),{authToken:{requestStatus:0}}):e})}function Tp(e){return void 0!==e&&2===e.registrationStatus}async function Ep(e,t=!1){var n,r=e;return e=r.appConfig,await((n=(await vp(e)).registrationPromise)&&await n),(await bp(r,t)).token}function Sp(e){return Gf.create("missing-app-config-values",{valueName:e})}const kp="installations",Cp=e=>{var t=e.getProvider("app").getImmediate();return{app:t,appConfig:function(e){if(!e||!e.options)throw Sp("App Configuration");if(!e.name)throw Sp("App Name");for(const t of["projectId","apiKey","appId"])if(!e.options[t])throw Sp(t);return{appName:e.name,projectId:e.options.projectId,apiKey:e.options.apiKey,appId:e.options.appId}}(t),platformLoggerProvider:ff(t,"platform-logger"),_delete:()=>Promise.resolve()}},Ap=e=>{const t=ff(e.getProvider("app").getImmediate(),kp).getImmediate();return{getId:()=>async function(e){var t=e;const{installationEntry:n,registrationPromise:r}=await vp(t.appConfig);return(r||bp(t)).catch(console.error),n.fid}(t),getToken:e=>Ep(t,e)}};df(new zd(kp,Cp,"PUBLIC")),df(new zd("installations-internal",Ap,"PRIVATE")),wf(We,c),wf(We,c,"esm2017");const Np="analytics",Rp="firebase_id",Pp="origin",xp="https://firebase.googleapis.com/v1alpha/projects/-/apps/{app-id}/webConfig",Op="https://www.googletagmanager.com/gtag/js",Dp=new ef("@firebase/analytics");function Lp(e){return Promise.all(e.map(e=>e.catch(e=>e)))}function Mp(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 Lp(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){Dp.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 Lp(n);var a=c.find(e=>e.measurementId===i);a&&await t[a.appId]}}catch(e){Dp.error(e)}e("config",i,s)}(r,i,s,o,t,n):r("set",t)}catch(e){Dp.error(e)}}}const Fp=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.'}),Up=30;const jp=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 qp(e){var t,{appId:n,apiKey:r}=e,r={method:"GET",headers:new Headers({Accept:"application/json","x-goog-api-key":r})},n=xp.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 Fp.create("config-fetch-failed",{httpStatus:i.status,responseMessage:e})}}async function Vp(e,t=jp,n){var{appId:r,apiKey:i,measurementId:s}=e.options;if(!r)throw Fp.create("no-app-id");if(!i){if(s)return{measurementId:s,appId:r};throw Fp.create("no-api-key")}var o=t.getThrottleMetadata(r)||{backoffCount:0,throttleEndTimeMillis:Date.now()};const a=new Kp;return setTimeout(async()=>{a.abort()},void 0!==n?n:6e4),async function t(n,{throttleEndTimeMillis:e,backoffCount:r},i,s=jp){const{appId:o,measurementId:a}=n;try{await Bp(i,e)}catch(e){if(a)return Dp.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 qp(n);return s.deleteThrottleMetadata(o),c}catch(e){if(!$p(e)){if(s.deleteThrottleMetadata(o),a)return Dp.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)?$d(r,s.intervalMillis,Up):$d(r,s.intervalMillis),u={throttleEndTimeMillis:Date.now()+l,backoffCount:r+1};return s.setThrottleMetadata(o,u),Dp.debug(`Calling attemptFetch again in ${l} millis`),t(n,u,i,s)}}({appId:r,apiKey:i,measurementId:s},o,a,t)}function Bp(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(Fp.create("fetch-throttle",{throttleEndTimeMillis:s}))})})}function $p(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 Kp{constructor(){this.listeners=[]}addEventListener(e){this.listeners.push(e)}abort(){this.listeners.forEach(e=>e())}}async function zp(t,e,n,r,i,s,o){const a=Vp(t);a.then(e=>{n[e.measurementId]=e.appId,t.options.measurementId&&e.measurementId!==t.options.measurementId&&Dp.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=>Dp.error(e)),e.push(a);var c=async function(){if(!dd())return Dp.warn(Fp.create("indexeddb-unavailable",{errorInfo:"IndexedDB is not available in this environment."}).message),!1;try{await fd()}catch(e){return Dp.warn(Fp.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(Op))return t}()&&function(e,t){const n=document.createElement("script");n.src=`${Op}?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[Pp]="firebase",h.update=!0,null!=u&&(h[Rp]=u),i("config",l.measurementId,h),l.measurementId}class Wp{constructor(e){this.app=e}_delete(){return delete Hp[this.app.options.appId],Promise.resolve()}}let Hp={},Gp=[];const Qp={};let Yp="dataLayer",Jp="gtag",Xp,Zp,eg=!1;function tg(e){if(eg)throw Fp.create("already-initialized");e.dataLayerName&&(Yp=e.dataLayerName),e.gtagName&&(Jp=e.gtagName)}function ng(e,t,n){!function(){const e=[];var t;cd()&&e.push("This is a browser extension environment."),pd()||e.push("Cookies are not available."),0<e.length&&(t=e.map((e,t)=>`(${t+1}) ${e}`).join(" "),t=Fp.create("invalid-analytics-context",{errorInfo:t}),Dp.warn(t.message))}();var r,i,s=e.options.appId;if(!s)throw Fp.create("no-app-id");if(!e.options.apiKey){if(!e.options.measurementId)throw Fp.create("no-api-key");Dp.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!=Hp[s])throw Fp.create("already-exists",{id:s});return eg||(function(e){let t=[];Array.isArray(window[e])?t=window[e]:window[e]=t,t}(Yp),{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]=Mp(s,e,t,n),{gtagCore:s,wrappedGtag:window[i]}}(Hp,Gp,Qp,Yp,Jp),Zp=r,Xp=i,eg=!0),Hp[s]=zp(e,Gp,Qp,t,Xp,Yp,n),new Wp(e)}async function rg(){if(cd())return!1;if(!pd())return!1;if(!dd())return!1;try{return await fd()}catch(e){return!1}}function ig(e,t,n){e=Kd(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})}(Zp,Hp[e.app.options.appId],t,n).catch(e=>Dp.error(e))}function sg(e,t,n){e=Kd(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})}(Zp,Hp[e.app.options.appId],t,n).catch(e=>Dp.error(e))}function og(e,t,n){e=Kd(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})}(Zp,Hp[e.app.options.appId],t,n).catch(e=>Dp.error(e))}function ag(e,t){e=Kd(e),async function(e,t){var n=await e;window[`ga-disable-${n}`]=!t}(Hp[e.app.options.appId],t).catch(e=>Dp.error(e))}function cg(e,t,n,r){e=Kd(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})))}(Zp,Hp[e.app.options.appId],t,n,r).catch(e=>Dp.error(e))}const lg="@firebase/analytics";df(new zd(Np,(e,{options:t})=>{return ng(e.getProvider("app").getImmediate(),e.getProvider("installations-internal").getImmediate(),t)},"PUBLIC")),df(new zd("analytics-internal",function(e){try{const r=e.getProvider(Np).getImmediate();return{logEvent:(e,t,n)=>cg(r,e,t,n)}}catch(e){throw Fp.create("interop-component-reg-failed",{reason:e})}},"PRIVATE")),wf(lg,"0.7.4"),wf(lg,"0.7.4","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)}}(W=ug=ug||{}).ADD_SHIPPING_INFO="add_shipping_info",W.ADD_PAYMENT_INFO="add_payment_info",W.ADD_TO_CART="add_to_cart",W.ADD_TO_WISHLIST="add_to_wishlist",W.BEGIN_CHECKOUT="begin_checkout",W.CHECKOUT_PROGRESS="checkout_progress",W.EXCEPTION="exception",W.GENERATE_LEAD="generate_lead",W.LOGIN="login",W.PAGE_VIEW="page_view",W.PURCHASE="purchase",W.REFUND="refund",W.REMOVE_FROM_CART="remove_from_cart",W.SCREEN_VIEW="screen_view",W.SEARCH="search",W.SELECT_CONTENT="select_content",W.SELECT_ITEM="select_item",W.SELECT_PROMOTION="select_promotion",W.SET_CHECKOUT_OPTION="set_checkout_option",W.SHARE="share",W.SIGN_UP="sign_up",W.TIMING_COMPLETE="timing_complete",W.VIEW_CART="view_cart",W.VIEW_ITEM="view_item",W.VIEW_ITEM_LIST="view_item_list",W.VIEW_PROMOTION="view_promotion",W.VIEW_SEARCH_RESULTS="view_search_results";const fg=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},Af.INTERNAL.registerComponent(new zd("analytics-compat",fg,"PUBLIC").setServiceProps(hg).setMultipleInstances(!0)),Af.registerVersion("@firebase/analytics-compat","0.1.5");const pg=new Map,gg={activated:!1,tokenObservers:[]},mg={initialized:!1,enabled:!1};function vg(e){return pg.get(e)||gg}function yg(e,t){pg.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."});function Eg(e=!1){var t;return e?null===(t=self.grecaptcha)||void 0===t?void 0:t.enterprise:self.grecaptcha}function Sg(e){if(!vg(e).activated)throw Tg.create("use-before-activation",{appName:e.name})}async function kg({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 Cg="firebase-app-check-database",Ag=1,Ng="firebase-app-check-store",Rg="debug-token";let Pg=null;function xg(){return Pg||(Pg=new Promise((t,n)=>{try{const e=indexedDB.open(Cg,Ag);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(Ng,{keyPath:"compositeKey"})}}catch(e){n(Tg.create("storage-open",{originalErrorMessage:e.message}))}}),Pg)}async function Og(e,t){const n=await xg(),r=n.transaction(Ng,"readwrite"),i=r.objectStore(Ng),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 Dg(e){const t=await xg(),i=t.transaction(Ng,"readonly"),n=i.objectStore(Ng),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 Lg(e){return`${e.options.appId}-${e.name}`}const Mg=new ef("@firebase/app-check");async function Fg(t){if(dd()){let e=void 0;try{e=await Dg(Lg(t))}catch(e){Mg.warn(`Failed to read token from IndexedDB. Error: ${e}`)}return e}}function Ug(e,t){return dd()?Og(Lg(e),t).catch(e=>{Mg.warn(`Failed to write token to IndexedDB. Error: ${e}`)}):Promise.resolve()}async function jg(){let e=void 0;try{e=await Dg(Rg)}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,Og(Rg,t).catch(e=>Mg.warn(`Failed to persist debug token to IndexedDB. Error: ${e}`)),n}function qg(){return mg.enabled}async function Vg(){var e=mg;if(e.enabled&&e.token)return e.token.promise;throw Error(`
7
+ `)}const Af=l;wf("@firebase/app-compat","0.1.10",void 0);Af.registerVersion("firebase","9.5.0","app-compat");function Nf(n){return new Promise(function(e,t){n.onsuccess=function(){e(n.result)},n.onerror=function(){t(n.error)}})}function Rf(n,r,i){var s,e=new Promise(function(e,t){Nf(s=n[r].apply(n,i)).then(e,t)});return e.request=s,e}function Pf(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 xf(t,n,r,e){e.forEach(function(e){e in r.prototype&&(t.prototype[e]=function(){return Rf(this[n],e,arguments)})})}function Df(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 Of(e,r,t,n){n.forEach(function(n){n in t.prototype&&(e.prototype[n]=function(){return e=this[r],(t=Rf(e,n,arguments)).then(function(e){if(e)return new Mf(e,t.request)});var e,t})})}function Lf(e){this._index=e}function Mf(e,t){this._cursor=e,this._request=t}function Ff(e){this._store=e}function Uf(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 jf(e,t,n){this._db=e,this.oldVersion=t,this.transaction=new Uf(n)}function qf(e){this._db=e}function Vf(e,t,n){var r=Rf(indexedDB,"open",[e,t]),i=r.request;return i&&(i.onupgradeneeded=function(e){n&&n(new jf(i.result,e.oldVersion,i.transaction))}),r.then(function(e){return new qf(e)})}function Bf(e){return Rf(indexedDB,"deleteDatabase",[e])}Pf(Lf,"_index",["name","keyPath","multiEntry","unique"]),xf(Lf,"_index",IDBIndex,["get","getKey","getAll","getAllKeys","count"]),Of(Lf,"_index",IDBIndex,["openCursor","openKeyCursor"]),Pf(Mf,"_cursor",["direction","key","primaryKey","value"]),xf(Mf,"_cursor",IDBCursor,["update","delete"]),["advance","continue","continuePrimaryKey"].forEach(function(n){n in IDBCursor.prototype&&(Mf.prototype[n]=function(){var t=this,e=arguments;return Promise.resolve().then(function(){return t._cursor[n].apply(t._cursor,e),Nf(t._request).then(function(e){if(e)return new Mf(e,t._request)})})})}),Ff.prototype.createIndex=function(){return new Lf(this._store.createIndex.apply(this._store,arguments))},Ff.prototype.index=function(){return new Lf(this._store.index.apply(this._store,arguments))},Pf(Ff,"_store",["name","keyPath","indexNames","autoIncrement"]),xf(Ff,"_store",IDBObjectStore,["put","add","delete","clear","get","getAll","getKey","getAllKeys","count"]),Of(Ff,"_store",IDBObjectStore,["openCursor","openKeyCursor"]),Df(Ff,"_store",IDBObjectStore,["deleteIndex"]),Uf.prototype.objectStore=function(){return new Ff(this._tx.objectStore.apply(this._tx,arguments))},Pf(Uf,"_tx",["objectStoreNames","mode"]),Df(Uf,"_tx",IDBTransaction,["abort"]),jf.prototype.createObjectStore=function(){return new Ff(this._db.createObjectStore.apply(this._db,arguments))},Pf(jf,"_db",["name","version","objectStoreNames"]),Df(jf,"_db",IDBDatabase,["deleteObjectStore","close"]),qf.prototype.transaction=function(){return new Uf(this._db.transaction.apply(this._db,arguments))},Pf(qf,"_db",["name","version","objectStoreNames"]),Df(qf,"_db",IDBDatabase,["close"]),["openCursor","openKeyCursor"].forEach(function(s){[Ff,Lf].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)}})})}),[Lf,Ff].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)})})})});We="@firebase/installations",c="0.5.4";const $f=1e4,Kf="w:0.5.4",zf="FIS_v2",Wf="https://firebaseinstallations.googleapis.com/v1",Hf=36e5;const Gf=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 Qf(e){return e instanceof gd&&e.code.includes("request-failed")}function Yf({projectId:e}){return`${Wf}/projects/${e}/installations`}function Jf(e){return{token:e.token,requestStatus:2,expiresIn:(e=e.expiresIn,Number(e.replace("s","000"))),creationTime:Date.now()}}async function Xf(e,t){var n=(await t.json()).error;return Gf.create("request-failed",{requestName:e,serverCode:n.code,serverMessage:n.message,serverStatus:n.status})}function Zf({apiKey:e}){return new Headers({"Content-Type":"application/json",Accept:"application/json","x-goog-api-key":e})}function ep(e,{refreshToken:t}){const n=Zf(e);return n.append("Authorization",(t=t,`${zf} ${t}`)),n}async function tp(e){var t=await e();return 500<=t.status&&t.status<600?e():t}function np(t){return new Promise(e=>{setTimeout(e,t)})}const rp=/^[cdef][\w-]{21}$/,ip="";function sp(){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 rp.test(e)?e:ip}catch(e){return ip}}function op(e){return`${e.appName}!${e.appId}`}const ap=new Map;function cp(e,t){var n=op(e);lp(n,t),function(e,t){const n=function(){!up&&"BroadcastChannel"in self&&(up=new BroadcastChannel("[Firebase] FID Change"),up.onmessage=e=>{lp(e.data.key,e.data.fid)});return up}();n&&n.postMessage({key:e,fid:t});0===ap.size&&up&&(up.close(),up=null)}(n,t)}function lp(e,t){var n=ap.get(e);if(n)for(const r of n)r(t)}let up=null;const hp="firebase-installations-store";let dp=null;function fp(){return dp=dp||Vf("firebase-installations-database",1,e=>{0===e.oldVersion&&e.createObjectStore(hp)}),dp}async function pp(e,t){var n=op(e);const r=await fp(),i=r.transaction(hp,"readwrite"),s=i.objectStore(hp);var o=await s.get(n);return await s.put(t,n),await i.complete,o&&o.fid===t.fid||cp(e,t.fid),t}async function gp(e){var t=op(e);const n=await fp(),r=n.transaction(hp,"readwrite");await r.objectStore(hp).delete(t),await r.complete}async function mp(e,t){var n=op(e);const r=await fp(),i=r.transaction(hp,"readwrite"),s=i.objectStore(hp);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||cp(e,a.fid),a}async function vp(n){let r;var e=await mp(n,e=>{var t=_p(e||{fid:sp(),registrationStatus:0}),t=function(e,t){{if(0!==t.registrationStatus)return 1===t.registrationStatus?{installationEntry:t,registrationPromise:async function(e){let t=await yp(e);for(;1===t.registrationStatus;)await np(100),t=await yp(e);if(0!==t.registrationStatus)return t;{var{installationEntry:n,registrationPromise:r}=await vp(e);return r||n}}(e)}:{installationEntry:t};if(!navigator.onLine){var n=Promise.reject(Gf.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=Yf(e);var r=Zf(e),i={fid:t,authVersion:zf,appId:e.appId,sdkVersion:Kf};const s={method:"POST",headers:r,body:JSON.stringify(i)},o=await tp(()=>fetch(n,s));if(o.ok){i=await o.json();return{fid:i.fid||t,registrationStatus:2,refreshToken:i.refreshToken,authToken:Jf(i.authToken)}}throw await Xf("Create Installation",o)}(t,n);return pp(t,e)}catch(e){throw Qf(e)&&409===e.customData.serverCode?await gp(t):await pp(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===ip?{installationEntry:await r}:{installationEntry:e,registrationPromise:r}}function yp(e){return mp(e,e=>{if(!e)throw Gf.create("installation-not-found");return _p(e)})}function _p(e){return 1===(t=e).registrationStatus&&t.registrationTime+$f<Date.now()?{fid:e.fid,registrationStatus:0}:e;var t}async function wp({appConfig:e,platformLoggerProvider:t},n){const r=([i,s]=[e,n["fid"]],`${Yf(i)}/${s}/authTokens:generate`);var i,s;const o=ep(e,n),a=t.getImmediate({optional:!0});a&&o.append("x-firebase-client",a.getPlatformInfoString());var c={installation:{sdkVersion:Kf}};const l={method:"POST",headers:o,body:JSON.stringify(c)},u=await tp(()=>fetch(r,l));if(u.ok)return Jf(await u.json());throw await Xf("Generate Auth Token",u)}async function bp(r,i=!1){let s;var e=await mp(r.appConfig,e=>{if(!Tp(e))throw Gf.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+Hf}(t)){if(1===n.requestStatus)return s=async function(e,t){let n=await Ip(e.appConfig);for(;1===n.authToken.requestStatus;)await np(100),n=await Ip(e.appConfig);var r=n.authToken;return 0===r.requestStatus?bp(e,t):r}(r,i),e;if(!navigator.onLine)throw Gf.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 wp(t,n),e=Object.assign(Object.assign({},n),{authToken:r});return await pp(t.appConfig,e),r}catch(e){throw!Qf(e)||401!==e.customData.serverCode&&404!==e.customData.serverCode?(r=Object.assign(Object.assign({},n),{authToken:{requestStatus:0}}),await pp(t.appConfig,r)):await gp(t.appConfig),e}}(r,n),n}return e});return s?await s:e.authToken}function Ip(e){return mp(e,e=>{if(!Tp(e))throw Gf.create("not-registered");var t,n=e.authToken;return 1===(t=n).requestStatus&&t.requestTime+$f<Date.now()?Object.assign(Object.assign({},e),{authToken:{requestStatus:0}}):e})}function Tp(e){return void 0!==e&&2===e.registrationStatus}async function Ep(e,t=!1){var n,r=e;return e=r.appConfig,await((n=(await vp(e)).registrationPromise)&&await n),(await bp(r,t)).token}function Sp(e){return Gf.create("missing-app-config-values",{valueName:e})}const kp="installations",Cp=e=>{var t=e.getProvider("app").getImmediate();return{app:t,appConfig:function(e){if(!e||!e.options)throw Sp("App Configuration");if(!e.name)throw Sp("App Name");for(const t of["projectId","apiKey","appId"])if(!e.options[t])throw Sp(t);return{appName:e.name,projectId:e.options.projectId,apiKey:e.options.apiKey,appId:e.options.appId}}(t),platformLoggerProvider:ff(t,"platform-logger"),_delete:()=>Promise.resolve()}},Ap=e=>{const t=ff(e.getProvider("app").getImmediate(),kp).getImmediate();return{getId:()=>async function(e){var t=e;const{installationEntry:n,registrationPromise:r}=await vp(t.appConfig);return(r||bp(t)).catch(console.error),n.fid}(t),getToken:e=>Ep(t,e)}};df(new zd(kp,Cp,"PUBLIC")),df(new zd("installations-internal",Ap,"PRIVATE")),wf(We,c),wf(We,c,"esm2017");const Np="analytics",Rp="firebase_id",Pp="origin",xp="https://firebase.googleapis.com/v1alpha/projects/-/apps/{app-id}/webConfig",Dp="https://www.googletagmanager.com/gtag/js",Op=new ef("@firebase/analytics");function Lp(e){return Promise.all(e.map(e=>e.catch(e=>e)))}function Mp(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 Lp(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){Op.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 Lp(n);var a=c.find(e=>e.measurementId===i);a&&await t[a.appId]}}catch(e){Op.error(e)}e("config",i,s)}(r,i,s,o,t,n):r("set",t)}catch(e){Op.error(e)}}}const Fp=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.'}),Up=30;const jp=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 qp(e){var t,{appId:n,apiKey:r}=e,r={method:"GET",headers:new Headers({Accept:"application/json","x-goog-api-key":r})},n=xp.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 Fp.create("config-fetch-failed",{httpStatus:i.status,responseMessage:e})}}async function Vp(e,t=jp,n){var{appId:r,apiKey:i,measurementId:s}=e.options;if(!r)throw Fp.create("no-app-id");if(!i){if(s)return{measurementId:s,appId:r};throw Fp.create("no-api-key")}var o=t.getThrottleMetadata(r)||{backoffCount:0,throttleEndTimeMillis:Date.now()};const a=new Kp;return setTimeout(async()=>{a.abort()},void 0!==n?n:6e4),async function t(n,{throttleEndTimeMillis:e,backoffCount:r},i,s=jp){const{appId:o,measurementId:a}=n;try{await Bp(i,e)}catch(e){if(a)return Op.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 qp(n);return s.deleteThrottleMetadata(o),c}catch(e){if(!$p(e)){if(s.deleteThrottleMetadata(o),a)return Op.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)?$d(r,s.intervalMillis,Up):$d(r,s.intervalMillis),u={throttleEndTimeMillis:Date.now()+l,backoffCount:r+1};return s.setThrottleMetadata(o,u),Op.debug(`Calling attemptFetch again in ${l} millis`),t(n,u,i,s)}}({appId:r,apiKey:i,measurementId:s},o,a,t)}function Bp(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(Fp.create("fetch-throttle",{throttleEndTimeMillis:s}))})})}function $p(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 Kp{constructor(){this.listeners=[]}addEventListener(e){this.listeners.push(e)}abort(){this.listeners.forEach(e=>e())}}async function zp(t,e,n,r,i,s,o){const a=Vp(t);a.then(e=>{n[e.measurementId]=e.appId,t.options.measurementId&&e.measurementId!==t.options.measurementId&&Op.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=>Op.error(e)),e.push(a);var c=async function(){if(!dd())return Op.warn(Fp.create("indexeddb-unavailable",{errorInfo:"IndexedDB is not available in this environment."}).message),!1;try{await fd()}catch(e){return Op.warn(Fp.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(Dp))return t}()&&function(e,t){const n=document.createElement("script");n.src=`${Dp}?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[Pp]="firebase",h.update=!0,null!=u&&(h[Rp]=u),i("config",l.measurementId,h),l.measurementId}class Wp{constructor(e){this.app=e}_delete(){return delete Hp[this.app.options.appId],Promise.resolve()}}let Hp={},Gp=[];const Qp={};let Yp="dataLayer",Jp="gtag",Xp,Zp,eg=!1;function tg(e){if(eg)throw Fp.create("already-initialized");e.dataLayerName&&(Yp=e.dataLayerName),e.gtagName&&(Jp=e.gtagName)}function ng(e,t,n){!function(){const e=[];var t;cd()&&e.push("This is a browser extension environment."),pd()||e.push("Cookies are not available."),0<e.length&&(t=e.map((e,t)=>`(${t+1}) ${e}`).join(" "),t=Fp.create("invalid-analytics-context",{errorInfo:t}),Op.warn(t.message))}();var r,i,s=e.options.appId;if(!s)throw Fp.create("no-app-id");if(!e.options.apiKey){if(!e.options.measurementId)throw Fp.create("no-api-key");Op.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!=Hp[s])throw Fp.create("already-exists",{id:s});return eg||(function(e){let t=[];Array.isArray(window[e])?t=window[e]:window[e]=t,t}(Yp),{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]=Mp(s,e,t,n),{gtagCore:s,wrappedGtag:window[i]}}(Hp,Gp,Qp,Yp,Jp),Zp=r,Xp=i,eg=!0),Hp[s]=zp(e,Gp,Qp,t,Xp,Yp,n),new Wp(e)}async function rg(){if(cd())return!1;if(!pd())return!1;if(!dd())return!1;try{return await fd()}catch(e){return!1}}function ig(e,t,n){e=Kd(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})}(Zp,Hp[e.app.options.appId],t,n).catch(e=>Op.error(e))}function sg(e,t,n){e=Kd(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})}(Zp,Hp[e.app.options.appId],t,n).catch(e=>Op.error(e))}function og(e,t,n){e=Kd(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})}(Zp,Hp[e.app.options.appId],t,n).catch(e=>Op.error(e))}function ag(e,t){e=Kd(e),async function(e,t){var n=await e;window[`ga-disable-${n}`]=!t}(Hp[e.app.options.appId],t).catch(e=>Op.error(e))}function cg(e,t,n,r){e=Kd(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})))}(Zp,Hp[e.app.options.appId],t,n,r).catch(e=>Op.error(e))}const lg="@firebase/analytics";df(new zd(Np,(e,{options:t})=>{return ng(e.getProvider("app").getImmediate(),e.getProvider("installations-internal").getImmediate(),t)},"PUBLIC")),df(new zd("analytics-internal",function(e){try{const r=e.getProvider(Np).getImmediate();return{logEvent:(e,t,n)=>cg(r,e,t,n)}}catch(e){throw Fp.create("interop-component-reg-failed",{reason:e})}},"PRIVATE")),wf(lg,"0.7.4"),wf(lg,"0.7.4","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)}}(W=ug=ug||{}).ADD_SHIPPING_INFO="add_shipping_info",W.ADD_PAYMENT_INFO="add_payment_info",W.ADD_TO_CART="add_to_cart",W.ADD_TO_WISHLIST="add_to_wishlist",W.BEGIN_CHECKOUT="begin_checkout",W.CHECKOUT_PROGRESS="checkout_progress",W.EXCEPTION="exception",W.GENERATE_LEAD="generate_lead",W.LOGIN="login",W.PAGE_VIEW="page_view",W.PURCHASE="purchase",W.REFUND="refund",W.REMOVE_FROM_CART="remove_from_cart",W.SCREEN_VIEW="screen_view",W.SEARCH="search",W.SELECT_CONTENT="select_content",W.SELECT_ITEM="select_item",W.SELECT_PROMOTION="select_promotion",W.SET_CHECKOUT_OPTION="set_checkout_option",W.SHARE="share",W.SIGN_UP="sign_up",W.TIMING_COMPLETE="timing_complete",W.VIEW_CART="view_cart",W.VIEW_ITEM="view_item",W.VIEW_ITEM_LIST="view_item_list",W.VIEW_PROMOTION="view_promotion",W.VIEW_SEARCH_RESULTS="view_search_results";const fg=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},Af.INTERNAL.registerComponent(new zd("analytics-compat",fg,"PUBLIC").setServiceProps(hg).setMultipleInstances(!0)),Af.registerVersion("@firebase/analytics-compat","0.1.5");const pg=new Map,gg={activated:!1,tokenObservers:[]},mg={initialized:!1,enabled:!1};function vg(e){return pg.get(e)||gg}function yg(e,t){pg.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 Sg(e){if(!vg(e).activated)throw Tg.create("use-before-activation",{appName:e.name})}function kg(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 Dg=null;function Og(){return Dg||(Dg=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}))}}),Dg)}async function Lg(e,t){const n=await Og(),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 Og(),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 ef("@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 $g(){var e=mg;if(e.enabled&&e.token)return e.token.promise;throw Error(`
8
8
  Can't get debug token in production mode.
9
- `)}function Bg(){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(jg())}}const $g={error:"UNKNOWN_ERROR"};async function Kg(e,t=!1){var n=e.app;Sg(n);const r=vg(n);let i=r.token,s=void 0;if(i||(o=await r.cachedTokenPromise)&&Gg(o)&&(i=o,yg(n,Object.assign(Object.assign({},r),{token:i})),Hg(n,{token:i.token})),!t&&i&&Gg(i))return{token:i.token};if(qg()){var o=await kg(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 Vg()),e.platformLoggerProvider);return await Ug(n,o),yg(n,Object.assign(Object.assign({},r),{token:o})),{token:o.token}}try{i=await r.provider.getToken()}catch(e){Mg.error(e),s=e}let a;return i?(a={token:i.token},yg(n,Object.assign(Object.assign({},r),{token:i})),await Ug(n,i)):a=(e=s,{token:function(e){return Zh.encodeString(JSON.stringify(e),!1)}($g),error:e}),Hg(n,a),a}function zg(e,t,n,r){var i=e["app"];const s=vg(i);var o={next:n,error:r,type:t};const a=Object.assign(Object.assign({},s),{tokenObservers:[...s.tokenObservers,o]});if(a.tokenRefresher||(o=function(n){const r=n["app"];return new Ig(async()=>{var e=vg(r);let t;if(t=e.token?await Kg(n,!0):await Kg(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),a.tokenRefresher=o),!a.tokenRefresher.isRunning()&&s.isTokenAutoRefreshEnabled&&a.tokenRefresher.start(),s.token&&Gg(s.token)){const c=s.token;Promise.resolve().then(()=>n({token:c.token})).catch(()=>{})}else null==s.token&&s.cachedTokenPromise.then(e=>{e&&Gg(e)&&n({token:e.token})}).catch(()=>{});yg(i,a)}function Wg(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 Hg(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 Gg(e){return 0<e.expireTimeMillis-Date.now()}class Qg{constructor(e,t){this.app=e,this.platformLoggerProvider=t}_delete(){var e=vg(this.app)["tokenObservers"];for(const t of e)Wg(this.app,t.next);return Promise.resolve()}}const Yg="https://www.google.com/recaptcha/api.js",Jg="https://www.google.com/recaptcha/enterprise.js";function Xg(t,n){var e=vg(t);const r=new rd;yg(t,Object.assign(Object.assign({},e),{reCAPTCHAState:{initialized:r}}));const i=tm(t);e=Eg(!1);return e?em(t,n,e,i,r):function(e){const t=document.createElement("script");t.src=Yg,t.onload=e,document.head.appendChild(t)}(()=>{var e=Eg(!1);if(!e)throw new Error("no recaptcha");em(t,n,e,i,r)}),r.promise}function Zg(t,n){var e=vg(t);const r=new rd;yg(t,Object.assign(Object.assign({},e),{reCAPTCHAState:{initialized:r}}));const i=tm(t);e=Eg(!0);return e?em(t,n,e,i,r):function(e){const t=document.createElement("script");t.src=Jg,t.onload=e,document.head.appendChild(t)}(()=>{var e=Eg(!0);if(!e)throw new Error("no recaptcha");em(t,n,e,i,r)}),r.promise}function em(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 tm(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 nm(r){Sg(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 rm{constructor(e){this._siteKey=e}async getToken(){var e=await nm(this._app).catch(e=>{throw Tg.create("recaptcha-error")});return kg(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,e),this._platformLoggerProvider)}initialize(e){this._app=e,this._platformLoggerProvider=ff(e,"platform-logger"),Xg(e,this._siteKey).catch(()=>{})}isEqual(e){return e instanceof rm&&this._siteKey===e._siteKey}}class im{constructor(e){this._siteKey=e}async getToken(){var e=await nm(this._app).catch(e=>{throw Tg.create("recaptcha-error")});return kg(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,e),this._platformLoggerProvider)}initialize(e){this._app=e,this._platformLoggerProvider=ff(e,"platform-logger"),Zg(e,this._siteKey).catch(()=>{})}isEqual(e){return e instanceof im&&this._siteKey===e._siteKey}}class sm{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 sm&&this._customProviderOptions.getToken.toString()===e._customProviderOptions.getToken.toString()}}function om(e=yf(),t){const n=ff(e=Kd(e),"app-check");if(mg.initialized||Bg(),qg()&&Vg().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=Fg(t).then(e=>(e&&Gg(e)&&yg(t,Object.assign(Object.assign({},vg(t)),{token:e})),e)),i.isTokenAutoRefreshEnabled=void 0===n?t.automaticDataCollectionEnabled:n,yg(t,i),i.provider.initialize(t)}(e,t.provider,t.isTokenAutoRefreshEnabled),r}const am="app-check-internal";df(new zd("app-check",e=>{var t,n=e.getProvider("app").getImmediate(),r=e.getProvider("platform-logger");return t=n,e=r,new Qg(t,e)},"PUBLIC").setInstantiationMode("EXPLICIT").setInstanceCreatedCallback((e,t,n)=>{e.getProvider(am).initialize()})),df(new zd(am,e=>{var t,n=e.getProvider("app-check").getImmediate();return t=n,{getToken:e=>Kg(t,e),addTokenListener:e=>zg(t,"INTERNAL",e),removeTokenListener:e=>Wg(t.app,e)}},"PUBLIC").setInstantiationMode("EXPLICIT")),wf("@firebase/app-check","0.5.1");const cm=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 lm{constructor(e){this.app=e}activate(e,t){let n;n="string"==typeof e?new rm(e):e instanceof im||e instanceof rm||e instanceof sm?e:new sm({getToken:e.getToken}),this._delegate=om(this.app,{provider:n,isTokenAutoRefreshEnabled:t})}setTokenAutoRefreshEnabled(e){if(!this._delegate)throw cm.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 cm.create("use-before-activation",{appName:this.app.name});return async function(e,t){var n=await Kg(e,t);if(n.error)throw n.error;return{token:n.token}}(this._delegate,e)}onTokenChanged(e,t,n){if(!this._delegate)throw cm.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),zg(e,"EXTERNAL",r,i),()=>Wg(e.app,r)}(this._delegate,e,t)}}const um=e=>{var t=e.getProvider("app-compat").getImmediate();return new lm(t)};function hm(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}Af.INTERNAL.registerComponent(new zd("appCheck-compat",um,"PUBLIC").setServiceProps({ReCaptchaEnterpriseProvider:im,ReCaptchaV3Provider:rm,CustomProvider:sm})),Af.registerVersion("@firebase/app-check-compat","0.2.1");const dm={FACEBOOK:"facebook.com",GITHUB:"github.com",GOOGLE:"google.com",PASSWORD:"password",PHONE:"phone",TWITTER:"twitter.com"},fm={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 pm(){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 gm(){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 mm=pm,vm=new md("auth","Firebase",pm()),ym=new ef("@firebase/auth");function _m(e,...t){ym.logLevel<=Kh.ERROR&&ym.error(`Auth (${mf}): ${e}`,...t)}function wm(e,...t){throw Em(e,...t)}function bm(e,...t){return Em(e,...t)}function Im(e,t,n){var r=Object.assign(Object.assign({},mm()),{[t]:n});const i=new md("auth","Firebase",r);return i.create(t,{appName:e.name})}function Tm(e,t,n){if(!(t instanceof n))throw n.name!==t.constructor.name&&wm(e,"argument-error"),Im(e,"argument-error",`Type of ${t.constructor.name} does not match expected instance.`+"Did you pass a reference from a different Auth SDK?")}function Em(e,...t){if("string"==typeof e)return vm.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 Sm(e,t,...n){if(!e)throw Em(t,...n)}function km(e){var t="INTERNAL ASSERTION FAILED: "+e;throw _m(t),new Error(t)}function Cm(e,t){e||km(t)}const Am=new Map;function Nm(e){Cm(e instanceof Function,"Expected a class definition");let t=Am.get(e);return t?Cm(t instanceof e,"Instance stored in cache mismatched with class"):(t=new e,Am.set(e,t)),t}function Rm(){var e;return"undefined"!=typeof self&&(null===(e=self.location)||void 0===e?void 0:e.href)||""}function Pm(){return"http:"===xm()||"https:"===xm()}function xm(){var e;return"undefined"!=typeof self&&(null===(e=self.location)||void 0===e?void 0:e.protocol)||null}class Om{constructor(e,t){Cm((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&&(Pm()||cd()||"connection"in navigator)&&!navigator.onLine?Math.min(5e3,this.shortDelay):this.isMobile?this.longDelay:this.shortDelay}}function Dm(e,t){Cm(e.emulator,"Emulator should always be set here");var n=e.emulator["url"];return t?`${n}${t.startsWith("/")?t.slice(1):t}`:n}class Lm{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 km("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 km("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 km("Could not find Response implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill"))}}const Mm={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"},Fm=new Om(3e4,6e4);function Um(e,t){return e.tenantId&&!t.tenantId?Object.assign(Object.assign({},t),{tenantId:e.tenantId}):t}async function jm(i,s,o,a,e={}){return qm(i,e,()=>{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=new(Lm.headers());return r.set("Content-Type","application/json"),r.set("X-Client-Version",i._getSdkClientVersion()),i.languageCode&&r.set("X-Firebase-Locale",i.languageCode),Lm.fetch()(Bm(i,i.config.apiHost,o,n),Object.assign({method:s,headers:r,referrerPolicy:"no-referrer"},e))})}async function qm(t,e,n){t._canInitEmulator=!1;var r=Object.assign(Object.assign({},Mm),e);try{const o=new $m(t),a=await Promise.race([n(),o.promise]);o.clearNetworkTimeout();var i=await a.json();if("needConfirmation"in i)throw Km(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 Km(t,"credential-already-in-use",i);if("EMAIL_EXISTS"===l)throw Km(t,"email-already-in-use",i);var s=r[l]||l.toLowerCase().replace(/[_\s]+/g,"-");if(u)throw Im(t,s,u);wm(t,s)}}catch(e){if(e instanceof gd)throw e;wm(t,"network-request-failed")}}async function Vm(e,t,n,r,i={}){var s=await jm(e,t,n,r,i);return"mfaPendingCredential"in s&&wm(e,"multi-factor-auth-required",{_serverResponse:s}),s}function Bm(e,t,n,r){var i=`${t}${n}?${r}`;return e.config.emulator?Dm(e.config,i):`${e.config.apiScheme}://${i}`}class $m{constructor(e){this.auth=e,this.timer=null,this.promise=new Promise((e,t)=>{this.timer=setTimeout(()=>t(bm(this.auth,"timeout")),Fm.get())})}clearNetworkTimeout(){clearTimeout(this.timer)}}function Km(e,t,n){const r={appName:e.name};n.email&&(r.email=n.email),n.phoneNumber&&(r.phoneNumber=n.phoneNumber);const i=bm(e,t,r);return i.customData._tokenResponse=n,i}function zm(e){if(e)try{const t=new Date(Number(e));if(!isNaN(t.getTime()))return t.toUTCString()}catch(e){}}function Wm(e){return 1e3*Number(e)}function Hm(e){var[t,n,r]=e.split(".");if(void 0===t||void 0===n||void 0===r)return _m("JWT malformed, contained fewer than 3 sections"),null;try{var i=td(n);return i?JSON.parse(i):(_m("Failed to decode base64 JWT payload"),null)}catch(e){return _m("Caught error parsing JWT payload as JSON",e),null}}async function Gm(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 Qm{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 Ym{constructor(e,t){this.createdAt=e,this.lastLoginAt=t,this._initializeTime()}_initializeTime(){this.lastSignInTime=zm(this.lastLoginAt),this.creationTime=zm(this.createdAt)}_copy(e){this.createdAt=e.createdAt,this.lastLoginAt=e.lastLoginAt,this._initializeTime()}toJSON(){return{createdAt:this.createdAt,lastLoginAt:this.lastLoginAt}}}async function Jm(e){var t=e.auth,n=await e.getIdToken(),r=await Gm(e,async function(e,t){return jm(e,"POST","/v1/accounts:lookup",t)}(t,{idToken:n}));Sm(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=hm(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 Ym(i.createdAt,i.lastLoginAt),isAnonymous:t};Object.assign(e,t)}class Xm{constructor(){this.refreshToken=null,this.accessToken=null,this.expirationTime=null}get isExpired(){return!this.expirationTime||Date.now()>this.expirationTime-3e4}updateFromServerResponse(e){Sm(e.idToken,"internal-error"),Sm(void 0!==e.idToken,"internal-error"),Sm(void 0!==e.refreshToken,"internal-error");var t,n,n="expiresIn"in e&&void 0!==e.expiresIn?Number(e.expiresIn):(t=e.idToken,Sm(n=Hm(t),"internal-error"),Sm(void 0!==n.exp,"internal-error"),Sm(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 Sm(!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 r,i,{accessToken:n,refreshToken:s,expiresIn:o}=(i=t,await{accessToken:(o=await qm(r=e,{},()=>{var e=Cd({grant_type:"refresh_token",refresh_token:i}).slice(1),{tokenApiHost:t,apiKey:n}=r.config,n=Bm(r,t,"/v1/token",`key=${n}`);return Lm.fetch()(n,{method:"POST",headers:{"X-Client-Version":r._getSdkClientVersion(),"Content-Type":"application/x-www-form-urlencoded"},body:e})})).access_token,expiresIn:o.expires_in,refreshToken:o.refresh_token});this.updateTokensAndExpiration(n,s,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 Xm;return n&&(Sm("string"==typeof n,"internal-error",{appName:e}),s.refreshToken=n),r&&(Sm("string"==typeof r,"internal-error",{appName:e}),s.accessToken=r),i&&(Sm("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 Xm,this.toJSON())}_performRefresh(){return km("not implemented")}}function Zm(e,t){Sm("string"==typeof e||void 0===e,"internal-error",{appName:t})}class ev{constructor(e){var{uid:t,auth:n,stsTokenManager:r}=e,i=hm(e,["uid","auth","stsTokenManager"]);this.providerId="firebase",this.emailVerified=!1,this.isAnonymous=!1,this.tenantId=null,this.providerData=[],this.proactiveRefresh=new Qm(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.metadata=new Ym(i.createdAt||void 0,i.lastLoginAt||void 0)}async getIdToken(e){var t=await Gm(this,this.stsTokenManager.getToken(this.auth,e));return Sm(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=Kd(e);var r=await n.getIdToken(t),i=Hm(r);Sm(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:zm(Wm(i.auth_time)),issuedAtTime:zm(Wm(i.iat)),expirationTime:zm(Wm(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=Kd(e);await Jm(t),await t.auth._persistUserIfCurrent(t),t.auth._notifyListenersIfCurrent(t)}(this)}_assign(e){this!==e&&(Sm(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 ev(Object.assign(Object.assign({},this),{auth:e,stsTokenManager:this.stsTokenManager._clone()}))}_onReload(e){Sm(!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 Jm(this),await this.auth._persistUserIfCurrent(this),n&&this.auth._notifyListenersIfCurrent(this)}async delete(){var e=await this.getIdToken();return await Gm(this,async function(e,t){return jm(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:f,stsTokenManager:p}=t;Sm(u&&p,e,"internal-error");var g=Xm.fromJSON(this.name,p);Sm("string"==typeof u,e,"internal-error"),Zm(n,e.name),Zm(r,e.name),Sm("boolean"==typeof h,e,"internal-error"),Sm("boolean"==typeof d,e,"internal-error"),Zm(i,e.name),Zm(s,e.name),Zm(o,e.name),Zm(a,e.name),Zm(c,e.name),Zm(l,e.name);const m=new ev({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 f&&Array.isArray(f)&&(m.providerData=f.map(e=>Object.assign({},e))),a&&(m._redirectEventId=a),m}static async _fromIdTokenResponse(e,t,n=!1){const r=new Xm;r.updateFromServerResponse(t);var i=new ev({uid:t.localId,auth:e,stsTokenManager:r,isAnonymous:n});return await Jm(i),i}}class tv{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){}}tv.type="NONE";const nv=tv;function rv(e,t,n){return`firebase:${e}:${t}:${n}`}class iv{constructor(e,t,n){this.persistence=e,this.auth=t,this.userKey=n;var{config:r,name:i}=this.auth;this.fullUserKey=rv(this.userKey,r.apiKey,i),this.fullPersistenceKey=rv("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?ev._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 iv(Nm(nv),e,n);const r=(await Promise.all(t.map(async e=>{if(await e._isAvailable())return e}))).filter(e=>e);let i=r[0]||Nm(nv);const s=rv(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=ev._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 iv(i,e,n)}}function sv(e){const t=e.toLowerCase();if(t.includes("opera/")||t.includes("opr/")||t.includes("opios/"))return"Opera";if(lv(t))return"IEMobile";if(t.includes("msie")||t.includes("trident/"))return"IE";if(t.includes("edge/"))return"Edge";if(ov(t))return"Firefox";if(t.includes("silk/"))return"Silk";if(hv(t))return"Blackberry";if(dv(t))return"Webos";if(av(t))return"Safari";if((t.includes("chrome/")||cv(t))&&!t.includes("edge/"))return"Chrome";if(uv(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 ov(e=sd()){return/firefox\//i.test(e)}function av(e=sd()){const t=e.toLowerCase();return t.includes("safari/")&&!t.includes("chrome/")&&!t.includes("crios/")&&!t.includes("android")}function cv(e=sd()){return/crios\//i.test(e)}function lv(e=sd()){return/iemobile/i.test(e)}function uv(e=sd()){return/android/i.test(e)}function hv(e=sd()){return/blackberry/i.test(e)}function dv(e=sd()){return/webos/i.test(e)}function fv(e=sd()){return/iphone|ipad|ipod/i.test(e)}function pv(e=sd()){return fv(e)||uv(e)||dv(e)||hv(e)||/windows phone/i.test(e)||lv(e)}function gv(e,t=[]){let n;switch(e){case"Browser":n=sv(sd());break;case"Worker":n=`${sv(sd())}-${e}`;break;default:n=e}var r=t.length?t.join(","):"FirebaseCore-web";return`${n}/JsCore/${mf}/${r}`}class mv{constructor(e,t){this.app=e,this.config=t,this.currentUser=null,this.emulatorConfig=null,this.operations=Promise.resolve(),this.authStateSubscription=new yv(this),this.idTokenSubscription=new yv(this),this.redirectUser=null,this.isProactiveRefreshEnabled=!1,this._canInitEmulator=!0,this._isInitialized=!1,this._deleted=!1,this._initializationPromise=null,this._popupRedirectResolver=null,this._errorFactory=vm,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=Nm(n)),this._initializationPromise=this.queue(async()=>{var e;this._deleted||(this.persistenceManager=await iv.create(this,t),this._deleted||(null!==(e=this._popupRedirectResolver)&&void 0!==e&&e._shouldInitProactively&&await this._popupRedirectResolver._initialize(this),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?(Sm(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 Jm(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?Kd(e):null;return t&&Sm(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&&Sm(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(Nm(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||(Sm(t=e&&Nm(e)||this._popupRedirectResolver,this,"argument-error"),this.redirectPersistenceManager=await iv.create(this,[Nm(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 Sm(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 Sm(this.persistenceManager,this,"internal-error"),this.persistenceManager}_logFramework(e){e&&!this.frameworks.includes(e)&&(this.frameworks.push(e),this.frameworks.sort(),this.clientVersion=gv(this.config.clientPlatform,this._getFrameworks()))}_getFrameworks(){return this.frameworks}_getSdkClientVersion(){return this.clientVersion}}function vv(e){return Kd(e)}class yv{constructor(e){this.auth=e,this.observer=null,this.addObserver=Pd(e=>this.observer=e)}get next(){return Sm(this.observer,this.auth,"internal-error"),this.observer.next.bind(this.observer)}}function _v(e,t,n){const r=vv(e);Sm(r._canInitEmulator,r,"emulator-config-failed"),Sm(/^https?:\/\//.test(t),r,"invalid-emulator-scheme");var i=!(null==n||!n.disableWarnings);const s=wv(t);var{host:o,port:a}=function(e){const t=wv(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:bv(r.substr(s.length+1))}}var[o,s]=r.split(":");return{host:o,port:bv(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 wv(e){var t=e.indexOf(":");return t<0?"":e.substr(0,t+1)}function bv(e){if(!e)return null;var t=Number(e);return isNaN(t)?null:t}class Iv{constructor(e,t){this.providerId=e,this.signInMethod=t}toJSON(){return km("not implemented")}_getIdTokenResponse(e){return km("not implemented")}_linkToIdToken(e,t){return km("not implemented")}_getReauthenticationResolver(e){return km("not implemented")}}async function Tv(e,t){return jm(e,"POST","/v1/accounts:resetPassword",Um(e,t))}async function Ev(e,t){return jm(e,"POST","/v1/accounts:update",t)}async function Sv(e,t){return jm(e,"POST","/v1/accounts:sendOobCode",Um(e,t))}class kv extends Iv{constructor(e,t,n,r=null){super("password",n),this._email=e,this._password=t,this._tenantId=r}static _fromEmailAndPassword(e,t){return new kv(e,t,"password")}static _fromEmailAndCode(e,t,n=null){return new kv(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 Vm(e,"POST","/v1/accounts:signInWithPassword",Um(e,t))}(e,{returnSecureToken:!0,email:this._email,password:this._password});case"emailLink":return async function(e,t){return Vm(e,"POST","/v1/accounts:signInWithEmailLink",Um(e,t))}(e,{email:this._email,oobCode:this._password});default:wm(e,"internal-error")}}async _linkToIdToken(e,t){switch(this.signInMethod){case"password":return Ev(e,{idToken:t,returnSecureToken:!0,email:this._email,password:this._password});case"emailLink":return async function(e,t){return Vm(e,"POST","/v1/accounts:signInWithEmailLink",Um(e,t))}(e,{idToken:t,email:this._email,oobCode:this._password});default:wm(e,"internal-error")}}_getReauthenticationResolver(e){return this._getIdTokenResponse(e)}}async function Cv(e,t){return Vm(e,"POST","/v1/accounts:signInWithIdp",Um(e,t))}class Av extends Iv{constructor(){super(...arguments),this.pendingToken=null}static _fromParams(e){const t=new Av(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):wm("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=hm(t,["providerId","signInMethod"]);if(!n||!r)return null;const i=new Av(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 Cv(e,this.buildRequest())}_linkToIdToken(e,t){const n=this.buildRequest();return n.idToken=t,Cv(e,n)}_getReauthenticationResolver(e){const t=this.buildRequest();return t.autoCreate=!1,Cv(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 Nv={USER_NOT_FOUND:"user-not-found"};class Rv extends Iv{constructor(e){super("phone","phone"),this.params=e}static _fromVerification(e,t){return new Rv({verificationId:e,verificationCode:t})}static _fromTokenResponse(e,t){return new Rv({phoneNumber:e,temporaryProof:t})}_getIdTokenResponse(e){return async function(e,t){return Vm(e,"POST","/v1/accounts:signInWithPhoneNumber",Um(e,t))}(e,this._makeVerificationRequest())}_linkToIdToken(e,t){return async function(e,t){var n=await Vm(e,"POST","/v1/accounts:signInWithPhoneNumber",Um(e,t));if(n.temporaryProof)throw Km(e,"account-exists-with-different-credential",n);return n}(e,Object.assign({idToken:t},this._makeVerificationRequest()))}_getReauthenticationResolver(e){return async function(e,t){return Vm(e,"POST","/v1/accounts:signInWithPhoneNumber",Um(e,Object.assign(Object.assign({},t),{operation:"REAUTH"})),Nv)}(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 Rv({verificationId:t,verificationCode:n,phoneNumber:r,temporaryProof:i}):null}}class Pv{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);Sm(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 Pv(t)}catch(e){return null}}}class xv{constructor(){this.providerId=xv.PROVIDER_ID}static credential(e,t){return kv._fromEmailAndPassword(e,t)}static credentialWithLink(e,t){var n=Pv.parseLink(t);return Sm(n,"argument-error"),kv._fromEmailAndCode(e,n.code,n.tenantId)}}xv.PROVIDER_ID="password",xv.EMAIL_PASSWORD_SIGN_IN_METHOD="password",xv.EMAIL_LINK_SIGN_IN_METHOD="emailLink";class Ov{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 Dv extends Ov{constructor(){super(...arguments),this.scopes=[]}addScope(e){return this.scopes.includes(e)||this.scopes.push(e),this}getScopes(){return[...this.scopes]}}class Lv extends Dv{static credentialFromJSON(e){var t="string"==typeof e?JSON.parse(e):e;return Sm("providerId"in t&&"signInMethod"in t,"argument-error"),Av._fromParams(t)}credential(e){return this._credential(Object.assign(Object.assign({},e),{nonce:e.rawNonce}))}_credential(e){return Sm(e.idToken||e.accessToken,"argument-error"),Av._fromParams(Object.assign(Object.assign({},e),{providerId:this.providerId,signInMethod:this.providerId}))}static credentialFromResult(e){return Lv.oauthCredentialFromTaggedObject(e)}static credentialFromError(e){return Lv.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 Lv(o)._credential({idToken:t,accessToken:n,nonce:s,pendingToken:i})}catch(e){return null}}}class Mv extends Dv{constructor(){super("facebook.com")}static credential(e){return Av._fromParams({providerId:Mv.PROVIDER_ID,signInMethod:Mv.FACEBOOK_SIGN_IN_METHOD,accessToken:e})}static credentialFromResult(e){return Mv.credentialFromTaggedObject(e)}static credentialFromError(e){return Mv.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!(e&&"oauthAccessToken"in e))return null;if(!e.oauthAccessToken)return null;try{return Mv.credential(e.oauthAccessToken)}catch(e){return null}}}Mv.FACEBOOK_SIGN_IN_METHOD="facebook.com",Mv.PROVIDER_ID="facebook.com";class Fv extends Dv{constructor(){super("google.com"),this.addScope("profile")}static credential(e,t){return Av._fromParams({providerId:Fv.PROVIDER_ID,signInMethod:Fv.GOOGLE_SIGN_IN_METHOD,idToken:e,accessToken:t})}static credentialFromResult(e){return Fv.credentialFromTaggedObject(e)}static credentialFromError(e){return Fv.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;var{oauthIdToken:t,oauthAccessToken:n}=e;if(!t&&!n)return null;try{return Fv.credential(t,n)}catch(e){return null}}}Fv.GOOGLE_SIGN_IN_METHOD="google.com",Fv.PROVIDER_ID="google.com";class Uv extends Dv{constructor(){super("github.com")}static credential(e){return Av._fromParams({providerId:Uv.PROVIDER_ID,signInMethod:Uv.GITHUB_SIGN_IN_METHOD,accessToken:e})}static credentialFromResult(e){return Uv.credentialFromTaggedObject(e)}static credentialFromError(e){return Uv.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!(e&&"oauthAccessToken"in e))return null;if(!e.oauthAccessToken)return null;try{return Uv.credential(e.oauthAccessToken)}catch(e){return null}}}Uv.GITHUB_SIGN_IN_METHOD="github.com",Uv.PROVIDER_ID="github.com";class jv extends Iv{constructor(e,t){super(e,e),this.pendingToken=t}_getIdTokenResponse(e){return Cv(e,this.buildRequest())}_linkToIdToken(e,t){const n=this.buildRequest();return n.idToken=t,Cv(e,n)}_getReauthenticationResolver(e){const t=this.buildRequest();return t.autoCreate=!1,Cv(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 jv(t,r):null}static _create(e,t){return new jv(e,t)}buildRequest(){return{requestUri:"http://localhost",returnSecureToken:!0,pendingToken:this.pendingToken}}}class qv extends Ov{constructor(e){Sm(e.startsWith("saml."),"argument-error"),super(e)}static credentialFromResult(e){return qv.samlCredentialFromTaggedObject(e)}static credentialFromError(e){return qv.samlCredentialFromTaggedObject(e.customData||{})}static credentialFromJSON(e){var t=jv.fromJSON(e);return Sm(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 jv._create(n,t)}catch(e){return null}}}class Vv extends Dv{constructor(){super("twitter.com")}static credential(e,t){return Av._fromParams({providerId:Vv.PROVIDER_ID,signInMethod:Vv.TWITTER_SIGN_IN_METHOD,oauthToken:e,oauthTokenSecret:t})}static credentialFromResult(e){return Vv.credentialFromTaggedObject(e)}static credentialFromError(e){return Vv.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;var{oauthAccessToken:t,oauthTokenSecret:n}=e;if(!t||!n)return null;try{return Vv.credential(t,n)}catch(e){return null}}}async function Bv(e,t){return Vm(e,"POST","/v1/accounts:signUp",Um(e,t))}Vv.TWITTER_SIGN_IN_METHOD="twitter.com",Vv.PROVIDER_ID="twitter.com";class $v{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 ev._fromIdTokenResponse(e,n,r),s=Kv(n);return new $v({user:i,providerId:s,_tokenResponse:n,operationType:t})}static async _forOperation(e,t,n){await e._updateTokensIfNecessary(n,!0);var r=Kv(n);return new $v({user:e,providerId:r,_tokenResponse:n,operationType:t})}}function Kv(e){return e.providerId||("phoneNumber"in e?"phone":null)}class zv extends gd{constructor(e,t,n,r){var i;super(t.code,t.message),this.operationType=n,this.user=r,Object.setPrototypeOf(this,zv.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 zv(e,t,n,r)}}function Wv(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 zv._fromErrorAndOperation(t,e,n,r);throw e})}function Hv(e){return new Set(e.map(({providerId:e})=>e).filter(e=>!!e))}async function Gv(e,t){const n=Kd(e);await Yv(!0,n,t);var r=(e=n.auth,t={idToken:await n.getIdToken(),deleteProvider:[t]},await jm(e,"POST","/v1/accounts:update",t))["providerUserInfo"];const i=Hv(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 Qv(e,t,n=!1){var r=await Gm(e,t._linkToIdToken(e.auth,await e.getIdToken()),n);return $v._forOperation(e,"link",r)}async function Yv(e,t,n){await Jm(t);const r=Hv(t.providerData);var i=!1===e?"provider-already-linked":"no-such-provider";Sm(r.has(n)===e,t.auth,i)}async function Jv(e,t,n=!1){var r=e["auth"],i="reauthenticate";try{var s=await Gm(e,Wv(r,i,t,e),n);Sm(s.idToken,r,"internal-error");var o=Hm(s.idToken);Sm(o,r,"internal-error");var a=o["sub"];return Sm(e.uid===a,r,"user-mismatch"),$v._forOperation(e,i,s)}catch(e){throw"auth/user-not-found"===(null==e?void 0:e.code)&&wm(r,"user-mismatch"),e}}async function Xv(e,t,n=!1){var r=await Wv(e,"signIn",t),r=await $v._fromIdTokenResponse(e,"signIn",r);return n||await e._updateCurrentUser(r.user),r}async function Zv(e,t){return Xv(vv(e),t)}async function ey(e,t){var n=Kd(e);return await Yv(!1,n,t.providerId),Qv(n,t)}async function ty(e,t){return Jv(Kd(e),t)}async function ny(e,t){const n=vv(e);var r=await Vm(n,"POST","/v1/accounts:signInWithCustomToken",Um(n,{token:t,returnSecureToken:!0})),r=await $v._fromIdTokenResponse(n,"signIn",r);return await n._updateCurrentUser(r.user),r}class ry{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?iy._fromServerResponse(e,t):wm(e,"internal-error")}}class iy extends ry{constructor(e){super("phone",e),this.phoneNumber=e.phoneInfo}static _fromServerResponse(e,t){return new iy(t)}}function sy(e,t,n){var r;Sm(0<(null===(r=n.url)||void 0===r?void 0:r.length),e,"invalid-continue-uri"),Sm(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&&(Sm(0<n.iOS.bundleId.length,e,"missing-ios-bundle-id"),t.iOSBundleId=n.iOS.bundleId),n.android&&(Sm(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 oy(e,t,n){var r=Kd(e),i={requestType:"PASSWORD_RESET",email:t};n&&sy(r,i,n),await Sv(r,i)}async function ay(e,t){await jm(e=Kd(e),"POST","/v1/accounts:update",Um(e,{oobCode:t}))}async function cy(e,t){var n=Kd(e),r=await Tv(n,{oobCode:t}),i=r.requestType;switch(Sm(i,n,"internal-error"),i){case"EMAIL_SIGNIN":break;case"VERIFY_AND_CHANGE_EMAIL":Sm(r.newEmail,n,"internal-error");break;case"REVERT_SECOND_FACTOR_ADDITION":Sm(r.mfaInfo,n,"internal-error");default:Sm(r.email,n,"internal-error")}let s=null;return r.mfaInfo&&(s=ry._fromServerResponse(vv(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 ly(e,t,n){var r=Kd(e),i={requestType:"EMAIL_SIGNIN",email:t};Sm(n.handleCodeInApp,r,"argument-error"),n&&sy(r,i,n),await Sv(r,i)}async function uy(e,t){var n=Pm()?Rm():"http://localhost",n=(await jm(e=Kd(e),"POST","/v1/accounts:createAuthUri",Um(e,{identifier:t,continueUri:n})))["signinMethods"];return n||[]}async function hy(e,t){var n=Kd(e),r={requestType:"VERIFY_EMAIL",idToken:await e.getIdToken()};t&&sy(n.auth,r,t);var r=(await Sv(n.auth,r))["email"];r!==e.email&&await e.reload()}async function dy(e,t,n){var r=Kd(e),i={requestType:"VERIFY_AND_CHANGE_EMAIL",idToken:await e.getIdToken(),newEmail:t};n&&sy(r.auth,i,n);var i=(await Sv(r.auth,i))["email"];i!==e.email&&await e.reload()}async function fy(e,{displayName:t,photoURL:n}){if(void 0!==t||void 0!==n){const i=Kd(e);var r=await i.getIdToken(),r=await Gm(i,async function(e,t){return jm(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 py(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 Gm(e,Ev(r,i));await e._updateTokensIfNecessary(r,!0)}class gy{constructor(e,t,n={}){this.isNewUser=e,this.providerId=t,this.profile=n}}class my extends gy{constructor(e,t,n,r){super(e,t,n),this.username=r}}class vy extends gy{constructor(e,t){super(e,"facebook.com",t)}}class yy extends my{constructor(e,t){super(e,"github.com",t,"string"==typeof(null==t?void 0:t.login)?null==t?void 0:t.login:null)}}class _y extends gy{constructor(e,t){super(e,"google.com",t)}}class wy extends my{constructor(e,t,n){super(e,"twitter.com",t,n)}}function by(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=Hm(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 gy(r,i)}}if(!t)return null;switch(t){case"facebook.com":return new vy(r,n);case"github.com":return new yy(r,n);case"google.com":return new _y(r,n);case"twitter.com":return new wy(r,n,e.screenName||null);case"custom":case"anonymous":return new gy(r,null);default:return new gy(r,t,n)}}(n)}class Iy{constructor(e,t){this.type=e,this.credential=t}static _fromIdtoken(e){return new Iy("enroll",e)}static _fromMfaPendingCredential(e){return new Iy("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 Iy._fromMfaPendingCredential(e.multiFactorSession.pendingCredential);if(null!==(t=e.multiFactorSession)&&void 0!==t&&t.idToken)return Iy._fromIdtoken(e.multiFactorSession.idToken)}return null}}class Ty{constructor(e,t,n){this.session=e,this.hints=t,this.signInResolver=n}static _fromError(e,i){const s=vv(e),o=i.customData._serverResponse;var t=(o.mfaInfo||[]).map(e=>ry._fromServerResponse(s,e));Sm(o.mfaPendingCredential,s,"internal-error");const a=Iy._fromMfaPendingCredential(o.mfaPendingCredential);return new Ty(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 $v._fromIdTokenResponse(s,i.operationType,n);return await s._updateCurrentUser(r.user),r;case"reauthenticate":return Sm(i.user,s,"internal-error"),$v._forOperation(i.user,i.operationType,n);default:wm(s,"internal-error")}})}async resolveSignIn(e){return this.signInResolver(e)}}class Ey{constructor(t){this.user=t,this.enrolledFactors=[],t._onReload(e=>{e.mfaInfo&&(this.enrolledFactors=e.mfaInfo.map(e=>ry._fromServerResponse(t.auth,e)))})}static _fromUser(e){return new Ey(e)}async getSession(){return Iy._fromIdtoken(await this.user.getIdToken())}async enroll(e,t){const n=e;var r=await this.getSession(),r=await Gm(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 Gm(this.user,(n=this.user.auth,e={idToken:r,mfaEnrollmentId:t},jm(n,"POST","/v2/accounts/mfaEnrollment:withdraw",Um(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 Sy=new WeakMap;const ky="__sak";class Cy{constructor(e,t){this.storageRetriever=e,this.type=t}_isAvailable(){try{return this.storage?(this.storage.setItem(ky,"1"),this.storage.removeItem(ky),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 Ay extends Cy{constructor(){var e;super(()=>window.localStorage,"LOCAL"),this.boundEventHandler=(e,t)=>this.onStorageEvent(e,t),this.listeners={},this.localCache={},this.pollTimer=null,this.safariLocalStorageNotSynced=(av(e=sd())||fv(e))&&function(){try{return!(!window||window===window.top)}catch(e){return!1}}(),this.fallbackToPolling=pv(),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]}}Ay.type="LOCAL";const Ny=Ay;class Ry extends Cy{constructor(){super(()=>window.sessionStorage,"SESSION")}_addListener(e,t){}_removeListener(e,t){}}Ry.type="SESSION";const Py=Ry;class xy{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 xy(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 Oy(e="",t=10){let n="";for(let r=0;r<t;r++)n+=Math.floor(10*Math.random());return e+n}xy.receivers=[];class Dy{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=Oy("",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 Ly(){return window}function My(){return void 0!==Ly().WorkerGlobalScope&&"function"==typeof Ly().importScripts}const Fy="firebaseLocalStorageDb",Uy="firebaseLocalStorage",jy="fbase_key";class qy{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 Vy(e,t){return e.transaction([Uy],t?"readwrite":"readonly").objectStore(Uy)}function By(){const r=indexedDB.open(Fy,1);return new Promise((n,t)=>{r.addEventListener("error",()=>{t(r.error)}),r.addEventListener("upgradeneeded",()=>{const e=r.result;try{e.createObjectStore(Uy,{keyPath:jy})}catch(e){t(e)}}),r.addEventListener("success",async()=>{const e=r.result;var t;e.objectStoreNames.contains(Uy)?n(e):(e.close(),t=indexedDB.deleteDatabase(Fy),await new qy(t).toPromise(),n(await By()))})})}async function $y(e,t,n){var r=Vy(e,!0).put({fbase_key:t,value:n});return new qy(r).toPromise()}function Ky(e,t){var n=Vy(e,!0).delete(t);return new qy(n).toPromise()}class zy{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 By(),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 My()?this.initializeReceiver():this.initializeSender()}async initializeReceiver(){this.receiver=xy._getInstance(My()?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 Dy(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 By();return await $y(e,ky,"1"),await Ky(e,ky),!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=>$y(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=Vy(e,!1).get(t);return void 0===(n=await new qy(n).toPromise())?null:n.value}(e,t));return this.localCache[t]=e}async _remove(t){return this._withPendingWrite(async()=>(await this._withRetries(e=>Ky(e,t)),delete this.localCache[t],this.notifyServiceWorker(t)))}async _poll(){var e,t,n=await this._withRetries(e=>{var t=Vy(e,!1).getAll();return new qy(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()}}zy.type="LOCAL";const Wy=zy;function Hy(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=bm("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 Gy(e){return`__${e}${Math.floor(1e6*Math.random())}`}class Qy{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 Yy(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 Yy{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;Sm(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 Jy=Gy("rcb"),Xy=new Om(3e4,6e4);class Zy{constructor(){this.hostLanguage="",this.counter=0,this.librarySeparatelyLoaded=!!Ly().grecaptcha}load(s,o=""){var e;return Sm((e=o).length<=6&&/^\s*[a-zA-Z0-9\-]*\s*$/.test(e),s,"argument-error"),this.shouldResolveImmediately(o)?Promise.resolve(Ly().grecaptcha):new Promise((t,n)=>{const i=Ly().setTimeout(()=>{n(bm(s,"network-request-failed"))},Xy.get());Ly()[Jy]=()=>{Ly().clearTimeout(i),delete Ly()[Jy];const e=Ly().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(bm(s,"internal-error"))},Hy(`https://www.google.com/recaptcha/api.js??${Cd({onload:Jy,render:"explicit",hl:o})}`).catch(()=>{clearTimeout(i),n(bm(s,"internal-error"))})})}clearedOneInstance(){this.counter--}shouldResolveImmediately(e){return!!Ly().grecaptcha&&(e===this.hostLanguage||0<this.counter||this.librarySeparatelyLoaded)}}class e_{async load(e){return new Qy(e)}clearedOneInstance(){}}const t_="recaptcha",n_={theme:"light",type:"image"};class r_{constructor(e,t=Object.assign({},n_),n){this.parameters=t,this.type=t_,this.destroyed=!1,this.widgetId=null,this.tokenChangeListeners=new Set,this.renderPromise=null,this.recaptcha=null,this.auth=vv(n),this.isInvisible="invisible"===this.parameters.size,Sm("undefined"!=typeof document,this.auth,"operation-not-supported-in-this-environment");var r="string"==typeof e?document.getElementById(e):e;Sm(r,this.auth,"argument-error"),this.container=r,this.parameters.callback=this.makeTokenCallback(this.parameters.callback),this._recaptchaLoader=new(this.auth.settings.appVerificationDisabledForTesting?e_:Zy),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(){Sm(!this.parameters.sitekey,this.auth,"argument-error"),Sm(this.isInvisible||!this.container.hasChildNodes(),this.auth,"argument-error"),Sm("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=Ly()[n];"function"==typeof e&&e(t)}}}assertNotDestroyed(){Sm(!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(){Sm(Pm()&&!My(),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 jm(this.auth,"GET","/v1/recaptchaParams")).recaptchaSiteKey||"");Sm(e,this.auth,"internal-error"),this.parameters.sitekey=e}getAssertedRecaptcha(){return Sm(this.recaptcha,this.auth,"internal-error"),this.recaptcha}}class i_{constructor(e,t){this.verificationId=e,this.onConfirmation=t}confirm(e){var t=Rv._fromVerification(this.verificationId,e);return this.onConfirmation(t)}}async function s_(t,n,r){var i,s,o,a,c,l,u=await r.verify();try{Sm("string"==typeof u,t,"argument-error"),Sm(r.type===t_,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 Sm("enroll"===h.type,t,"internal-error"),(c=t,l={idToken:h.credential,phoneEnrollmentInfo:{phoneNumber:e.phoneNumber,recaptchaToken:u}},await jm(c,"POST","/v2/accounts/mfaEnrollment:start",Um(c,l))).phoneSessionInfo.sessionInfo;Sm("signin"===h.type,t,"internal-error");var d=(null===(i=e.multiFactorHint)||void 0===i?void 0:i.uid)||e.multiFactorUid;return Sm(d,t,"missing-multi-factor-info"),(a={mfaPendingCredential:h.credential,mfaEnrollmentId:d,phoneSignInInfo:{recaptchaToken:u}},await jm(t,"POST","/v2/accounts/mfaSignIn:start",Um(t,a))).phoneResponseInfo.sessionInfo}var f=(s=t,o={phoneNumber:e.phoneNumber,recaptchaToken:u},await jm(s,"POST","/v1/accounts:sendVerificationCode",Um(s,o)))["sessionInfo"];return f}finally{r._reset()}}class o_{constructor(e){this.providerId=o_.PROVIDER_ID,this.auth=vv(e)}verifyPhoneNumber(e,t){return s_(this.auth,e,Kd(t))}static credential(e,t){return Rv._fromVerification(e,t)}static credentialFromResult(e){var t=e;return o_.credentialFromTaggedObject(t)}static credentialFromError(e){return o_.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;var{phoneNumber:t,temporaryProof:n}=e;return t&&n?Rv._fromTokenResponse(t,n):null}}function a_(e,t){return t?Nm(t):(Sm(e._popupRedirectResolver,e,"argument-error"),e._popupRedirectResolver)}o_.PROVIDER_ID="phone",o_.PHONE_SIGN_IN_METHOD="phone";class c_ extends Iv{constructor(e){super("custom","custom"),this.params=e}_getIdTokenResponse(e){return Cv(e,this._buildIdpRequest())}_linkToIdToken(e,t){return Cv(e,this._buildIdpRequest(t))}_getReauthenticationResolver(e){return Cv(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 l_(e){return Xv(e.auth,new c_(e),e.bypassAuthState)}function u_(e){var{auth:t,user:n}=e;return Sm(n,t,"internal-error"),Jv(n,new c_(e),e.bypassAuthState)}async function h_(e){var{auth:t,user:n}=e;return Sm(n,t,"internal-error"),Qv(n,new c_(e),e.bypassAuthState)}class d_{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 l_;case"linkViaPopup":case"linkViaRedirect":return h_;case"reauthViaPopup":case"reauthViaRedirect":return u_;default:wm(this.auth,"internal-error")}}resolve(e){Cm(this.pendingPromise,"Pending promise was never set"),this.pendingPromise.resolve(e),this.unregisterAndCleanUp()}reject(e){Cm(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 f_=new Om(2e3,1e4);class p_ extends d_{constructor(e,t,n,r,i){super(e,t,r,i),this.provider=n,this.authWindow=null,this.pollId=null,p_.currentPopupAction&&p_.currentPopupAction.cancel(),p_.currentPopupAction=this}async executeNotNull(){var e=await this.execute();return Sm(e,this.auth,"internal-error"),e}async onExecution(){Cm(1===this.filter.length,"Popup operations only handle one event");var e=Oy();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(bm(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(bm(this.auth,"cancelled-popup-request"))}cleanUp(){this.authWindow&&this.authWindow.close(),this.pollId&&window.clearTimeout(this.pollId),this.authWindow=null,this.pollId=null,p_.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(bm(this.auth,"popup-closed-by-user"))},2e3):this.pollId=window.setTimeout(t,f_.get())};t()}}p_.currentPopupAction=null;const g_="pendingRedirect",m_=new Map;class v_ extends d_{constructor(e,t,n=!1){super(e,["signInViaRedirect","linkViaRedirect","reauthViaRedirect","unknown"],t,void 0,n),this.eventId=null}async execute(){let t=m_.get(this.auth._key());if(!t){try{const e=await async function(e,t){const n=w_(t),r=__(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)}m_.set(this.auth._key(),t)}return this.bypassAuthState||m_.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 y_(e,t){return __(e)._set(w_(t),"true")}function __(e){return Nm(e._redirectPersistence)}function w_(e){return rv(g_,e.config.apiKey,e.name)}function b_(e,t,n){return async function(e,t,n){var r=vv(e);Tm(e,t,Ov);const i=a_(r,n);return await y_(i,r),i._openRedirect(r,t,"signInViaRedirect")}(e,t,n)}function I_(e,t,n){return async function(e,t,n){var r=Kd(e);Tm(r.auth,t,Ov);const i=a_(r.auth,n);await y_(i,r.auth);var s=await S_(r);return i._openRedirect(r.auth,t,"reauthViaRedirect",s)}(e,t,n)}function T_(e,t,n){return async function(e,t,n){var r=Kd(e);Tm(r.auth,t,Ov);const i=a_(r.auth,n);await Yv(!1,r,t.providerId),await y_(i,r.auth);var s=await S_(r);return i._openRedirect(r.auth,t,"linkViaRedirect",s)}(e,t,n)}async function E_(e,t,n=!1){const r=vv(e);var i=a_(r,t);const s=new v_(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 S_(e){var t=Oy(`${e.uid}:::`);return e._redirectEventId=t,await e.auth._setRedirectUser(e),await e.auth._persistUserIfCurrent(e),t}class k_{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 A_(e);default:return!1}}(t)||(this.hasHandledPotentialRedirect=!0,n||(this.queuedRedirectEvent=t,n=!0)),n}sendToConsumer(e,t){var n;e.error&&!A_(e)?(n=(null===(n=e.error.code)||void 0===n?void 0:n.split("auth/")[1])||"internal-error",t.onError(bm(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(C_(e))}saveEventToCache(e){this.cachedEventUids.add(C_(e)),this.lastProcessedEventTime=Date.now()}}function C_(e){return[e.type,e.eventId,e.sessionId,e.tenantId].filter(e=>e).join("-")}function A_({type:e,error:t}){return"unknown"===e&&"auth/no-auth-event"===(null==t?void 0:t.code)}async function N_(e,t={}){return jm(e,"GET","/v1/projects",t)}const R_=/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/,P_=/^https?/;async function x_(e){if(!e.config.emulator){var t=(await N_(e))["authorizedDomains"];for(const n of t)try{if(function(e){const t=Rm(),{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(!P_.test(n))return!1;if(R_.test(e))return r===e;const s=e.replace(/\./g,"\\."),o=new RegExp("^(.+\\."+s+"|"+s+")$","i");return o.test(r)}(n))return}catch(e){}wm(e,"unauthorized-domain")}}const O_=new Om(3e4,6e4);function D_(){const t=Ly().___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 L_=null;function M_(e){var i;return L_=L_||(i=e,new Promise((e,t)=>{function n(){D_(),gapi.load("gapi.iframes",{callback:()=>{e(gapi.iframes.getContext())},ontimeout:()=>{D_(),t(bm(i,"network-request-failed"))},timeout:O_.get()})}if(null!==(r=null===(r=Ly().gapi)||void 0===r?void 0:r.iframes)&&void 0!==r&&r.Iframe)e(gapi.iframes.getContext());else{if(null===(r=Ly().gapi)||void 0===r||!r.load){var r=Gy("iframefcb");return Ly()[r]=()=>{gapi.load?n():t(bm(i,"network-request-failed"))},Hy(`https://apis.google.com/js/api.js?onload=${r}`)}n()}}).catch(e=>{throw L_=null,e})),L_}const F_=new Om(5e3,15e3),U_="__/auth/iframe",j_="emulator/auth/iframe",q_={style:{position:"absolute",top:"-100px",width:"1px",height:"1px"},"aria-hidden":"true",tabindex:"-1"},V_=new Map([["identitytoolkit.googleapis.com","p"],["staging-identitytoolkit.sandbox.googleapis.com","s"],["test-identitytoolkit.sandbox.googleapis.com","t"]]);async function B_(o){const e=await M_(o);var t=Ly().gapi;return Sm(t,o,"internal-error"),e.open({where:document.body,url:function(e){var t=e.config;Sm(t.authDomain,e,"auth-domain-config-required");var n=t.emulator?Dm(t,j_):`https://${e.config.authDomain}/${U_}`;const r={apiKey:t.apiKey,appName:e.name,v:mf};(t=V_.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:q_,dontclear:!0},s=>new Promise(async(e,t)=>{await s.restyle({setHideOnLeave:!1});const n=bm(o,"network-request-failed"),r=Ly().setTimeout(()=>{t(n)},F_.get());function i(){Ly().clearTimeout(r),e(s)}s.ping(i).then(i,()=>{t(n)})}))}const $_={location:"yes",resizable:"yes",statusbar:"yes",toolbar:"no"};class K_{constructor(e){this.window=e,this.associatedEvent=null}close(){if(this.window)try{this.window.close()}catch(e){}}}function z_(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({},$_),{width:r.toString(),height:i.toString(),top:s,left:o});s=sd().toLowerCase();n&&(a=cv(s)?"_blank":n),ov(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],fv(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 K_(null);const u=window.open(t||"",a,o);Sm(u,e,"popup-blocked");try{u.focus()}catch(e){}return new K_(u)}const W_="__/auth/handler",H_="emulator/auth/handler";function G_(e,t,n,r,i,s){Sm(e.config.authDomain,e,"auth-domain-config-required"),Sm(e.config.apiKey,e,"invalid-api-key");const o={apiKey:e.config.apiKey,appName:e.name,authType:n,redirectUrl:r,v:mf,eventId:i};if(t instanceof Ov){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 Dv){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?Dm(e,H_):`https://${e.authDomain}/${W_}`}?${Cd(l).slice(1)}`}const Q_="webStorageSupport";const Y_=class{constructor(){this.eventManagers={},this.iframes={},this.originValidationPromises={},this._redirectPersistence=Py,this._completeRedirectFn=E_}async _openPopup(e,t,n,r){var i;return Cm(null===(i=this.eventManagers[e._key()])||void 0===i?void 0:i.manager,"_initialize() not called before _openPopup()"),z_(e,G_(e,t,n,Rm(),r),Oy())}async _openRedirect(e,t,n,r){return await this._originValidation(e),r=G_(e,t,n,Rm(),r),Ly().location.href=r,new Promise(()=>{})}_initialize(e){var t=e._key();if(this.eventManagers[t]){const{manager:r,promise:n}=this.eventManagers[t];return r?Promise.resolve(r):(Cm(n,"If manager is not set, promise should be"),n)}const n=this.initAndGetManager(e);return this.eventManagers[t]={promise:n},n}async initAndGetManager(t){const e=await B_(t),n=new k_(t);return e.register("authEvent",e=>{return Sm(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(Q_,{type:Q_},e=>{var t=null===(t=null==e?void 0:e[0])||void 0===t?void 0:t[Q_];void 0!==t&&r(!!t),wm(n,"internal-error")},gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER)}_originValidation(e){var t=e._key();return this.originValidationPromises[t]||(this.originValidationPromises[t]=x_(e)),this.originValidationPromises[t]}get _shouldInitProactively(){return pv()||av()||fv()}};class J_ 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 km("unexpected MultiFactorSessionType")}}}{constructor(e){super("phone"),this.credential=e}static _fromCredential(e){return new J_(e)}_finalizeEnroll(e,t,n){return e=e,n={idToken:t,displayName:n,phoneVerificationInfo:this.credential._makeVerificationRequest()},jm(e,"POST","/v2/accounts/mfaEnrollment:finalize",Um(e,n))}_finalizeSignIn(e,t){return e=e,t={mfaPendingCredential:t,phoneVerificationInfo:this.credential._makeVerificationRequest()},jm(e,"POST","/v2/accounts/mfaSignIn:finalize",Um(e,t))}}class X_{constructor(){}static assertion(e){return J_._fromCredential(e)}}X_.FACTOR_ID="phone";var Z_,ew="@firebase/auth";class tw{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(){Sm(this.auth._initializationPromise,"dependent-sdk-initialized-before-auth")}updateProactiveRefresh(){0<this.internalListeners.size?this.auth._startProactiveRefresh():this.auth._stopProactiveRefresh()}}function nw(){return window}Z_="Browser",df(new zd("auth",(e,{options:n})=>{var t=e.getProvider("app").getImmediate();const{apiKey:r,authDomain:i}=t.options;return(e=>{Sm(r&&!r.includes(":"),"invalid-api-key",{appName:e.name}),Sm(!(null!==i&&void 0!==i&&i.includes(":")),"argument-error",{appName:e.name});var t={apiKey:r,authDomain:i,clientPlatform:Z_,apiHost:"identitytoolkit.googleapis.com",tokenApiHost:"securetoken.googleapis.com",apiScheme:"https",sdkClientVersion:gv(Z_)},t=new mv(e,t);return function(e,t){const n=(null==t?void 0:t.persistence)||[];var r=(Array.isArray(n)?n:[n]).map(Nm);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()})),df(new zd("auth-internal",e=>{var t=vv(e.getProvider("auth").getImmediate());return e=t,new tw(e)},"PRIVATE").setInstantiationMode("EXPLICIT")),wf(ew,"0.19.3",function(e){switch(e){case"Node":return"node";case"ReactNative":return"rn";case"Worker":return"webworker";case"Cordova":return"cordova";default:return}}(Z_)),wf(ew,"0.19.3","esm2017");async function rw(e,t,n){var r=nw()["BuildInfo"];Cm(t.sessionId,"AuthEvent did not contain a session ID");var i=await async function(e){const t=function(e){if(Cm(/[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 fv()?s.ibi=r.packageName:uv()?s.apn=r.packageName:wm(e,"operation-not-supported-in-this-environment"),r.displayName&&(s.appDisplayName=r.displayName),s.sessionId=i,G_(e,n,t.type,void 0,null!==(i=t.eventId)&&void 0!==i?i:void 0,s)}function iw(r){const i=nw()["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 sw=20;class ow extends k_{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 aw(e,t,n=null){return{type:t,eventId:n,urlResponse:null,sessionId:function(){const e=[],t="1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";for(let r=0;r<sw;r++){var n=Math.floor(Math.random()*t.length);e.push(t.charAt(n))}return e.join("")}(),postBody:null,tenantId:e.tenantId,error:bm(e,"no-auth-event")}}async function cw(e){var t=await uw()._get(hw(e));return t&&await uw()._remove(hw(e)),t}function lw(e,t){var n,r,i;const s=(n=dw(t=t),o=n.link?decodeURIComponent(n.link):void 0,r=dw(o).link,i=n.deep_link_id?decodeURIComponent(n.deep_link_id):void 0,(n=dw(i).link)||i||r||o||t);if(s.includes("/__/auth/callback")){var o=dw(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?bm(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 uw(){return Nm(Ny)}function hw(e){return rv("authEvent",e.config.apiKey,e.name)}function dw(e){if(null==e||!e.includes("?"))return{};const[,...t]=e.split("?");return Ad(t.join("?"))}const fw=class{constructor(){this._redirectPersistence=Py,this._shouldInitProactively=!0,this.eventManagers=new Map,this.originValidationPromises={},this._completeRedirectFn=E_}async _initialize(e){var t=e._key();let n=this.eventManagers.get(t);return n||(n=new ow(e),this.eventManagers.set(t,n),this.attachCallbackListeners(e,n)),n}_openPopup(e){wm(e,"operation-not-supported-in-this-environment")}async _openRedirect(e,t,n,r){var i,s;i=e,a=nw(),Sm("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"}),Sm(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"}),Sm("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"}),Sm("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"}),Sm("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(),m_.clear(),await this._originValidation(e);var a=aw(e,n,r);n=e,r=a,await uw()._set(hw(n),r);a=await iw(await rw(e,a,t));return async function(o,a,c){const l=nw()["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(bm(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),uv()&&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=nw()["BuildInfo"];const n={};fv()?n.iosBundleId=t.packageName:uv()?n.androidPackageName=t.packageName:wm(e,"operation-not-supported-in-this-environment"),await N_(e,n)}(e)),this.originValidationPromises[t]}attachCallbackListeners(r,i){const{universalLinks:e,handleOpenURL:t,BuildInfo:n}=nw(),s=setTimeout(async()=>{await cw(r),i.onEvent(pw())},500),o=async e=>{clearTimeout(s);var t=await cw(r);let n=null;t&&null!=e&&e.url&&(n=lw(t,e.url)),i.onEvent(n||pw())};void 0!==e&&"function"==typeof e.subscribe&&e.subscribe(null,o);const a=t,c=`${n.packageName.toLowerCase()}://`;nw().handleOpenURL=async e=>{if(e.toLowerCase().startsWith(c)&&o({url:e}),"function"==typeof a)try{a(e)}catch(e){console.error(e)}}}};function pw(){return{type:"unknown",eventId:null,sessionId:null,urlResponse:null,postBody:null,tenantId:null,error:bm("no-auth-event")}}var gw;function mw(){var e;return(null===(e=null===self||void 0===self?void 0:self.location)||void 0===e?void 0:e.protocol)||null}function vw(e=sd()){return!("file:"!==mw()&&"ionic:"!==mw()||!e.toLowerCase().match(/iphone|ipad|ipod|android/))}function yw(e=sd()){return ud()&&11===(null===document||void 0===document?void 0:document.documentMode)||([e=sd()]=[e],/Edge\/\d+/.test(e))}function _w(){try{const t=self.localStorage;var e=Oy();if(t)return t.setItem(e,"1"),t.removeItem(e),!yw()||dd()}catch(e){return ww()&&dd()}return!1}function ww(){return"undefined"!=typeof global&&"WorkerGlobalScope"in global&&"importScripts"in global}function bw(){return("http:"===mw()||"https:"===mw()||cd()||vw())&&!(ld()||ad())&&_w()&&!ww()}function Iw(){return vw()&&"undefined"!=typeof document}const Tw={LOCAL:"local",NONE:"none",SESSION:"session"},Ew=Sm,Sw="persistence";async function kw(e){await e._initializationPromise;const t=Cw();var n=rv(Sw,e.config.apiKey,e.name);null!==t&&void 0!==t&&t.sessionStorage&&t.sessionStorage.setItem(n,e._getPersistence())}function Cw(){return"undefined"!=typeof window?window:null}const Aw=Sm;class Nw{constructor(){this.browserResolver=Nm(Y_),this.cordovaResolver=Nm(fw),this.underlyingResolver=null,this._redirectPersistence=Py,this._completeRedirectFn=E_}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 Iw()||this.browserResolver._shouldInitProactively}get assertedUnderlyingResolver(){return Aw(this.underlyingResolver,"internal-error"),this.underlyingResolver}async selectUnderlyingResolver(){var e;this.underlyingResolver||(e=await(!!Iw()&&new Promise(e=>{const t=setTimeout(()=>{e(!1)},1e3);document.addEventListener("deviceready",()=>{clearTimeout(t),e(!0)})})),this.underlyingResolver=e?this.cordovaResolver:this.browserResolver)}}function Rw(e){return e.unwrap()}function Pw(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 Lw(e,(n=t,i=Kd(e),Sm((o=n).customData.operationType,i,"argument-error"),Sm(null===(r=o.customData._serverResponse)||void 0===r?void 0:r.mfaPendingCredential,i,"argument-error"),Ty._fromError(i,o)))}else if(s){var o=xw(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 xw(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 o_.credentialFromResult(e);const n=t.providerId;if(!n||n===dm.PASSWORD)return null;let r;switch(n){case dm.GOOGLE:r=Fv;break;case dm.FACEBOOK:r=Mv;break;case dm.GITHUB:r=Uv;break;case dm.TWITTER:r=Vv;break;default:var{oauthIdToken:i,oauthAccessToken:s,oauthTokenSecret:o,pendingToken:a,nonce:c}=t;return s||o||i||a?a?n.startsWith("saml.")?jv._create(n,a):Av._fromParams({providerId:n,signInMethod:n,pendingToken:a,idToken:i,accessToken:s}):new Lv(n).credential({idToken:i,accessToken:s,rawNonce:c}):null}return e instanceof gd?r.credentialFromError(e):r.credentialFromResult(e)}function Ow(t,e){return e.catch(e=>{throw e instanceof gd&&Pw(t,e),e}).then(e=>{var t=e.operationType,n=e.user;return{operationType:t,credential:xw(e),additionalUserInfo:by(e),user:Mw.getOrCreate(n)}})}async function Dw(t,e){const n=await e;return{verificationId:n.verificationId,confirm:e=>Ow(t,n.confirm(e))}}class Lw{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 Ow(Rw(this.auth),this.resolver.resolveSignIn(e))}}class Mw{constructor(e){var t;this._delegate=e,this.multiFactor=(t=Kd(e),Sy.has(t)||Sy.set(t,Ey._fromUser(t)),Sy.get(t))}static getOrCreate(e){return Mw.USER_MAP.has(e)||Mw.USER_MAP.set(e,new Mw(e)),Mw.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 Ow(this.auth,ey(this._delegate,e))}async linkWithPhoneNumber(e,t){return Dw(this.auth,async function(e,t,n){const r=Kd(e);await Yv(!1,r,"phone");var i=await s_(r.auth,t,Kd(n));return new i_(i,e=>ey(r,e))}(this._delegate,e,t))}async linkWithPopup(e){return Ow(this.auth,async function(e,t,n){var r=Kd(e);Tm(r.auth,t,Ov);var i=a_(r.auth,n);const s=new p_(r.auth,"linkViaPopup",t,i,r);return s.executeNotNull()}(this._delegate,e,Nw))}async linkWithRedirect(e){return await kw(vv(this.auth)),T_(this._delegate,e,Nw)}reauthenticateAndRetrieveDataWithCredential(e){return this.reauthenticateWithCredential(e)}async reauthenticateWithCredential(e){return Ow(this.auth,ty(this._delegate,e))}reauthenticateWithPhoneNumber(e,t){return Dw(this.auth,async function(e,t,n){const r=Kd(e);var i=await s_(r.auth,t,Kd(n));return new i_(i,e=>ty(r,e))}(this._delegate,e,t))}reauthenticateWithPopup(e){return Ow(this.auth,async function(e,t,n){var r=Kd(e);Tm(r.auth,t,Ov);var i=a_(r.auth,n);const s=new p_(r.auth,"reauthViaPopup",t,i,r);return s.executeNotNull()}(this._delegate,e,Nw))}async reauthenticateWithRedirect(e){return await kw(vv(this.auth)),I_(this._delegate,e,Nw)}sendEmailVerification(e){return hy(this._delegate,e)}async unlink(e){return await Gv(this._delegate,e),this}updateEmail(e){return py(Kd(this._delegate),e,null)}updatePassword(e){return py(Kd(this._delegate),null,e)}updatePhoneNumber(e){return async function(e,t){await Qv(Kd(e),t)}(this._delegate,e)}updateProfile(e){return fy(this._delegate,e)}verifyBeforeUpdateEmail(e,t){return dy(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}}Mw.USER_MAP=new WeakMap;const Fw=Sm;class Uw{constructor(e,t){if(this.app=e,t.isInitialized())return this._delegate=t.getImmediate(),void this.linkUnderlyingAuth();var n=e.options["apiKey"];Fw(n,"invalid-api-key",{appName:e.name});let r=[nv];if("undefined"!=typeof window){r=function(e,t){const n=Cw();if(null===n||void 0===n||!n.sessionStorage)return[];var r=rv(Sw,e,t);switch(n.sessionStorage.getItem(r)){case Tw.NONE:return[nv];case Tw.LOCAL:return[Wy,Py];case Tw.SESSION:return[Py];default:return[]}}(n,e.name);for(const i of[Wy,Ny,Py])r.includes(i)||r.push(i)}Fw(n,"invalid-api-key",{appName:e.name});n="undefined"!=typeof window?Nw:void 0;this._delegate=t.initialize({options:{persistence:r,popupRedirectResolver:n}}),this._delegate._updateErrorMap(gm),this.linkUnderlyingAuth()}get emulatorConfig(){return this._delegate.emulatorConfig}get currentUser(){return this._delegate.currentUser?Mw.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){_v(this._delegate,e,t)}applyActionCode(e){return ay(this._delegate,e)}checkActionCode(e){return cy(this._delegate,e)}confirmPasswordReset(e,t){return async function(e,t,n){await Tv(Kd(e),{oobCode:t,newPassword:n})}(this._delegate,e,t)}async createUserWithEmailAndPassword(e,t){return Ow(this._delegate,async function(e,t,n){const r=vv(e);var i=await Bv(r,{returnSecureToken:!0,email:t,password:n}),i=await $v._fromIdTokenResponse(r,"signIn",i);return await r._updateCurrentUser(i.user),i}(this._delegate,e,t))}fetchProvidersForEmail(e){return this.fetchSignInMethodsForEmail(e)}fetchSignInMethodsForEmail(e){return uy(this._delegate,e)}isSignInWithEmailLink(e){return this._delegate,e=e,"EMAIL_SIGNIN"===(null==(t=Pv.parseLink(e))?void 0:t.operation);var t}async getRedirectResult(){Fw(bw(),this._delegate,"operation-not-supported-in-this-environment");var e,t,n=(e=this._delegate,t=Nw,await vv(e)._initializationPromise,await E_(e,t,!1));return n?Ow(this._delegate,Promise.resolve(n)):{credential:null,user:null}}addFrameworkForLogging(e){vv(this._delegate)._logFramework(e)}onAuthStateChanged(e,t,n){var{next:r,error:i,complete:s}=jw(e,t,n);return this._delegate.onAuthStateChanged(r,i,s)}onIdTokenChanged(e,t,n){var{next:r,error:i,complete:s}=jw(e,t,n);return this._delegate.onIdTokenChanged(r,i,s)}sendSignInLinkToEmail(e,t){return ly(this._delegate,e,t)}sendPasswordResetEmail(e,t){return oy(this._delegate,e,t||void 0)}async setPersistence(e){var t,n;t=this._delegate,n=e,Ew(Object.values(Tw).includes(n),t,"invalid-persistence-type"),ld()?Ew(n!==Tw.SESSION,t,"unsupported-persistence-type"):ad()?Ew(n===Tw.NONE,t,"unsupported-persistence-type"):ww()?Ew(n===Tw.NONE||n===Tw.LOCAL&&dd(),t,"unsupported-persistence-type"):Ew(n===Tw.NONE||_w(),t,"unsupported-persistence-type");let r;switch(e){case Tw.SESSION:r=Py;break;case Tw.LOCAL:var i=await Nm(Wy)._isAvailable();r=i?Wy:Ny;break;case Tw.NONE:r=nv;break;default:return wm("argument-error",{appName:this._delegate.name})}return this._delegate.setPersistence(r)}signInAndRetrieveDataWithCredential(e){return this.signInWithCredential(e)}signInAnonymously(){return Ow(this._delegate,async function(e){const t=vv(e);if(await t._initializationPromise,null!==(n=t.currentUser)&&void 0!==n&&n.isAnonymous)return new $v({user:t.currentUser,providerId:null,operationType:"signIn"});var n=await Bv(t,{returnSecureToken:!0}),n=await $v._fromIdTokenResponse(t,"signIn",n,!0);return await t._updateCurrentUser(n.user),n}(this._delegate))}signInWithCredential(e){return Ow(this._delegate,Zv(this._delegate,e))}signInWithCustomToken(e){return Ow(this._delegate,ny(this._delegate,e))}signInWithEmailAndPassword(e,t){return Ow(this._delegate,(n=this._delegate,e=e,t=t,Zv(Kd(n),xv.credential(e,t))));var n}signInWithEmailLink(e,t){return Ow(this._delegate,async function(e,t,n){var r=Kd(e),i=xv.credentialWithLink(t,n||Rm());return Sm(i._tenantId===(r.tenantId||null),r,"tenant-id-mismatch"),Zv(r,i)}(this._delegate,e,t))}signInWithPhoneNumber(e,t){return Dw(this._delegate,async function(e,t,n){const r=vv(e);var i=await s_(r,t,Kd(n));return new i_(i,e=>Zv(r,e))}(this._delegate,e,t))}async signInWithPopup(e){return Fw(bw(),this._delegate,"operation-not-supported-in-this-environment"),Ow(this._delegate,async function(e,t,n){var r=vv(e);Tm(e,t,Ov);var i=a_(r,n);const s=new p_(r,"signInViaPopup",t,i);return s.executeNotNull()}(this._delegate,e,Nw))}async signInWithRedirect(e){return Fw(bw(),this._delegate,"operation-not-supported-in-this-environment"),await kw(this._delegate),b_(this._delegate,e,Nw)}updateCurrentUser(e){return this._delegate.updateCurrentUser(e)}verifyPasswordResetCode(e){return async function(e,t){var n=(await cy(Kd(e),t))["data"];return n.email}(this._delegate,e)}unwrap(){return this._delegate}_delete(){return this._delegate._delete()}linkUnderlyingAuth(){this._delegate.wrapped=()=>this}}function jw(e,t,n){let r=e;"function"!=typeof e&&({next:r,error:t,complete:n}=e);const i=r;return{next:e=>i(e&&Mw.getOrCreate(e)),error:t,complete:n}}Uw.Persistence=Tw;class qw{constructor(){this.providerId="phone",this._delegate=new o_(Rw(Af.auth()))}static credential(e,t){return o_.credential(e,t)}verifyPhoneNumber(e,t){return this._delegate.verifyPhoneNumber(e,t)}unwrap(){return this._delegate}}qw.PHONE_SIGN_IN_METHOD=o_.PHONE_SIGN_IN_METHOD,qw.PROVIDER_ID=o_.PROVIDER_ID;const Vw=Sm;class Bw{constructor(e,t,n=Af.app()){var r;Vw(null===(r=n.options)||void 0===r?void 0:r.apiKey,"invalid-api-key",{appName:n.name}),this._delegate=new r_(e,t,n.auth()),this.type=this._delegate.type}clear(){this._delegate.clear()}render(){return this._delegate.render()}verify(){return this._delegate.verify()}}(gw=Af).INTERNAL.registerComponent(new zd("auth-compat",e=>{var t=e.getProvider("app-compat").getImmediate(),n=e.getProvider("auth");return new Uw(t,n)},"PUBLIC").setServiceProps({ActionCodeInfo:{Operation:{EMAIL_SIGNIN:fm.EMAIL_SIGNIN,PASSWORD_RESET:fm.PASSWORD_RESET,RECOVER_EMAIL:fm.RECOVER_EMAIL,REVERT_SECOND_FACTOR_ADDITION:fm.REVERT_SECOND_FACTOR_ADDITION,VERIFY_AND_CHANGE_EMAIL:fm.VERIFY_AND_CHANGE_EMAIL,VERIFY_EMAIL:fm.VERIFY_EMAIL}},EmailAuthProvider:xv,FacebookAuthProvider:Mv,GithubAuthProvider:Uv,GoogleAuthProvider:Fv,OAuthProvider:Lv,SAMLAuthProvider:qv,PhoneAuthProvider:qw,PhoneMultiFactorGenerator:X_,RecaptchaVerifier:Bw,TwitterAuthProvider:Vv,Auth:Uw,AuthCredential:Iv,Error:gd}).setInstantiationMode("LAZY").setMultipleInstances(!1)),gw.registerVersion("@firebase/auth-compat","0.2.3");const $w="@firebase/database";let Kw="";function zw(e){Kw=e}class Ww{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 Hw{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 Gw,Qw,Yw,Jw,Xw,Zw,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 Ww(t)}}catch(e){}return new Hw};function eb(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++,Jh(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 tb=yt("localStorage"),nb=yt("sessionStorage"),rb=new ef("@firebase/database"),ib=function(){let e=1;return function(){return e++}}(),sb=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+=sb.apply(null,n):t+="object"==typeof n?_d(n):n,t+=" "}return t};let ob=null,ab=!0;function cb(t){return function(...e){gb(t,...e)}}function lb(...e){var t="FIREBASE INTERNAL ERROR: "+sb(...e);rb.error(t)}function ub(e,t){return e===t?0:e<t?-1:1}function hb(e,t){if(t&&e in t)return t[e];throw new Error("Missing required key ("+e+") in object: "+_d(t))}function db(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+=db(e[t[i]]);return n+="}",n}function fb(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 pb=function(e,t){Jh(!t||!0===e||!1===e,"Can't turn on custom loggers persistently."),!0===e?(rb.logLevel=Kh.VERBOSE,ob=rb.log.bind(rb),t&&nb.set("logging_enabled",!0)):"function"==typeof e?ob=e:(ob=null,nb.remove("logging_enabled"))},gb=function(...e){var t;!0===ab&&(ab=!1,null===ob&&!0===nb.get("logging_enabled")&&pb(!0)),ob&&(t=sb.apply(null,e),ob(t))},mb=function(...e){var t=`FIREBASE FATAL ERROR: ${sb(...e)}`;throw rb.error(t),new Error(t)},vb=function(...e){var t="FIREBASE WARNING: "+sb(...e);rb.warn(t)},yb=function(){"undefined"!=typeof window&&window.location&&window.location.protocol&&-1!==window.location.protocol.indexOf("https:")&&vb("Insecure Firebase access from a secure page. Please use https in calls to new Firebase().")},_b=function(e){return"number"==typeof e&&(e!=e||e===Number.POSITIVE_INFINITY||e===Number.NEGATIVE_INFINITY)},wb="[MIN_NAME]",bb="[MAX_NAME]",Ib=function(e,t){if(e===t)return 0;if(e===wb||t===bb)return-1;if(t===wb||e===bb)return 1;var n=Nb(e),r=Nb(t);return null!==n?null!==r?n-r==0?e.length-t.length:n-r:-1:null===r&&e<t?-1:1};function Tb(e,t){for(const n in e)e.hasOwnProperty(n)&&t(n,e[n])}function Eb(e){Jh(!_b(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 Sb(e,t){const n=setTimeout(e,t);return"object"==typeof n&&n.unref&&n.unref(),n}const kb=new RegExp("^-?(0*)\\d{1,10}$"),Cb=-2147483648,Ab=2147483647,Nb=function(e){if(kb.test(e)){var t=Number(e);if(t>=Cb&&t<=Ab)return t}return null},Rb=function(e){try{e()}catch(t){setTimeout(()=>{var e=t.stack||"";throw vb("Exception was thrown by user callback.",e),t},Math.floor(0))}};class Pb{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(){vb(`Provided AppCheck credentials for the app named "${this.appName_}" `+"are invalid. This usually indicates your app was not initialized correctly.")}}class xb{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?(gb("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/.',vb(e)}}class Ob{constructor(e){this.accessToken=e}getToken(e){return Promise.resolve({accessToken:this.accessToken})}addTokenChangeListener(e){e(this.accessToken)}removeTokenChangeListener(e){}notifyForInvalidToken(){}}Ob.OWNER="owner";const Db=/(console\.firebase|firebase-console-\w+\.corp|firebase\.corp)\.google\.com/,Lb="websocket",Mb="long_polling";class Fb{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=tb.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()&&tb.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 Ub(e,t,n){Jh("string"==typeof t,"typeof type must == string"),Jh("object"==typeof n,"typeof params must == object");let r;if(t===Lb)r=(e.secure?"wss://":"ws://")+e.internalHost+"/.ws?";else{if(t!==Mb)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 Tb(n,(e,t)=>{i.push(e+"="+t)}),r+i.join("&")}class jb{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 qb={},Vb={};function Bb(e){var t=e.toString();return qb[t]||(qb[t]=new jb),qb[t]}class $b{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]&&Rb(()=>{this.onMessage_(n[e])});if(this.currentResponseNum===this.closeAfterResponse){this.onClose&&(this.onClose(),this.onClose=null);break}this.currentResponseNum++}}}class Kb{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_=cb(e),this.stats_=Bb(t),this.urlFn=e=>(this.appCheckToken&&(e.ac=this.appCheckToken),Ub(t,Mb,e))}open(e,t){this.curSegmentNum=0,this.onDisconnect_=t,this.myPacketOrderer=new $b(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 zb((...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&&Db.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(){Kb.forceAllow_=!0}static forceDisallow(){Kb.forceDisallow_=!0}static isAvailable(){return!!Kb.forceAllow_||!(Kb.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=fb(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 zb{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=ib(),window["pLPCommand"+this.uniqueCallbackIdentifier]=t,window["pRTLPCB"+this.uniqueCallbackIdentifier]=n,this.myIFrame=zb.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){gb("frame writing exception"),e.stack&&gb(e.stack),gb(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||gb("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=()=>{gb("Long-poll script failed to load: "+e),this.sendNewPolls=!1,this.close()},this.myIFrame.doc.body.appendChild(t)}catch(e){}},Math.floor(1))}}let Wb=null;"undefined"!=typeof MozWebSocket?Wb=MozWebSocket:"undefined"!=typeof WebSocket&&(Wb=WebSocket);class Hb{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_=cb(this.connId),this.stats_=Bb(t),this.connURL=Hb.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&&Db.test(location.hostname)&&(i.r="f"),t&&(i.s=t),n&&(i.ls=n),r&&(i.ac=r),Ub(e,Lb,i)}open(e,t){this.onDisconnect=t,this.onMessage=e,this.log_("Websocket connecting to "+this.connURL),this.everConnected_=!1,tb.set("previous_websocket_failure",!0);try{hd()||(n={headers:{"X-Firebase-GMPID":this.applicationId||"","X-Firebase-AppCheck":this.appCheckToken||""}},this.mySock=new Wb(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(){Hb.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!==Wb&&!Hb.forceDisallow_}static previouslyFailed(){return tb.isInMemoryStorage||!0===tb.get("previous_websocket_failure")}markConnectionHealthy(){tb.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(Jh(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=fb(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)}}}Hb.responsesRequiredToBeHealthy=2,Hb.healthyTimeout=3e4;class Gb{constructor(e){this.initTransports_(e)}static get ALL_TRANSPORTS(){return[Kb,Hb]}initTransports_(e){var t=Hb&&Hb.isAvailable();let n=t&&!Hb.previouslyFailed();if(e.webSocketOnly&&(t||vb("wss:// URL used, but browser isn't known to support websockets. Trying anyway."),n=!0),n)this.transports_=[Hb];else{const r=this.transports_=[];for(const i of Gb.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 Qb{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_=cb("c:"+this.id+":"),this.transportManager_=new Gb(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_=Sb(()=>{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=hb("t",e),n=hb("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=hb("t",e),n=hb("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=hb("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?lb("Server Error: "+n):"o"===t?(this.log_("got pong on primary."),this.onPrimaryResponse_(),this.sendPingOnPrimaryIfNecessary_()):lb("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&&vb("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),Sb(()=>{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):Sb(()=>{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()&&(tb.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 Yb{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 Jb{constructor(e){this.allowedEvents_=e,this.listeners_={},Jh(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){Jh(this.allowedEvents_.find(e=>e===t),"Unknown event: "+t)}}class Xb extends Jb{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 Xb}getInitialEvent(e){return Jh("online"===e,"Unknown event type: "+e),[this.online_]}currentlyOnline(){return this.online_}}class Zb{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 eI(){return new Zb("")}function tI(e){return e.pieceNum_>=e.pieces_.length?null:e.pieces_[e.pieceNum_]}function nI(e){return e.pieces_.length-e.pieceNum_}function rI(e){let t=e.pieceNum_;return t<e.pieces_.length&&t++,new Zb(e.pieces_,t)}function iI(e){return e.pieceNum_<e.pieces_.length?e.pieces_[e.pieces_.length-1]:null}function sI(e,t=0){return e.pieces_.slice(e.pieceNum_+t)}function oI(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 Zb(t,0)}function aI(e,t){const n=[];for(let i=e.pieceNum_;i<e.pieces_.length;i++)n.push(e.pieces_[i]);if(t instanceof Zb)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 Zb(n,0)}function cI(e){return e.pieceNum_>=e.pieces_.length}function lI(e,t){var n=tI(e),r=tI(t);if(null===n)return t;if(n===r)return lI(rI(e),rI(t));throw new Error("INTERNAL ERROR: innerPath ("+t+") is not within outerPath ("+e+")")}function uI(e,t){var n=sI(e,0),r=sI(t,0);for(let s=0;s<n.length&&s<r.length;s++){var i=Ib(n[s],r[s]);if(0!==i)return i}return n.length===r.length?0:n.length<r.length?-1:1}function hI(e,t){if(nI(e)!==nI(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 dI(e,t){let n=e.pieceNum_,r=t.pieceNum_;if(nI(e)>nI(t))return!1;for(;n<e.pieces_.length;){if(e.pieces_[n]!==t.pieces_[r])return!1;++n,++r}return!0}class fI{constructor(e,t){this.errorPrefix_=t,this.parts_=sI(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]);pI(this)}}function pI(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 "+gI(e))}function gI(e){return 0===e.parts_.length?"":"in property '"+e.parts_.join(".")+"'"}class mI extends Jb{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 mI}getInitialEvent(e){return Jh("visible"===e,"Unknown event type: "+e),[this.visible_]}}class vI extends Yb{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=vI.nextPersistentConnectionId_++,this.log_=cb("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");mI.getInstance().on("visible",this.onVisible_,this),-1===e.host.indexOf("fblocal")&&Xb.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)),Jh(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),Jh(e._queryParams.isDefault()||!e._queryParams.loadsAllData(),"listen() called for non-default but complete query"),Jh(!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;vI.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(),vb("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),Jh(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):lb("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){Jh(!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+":"+vI.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){Jh(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?gb("getToken() completed but was canceled"):(gb("getToken() completed. Creating connection."),this.authToken_=c&&c.accessToken,this.appCheckToken_=l&&l.token,n=new Qb(i,this.repoInfo_,this.applicationId_,this.appCheckToken_,this.authToken_,e,r,u,e=>{vb(e+" ("+this.repoInfo_.toString()+")"),this.interrupt("server_kill")},s))}catch(e){this.log_("Failed to get token: "+e),t||(this.repoInfo_.nodeAdmin&&vb(e),o())}}}interrupt(e){gb("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){gb("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=>db(e)).join("$"):"default";const r=this.removeListen_(e,n);r&&r.onComplete&&r.onComplete("permission_denied")}removeListen_(e,t){var n=new Zb(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){gb("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){gb("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."+Kw.replace(/\./g,"-")]=1,od()?e["framework.cordova"]=1:ld()&&(e["framework.reactnative"]=1),this.reportStats(e)}shouldReconnect_(){var e=Xb.getInstance().currentlyOnline();return Td(this.interruptReasons_)&&e}}vI.nextPersistentConnectionId_=0,vI.nextConnectionId_=0;class yI{constructor(e,t){this.name=e,this.node=t}static Wrap(e,t){return new yI(e,t)}}class _I{getCompare(){return this.compare.bind(this)}indexedValueChanged(e,t){var n=new yI(wb,e),r=new yI(wb,t);return 0!==this.compare(n,r)}minPost(){return yI.MIN}}let wI;class bI extends _I{static get __EMPTY_NODE(){return wI}static set __EMPTY_NODE(e){wI=e}compare(e,t){return Ib(e.name,t.name)}isDefinedOn(e){throw Xh("KeyIndex.isDefinedOn not expected to be called.")}indexedValueChanged(e,t){return!1}minPost(){return yI.MIN}maxPost(){return new yI(bb,wI)}makePost(e,t){return Jh("string"==typeof e,"KeyIndex indexValue must always be a string."),new yI(e,wI)}toString(){return".key"}}const II=new bI;class TI{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 EI{constructor(e,t,n,r,i){this.key=e,this.value=t,this.color=null!=n?n:EI.RED,this.left=null!=r?r:SI.EMPTY_NODE,this.right=null!=i?i:SI.EMPTY_NODE}copy(e,t,n,r,i){return new EI(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 SI.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 SI.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,EI.RED,null,this.right.left);return this.right.copy(null,null,this.color,e,null)}rotateRight_(){var e=this.copy(null,null,EI.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)}}EI.RED=!0,EI.BLACK=!1;class SI{constructor(e,t=SI.EMPTY_NODE){this.comparator_=e,this.root_=t}insert(e,t){return new SI(this.comparator_,this.root_.insert(e,t,this.comparator_).copy(null,null,EI.BLACK,null,null))}remove(e){return new SI(this.comparator_,this.root_.remove(e,this.comparator_).copy(null,null,EI.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 TI(this.root_,null,this.comparator_,!1,e)}getIteratorFrom(e,t){return new TI(this.root_,e,this.comparator_,!1,t)}getReverseIteratorFrom(e,t){return new TI(this.root_,e,this.comparator_,!0,t)}getReverseIterator(e){return new TI(this.root_,null,this.comparator_,!0,e)}}function kI(e,t){return Ib(e.name,t.name)}function CI(e,t){return Ib(e,t)}SI.EMPTY_NODE=new class{copy(e,t,n,r,i){return this}insert(e,t,n){return new EI(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 AI;function NI(e){return"number"==typeof e?"number:"+Eb(e):"string:"+e}function RI(e){var t;e.isLeafNode()?(t=e.val(),Jh("string"==typeof t||"number"==typeof t||"object"==typeof t&&bd(t,".sv"),"Priority must be a string or number.")):Jh(e===AI||e.isEmpty(),"priority of unexpected type."),Jh(e===AI||e.getPriority().isEmpty(),"Priority nodes can't have a priority of their own.")}let PI;class xI{constructor(e,t=xI.__childrenNodeConstructor.EMPTY_NODE){this.value_=e,this.priorityNode_=t,this.lazyHash_=null,Jh(void 0!==this.value_&&null!==this.value_,"LeafNode shouldn't be created with null/undefined value."),RI(this.priorityNode_)}static set __childrenNodeConstructor(e){PI=e}static get __childrenNodeConstructor(){return PI}isLeafNode(){return!0}getPriority(){return this.priorityNode_}updatePriority(e){return new xI(this.value_,e)}getImmediateChild(e){return".priority"===e?this.priorityNode_:xI.__childrenNodeConstructor.EMPTY_NODE}getChild(e){return cI(e)?this:".priority"===tI(e)?this.priorityNode_:xI.__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:xI.__childrenNodeConstructor.EMPTY_NODE.updateImmediateChild(e,t).updatePriority(this.priorityNode_)}updateChild(e,t){var n=tI(e);return null===n?t:t.isEmpty()&&".priority"!==n?this:(Jh(".priority"!==n||1===nI(e),".priority must be the last token in a path"),this.updateImmediateChild(n,xI.__childrenNodeConstructor.EMPTY_NODE.updateChild(rI(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:"+NI(this.priorityNode_.val())+":");var t=typeof this.value_;e+=t+":",e+="number"==t?Eb(this.value_):this.value_,this.lazyHash_=eb(e)}return this.lazyHash_}getValue(){return this.value_}compareTo(e){return e===xI.__childrenNodeConstructor.EMPTY_NODE?1:e instanceof xI.__childrenNodeConstructor?-1:(Jh(e.isLeafNode(),"Unknown node type"),this.compareToLeafNode_(e))}compareToLeafNode_(e){var t=typeof e.value_,n=typeof this.value_,r=xI.VALUE_TYPE_ORDER.indexOf(t),i=xI.VALUE_TYPE_ORDER.indexOf(n);return Jh(0<=r,"Unknown leaf type: "+t),Jh(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_))}}xI.VALUE_TYPE_ORDER=["object","boolean","number","string"];let OI,DI;const LI=new class extends _I{compare(e,t){const n=e.node.getPriority();var r=t.node.getPriority(),r=n.compareTo(r);return 0===r?Ib(e.name,t.name):r}isDefinedOn(e){return!e.getPriority().isEmpty()}indexedValueChanged(e,t){return!e.getPriority().equals(t.getPriority())}minPost(){return yI.MIN}maxPost(){return new yI(bb,new xI("[PRIORITY-POST]",DI))}makePost(e,t){var n=OI(e);return new yI(t,new xI("[PRIORITY-POST]",n))}toString(){return".priority"}},MI=Math.log(2);class FI{constructor(e){var t;this.count=(t=e+1,parseInt(Math.log(t)/MI,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 UI(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 EI(i,r.node,EI.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 EI(i,r.node,EI.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 EI(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,EI.BLACK):(t(r,EI.BLACK),t(r,EI.RED))}return o}(new FI(c.length));return new SI(t||e,n)}let jI;const qI={};class VI{constructor(e,t){this.indexes_=e,this.indexSet_=t}static get Default(){return Jh((qI,LI),"ChildrenNode.ts has not been loaded"),jI=jI||new VI({".priority":qI},{".priority":LI}),jI}get(e){var t=Id(this.indexes_,e);if(!t)throw new Error("No index defined for "+e);return t instanceof SI?t:null}hasIndex(e){return bd(this.indexSet_,e.toString())}addIndex(e,t){Jh(e!==II,"KeyIndex always exists and isn't meant to be added to the IndexMap.");const n=[];let r=!1;const i=t.getIterator(yI.Wrap);let s=i.getNext();for(;s;)r=r||e.isDefinedOn(s.node),n.push(s),s=i.getNext();let o;o=r?UI(n,e.getCompare()):qI;var a=e.toString();const c=Object.assign({},this.indexSet_);c[a]=e;const l=Object.assign({},this.indexes_);return l[a]=o,new VI(l,c)}addToIndexes(o,a){var e=Ed(this.indexes_,(t,e)=>{const n=Id(this.indexSet_,e);if(Jh(n,"Missing index implementation for "+e),t===qI){if(n.isDefinedOn(o.node)){const i=[],s=a.getIterator(yI.Wrap);let e=s.getNext();for(;e;)e.name!==o.name&&i.push(e),e=s.getNext();return i.push(o),UI(i,n.getCompare())}return qI}{var r=a.get(o.name);let e=t;return r&&(e=e.remove(new yI(o.name,r))),e.insert(o,o.node)}});return new VI(e,this.indexSet_)}removeFromIndexes(n,r){var e=Ed(this.indexes_,e=>{if(e===qI)return e;var t=r.get(n.name);return t?e.remove(new yI(n.name,t)):e});return new VI(e,this.indexSet_)}}let BI;class $I{constructor(e,t,n){this.children_=e,this.priorityNode_=t,this.indexMap_=n,this.lazyHash_=null,this.priorityNode_&&RI(this.priorityNode_),this.children_.isEmpty()&&Jh(!this.priorityNode_||this.priorityNode_.isEmpty(),"An empty node cannot have a priority")}static get EMPTY_NODE(){return BI=BI||new $I(new SI(CI),null,VI.Default)}isLeafNode(){return!1}getPriority(){return this.priorityNode_||BI}updatePriority(e){return this.children_.isEmpty()?this:new $I(this.children_,e,this.indexMap_)}getImmediateChild(e){if(".priority"===e)return this.getPriority();var t=this.children_.get(e);return null===t?BI:t}getChild(e){var t=tI(e);return null===t?this:this.getImmediateChild(t).getChild(rI(e))}hasChild(e){return null!==this.children_.get(e)}updateImmediateChild(n,r){if(Jh(r,"We should always be passing snapshot nodes"),".priority"===n)return this.updatePriority(r);{var i=new yI(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()?BI:this.priorityNode_;return new $I(e,i,t)}}updateChild(e,t){var n=tI(e);if(null===n)return t;Jh(".priority"!==tI(e)||1===nI(e),".priority must be the last token in a path");var r=this.getImmediateChild(n).updateChild(rI(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(LI,(e,t)=>{r[e]=t.val(n),i++,o&&$I.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:"+NI(this.getPriority().val())+":"),this.forEachChild(LI,(e,t)=>{var n=t.hash();""!==n&&(r+=":"+e+":"+n)}),this.lazyHash_=""===r?"":eb(r)}return this.lazyHash_}getPredecessorChildName(e,t,n){const r=this.resolveIndex_(n);if(r){var i=r.getPredecessorKey(new yI(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 yI(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 yI(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,yI.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,yI.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===zI?-1:0}withIndex(e){if(e===II||this.indexMap_.hasIndex(e))return this;var t=this.indexMap_.addIndex(e,this.children_);return new $I(this.children_,this.priorityNode_,t)}isIndexed(e){return e===II||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(LI),i=n.getIterator(LI);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===II?null:this.indexMap_.get(e.toString())}}$I.INTEGER_REGEXP_=/^(0|[1-9]\d*)$/;class KI extends $I{constructor(){super(new SI(CI),$I.EMPTY_NODE,VI.Default)}compareTo(e){return e===this?0:1}equals(e){return e===this}getPriority(){return this}getImmediateChild(e){return $I.EMPTY_NODE}isEmpty(){return!1}}const zI=new KI;Object.defineProperties(yI,{MIN:{value:new yI(wb,$I.EMPTY_NODE)},MAX:{value:new yI(bb,zI)}}),bI.__EMPTY_NODE=$I.EMPTY_NODE,xI.__childrenNodeConstructor=$I,Gw=zI,AI=Gw,Qw=zI,DI=Qw;const WI=!0;function HI(i,e=null){if(null===i)return $I.EMPTY_NODE;if("object"==typeof i&&".priority"in i&&(e=i[".priority"]),Jh(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 xI(t,HI(e))}if(i instanceof Array||!WI){let r=$I.EMPTY_NODE;return Tb(i,(e,t)=>{if(bd(i,e)&&"."!==e.substring(0,1)){const n=HI(t);!n.isLeafNode()&&n.isEmpty()||(r=r.updateImmediateChild(e,n))}}),r.updatePriority(HI(e))}{const s=[];let r=!1;if(Tb(i,(e,t)=>{if("."!==e.substring(0,1)){const n=HI(t);n.isEmpty()||(r=r||!n.getPriority().isEmpty(),s.push(new yI(e,n)))}}),0===s.length)return $I.EMPTY_NODE;var n=UI(s,kI,e=>e.name,CI);if(r){t=UI(s,LI.getCompare());return new $I(n,HI(e),new VI({".priority":t},{".priority":LI}))}return new $I(n,HI(e),VI.Default)}}OI=HI;class GI extends _I{constructor(e){super(),this.indexPath_=e,Jh(!cI(e)&&".priority"!==tI(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?Ib(e.name,t.name):r}makePost(e,t){var n=HI(e),n=$I.EMPTY_NODE.updateChild(this.indexPath_,n);return new yI(t,n)}maxPost(){var e=$I.EMPTY_NODE.updateChild(this.indexPath_,zI);return new yI(bb,e)}toString(){return sI(this.indexPath_,0).join("/")}}function QI(e){if(e===""+Ab)return ZI;var t=Nb(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<tT)return n.push(ZI),n.join("");let r=n.length-1;for(;0<=r&&n[r]===eT;)r--;return-1===r?bb:(t=n[r],t=XI.charAt(XI.indexOf(t)+1),n[r]=t,n.slice(0,r+1).join(""))}function YI(e){if(e===""+Cb)return wb;var t=Nb(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]===ZI?1===n.length?""+Ab:(delete n[n.length-1],n.join("")):(n[n.length-1]=XI.charAt(XI.indexOf(n[n.length-1])-1),n.join("")+eT.repeat(tT-n.length))}const JI=new class extends _I{compare(e,t){var n=e.node.compareTo(t.node);return 0===n?Ib(e.name,t.name):n}isDefinedOn(e){return!0}indexedValueChanged(e,t){return!e.equals(t)}minPost(){return yI.MIN}maxPost(){return yI.MAX}makePost(e,t){var n=HI(e);return new yI(t,n)}toString(){return".value"}},XI="-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz",ZI="-",eT="z",tT=786,nT=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]=XI.charAt(e%64),e=Math.floor(e/64);Jh(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+=XI.charAt(o[n]);return Jh(20===i.length,"nextPushId: Length should be 20."),i}}();function rT(e){return{type:"value",snapshotNode:e}}function iT(e,t){return{type:"child_added",snapshotNode:t,childName:e}}function sT(e,t){return{type:"child_removed",snapshotNode:t,childName:e}}function oT(e,t,n){return{type:"child_changed",snapshotNode:t,childName:e,oldSnap:n}}class aT{constructor(e){this.index_=e}updateChild(e,t,n,r,i,s){Jh(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(sT(t,o)):Jh(e.isLeafNode(),"A child remove without an old child only makes sense on a leaf node"):o.isEmpty()?s.trackChildChange(iT(t,n)):s.trackChildChange(oT(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(LI,(e,t)=>{n.hasChild(e)||i.trackChildChange(sT(e,t))}),n.isLeafNode()||n.forEachChild(LI,(e,t)=>{if(r.hasChild(e)){const n=r.getImmediateChild(e);n.equals(t)||i.trackChildChange(oT(e,t,n))}else i.trackChildChange(iT(e,t))})),n.withIndex(this.index_)}updatePriority(e,t){return e.isEmpty()?$I.EMPTY_NODE:e.updatePriority(t)}filtersNodes(){return!1}getIndexedFilter(){return this}getIndex(){return this.index_}}class cT{constructor(e){this.indexedFilter_=new aT(e.getIndex()),this.index_=e.getIndex(),this.startPost_=cT.getStartPost_(e),this.endPost_=cT.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 yI(t,n))||(n=$I.EMPTY_NODE),this.indexedFilter_.updateChild(e,t,n,r,i,s)}updateFullNode(e,t,n){let r=(t=t.isLeafNode()?$I.EMPTY_NODE:t).withIndex(this.index_);r=r.updatePriority($I.EMPTY_NODE);const i=this;return t.forEachChild(LI,(e,t)=>{i.matches(new yI(e,t))||(r=r.updateImmediateChild(e,$I.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 lT{constructor(e){this.rangedFilter_=new cT(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 yI(t,n))||(n=$I.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=$I.EMPTY_NODE.withIndex(this.index_);else if(2*this.limit_<o.numChildren()&&o.isIndexed(this.index_)){a=$I.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($I.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,$I.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;Jh(o.numChildren()===this.limit_,"");var a=new yI(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(oT(t,n,u)),o.updateImmediateChild(t,n);{null!=i&&i.trackChildChange(sT(t,u));const f=o.updateImmediateChild(t,$I.EMPTY_NODE);return null!=e&&this.rangedFilter_.matches(e)?(null!=i&&i.trackChildChange(iT(e.name,e.node)),f.updateImmediateChild(e.name,e.node)):f}}return!n.isEmpty()&&l&&0<=s(c,a)?(null!=i&&(i.trackChildChange(sT(c.name,c.node)),i.trackChildChange(iT(t,n))),o.updateImmediateChild(t,n).updateImmediateChild(c.name,$I.EMPTY_NODE)):e}}class uT{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_=LI}hasStart(){return this.startSet_}hasStartAfter(){return this.startAfterSet_}hasEndBefore(){return this.endBeforeSet_}isViewFromLeft(){return""===this.viewFrom_?this.startSet_:"l"===this.viewFrom_}getIndexStartValue(){return Jh(this.startSet_,"Only valid if start has been set"),this.indexStartValue_}getIndexStartName(){return Jh(this.startSet_,"Only valid if start has been set"),this.startNameSet_?this.indexStartName_:wb}hasEnd(){return this.endSet_}getIndexEndValue(){return Jh(this.endSet_,"Only valid if end has been set"),this.indexEndValue_}getIndexEndName(){return Jh(this.endSet_,"Only valid if end has been set"),this.endNameSet_?this.indexEndName_:bb}hasLimit(){return this.limitSet_}hasAnchoredLimit(){return this.limitSet_&&""!==this.viewFrom_}getLimit(){return Jh(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_===LI}copy(){const e=new uT;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 hT(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 dT(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 fT(e,t){const n=e.copy();return n.index_=t,n}function pT(e){const t={};if(e.isDefault())return t;let n;return n=e.index_===LI?"$priority":e.index_===JI?"$value":e.index_===II?"$key":(Jh(e.index_ instanceof GI,"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 gT(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_!==LI&&(n.i=t.index_.toString()),n}class mT extends Yb{constructor(e,t,n,r){super(),this.repoInfo_=e,this.onDataUpdate_=t,this.authTokenProvider_=n,this.appCheckTokenProvider_=r,this.log_=cb("p:rest:"),this.listens_={}}reportStats(e){throw new Error("Method not implemented.")}static getListenId_(e,t){return void 0!==t?"tag$"+t:(Jh(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=mT.getListenId_(e,r),a={};this.listens_[o]=a;var n=pT(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=mT.getListenId_(e,t);delete this.listens_[n]}get(e){var t=pT(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){vb("Failed to parse JSON response for "+n+": "+r.responseText)}o(null,e)}else 401!==r.status&&404!==r.status&&vb("Got unsuccessful REST response for "+n+" Status: "+r.status),o(r.status);o=null}},r.open("GET",n,!0),r.send()})}}class vT{constructor(){this.rootNode_=$I.EMPTY_NODE}getNode(e){return this.rootNode_.getChild(e)}updateSnapshot(e,t){this.rootNode_=this.rootNode_.updateChild(e,t)}}function yT(){return{value:null,children:new Map}}function _T(e,t,n){var r;cI(t)?(e.value=n,e.children.clear()):null!==e.value?e.value=e.value.updateChild(t,n):(r=tI(t),e.children.has(r)||e.children.set(r,yT()),_T(e.children.get(r),t=rI(t),n))}function wT(e,n,r){var i;null!==e.value?r(n,e.value):(i=(e,t)=>{wT(t,new Zb(n.toString()+"/"+e),r)},e.children.forEach((e,t)=>{i(t,e)}))}class bT{constructor(e){this.collection_=e,this.last_=null}get(){var e=this.collection_.get();const n=Object.assign({},e);return this.last_&&Tb(this.last_,(e,t)=>{n[e]=n[e]-t}),this.last_=e,n}}class IT{constructor(e,t){this.server_=t,this.statsToReport_={},this.statsListener_=new bT(e);var n=1e4+2e4*Math.random();Sb(this.reportStats_.bind(this),Math.floor(n))}reportStats_(){var e=this.statsListener_.get();const n={};let r=!1;Tb(e,(e,t)=>{0<t&&bd(this.statsToReport_,e)&&(n[e]=t,r=!0)}),r&&this.server_.reportStats(n),Sb(this.reportStats_.bind(this),Math.floor(2*Math.random()*3e5))}}function TT(){return{fromUser:!0,fromServer:!1,queryId:null,tagged:!1}}function ET(){return{fromUser:!1,fromServer:!0,queryId:null,tagged:!1}}function ST(e){return{fromUser:!1,fromServer:!0,queryId:e,tagged:!0}}(W=Yw=Yw||{})[W.OVERWRITE=0]="OVERWRITE",W[W.MERGE=1]="MERGE",W[W.ACK_USER_WRITE=2]="ACK_USER_WRITE",W[W.LISTEN_COMPLETE=3]="LISTEN_COMPLETE";class kT{constructor(e,t,n){this.path=e,this.affectedTree=t,this.revert=n,this.type=Yw.ACK_USER_WRITE,this.source=TT()}operationForChild(e){if(cI(this.path)){if(null!=this.affectedTree.value)return Jh(this.affectedTree.children.isEmpty(),"affectedTree should not have overlapping affected paths."),this;var t=this.affectedTree.subtree(new Zb(e));return new kT(eI(),t,this.revert)}return Jh(tI(this.path)===e,"operationForChild called for unrelated child."),new kT(rI(this.path),this.affectedTree,this.revert)}}class CT{constructor(e,t){this.source=e,this.path=t,this.type=Yw.LISTEN_COMPLETE}operationForChild(e){return cI(this.path)?new CT(this.source,eI()):new CT(this.source,rI(this.path))}}class AT{constructor(e,t,n){this.source=e,this.path=t,this.snap=n,this.type=Yw.OVERWRITE}operationForChild(e){return cI(this.path)?new AT(this.source,eI(),this.snap.getImmediateChild(e)):new AT(this.source,rI(this.path),this.snap)}}class NT{constructor(e,t,n){this.source=e,this.path=t,this.children=n,this.type=Yw.MERGE}operationForChild(e){if(cI(this.path)){const t=this.children.subtree(new Zb(e));return t.isEmpty()?null:t.value?new AT(this.source,eI(),t.value):new NT(this.source,eI(),t)}return Jh(tI(this.path)===e,"Can't get a merge for a child not on the path of the operation"),new NT(this.source,rI(this.path),this.children)}toString(){return"Operation("+this.path+": "+this.source.toString()+" merge: "+this.children.toString()+")"}}class RT{constructor(e,t,n){this.node_=e,this.fullyInitialized_=t,this.filtered_=n}isFullyInitialized(){return this.fullyInitialized_}isFiltered(){return this.filtered_}isCompleteForPath(e){if(cI(e))return this.isFullyInitialized()&&!this.filtered_;var t=tI(e);return this.isCompleteForChild(t)}isCompleteForChild(e){return this.isFullyInitialized()&&!this.filtered_||this.node_.hasChild(e)}getNode(){return this.node_}}class PT{constructor(e){this.query_=e,this.index_=this.query_._queryParams.getIndex()}}function xT(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}))}),OT(n,i,"child_removed",e,r,t),OT(n,i,"child_added",e,r,t),OT(n,i,"child_moved",s,r,t),OT(n,i,"child_changed",e,r,t),OT(n,i,"value",e,r,t),i}function OT(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 Xh("Should only compare child_ events.");var r=new yI(t.childName,t.snapshotNode),i=new yI(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 DT(e,t){return{eventCache:e,serverCache:t}}function LT(e,t,n,r){return DT(new RT(t,n,r),e.serverCache)}function MT(e,t,n,r){return DT(e.eventCache,new RT(t,n,r))}function FT(e){return e.eventCache.isFullyInitialized()?e.eventCache.getNode():null}function UT(e){return e.serverCache.isFullyInitialized()?e.serverCache.getNode():null}let jT;class qT{constructor(e,t=(jT=jT||new SI(ub),jT)){this.value=e,this.children=t}static fromObject(e){let n=new qT(null);return Tb(e,(e,t)=>{n=n.set(new Zb(e),t)}),n}isEmpty(){return null===this.value&&this.children.isEmpty()}findRootMostMatchingPathAndValue(e,t){if(null!=this.value&&t(this.value))return{path:eI(),value:this.value};if(cI(e))return null;{var n=tI(e);const i=this.children.get(n);if(null===i)return null;var r=i.findRootMostMatchingPathAndValue(rI(e),t);return null==r?null:{path:aI(new Zb(n),r.path),value:r.value}}}findRootMostValueAndPath(e){return this.findRootMostMatchingPathAndValue(e,()=>!0)}subtree(e){if(cI(e))return this;{var t=tI(e);const n=this.children.get(t);return null!==n?n.subtree(rI(e)):new qT(null)}}set(e,t){if(cI(e))return new qT(t,this.children);{var n=tI(e);const i=this.children.get(n)||new qT(null);var r=i.set(rI(e),t),r=this.children.insert(n,r);return new qT(this.value,r)}}remove(t){if(cI(t))return this.children.isEmpty()?new qT(null):new qT(null,this.children);{var n=tI(t);const r=this.children.get(n);if(r){const i=r.remove(rI(t));let e;return e=i.isEmpty()?this.children.remove(n):this.children.insert(n,i),null===this.value&&e.isEmpty()?new qT(null):new qT(this.value,e)}return this}}get(e){if(cI(e))return this.value;{var t=tI(e);const n=this.children.get(t);return n?n.get(rI(e)):null}}setTree(t,n){if(cI(t))return n;{var r=tI(t);const i=this.children.get(r)||new qT(null),s=i.setTree(rI(t),n);let e;return e=s.isEmpty()?this.children.remove(r):this.children.insert(r,s),new qT(this.value,e)}}fold(e){return this.fold_(eI(),e)}fold_(n,r){const i={};return this.children.inorderTraversal((e,t)=>{i[e]=t.fold_(aI(n,e),r)}),r(n,this.value,i)}findOnPath(e,t){return this.findOnPath_(e,eI(),t)}findOnPath_(e,t,n){var r=!!this.value&&n(t,this.value);if(r)return r;if(cI(e))return null;{r=tI(e);const i=this.children.get(r);return i?i.findOnPath_(rI(e),aI(t,r),n):null}}foreachOnPath(e,t){return this.foreachOnPath_(e,eI(),t)}foreachOnPath_(e,t,n){if(cI(e))return this;{this.value&&n(t,this.value);var r=tI(e);const i=this.children.get(r);return i?i.foreachOnPath_(rI(e),aI(t,r),n):new qT(null)}}foreach(e){this.foreach_(eI(),e)}foreach_(n,r){this.children.inorderTraversal((e,t)=>{t.foreach_(aI(n,e),r)}),this.value&&r(n,this.value)}foreachChild(n){this.children.inorderTraversal((e,t)=>{t.value&&n(e,t.value)})}}class VT{constructor(e){this.writeTree_=e}static empty(){return new VT(new qT(null))}}function BT(t,n,r){if(cI(n))return new VT(new qT(r));var i=t.writeTree_.findRootMostValueAndPath(n);if(null!=i){var s=i.path;let e=i.value;i=lI(s,n);return e=e.updateChild(i,r),new VT(t.writeTree_.set(s,e))}s=new qT(r),s=t.writeTree_.setTree(n,s);return new VT(s)}function $T(e,n,t){let r=e;return Tb(t,(e,t)=>{r=BT(r,aI(n,e),t)}),r}function KT(e,t){if(cI(t))return VT.empty();var n=e.writeTree_.setTree(t,new qT(null));return new VT(n)}function zT(e,t){return null!=WT(e,t)}function WT(e,t){var n=e.writeTree_.findRootMostValueAndPath(t);return null!=n?e.writeTree_.get(n.path).getChild(lI(n.path,t)):null}function HT(e){const n=[],t=e.writeTree_.value;return null!=t?t.isLeafNode()||t.forEachChild(LI,(e,t)=>{n.push(new yI(e,t))}):e.writeTree_.children.inorderTraversal((e,t)=>{null!=t.value&&n.push(new yI(e,t.value))}),n}function GT(e,t){if(cI(t))return e;var n=WT(e,t);return null!=n?new VT(new qT(n)):new VT(e.writeTree_.subtree(t))}function QT(e){return e.writeTree_.isEmpty()}function YT(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?(Jh(null!==t.value,"Priority writes must always be leaf nodes"),n=t.value):s=r(aI(i,e),t,s)}),s=!s.getChild(i).isEmpty()&&null!==n?s.updateChild(aI(i,".priority"),n):s}}}(eI(),e.writeTree_,t)}function JT(e,t){return l0(t,e)}function XT(t,n){var e,r=t.allWrites.findIndex(e=>e.writeId===n);Jh(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 dI(e.path,t);for(const n in e.children)if(e.children.hasOwnProperty(n)&&dI(aI(e.path,n),t))return!0;return!1}}(c,i.path)?s=!1:dI(i.path,c.path)&&(o=!0)),a--}return!!s&&(o?((e=t).visibleWrites=e0(e.allWrites,ZT,eI()),0<e.allWrites.length?e.lastWriteId=e.allWrites[e.allWrites.length-1].writeId:e.lastWriteId=-1):i.snap?t.visibleWrites=KT(t.visibleWrites,i.path):Tb(i.children,e=>{t.visibleWrites=KT(t.visibleWrites,aI(i.path,e))}),!0)}function ZT(e){return e.visible}function e0(e,t,n){let r=VT.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)dI(n,i)?(e=lI(n,i),r=BT(r,e,o.snap)):dI(i,n)&&(e=lI(i,n),r=BT(r,eI(),o.snap.getChild(e)));else{if(!o.children)throw Xh("WriteRecord should have .snap or .children");if(dI(n,i))e=lI(n,i),r=$T(r,e,o.children);else if(dI(i,n))if(e=lI(i,n),cI(e))r=$T(r,eI(),o.children);else{const a=Id(o.children,tI(e));a&&(i=a.getChild(rI(e)),r=BT(r,eI(),i))}}}}return r}function t0(e,t,n,r,i){if(r||i){var s=GT(e.visibleWrites,t);if(!i&&QT(s))return n;if(i||null!=n||zT(s,eI()))return YT(e0(e.allWrites,function(e){return(e.visible||i)&&(!r||!~r.indexOf(e.writeId))&&(dI(e.path,t)||dI(t,e.path))},t),n||$I.EMPTY_NODE);return null}s=WT(e.visibleWrites,t);if(null!=s)return s;s=GT(e.visibleWrites,t);return QT(s)?n:null!=n||zT(s,eI())?YT(s,n||$I.EMPTY_NODE):null}function n0(e,t,n,r){return t0(e.writeTree,e.treePath,t,n,r)}function r0(e,t){return function(e,t,n){let r=$I.EMPTY_NODE;const i=WT(e.visibleWrites,t);if(i)return i.isLeafNode()||i.forEachChild(LI,(e,t)=>{r=r.updateImmediateChild(e,t)}),r;if(n){const s=GT(e.visibleWrites,t);return n.forEachChild(LI,(e,t)=>{var n=YT(GT(s,new Zb(e)),t);r=r.updateImmediateChild(e,n)}),HT(s).forEach(e=>{r=r.updateImmediateChild(e.name,e.node)}),r}return HT(GT(e.visibleWrites,t)).forEach(e=>{r=r.updateImmediateChild(e.name,e.node)}),r}(e.writeTree,e.treePath,t)}function i0(e,t,n,r){return function(e,t,n,r,i){Jh(r||i,"Either existingEventSnap or existingServerSnap must exist");var s=aI(t,n);return zT(e.visibleWrites,s)?null:QT(s=GT(e.visibleWrites,s))?i.getChild(n):YT(s,i.getChild(n))}(e.writeTree,e.treePath,t,n,r)}function s0(e,t){return n=e.writeTree,t=aI(e.treePath,t),WT(n.visibleWrites,t);var n}function o0(e,t,n,r,i,s){return function(e,t,n,r,i,s,o){let a;var c=GT(e.visibleWrites,t),l=WT(c,eI());if(null!=l)a=l;else{if(null==n)return[];a=YT(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 a0(e,t,n){return r=e.writeTree,e=e.treePath,n=n,i=aI(e,t=t),null!=(s=WT(r.visibleWrites,i))?s:n.isCompleteForChild(t)?YT(GT(r.visibleWrites,i),n.getNode().getImmediateChild(t)):null;var r,i,s}function c0(e,t){return l0(aI(e.treePath,t),e.writeTree)}function l0(e,t){return{treePath:e,writeTree:t}}class u0{constructor(){this.changeMap=new Map}trackChildChange(e){var t=e.type,n=e.childName;Jh("child_added"===t||"child_changed"===t||"child_removed"===t,"Only child changes supported for tracking"),Jh(".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,oT(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,sT(n,r.oldSnap));else if("child_changed"===t&&"child_added"===i)this.changeMap.set(n,iT(n,e.snapshotNode));else{if("child_changed"!==t||"child_changed"!==i)throw Xh("Illegal combination of changes: "+e+" occurred after "+r);this.changeMap.set(n,oT(n,e.snapshotNode,r.oldSnap))}}else this.changeMap.set(n,e)}getChanges(){return Array.from(this.changeMap.values())}}const h0=new class{getCompleteChild(e){return null}getChildAfterChild(e,t,n){return null}};class d0{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 RT(this.optCompleteServerCache_,!0,!1):this.viewCache_.serverCache;return a0(this.writes_,e,n)}getChildAfterChild(e,t,n){var r=null!=this.optCompleteServerCache_?this.optCompleteServerCache_:UT(this.viewCache_),r=o0(this.writes_,r,t,1,n,e);return 0===r.length?null:r[0]}}function f0(e,t,n,r,i){const s=new u0;let o,a;if(n.type===Yw.OVERWRITE){var c=n;o=c.source.fromUser?m0(e,t,c.path,c.snap,r,i,s):(Jh(c.source.fromServer,"Unknown source."),a=c.source.tagged||t.serverCache.isFiltered()&&!cI(c.path),g0(e,t,c.path,c.snap,r,i,a,s))}else if(n.type===Yw.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=aI(s,e);v0(i,tI(n))&&(l=m0(r,l,n,t,o,a,c))}),e.foreach((e,t)=>{var n=aI(s,e);v0(i,tI(n))||(l=m0(r,l,n,t,o,a,c))}),l}(e,t,c.path,c.children,r,i,s):(Jh(c.source.fromServer,"Unknown source."),a=c.source.tagged||t.serverCache.isFiltered(),_0(e,t,c.path,c.children,r,i,a,s))}else if(n.type===Yw.ACK_USER_WRITE){var l=n;o=l.revert?function(n,r,i,s,e,o){let a;{if(null!=s0(s,i))return r;{var c=new d0(s,r,e);const u=r.eventCache.getNode();let t;if(cI(i)||".priority"===tI(i)){let e;e=r.serverCache.isFullyInitialized()?n0(s,UT(r)):(l=r.serverCache.getNode(),Jh(l instanceof $I,"serverChildren would be complete if leaf node"),r0(s,l)),e=e,t=n.filter.updateFullNode(u,e,o)}else{var l=tI(i);let e=a0(s,l,r.serverCache);null==e&&r.serverCache.isCompleteForChild(l)&&(e=u.getImmediateChild(l)),t=null!=e?n.filter.updateChild(u,l,e,rI(i),c,o):r.eventCache.getNode().hasChild(l)?n.filter.updateChild(u,l,$I.EMPTY_NODE,rI(i),c,o):u,t.isEmpty()&&r.serverCache.isFullyInitialized()&&(a=n0(s,UT(r)),a.isLeafNode()&&(t=n.filter.updateFullNode(t,a,o)))}return a=r.serverCache.isFullyInitialized()||null!=s0(s,eI()),LT(r,t,a,n.filter.filtersNodes())}}}(e,t,l.path,r,i,s):function(e,t,i,n,s,o,a){if(null!=s0(s,i))return t;const c=t.serverCache.isFiltered(),l=t.serverCache;{if(null!=n.value){if(cI(i)&&l.isFullyInitialized()||l.isCompleteForPath(i))return g0(e,t,i,l.getNode().getChild(i),s,o,c,a);if(cI(i)){let n=new qT(null);return l.getNode().forEachChild(II,(e,t)=>{n=n.set(new Zb(e),t)}),_0(e,t,i,n,s,o,c,a)}return t}{let r=new qT(null);return n.foreach((e,t)=>{var n=aI(i,e);l.isCompleteForPath(n)&&(r=r.set(e,l.getNode().getChild(n)))}),_0(e,t,i,r,s,o,c,a)}}}(e,t,l.path,l.affectedTree,r,i,s)}else{if(n.type!==Yw.LISTEN_COMPLETE)throw Xh("Unknown operation type: "+n.type);o=function(e,t,n,r,i){const s=t.serverCache,o=MT(t,s.getNode(),s.isFullyInitialized()||cI(n),s.isFiltered());return p0(e,o,n,r,h0,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=FT(e);(0<n.length||!e.eventCache.isFullyInitialized()||i&&!r.getNode().equals(s)||!r.getNode().getPriority().equals(s.getPriority()))&&n.push(rT(FT(t)))}}(t,o,l),{viewCache:o,changes:l}}function p0(r,i,s,o,a,c){const l=i.eventCache;if(null!=s0(o,s))return i;{let t,n;if(cI(s)){var e;Jh(i.serverCache.isFullyInitialized(),"If change path is empty, we must have complete server data"),t=i.serverCache.isFiltered()?(e=r0(o,(e=UT(i))instanceof $I?e:$I.EMPTY_NODE),r.filter.updateFullNode(i.eventCache.getNode(),e,c)):(u=n0(o,UT(i)),r.filter.updateFullNode(i.eventCache.getNode(),u,c))}else{var u=tI(s);if(".priority"===u){Jh(1===nI(s),"Can't have a priority with additional path components");var h=l.getNode();n=i.serverCache.getNode();var d=i0(o,s,h,n);t=null!=d?r.filter.updatePriority(h,d):l.getNode()}else{h=rI(s);let e;e=l.isCompleteForChild(u)?(n=i.serverCache.getNode(),null!=(d=i0(o,s,l.getNode(),n))?l.getNode().getImmediateChild(u).updateChild(h,d):l.getNode().getImmediateChild(u)):a0(o,u,i.serverCache),t=null!=e?r.filter.updateChild(l.getNode(),u,e,h,a,c):l.getNode()}}return LT(i,t,l.isFullyInitialized()||cI(s),r.filter.filtersNodes())}}function g0(e,t,n,r,i,s,o,a){const c=t.serverCache;let l;const u=o?e.filter:e.filter.getIndexedFilter();if(cI(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=tI(n);if(!c.isCompleteForPath(n)&&1<nI(n))return t;var f=rI(n);const p=c.getNode().getImmediateChild(d);h=p.updateChild(f,r);l=".priority"===d?u.updatePriority(c.getNode(),h):u.updateChild(c.getNode(),d,h,f,h0,null)}f=MT(t,l,c.isFullyInitialized()||cI(n),u.filtersNodes());return p0(e,f,n,i,new d0(i,f,s),a)}function m0(t,n,r,i,e,s,o){const a=n.eventCache;let c,l;const u=new d0(e,n,s);if(cI(r))l=t.filter.updateFullNode(n.eventCache.getNode(),i,o),c=LT(n,l,!0,t.filter.filtersNodes());else{var h=tI(r);if(".priority"===h)l=t.filter.updatePriority(n.eventCache.getNode(),i),c=LT(n,l,a.isFullyInitialized(),a.isFiltered());else{var d=rI(r);const f=a.getNode().getImmediateChild(h);let e;if(cI(d))e=i;else{const p=u.getCompleteChild(h);e=null!=p?".priority"===iI(d)&&p.getChild(oI(d)).isEmpty()?p:p.updateChild(d,i):$I.EMPTY_NODE}c=f.equals(e)?n:LT(n,t.filter.updateChild(a.getNode(),h,e,d,u,o),a.isFullyInitialized(),t.filter.filtersNodes())}}return c}function v0(e,t){return e.eventCache.isCompleteForChild(t)}function y0(e,n,t){return t.foreach((e,t)=>{n=n.updateChild(e,t)}),n}function _0(r,i,e,t,s,o,a,c){if(i.serverCache.getNode().isEmpty()&&!i.serverCache.isFullyInitialized())return i;let l=i,n;n=cI(e)?t:new qT(null).setTree(e,t);const u=i.serverCache.getNode();return n.children.inorderTraversal((e,t)=>{var n;u.hasChild(e)&&(n=y0(0,i.serverCache.getNode().getImmediateChild(e),t),l=g0(r,l,new Zb(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=y0(0,i.serverCache.getNode().getImmediateChild(e),t),l=g0(r,l,new Zb(e),n,s,o,a,c))}),l}class w0{constructor(e,t){this.query_=e,this.eventRegistrations_=[];const n=this.query_._queryParams,r=new aT(n.getIndex()),i=(e=n).loadsAllData()?new aT(e.getIndex()):new(e.hasLimit()?lT:cT)(e);this.processor_={filter:i};const s=t.serverCache,o=t.eventCache;var a=r.updateFullNode($I.EMPTY_NODE,s.getNode(),null),c=i.updateFullNode($I.EMPTY_NODE,o.getNode(),null),a=new RT(a,s.isFullyInitialized(),r.filtersNodes()),c=new RT(c,o.isFullyInitialized(),i.filtersNodes());this.viewCache_=DT(c,a),this.eventGenerator_=new PT(this.query_)}get query(){return this.query_}}function b0(e){return 0===e.eventRegistrations_.length}function I0(n,r,i){const s=[];if(i){Jh(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 T0(e,t,n,r){t.type===Yw.MERGE&&null!==t.source.queryId&&(Jh(UT(e.viewCache_),"We should always have a full cache before handling merges"),Jh(FT(e.viewCache_),"Missing event cache, even though we have a server cache"));const i=e.viewCache_,s=f0(e.processor_,i,t,n,r);return n=e.processor_,r=s.viewCache,Jh(r.eventCache.getNode().isIndexed(n.filter.getIndex()),"Event snap not indexed"),Jh(r.serverCache.getNode().isIndexed(n.filter.getIndex()),"Server snap not indexed"),Jh(s.viewCache.serverCache.isFullyInitialized()||!i.serverCache.isFullyInitialized(),"Once a server snap is complete, it should never go back"),e.viewCache_=s.viewCache,E0(e,s.changes,s.viewCache.eventCache.getNode(),null)}function E0(e,t,n,r){var i=r?[r]:e.eventRegistrations_;return xT(e.eventGenerator_,t,n,i)}let S0;class k0{constructor(){this.views=new Map}}function C0(t,n,r,i){var e=n.source.queryId;if(null!==e){e=t.views.get(e);return Jh(null!=e,"SyncTree gave us an op for an invalid query."),T0(e,n,r,i)}{let e=[];for(const s of t.views.values())e=e.concat(T0(s,n,r,i));return e}}function A0(e,n,r,i,s){var o=n._queryIdentifier,o=e.views.get(o);if(o)return o;{let e=n0(r,s?i:null),t=!1;t=!!e||(e=i instanceof $I?r0(r,i):$I.EMPTY_NODE,!1);o=DT(new RT(e,t,!1),new RT(i,s,!1));return new w0(n,o)}}function N0(e,t,n,r,i,s){var o=A0(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(LI,(e,t)=>{r.push(iT(e,t))})}return n.isFullyInitialized()&&r.push(rT(n.getNode())),E0(e,r,n.getNode(),t)}(o,n)}function R0(e,t,n,r){var i=t._queryIdentifier;const s=[];let o=[];var a=L0(e);if("default"===i)for(var[c,l]of e.views.entries())o=o.concat(I0(l,n,r)),b0(l)&&(e.views.delete(c),l.query._queryParams.loadsAllData()||s.push(l.query));else{const u=e.views.get(i);u&&(o=o.concat(I0(u,n,r)),b0(u)&&(e.views.delete(i),u.query._queryParams.loadsAllData()||s.push(u.query)))}return a&&!L0(e)&&s.push((Jh(S0,"Reference.ts has not been loaded"),new S0(t._repo,t._path))),{removed:s,events:o}}function P0(e){const t=[];for(const n of e.views.values())n.query._queryParams.loadsAllData()||t.push(n);return t}function x0(e,t){let n=null;for(const r of e.views.values())n=n||function(e,t){const n=UT(e.viewCache_);return n&&(e.query._queryParams.loadsAllData()||!cI(t)&&!n.getImmediateChild(tI(t)).isEmpty())?n.getChild(t):null}(r,t);return n}function O0(e,t){const n=t._queryParams;if(n.loadsAllData())return M0(e);var r=t._queryIdentifier;return e.views.get(r)}function D0(e,t){return null!=O0(e,t)}function L0(e){return null!=M0(e)}function M0(e){for(const t of e.views.values())if(t.query._queryParams.loadsAllData())return t;return null}let F0;let U0=1;class j0{constructor(e){this.listenProvider_=e,this.syncPointTree_=new qT(null),this.pendingWriteTree_={visibleWrites:VT.empty(),allWrites:[],lastWriteId:-1},this.tagToQueryMap=new Map,this.queryToTagMap=new Map}}function q0(e,t,n,r,i){var s,o,a,c;return s=e.pendingWriteTree_,o=t,a=n,c=r,r=i,Jh(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=BT(s.visibleWrites,o,a)),s.lastWriteId=c,i?G0(e,new AT(TT(),t,n)):[]}function V0(e,t,n,r){var i,s,o;i=e.pendingWriteTree_,s=t,o=n,r=r,Jh(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=$T(i.visibleWrites,s,o),i.lastWriteId=r;var a=qT.fromObject(n);return G0(e,new NT(TT(),t,a))}function B0(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(XT(e.pendingWriteTree_,t)){let t=new qT(null);return null!=r.snap?t=t.set(eI(),!0):Tb(r.children,e=>{t=t.set(new Zb(e),!0)}),G0(e,new kT(r.path,t,n))}return[]}function $0(e,t,n){return G0(e,new AT(ET(),t,n))}function K0(n,e,t,r){var i=e._path,s=n.syncPointTree_.get(i);let o=[];if(s&&("default"===e._queryIdentifier||D0(s,e))){var a=R0(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)=>L0(t));if(s&&!a){const d=n.syncPointTree_.subtree(i);if(!d.isEmpty()){var c=d.fold((e,t,r)=>{if(t&&L0(t))return[M0(t)];{let n=[];return t&&(n=P0(t)),Tb(r,(e,t)=>{n=n.concat(t)}),n}});for(let e=0;e<c.length;++e){var l=c[e],u=l.query,l=Y0(n,l);n.listenProvider_.startListening(nE(u),J0(n,u),l.hashFn,l.onComplete)}}}!a&&0<h.length&&!r&&(s?n.listenProvider_.stopListening(nE(e),null):h.forEach(e=>{var t=n.queryToTagMap.get(X0(e));n.listenProvider_.stopListening(nE(e),t)})),function(e,t){for(let i=0;i<t.length;++i){const s=t[i];var n,r;s._queryParams.loadsAllData()||(n=X0(s),r=e.queryToTagMap.get(n),e.queryToTagMap.delete(n),e.tagToQueryMap.delete(r))}}(n,h)}return o}function z0(e,t,n){const r=t._path;let i=null,s=!1;e.syncPointTree_.foreachOnPath(r,(e,t)=>{var n=lI(e,r);i=i||x0(t,n),s=s||L0(t)});let o=e.syncPointTree_.get(r);o?(s=s||L0(o),i=i||x0(o,eI())):(o=new k0,e.syncPointTree_=e.syncPointTree_.set(r,o));let a;if(null!=i)a=!0;else{a=!1,i=$I.EMPTY_NODE;const d=e.syncPointTree_.subtree(r);d.foreachChild((e,t)=>{var n=x0(t,eI());n&&(i=i.updateImmediateChild(e,n))})}var c,l=D0(o,t);l||t._queryParams.loadsAllData()||(u=X0(t),Jh(!e.queryToTagMap.has(u),"View does not exist, but we have a tag"),c=U0++,e.queryToTagMap.set(u,c),e.tagToQueryMap.set(c,u));var u=JT(e.pendingWriteTree_,r);let h=N0(o,t,n,u,i,a);return l||s||(l=O0(o,t),h=h.concat(function(t,e,n){const r=e._path,i=J0(t,e),s=Y0(t,n),o=t.listenProvider_.startListening(nE(e),i,s.hashFn,s.onComplete),a=t.syncPointTree_.subtree(r);if(i)Jh(!L0(a.value),"If we're adding a query, it shouldn't be shadowed");else{var c=a.fold((e,t,r)=>{if(!cI(e)&&t&&L0(t))return[M0(t).query];{let n=[];return t&&(n=n.concat(P0(t).map(e=>e.query))),Tb(r,(e,t)=>{n=n.concat(t)}),n}});for(let e=0;e<c.length;++e){var l=c[e];t.listenProvider_.stopListening(nE(l),J0(t,l))}}return o}(e,t,l))),h}function W0(e,r,t){var n=e.pendingWriteTree_,i=e.syncPointTree_.findOnPath(r,(e,t)=>{var n=x0(t,lI(e,r));if(n)return n});return t0(n,r,i,t,!0)}function H0(e,t){const r=t._path;let i=null;e.syncPointTree_.foreachOnPath(r,(e,t)=>{var n=lI(e,r);i=i||x0(t,n)});let n=e.syncPointTree_.get(r);n?i=i||x0(n,eI()):(n=new k0,e.syncPointTree_=e.syncPointTree_.set(r,n));var s=null!=i;const o=s?new RT(i,!0,!1):null;var a=JT(e.pendingWriteTree_,t._path);return FT(A0(n,t,a,s?o.getNode():$I.EMPTY_NODE,s).viewCache_)}function G0(e,t){return function t(n,r,i,s){{if(cI(n.path))return Q0(n,r,i,s);{const o=r.get(eI());null==i&&null!=o&&(i=x0(o,eI()));let e=[];const a=tI(n.path),c=n.operationForChild(a),l=r.children.get(a);if(l&&c){const u=i?i.getImmediateChild(a):null,h=c0(s,a);e=e.concat(t(c,l,u,h))}return o&&(e=e.concat(C0(o,n,s,i))),e}}}(t,e.syncPointTree_,null,JT(e.pendingWriteTree_,eI()))}function Q0(s,e,o,a){var t=e.get(eI());null==o&&null!=t&&(o=x0(t,eI()));let c=[];return e.children.inorderTraversal((e,t)=>{var n=o?o.getImmediateChild(e):null,r=c0(a,e),i=s.operationForChild(e);i&&(c=c.concat(Q0(i,t,n,r)))}),t&&(c=c.concat(C0(t,s,a,o))),c}function Y0(i,t){const s=t.query,o=J0(i,s);return{hashFn:()=>{const e=t.viewCache_.serverCache.getNode()||$I.EMPTY_NODE;return e.hash()},onComplete:e=>{if("ok"===e)return o?function(e,t,n){if(s=Z0(e,n)){var r=eE(s),i=r.path,s=r.queryId,r=lI(i,t);return tE(e,i,new CT(ST(s),r))}return[]}(i,s._path,o):(t=i,n=s._path,G0(t,new CT(ET(),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 K0(i,s,null,r)}}}function J0(e,t){var n=X0(t);return e.queryToTagMap.get(n)}function X0(e){return e._path.toString()+"$"+e._queryIdentifier}function Z0(e,t){return e.tagToQueryMap.get(t)}function eE(e){var t=e.indexOf("$");return Jh(-1!==t&&t<e.length-1,"Bad queryKey."),{queryId:e.substr(t+1),path:new Zb(e.substr(0,t))}}function tE(e,t,n){var r=e.syncPointTree_.get(t);return Jh(r,"Missing sync point for query tag that we're tracking"),C0(r,n,JT(e.pendingWriteTree_,t),null)}function nE(e){return e._queryParams.loadsAllData()&&!e._queryParams.isDefault()?(Jh(F0,"Reference.ts has not been loaded"),new F0(e._repo,e._path)):e}class rE{constructor(e){this.node_=e}getImmediateChild(e){var t=this.node_.getImmediateChild(e);return new rE(t)}node(){return this.node_}}class iE{constructor(e,t){this.syncTree_=e,this.path_=t}getImmediateChild(e){var t=aI(this.path_,e);return new iE(this.syncTree_,t)}node(){return W0(this.syncTree_,this.path_)}}function sE(e){return(e=e||{}).timestamp=e.timestamp||(new Date).getTime(),e}function oE(e,t,n){return e&&"object"==typeof e?(Jh(".sv"in e,"Unexpected leaf node or priority contents"),"string"==typeof e[".sv"]?aE(e[".sv"],t,n):"object"==typeof e[".sv"]?cE(e[".sv"],t):void Jh(!1,"Unexpected server value: "+JSON.stringify(e,null,2))):e}const aE=function(e,t,n){if("timestamp"===e)return n.timestamp;Jh(!1,"Unexpected server value: "+e)},cE=function(e,t,n){e.hasOwnProperty("increment")||Jh(!1,"Unexpected server value: "+JSON.stringify(e,null,2));var r=e.increment;"number"!=typeof r&&Jh(!1,"Unexpected increment value: "+r);const i=t.node();if(Jh(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},lE=function(e,t,n,r){return hE(t,new iE(n,e),r)},uE=function(e,t,n){return hE(e,new rE(t),n)};function hE(e,r,i){var t=e.getPriority().val(),n=oE(t,r.getImmediateChild(".priority"),i);let s;if(e.isLeafNode()){const o=e;t=oE(o.getValue(),r,i);return t!==o.getValue()||n!==o.getPriority().val()?new xI(t,HI(n)):e}{const a=e;return s=a,n!==a.getPriority().val()&&(s=s.updatePriority(new xI(n))),a.forEachChild(LI,(e,t)=>{var n=hE(t,r.getImmediateChild(e),i);n!==t&&(s=s.updateImmediateChild(e,n))}),s}}class dE{constructor(e="",t=null,n={children:{},childCount:0}){this.name=e,this.parent=t,this.node=n}}function fE(e,t){let n=t instanceof Zb?t:new Zb(t),r=e,i=tI(n);for(;null!==i;){var s=Id(r.node.children,i)||{children:{},childCount:0};r=new dE(i,r,s),n=rI(n),i=tI(n)}return r}function pE(e){return e.node.value}function gE(e,t){e.node.value=t,_E(e)}function mE(e){return 0<e.node.childCount}function vE(n,r){Tb(n.node.children,(e,t)=>{r(new dE(e,n,t))})}function yE(e){return new Zb(null===e.parent?e.name:yE(e.parent)+"/"+e.name)}function _E(e){var t,n,r,i;null!==e.parent&&(t=e.parent,n=e.name,r=function(e){return void 0===pE(e)&&!mE(e)}(e=e),i=bd(t.node.children,n),r&&i?(delete t.node.children[n],t.node.childCount--,_E(t)):r||i||(t.node.children[n]=e.node,t.node.childCount++,_E(t)))}function wE(e,t,n,r){r&&void 0===t||OE(Ld(e,"value"),t,n)}function bE(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=[];Tb(t,(e,t)=>{const n=new Zb(e);if(OE(i,t,aI(r,n)),".priority"===iI(n)&&!xE(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=sI(i);for(let e=0;e<s.length;e++)if((".priority"!==s[e]||e!==s.length-1)&&!NE(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(uI);let e=null;for(r=0;r<n.length;r++){if(i=n[r],null!==e&&dI(e,i))throw new Error(t+"contains a path "+e.toString()+" that is ancestor of another path "+i.toString());e=i}}(i,s)}}function IE(e,t,n){if(!n||void 0!==t){if(_b(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(!xE(t))throw new Error(Ld(e,"priority")+"must be a valid Firebase priority (a string, finite number, server value, or null).")}}function TE(e,t,n,r){if(!(r&&void 0===n||NE(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 EE(e,t,n,r){n=n&&n.replace(/^\/*\.info(\/|$)/,"/"),DE(e,t,n,r)}function SE(e,t){if(".info"===tI(t))throw new Error(e+" failed = Can't modify data under /.info/")}const kE=/[\[\].#$\/\u0000-\u001F\u007F]/,CE=/[\[\].#$\u0000-\u001F\u007F]/,AE=10485760,NE=function(e){return"string"==typeof e&&0!==e.length&&!kE.test(e)},RE=function(e){return"string"==typeof e&&0!==e.length&&!CE.test(e)},PE=function(e){return e=e&&e.replace(/^\/*\.info(\/|$)/,"/"),RE(e)},xE=function(e){return null===e||"string"==typeof e||"number"==typeof e&&!_b(e)||e&&"object"==typeof e&&bd(e,".sv")},OE=function(o,e,t){const a=t instanceof Zb?new fI(t,o):t;if(void 0===e)throw new Error(o+"contains undefined "+gI(a));if("function"==typeof e)throw new Error(o+"contains a function "+gI(a)+" with contents = "+e.toString());if(_b(e))throw new Error(o+"contains "+e.toString()+" "+gI(a));if("string"==typeof e&&e.length>AE/3&&Ud(e)>AE)throw new Error(o+"contains a string greater than "+AE+" utf8 bytes "+gI(a)+" ('"+e.substring(0,50)+"...')");if(e&&"object"==typeof e){let i=!1,s=!1;if(Tb(e,(e,t)=>{if(".value"===e)i=!0;else if(".priority"!==e&&".sv"!==e&&(s=!0,!NE(e)))throw new Error(o+" contains an invalid key ("+e+") "+gI(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),pI(n),OE(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 '+gI(a)+" in addition to actual children.")}},DE=function(e,t,n,r){if(!(r&&void 0===n||RE(n)))throw new Error(Ld(e,t)+'was an invalid path = "'+n+'". Paths must be non-empty strings and can\'t contain ".", "#", "$", "[", or "]"')},LE=function(e,t){var n=t.path.toString();if("string"!=typeof t.repoInfo.host||0===t.repoInfo.host.length||!NE(t.repoInfo.namespace)&&"localhost"!==t.repoInfo.host.split(":")[0]||0!==n.length&&!PE(n))throw new Error(Ld(e,"url")+'must be a valid firebase URL and the path can\'t contain ".", "#", "$", "[", or "]".')};class ME{constructor(){this.eventLists_=[],this.recursionDepth_=0}}function FE(e,t){let n=null;for(let i=0;i<t.length;i++){const s=t[i];var r=s.getPath();null===n||hI(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 UE(e,t,n){FE(e,n),qE(e,e=>hI(e,t))}function jE(e,t,n){FE(e,n),qE(e,e=>dI(e,t)||dI(t,e))}function qE(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(),ob&&gb("event: "+r.toString()),Rb(t))}}(e.eventLists_[i]),e.eventLists_[i]=null):n=!1)}n&&(e.eventLists_=[]),e.recursionDepth_--}const VE="repo_interrupt",BE=25;class $E{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 ME,this.nextWriteId_=1,this.interceptServerDataCallback_=null,this.onDisconnect_=yT(),this.transactionQueueTree_=new dE,this.persistentConnection_=null,this.key=this.repoInfo_.toURLString()}toString(){return(this.repoInfo_.secure?"https://":"http://")+this.repoInfo_.host}}function KE(o,e,t){if(o.stats_=Bb(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 mT(o.repoInfo_,(e,t,n,r)=>{HE(o,e,t,n,r)},o.authTokenProvider_,o.appCheckProvider_),setTimeout(()=>GE(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 vI(o.repoInfo_,e,(e,t,n,r)=>{HE(o,e,t,n,r)},e=>{GE(o,e)},e=>{var n;n=o,Tb(e,(e,t)=>{QE(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 IT(o.stats_,o.server_),n=e.toString(),Vb[n]||(Vb[n]=t()),Vb[n]),o.infoData_=new vT,o.infoSyncTree_=new j0({startListening:(e,t,n,r)=>{let i=[];const s=o.infoData_.getNode(e._path);return s.isEmpty()||(i=$0(o.infoSyncTree_,e._path,s),setTimeout(()=>{r("ok")},0)),i},stopListening:()=>{}}),QE(o,"connected",!1),o.serverSyncTree_=new j0({startListening:(r,e,t,i)=>(o.server_.listen(r,t,e,(e,t)=>{var n=i(e,t);jE(o.eventQueue_,r._path,n)}),[]),stopListening:(e,t)=>{o.server_.unlisten(e,t)}})}function zE(e){const t=e.infoData_.getNode(new Zb(".info/serverTimeOffset"));var n=t.val()||0;return(new Date).getTime()+n}function WE(e){return sE({timestamp:zE(e)})}function HE(e,t,n,r,i){e.dataUpdateCount++;var s,o,a=new Zb(t);n=e.interceptServerDataCallback_?e.interceptServerDataCallback_(t,n):n;let c=[];c=i?r?(s=Ed(n,e=>HI(e)),function(e,t,n,r){if(a=Z0(e,r)){var i=eE(a),s=i.path,o=i.queryId,a=lI(s,t),i=qT.fromObject(n);return tE(e,s,new NT(ST(o),a,i))}return[]}(e.serverSyncTree_,a,s,i)):(s=HI(n),function(e,t,n,r){if(null==(s=Z0(e,r)))return[];var i=(o=eE(s)).path,s=o.queryId,o=lI(i,t);return tE(e,i,new AT(ST(s),o,n))}(e.serverSyncTree_,a,s,i)):r?(o=Ed(n,e=>HI(e)),t=e.serverSyncTree_,i=a,r=o,o=qT.fromObject(r),G0(t,new NT(ET(),i,o))):(o=HI(n),$0(e.serverSyncTree_,a,o));let l=a;0<c.length&&(l=oS(e,a)),jE(e.eventQueue_,l,c)}function GE(e,t){QE(e,"connected",t),!1===t&&function(r){nS(r,"onDisconnectEvents");const i=WE(r),s=yT();wT(r.onDisconnect_,eI(),(e,t)=>{var n=lE(e,t,r.serverSyncTree_,i);_T(s,e,n)});let o=[];wT(s,eI(),(e,t)=>{o=o.concat($0(r.serverSyncTree_,e,t));var n=uS(r,e);oS(r,n)}),r.onDisconnect_=yT(),jE(r.eventQueue_,eI(),o)}(e)}function QE(e,t,n){var r=new Zb("/.info/"+t),i=HI(n);e.infoData_.updateSnapshot(r,i);i=$0(e.infoSyncTree_,r,i);jE(e.eventQueue_,r,i)}function YE(e){return e.nextWriteId_++}function JE(r,i,e,t,s){nS(r,"set",{path:i.toString(),value:e,priority:t});var n=WE(r);const o=HI(e,t);var a=W0(r.serverSyncTree_,i),n=uE(o,a,n);const c=YE(r);n=q0(r.serverSyncTree_,i,n,c,!0);FE(r.eventQueue_,n),r.server_.put(i.toString(),o.val(!0),(e,t)=>{var n="ok"===e;n||vb("set at "+i+" failed: "+e);n=B0(r.serverSyncTree_,c,!n);jE(r.eventQueue_,i,n),rS(0,s,e,t)});n=uS(r,i);oS(r,n),jE(r.eventQueue_,n,[])}function XE(n,r,i){n.server_.onDisconnectCancel(r.toString(),(e,t)=>{"ok"===e&&!function e(n,t){if(cI(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(LI,(e,t)=>{_T(n,new Zb(e),t)}),e(n,t)}}if(0<n.children.size){var r=tI(t);return t=rI(t),n.children.has(r)&&e(n.children.get(r),t)&&n.children.delete(r),0===n.children.size}return!0}(n.onDisconnect_,r),rS(0,i,e,t)})}function ZE(n,r,e,i){const s=HI(e);n.server_.onDisconnectPut(r.toString(),s.val(!0),(e,t)=>{"ok"===e&&_T(n.onDisconnect_,r,s),rS(0,i,e,t)})}function eS(e,t,n){let r;r=".info"===tI(t._path)?K0(e.infoSyncTree_,t,n):K0(e.serverSyncTree_,t,n),UE(e.eventQueue_,t._path,r)}function tS(e){e.persistentConnection_&&e.persistentConnection_.interrupt(VE)}function nS(e,...t){let n="";e.persistentConnection_&&(n=e.persistentConnection_.id+":"),gb(n,...t)}function rS(e,r,i,s){r&&Rb(()=>{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 iS(e,t,n){return W0(e.serverSyncTree_,t,n)||$I.EMPTY_NODE}function sS(t,e=t.transactionQueueTree_){if(e||lS(t,e),pE(e)){const n=cS(t,e);Jh(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=iS(i,s,e);let n=t;var r=t.hash();for(let u=0;u<o.length;u++){const h=o[u];Jh(0===h.status,"tryToSendTransactionQueue_: items in queue should all be run."),h.status=1,h.retryCount++;var a=lI(s,h.path);n=n.updateChild(a,h.currentOutputSnapshotRaw)}const c=n.val(!0),l=s;i.server_.put(l.toString(),c,t=>{nS(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(B0(i.serverSyncTree_,o[e].currentWriteId)),o[e].onComplete&&r.push(()=>o[e].onComplete(null,!0,o[e].currentOutputSnapshotResolved)),o[e].unwatcher();lS(i,fE(i.transactionQueueTree_,s)),sS(i,i.transactionQueueTree_),jE(i.eventQueue_,s,n);for(let t=0;t<r.length;t++)Rb(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{vb("transaction at "+l.toString()+" failed: "+t);for(let e=0;e<o.length;e++)o[e].status=4,o[e].abortReason=t}oS(i,s)}},r)}(t,yE(e),n)}else mE(e)&&vE(e,e=>{sS(t,e)})}function oS(e,t){var n=aS(e,t),r=yE(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=lI(o,h.path);let e=!1,t;if(Jh(null!==a,"rerunTransactionsUnderNode_: relativePath should not be null."),4===h.status)e=!0,t=h.abortReason,n=n.concat(B0(i.serverSyncTree_,h.currentWriteId,!0));else if(0===h.status)if(h.retryCount>=BE)e=!0,t="maxretry",n=n.concat(B0(i.serverSyncTree_,h.currentWriteId,!0));else{const d=iS(i,h.path,u);h.currentInputSnapshot=d;var c=s[r].update(d.val());if(void 0!==c){OE("transaction failed: Data returned ",c,h.path);let e=HI(c);"object"==typeof c&&null!=c&&bd(c,".priority")||(e=e.updatePriority(d.getPriority()));a=h.currentWriteId,c=WE(i),c=uE(e,d,c);h.currentOutputSnapshotRaw=e,h.currentOutputSnapshotResolved=c,h.currentWriteId=YE(i),u.splice(u.indexOf(a),1),n=n.concat(q0(i.serverSyncTree_,h.path,c,h.currentWriteId,h.applyLocally)),n=n.concat(B0(i.serverSyncTree_,a,!0))}else e=!0,t="nodata",n=n.concat(B0(i.serverSyncTree_,h.currentWriteId,!0))}jE(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))))}lS(i,i.transactionQueueTree_);for(let e=0;e<l.length;e++)Rb(l[e]);sS(i,i.transactionQueueTree_)}}(e,cS(e,n),r),r}function aS(e,t){let n,r=e.transactionQueueTree_;for(n=tI(t);null!==n&&void 0===pE(r);)r=fE(r,n),t=rI(t),n=tI(t);return r}function cS(e,t){const n=[];return function t(n,e,r){const i=pE(e);if(i)for(let e=0;e<i.length;e++)r.push(i[e]);vE(e,e=>{t(n,e,r)})}(e,t,n),n.sort((e,t)=>e.order-t.order),n}function lS(t,n){const r=pE(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,gE(n,0<r.length?r:void 0)}vE(n,e=>{lS(t,e)})}function uS(t,e){var n=yE(aS(t,e)),r=fE(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=>{hS(t,e)}),hS(t,r),function t(e,n,r,i){r&&!i&&n(e),vE(e,e=>{t(e,n,!0,i)}),r&&i&&n(e)}(r,e=>{hS(t,e)}),n}function hS(i,s){const o=pE(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?(Jh(t===n-1,"All SENT items should be at beginning of queue."),t=n,o[n].status=3,o[n].abortReason="set"):(Jh(0===o[n].status,"Unexpected transaction status in abort"),o[n].unwatcher(),e=e.concat(B0(i.serverSyncTree_,o[n].currentWriteId,!0)),o[n].onComplete&&a.push(o[n].onComplete.bind(null,new Error("set"),!1,null))));-1===t?gE(s,void 0):o.length=t+1,jE(i.eventQueue_,yE(s),e);for(let r=0;r<a.length;r++)Rb(a[r])}}const dS=function(e,t){var n=fS(e),r=n.namespace;"firebase.com"===n.domain&&mb(n.host+" is no longer supported. Please use <YOUR FIREBASE>.firebaseio.com instead"),r&&"undefined"!==r||"localhost"===n.domain||mb("Cannot parse Firebase url. Please use https://<YOUR FIREBASE>.firebaseio.com"),n.secure||yb();var i="ws"===n.scheme||"wss"===n.scheme;return{repoInfo:new Fb(n.host,n.secure,r,t,i,"",r!==n.subdomain),path:new Zb(n.pathString)}},fS=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,f=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]):vb(`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 p=i.slice(0,e);"localhost"===p.toLowerCase()?s="localhost":p.split(".").length<=2?s=p:(d=i.indexOf("."),o=i.substring(0,d).toLowerCase(),s=i.substring(d+1),c=o),"ns"in f&&(c=f.ns)}return{host:i,port:h,domain:s,subdomain:o,secure:l,scheme:u,pathString:a,namespace:c}};class pS{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 gS{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 mS{constructor(e,t){this.snapshotCallback=e,this.cancelCallback=t}onValue(e,t){this.snapshotCallback.call(null,e,t)}onCancel(e){return Jh(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 vS{constructor(e,t){this._repo=e,this._path=t}cancel(){const e=new rd;return XE(this._repo,this._path,e.wrapCallback(()=>{})),e.promise}remove(){SE("OnDisconnect.remove",this._path);const e=new rd;return ZE(this._repo,this._path,null,e.wrapCallback(()=>{})),e.promise}set(e){SE("OnDisconnect.set",this._path),wE("OnDisconnect.set",e,this._path,!1);const t=new rd;return ZE(this._repo,this._path,e,t.wrapCallback(()=>{})),t.promise}setWithPriority(e,t){SE("OnDisconnect.setWithPriority",this._path),wE("OnDisconnect.setWithPriority",e,this._path,!1),IE("OnDisconnect.setWithPriority",t,!1);const n=new rd;return function(n,r,e,t,i){const s=HI(e,t);n.server_.onDisconnectPut(r.toString(),s.val(!0),(e,t)=>{"ok"===e&&_T(n.onDisconnect_,r,s),rS(0,i,e,t)})}(this._repo,this._path,e,t,n.wrapCallback(()=>{})),n.promise}update(e){SE("OnDisconnect.update",this._path),bE("OnDisconnect.update",e,this._path,!1);const t=new rd;return function(r,i,n,s){if(Td(n))return gb("onDisconnect().update() called with empty data. Don't do anything."),rS(0,s,"ok",void 0);r.server_.onDisconnectMerge(i.toString(),n,(e,t)=>{"ok"===e&&Tb(n,(e,t)=>{var n=HI(t);_T(r.onDisconnect_,aI(i,e),n)}),rS(0,s,e,t)})}(this._repo,this._path,e,t.wrapCallback(()=>{})),t.promise}}class yS{constructor(e,t,n,r){this._repo=e,this._path=t,this._queryParams=n,this._orderByCalled=r}get key(){return cI(this._path)?null:iI(this._path)}get ref(){return new IS(this._repo,this._path)}get _queryIdentifier(){var e=gT(this._queryParams),e=db(e);return"{}"===e?"default":e}get _queryObject(){return gT(this._queryParams)}isEqual(e){if(!((e=Kd(e))instanceof yS))return!1;var t=this._repo===e._repo,n=hI(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 _S(e,t){if(!0===e._orderByCalled)throw new Error(t+": You can't combine multiple orderBy calls.")}function wS(e){let t=null,n=null;if(e.hasStart()&&(t=e.getIndexStartValue()),e.hasEnd()&&(n=e.getIndexEndValue()),e.getIndex()===II){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()!==wb)throw new Error(r);if("string"!=typeof t)throw new Error(i)}if(e.hasEnd()){if(e.getIndexEndName()!==bb)throw new Error(r);if("string"!=typeof n)throw new Error(i)}}else if(e.getIndex()===LI){if(null!=t&&!xE(t)||null!=n&&!xE(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(Jh(e.getIndex()instanceof GI||e.getIndex()===JI,"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 bS(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 IS extends yS{constructor(e,t){super(e,t,new uT,!1)}get parent(){var e=oI(this._path);return null===e?null:new IS(this._repo,e)}get root(){let e=this;for(;null!==e.parent;)e=e.parent;return e}}class TS{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 Zb(e),n=kS(this.ref,e);return new TS(this._node.getChild(t),n,LI)}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 TS(t,kS(this.ref,e),LI)))}hasChild(e){var t=new Zb(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 ES(e,t){return(e=Kd(e))._checkNotDeleted("ref"),void 0!==t?kS(e._root,t):e._root}function SS(e,t){(e=Kd(e))._checkNotDeleted("refFromURL");const n=dS(t,e._repo.repoInfo_.nodeAdmin);LE("refFromURL",n);var r=n.repoInfo;return e._repo.repoInfo_.isCustomHost()||r.host===e._repo.repoInfo_.host||mb("refFromURL: Host name does not match the current database: (found "+r.host+" but expected "+e._repo.repoInfo_.host+")"),ES(e,n.path.toString())}function kS(e,t){return(null===tI((e=Kd(e))._path)?EE:DE)("child","path",t,!1),new IS(e._repo,aI(e._path,t))}function CS(e,t){e=Kd(e),SE("set",e._path),wE("set",t,e._path,!1);const n=new rd;return JE(e._repo,e._path,t,null,n.wrapCallback(()=>{})),n.promise}function AS(e,t){bE("update",t,e._path,!1);const n=new rd;return function(i,s,e,o){nS(i,"update",{path:s.toString(),value:e});let n=!0;const r=WE(i),a={};if(Tb(e,(e,t)=>{n=!1,a[e]=lE(aI(s,e),HI(t),i.serverSyncTree_,r)}),n)gb("update() called with empty data. Don't do anything."),rS(0,o,"ok",void 0);else{const c=YE(i);var t=V0(i.serverSyncTree_,s,a,c);FE(i.eventQueue_,t),i.server_.merge(s.toString(),e,(e,t)=>{var n="ok"===e;n||vb("update at "+s+" failed: "+e);var r=B0(i.serverSyncTree_,c,!n),n=0<r.length?oS(i,s):s;jE(i.eventQueue_,n,r),rS(0,o,e,t)}),Tb(e,e=>{var t=uS(i,aI(s,e));oS(i,t)}),jE(i.eventQueue_,s,[])}}(e._repo,e._path,t,n.wrapCallback(()=>{})),n.promise}function NS(t){return t=Kd(t),r=t._repo,i=t,(null!=(e=H0(r.serverSyncTree_,i))?Promise.resolve(e):r.server_.get(i).then(e=>{var t=HI(e).withIndex(i._queryParams.getIndex()),n=$0(r.serverSyncTree_,i._path,t);return UE(r.eventQueue_,i._path,n),Promise.resolve(t)},e=>(nS(r,"get for query "+_d(i)+" failed: "+e),Promise.reject(new Error(e))))).then(e=>new TS(e,new IS(t._repo,t._path),t._queryParams.getIndex()));var r,i,e}class RS{constructor(e){this.callbackContext=e}respondsTo(e){return"value"===e}createEvent(e,t){var n=t._queryParams.getIndex();return new pS("value",this,new TS(e.snapshotNode,new IS(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 gS(this,e,t):null}matches(e){return e instanceof RS&&(!e.callbackContext||!this.callbackContext||e.callbackContext.matches(this.callbackContext))}hasAnyCallback(){return null!==this.callbackContext}}class PS{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 gS(this,e,t):null}createEvent(e,t){Jh(null!=e.childName,"Child events should have a childName.");var n=kS(new IS(t._repo,t._path),e.childName),r=t._queryParams.getIndex();return new pS(e.type,this,new TS(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 PS&&(this.eventType===e.eventType&&(!this.callbackContext||!e.callbackContext||this.callbackContext.matches(e.callbackContext)))}hasAnyCallback(){return!!this.callbackContext}}function xS(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)=>{eS(n._repo,n,a),c(e,t)};o.userCallback=t.userCallback,o.context=t.context,t=o}o=new mS(t,s||void 0);const a="value"===e?new RS(o):new PS(e,o);return function(e,t,n){let r;r=".info"===tI(t._path)?z0(e.infoSyncTree_,t,n):z0(e.serverSyncTree_,t,n),UE(e.eventQueue_,t._path,r)}(n._repo,n,a),()=>eS(n._repo,n,a)}function OS(e,t,n,r){return xS(e,"value",t,n,r)}function DS(e,t,n,r){return xS(e,"child_added",t,n,r)}function LS(e,t,n,r){return xS(e,"child_changed",t,n,r)}function MS(e,t,n,r){return xS(e,"child_moved",t,n,r)}function FS(e,t,n,r){return xS(e,"child_removed",t,n,r)}function US(e,t,n){let r=null;var i=n?new mS(n):null;"value"===t?r=new RS(i):t&&(r=new PS(t,i)),eS(e._repo,e,r)}class jS{}class qS extends jS{constructor(e,t){super(),this._value=e,this._key=t}_apply(e){wE("endAt",this._value,e._path,!0);var t=dT(e._queryParams,this._value,this._key);if(bS(t),wS(t),e._queryParams.hasEnd())throw new Error("endAt: Starting point was already set (by another call to endAt, endBefore or equalTo).");return new yS(e._repo,e._path,t,e._orderByCalled)}}class VS extends jS{constructor(e,t){super(),this._value=e,this._key=t}_apply(e){wE("endBefore",this._value,e._path,!1);var t=function(e,t,n){let r,i;return i=e.index_===II?dT(e,t="string"==typeof t?YI(t):t,n):(r=null==n?wb:YI(n),dT(e,t,r)),i.endBeforeSet_=!0,i}(e._queryParams,this._value,this._key);if(bS(t),wS(t),e._queryParams.hasEnd())throw new Error("endBefore: Starting point was already set (by another call to endAt, endBefore or equalTo).");return new yS(e._repo,e._path,t,e._orderByCalled)}}class BS extends jS{constructor(e,t){super(),this._value=e,this._key=t}_apply(e){wE("startAt",this._value,e._path,!0);var t=hT(e._queryParams,this._value,this._key);if(bS(t),wS(t),e._queryParams.hasStart())throw new Error("startAt: Starting point was already set (by another call to startAt, startBefore or equalTo).");return new yS(e._repo,e._path,t,e._orderByCalled)}}class $S extends jS{constructor(e,t){super(),this._value=e,this._key=t}_apply(e){wE("startAfter",this._value,e._path,!1);var t=function(t,n,r){let i;if(t.index_===II)"string"==typeof n&&(n=QI(n)),i=hT(t,n,r);else{let e;e=null==r?bb:QI(r),i=hT(t,n,e)}return i.startAfterSet_=!0,i}(e._queryParams,this._value,this._key);if(bS(t),wS(t),e._queryParams.hasStart())throw new Error("startAfter: Starting point was already set (by another call to startAt, startAfter, or equalTo).");return new yS(e._repo,e._path,t,e._orderByCalled)}}class KS extends jS{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 yS(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 zS extends jS{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 yS(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 WS extends jS{constructor(e){super(),this._path=e}_apply(e){_S(e,"orderByChild");var t=new Zb(this._path);if(cI(t))throw new Error("orderByChild: cannot pass in empty path. Use orderByValue() instead.");t=new GI(t),t=fT(e._queryParams,t);return wS(t),new yS(e._repo,e._path,t,!0)}}class HS extends jS{_apply(e){_S(e,"orderByKey");var t=fT(e._queryParams,II);return wS(t),new yS(e._repo,e._path,t,!0)}}class GS extends jS{_apply(e){_S(e,"orderByPriority");var t=fT(e._queryParams,LI);return wS(t),new yS(e._repo,e._path,t,!0)}}class QS extends jS{_apply(e){_S(e,"orderByValue");var t=fT(e._queryParams,JI);return wS(t),new yS(e._repo,e._path,t,!0)}}class YS extends jS{constructor(e,t){super(),this._value=e,this._key=t}_apply(e){if(wE("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 qS(this._value,this._key)._apply(new BS(this._value,this._key)._apply(e))}}function JS(e,...t){let n=Kd(e);for(const r of t)n=r._apply(n);return n}Jw=IS,Jh(!S0,"__referenceConstructor has already been defined"),S0=Jw,Xw=IS,Jh(!F0,"__referenceConstructor has already been defined"),F0=Xw;const XS="FIREBASE_DATABASE_EMULATOR_HOST",ZS={};let ek=!1;function tk(e,t,n,r,i){let s=r||e.options.databaseURL;void 0===s&&(e.options.projectId||mb("Can't determine Firebase Database URL. Be sure to include a Project ID when calling firebase.initializeApp()."),gb("Using default host for project ",e.options.projectId),s=`${e.options.projectId}-default-rtdb.firebaseio.com`);let o=dS(s,i),a=o.repoInfo,c,l=void 0;"undefined"!=typeof process&&(l=process.env[XS]),l?(c=!0,s=`http://${l}?ns=${a.namespace}`,o=dS(s,i),a=o.repoInfo):c=!o.repoInfo.secure;var u=i&&c?new Ob(Ob.OWNER):new xb(e.name,e.options,t);LE("Invalid Firebase Database URL",o),cI(o.path)||mb("Database URL must point to the root of a Firebase Database (not including a child path).");u=function(e,t,n,r){let i=ZS[t.name];i||(i={},ZS[t.name]=i);var s=i[e.toURLString()];s&&mb("Database initialized multiple times. Please make sure the format of the database URL matches with each database() call.");return s=new $E(e,ek,n,r),i[e.toURLString()]=s}(a,e,u,new Pb(e.name,n));return new nk(u,e)}class nk{constructor(e,t){this._repoInternal=e,this.app=t,this.type="database",this._instanceStarted=!1}get _repo(){return this._instanceStarted||(KE(this._repoInternal,this.app.options.appId,this.app.options.databaseAuthVariableOverride),this._instanceStarted=!0),this._repoInternal}get _root(){return this._rootInternal||(this._rootInternal=new IS(this._repo,eI())),this._rootInternal}_delete(){return null!==this._rootInternal&&(function(e,t){const n=ZS[t];n&&n[e.key]===e||mb(`Database ${t}(${e.repoInfo_}) has already been deleted.`),tS(e),delete n[e.key]}(this._repo,this.app.name),this._repoInternal=null,this._rootInternal=null),Promise.resolve()}_checkNotDeleted(e){null===this._rootInternal&&mb("Cannot call "+e+" on a deleted database.")}}function rk(e,t,n,r={}){(e=Kd(e))._checkNotDeleted("useEmulator"),e._instanceStarted&&mb("Cannot call useEmulator() after instance has already been initialized.");var i,s=e._repoInternal;let o=void 0;s.repoInfo_.nodeAdmin?(r.mockUserToken&&mb('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 Ob(Ob.OWNER)):r.mockUserToken&&(i="string"==typeof r.mockUserToken?r.mockUserToken:id(r.mockUserToken,e.app.options.projectId),o=new Ob(i)),r=s,e=t,t=n,n=o,r.repoInfo_=new Fb(`${e}:${t}`,!1,r.repoInfo_.namespace,r.repoInfo_.webSocketOnly,r.repoInfo_.nodeAdmin,r.repoInfo_.persistenceKey,r.repoInfo_.includeNamespaceInQueryParams),n&&(r.authTokenProvider_=n)}function ik(e){(e=Kd(e))._checkNotDeleted("goOnline"),(e=e._repo).persistentConnection_&&e.persistentConnection_.resume(VE)}function sk(e,t){pb(e,t)}const ok={".sv":"timestamp"};class ak{constructor(e,t){this.committed=e,this.snapshot=t}toJSON(){return{committed:this.committed,snapshot:this.snapshot.toJSON()}}}function ck(i,e,t){if(i=Kd(i),SE("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=OS(i,()=>{});return function(t,n,e,r,i,s){nS(t,"transaction on "+n);const o={path:n,update:e,onComplete:r,status:null,order:ib(),applyLocally:s,retryCount:0,unwatcher:i,abortReason:null,currentWriteId:null,currentInputSnapshot:null,currentOutputSnapshotRaw:null,currentOutputSnapshotResolved:null},a=iS(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{OE("transaction failed: Data returned ",c,o.path),o.status=0;var l=fE(t.transactionQueueTree_,n);const u=pE(l)||[];u.push(o),gE(l,u);let e;if("object"==typeof c&&null!==c&&bd(c,".priority"))e=Id(c,".priority"),Jh(xE(e),"Invalid priority returned by transaction. Priority must be a valid string, finite number, server value, or null.");else{const h=W0(t.serverSyncTree_,n)||$I.EMPTY_NODE;e=h.getPriority().val()}l=WE(t),c=HI(c,e),l=uE(c,a,l);o.currentOutputSnapshotRaw=c,o.currentOutputSnapshotResolved=l,o.currentWriteId=YE(t);l=q0(t.serverSyncTree_,n,l,o.currentWriteId,o.applyLocally);jE(t.eventQueue_,n,l),sS(t,t.transactionQueueTree_)}}(i._repo,i._path,e,(e,t,n)=>{var r;e?s.reject(e):(r=new TS(n,new IS(i._repo,i._path),LI),s.resolve(new ak(t,r)))},r,n),s.promise}vI.prototype.simpleListen=function(e,t){this.sendRequest("q",{p:e},t)},vI.prototype.echo=function(e,t){this.sendRequest("echo",{d:e},t)},zw(mf),df(new zd("database",(e,{instanceIdentifier:t})=>{return tk(e.getProvider("app").getImmediate(),e.getProvider("auth-internal"),e.getProvider("app-check-internal"),t)},"PUBLIC").setMultipleInstances(!0)),wf($w,"0.12.4",Zw),wf($w,"0.12.4","esm2017");function lk(e){var t="FIREBASE WARNING: "+e;uk.warn(t)}const uk=new ef("@firebase/database-compat");class hk{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,lk("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 dk{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 fk{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),DE("DataSnapshot.child","path",e,!1),new fk(this._database,this._delegate.child(e))}hasChild(e){return Dd("DataSnapshot.hasChild",1,1,arguments.length),DE("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 fk(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 gk(this._database,this._delegate.ref)}get ref(){return this.getRef()}}class pk{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=pk.getCancelAndContextArgs_("Query.on",t,r);var o=(e,t)=>{n.call(s.context,new fk(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 OS(this._delegate,o,a),n;case"child_added":return DS(this._delegate,o,a),n;case"child_removed":return FS(this._delegate,o,a),n;case"child_changed":return LS(this._delegate,o,a),n;case"child_moved":return MS(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,US(this._delegate,e,r)):US(this._delegate,e)}get(){return NS(this._delegate).then(e=>new fk(this.database,e))}once(e,r,t,n){Dd("Query.once",1,4,arguments.length),Md("Query.once","callback",r,!0);const i=pk.getCancelAndContextArgs_("Query.once",t,n),s=new rd;var o=(e,t)=>{var n=new fk(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":OS(this._delegate,o,a,{onlyOnce:!0});break;case"child_added":DS(this._delegate,o,a,{onlyOnce:!0});break;case"child_removed":FS(this._delegate,o,a,{onlyOnce:!0});break;case"child_changed":LS(this._delegate,o,a,{onlyOnce:!0});break;case"child_moved":MS(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 pk(this.database,JS(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 KS(e)}(e)))}limitToLast(e){return Dd("Query.limitToLast",1,1,arguments.length),new pk(this.database,JS(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 zS(e)}(e)))}orderByChild(e){return Dd("Query.orderByChild",1,1,arguments.length),new pk(this.database,JS(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 DE("orderByChild","path",e,!1),new WS(e)}(e)))}orderByKey(){return Dd("Query.orderByKey",0,0,arguments.length),new pk(this.database,JS(this._delegate,new HS))}orderByPriority(){return Dd("Query.orderByPriority",0,0,arguments.length),new pk(this.database,JS(this._delegate,new GS))}orderByValue(){return Dd("Query.orderByValue",0,0,arguments.length),new pk(this.database,JS(this._delegate,new QS))}startAt(e=null,t){return Dd("Query.startAt",0,2,arguments.length),new pk(this.database,JS(this._delegate,([e=null,t]=[e,t],TE("startAt","key",t,!0),new BS(e,t))))}startAfter(e=null,t){return Dd("Query.startAfter",0,2,arguments.length),new pk(this.database,JS(this._delegate,(e=e,t=t,TE("startAfter","key",t,!0),new $S(e,t))))}endAt(e=null,t){return Dd("Query.endAt",0,2,arguments.length),new pk(this.database,JS(this._delegate,(e=e,t=t,TE("endAt","key",t,!0),new qS(e,t))))}endBefore(e=null,t){return Dd("Query.endBefore",0,2,arguments.length),new pk(this.database,JS(this._delegate,(e=e,t=t,TE("endBefore","key",t,!0),new VS(e,t))))}equalTo(e,t){return Dd("Query.equalTo",1,2,arguments.length),new pk(this.database,JS(this._delegate,(e=e,t=t,TE("equalTo","key",t,!0),new YS(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 pk)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 gk(this.database,new IS(this._delegate._repo,this._delegate._path))}}class gk extends pk{constructor(e,t){super(e,new yS(t._repo,t._path,new uT,!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 gk(this.database,kS(this._delegate,e))}getParent(){Dd("Reference.parent",0,0,arguments.length);var e=this._delegate.parent;return e?new gk(this.database,e):null}getRoot(){return Dd("Reference.root",0,0,arguments.length),new gk(this.database,this._delegate.root)}set(e,t){Dd("Reference.set",1,2,arguments.length),Md("Reference.set","onComplete",t,!0);const n=CS(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,lk("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.")}SE("Reference.update",this._delegate._path),Md("Reference.update","onComplete",n,!0);const e=AS(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(SE("setWithPriority",e._path),wE("setWithPriority",t,e._path,!1),IE("setWithPriority",n,!1),".length"===e.key||".keys"===e.key)throw"setWithPriority failed: "+e.key+" is a read-only object.";const r=new rd;return JE(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,SE("remove",n._path),CS(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=ck(this._delegate,e,{applyLocally:n}).then(e=>new dk(e.committed,new fk(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=Kd(e),SE("setPriority",e._path),IE("setPriority",t,!1);const n=new rd;return JE(e._repo,aI(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=Kd(e),SE("push",e._path),wE("push",t,e._path,!0);var n=zE(e._repo),n=nT(n);const r=kS(e,n),i=kS(e,n);let s;return s=null!=t?CS(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 gk(this.database,e));t&&r.then(()=>t(null),e=>t(e));const i=new gk(this.database,n);return i.then=r.then.bind(r),i.catch=r.catch.bind(r,void 0),i}onDisconnect(){return SE("Reference.onDisconnect",this._delegate._path),new hk(new vS(this._delegate._repo,this._delegate._path))}get key(){return this.getKey()}get parent(){return this.getParent()}get root(){return this.getRoot()}}class mk{constructor(e,t){this._delegate=e,this.app=t,this.INTERNAL={delete:()=>this._delegate._delete()}}useEmulator(e,t,n={}){rk(this._delegate,e,t,n)}ref(e){if(Dd("database.ref",0,1,arguments.length),e instanceof gk){var t=SS(this._delegate,e.toString());return new gk(this,t)}t=ES(this._delegate,e);return new gk(this,t)}refFromURL(e){Dd("database.refFromURL",1,1,arguments.length);var t=SS(this._delegate,e);return new gk(this,t)}goOffline(){var e;Dd("database.goOffline",0,0,arguments.length),(e=Kd(e=this._delegate))._checkNotDeleted("goOffline"),tS(e._repo)}goOnline(){return Dd("database.goOnline",0,0,arguments.length),ik(this._delegate)}}mk.ServerValue={TIMESTAMP:ok,increment:e=>({".sv":{increment:e}})};var vk,yk=Object.freeze({__proto__:null,initStandalone:function({app:e,url:t,version:n,customAuthImpl:r,namespace:i,nodeAdmin:s=!1}){zw(n);const o=new Hd("auth-internal",new Gd("database-standalone"));return o.setComponent(new zd("auth-internal",()=>r,"PRIVATE")),{instance:new mk(tk(e,o,void 0,t,s),e),namespace:i}}});const _k=mk.ServerValue;(vk=Af).INTERNAL.registerComponent(new zd("database-compat",(e,{instanceIdentifier:t})=>{var n=e.getProvider("app-compat").getImmediate(),r=e.getProvider("database").getImmediate({identifier:t});return new mk(r,n)},"PUBLIC").setServiceProps({Reference:gk,Query:pk,Database:mk,DataSnapshot:fk,enableLogging:sk,INTERNAL:yk,ServerValue:_k}).setMultipleInstances(!0)),vk.registerVersion("@firebase/database-compat","0.1.4");var l="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},wk={},bk=l||self;function Ik(){}function Tk(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 Ek(e){var t=typeof e;return"object"==t&&null!=e||"function"==t}var Sk="closure_uid_"+(1e9*Math.random()>>>0),kk=0;function Ck(e,t,n){return e.call.apply(e.bind,arguments)}function Ak(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 Nk(e,t,n){return(Nk=Function.prototype.bind&&-1!=Function.prototype.bind.toString().indexOf("native code")?Ck:Ak).apply(null,arguments)}function Rk(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 Pk(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 xk(){this.s=this.s,this.o=this.o}var Ok={};xk.prototype.s=!1,xk.prototype.na=function(){var e,t;!this.s&&(this.s=!0,this.M(),0)&&(t=this,e=Object.prototype.hasOwnProperty.call(t,Sk)&&t[Sk]||(t[Sk]=++kk),delete Ok[e])},xk.prototype.M=function(){if(this.o)for(;this.o.length;)this.o.shift()()};const Dk=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},Lk=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 Mk(){return Array.prototype.concat.apply([],arguments)}function Fk(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 Uk(e){return/^[\s\xa0]*$/.test(e)}var jk,qk=String.prototype.trim?function(e){return e.trim()}:function(e){return/^[\s\xa0]*([\s\S]*?)[\s\xa0]*$/.exec(e)[1]};function Vk(e,t){return-1!=e.indexOf(t)}function Bk(e,t){return e<t?-1:t<e?1:0}e:{var $k=bk.navigator;if($k){$k=$k.userAgent;if($k){jk=$k;break e}}jk=""}function Kk(e,t,n){for(const r in e)t.call(n,e[r],r,e)}function zk(e){const t={};for(const n in e)t[n]=e[n];return t}var Wk="constructor hasOwnProperty isPrototypeOf propertyIsEnumerable toLocaleString toString valueOf".split(" ");function Hk(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<Wk.length;e++)n=Wk[e],Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=r[n])}}function Gk(e){return Gk[" "](e),e}Gk[" "]=Ik;var Qk,Yk=Vk(jk,"Opera"),Jk=Vk(jk,"Trident")||Vk(jk,"MSIE"),Xk=Vk(jk,"Edge"),Zk=Xk||Jk,eC=Vk(jk,"Gecko")&&!(Vk(jk.toLowerCase(),"webkit")&&!Vk(jk,"Edge"))&&!(Vk(jk,"Trident")||Vk(jk,"MSIE"))&&!Vk(jk,"Edge"),tC=Vk(jk.toLowerCase(),"webkit")&&!Vk(jk,"Edge");function nC(){var e=bk.document;return e?e.documentMode:void 0}e:{var rC="",iC=(iC=jk,eC?/rv:([^\);]+)(\)|;)/.exec(iC):Xk?/Edge\/([\d\.]+)/.exec(iC):Jk?/\b(?:MSIE|rv)[: ]([^\);]+)(\)|;)/.exec(iC):tC?/WebKit\/(\S+)/.exec(iC):Yk?/(?:Version)[ \/]?(\S+)/.exec(iC):void 0);if(iC&&(rC=iC?iC[1]:""),Jk){iC=nC();if(null!=iC&&iC>parseFloat(rC)){Qk=String(iC);break e}}Qk=rC}var sC={};function oC(){return e=function(){let e=0;var t=qk(String(Qk)).split("."),n=qk("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=Bk(0==i[1].length?0:parseInt(i[1],10),0==s[1].length?0:parseInt(s[1],10))||Bk(0==i[2].length,0==s[2].length)||Bk(i[2],s[2]),i=i[3],s=s[3],0==e););return 0<=e},t=sC,Object.prototype.hasOwnProperty.call(t,9)?t[9]:t[9]=e(9);var e,t}var aC=bk.document&&Jk&&(nC()||parseInt(Qk,10))||void 0,cC=function(){if(!bk.addEventListener||!Object.defineProperty)return!1;var e=!1,t=Object.defineProperty({},"passive",{get:function(){e=!0}});try{bk.addEventListener("test",Ik,t),bk.removeEventListener("test",Ik,t)}catch(e){}return e}();function lC(e,t){this.type=e,this.g=this.target=t,this.defaultPrevented=!1}function uC(e,t){if(lC.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(eC){e:{try{Gk(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:hC[e.pointerType]||"",this.state=e.state,(this.i=e).defaultPrevented&&uC.Z.h.call(this)}}lC.prototype.h=function(){this.defaultPrevented=!0},Pk(uC,lC);var hC={2:"touch",3:"pen",4:"mouse"};uC.prototype.h=function(){uC.Z.h.call(this);var e=this.i;e.preventDefault?e.preventDefault():e.returnValue=!1};var dC="closure_listenable_"+(1e6*Math.random()|0),fC=0;function pC(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=++fC,this.ca=this.fa=!1}function gC(e){e.ca=!0,e.listener=null,e.proxy=null,e.src=null,e.ia=null}function mC(e){this.src=e,this.g={},this.h=0}function vC(e,t){var n,r,i,s=t.type;s in e.g&&(n=e.g[s],(i=0<=(r=Dk(n,t)))&&Array.prototype.splice.call(n,r,1),i&&(gC(t),0==e.g[s].length&&(delete e.g[s],e.h--)))}function yC(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}mC.prototype.add=function(e,t,n,r,i){var s=e.toString();(e=this.g[s])||(e=this.g[s]=[],this.h++);var o=yC(e,t,r,i);return-1<o?(t=e[o],n||(t.fa=!1)):((t=new pC(t,this.src,s,!!r,i)).fa=n,e.push(t)),t};var _C="closure_lm_"+(1e6*Math.random()|0),wC={};function bC(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=AC(r);return t&&t[dC]?t.O(n,r,Ek(i)?!!i.capture:!!i,s):IC(t,n,r,!0,i,s)}(e,t,n,r,i);if(Array.isArray(t)){for(var s=0;s<t.length;s++)bC(e,t[s],n,r,i);return null}return n=AC(n),e&&e[dC]?e.N(t,n,Ek(r)?!!r.capture:!!r,i):IC(e,t,n,!1,r,i)}function IC(e,t,n,r,i,s){if(!t)throw Error("Invalid event type");var o,a=Ek(i)?!!i.capture:!!i,c=kC(e);if(c||(e[_C]=c=new mC(e)),(n=c.add(t,n,r,a,s)).proxy)return n;if(o=SC,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=!cC?a:i)&&(i=!1),e.addEventListener(t.toString(),r,i);else if(e.attachEvent)e.attachEvent(EC(t.toString()),r);else{if(!e.addListener||!e.removeListener)throw Error("addEventListener and attachEvent are unavailable.");e.addListener(r)}return n}function TC(e){var t,n,r;"number"!=typeof e&&e&&!e.ca&&((t=e.src)&&t[dC]?vC(t.i,e):(n=e.type,r=e.proxy,t.removeEventListener?t.removeEventListener(n,r,e.capture):t.detachEvent?t.detachEvent(EC(n),r):t.addListener&&t.removeListener&&t.removeListener(r),(n=kC(t))?(vC(n,e),0==n.h&&(n.src=null,t[_C]=null)):gC(e)))}function EC(e){return e in wC?wC[e]:wC[e]="on"+e}function SC(e,t){var n,r;return e=!!e.ca||(t=new uC(t,this),n=e.listener,r=e.ia||e.src,e.fa&&TC(e),n.call(r,t))}function kC(e){return(e=e[_C])instanceof mC?e:null}var CC="__closure_events_fn_"+(1e9*Math.random()>>>0);function AC(t){return"function"==typeof t?t:(t[CC]||(t[CC]=function(e){return t.handleEvent(e)}),t[CC])}function NC(){xk.call(this),this.i=new mC(this),(this.P=this).I=null}function RC(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 lC(t,e):t instanceof lC?t.target=t.target||e:(o=t,Hk(t=new lC(r,e),o)),o=!0,n)for(var i=n.length-1;0<=i;i--)var s=t.g=n[i],o=PC(s,r,!0,t)&&o;if(o=PC(s=t.g=e,r,!0,t)&&o,o=PC(s,r,!1,t)&&o,n)for(i=0;i<n.length;i++)o=PC(s=t.g=n[i],r,!1,t)&&o}function PC(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&&vC(e.i,c),i=!1!==o.call(a,r)&&i)}return i&&!r.defaultPrevented}Pk(NC,xk),NC.prototype[dC]=!0,NC.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=Ek(i)?!!i.capture:!!i,r=AC(r),t&&t[dC]?(t=t.i,(n=String(n).toString())in t.g&&-1<(r=yC(o=t.g[n],r,i,s))&&(gC(o[r]),Array.prototype.splice.call(o,r,1),0==o.length&&(delete t.g[n],t.h--))):(t=t&&kC(t))&&(n=t.g[n.toString()],(r=(t=-1)<(t=n?yC(n,r,i,s):t)?n[t]:null)&&TC(r))}(this,e,t,n,r)},NC.prototype.M=function(){if(NC.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++)gC(n[r]);delete t.g[e],t.h--}}this.I=null},NC.prototype.N=function(e,t,n,r){return this.i.add(String(e),t,!1,n,r)},NC.prototype.O=function(e,t,n,r){return this.i.add(String(e),t,!0,n,r)};var xC=bk.JSON.stringify;var OC,DC=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 LC,e=>e.reset());class LC{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 MC(e,t){var n;OC||(n=bk.Promise.resolve(void 0),OC=function(){n.then(jC)}),FC||(OC(),FC=!0),UC.add(e,t)}var FC=!1,UC=new class{constructor(){this.h=this.g=null}add(e,t){const n=DC.get();n.set(e,t),this.h?this.h.next=n:this.g=n,this.h=n}};function jC(){for(var e;e=function(){var e=UC;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){bk.setTimeout(()=>{throw e},0)}(e)}var t=DC;t.j(e),t.h<100&&(t.h++,e.next=t.g,t.g=e)}FC=!1}function qC(e,t){NC.call(this),this.h=e||1,this.g=t||bk,this.j=Nk(this.kb,this),this.l=Date.now()}function VC(e){e.da=!1,e.S&&(e.g.clearTimeout(e.S),e.S=null)}function BC(e,t,n){if("function"==typeof e)n&&(e=Nk(e,n));else{if(!e||"function"!=typeof e.handleEvent)throw Error("Invalid listener argument");e=Nk(e.handleEvent,e)}return 2147483647<Number(t)?-1:bk.setTimeout(e,t||0)}Pk(qC,NC),(We=qC.prototype).da=!1,We.S=null,We.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),RC(this,"tick"),this.da&&(VC(this),this.start())))},We.start=function(){this.da=!0,this.S||(this.S=this.g.setTimeout(this.j,this.h),this.l=Date.now())},We.M=function(){qC.Z.M.call(this),VC(this),delete this.g};class $C extends xk{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=BC(()=>{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&&(bk.clearTimeout(this.g),this.g=null,this.i=!1,this.h=null)}}function KC(e){xk.call(this),this.h=e,this.g={}}Pk(KC,xk);var zC=[];function WC(e,t,n,r){Array.isArray(n)||(n&&(zC[0]=n.toString()),n=zC);for(var i=0;i<n.length;i++){var s=bC(t,n[i],r||e.handleEvent,!1,e.h||e);if(!s)break;e.g[s.key]=s}}function HC(e){Kk(e.g,function(e,t){this.g.hasOwnProperty(t)&&TC(e)},e),e.g={}}function GC(){this.g=!0}function QC(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 xC(n)}catch(e){return t}}(e,n)+(r?" "+r:"")})}KC.prototype.M=function(){KC.Z.M.call(this),HC(this)},KC.prototype.handleEvent=function(){throw Error("EventHandler.handleEvent not implemented")},GC.prototype.Aa=function(){this.g=!1},GC.prototype.info=function(){};var YC={},JC=null;function XC(){return JC=JC||new NC}function ZC(e){lC.call(this,YC.Ma,e)}function eA(){var e=XC();RC(e,new ZC(e))}function tA(e,t){lC.call(this,YC.STAT_EVENT,e),this.stat=t}function nA(e){var t=XC();RC(t,new tA(t,e))}function rA(e,t){lC.call(this,YC.Na,e),this.size=t}function iA(e,t){if("function"!=typeof e)throw Error("Fn must not be null and must be a function");return bk.setTimeout(function(){e()},t)}YC.Ma="serverreachability",Pk(ZC,lC),YC.STAT_EVENT="statevent",Pk(tA,lC),YC.Na="timingevent",Pk(rA,lC);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 sA(){}function oA(e){return e.h||(e.h=e.i())}function aA(){}sA.prototype.h=null;l={OPEN:"a",pb:"b",Ka:"c",Bb:"d"};function cA(){lC.call(this,"d")}function lA(){lC.call(this,"c")}function uA(){}function hA(e,t,n,r){this.l=e,this.j=t,this.m=n,this.X=r||1,this.V=new KC(this),this.P=pA,this.W=new qC(e=Zk?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 dA}function dA(){this.i=null,this.g="",this.h=!1}Pk(cA,lC),Pk(lA,lC),Pk(uA,sA),uA.prototype.g=function(){return new XMLHttpRequest},uA.prototype.i=function(){return{}};var fA=new uA,pA=45e3,gA={},mA={};function vA(e,t,n){e.K=1,e.v=jA(OA(t)),e.s=n,e.U=!0,yA(e,null)}function yA(e,t){e.F=Date.now(),bA(e),e.A=OA(e.v);var o,a,c,l,u,h,n=e.A,r=e.X;Array.isArray(r)||(r=[String(r)]),XA(n.h,"t",r),e.C=0,n=e.l.H,e.h=new dA,e.g=XN(e.l,n?t:null,!e.s),0<e.O&&(e.L=new $C(Nk(e.Ia,e,e.g),e.O)),WC(e.V,e.g,"readystatechange",e.gb),t=e.H?zk(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)),eA(),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 _A(e){return e.g&&("GET"==e.u&&2!=e.K&&e.l.Ba)}function wA(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))?mA:(a=Number(o.substring(a,c)),isNaN(a)?gA:(c+=1)+a>o.length?mA:(o=o.substr(c,a),s.C=c+a,o))),i==mA){4==t&&(e.o=4,nA(14),r=!1),QC(e.j,e.m,null,"[Incomplete Response]");break}if(i==gA){e.o=4,nA(15),QC(e.j,e.m,n,"[Invalid Chunk]"),r=!1;break}QC(e.j,e.m,i,null),kA(e,i)}var s,o,a,c;_A(e)&&i!=mA&&i!=gA&&(e.h.g="",e.C=0),4!=t||0!=n.length||e.h.h||(e.o=1,nA(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),KN(t),t.L=!0,nA(11))):(QC(e.j,e.m,n,"[Invalid Chunked Response]"),SA(e),EA(e))}function bA(e){e.Y=Date.now()+e.P,IA(e,e.P)}function IA(e,t){if(null!=e.B)throw Error("WatchDog timer not null");e.B=iA(Nk(e.eb,e),t)}function TA(e){e.B&&(bk.clearTimeout(e.B),e.B=null)}function EA(e){0==e.l.G||e.I||HN(e.l,e)}function SA(e){TA(e);var t=e.L;t&&"function"==typeof t.na&&t.na(),e.L=null,VC(e.W),HC(e.V),e.g&&(t=e.g,e.g=null,t.abort(),t.na())}function kA(e,t){try{var n=e.l;if(0!=n.G&&(n.g==e||sN(n.i,e)))if(n.I=e.N,!e.J&&sN(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;WN(n),LN(n)}$N(n),nA(18)}}else n.ta=i[1],0<n.ta-n.U&&i[2]<37500&&n.N&&0==n.A&&!n.v&&(n.v=iA(Nk(n.ab,n),6e3));if(iN(n.i)<=1&&n.ka){try{n.ka()}catch(e){}n.ka=void 0}}else QN(n,11)}else if(!e.J&&n.g!=e||WN(n),!Uk(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&&(Vk(c,"spdy")||Vk(c,"quic")||Vk(c,"h2"))&&(l.j=l.l,l.g=new Set,l.h&&(oN(l,l.h),l.h=null)),!r.D||(u=g.g?g.g.getResponseHeader("X-HTTP-Session-Id"):null)&&(r.sa=u,UA(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,f,p=e;(r=n).oa=JN(r,r.H?r.la:null,r.W),p.J?(aN(r.i,p),d=p,(f=r.K)&&d.setTimeout(f),d.B&&(TA(d),bA(d)),r.g=p):BN(r),0<n.l.length&&UN(n)}else"stop"!=s[0]&&"close"!=s[0]||QN(n,7);else 3==n.G&&("stop"==s[0]||"close"==s[0]?"stop"==s[0]?QN(n,7):DN(n):"noop"!=s[0]&&n.j&&n.j.wa(s),n.A=0)}eA()}catch(e){}}function CA(e,t){if(e.forEach&&"function"==typeof e.forEach)e.forEach(t,void 0);else if(Tk(e)||"string"==typeof e)Lk(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(Tk(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(Tk(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 AA(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 AA)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 NA(e){if(e.i!=e.g.length){for(var t=0,n=0;t<e.g.length;){var r=e.g[t];RA(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;)RA(i,r=e.g[t])||(i[e.g[n++]=r]=1),t++;e.g.length=n}}function RA(e,t){return Object.prototype.hasOwnProperty.call(e,t)}(We=hA.prototype).setTimeout=function(e){this.P=e},We.gb=function(e){e=e.target;const t=this.L;t&&3==NN(e)?t.l():this.Ia(e)},We.Ia=function(e){try{if(e==this.g)e:{var t=NN(this.g),n=this.g.Da();this.g.ba();if(!(t<3)&&(3!=t||Zk||this.g&&(this.h.h||this.g.ga()||RN(this.g)))){this.I||4!=t||7==n||eA(),TA(this);var r=this.g.ba();this.N=r;t:if(_A(this)){var i=RN(this.g);e="";var s=i.length,o=4==NN(this.g);if(!this.h.i){if("undefined"==typeof TextDecoder){SA(this),EA(this);var a="";break t}this.h.i=new bk.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,f=this.A,p=this.m,g=this.X,m=t,v=r,h.info(function(){return"XMLHTTP RESP ("+p+") [ attempt "+g+"]: "+d+"\n"+f+"\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)&&!Uk(c)){var u=c;break t}}u=null}if(!(r=u)){this.i=!1,this.o=3,nA(12),SA(this),EA(this);break e}QC(this.j,this.m,r,"Initial handshake response via X-HTTP-Initial-Response"),this.J=!0,kA(this,r)}this.U?(wA(this,t,a),Zk&&this.i&&3==t&&(WC(this.V,this.W,"tick",this.fb),this.W.start())):(QC(this.j,this.m,a,null),kA(this,a)),4==t&&SA(this),this.i&&!this.I&&(4==t?HN(this.l,this):(this.i=!1,bA(this)))}else 400==r&&0<a.indexOf("Unknown SID")?(this.o=3,nA(12)):(this.o=0,nA(13)),SA(this),EA(this)}}}catch(e){}var h,d,f,p,g,m,v},We.fb=function(){var e,t;this.g&&(e=NN(this.g),t=this.g.ga(),this.C<t.length&&(TA(this),wA(this,e,t),this.i&&4!=e&&bA(this)))},We.cancel=function(){this.I=!0,SA(this)},We.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&&(eA(),nA(17)),SA(this),this.o=2,EA(this)):IA(this,this.Y-n)},(We=AA.prototype).R=function(){NA(this);for(var e=[],t=0;t<this.g.length;t++)e.push(this.h[this.g[t]]);return e},We.T=function(){return NA(this),this.g.concat()},We.get=function(e,t){return RA(this.h,e)?this.h[e]:t},We.set=function(e,t){RA(this.h,e)||(this.i++,this.g.push(e)),this.h[e]=t},We.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 PA=/^(?:([^:/?#.]+):)?(?:\/\/(?:([^\\/?#]*)@)?([^\\/?#]*?)(?::([0-9]+))?(?=[\\/?#]|$))?([^?#]+)?(?:\?([^#]*))?(?:#([\s\S]*))?$/;function xA(e,t){var n;this.i=this.s=this.j="",this.m=null,this.o=this.l="",this.g=!1,e instanceof xA?(this.g=void 0!==t?t:e.g,DA(this,e.j),this.s=e.s,LA(this,e.i),MA(this,e.m),this.l=e.l,t=e.h,(n=new GA).i=t.i,t.g&&(n.g=new AA(t.g),n.h=t.h),FA(this,n),this.o=e.o):e&&(n=String(e).match(PA))?(this.g=!!t,DA(this,n[1]||"",!0),this.s=qA(n[2]||""),LA(this,n[3]||"",!0),MA(this,n[4]),this.l=qA(n[5]||"",!0),FA(this,n[6]||"",!0),this.o=qA(n[7]||"")):(this.g=!!t,this.h=new GA(null,this.g))}function OA(e){return new xA(e)}function DA(e,t,n){e.j=n?qA(t,!0):t,e.j&&(e.j=e.j.replace(/:$/,""))}function LA(e,t,n){e.i=n?qA(t,!0):t}function MA(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 FA(e,t,n){var r,i;t instanceof GA?(e.h=t,r=e.h,(i=e.g)&&!r.j&&(QA(r),r.i=null,r.g.forEach(function(e,t){var n=t.toLowerCase();t!=n&&(YA(this,t),XA(this,n,e))},r)),r.j=i):(n||(t=VA(t,WA)),e.h=new GA(t,e.g))}function UA(e,t,n){e.h.set(t,n)}function jA(e){return UA(e,"zx",Math.floor(2147483648*Math.random()).toString(36)+Math.abs(Math.floor(2147483648*Math.random())^Date.now()).toString(36)),e}function qA(e,t){return e?t?decodeURI(e.replace(/%25/g,"%2525")):decodeURIComponent(e):""}function VA(e,t,n){return"string"==typeof e?(e=encodeURI(e).replace(t,BA),e=n?e.replace(/%25([0-9a-fA-F]{2})/g,"%$1"):e):null}function BA(e){return"%"+((e=e.charCodeAt(0))>>4&15).toString(16)+(15&e).toString(16)}xA.prototype.toString=function(){var e=[],t=this.j;t&&e.push(VA(t,$A,!0),":");var n=this.i;return!n&&"file"!=t||(e.push("//"),(t=this.s)&&e.push(VA(t,$A,!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(VA(n,"/"==n.charAt(0)?zA:KA,!0))),(n=this.h.toString())&&e.push("?",n),(n=this.o)&&e.push("#",VA(n,HA)),e.join("")};var $A=/[#\/\?@]/g,KA=/[#\?:]/g,zA=/[#\?]/g,WA=/[#\?@]/g,HA=/#/g;function GA(e,t){this.h=this.g=null,this.i=e||null,this.j=!!t}function QA(n){n.g||(n.g=new AA,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 YA(e,t){QA(e),t=ZA(e,t),RA(e.g.h,t)&&(e.i=null,e.h-=e.g.get(t).length,RA((e=e.g).h,t)&&(delete e.h[t],e.i--,e.g.length>2*e.i&&NA(e)))}function JA(e,t){return QA(e),t=ZA(e,t),RA(e.g.h,t)}function XA(e,t,n){YA(e,t),0<n.length&&(e.i=null,e.g.set(ZA(e,t),Fk(n)),e.h+=n.length)}function ZA(e,t){return t=String(t),t=e.j?t.toLowerCase():t}(We=GA.prototype).add=function(e,t){QA(this),this.i=null,e=ZA(this,e);var n=this.g.get(e);return n||this.g.set(e,n=[]),n.push(t),this.h+=1,this},We.forEach=function(n,r){QA(this),this.g.forEach(function(e,t){Lk(e,function(e){n.call(r,e,t,this)},this)},this)},We.T=function(){QA(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},We.R=function(e){QA(this);var t=[];if("string"==typeof e)JA(this,e)&&(t=Mk(t,this.g.get(ZA(this,e))));else{e=this.g.R();for(var n=0;n<e.length;n++)t=Mk(t,e[n])}return t},We.set=function(e,t){return QA(this),this.i=null,JA(this,e=ZA(this,e))&&(this.h-=this.g.get(e).length),this.g.set(e,[t]),this.h+=1,this},We.get=function(e,t){return e&&0<(e=this.R(e)).length?String(e[0]):t},We.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 eN=class{constructor(e,t){this.h=e,this.g=t}};function tN(e){this.l=e||10,e=bk.PerformanceNavigationTiming?0<(e=bk.performance.getEntriesByType("navigation")).length&&("hq"==e[0].nextHopProtocol||"h2"==e[0].nextHopProtocol):!!(bk.g&&bk.g.Ea&&bk.g.Ea()&&bk.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 nN;function rN(e){return e.h||e.g&&e.g.size>=e.j}function iN(e){return e.h?1:e.g?e.g.size:0}function sN(e,t){return e.h?e.h==t:e.g&&e.g.has(t)}function oN(e,t){e.g?e.g.add(t):e.h=t}function aN(e,t){e.h&&e.h==t?e.h=null:e.g&&e.g.has(t)&&e.g.delete(t)}function cN(t){if(null!=t.h)return t.i.concat(t.h.D);if(null==t.g||0===t.g.size)return Fk(t.i);{let e=t.i;for(const n of t.g.values())e=e.concat(n.D);return e}}function lN(){}function uN(){this.g=new lN}function hN(e,t,n,r,i){try{t.onload=null,t.onerror=null,t.onabort=null,t.ontimeout=null,i(r)}catch(e){}}function dN(e){this.l=e.$b||null,this.j=e.ib||!1}function fN(e,t){NC.call(this),this.D=e,this.u=t,this.m=void 0,this.readyState=pN,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}tN.prototype.cancel=function(){if(this.i=cN(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()}},lN.prototype.stringify=function(e){return bk.JSON.stringify(e,void 0)},lN.prototype.parse=function(e){return bk.JSON.parse(e,void 0)},Pk(dN,sA),dN.prototype.g=function(){return new fN(this.l,this.j)},dN.prototype.i=(nN={},function(){return nN}),Pk(fN,NC);var pN=0;function gN(e){e.j.read().then(e.Sa.bind(e)).catch(e.ha.bind(e))}function mN(e){e.readyState=4,e.l=null,e.j=null,e.A=null,vN(e)}function vN(e){e.onreadystatechange&&e.onreadystatechange.call(e)}(We=fN.prototype).open=function(e,t){if(this.readyState!=pN)throw this.abort(),Error("Error reopening a connection");this.C=e,this.B=t,this.readyState=1,vN(this)},We.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||bk).fetch(new Request(this.B,t)).then(this.Va.bind(this),this.ha.bind(this))},We.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,mN(this)),this.readyState=pN},We.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,vN(this)),this.g&&(this.readyState=3,vN(this),this.g)))if("arraybuffer"===this.responseType)e.arrayBuffer().then(this.Ta.bind(this),this.ha.bind(this));else if(void 0!==bk.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;gN(this)}else e.text().then(this.Ua.bind(this),this.ha.bind(this))},We.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?mN:vN)(this),3==this.readyState&&gN(this))},We.Ua=function(e){this.g&&(this.response=this.responseText=e,mN(this))},We.Ta=function(e){this.g&&(this.response=e,mN(this))},We.ha=function(){this.g&&mN(this)},We.setRequestHeader=function(e,t){this.v.append(e,t)},We.getResponseHeader=function(e){return this.h&&this.h.get(e.toLowerCase())||""},We.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(fN.prototype,"withCredentials",{get:function(){return"include"===this.m},set:function(e){this.m=e?"include":"same-origin"}});var yN=bk.JSON.parse;function _N(e){NC.call(this),this.headers=new AA,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=wN,this.K=this.L=!1}Pk(_N,NC);var wN="",bN=/^https?$/i,IN=["POST","PUT"];function TN(e){return"content-type"==e.toLowerCase()}function EN(e,t){e.h=!1,e.g&&(e.l=!0,e.g.abort(),e.l=!1),e.j=t,e.m=5,SN(e),CN(e)}function SN(e){e.D||(e.D=!0,RC(e,"complete"),RC(e,"error"))}function kN(e){if(e.h&&void 0!==wk&&(!e.C[1]||4!=NN(e)||2!=e.ba()))if(e.v&&4==NN(e))BC(e.Fa,0,e);else if(RC(e,"readystatechange"),4==NN(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(PA)[1]||null)&&bk.self&&bk.self.location&&(i=(r=bk.self.location.protocol).substr(0,r.length-1)),n=!bN.test(i?i.toLowerCase():"")),t=n),t)RC(e,"complete"),RC(e,"success");else{e.m=6;try{var a=2<NN(e)?e.g.statusText:""}catch(e){a=""}e.j=a+" ["+e.ba()+"]",SN(e)}}finally{CN(e)}}}function CN(e,t){if(e.g){AN(e);const n=e.g,r=e.C[0]?Ik:null;e.g=null,e.C=null,t||RC(e,"ready");try{n.onreadystatechange=r}catch(e){}}}function AN(e){e.g&&e.K&&(e.g.ontimeout=null),e.A&&(bk.clearTimeout(e.A),e.A=null)}function NN(e){return e.g?e.g.readyState:0}function RN(e){try{if(!e.g)return null;if("response"in e.g)return e.g.response;switch(e.J){case wN:case"text":return e.g.responseText;case"arraybuffer":if("mozResponseArrayBuffer"in e.g)return e.g.mozResponseArrayBuffer}return null}catch(e){return null}}function PN(e,t,n){e:{for(r in n){var r=!1;break e}r=!0}r||(n=function(e){let n="";return Kk(e,function(e,t){n+=t,n+=":",n+=e,n+="\r\n"}),n}(n),"string"==typeof e?null!=n&&encodeURIComponent(String(n)):UA(e,t,n))}function xN(e,t,n){return n&&n.internalChannelParams&&n.internalChannelParams[e]||t}function ON(e){this.za=0,this.l=[],this.h=new GC,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=xN("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=xN("baseRetryDelayMs",5e3,e),this.$a=xN("retryDelaySeedMs",1e4,e),this.Ya=xN("forwardChannelMaxRetries",2,e),this.ra=xN("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 tN(e&&e.concurrentRequestLimit),this.Ca=new uN,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 DN(e){var t,n;MN(e),3==e.G&&(t=e.V++,UA(n=OA(e.F),"SID",e.J),UA(n,"RID",t),UA(n,"TYPE","terminate"),qN(e,n),(t=new hA(e,e.h,t,void 0)).K=2,t.v=jA(OA(n)),n=!1,!(n=bk.navigator&&bk.navigator.sendBeacon?bk.navigator.sendBeacon(t.v.toString(),""):n)&&bk.Image&&((new Image).src=t.v,n=!0),n||(t.g=XN(t.l,null),t.g.ea(t.v)),t.F=Date.now(),bA(t)),YN(e)}function LN(e){e.g&&(KN(e),e.g.cancel(),e.g=null)}function MN(e){LN(e),e.u&&(bk.clearTimeout(e.u),e.u=null),WN(e),e.i.cancel(),e.m&&("number"==typeof e.m&&bk.clearTimeout(e.m),e.m=null)}function FN(e,t){e.l.push(new eN(e.Za++,t)),3==e.G&&UN(e)}function UN(e){rN(e.i)||e.m||(e.m=!0,MC(e.Ha,e),e.C=0)}function jN(e,t){var n=t?t.m:e.V++,r=OA(e.F);UA(r,"SID",e.J),UA(r,"RID",n),UA(r,"AID",e.U),qN(e,r),e.o&&e.s&&PN(r,e.o,e.s),n=new hA(e,e.h,n,e.C+1),null===e.o&&(n.H=e.s),t&&(e.l=t.D.concat(e.l)),t=VN(e,n,1e3),n.setTimeout(Math.round(.5*e.ra)+Math.round(.5*e.ra*Math.random())),oN(e.i,n),vA(n,r,t)}function qN(e,n){e.j&&CA({},function(e,t){UA(n,t,e)})}function VN(e,t,r){r=Math.min(e.l.length,r);var i=e.j?Nk(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{CA(e,function(e,t){let n=e;Ek(e)&&(n=xC(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 BN(e){e.g||e.u||(e.Y=1,MC(e.Ga,e),e.A=0)}function $N(e){return!(e.g||e.u||3<=e.A)&&(e.Y++,e.u=iA(Nk(e.Ga,e),GN(e,e.A)),e.A++,1)}function KN(e){null!=e.B&&(bk.clearTimeout(e.B),e.B=null)}function zN(e){e.g=new hA(e,e.h,"rpc",e.Y),null===e.o&&(e.g.H=e.s),e.g.O=0;var t=OA(e.oa);UA(t,"RID","rpc"),UA(t,"SID",e.J),UA(t,"CI",e.N?"0":"1"),UA(t,"AID",e.U),qN(e,t),UA(t,"TYPE","xmlhttp"),e.o&&e.s&&PN(t,e.o,e.s),e.K&&e.g.setTimeout(e.K);var n=e.g;e=e.la,n.K=1,n.v=jA(OA(t)),n.s=null,n.U=!0,yA(n,e)}function WN(e){null!=e.v&&(bk.clearTimeout(e.v),e.v=null)}function HN(e,t){var n,r,i,s=null;if(e.g==t){WN(e),KN(e),e.g=null;var o=2}else{if(!sN(e.i,t))return;s=t.D,aN(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,RC(o=XC(),new rA(o,s)),UN(e)):BN(e);else if(3==(n=t.o)||0==n&&0<e.I||(1!=o||(i=t,iN((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=iA(Nk(r.Ha,r,i),GN(r,r.C)),r.C++,0))))&&(2!=o||!$N(e)))switch(s&&0<s.length&&(t=e.i,t.i=t.i.concat(s)),n){case 1:QN(e,5);break;case 4:QN(e,10);break;case 3:QN(e,6);break;default:QN(e,2)}}function GN(e,t){let n=e.Pa+Math.floor(Math.random()*e.$a);return e.j||(n*=2),n*t}function QN(e,t){var n,r;e.h.info("Error code "+t),2==t?(n=null,e.j&&(n=null),r=Nk(e.jb,e),n||(n=new xA("//www.google.com/images/cleardot.gif"),bk.location&&"http"==bk.location.protocol||DA(n,"https"),jA(n)),function(e,t){var n=new GC;if(bk.Image){const r=new Image;r.onload=Rk(hN,n,r,"TestLoadImage: loaded",!0,t),r.onerror=Rk(hN,n,r,"TestLoadImage: error",!1,t),r.onabort=Rk(hN,n,r,"TestLoadImage: abort",!1,t),r.ontimeout=Rk(hN,n,r,"TestLoadImage: timeout",!1,t),bk.setTimeout(function(){r.ontimeout&&r.ontimeout()},1e4),r.src=e}else t(!1)}(n.toString(),r)):nA(2),e.G=0,e.j&&e.j.va(t),YN(e),MN(e)}function YN(e){e.G=0,e.I=-1,e.j&&(0==cN(e.i).length&&0==e.l.length||(e.i.i.length=0,Fk(e.l),e.l.length=0),e.j.ua())}function JN(e,t,n){let r=(a=n)instanceof xA?OA(a):new xA(a,void 0);var i,s,o,a,c;return""!=r.i?(t&&LA(r,t+"."+r.i),MA(r,r.m)):(c=bk.location,r=(i=c.protocol,s=t?t+"."+c.hostname:c.hostname,o=+c.port,a=n,c=new xA(null,void 0),i&&DA(c,i),s&&LA(c,s),o&&MA(c,o),a&&(c.l=a),c)),e.aa&&Kk(e.aa,function(e,t){UA(r,t,e)}),t=e.D,n=e.sa,t&&n&&UA(r,t,n),UA(r,"VER",e.ma),qN(e,r),r}function XN(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 _N(new dN({ib:!0})):new _N(e.qa)).L=e.H,t}function ZN(){}function eR(){if(Jk&&!(10<=Number(aC)))throw Error("Environmental error: no available transport.")}function tR(e,t){NC.call(this),this.g=new ON(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)&&!Uk(e)&&(this.g.o=e),this.A=t&&t.supportsCrossDomainXhr||!1,this.v=t&&t.sendRawJson||!1,(t=t&&t.httpSessionIdParam)&&!Uk(t)&&(this.g.D=t,null!==(e=this.h)&&t in e&&(t in(e=this.h)&&delete e[t])),this.j=new iR(this)}function nR(e){cA.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 rR(){lA.call(this),this.status=1}function iR(e){this.g=e}(We=_N.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||fA).g(),this.C=this.u?oA(this.u):oA(fA),this.g.onreadystatechange=Nk(this.Fa,this);try{this.F=!0,this.g.open(t,String(e),!0),this.F=!1}catch(e){return void EN(this,e)}e=n||"";const i=new AA(this.headers);r&&CA(r,function(e,t){i.set(t,e)}),r=function(t){e:{var n=TN,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=bk.FormData&&e instanceof bk.FormData,0<=Dk(IN,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{AN(this),0<this.B&&((this.K=(s=this.g,Jk&&oC()&&"number"==typeof s.timeout&&void 0!==s.ontimeout))?(this.g.timeout=this.B,this.g.ontimeout=Nk(this.pa,this)):this.A=BC(this.pa,this.B,this)),this.v=!0,this.g.send(e),this.v=!1}catch(e){EN(this,e)}var s},We.pa=function(){void 0!==wk&&this.g&&(this.j="Timed out after "+this.B+"ms, aborting",this.m=8,RC(this,"timeout"),this.abort(8))},We.abort=function(e){this.g&&this.h&&(this.h=!1,this.l=!0,this.g.abort(),this.l=!1,this.m=e||7,RC(this,"complete"),RC(this,"abort"),CN(this))},We.M=function(){this.g&&(this.h&&(this.h=!1,this.l=!0,this.g.abort(),this.l=!1),CN(this,!0)),_N.Z.M.call(this)},We.Fa=function(){this.s||(this.F||this.v||this.l?kN(this):this.cb())},We.cb=function(){kN(this)},We.ba=function(){try{return 2<NN(this)?this.g.status:-1}catch(e){return-1}},We.ga=function(){try{return this.g?this.g.responseText:""}catch(e){return""}},We.Qa=function(e){if(this.g){var t=this.g.responseText;return e&&0==t.indexOf(e)&&(t=t.substring(e.length)),yN(t)}},We.Da=function(){return this.m},We.La=function(){return"string"==typeof this.j?this.j:String(this.j)},(We=ON.prototype).ma=8,We.G=1,We.hb=function(e){try{this.h.info("Origin Trials invoked: "+e)}catch(e){}},We.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 hA(this,this.h,t,void 0);let e=this.s;if(this.P&&(e?(e=zk(e),Hk(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=VN(this,s,n),UA(r=OA(this.F),"RID",t),UA(r,"CVER",22),this.D&&UA(r,"X-HTTP-Session-Id",this.D),qN(this,r),this.o&&e&&PN(r,this.o,e),oN(this.i,s),this.Ra&&UA(r,"TYPE","init"),this.ja?(UA(r,"$req",n),UA(r,"SID","null"),s.$=!0,vA(s,r,null)):vA(s,r,n),this.G=2}}else 3==this.G&&(t?jN(this,t):0==this.l.length||rN(this.i)||jN(this))},We.Ga=function(){var e;this.u=null,zN(this),this.$&&!(this.L||null==this.g||this.O<=0)&&(e=2*this.O,this.h.info("BP detection timer enabled: "+e),this.B=iA(Nk(this.bb,this),e))},We.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,nA(10),LN(this),zN(this))},We.ab=function(){null!=this.v&&(this.v=null,LN(this),$N(this),nA(19))},We.jb=function(e){e?(this.h.info("Successfully pinged google.com"),nA(2)):(this.h.info("Failed to ping google.com"),nA(1))},(We=ZN.prototype).xa=function(){},We.wa=function(){},We.va=function(){},We.ua=function(){},We.Oa=function(){},eR.prototype.g=function(e,t){return new tR(e,t)},Pk(tR,NC),tR.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."),MC(Nk(e.hb,e,t))),nA(0),e.W=t,e.aa=n||{},e.N=e.X,e.F=JN(e,null,e.W),UN(e)},tR.prototype.close=function(){DN(this.g)},tR.prototype.u=function(e){var t;"string"==typeof e?((t={}).__data__=e,FN(this.g,t)):this.v?((t={}).__data__=xC(e),FN(this.g,t)):FN(this.g,e)},tR.prototype.M=function(){this.g.j=null,delete this.j,DN(this.g),delete this.g,tR.Z.M.call(this)},Pk(nR,cA),Pk(rR,lA),Pk(iR,ZN),iR.prototype.xa=function(){RC(this.g,"a")},iR.prototype.wa=function(e){RC(this.g,new nR(e))},iR.prototype.va=function(e){RC(this.g,new rR)},iR.prototype.ua=function(){RC(this.g,"b")},eR.prototype.createWebChannel=eR.prototype.g,tR.prototype.send=tR.prototype.u,tR.prototype.open=tR.prototype.m,c.NO_ERROR=0,c.TIMEOUT=8,c.HTTP_ERROR=6,yt.COMPLETE="complete",(aA.EventType=l).OPEN="a",l.CLOSE="b",l.ERROR="c",l.MESSAGE="d",NC.prototype.listen=NC.prototype.N,_N.prototype.listenOnce=_N.prototype.O,_N.prototype.getLastError=_N.prototype.La,_N.prototype.getLastErrorCode=_N.prototype.Da,_N.prototype.getStatus=_N.prototype.ba,_N.prototype.getResponseJson=_N.prototype.Qa,_N.prototype.getResponseText=_N.prototype.ga,_N.prototype.send=_N.prototype.ea;var sR,oR=XC,aR=c,cR=yt,lR=YC,uR=10,hR=11,dR=dN,fR=aA,pR=_N;const gR="@firebase/firestore";class mR{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}}mR.UNAUTHENTICATED=new mR(null),mR.GOOGLE_CREDENTIALS=new mR("google-credentials-uid"),mR.FIRST_PARTY=new mR("first-party-uid"),mR.MOCK_USER=new mR("mock-user");let vR="9.4.1";const yR=new ef("@firebase/firestore");function _R(){return yR.logLevel}function wR(e,...t){var n;yR.logLevel<=Kh.DEBUG&&(n=t.map(TR),yR.debug(`Firestore (${vR}): ${e}`,...n))}function bR(e,...t){var n;yR.logLevel<=Kh.ERROR&&(n=t.map(TR),yR.error(`Firestore (${vR}): ${e}`,...n))}function IR(e,...t){var n;yR.logLevel<=Kh.WARN&&(n=t.map(TR),yR.warn(`Firestore (${vR}): ${e}`,...n))}function TR(t){if("string"==typeof t)return t;try{return JSON.stringify(t)}catch(e){return t}}function ER(e="Unexpected state"){var t=`FIRESTORE (${vR}) INTERNAL ASSERTION FAILED: `+e;throw bR(t),new Error(t)}function SR(e){e||ER()}const kR={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 CR extends Error{constructor(e,t){super(t),this.code=e,this.message=t,this.name="FirebaseError",this.toString=()=>`${this.name}: [code=${this.code}]: ${this.message}`}}class AR{constructor(){this.promise=new Promise((e,t)=>{this.resolve=e,this.reject=t})}}class NR{constructor(e,t){this.user=t,this.type="OAuth",this.authHeaders={},this.authHeaders.Authorization=`Bearer ${e}`}}class RR{getToken(){return Promise.resolve(null)}invalidateToken(){}start(e,t){e.enqueueRetryable(()=>t(mR.UNAUTHENTICATED))}shutdown(){}}class PR{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 xR{constructor(e){this.t=e,this.currentUser=mR.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 AR;this.o=()=>{this.i++,this.currentUser=this.u(),s.resolve(),s=new AR,t.enqueueRetryable(()=>i(this.currentUser))};const o=()=>{const e=s;t.enqueueRetryable(async()=>{await e.promise,await i(this.currentUser)})},a=e=>{wR("FirebaseCredentialsProvider","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):(wR("FirebaseCredentialsProvider","Auth not yet detected"),s.resolve(),s=new AR))},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?(wR("FirebaseCredentialsProvider","getToken aborted due to token change."),this.getToken()):e?(SR("string"==typeof e.accessToken),new NR(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 SR(null===e||"string"==typeof e),new mR(e)}}class OR{constructor(e,t,n){this.h=e,this.l=t,this.m=n,this.type="FirstParty",this.user=mR.FIRST_PARTY}get authHeaders(){const e={"X-Goog-AuthUser":this.l},t=this.h.auth.getAuthHeaderValueForFirstParty([]);return t&&(e.Authorization=t),this.m&&(e["X-Goog-Iam-Authorization-Token"]=this.m),e}}class DR{constructor(e,t,n){this.h=e,this.l=t,this.m=n}getToken(){return Promise.resolve(new OR(this.h,this.l,this.m))}start(e,t){e.enqueueRetryable(()=>t(mR.FIRST_PARTY))}shutdown(){}invalidateToken(){}}class LR{constructor(e,t){this.previousValue=e,t&&(t.sequenceNumberHandler=e=>this.g(e),this.p=e=>t.writeSequenceNumber(e))}g(e){return this.previousValue=Math.max(e,this.previousValue),this.previousValue}next(){var e=++this.previousValue;return this.p&&this.p(e),e}}LR.T=-1;class MR{static I(){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 FR(e,t){return e<t?-1:t<e?1:0}function UR(e,n,r){return e.length===n.length&&e.every((e,t)=>r(e,n[t]))}function jR(e){return e+"\0"}class qR{constructor(e,t){if(this.seconds=e,(this.nanoseconds=t)<0)throw new CR(kR.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+t);if(1e9<=t)throw new CR(kR.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+t);if(e<-62135596800)throw new CR(kR.INVALID_ARGUMENT,"Timestamp seconds out of range: "+e);if(253402300800<=e)throw new CR(kR.INVALID_ARGUMENT,"Timestamp seconds out of range: "+e)}static now(){return qR.fromMillis(Date.now())}static fromDate(e){return qR.fromMillis(e.getTime())}static fromMillis(e){var t=Math.floor(e/1e3),n=Math.floor(1e6*(e-1e3*t));return new qR(t,n)}toDate(){return new Date(this.toMillis())}toMillis(){return 1e3*this.seconds+this.nanoseconds/1e6}_compareTo(e){return this.seconds===e.seconds?FR(this.nanoseconds,e.nanoseconds):FR(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 VR{constructor(e){this.timestamp=e}static fromTimestamp(e){return new VR(e)}static min(){return new VR(new qR(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 BR(e){let t=0;for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&t++;return t}function $R(e,t){for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&t(n,e[n])}function KR(e){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}class zR{constructor(e,t,n){void 0===t?t=0:t>e.length&&ER(),void 0===n?n=e.length-t:n>e.length-t&&ER(),this.segments=e,this.offset=t,this.len=n}get length(){return this.len}isEqual(e){return 0===zR.comparator(this,e)}child(e){const t=this.segments.slice(this.offset,this.limit());return e instanceof zR?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 WR extends zR{construct(e,t,n){return new WR(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 CR(kR.INVALID_ARGUMENT,`Invalid segment (${n}). Paths must not contain // in them.`);t.push(...n.split("/").filter(e=>0<e.length))}return new WR(t)}static emptyPath(){return new WR([])}}const HR=/^[_a-zA-Z][_a-zA-Z0-9]*$/;class GR extends zR{construct(e,t,n){return new GR(e,t,n)}static isValidIdentifier(e){return HR.test(e)}canonicalString(){return this.toArray().map(e=>(e=e.replace(/\\/g,"\\\\").replace(/`/g,"\\`"),e=!GR.isValidIdentifier(e)?"`"+e+"`":e)).join(".")}toString(){return this.canonicalString()}isKeyField(){return 1===this.length&&"__name__"===this.get(0)}static keyField(){return new GR(["__name__"])}static fromServerFormat(e){const t=[];let n="",r=0;var i=()=>{if(0===n.length)throw new CR(kR.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 CR(kR.INVALID_ARGUMENT,"Path has trailing escape character: "+e);const t=e[r+1];if("\\"!==t&&"."!==t&&"`"!==t)throw new CR(kR.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 CR(kR.INVALID_ARGUMENT,"Unterminated ` in path: "+e);return new GR(t)}static emptyPath(){return new GR([])}}class QR{constructor(e){(this.fields=e).sort(GR.comparator)}covers(e){for(const t of this.fields)if(t.isPrefixOf(e))return!0;return!1}isEqual(e){return UR(this.fields,e.fields,(e,t)=>e.isEqual(t))}}class YR{constructor(e){this.binaryString=e}static fromBase64String(e){var t=atob(e);return new YR(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 YR(t)}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 FR(this.binaryString,e.binaryString)}isEqual(e){return this.binaryString===e.binaryString}}YR.EMPTY_BYTE_STRING=new YR("");const JR=new RegExp(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.(\d+))?Z$/);function XR(t){if(SR(!!t),"string"!=typeof t)return{seconds:ZR(t.seconds),nanos:ZR(t.nanos)};{let e=0;var n=JR.exec(t);SR(!!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 ZR(e){return"number"==typeof e?e:"string"==typeof e?Number(e):0}function eP(e){return"string"==typeof e?YR.fromBase64String(e):YR.fromUint8Array(e)}function tP(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 nP(e){var t=XR(e.mapValue.fields.__local_write_time__.timestampValue);return new qR(t.seconds,t.nanos)}function rP(e){return null==e}function iP(e){return 0===e&&1/e==-1/0}function sP(e){return"number"==typeof e&&Number.isInteger(e)&&!iP(e)&&e<=Number.MAX_SAFE_INTEGER&&e>=Number.MIN_SAFE_INTEGER}class oP{constructor(e){this.path=e}static fromPath(e){return new oP(WR.fromString(e))}static fromName(e){return new oP(WR.fromString(e).popFirst(5))}hasCollectionId(e){return 2<=this.path.length&&this.path.get(this.path.length-2)===e}isEqual(e){return null!==e&&0===WR.comparator(this.path,e.path)}toString(){return this.path.toString()}static comparator(e,t){return WR.comparator(e.path,t.path)}static isDocumentKey(e){return e.length%2==0}static fromSegments(e){return new oP(new WR(e.slice()))}}function aP(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?tP(e)?4:10:ER()}function cP(r,i){var e,t,n=aP(r);if(n!==aP(i))return!1;switch(n){case 0:return!0;case 1:return r.booleanValue===i.booleanValue;case 4:return nP(r).isEqual(nP(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=XR(r.timestampValue),n=XR(e.timestampValue);return t.seconds===n.seconds&&t.nanos===n.nanos}(i);case 5:return r.stringValue===i.stringValue;case 6:return t=i,eP(r.bytesValue).isEqual(eP(t.bytesValue));case 7:return r.referenceValue===i.referenceValue;case 8:return e=i,ZR((t=r).geoPointValue.latitude)===ZR(e.geoPointValue.latitude)&&ZR(t.geoPointValue.longitude)===ZR(e.geoPointValue.longitude);case 2:return function(e,t){if("integerValue"in e&&"integerValue"in t)return ZR(e.integerValue)===ZR(t.integerValue);if("doubleValue"in e&&"doubleValue"in t){var n=ZR(e.doubleValue),r=ZR(t.doubleValue);return n===r?iP(n)===iP(r):isNaN(n)&&isNaN(r)}return!1}(r,i);case 9:return UR(r.arrayValue.values||[],i.arrayValue.values||[],cP);case 10:return function(e){const t=e.mapValue.fields||{},n=i.mapValue.fields||{};if(BR(t)!==BR(n))return!1;for(const e in t)if(t.hasOwnProperty(e)&&(void 0===n[e]||!cP(t[e],n[e])))return!1;return!0}(r);default:return ER()}}function lP(e,t){return void 0!==(e.values||[]).find(e=>cP(e,t))}function uP(e,t){var n,r,i,s,o=aP(e),a=aP(t);if(o!==a)return FR(o,a);switch(o){case 0:return 0;case 1:return FR(e.booleanValue,t.booleanValue);case 2:return r=t,i=ZR(e.integerValue||e.doubleValue),s=ZR(r.integerValue||r.doubleValue),i<s?-1:s<i?1:i===s?0:isNaN(i)?isNaN(s)?0:-1:1;case 3:return hP(e.timestampValue,t.timestampValue);case 4:return hP(nP(e),nP(t));case 5:return FR(e.stringValue,t.stringValue);case 6:return function(e,t){const n=eP(e),r=eP(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=FR(n[i],r[i]);if(0!==t)return t}return FR(n.length,r.length)}(e.referenceValue,t.referenceValue);case 8:return n=e.geoPointValue,r=t.geoPointValue,0!==(s=FR(ZR(n.latitude),ZR(r.latitude)))?s:FR(ZR(n.longitude),ZR(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=uP(n[i],r[i]);if(t)return t}return FR(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=FR(r[a],s[a]);if(0!==t)return t;var o=uP(n[r[a]],i[s[a]]);if(0!==o)return o}return FR(r.length,s.length)}(e.mapValue,t.mapValue);default:throw ER()}}function hP(e,t){if("string"==typeof e&&"string"==typeof t&&e.length===t.length)return FR(e,t);var n=XR(e),r=XR(t),i=FR(n.seconds,r.seconds);return 0!==i?i:FR(n.nanos,r.nanos)}function dP(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=XR(e);return`time(${t.seconds},${t.nanos})`}(e.timestampValue):"stringValue"in e?e.stringValue:"bytesValue"in e?eP(e.bytesValue).toBase64():"referenceValue"in e?(t=e.referenceValue,oP.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):ER();var t}(e)}function fP(e,t){return{referenceValue:`projects/${e.projectId}/databases/${e.database}/documents/${t.path.canonicalString()}`}}function pP(e){return e&&"integerValue"in e}function gP(e){return!!e&&"arrayValue"in e}function mP(e){return e&&"nullValue"in e}function vP(e){return e&&"doubleValue"in e&&isNaN(Number(e.doubleValue))}function yP(e){return e&&"mapValue"in e}function _P(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 $R(t.mapValue.fields,(e,t)=>n.mapValue.fields[e]=_P(t)),n}if(t.arrayValue){const r={arrayValue:{values:[]}};for(let e=0;e<(t.arrayValue.values||[]).length;++e)r.arrayValue.values[e]=_P(t.arrayValue.values[e]);return r}return Object.assign({},t)}class wP{constructor(e){this.value=e}static empty(){return new wP({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)],!yP(e))return null;return e=(e.mapValue.fields||{})[n.lastSegment()],e||null}}set(e,t){this.getFieldsMap(e.popLast())[e.lastSegment()]=_P(t)}setAll(e){let n=GR.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()]=_P(e):i.push(t.lastSegment())});var t=this.getFieldsMap(n);this.applyChanges(t,r,i)}delete(e){const t=this.field(e.popLast());yP(t)&&t.mapValue.fields&&delete t.mapValue.fields[e.lastSegment()]}isEqual(e){return cP(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)];yP(e)&&e.mapValue.fields||(e={mapValue:{fields:{}}},n.mapValue.fields[t.get(r)]=e),n=e}return n.mapValue.fields}applyChanges(n,e,t){$R(e,(e,t)=>n[e]=t);for(const e of t)delete n[e]}clone(){return new wP(_P(this.value))}}class bP{constructor(e,t,n,r,i){this.key=e,this.documentType=t,this.version=n,this.data=r,this.documentState=i}static newInvalidDocument(e){return new bP(e,0,VR.min(),wP.empty(),0)}static newFoundDocument(e,t,n){return new bP(e,1,t,n,0)}static newNoDocument(e,t){return new bP(e,2,t,wP.empty(),0)}static newUnknownDocument(e,t){return new bP(e,3,t,wP.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=wP.empty(),this.documentState=0,this}convertToUnknownDocument(e){return this.version=e,this.documentType=3,this.data=wP.empty(),this.documentState=2,this}setHasCommittedMutations(){return this.documentState=2,this}setHasLocalMutations(){return this.documentState=1,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 bP&&this.key.isEqual(e.key)&&this.version.isEqual(e.version)&&this.documentType===e.documentType&&this.documentState===e.documentState&&this.data.isEqual(e.data)}clone(){return new bP(this.key,this.documentType,this.version,this.data.clone(),this.documentState)}toString(){return`Document(${this.key}, ${this.version}, ${JSON.stringify(this.data.value)}, {documentType: ${this.documentType}}), {documentState: ${this.documentState}})`}}class IP{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.A=null}}function TP(e,t=null,n=[],r=[],i=null,s=null,o=null){return new IP(e,t,n,r,i,s,o)}function EP(e){const t=e;if(null===t.A){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()+dP(e.value)}(e)).join(","),e+="|ob:",e+=t.orderBy.map(e=>function(e){return e.field.canonicalString()+e.dir}(e)).join(","),rP(t.limit)||(e+="|l:",e+=t.limit),t.startAt&&(e+="|lb:",e+=FP(t.startAt)),t.endAt&&(e+="|ub:",e+=FP(t.endAt)),t.A=e}return t.A}function SP(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)||!cP(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 kP(e){return oP.isDocumentKey(e.path)&&null===e.collectionGroup&&0===e.filters.length}class CP 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.R(e,t,n):new AP(e,t,n):"array-contains"===t?new xP(e,n):"in"===t?new OP(e,n):"not-in"===t?new DP(e,n):"array-contains-any"===t?new LP(e,n):new CP(e,t,n)}static R(e,t,n){return new("in"===t?NP:RP)(e,n)}matches(e){var t=e.data.field(this.field);return"!="===this.op?null!==t&&this.P(uP(t,this.value)):null!==t&&aP(this.value)===aP(t)&&this.P(uP(t,this.value))}P(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 ER()}}v(){return 0<=["<","<=",">",">=","!=","not-in"].indexOf(this.op)}}class AP extends CP{constructor(e,t,n){super(e,t,n),this.key=oP.fromName(n.referenceValue)}matches(e){var t=oP.comparator(e.key,this.key);return this.P(t)}}class NP extends CP{constructor(e,t){super(e,"in",t),this.keys=PP(0,t)}matches(t){return this.keys.some(e=>e.isEqual(t.key))}}class RP extends CP{constructor(e,t){super(e,"not-in",t),this.keys=PP(0,t)}matches(t){return!this.keys.some(e=>e.isEqual(t.key))}}function PP(e,t){var n;return((null===(n=t.arrayValue)||void 0===n?void 0:n.values)||[]).map(e=>oP.fromName(e.referenceValue))}class xP extends CP{constructor(e,t){super(e,"array-contains",t)}matches(e){var t=e.data.field(this.field);return gP(t)&&lP(t.arrayValue,this.value)}}class OP extends CP{constructor(e,t){super(e,"in",t)}matches(e){var t=e.data.field(this.field);return null!==t&&lP(this.value.arrayValue,t)}}class DP extends CP{constructor(e,t){super(e,"not-in",t)}matches(e){if(lP(this.value.arrayValue,{nullValue:"NULL_VALUE"}))return!1;var t=e.data.field(this.field);return null!==t&&!lP(this.value.arrayValue,t)}}class LP extends CP{constructor(e,t){super(e,"array-contains-any",t)}matches(e){const t=e.data.field(this.field);return!(!gP(t)||!t.arrayValue.values)&&t.arrayValue.values.some(e=>lP(this.value.arrayValue,e))}}class MP{constructor(e,t){this.position=e,this.before=t}}function FP(e){return`${e.before?"b":"a"}:${e.position.map(e=>dP(e)).join(",")}`}class UP{constructor(e,t="asc"){this.field=e,this.dir=t}}function jP(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()?oP.comparator(oP.fromName(o.referenceValue),n.key):uP(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(!cP(e.position[n],t.position[n]))return!1;return!0}class VP{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.V=null,this.S=null,this.startAt,this.endAt}}function BP(e,t,n,r,i,s,o,a){return new VP(e,t,n,r,i,s,o,a)}function $P(e){return new VP(e)}function KP(e){return!rP(e.limit)&&"F"===e.limitType}function zP(e){return!rP(e.limit)&&"L"===e.limitType}function WP(e){return 0<e.explicitOrderBy.length?e.explicitOrderBy[0].field:null}function HP(e){for(const t of e.filters)if(t.v())return t.field;return null}function GP(e){return null!==e.collectionGroup}function QP(t){const n=t;if(null===n.V){n.V=[];const t=HP(n),e=WP(n);if(null!==t&&null===e)t.isKeyField()||n.V.push(new UP(t)),n.V.push(new UP(GR.keyField(),"asc"));else{let e=!1;for(const r of n.explicitOrderBy)n.V.push(r),r.field.isKeyField()&&(e=!0);if(!e){const t=0<n.explicitOrderBy.length?n.explicitOrderBy[n.explicitOrderBy.length-1].dir:"asc";n.V.push(new UP(GR.keyField(),t))}}}return n.V}function YP(e){const t=e;if(!t.S)if("F"===t.limitType)t.S=TP(t.path,t.collectionGroup,QP(t),t.filters,t.limit,t.startAt,t.endAt);else{const e=[];for(const i of QP(t)){const t="desc"===i.dir?"asc":"desc";e.push(new UP(i.field,t))}var n=t.endAt?new MP(t.endAt.position,!t.endAt.before):null,r=t.startAt?new MP(t.startAt.position,!t.startAt.before):null;t.S=TP(t.path,t.collectionGroup,e,t.filters,t.limit,n,r)}return t.S}function JP(e,t,n){return new VP(e.path,e.collectionGroup,e.explicitOrderBy.slice(),e.filters.slice(),t,n,e.startAt,e.endAt)}function XP(e,t){return SP(YP(e),YP(t))&&e.limitType===t.limitType}function ZP(e){return`${EP(YP(e))}|lt:${e.limitType}`}function ex(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} ${dP(t.value)}`;var t}).join(", ")}]`),rP(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: "+FP(e.startAt)),e.endAt&&(t+=", endAt: "+FP(e.endAt)),`Target(${t})`}(YP(e))}; limitType=${e.limitType})`}function tx(n,e){return e.isFoundDocument()&&(t=n,i=(r=e).key.path,null!==t.collectionGroup?r.key.hasCollectionId(t.collectionGroup)&&t.path.isPrefixOf(i):oP.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||jP(e.startAt,QP(e),t))&&(!e.endAt||!jP(e.endAt,QP(e),t)));var t,r,i}function nx(i){return(e,t)=>{let n=!1;for(const r of QP(i)){const i=function(e,i,t){var n=e.field.isKeyField()?oP.comparator(i.key,t.key):function(e,t){var n=i.data.field(e),r=t.data.field(e);return null!==n&&null!==r?uP(n,r):ER()}(e.field,t);switch(e.dir){case"asc":return n;case"desc":return-1*n;default:return ER()}}(r,e,t);if(0!==i)return i;n=n||r.field.isKeyField()}return 0}}function rx(e,t){if(e.D){if(isNaN(t))return{doubleValue:"NaN"};if(t===1/0)return{doubleValue:"Infinity"};if(t===-1/0)return{doubleValue:"-Infinity"}}return{doubleValue:iP(t)?"-0":t}}function ix(e){return{integerValue:""+e}}function sx(e,t){return sP(t)?ix(t):rx(e,t)}class ox{constructor(){this._=void 0}}function ax(e,t){return e instanceof fx?pP(n=t)||n&&"doubleValue"in n?t:{integerValue:0}:null;var n}class cx extends ox{}class lx extends ox{constructor(e){super(),this.elements=e}}function ux(e,t){const n=gx(t);for(const t of e.elements)n.some(e=>cP(e,t))||n.push(t);return{arrayValue:{values:n}}}class hx extends ox{constructor(e){super(),this.elements=e}}function dx(e,t){let n=gx(t);for(const t of e.elements)n=n.filter(e=>!cP(e,t));return{arrayValue:{values:n}}}class fx extends ox{constructor(e,t){super(),this.N=e,this.C=t}}function px(e){return ZR(e.integerValue||e.doubleValue)}function gx(e){return gP(e)&&e.arrayValue.values?e.arrayValue.values.slice():[]}class mx{constructor(e,t){this.field=e,this.transform=t}}class vx{constructor(e,t){this.version=e,this.transformResults=t}}class yx{constructor(e,t){this.updateTime=e,this.exists=t}static none(){return new yx}static exists(e){return new yx(void 0,e)}static updateTime(e){return new yx(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 _x(e,t){return void 0!==e.updateTime?t.isFoundDocument()&&t.version.isEqual(e.updateTime):void 0===e.exists||e.exists===t.isFoundDocument()}class wx{}function bx(e,t,n){e instanceof Sx?function(e,t,n){const r=e.value.clone(),i=Ax(e.fieldTransforms,t,n.transformResults);r.setAll(i),t.convertToFoundDocument(n.version,r).setHasCommittedMutations()}(e,t,n):e instanceof kx?function(e,t,n){if(!_x(e.precondition,t))return t.convertToUnknownDocument(n.version);const r=Ax(e.fieldTransforms,t,n.transformResults),i=t.data;i.setAll(Cx(e)),i.setAll(r),t.convertToFoundDocument(n.version,i).setHasCommittedMutations()}(e,t,n):t.convertToNoDocument(n.version).setHasCommittedMutations()}function Ix(e,t,n){e instanceof Sx?function(e,t,n){if(_x(e.precondition,t)){const r=e.value.clone(),i=Nx(e.fieldTransforms,n,t);r.setAll(i),t.convertToFoundDocument(Ex(t),r).setHasLocalMutations()}}(e,t,n):e instanceof kx?function(e,t,n){if(_x(e.precondition,t)){const r=Nx(e.fieldTransforms,n,t),i=t.data;i.setAll(Cx(e)),i.setAll(r),t.convertToFoundDocument(Ex(t),i).setHasLocalMutations()}}(e,t,n):(t=t,_x(e.precondition,t)&&t.convertToNoDocument(VR.min()))}function Tx(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&&UR(n,r,(e,t)=>function(e,t){return e.field.isEqual(t.field)&&(e=e.transform,t=t.transform,e instanceof lx&&t instanceof lx||e instanceof hx&&t instanceof hx?UR(e.elements,t.elements,cP):e instanceof fx&&t instanceof fx?cP(e.C,t.C):e instanceof cx&&t instanceof cx)}(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 Ex(e){return e.isFoundDocument()?e.version:VR.min()}class Sx extends wx{constructor(e,t,n,r=[]){super(),this.key=e,this.value=t,this.precondition=n,this.fieldTransforms=r,this.type=0}}class kx extends wx{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 Cx(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 Ax(e,t,n){const r=new Map;SR(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 lx?ux(a,c):a instanceof hx?dx(a,c):l))}var a,c,l;return r}function Nx(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 cx?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 lx?ux(i,s):i instanceof hx?dx(i,s):(a=ax(i=i,s),c=px(a)+px(i.C),pP(a)&&pP(i.C)?ix(c):rx(i.N,c))))}var i,s,o,a,c;return r}class Rx extends wx{constructor(e,t){super(),this.key=e,this.precondition=t,this.type=2,this.fieldTransforms=[]}}class Px extends wx{constructor(e,t){super(),this.key=e,this.precondition=t,this.type=3,this.fieldTransforms=[]}}class xx{constructor(e){this.count=e}}function Ox(e){switch(e){default:return ER(),0;case kR.CANCELLED:case kR.UNKNOWN:case kR.DEADLINE_EXCEEDED:case kR.RESOURCE_EXHAUSTED:case kR.INTERNAL:case kR.UNAVAILABLE:case kR.UNAUTHENTICATED:return;case kR.INVALID_ARGUMENT:case kR.NOT_FOUND:case kR.ALREADY_EXISTS:case kR.PERMISSION_DENIED:case kR.FAILED_PRECONDITION:case kR.ABORTED:case kR.OUT_OF_RANGE:case kR.UNIMPLEMENTED:case kR.DATA_LOSS:return 1}}function Dx(e){if(void 0===e)return bR("GRPC error has no .code"),kR.UNKNOWN;switch(e){case sR.OK:return kR.OK;case sR.CANCELLED:return kR.CANCELLED;case sR.UNKNOWN:return kR.UNKNOWN;case sR.DEADLINE_EXCEEDED:return kR.DEADLINE_EXCEEDED;case sR.RESOURCE_EXHAUSTED:return kR.RESOURCE_EXHAUSTED;case sR.INTERNAL:return kR.INTERNAL;case sR.UNAVAILABLE:return kR.UNAVAILABLE;case sR.UNAUTHENTICATED:return kR.UNAUTHENTICATED;case sR.INVALID_ARGUMENT:return kR.INVALID_ARGUMENT;case sR.NOT_FOUND:return kR.NOT_FOUND;case sR.ALREADY_EXISTS:return kR.ALREADY_EXISTS;case sR.PERMISSION_DENIED:return kR.PERMISSION_DENIED;case sR.FAILED_PRECONDITION:return kR.FAILED_PRECONDITION;case sR.ABORTED:return kR.ABORTED;case sR.OUT_OF_RANGE:return kR.OUT_OF_RANGE;case sR.UNIMPLEMENTED:return kR.UNIMPLEMENTED;case sR.DATA_LOSS:return kR.DATA_LOSS;default:return ER()}}(c=sR=sR||{})[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 Lx{constructor(e,t){this.comparator=e,this.root=t||Fx.EMPTY}insert(e,t){return new Lx(this.comparator,this.root.insert(e,t,this.comparator).copy(null,null,Fx.BLACK,null,null))}remove(e){return new Lx(this.comparator,this.root.remove(e,this.comparator).copy(null,null,Fx.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 Mx(this.root,null,this.comparator,!1)}getIteratorFrom(e){return new Mx(this.root,e,this.comparator,!1)}getReverseIterator(){return new Mx(this.root,null,this.comparator,!0)}getReverseIteratorFrom(e){return new Mx(this.root,e,this.comparator,!0)}}class Mx{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 Fx{constructor(e,t,n,r,i){this.key=e,this.value=t,this.color=null!=n?n:Fx.RED,this.left=null!=r?r:Fx.EMPTY,this.right=null!=i?i:Fx.EMPTY,this.size=this.left.size+1+this.right.size}copy(e,t,n,r,i){return new Fx(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 Fx.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 Fx.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,Fx.RED,null,this.right.left);return this.right.copy(null,null,this.color,e,null)}rotateRight(){var e=this.copy(null,null,Fx.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 ER();if(this.right.isRed())throw ER();var e=this.left.check();if(e!==this.right.check())throw ER();return e+(this.isRed()?0:1)}}Fx.EMPTY=null,Fx.RED=!0,Fx.BLACK=!1,Fx.EMPTY=new class{constructor(){this.size=0}get key(){throw ER()}get value(){throw ER()}get color(){throw ER()}get left(){throw ER()}get right(){throw ER()}copy(e,t,n,r,i){return this}insert(e,t,n){return new Fx(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 Ux{constructor(e){this.comparator=e,this.data=new Lx(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 jx(this.data.getIterator())}getIteratorFrom(e){return new jx(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 Ux))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 Ux(this.comparator);return t.data=e,t}}class jx{constructor(e){this.iter=e}getNext(){return this.iter.getNext().key}hasNext(){return this.iter.hasNext()}}const qx=new Lx(oP.comparator);const Vx=new Lx(oP.comparator);const Bx=new Lx(oP.comparator);const $x=new Ux(oP.comparator);function Kx(...e){let t=$x;for(const n of e)t=t.add(n);return t}const zx=new Ux(FR);class Wx{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,Hx.createSynthesizedTargetChangeForCurrentChange(e,t)),new Wx(VR.min(),n,zx,qx,Kx())}}class Hx{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 Hx(YR.EMPTY_BYTE_STRING,t,Kx(),Kx(),Kx())}}class Gx{constructor(e,t,n,r){this.k=e,this.removedTargetIds=t,this.key=n,this.$=r}}class Qx{constructor(e,t){this.targetId=e,this.O=t}}class Yx{constructor(e,t,n=YR.EMPTY_BYTE_STRING,r=null){this.state=e,this.targetIds=t,this.resumeToken=n,this.cause=r}}class Jx{constructor(){this.F=0,this.M=eO(),this.L=YR.EMPTY_BYTE_STRING,this.B=!1,this.U=!0}get current(){return this.B}get resumeToken(){return this.L}get q(){return 0!==this.F}get K(){return this.U}j(e){0<e.approximateByteSize()&&(this.U=!0,this.L=e)}W(){let n=Kx(),r=Kx(),i=Kx();return this.M.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:ER()}}),new Hx(this.L,this.B,n,r,i)}G(){this.U=!1,this.M=eO()}H(e,t){this.U=!0,this.M=this.M.insert(e,t)}J(e){this.U=!0,this.M=this.M.remove(e)}Y(){this.F+=1}X(){--this.F}Z(){this.U=!0,this.B=!0}}class Xx{constructor(e){this.tt=e,this.et=new Map,this.nt=qx,this.st=Zx(),this.it=new Ux(FR)}rt(e){for(const t of e.k)e.$&&e.$.isFoundDocument()?this.ot(t,e.$):this.ct(t,e.key,e.$);for(const n of e.removedTargetIds)this.ct(n,e.key,e.$)}at(n){this.forEachTarget(n,e=>{const t=this.ut(e);switch(n.state){case 0:this.ht(e)&&t.j(n.resumeToken);break;case 1:t.X(),t.q||t.G(),t.j(n.resumeToken);break;case 2:t.X(),t.q||this.removeTarget(e);break;case 3:this.ht(e)&&(t.Z(),t.j(n.resumeToken));break;case 4:this.ht(e)&&(this.lt(e),t.j(n.resumeToken));break;default:ER()}})}forEachTarget(e,n){0<e.targetIds.length?e.targetIds.forEach(n):this.et.forEach((e,t)=>{this.ht(t)&&n(t)})}ft(e){const t=e.targetId,n=e.O.count,r=this.dt(t);if(r){const e=r.target;if(kP(e))if(0===n){const n=new oP(e.path);this.ct(t,n,bP.newNoDocument(n,VR.min()))}else SR(1===n);else this.wt(t)!==n&&(this.lt(t),this.it=this.it.add(t))}}_t(r){const i=new Map;this.et.forEach((e,t)=>{var n=this.dt(t);if(n){if(e.current&&kP(n.target)){const i=new oP(n.target.path);null!==this.nt.get(i)||this.gt(t,i)||this.ct(t,i,bP.newNoDocument(i,r))}e.K&&(i.set(t,e.W()),e.G())}});let s=Kx();this.st.forEach((e,t)=>{let n=!0;t.forEachWhile(e=>{var t=this.dt(e);return!t||2===t.purpose||(n=!1)}),n&&(s=s.add(e))});var e=new Wx(r,i,this.it,this.nt,s);return this.nt=qx,this.st=Zx(),this.it=new Ux(FR),e}ot(e,t){var n;this.ht(e)&&(n=this.gt(e,t.key)?2:0,this.ut(e).H(t.key,n),this.nt=this.nt.insert(t.key,t),this.st=this.st.insert(t.key,this.yt(t.key).add(e)))}ct(e,t,n){if(this.ht(e)){const r=this.ut(e);this.gt(e,t)?r.H(t,1):r.J(t),this.st=this.st.insert(t,this.yt(t).delete(e)),n&&(this.nt=this.nt.insert(t,n))}}removeTarget(e){this.et.delete(e)}wt(e){var t=this.ut(e).W();return this.tt.getRemoteKeysForTarget(e).size+t.addedDocuments.size-t.removedDocuments.size}Y(e){this.ut(e).Y()}ut(e){let t=this.et.get(e);return t||(t=new Jx,this.et.set(e,t)),t}yt(e){let t=this.st.get(e);return t||(t=new Ux(FR),this.st=this.st.insert(e,t)),t}ht(e){var t=null!==this.dt(e);return t||wR("WatchChangeAggregator","Detected inactive target",e),t}dt(e){var t=this.et.get(e);return t&&t.q?null:this.tt.Tt(e)}lt(t){this.et.set(t,new Jx),this.tt.getRemoteKeysForTarget(t).forEach(e=>{this.ct(t,e,null)})}gt(e,t){return this.tt.getRemoteKeysForTarget(e).has(t)}}function Zx(){return new Lx(oP.comparator)}function eO(){return new Lx(oP.comparator)}const tO={asc:"ASCENDING",desc:"DESCENDING"},nO={"<":"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 rO{constructor(e,t){this.databaseId=e,this.D=t}}function iO(e,t){return e.D?`${new Date(1e3*t.seconds).toISOString().replace(/\.\d*/,"").replace("Z","")}.${("000000000"+t.nanoseconds).slice(-9)}Z`:{seconds:""+t.seconds,nanos:t.nanoseconds}}function sO(e,t){return e.D?t.toBase64():t.toUint8Array()}function oO(e){return SR(!!e),VR.fromTimestamp((t=XR(e),new qR(t.seconds,t.nanos)));var t}function aO(e,t){return e=e,new WR(["projects",e.projectId,"databases",e.database]).child("documents").child(t).canonicalString()}function cO(e){var t=WR.fromString(e);return SR(AO(t)),t}function lO(e,t){return aO(e.databaseId,t.path)}function uO(e,t){const n=cO(t);if(n.get(1)!==e.databaseId.projectId)throw new CR(kR.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 CR(kR.INVALID_ARGUMENT,"Tried to deserialize key from different database: "+n.get(3)+" vs "+e.databaseId.database);return new oP(pO(n))}function hO(e,t){return aO(e.databaseId,t)}function dO(e){var t=cO(e);return 4===t.length?WR.emptyPath():pO(t)}function fO(e){return new WR(["projects",e.databaseId.projectId,"databases",e.databaseId.database]).canonicalString()}function pO(e){return SR(4<e.length&&"documents"===e.get(4)),e.popFirst(5)}function gO(e,t,n){return{name:lO(e,t),fields:n.value.mapValue.fields}}function mO(e,t,n){const r=uO(e,t.name),i=oO(t.updateTime),s=new wP({mapValue:{fields:t.fields}}),o=bP.newFoundDocument(r,i,s);return n&&o.setHasCommittedMutations(),n?o.setHasCommittedMutations():o}function vO(e,t){let n;if(t instanceof Sx)n={update:gO(e,t.key,t.value)};else if(t instanceof Rx)n={delete:lO(e,t.key)};else if(t instanceof kx)n={update:gO(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 Px))return ER();n={verify:lO(e,t.key)}}return 0<t.fieldTransforms.length&&(n.updateTransforms=t.fieldTransforms.map(e=>function(e){var t=e.transform;if(t instanceof cx)return{fieldPath:e.field.canonicalString(),setToServerValue:"REQUEST_TIME"};if(t instanceof lx)return{fieldPath:e.field.canonicalString(),appendMissingElements:{values:t.elements}};if(t instanceof hx)return{fieldPath:e.field.canonicalString(),removeAllFromArray:{values:t.elements}};if(t instanceof fx)return{fieldPath:e.field.canonicalString(),increment:t.C};throw ER()}(e))),t.precondition.isNone||(n.currentDocument=void 0!==(r=t.precondition).updateTime?{updateTime:(t=r.updateTime,iO(e,t.toTimestamp()))}:void 0!==r.exists?{exists:r.exists}:ER()),n;var r}function yO(t,n){const e=n.currentDocument?void 0!==(i=n.currentDocument).updateTime?yx.updateTime(oO(i.updateTime)):void 0!==i.exists?yx.exists(i.exists):yx.none():yx.none(),r=n.updateTransforms?n.updateTransforms.map(e=>function(e,t){let n=null;if("setToServerValue"in t)SR("REQUEST_TIME"===t.setToServerValue),n=new cx;else if("appendMissingElements"in t){const e=t.appendMissingElements.values||[];n=new lx(e)}else if("removeAllFromArray"in t){const e=t.removeAllFromArray.values||[];n=new hx(e)}else"increment"in t?n=new fx(e,t.increment):ER();var r=GR.fromServerFormat(t.fieldPath);return new mx(r,n)}(t,e)):[];var i;if(n.update){n.update.name;var s=uO(t,n.update.name),o=new wP({mapValue:{fields:n.update.fields}});if(n.updateMask){const t=function(){const e=n.updateMask.fieldPaths||[];return new QR(e.map(e=>GR.fromServerFormat(e)))}();return new kx(s,o,t,e,r)}return new Sx(s,o,e,r)}if(n.delete){const r=uO(t,n.delete);return new Rx(r,e)}if(n.verify){const r=uO(t,n.verify);return new Px(r,e)}return ER()}function _O(e,t){return{documents:[hO(e,t.path)]}}function wO(e,t){const n={structuredQuery:{}},r=t.path;null!==t.collectionGroup?(n.parent=hO(e,r),n.structuredQuery.from=[{collectionId:t.collectionGroup,allDescendants:!0}]):(n.parent=hO(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(vP(e.value))return{unaryFilter:{field:EO(e.field),op:"IS_NAN"}};if(mP(e.value))return{unaryFilter:{field:EO(e.field),op:"IS_NULL"}}}else if("!="===e.op){if(vP(e.value))return{unaryFilter:{field:EO(e.field),op:"IS_NOT_NAN"}};if(mP(e.value))return{unaryFilter:{field:EO(e.field),op:"IS_NOT_NULL"}}}return{fieldFilter:{field:EO(e.field),op:(t=e.op,nO[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:EO(e.field),direction:(e=e.dir,tO[e])}}(e))}(t.orderBy);i&&(n.structuredQuery.orderBy=i);var s,i=(s=t.limit,e.D||rP(s)?s:{value:s});return null!==i&&(n.structuredQuery.limit=i),t.startAt&&(n.structuredQuery.startAt=IO(t.startAt)),t.endAt&&(n.structuredQuery.endAt=IO(t.endAt)),n}function bO(e){let t=dO(e.parent);const n=e.structuredQuery,r=n.from?n.from.length:0;let i=null;if(0<r){SR(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?[CO(e)]:void 0!==e.fieldFilter?[kO(e)]:void 0!==e.compositeFilter?e.compositeFilter.filters.map(e=>t(e)).reduce((e,t)=>e.concat(t)):ER():[]}(n.where));let o=[];n.orderBy&&(o=n.orderBy.map(e=>function(e){return new UP(SO(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,rP(c="object"==typeof e?e.value:e)?null:c));let l=null;n.startAt&&(l=TO(n.startAt));let u=null;return n.endAt&&(u=TO(n.endAt)),BP(t,i,o,s,a,"F",l,u)}function IO(e){return{before:e.before,values:e.position}}function TO(e){var t=!!e.before,n=e.values||[];return new MP(n,t)}function EO(e){return{fieldPath:e.canonicalString()}}function SO(e){return GR.fromServerFormat(e.fieldPath)}function kO(e){return CP.create(SO(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 ER()}}(),e.fieldFilter.value)}function CO(e){switch(e.unaryFilter.op){case"IS_NAN":var t=SO(e.unaryFilter.field);return CP.create(t,"==",{doubleValue:NaN});case"IS_NULL":t=SO(e.unaryFilter.field);return CP.create(t,"==",{nullValue:"NULL_VALUE"});case"IS_NOT_NAN":var n=SO(e.unaryFilter.field);return CP.create(n,"!=",{doubleValue:NaN});case"IS_NOT_NULL":n=SO(e.unaryFilter.field);return CP.create(n,"!=",{nullValue:"NULL_VALUE"});default:return ER()}}function AO(e){return 4<=e.length&&"projects"===e.get(0)&&"databases"===e.get(2)}function NO(e){let t="";for(let n=0;n<e.length;n++)0<t.length&&(t=RO(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 RO(t)}function RO(e){return e+""}function PO(t){const n=t.length;if(SR(2<=n),2===n)return SR(""===t.charAt(0)&&""===t.charAt(1)),WR.emptyPath();const r=n-2,i=[];let s="";for(let o=0;o<n;){const n=t.indexOf("",o);switch((n<0||n>r)&&ER(),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:ER()}o=n+2}return new WR(i)}class xO{constructor(e,t){this.seconds=e,this.nanoseconds=t}}class OO{constructor(e,t,n){this.ownerId=e,this.allowTabSynchronization=t,this.leaseTimestampMs=n}}OO.store="owner",OO.key="owner";class DO{constructor(e,t,n){this.userId=e,this.lastAcknowledgedBatchId=t,this.lastStreamToken=n}}DO.store="mutationQueues",DO.keyPath="userId";class LO{constructor(e,t,n,r,i){this.userId=e,this.batchId=t,this.localWriteTimeMs=n,this.baseMutations=r,this.mutations=i}}LO.store="mutations",LO.keyPath="batchId",LO.userMutationsIndex="userMutationsIndex",LO.userMutationsKeyPath=["userId","batchId"];class MO{constructor(){}static prefixForUser(e){return[e]}static prefixForPath(e,t){return[e,NO(t)]}static key(e,t,n){return[e,NO(t),n]}}MO.store="documentMutations",MO.PLACEHOLDER=new MO;class FO{constructor(e,t){this.path=e,this.readTime=t}}class UO{constructor(e,t){this.path=e,this.version=t}}class jO{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}}jO.store="remoteDocuments",jO.readTimeIndex="readTimeIndex",jO.readTimeIndexPath="readTime",jO.collectionReadTimeIndex="collectionReadTimeIndex",jO.collectionReadTimeIndexPath=["parentPath","readTime"];class qO{constructor(e){this.byteSize=e}}qO.store="remoteDocumentGlobal",qO.key="remoteDocumentGlobalKey";class VO{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}}VO.store="targets",VO.keyPath="targetId",VO.queryTargetsIndexName="queryTargetsIndex",VO.queryTargetsKeyPath=["canonicalId","targetId"];class BO{constructor(e,t,n){this.targetId=e,this.path=t,this.sequenceNumber=n}}BO.store="targetDocuments",BO.keyPath=["targetId","path"],BO.documentTargetsIndex="documentTargetsIndex",BO.documentTargetsKeyPath=["path","targetId"];class $O{constructor(e,t,n,r){this.highestTargetId=e,this.highestListenSequenceNumber=t,this.lastRemoteSnapshotVersion=n,this.targetCount=r}}$O.key="targetGlobalKey",$O.store="targetGlobal";class KO{constructor(e,t){this.collectionId=e,this.parent=t}}KO.store="collectionParents",KO.keyPath=["collectionId","parent"];class zO{constructor(e,t,n,r){this.clientId=e,this.updateTimeMs=t,this.networkEnabled=n,this.inForeground=r}}zO.store="clientMetadata",zO.keyPath="clientId";class WO{constructor(e,t,n){this.bundleId=e,this.createTime=t,this.version=n}}WO.store="bundles",WO.keyPath="bundleId";class HO{constructor(e,t,n){this.name=e,this.readTime=t,this.bundledQuery=n}}HO.store="namedQueries",HO.keyPath="name";const GO=[DO.store,LO.store,MO.store,jO.store,VO.store,OO.store,$O.store,BO.store,zO.store,qO.store,KO.store,WO.store,HO.store],QO="The current tab is not in the required state to perform this operation. It might be necessary to refresh the browser tab.";class YO{constructor(){this.onCommittedListeners=[]}addOnCommittedListener(e){this.onCommittedListeners.push(e)}raiseOnCommittedEvent(){this.onCommittedListeners.forEach(e=>e())}}class JO{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&&ER(),this.callbackAttached=!0,this.isDone?this.error?this.wrapFailure(i,this.error):this.wrapSuccess(r,this.result):new JO((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 JO?t:JO.resolve(t)}catch(e){return JO.reject(e)}}wrapSuccess(e,t){return e?this.wrapUserFunction(()=>e(t)):JO.resolve(t)}wrapFailure(e,t){return e?this.wrapUserFunction(()=>e(t)):JO.reject(t)}static resolve(n){return new JO((e,t)=>{e(n)})}static reject(n){return new JO((e,t)=>{t(n)})}static waitFor(e){return new JO((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=JO.resolve(!1);for(const n of e)t=t.next(e=>e?JO.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 XO{constructor(n,e){this.action=n,this.transaction=e,this.aborted=!1,this.Et=new AR,this.transaction.oncomplete=()=>{this.Et.resolve()},this.transaction.onabort=()=>{e.error?this.Et.reject(new tD(n,e.error)):this.Et.resolve()},this.transaction.onerror=e=>{var t=oD(e.target.error);this.Et.reject(new tD(n,t))}}static open(e,t,n,r){try{return new XO(t,e.transaction(r,n))}catch(e){throw new tD(t,e)}}get It(){return this.Et.promise}abort(e){e&&this.Et.reject(e),this.aborted||(wR("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 rD(t)}}class ZO{constructor(e,t,n){this.name=e,this.version=t,this.At=n,12.2===ZO.Rt(sd())&&bR("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 wR("SimpleDb","Removing database:",e),iD(window.indexedDB.deleteDatabase(e)).toPromise()}static bt(){if(!dd())return!1;if(ZO.Pt())return!0;const e=sd(),t=ZO.Rt(e),n=0<t&&t<10,r=ZO.vt(e),i=0<r&&r<4.5;return!(0<e.indexOf("MSIE ")||0<e.indexOf("Trident/")||0<e.indexOf("Edge/")||n||i)}static Pt(){var e;return"undefined"!=typeof process&&"YES"===(null===(e=process.env)||void 0===e?void 0:e.Vt)}static St(e,t){return e.store(t)}static Rt(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 vt(e){const t=e.match(/Android ([\d.]+)/i),n=t?t[1].split(".").slice(0,2).join("."):"-1";return Number(n)}async Dt(s){return this.db||(wR("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 tD(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 CR(kR.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 CR(kR.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 tD(s,t))},i.onupgradeneeded=e=>{wR("SimpleDb",'Database "'+this.name+'" requires upgrade from version:',e.oldVersion);var t=e.target.result;this.At.Ct(t,i.transaction,e.oldVersion,this.version).next(()=>{wR("SimpleDb","Database upgrade to version "+this.version+" complete")})}})),this.Nt&&(this.db.onversionchange=e=>this.Nt(e)),this.db}xt(t){this.Nt=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.Dt(e);const t=XO.open(this.db,e,i?"readonly":"readwrite",n),s=r(t).catch(e=>(t.abort(e),JO.reject(e))).toPromise();return s.catch(()=>{}),await t.It,s}catch(e){const t="FirebaseError"!==e.name&&s<3;if(wR("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 eD{constructor(e){this.kt=e,this.$t=!1,this.Ot=null}get isDone(){return this.$t}get Ft(){return this.Ot}set cursor(e){this.kt=e}done(){this.$t=!0}Mt(e){this.Ot=e}delete(){return iD(this.kt.delete())}}class tD extends CR{constructor(e,t){super(kR.UNAVAILABLE,`IndexedDB transaction '${e}' failed: ${t}`),this.name="IndexedDbTransactionError"}}function nD(e){return"IndexedDbTransactionError"===e.name}class rD{constructor(e){this.store=e}put(e,t){let n;return n=void 0!==t?(wR("SimpleDb","PUT",this.store.name,e,t),this.store.put(t,e)):(wR("SimpleDb","PUT",this.store.name,"<auto-key>",e),this.store.put(e)),iD(n)}add(e){return wR("SimpleDb","ADD",this.store.name,e,e),iD(this.store.add(e))}get(t){return iD(this.store.get(t)).next(e=>(wR("SimpleDb","GET",this.store.name,t,e=void 0===e?null:e),e))}delete(e){return wR("SimpleDb","DELETE",this.store.name,e),iD(this.store.delete(e))}count(){return wR("SimpleDb","COUNT",this.store.name),iD(this.store.count())}Lt(e,t){const n=this.cursor(this.options(e,t)),r=[];return this.Bt(n,(e,t)=>{r.push(t)}).next(()=>r)}Ut(e,t){wR("SimpleDb","DELETE ALL",this.store.name);const n=this.options(e,t);n.qt=!1;var r=this.cursor(n);return this.Bt(r,(e,t,n)=>n.delete())}Kt(e,t){let n;t?n=e:(n={},t=e);var r=this.cursor(n);return this.Bt(r,t)}jt(i){const e=this.cursor({});return new JO((n,r)=>{e.onerror=e=>{var t=oD(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()}})}Bt(e,s){const o=[];return new JO((i,t)=>{e.onerror=e=>{t(e.target.error)},e.onsuccess=e=>{const t=e.target.result;if(t){const n=new eD(t),r=s(t.primaryKey,t.value,n);if(r instanceof JO){const e=r.catch(e=>(n.done(),JO.reject(e)));o.push(e)}n.isDone?i():null===n.Ft?t.continue():t.continue(n.Ft)}else i()}}).next(()=>JO.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 iD(e){return new JO((n,r)=>{e.onsuccess=e=>{var t=e.target.result;n(t)},e.onerror=e=>{var t=oD(e.target.error);r(t)}})}let sD=!1;function oD(e){const t=ZO.Rt(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 CR("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 sD||(sD=!0,setTimeout(()=>{throw e},0)),e}}return e}class aD extends YO{constructor(e,t){super(),this.Qt=e,this.currentSequenceNumber=t}}function cD(e,t){var n=e;return ZO.St(n.Qt,t)}class lD{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)&&bx(i,e,n[r])}}applyToLocalView(e){for(const t of this.baseMutations)t.key.isEqual(e.key)&&Ix(t,e,this.localWriteTime);for(const n of this.mutations)n.key.isEqual(e.key)&&Ix(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(VR.min())})}keys(){return this.mutations.reduce((e,t)=>e.add(t.key),Kx())}isEqual(e){return this.batchId===e.batchId&&UR(this.mutations,e.mutations,(e,t)=>Tx(e,t))&&UR(this.baseMutations,e.baseMutations,(e,t)=>Tx(e,t))}}class uD{constructor(e,t,n,r){this.batch=e,this.commitVersion=t,this.mutationResults=n,this.docVersions=r}static from(e,t,n){SR(e.mutations.length===n.length);let r=Bx;var i=e.mutations;for(let s=0;s<i.length;s++)r=r.insert(i[s].key,n[s].version);return new uD(e,t,n,r)}}class hD{constructor(e,t,n,r,i=VR.min(),s=VR.min(),o=YR.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 hD(this.target,this.targetId,this.purpose,e,this.snapshotVersion,this.lastLimboFreeSnapshotVersion,this.resumeToken)}withResumeToken(e,t){return new hD(this.target,this.targetId,this.purpose,this.sequenceNumber,t,this.lastLimboFreeSnapshotVersion,e)}withLastLimboFreeSnapshotVersion(e){return new hD(this.target,this.targetId,this.purpose,this.sequenceNumber,this.snapshotVersion,e,this.resumeToken)}}class dD{constructor(e){this.Wt=e}}function fD(e,t){if(t.document)return mO(e.Wt,t.document,!!t.hasCommittedMutations);if(t.noDocument){const e=oP.fromSegments(t.noDocument.path),n=yD(t.noDocument.readTime),r=bP.newNoDocument(e,n);return t.hasCommittedMutations?r.setHasCommittedMutations():r}if(t.unknownDocument){const e=oP.fromSegments(t.unknownDocument.path),i=yD(t.unknownDocument.version);return bP.newUnknownDocument(e,i)}return ER()}function pD(e,t,n){var r=gD(n),i=t.key.path.popLast().toArray();if(t.isFoundDocument()){const s={name:lO(n=e.Wt,(e=t).key),fields:e.data.value.mapValue.fields,updateTime:iO(n,e.version.toTimestamp())},o=t.hasCommittedMutations;return new jO(null,null,s,o,r,i)}if(t.isNoDocument()){const a=t.key.path.toArray(),s=vD(t.version),c=t.hasCommittedMutations;return new jO(null,new FO(a,s),null,c,r,i)}if(t.isUnknownDocument()){const a=t.key.path.toArray(),s=vD(t.version);return new jO(new UO(a,s),null,null,!0,r,i)}return ER()}function gD(e){var t=e.toTimestamp();return[t.seconds,t.nanoseconds]}function mD(e){var t=new qR(e[0],e[1]);return VR.fromTimestamp(t)}function vD(e){var t=e.toTimestamp();return new xO(t.seconds,t.nanoseconds)}function yD(e){var t=new qR(e.seconds,e.nanoseconds);return VR.fromTimestamp(t)}function _D(t,e){const n=(e.baseMutations||[]).map(e=>yO(t.Wt,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=>yO(t.Wt,e)),i=qR.fromMillis(e.localWriteTimeMs);return new lD(e.batchId,i,n,r)}function wD(e){var t,n=yD(e.readTime),r=void 0!==e.lastLimboFreeSnapshotVersion?yD(e.lastLimboFreeSnapshotVersion):VR.min();let i;return i=void 0!==e.query.documents?(SR(1===(t=e.query).documents.length),YP($P(dO(t.documents[0])))):YP(bO(e.query)),new hD(i,e.targetId,0,e.lastListenSequenceNumber,n,r,YR.fromBase64String(e.resumeToken))}function bD(e,t){var n=vD(t.snapshotVersion),r=vD(t.lastLimboFreeSnapshotVersion),i=(kP(t.target)?_O:wO)(e.Wt,t.target),s=t.resumeToken.toBase64();return new VO(t.targetId,EP(t.target),n,s,t.sequenceNumber,r,i)}function ID(e){var t=bO({parent:e.parent,structuredQuery:e.structuredQuery});return"LAST"===e.limitType?JP(t,t.limit,"L"):t}class TD{getBundleMetadata(e,t){return ED(e).get(t).next(e=>{if(e)return{id:(t=e).bundleId,createTime:yD(t.createTime),version:t.version};var t})}saveBundleMetadata(e,t){return ED(e).put({bundleId:(n=t).id,createTime:vD(oO(n.createTime)),version:n.version});var n}getNamedQuery(e,t){return SD(e).get(t).next(e=>{if(e)return{name:(t=e).name,query:ID(t.bundledQuery),readTime:yD(t.readTime)};var t})}saveNamedQuery(e,t){return SD(e).put({name:(t=t).name,readTime:vD(oO(t.readTime)),bundledQuery:t.bundledQuery})}}function ED(e){return cD(e,WO.store)}function SD(e){return cD(e,HO.store)}class kD{constructor(){this.Gt=new CD}addToCollectionParentIndex(e,t){return this.Gt.add(t),JO.resolve()}getCollectionParents(e,t){return JO.resolve(this.Gt.getEntries(t))}}class CD{constructor(){this.index={}}add(e){const t=e.lastSegment(),n=e.popLast(),r=this.index[t]||new Ux(WR.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 Ux(WR.comparator)).toArray()}}class AD{constructor(){this.zt=new CD}addToCollectionParentIndex(e,t){if(this.zt.has(t))return JO.resolve();var n=t.lastSegment(),r=t.popLast();e.addOnCommittedListener(()=>{this.zt.add(t)});r={collectionId:n,parent:NO(r)};return ND(e).put(r)}getCollectionParents(e,n){const r=[],t=IDBKeyRange.bound([n,""],[jR(n),""],!1,!0);return ND(e).Lt(t).next(e=>{for(const t of e){if(t.collectionId!==n)break;r.push(PO(t.parent))}return r})}}function ND(e){return cD(e,KO.store)}const RD={didRun:!1,sequenceNumbersCollected:0,targetsRemoved:0,documentsRemoved:0};class PD{constructor(e,t,n){this.cacheSizeCollectionThreshold=e,this.percentileToCollect=t,this.maximumSequenceNumbersToCollect=n}static withCacheSize(e){return new PD(e,PD.DEFAULT_COLLECTION_PERCENTILE,PD.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT)}}function xD(e,t,n){const r=e.store(LO.store),i=e.store(MO.store),s=[],o=IDBKeyRange.only(n.batchId);let a=0;const c=r.Kt({range:o},(e,t,n)=>(a++,n.delete()));s.push(c.next(()=>{SR(1===a)}));const l=[];for(const e of n.mutations){const r=MO.key(t,e.key.path,n.batchId);s.push(i.delete(r)),l.push(e.key)}return JO.waitFor(s).next(()=>l)}function OD(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 ER();t=e.noDocument}return JSON.stringify(t).length}PD.DEFAULT_COLLECTION_PERCENTILE=10,PD.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT=1e3,PD.DEFAULT=new PD(41943040,PD.DEFAULT_COLLECTION_PERCENTILE,PD.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT),PD.DISABLED=new PD(-1,0,0);class DD{constructor(e,t,n,r){this.userId=e,this.N=t,this.Ht=n,this.referenceDelegate=r,this.Jt={}}static Yt(e,t,n,r){SR(""!==e.uid);var i=e.isAuthenticated()?e.uid:"";return new DD(i,t,n,r)}checkEmpty(e){let r=!0;var t=IDBKeyRange.bound([this.userId,Number.NEGATIVE_INFINITY],[this.userId,Number.POSITIVE_INFINITY]);return MD(e).Kt({index:LO.userMutationsIndex,range:t},(e,t,n)=>{r=!1,n.done()}).next(()=>r)}addMutationBatch(u,h,d,f){const p=FD(u),g=MD(u);return g.add({}).next(e=>{SR("number"==typeof e);const t=new lD(e,h,d,f),n=(i=this.N,s=this.userId,o=t,a=o.baseMutations.map(e=>vO(i.Wt,e)),c=o.mutations.map(e=>vO(i.Wt,e)),new LO(s,o.batchId,o.localWriteTime.toMillis(),a,c)),r=[];var i,s,o,a,c;let l=new Ux((e,t)=>FR(e.canonicalString(),t.canonicalString()));for(const u of f){const h=MO.key(this.userId,u.key.path,e);l=l.add(u.key.path.popLast()),r.push(g.put(n)),r.push(p.put(h,MO.PLACEHOLDER))}return l.forEach(e=>{r.push(this.Ht.addToCollectionParentIndex(u,e))}),u.addOnCommittedListener(()=>{this.Jt[e]=t.keys()}),JO.waitFor(r).next(()=>t)})}lookupMutationBatch(e,t){return MD(e).get(t).next(e=>e?(SR(e.userId===this.userId),_D(this.N,e)):null)}Xt(e,n){return this.Jt[n]?JO.resolve(this.Jt[n]):this.lookupMutationBatch(e,n).next(e=>{if(e){var t=e.keys();return this.Jt[n]=t}return null})}getNextMutationBatchAfterBatchId(e,t){const r=t+1,n=IDBKeyRange.lowerBound([this.userId,r]);let i=null;return MD(e).Kt({index:LO.userMutationsIndex,range:n},(e,t,n)=>{t.userId===this.userId&&(SR(t.batchId>=r),i=_D(this.N,t)),n.done()}).next(()=>i)}getHighestUnacknowledgedBatchId(e){var t=IDBKeyRange.upperBound([this.userId,Number.POSITIVE_INFINITY]);let r=-1;return MD(e).Kt({index:LO.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 MD(e).Lt(LO.userMutationsIndex,t).next(e=>e.map(e=>_D(this.N,e)))}getAllMutationBatchesAffectingDocumentKey(o,a){const e=MO.prefixForPath(this.userId,a.path),t=IDBKeyRange.lowerBound(e),c=[];return FD(o).Kt({range:t},(e,t,n)=>{var[r,i,s]=e,i=PO(i);if(r===this.userId&&a.path.isEqual(i))return MD(o).get(s).next(e=>{if(!e)throw ER();SR(e.userId===this.userId),c.push(_D(this.N,e))});n.done()}).next(()=>c)}getAllMutationBatchesAffectingDocumentKeys(t,e){let a=new Ux(FR);const n=[];return e.forEach(o=>{var e=MO.prefixForPath(this.userId,o.path),e=IDBKeyRange.lowerBound(e),e=FD(t).Kt({range:e},(e,t,n)=>{var[r,i,s]=e,i=PO(i);r===this.userId&&o.path.isEqual(i)?a=a.add(s):n.done()});n.push(e)}),JO.waitFor(n).next(()=>this.Zt(t,a))}getAllMutationBatchesAffectingQuery(e,t){const o=t.path,a=o.length+1,n=MO.prefixForPath(this.userId,o),r=IDBKeyRange.lowerBound(n);let c=new Ux(FR);return FD(e).Kt({range:r},(e,t,n)=>{var[r,i,s]=e,i=PO(i);r===this.userId&&o.isPrefixOf(i)?i.length===a&&(c=c.add(s)):n.done()}).next(()=>this.Zt(e,c))}Zt(t,e){const n=[],r=[];return e.forEach(e=>{r.push(MD(t).get(e).next(e=>{if(null===e)throw ER();SR(e.userId===this.userId),n.push(_D(this.N,e))}))}),JO.waitFor(r).next(()=>n)}removeMutationBatch(t,n){return xD(t.Qt,this.userId,n).next(e=>(t.addOnCommittedListener(()=>{this.te(n.batchId)}),JO.forEach(e,e=>this.referenceDelegate.markPotentiallyOrphaned(t,e))))}te(e){delete this.Jt[e]}performConsistencyCheck(n){return this.checkEmpty(n).next(e=>{if(!e)return JO.resolve();const t=IDBKeyRange.lowerBound(MO.prefixForUser(this.userId)),r=[];return FD(n).Kt({range:t},(e,t,n)=>{if(e[0]===this.userId){const t=PO(e[1]);r.push(t)}else n.done()}).next(()=>{SR(0===r.length)})})}containsKey(e,t){return LD(e,this.userId,t)}ee(e){return UD(e).get(this.userId).next(e=>e||new DO(this.userId,-1,""))}}function LD(e,s,t){const n=MO.prefixForPath(s,t.path),o=n[1],r=IDBKeyRange.lowerBound(n);let a=!1;return FD(e).Kt({range:r,qt:!0},(e,t,n)=>{var[r,i]=e;r===s&&i===o&&(a=!0),n.done()}).next(()=>a)}function MD(e){return cD(e,LO.store)}function FD(e){return cD(e,MO.store)}function UD(e){return cD(e,DO.store)}class jD{constructor(e){this.ne=e}next(){return this.ne+=2,this.ne}static se(){return new jD(0)}static ie(){return new jD(-1)}}class qD{constructor(e,t){this.referenceDelegate=e,this.N=t}allocateTargetId(n){return this.re(n).next(e=>{const t=new jD(e.highestTargetId);return e.highestTargetId=t.next(),this.oe(n,e).next(()=>e.highestTargetId)})}getLastRemoteSnapshotVersion(e){return this.re(e).next(e=>VR.fromTimestamp(new qR(e.lastRemoteSnapshotVersion.seconds,e.lastRemoteSnapshotVersion.nanoseconds)))}getHighestSequenceNumber(e){return this.re(e).next(e=>e.highestListenSequenceNumber)}setTargetsMetadata(t,n,r){return this.re(t).next(e=>(e.highestListenSequenceNumber=n,r&&(e.lastRemoteSnapshotVersion=r.toTimestamp()),n>e.highestListenSequenceNumber&&(e.highestListenSequenceNumber=n),this.oe(t,e)))}addTargetData(t,n){return this.ce(t,n).next(()=>this.re(t).next(e=>(e.targetCount+=1,this.ae(n,e),this.oe(t,e))))}updateTargetData(e,t){return this.ce(e,t)}removeTargetData(t,e){return this.removeMatchingKeysForTargetId(t,e.targetId).next(()=>VD(t).delete(e.targetId)).next(()=>this.re(t)).next(e=>(SR(0<e.targetCount),--e.targetCount,this.oe(t,e)))}removeTargets(r,i,s){let o=0;const a=[];return VD(r).Kt((e,t)=>{var n=wD(t);n.sequenceNumber<=i&&null===s.get(n.targetId)&&(o++,a.push(this.removeTargetData(r,n)))}).next(()=>JO.waitFor(a)).next(()=>o)}forEachTarget(e,r){return VD(e).Kt((e,t)=>{var n=wD(t);r(n)})}re(e){return BD(e).get($O.key).next(e=>(SR(null!==e),e))}oe(e,t){return BD(e).put($O.key,t)}ce(e,t){return VD(e).put(bD(this.N,t))}ae(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.re(e).next(e=>e.targetCount)}getTargetData(e,i){var t=EP(i),t=IDBKeyRange.bound([t,Number.NEGATIVE_INFINITY],[t,Number.POSITIVE_INFINITY]);let s=null;return VD(e).Kt({range:t,index:VO.queryTargetsIndexName},(e,t,n)=>{var r=wD(t);SP(i,r.target)&&(s=r,n.done())}).next(()=>s)}addMatchingKeys(n,e,r){const i=[],s=$D(n);return e.forEach(e=>{var t=NO(e.path);i.push(s.put(new BO(r,t))),i.push(this.referenceDelegate.addReference(n,r,e))}),JO.waitFor(i)}removeMatchingKeys(n,e,r){const i=$D(n);return JO.forEach(e,e=>{var t=NO(e.path);return JO.waitFor([i.delete([r,t]),this.referenceDelegate.removeReference(n,r,e)])})}removeMatchingKeysForTargetId(e,t){const n=$D(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=$D(e);let i=Kx();return r.Kt({range:n,qt:!0},(e,t,n)=>{var r=PO(e[1]),r=new oP(r);i=i.add(r)}).next(()=>i)}containsKey(e,t){var n=NO(t.path),n=IDBKeyRange.bound([n],[jR(n)],!1,!0);let r=0;return $D(e).Kt({index:BO.documentTargetsIndex,qt:!0,range:n},([e],t,n)=>{0!==e&&(r++,n.done())}).next(()=>0<r)}Tt(e,t){return VD(e).get(t).next(e=>e?wD(e):null)}}function VD(e){return cD(e,VO.store)}function BD(e){return cD(e,$O.store)}function $D(e){return cD(e,BO.store)}async function KD(e){if(e.code!==kR.FAILED_PRECONDITION||e.message!==QO)throw e;wR("LocalStore","Unexpectedly lost primary lease")}function zD([e,t],[n,r]){var i=FR(e,n);return 0===i?FR(t,r):i}class WD{constructor(e){this.ue=e,this.buffer=new Ux(zD),this.he=0}le(){return++this.he}fe(e){var t=[e,this.le()];if(this.buffer.size<this.ue)this.buffer=this.buffer.add(t);else{const e=this.buffer.last();zD(t,e)<0&&(this.buffer=this.buffer.delete(e).add(t))}}get maxValue(){return this.buffer.last()[0]}}class HD{constructor(e,t){this.garbageCollector=e,this.asyncQueue=t,this.de=!1,this.we=null}start(e){-1!==this.garbageCollector.params.cacheSizeCollectionThreshold&&this._e(e)}stop(){this.we&&(this.we.cancel(),this.we=null)}get started(){return null!==this.we}_e(e){var t=this.de?3e5:6e4;wR("LruGarbageCollector",`Garbage collection scheduled in ${t}ms`),this.we=this.asyncQueue.enqueueAfterDelay("lru_garbage_collection",t,async()=>{this.we=null,this.de=!0;try{await e.collectGarbage(this.garbageCollector)}catch(e){nD(e)?wR("LruGarbageCollector","Ignoring IndexedDB error during garbage collection: ",e):await KD(e)}await this._e(e)})}}class GD{constructor(e,t){this.me=e,this.params=t}calculateTargetCount(e,t){return this.me.ge(e).next(e=>Math.floor(t/100*e))}nthSequenceNumber(e,t){if(0===t)return JO.resolve(LR.T);const n=new WD(t);return this.me.forEachTarget(e,e=>n.fe(e.sequenceNumber)).next(()=>this.me.ye(e,e=>n.fe(e))).next(()=>n.maxValue)}removeTargets(e,t,n){return this.me.removeTargets(e,t,n)}removeOrphanedDocuments(e,t){return this.me.removeOrphanedDocuments(e,t)}collect(t,n){return-1===this.params.cacheSizeCollectionThreshold?(wR("LruGarbageCollector","Garbage collection skipped; disabled"),JO.resolve(RD)):this.getCacheSize(t).next(e=>e<this.params.cacheSizeCollectionThreshold?(wR("LruGarbageCollector",`Garbage collection skipped; Cache size ${e} is lower than threshold ${this.params.cacheSizeCollectionThreshold}`),RD):this.pe(t,n))}getCacheSize(e){return this.me.getCacheSize(e)}pe(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?(wR("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(),_R()<=Kh.DEBUG&&wR("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`),JO.resolve({didRun:!0,sequenceNumbersCollected:i,targetsRemoved:s,documentsRemoved:e})))}}class QD{constructor(e,t){this.db=e,this.garbageCollector=(e=this,t=t,new GD(e,t))}ge(e){const n=this.Te(e);return this.db.getTargetCache().getTargetCount(e).next(t=>n.next(e=>t+e))}Te(e){let t=0;return this.ye(e,e=>{t++}).next(()=>t)}forEachTarget(e,t){return this.db.getTargetCache().forEachTarget(e,t)}ye(e,n){return this.Ee(e,(e,t)=>n(t))}addReference(e,t,n){return YD(e,n)}removeReference(e,t,n){return YD(e,n)}removeTargets(e,t,n){return this.db.getTargetCache().removeTargets(e,t,n)}markPotentiallyOrphaned(e,t){return YD(e,t)}Ie(t,n){let r=!1;return UD(t).jt(e=>LD(t,e,n).next(e=>(e&&(r=!0),JO.resolve(!e)))).next(()=>r)}removeOrphanedDocuments(n,r){const i=this.db.getRemoteDocumentCache().newChangeBuffer(),s=[];let o=0;return this.Ee(n,(t,e)=>{if(e<=r){const r=this.Ie(n,t).next(e=>{if(!e)return o++,i.getEntry(n,t).next(()=>(i.removeEntry(t),$D(n).delete([0,NO(t.path)])))});s.push(r)}}).next(()=>JO.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 YD(e,t)}Ee(e,r){const t=$D(e);let i,s=LR.T;return t.Kt({index:BO.documentTargetsIndex},([e],{path:t,sequenceNumber:n})=>{0===e?(s!==LR.T&&r(new oP(PO(i)),s),s=n,i=t):s=LR.T}).next(()=>{s!==LR.T&&r(new oP(PO(i)),s)})}getCacheSize(e){return this.db.getRemoteDocumentCache().getSize(e)}}function YD(e,t){return $D(e).put((t=t,e=e.currentSequenceNumber,new BO(0,NO(t.path),e)))}class JD{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){$R(this.inner,(e,t)=>{for(const[e,n]of t)r(e,n)})}isEmpty(){return KR(this.inner)}}class XD{constructor(){this.changes=new JD(e=>e.toString(),(e,t)=>e.isEqual(t)),this.changesApplied=!1}getReadTime(e){var t=this.changes.get(e);return t?t.readTime:VR.min()}addEntry(e,t){this.assertNotApplied(),this.changes.set(e.key,{document:e,readTime:t})}removeEntry(e,t=null){this.assertNotApplied(),this.changes.set(e,{document:bP.newInvalidDocument(e),readTime:t})}getEntry(e,t){this.assertNotApplied();var n=this.changes.get(t);return void 0!==n?JO.resolve(n.document):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 ZD{constructor(e,t){this.N=e,this.Ht=t}addEntry(e,t,n){return n1(e).put(r1(t),n)}removeEntry(e,t){const n=n1(e),r=r1(t);return n.delete(r)}updateMetadata(t,n){return this.getMetadata(t).next(e=>(e.byteSize+=n,this.Ae(t,e)))}getEntry(e,t){return n1(e).get(r1(t)).next(e=>this.Re(t,e))}be(e,t){return n1(e).get(r1(t)).next(e=>({document:this.Re(t,e),size:OD(e)}))}getEntries(e,t){let r=qx;return this.Pe(e,t,(e,t)=>{var n=this.Re(e,t);r=r.insert(e,n)}).next(()=>r)}ve(e,t){let r=qx,i=new Lx(oP.comparator);return this.Pe(e,t,(e,t)=>{var n=this.Re(e,t);r=r.insert(e,n),i=i.insert(e,OD(t))}).next(()=>({documents:r,Ve:i}))}Pe(e,t,i){if(t.isEmpty())return JO.resolve();const n=IDBKeyRange.bound(t.first().path.toArray(),t.last().path.toArray()),s=t.getIterator();let o=s.getNext();return n1(e).Kt({range:n},(e,t,n)=>{for(var r=oP.fromSegments(e);o&&oP.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.Mt(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(VR.min())){const e=i.path.toArray();n.range=IDBKeyRange.lowerBound(e)}else{const e=i.path.toArray(),s=gD(t);n.range=IDBKeyRange.lowerBound([e,s],!0),n.index=jO.collectionReadTimeIndex}return n1(e).Kt(n,(e,t,n)=>{var r;e.length===o&&(r=fD(this.N,t),i.path.isPrefixOf(r.key.path)?tx(i,r)&&(s=s.insert(r.key,r)):n.done())}).next(()=>s)}newChangeBuffer(e){return new e1(this,!!e&&e.trackRemovals)}getSize(e){return this.getMetadata(e).next(e=>e.byteSize)}getMetadata(e){return t1(e).get(qO.key).next(e=>(SR(!!e),e))}Ae(e,t){return t1(e).put(qO.key,t)}Re(e,t){if(t){const e=fD(this.N,t);if(!e.isNoDocument()||!e.version.isEqual(VR.min()))return e}return bP.newInvalidDocument(e)}}class e1 extends XD{constructor(e,t){super(),this.Se=e,this.trackRemovals=t,this.De=new JD(e=>e.toString(),(e,t)=>e.isEqual(t))}applyChanges(s){const o=[];let a=0,c=new Ux((e,t)=>FR(e.canonicalString(),t.canonicalString()));return this.changes.forEach((e,t)=>{var n=this.De.get(e);if(t.document.isValidDocument()){var r=pD(this.Se.N,t.document,this.getReadTime(e));c=c.add(e.path.popLast());var i=OD(r);a+=i-n,o.push(this.Se.addEntry(s,e,r))}else if(a-=n,this.trackRemovals){const a=pD(this.Se.N,bP.newNoDocument(e,VR.min()),this.getReadTime(e));o.push(this.Se.addEntry(s,e,a))}else o.push(this.Se.removeEntry(s,e))}),c.forEach(e=>{o.push(this.Se.Ht.addToCollectionParentIndex(s,e))}),o.push(this.Se.updateMetadata(s,a)),JO.waitFor(o)}getFromCache(e,t){return this.Se.be(e,t).next(e=>(this.De.set(t,e.size),e.document))}getAllFromCache(e,t){return this.Se.ve(e,t).next(({documents:e,Ve:t})=>(t.forEach((e,t)=>{this.De.set(e,t)}),e))}}function t1(e){return cD(e,qO.store)}function n1(e){return cD(e,jO.store)}function r1(e){return e.path.toArray()}class i1{constructor(e){this.N=e}Ct(t,n,e,r){SR(e<r&&0<=e&&r<=11);const i=new XO("createOrUpgrade",n);var s;e<1&&1<=r&&(t.createObjectStore(OO.store),(s=t).createObjectStore(DO.store,{keyPath:DO.keyPath}),s.createObjectStore(LO.store,{keyPath:LO.keyPath,autoIncrement:!0}).createIndex(LO.userMutationsIndex,LO.userMutationsKeyPath,{unique:!0}),s.createObjectStore(MO.store),s1(t),t.createObjectStore(jO.store));let o=JO.resolve();return e<3&&3<=r&&(0!==e&&((s=t).deleteObjectStore(BO.store),s.deleteObjectStore(VO.store),s.deleteObjectStore($O.store),s1(t)),o=o.next(()=>function(){const e=i.store($O.store),t=new $O(0,0,VR.min().toTimestamp(),0);return e.put($O.key,t)}())),e<4&&4<=r&&(0!==e&&(o=o.next(()=>function(r,i){return i.store(LO.store).Lt().next(e=>{r.deleteObjectStore(LO.store),r.createObjectStore(LO.store,{keyPath:LO.keyPath,autoIncrement:!0}).createIndex(LO.userMutationsIndex,LO.userMutationsKeyPath,{unique:!0});const t=i.store(LO.store),n=e.map(e=>t.put(e));return JO.waitFor(n)})}(t,i))),o=o.next(()=>{t.createObjectStore(zO.store,{keyPath:zO.keyPath})})),e<5&&5<=r&&(o=o.next(()=>this.Ce(i))),e<6&&6<=r&&(o=o.next(()=>(t.createObjectStore(qO.store),this.Ne(i)))),e<7&&7<=r&&(o=o.next(()=>this.xe(i))),e<8&&8<=r&&(o=o.next(()=>this.ke(t,i))),e<9&&9<=r&&(o=o.next(()=>{var e;(e=t).objectStoreNames.contains("remoteDocumentChanges")&&e.deleteObjectStore("remoteDocumentChanges"),function(){const e=n.objectStore(jO.store);e.createIndex(jO.readTimeIndex,jO.readTimeIndexPath,{unique:!1}),e.createIndex(jO.collectionReadTimeIndex,jO.collectionReadTimeIndexPath,{unique:!1})}()})),e<10&&10<=r&&(o=o.next(()=>this.$e(i))),e<11&&11<=r&&(o=o.next(()=>{t.createObjectStore(WO.store,{keyPath:WO.keyPath}),t.createObjectStore(HO.store,{keyPath:HO.keyPath})})),o}Ne(t){let n=0;return t.store(jO.store).Kt((e,t)=>{n+=OD(t)}).next(()=>{var e=new qO(n);return t.store(qO.store).put(qO.key,e)})}Ce(r){const e=r.store(DO.store),t=r.store(LO.store);return e.Lt().next(e=>JO.forEach(e,n=>{var e=IDBKeyRange.bound([n.userId,-1],[n.userId,n.lastAcknowledgedBatchId]);return t.Lt(LO.userMutationsIndex,e).next(e=>JO.forEach(e,e=>{SR(e.userId===n.userId);var t=_D(this.N,e);return xD(r,n.userId,t).next(()=>{})}))}))}xe(e){const o=e.store(BO.store),t=e.store(jO.store);return e.store($O.store).get($O.key).next(i=>{const s=[];return t.Kt((e,t)=>{const n=new WR(e),r=[0,NO(n)];s.push(o.get(r).next(e=>e?JO.resolve():(e=>o.put(new BO(0,NO(e),i.highestListenSequenceNumber)))(n)))}).next(()=>JO.waitFor(s))})}ke(e,t){e.createObjectStore(KO.store,{keyPath:KO.keyPath});const n=t.store(KO.store),r=new CD,i=e=>{if(r.add(e)){const t=e.lastSegment(),r=e.popLast();return n.put({collectionId:t,parent:NO(r)})}};return t.store(jO.store).Kt({qt:!0},(e,t)=>{const n=new WR(e);return i(n.popLast())}).next(()=>t.store(MO.store).Kt({qt:!0},([,e],t)=>{const n=PO(e);return i(n.popLast())}))}$e(e){const r=e.store(VO.store);return r.Kt((e,t)=>{var n=wD(t),n=bD(this.N,n);return r.put(n)})}}function s1(e){e.createObjectStore(BO.store,{keyPath:BO.keyPath}).createIndex(BO.documentTargetsIndex,BO.documentTargetsKeyPath,{unique:!0}),e.createObjectStore(VO.store,{keyPath:VO.keyPath}).createIndex(VO.queryTargetsIndexName,VO.queryTargetsKeyPath,{unique:!0}),e.createObjectStore($O.store)}const o1="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 a1{constructor(e,t,n,r,i,s,o,a,c,l){if(this.allowTabSynchronization=e,this.persistenceKey=t,this.clientId=n,this.Oe=i,this.window=s,this.document=o,this.Fe=c,this.Me=l,this.Le=null,this.Be=!1,this.isPrimary=!1,this.networkEnabled=!0,this.Ue=null,this.inForeground=!1,this.qe=null,this.Ke=null,this.je=Number.NEGATIVE_INFINITY,this.Qe=e=>Promise.resolve(),!a1.bt())throw new CR(kR.UNIMPLEMENTED,"This platform is either missing IndexedDB or is known to have an incomplete implementation. Offline persistence has been disabled.");this.referenceDelegate=new QD(this,r),this.We=t+"main",this.N=new dD(a),this.Ge=new ZO(this.We,11,new i1(this.N)),this.ze=new qD(this.referenceDelegate,this.N),this.Ht=new AD,this.He=(t=this.N,a=this.Ht,new ZD(t,a)),this.Je=new TD,this.window&&this.window.localStorage?this.Ye=this.window.localStorage:(this.Ye=null,!1===l&&bR("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.Xe().then(()=>{if(!this.isPrimary&&!this.allowTabSynchronization)throw new CR(kR.FAILED_PRECONDITION,o1);return this.Ze(),this.tn(),this.en(),this.runTransaction("getHighestListenSequenceNumber","readonly",e=>this.ze.getHighestSequenceNumber(e))}).then(e=>{this.Le=new LR(e,this.Fe)}).then(()=>{this.Be=!0}).catch(e=>(this.Ge&&this.Ge.close(),Promise.reject(e)))}nn(t){return this.Qe=async e=>{if(this.started)return t(e)},t(this.isPrimary)}setDatabaseDeletedListener(t){this.Ge.xt(async e=>{null===e.newVersion&&await t()})}setNetworkEnabled(e){this.networkEnabled!==e&&(this.networkEnabled=e,this.Oe.enqueueAndForget(async()=>{this.started&&await this.Xe()}))}Xe(){return this.runTransaction("updateClientMetadataAndTryBecomePrimary","readwrite",t=>l1(t).put(new zO(this.clientId,Date.now(),this.networkEnabled,this.inForeground)).next(()=>{if(this.isPrimary)return this.sn(t).next(e=>{e||(this.isPrimary=!1,this.Oe.enqueueRetryable(()=>this.Qe(!1)))})}).next(()=>this.rn(t)).next(e=>this.isPrimary&&!e?this.on(t).next(()=>!1):!!e&&this.cn(t).next(()=>!0))).catch(e=>{if(nD(e))return wR("IndexedDbPersistence","Failed to extend owner lease: ",e),this.isPrimary;if(!this.allowTabSynchronization)throw e;return wR("IndexedDbPersistence","Releasing owner lease after error during lease refresh",e),!1}).then(e=>{this.isPrimary!==e&&this.Oe.enqueueRetryable(()=>this.Qe(e)),this.isPrimary=e})}sn(e){return c1(e).get(OO.key).next(e=>JO.resolve(this.an(e)))}un(e){return l1(e).delete(this.clientId)}async hn(){if(this.isPrimary&&!this.ln(this.je,18e5)){this.je=Date.now();var e=await this.runTransaction("maybeGarbageCollectMultiClientState","readwrite-primary",e=>{const r=cD(e,zO.store);return r.Lt().next(e=>{const t=this.fn(e,18e5),n=e.filter(e=>-1===t.indexOf(e));return JO.forEach(n,e=>r.delete(e.clientId)).next(()=>n)})}).catch(()=>[]);if(this.Ye)for(const t of e)this.Ye.removeItem(this.dn(t.clientId))}}en(){this.Ke=this.Oe.enqueueAfterDelay("client_metadata_refresh",4e3,()=>this.Xe().then(()=>this.hn()).then(()=>this.en()))}an(e){return!!e&&e.ownerId===this.clientId}rn(t){return this.Me?JO.resolve(!0):c1(t).get(OO.key).next(e=>{if(null!==e&&this.ln(e.leaseTimestampMs,5e3)&&!this.wn(e.ownerId)){if(this.an(e)&&this.networkEnabled)return!0;if(!this.an(e)){if(!e.allowTabSynchronization)throw new CR(kR.FAILED_PRECONDITION,o1);return!1}}return!(!this.networkEnabled||!this.inForeground)||l1(t).Lt().next(e=>void 0===this.fn(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&&wR("IndexedDbPersistence",`Client ${e?"is":"is not"} eligible for a primary lease.`),e))}async shutdown(){this.Be=!1,this._n(),this.Ke&&(this.Ke.cancel(),this.Ke=null),this.mn(),this.gn(),await this.Ge.runTransaction("shutdown","readwrite",[OO.store,zO.store],e=>{const t=new aD(e,LR.T);return this.on(t).next(()=>this.un(t))}),this.Ge.close(),this.yn()}fn(e,t){return e.filter(e=>this.ln(e.updateTimeMs,t)&&!this.wn(e.clientId))}pn(){return this.runTransaction("getActiveClients","readonly",e=>l1(e).Lt().next(e=>this.fn(e,18e5).map(e=>e.clientId)))}get started(){return this.Be}getMutationQueue(e){return DD.Yt(e,this.N,this.Ht,this.referenceDelegate)}getTargetCache(){return this.ze}getRemoteDocumentCache(){return this.He}getIndexManager(){return this.Ht}getBundleCache(){return this.Je}runTransaction(t,n,r){wR("IndexedDbPersistence","Starting transaction:",t);let i;return this.Ge.runTransaction(t,"readonly"===n?"readonly":"readwrite",GO,e=>(i=new aD(e,this.Le?this.Le.next():LR.T),"readwrite-primary"===n?this.sn(i).next(e=>!!e||this.rn(i)).next(e=>{if(!e)throw bR(`Failed to obtain primary lease for action '${t}'.`),this.isPrimary=!1,this.Oe.enqueueRetryable(()=>this.Qe(!1)),new CR(kR.FAILED_PRECONDITION,QO);return r(i)}).next(e=>this.cn(i).next(()=>e)):this.Tn(i).next(()=>r(i)))).then(e=>(i.raiseOnCommittedEvent(),e))}Tn(e){return c1(e).get(OO.key).next(e=>{if(null!==e&&this.ln(e.leaseTimestampMs,5e3)&&!this.wn(e.ownerId)&&!this.an(e)&&!(this.Me||this.allowTabSynchronization&&e.allowTabSynchronization))throw new CR(kR.FAILED_PRECONDITION,o1)})}cn(e){var t=new OO(this.clientId,this.allowTabSynchronization,Date.now());return c1(e).put(OO.key,t)}static bt(){return ZO.bt()}on(e){const t=c1(e);return t.get(OO.key).next(e=>this.an(e)?(wR("IndexedDbPersistence","Releasing primary lease."),t.delete(OO.key)):JO.resolve())}ln(e,t){var n=Date.now();return!(e<n-t||n<e&&(bR(`Detected an update time that is in the future: ${e} > ${n}`),1))}Ze(){null!==this.document&&"function"==typeof this.document.addEventListener&&(this.qe=()=>{this.Oe.enqueueAndForget(()=>(this.inForeground="visible"===this.document.visibilityState,this.Xe()))},this.document.addEventListener("visibilitychange",this.qe),this.inForeground="visible"===this.document.visibilityState)}mn(){this.qe&&(this.document.removeEventListener("visibilitychange",this.qe),this.qe=null)}tn(){var e;"function"==typeof(null===(e=this.window)||void 0===e?void 0:e.addEventListener)&&(this.Ue=()=>{this._n(),!ad()&&navigator.userAgent.includes("Safari")&&!navigator.userAgent.includes("Chrome")&&navigator.appVersion.match("Version/14")&&this.Oe.enterRestrictedMode(!0),this.Oe.enqueueAndForget(()=>this.shutdown())},this.window.addEventListener("pagehide",this.Ue))}gn(){this.Ue&&(this.window.removeEventListener("pagehide",this.Ue),this.Ue=null)}wn(e){var t;try{var n=null!==(null===(t=this.Ye)||void 0===t?void 0:t.getItem(this.dn(e)));return wR("IndexedDbPersistence",`Client '${e}' ${n?"is":"is not"} zombied in LocalStorage`),n}catch(e){return bR("IndexedDbPersistence","Failed to get zombied client id.",e),!1}}_n(){if(this.Ye)try{this.Ye.setItem(this.dn(this.clientId),String(Date.now()))}catch(e){bR("Failed to set zombie client id.",e)}}yn(){if(this.Ye)try{this.Ye.removeItem(this.dn(this.clientId))}catch(e){}}dn(e){return`firestore_zombie_${this.persistenceKey}_${e}`}}function c1(e){return cD(e,OO.store)}function l1(e){return cD(e,zO.store)}function u1(e,t){let n=e.projectId;return e.isDefaultDatabase||(n+="."+e.database),"firestore/"+t+"/"+n+"/"}class h1{constructor(e,t){this.progress=e,this.En=t}}class d1{constructor(e,t,n){this.He=e,this.In=t,this.Ht=n}An(t,n){return this.In.getAllMutationBatchesAffectingDocumentKey(t,n).next(e=>this.Rn(t,n,e))}Rn(e,t,n){return this.He.getEntry(e,t).next(e=>{for(const t of n)t.applyToLocalView(e);return e})}bn(e,n){e.forEach((e,t)=>{for(const e of n)e.applyToLocalView(t)})}Pn(t,e){return this.He.getEntries(t,e).next(e=>this.vn(t,e).next(()=>e))}vn(e,t){return this.In.getAllMutationBatchesAffectingDocumentKeys(e,t).next(e=>this.bn(t,e))}getDocumentsMatchingQuery(e,t,n){return r=t,oP.isDocumentKey(r.path)&&null===r.collectionGroup&&0===r.filters.length?this.Vn(e,t.path):GP(t)?this.Sn(e,t,n):this.Dn(e,t,n);var r}Vn(e,t){return this.An(e,new oP(t)).next(e=>{let t=Vx;return e.isFoundDocument()&&(t=t.insert(e.key,e)),t})}Sn(r,i,s){const o=i.collectionGroup;let a=Vx;return this.Ht.getCollectionParents(r,o).next(e=>JO.forEach(e,e=>{var t,n=(t=i,e=e.child(o),new VP(e,null,t.explicitOrderBy.slice(),t.filters.slice(),t.limit,t.limitType,t.startAt,t.endAt));return this.Dn(r,n,s).next(e=>{e.forEach((e,t)=>{a=a.insert(e,t)})})}).next(()=>a))}Dn(t,n,e){let i,s;return this.He.getDocumentsMatchingQuery(t,n,e).next(e=>(i=e,this.In.getAllMutationBatchesAffectingQuery(t,n))).next(e=>(s=e,this.Cn(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=bP.newInvalidDocument(n),i=i.insert(n,e)),Ix(r,e,t.localWriteTime),e.isFoundDocument()||(i=i.remove(n))}}))).next(()=>(i.forEach((e,t)=>{tx(n,t)||(i=i.remove(e))}),i))}Cn(e,t,n){let r=Kx();for(const e of t)for(const t of e.mutations)t instanceof kx&&null===n.get(t.key)&&(r=r.add(t.key));let i=n;return this.He.getEntries(e,r).next(e=>(e.forEach((e,t)=>{t.isFoundDocument()&&(i=i.insert(e,t))}),i))}}class f1{constructor(e,t,n,r){this.targetId=e,this.fromCache=t,this.Nn=n,this.xn=r}static kn(e,t){let n=Kx(),r=Kx();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 f1(e,t.fromCache,n,r)}}class p1{$n(e){this.On=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(VR.min())?this.Fn(t,r):this.On.Pn(t,s).next(e=>{const n=this.Mn(r,e);return(KP(r)||zP(r))&&this.Ln(r.limitType,n,s,i)?this.Fn(t,r):(_R()<=Kh.DEBUG&&wR("QueryEngine","Re-using previous result from %s to execute query: %s",i.toString(),ex(r)),this.On.getDocumentsMatchingQuery(t,r,i).next(t=>(n.forEach(e=>{t=t.insert(e.key,e)}),t)))});var e}Mn(n,e){let r=new Ux(nx(n));return e.forEach((e,t)=>{tx(n,t)&&(r=r.add(t))}),r}Ln(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))}Fn(e,t){return _R()<=Kh.DEBUG&&wR("QueryEngine","Using full collection scan to execute query:",ex(t)),this.On.getDocumentsMatchingQuery(e,t,VR.min())}}class g1{constructor(e,t,n,r){this.persistence=e,this.Bn=t,this.N=r,this.Un=new Lx(FR),this.qn=new JD(e=>EP(e),SP),this.Kn=VR.min(),this.In=e.getMutationQueue(n),this.jn=e.getRemoteDocumentCache(),this.ze=e.getTargetCache(),this.Qn=new d1(this.jn,this.In,this.persistence.getIndexManager()),this.Je=e.getBundleCache(),this.Bn.$n(this.Qn)}collectGarbage(t){return this.persistence.runTransaction("Collect garbage","readwrite-primary",e=>t.collect(e,this.Un))}}function m1(e,t,n,r){return new g1(e,t,n,r)}async function v1(e,t){const n=e;let r=n.In,o=n.Qn;var i=await n.persistence.runTransaction("Handle user change","readonly",i=>{let s;return n.In.getAllMutationBatches(i).next(e=>(s=e,r=n.persistence.getMutationQueue(t),o=new d1(n.jn,r,n.persistence.getIndexManager()),r.getAllMutationBatches(i))).next(e=>{const t=[],n=[];let r=Kx();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.Pn(i,r).next(e=>({Wn:e,removedBatchIds:t,addedBatchIds:n}))})});return n.In=r,n.Qn=o,n.Bn.$n(n.Qn),i}function y1(e){const t=e;return t.persistence.runTransaction("Get last remote snapshot version","readonly",e=>t.ze.getLastRemoteSnapshotVersion(e))}function _1(e,n){const u=e,h=n.snapshotVersion;let d=u.Un;return u.persistence.runTransaction("Apply remote event","readwrite-primary",c=>{const e=u.jn.newChangeBuffer({trackRemovals:!0});d=u.Un;const l=[];n.targetChanges.forEach((e,t)=>{const n=d.get(t);if(n){l.push(u.ze.removeMatchingKeys(c,e.removedDocuments,t).next(()=>u.ze.addMatchingKeys(c,e.addedDocuments,t)));const a=e.resumeToken;var r,i,s,o;0<a.approximateByteSize()&&(r=n.withResumeToken(a,h).withSequenceNumber(c.currentSequenceNumber),d=d.insert(t,r),i=n,o=e,SR(0<(s=r).resumeToken.approximateByteSize()),0!==i.resumeToken.approximateByteSize()&&!(3e8<=s.snapshotVersion.toMicroseconds()-i.snapshotVersion.toMicroseconds()||0<o.addedDocuments.size+o.modifiedDocuments.size+o.removedDocuments.size)||l.push(u.ze.updateTargetData(c,r)))}});let t=qx;if(n.documentUpdates.forEach((e,t)=>{n.resolvedLimboDocuments.has(e)&&l.push(u.persistence.referenceDelegate.updateLimboDocument(c,e))}),l.push(w1(c,e,n.documentUpdates,h,void 0).next(e=>{t=e})),!h.isEqual(VR.min())){const n=u.ze.getLastRemoteSnapshotVersion(c).next(e=>u.ze.setTargetsMetadata(c,c.currentSequenceNumber,h));l.push(n)}return JO.waitFor(l).next(()=>e.apply(c)).next(()=>u.Qn.vn(c,t)).next(()=>t)}).then(e=>(u.Un=d,e))}function w1(e,o,t,a,c){let n=Kx();return t.forEach(e=>n=n.add(e)),o.getEntries(e,n).next(i=>{let s=qx;return t.forEach((e,t)=>{const n=i.get(e),r=(null==c?void 0:c.get(e))||a;t.isNoDocument()&&t.version.isEqual(VR.min())?(o.removeEntry(e,r),s=s.insert(e,t)):!n.isValidDocument()||0<t.version.compareTo(n.version)||0===t.version.compareTo(n.version)&&n.hasPendingWrites?(o.addEntry(t,r),s=s.insert(e,t)):wR("LocalStore","Ignoring outdated watch update for ",e,". Current version:",n.version," Watch version:",t.version)}),s})}function b1(e,r){const i=e;return i.persistence.runTransaction("Allocate target","readwrite",t=>{let n;return i.ze.getTargetData(t,r).next(e=>e?(n=e,JO.resolve(n)):i.ze.allocateTargetId(t).next(e=>(n=new hD(r,e,0,t.currentSequenceNumber),i.ze.addTargetData(t,n).next(()=>n))))}).then(e=>{var t=i.Un.get(e.targetId);return(null===t||0<e.snapshotVersion.compareTo(t.snapshotVersion))&&(i.Un=i.Un.insert(e.targetId,e),i.qn.set(r,e.targetId)),e})}async function I1(e,t,n){const r=e,i=r.Un.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(!nD(e))throw e;wR("LocalStore",`Failed to update sequence numbers for target ${t}: ${e}`)}r.Un=r.Un.remove(t),r.qn.delete(i.target)}function T1(e,n,r){const i=e;let s=VR.min(),o=Kx();return i.persistence.runTransaction("Execute query","readonly",t=>function(e,t,n){const r=e,i=r.qn.get(n);return void 0!==i?JO.resolve(r.Un.get(i)):r.ze.getTargetData(t,n)}(i,t,YP(n)).next(e=>{if(e)return s=e.lastLimboFreeSnapshotVersion,i.ze.getMatchingKeysForTargetId(t,e.targetId).next(e=>{o=e})}).next(()=>i.Bn.getDocumentsMatchingQuery(t,n,r?s:VR.min(),r?o:Kx())).next(e=>({documents:e,Gn:o})))}function E1(e,t){const n=e,r=n.ze,i=n.Un.get(t);return i?Promise.resolve(i.target):n.persistence.runTransaction("Get target data","readonly",e=>r.Tt(e,t).next(e=>e?e.target:null))}function S1(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=gD(n);const o=n1(t),a=IDBKeyRange.lowerBound(s,!0);return o.Kt({index:jO.readTimeIndex,range:a},(e,t)=>{var n=fD(r.N,t);i=i.insert(n.key,n),s=t.readTime}).next(()=>({En:i,readTime:mD(s)}))}(n.jn,e,n.Kn)).then(({En:e,readTime:t})=>(n.Kn=t,e))}class k1{constructor(e){this.N=e,this.Yn=new Map,this.Xn=new Map}getBundleMetadata(e,t){return JO.resolve(this.Yn.get(t))}saveBundleMetadata(e,t){return this.Yn.set(t.id,{id:t.id,version:t.version,createTime:oO(t.createTime)}),JO.resolve()}getNamedQuery(e,t){return JO.resolve(this.Xn.get(t))}saveNamedQuery(e,t){return this.Xn.set(t.name,{name:(t=t).name,query:ID(t.bundledQuery),readTime:oO(t.readTime)}),JO.resolve()}}class C1{constructor(){this.Zn=new Ux(A1.ts),this.es=new Ux(A1.ns)}isEmpty(){return this.Zn.isEmpty()}addReference(e,t){var n=new A1(e,t);this.Zn=this.Zn.add(n),this.es=this.es.add(n)}ss(e,t){e.forEach(e=>this.addReference(e,t))}removeReference(e,t){this.rs(new A1(e,t))}os(e,t){e.forEach(e=>this.removeReference(e,t))}cs(e){const t=new oP(new WR([])),n=new A1(t,e),r=new A1(t,e+1),i=[];return this.es.forEachInRange([n,r],e=>{this.rs(e),i.push(e.key)}),i}us(){this.Zn.forEach(e=>this.rs(e))}rs(e){this.Zn=this.Zn.delete(e),this.es=this.es.delete(e)}hs(e){var t=new oP(new WR([])),n=new A1(t,e),t=new A1(t,e+1);let r=Kx();return this.es.forEachInRange([n,t],e=>{r=r.add(e.key)}),r}containsKey(e){var t=new A1(e,0),t=this.Zn.firstAfterOrEqual(t);return null!==t&&e.isEqual(t.key)}}class A1{constructor(e,t){this.key=e,this.ls=t}static ts(e,t){return oP.comparator(e.key,t.key)||FR(e.ls,t.ls)}static ns(e,t){return FR(e.ls,t.ls)||oP.comparator(e.key,t.key)}}class N1{constructor(e,t){this.Ht=e,this.referenceDelegate=t,this.In=[],this.fs=1,this.ds=new Ux(A1.ts)}checkEmpty(e){return JO.resolve(0===this.In.length)}addMutationBatch(e,t,n,r){var i=this.fs;this.fs++,0<this.In.length&&this.In[this.In.length-1];var s=new lD(i,t,n,r);this.In.push(s);for(const t of r)this.ds=this.ds.add(new A1(t.key,i)),this.Ht.addToCollectionParentIndex(e,t.key.path.popLast());return JO.resolve(s)}lookupMutationBatch(e,t){return JO.resolve(this.ws(t))}getNextMutationBatchAfterBatchId(e,t){var n=this._s(t+1),n=n<0?0:n;return JO.resolve(this.In.length>n?this.In[n]:null)}getHighestUnacknowledgedBatchId(){return JO.resolve(0===this.In.length?-1:this.fs-1)}getAllMutationBatches(e){return JO.resolve(this.In.slice())}getAllMutationBatchesAffectingDocumentKey(e,t){const n=new A1(t,0),r=new A1(t,Number.POSITIVE_INFINITY),i=[];return this.ds.forEachInRange([n,r],e=>{var t=this.ws(e.ls);i.push(t)}),JO.resolve(i)}getAllMutationBatchesAffectingDocumentKeys(e,t){let r=new Ux(FR);return t.forEach(e=>{var t=new A1(e,0),n=new A1(e,Number.POSITIVE_INFINITY);this.ds.forEachInRange([t,n],e=>{r=r.add(e.ls)})}),JO.resolve(this.gs(r))}getAllMutationBatchesAffectingQuery(e,t){const n=t.path,r=n.length+1;let i=n;oP.isDocumentKey(i)||(i=i.child(""));var s=new A1(new oP(i),0);let o=new Ux(FR);return this.ds.forEachWhile(e=>{var t=e.key.path;return!!n.isPrefixOf(t)&&(t.length===r&&(o=o.add(e.ls)),!0)},s),JO.resolve(this.gs(o))}gs(e){const n=[];return e.forEach(e=>{var t=this.ws(e);null!==t&&n.push(t)}),n}removeMutationBatch(n,r){SR(0===this.ys(r.batchId,"removed")),this.In.shift();let i=this.ds;return JO.forEach(r.mutations,e=>{var t=new A1(e.key,r.batchId);return i=i.delete(t),this.referenceDelegate.markPotentiallyOrphaned(n,e.key)}).next(()=>{this.ds=i})}te(e){}containsKey(e,t){var n=new A1(t,0),n=this.ds.firstAfterOrEqual(n);return JO.resolve(t.isEqual(n&&n.key))}performConsistencyCheck(e){return this.In.length,JO.resolve()}ys(e,t){return this._s(e)}_s(e){return 0===this.In.length?0:e-this.In[0].batchId}ws(e){var t=this._s(e);return t<0||t>=this.In.length?null:this.In[t]}}class R1{constructor(e,t){this.Ht=e,this.ps=t,this.docs=new Lx(oP.comparator),this.size=0}addEntry(e,t,n){const r=t.key,i=this.docs.get(r),s=i?i.size:0,o=this.ps(t);return this.docs=this.docs.insert(r,{document:t.clone(),size:o,readTime:n}),this.size+=o-s,this.Ht.addToCollectionParentIndex(e,r.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 JO.resolve(n?n.document.clone():bP.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.clone():bP.newInvalidDocument(e))}),JO.resolve(n)}getDocumentsMatchingQuery(e,t,n){let r=qx;const i=new oP(t.path.child("")),s=this.docs.getIteratorFrom(i);for(;s.hasNext();){const{key:e,value:{document:i,readTime:o}}=s.getNext();if(!t.path.isPrefixOf(e.path))break;o.compareTo(n)<=0||tx(t,i)&&(r=r.insert(i.key,i.clone()))}return JO.resolve(r)}Ts(e,t){return JO.forEach(this.docs,e=>t(e))}newChangeBuffer(e){return new P1(this)}getSize(e){return JO.resolve(this.size)}}class P1 extends XD{constructor(e){super(),this.Se=e}applyChanges(n){const r=[];return this.changes.forEach((e,t)=>{t.document.isValidDocument()?r.push(this.Se.addEntry(n,t.document,this.getReadTime(e))):this.Se.removeEntry(e)}),JO.waitFor(r)}getFromCache(e,t){return this.Se.getEntry(e,t)}getAllFromCache(e,t){return this.Se.getEntries(e,t)}}class x1{constructor(e){this.persistence=e,this.Es=new JD(e=>EP(e),SP),this.lastRemoteSnapshotVersion=VR.min(),this.highestTargetId=0,this.Is=0,this.As=new C1,this.targetCount=0,this.Rs=jD.se()}forEachTarget(e,n){return this.Es.forEach((e,t)=>n(t)),JO.resolve()}getLastRemoteSnapshotVersion(e){return JO.resolve(this.lastRemoteSnapshotVersion)}getHighestSequenceNumber(e){return JO.resolve(this.Is)}allocateTargetId(e){return this.highestTargetId=this.Rs.next(),JO.resolve(this.highestTargetId)}setTargetsMetadata(e,t,n){return n&&(this.lastRemoteSnapshotVersion=n),t>this.Is&&(this.Is=t),JO.resolve()}ce(e){this.Es.set(e.target,e);var t=e.targetId;t>this.highestTargetId&&(this.Rs=new jD(t),this.highestTargetId=t),e.sequenceNumber>this.Is&&(this.Is=e.sequenceNumber)}addTargetData(e,t){return this.ce(t),this.targetCount+=1,JO.resolve()}updateTargetData(e,t){return this.ce(t),JO.resolve()}removeTargetData(e,t){return this.Es.delete(t.target),this.As.cs(t.targetId),--this.targetCount,JO.resolve()}removeTargets(n,r,i){let s=0;const o=[];return this.Es.forEach((e,t)=>{t.sequenceNumber<=r&&null===i.get(t.targetId)&&(this.Es.delete(e),o.push(this.removeMatchingKeysForTargetId(n,t.targetId)),s++)}),JO.waitFor(o).next(()=>s)}getTargetCount(e){return JO.resolve(this.targetCount)}getTargetData(e,t){var n=this.Es.get(t)||null;return JO.resolve(n)}addMatchingKeys(e,t,n){return this.As.ss(t,n),JO.resolve()}removeMatchingKeys(t,e,n){this.As.os(e,n);const r=this.persistence.referenceDelegate,i=[];return r&&e.forEach(e=>{i.push(r.markPotentiallyOrphaned(t,e))}),JO.waitFor(i)}removeMatchingKeysForTargetId(e,t){return this.As.cs(t),JO.resolve()}getMatchingKeysForTargetId(e,t){var n=this.As.hs(t);return JO.resolve(n)}containsKey(e,t){return JO.resolve(this.As.containsKey(t))}}class O1{constructor(e,t){var n;this.bs={},this.Le=new LR(0),this.Be=!1,this.Be=!0,this.referenceDelegate=e(this),this.ze=new x1(this),this.Ht=new kD,this.He=(n=this.Ht,e=e=>this.referenceDelegate.Ps(e),new R1(n,e)),this.N=new dD(t),this.Je=new k1(this.N)}start(){return Promise.resolve()}shutdown(){return this.Be=!1,Promise.resolve()}get started(){return this.Be}setDatabaseDeletedListener(){}setNetworkEnabled(){}getIndexManager(){return this.Ht}getMutationQueue(e){let t=this.bs[e.toKey()];return t||(t=new N1(this.Ht,this.referenceDelegate),this.bs[e.toKey()]=t),t}getTargetCache(){return this.ze}getRemoteDocumentCache(){return this.He}getBundleCache(){return this.Je}runTransaction(e,t,n){wR("MemoryPersistence","Starting transaction:",e);const r=new D1(this.Le.next());return this.referenceDelegate.vs(),n(r).next(e=>this.referenceDelegate.Vs(r).next(()=>e)).toPromise().then(e=>(r.raiseOnCommittedEvent(),e))}Ss(t,n){return JO.or(Object.values(this.bs).map(e=>()=>e.containsKey(t,n)))}}class D1 extends YO{constructor(e){super(),this.currentSequenceNumber=e}}class L1{constructor(e){this.persistence=e,this.Ds=new C1,this.Cs=null}static Ns(e){return new L1(e)}get xs(){if(this.Cs)return this.Cs;throw ER()}addReference(e,t,n){return this.Ds.addReference(n,t),this.xs.delete(n.toString()),JO.resolve()}removeReference(e,t,n){return this.Ds.removeReference(n,t),this.xs.add(n.toString()),JO.resolve()}markPotentiallyOrphaned(e,t){return this.xs.add(t.toString()),JO.resolve()}removeTarget(e,t){this.Ds.cs(t.targetId).forEach(e=>this.xs.add(e.toString()));const n=this.persistence.getTargetCache();return n.getMatchingKeysForTargetId(e,t.targetId).next(e=>{e.forEach(e=>this.xs.add(e.toString()))}).next(()=>n.removeTargetData(e,t))}vs(){this.Cs=new Set}Vs(n){const r=this.persistence.getRemoteDocumentCache().newChangeBuffer();return JO.forEach(this.xs,e=>{const t=oP.fromPath(e);return this.ks(n,t).next(e=>{e||r.removeEntry(t)})}).next(()=>(this.Cs=null,r.apply(n)))}updateLimboDocument(e,t){return this.ks(e,t).next(e=>{e?this.xs.delete(t.toString()):this.xs.add(t.toString())})}Ps(e){return 0}ks(e,t){return JO.or([()=>JO.resolve(this.Ds.containsKey(t)),()=>this.persistence.getTargetCache().containsKey(e,t),()=>this.persistence.Ss(e,t)])}}function M1(e,t){return`firestore_clients_${e}_${t}`}function F1(e,t,n){let r=`firestore_mutations_${e}_${n}`;return t.isAuthenticated()&&(r+=`_${t.uid}`),r}function U1(e,t){return`firestore_targets_${e}_${t}`}class j1{constructor(e,t,n,r){this.user=e,this.batchId=t,this.state=n,this.error=r}static $s(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 CR(r.error.code,r.error.message))),s?new j1(e,t,r.state,i):(bR("SharedClientState",`Failed to parse mutation state for ID '${t}': ${n}`),null)}Os(){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 q1{constructor(e,t,n){this.targetId=e,this.state=t,this.error=n}static $s(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 CR(n.error.code,n.error.message))),i?new q1(e,n.state,r):(bR("SharedClientState",`Failed to parse target state for ID '${e}': ${t}`),null)}Os(){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 V1{constructor(e,t){this.clientId=e,this.activeTargetIds=t}static $s(e,t){var n=JSON.parse(t);let r="object"==typeof n&&n.activeTargetIds instanceof Array,i=zx;for(let s=0;r&&s<n.activeTargetIds.length;++s)r=sP(n.activeTargetIds[s]),i=i.add(n.activeTargetIds[s]);return r?new V1(e,i):(bR("SharedClientState",`Failed to parse client data for instance '${e}': ${t}`),null)}}class B1{constructor(e,t){this.clientId=e,this.onlineState=t}static $s(e){var t=JSON.parse(e);return"object"==typeof t&&-1!==["Unknown","Online","Offline"].indexOf(t.onlineState)&&"string"==typeof t.clientId?new B1(t.clientId,t.onlineState):(bR("SharedClientState",`Failed to parse online state: ${e}`),null)}}class $1{constructor(){this.activeTargetIds=zx}Fs(e){this.activeTargetIds=this.activeTargetIds.add(e)}Ms(e){this.activeTargetIds=this.activeTargetIds.delete(e)}Os(){var e={activeTargetIds:this.activeTargetIds.toArray(),updateTimeMs:Date.now()};return JSON.stringify(e)}}class K1{constructor(e,t,n,r,i){this.window=e,this.Oe=t,this.persistenceKey=n,this.Ls=r,this.syncEngine=null,this.onlineStateHandler=null,this.sequenceNumberHandler=null,this.Bs=this.Us.bind(this),this.qs=new Lx(FR),this.started=!1,this.Ks=[];var s=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");this.storage=this.window.localStorage,this.currentUser=i,this.js=M1(this.persistenceKey,this.Ls),this.Qs=`firestore_sequence_number_${this.persistenceKey}`,this.qs=this.qs.insert(this.Ls,new $1),this.Ws=new RegExp(`^firestore_clients_${s}_([^_]*)$`),this.Gs=new RegExp(`^firestore_mutations_${s}_(\\d+)(?:_(.*))?$`),this.zs=new RegExp(`^firestore_targets_${s}_(\\d+)$`),this.Hs=`firestore_online_state_${this.persistenceKey}`,this.Js=`firestore_bundle_loaded_${this.persistenceKey}`,this.window.addEventListener("storage",this.Bs)}static bt(e){return!(!e||!e.localStorage)}async start(){const e=await this.syncEngine.pn();for(const n of e)if(n!==this.Ls){const e=this.getItem(M1(this.persistenceKey,n));var t;!e||(t=V1.$s(n,e))&&(this.qs=this.qs.insert(t.clientId,t))}this.Ys();const n=this.storage.getItem(this.Hs);if(n){const e=this.Xs(n);e&&this.Zs(e)}for(const e of this.Ks)this.Us(e);this.Ks=[],this.window.addEventListener("pagehide",()=>this.shutdown()),this.started=!0}writeSequenceNumber(e){this.setItem(this.Qs,JSON.stringify(e))}getAllActiveQueryTargets(){return this.ti(this.qs)}isActiveQueryTarget(n){let r=!1;return this.qs.forEach((e,t)=>{t.activeTargetIds.has(n)&&(r=!0)}),r}addPendingMutation(e){this.ei(e,"pending")}updateMutationState(e,t,n){this.ei(e,t,n),this.ni(e)}addLocalQueryTarget(e){let t="not-current";var n;return this.isActiveQueryTarget(e)&&(!(n=this.storage.getItem(U1(this.persistenceKey,e)))||(n=q1.$s(e,n))&&(t=n.state)),this.si.Fs(e),this.Ys(),t}removeLocalQueryTarget(e){this.si.Ms(e),this.Ys()}isLocalQueryTarget(e){return this.si.activeTargetIds.has(e)}clearQueryState(e){this.removeItem(U1(this.persistenceKey,e))}updateQueryState(e,t,n){this.ii(e,t,n)}handleUserChange(e,t,n){t.forEach(e=>{this.ni(e)}),this.currentUser=e,n.forEach(e=>{this.addPendingMutation(e)})}setOnlineState(e){this.ri(e)}notifyBundleLoaded(){this.oi()}shutdown(){this.started&&(this.window.removeEventListener("storage",this.Bs),this.removeItem(this.js),this.started=!1)}getItem(e){var t=this.storage.getItem(e);return wR("SharedClientState","READ",e,t),t}setItem(e,t){wR("SharedClientState","SET",e,t),this.storage.setItem(e,t)}removeItem(e){wR("SharedClientState","REMOVE",e),this.storage.removeItem(e)}Us(e){const r=e;r.storageArea===this.storage&&(wR("SharedClientState","EVENT",r.key,r.newValue),r.key!==this.js?this.Oe.enqueueRetryable(async()=>{if(this.started){if(null!==r.key)if(this.Ws.test(r.key)){if(null==r.newValue){var e=this.ci(r.key);return this.ai(e,null)}e=this.ui(r.key,r.newValue);if(e)return this.ai(e.clientId,e)}else if(this.Gs.test(r.key)){if(null!==r.newValue){var t=this.hi(r.key,r.newValue);if(t)return this.li(t)}}else if(this.zs.test(r.key)){if(null!==r.newValue){t=this.fi(r.key,r.newValue);if(t)return this.di(t)}}else if(r.key===this.Hs){if(null!==r.newValue){var n=this.Xs(r.newValue);if(n)return this.Zs(n)}}else if(r.key===this.Qs){n=function(e){let t=LR.T;if(null!=e)try{var n=JSON.parse(e);SR("number"==typeof n),t=n}catch(e){bR("SharedClientState","Failed to read sequence number from WebStorage",e)}return t}(r.newValue);n!==LR.T&&this.sequenceNumberHandler(n)}else if(r.key===this.Js)return this.syncEngine.wi()}else this.Ks.push(r)}):bR("Received WebStorage notification for local change. Another client might have garbage-collected our state"))}get si(){return this.qs.get(this.Ls)}Ys(){this.setItem(this.js,this.si.Os())}ei(e,t,n){const r=new j1(this.currentUser,e,t,n),i=F1(this.persistenceKey,this.currentUser,e);this.setItem(i,r.Os())}ni(e){var t=F1(this.persistenceKey,this.currentUser,e);this.removeItem(t)}ri(e){var t={clientId:this.Ls,onlineState:e};this.storage.setItem(this.Hs,JSON.stringify(t))}ii(e,t,n){const r=U1(this.persistenceKey,e),i=new q1(e,t,n);this.setItem(r,i.Os())}oi(){this.setItem(this.Js,"value-not-used")}ci(e){var t=this.Ws.exec(e);return t?t[1]:null}ui(e,t){var n=this.ci(e);return V1.$s(n,t)}hi(e,t){var n=this.Gs.exec(e),r=Number(n[1]),n=void 0!==n[2]?n[2]:null;return j1.$s(new mR(n),r,t)}fi(e,t){var n=this.zs.exec(e),n=Number(n[1]);return q1.$s(n,t)}Xs(e){return B1.$s(e)}async li(e){if(e.user.uid===this.currentUser.uid)return this.syncEngine._i(e.batchId,e.state,e.error);wR("SharedClientState",`Ignoring mutation for non-active user ${e.user.uid}`)}di(e){return this.syncEngine.mi(e.targetId,e.state,e.error)}ai(e,t){const n=t?this.qs.insert(e,t):this.qs.remove(e),r=this.ti(this.qs),i=this.ti(n),s=[],o=[];return i.forEach(e=>{r.has(e)||s.push(e)}),r.forEach(e=>{i.has(e)||o.push(e)}),this.syncEngine.gi(s,o).then(()=>{this.qs=n})}Zs(e){this.qs.get(e.clientId)&&this.onlineStateHandler(e.onlineState)}ti(e){let n=zx;return e.forEach((e,t)=>{n=n.unionWith(t.activeTargetIds)}),n}}class z1{constructor(){this.yi=new $1,this.pi={},this.onlineStateHandler=null,this.sequenceNumberHandler=null}addPendingMutation(e){}updateMutationState(e,t,n){}addLocalQueryTarget(e){return this.yi.Fs(e),this.pi[e]||"not-current"}updateQueryState(e,t,n){this.pi[e]=t}removeLocalQueryTarget(e){this.yi.Ms(e)}isLocalQueryTarget(e){return this.yi.activeTargetIds.has(e)}clearQueryState(e){delete this.pi[e]}getAllActiveQueryTargets(){return this.yi.activeTargetIds}isActiveQueryTarget(e){return this.yi.activeTargetIds.has(e)}start(){return this.yi=new $1,Promise.resolve()}handleUserChange(e,t,n){}setOnlineState(e){}shutdown(){}writeSequenceNumber(e){}notifyBundleLoaded(){}}class W1{Ti(e){}shutdown(){}}class H1{constructor(){this.Ei=()=>this.Ii(),this.Ai=()=>this.Ri(),this.bi=[],this.Pi()}Ti(e){this.bi.push(e)}shutdown(){window.removeEventListener("online",this.Ei),window.removeEventListener("offline",this.Ai)}Pi(){window.addEventListener("online",this.Ei),window.addEventListener("offline",this.Ai)}Ii(){wR("ConnectivityMonitor","Network connectivity changed: AVAILABLE");for(const e of this.bi)e(0)}Ri(){wR("ConnectivityMonitor","Network connectivity changed: UNAVAILABLE");for(const e of this.bi)e(1)}static bt(){return"undefined"!=typeof window&&void 0!==window.addEventListener&&void 0!==window.removeEventListener}}const G1={BatchGetDocuments:"batchGet",Commit:"commit",RunQuery:"runQuery"};class Q1{constructor(e){this.vi=e.vi,this.Vi=e.Vi}Si(e){this.Di=e}Ci(e){this.Ni=e}onMessage(e){this.xi=e}close(){this.Vi()}send(e){this.vi(e)}ki(){this.Di()}$i(e){this.Ni(e)}Oi(e){this.xi(e)}}class Y1 extends class{constructor(e){this.databaseInfo=e,this.databaseId=e.databaseId;var t=e.ssl?"https":"http";this.Fi=t+"://"+e.host,this.Mi="projects/"+this.databaseId.projectId+"/databases/"+this.databaseId.database+"/documents"}Li(t,e,n,r){const i=this.Bi(t,e);wR("RestConnection","Sending: ",i,n);var s={};return this.Ui(s,r),this.qi(t,i,s,n).then(e=>(wR("RestConnection","Received: ",e),e),e=>{throw IR("RestConnection",`${t} failed with error: `,e,"url: ",i,"request:",n),e})}Ki(e,t,n,r){return this.Li(e,t,n,r)}Ui(e,t){if(e["X-Goog-Api-Client"]="gl-js/ fire/"+vR,e["Content-Type"]="text/plain",this.databaseInfo.appId&&(e["X-Firebase-GMPID"]=this.databaseInfo.appId),t)for(const n in t.authHeaders)t.authHeaders.hasOwnProperty(n)&&(e[n]=t.authHeaders[n])}Bi(e,t){var n=G1[e];return`${this.Fi}/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 pR;o.listenOnce(cR.COMPLETE,()=>{try{switch(o.getLastErrorCode()){case aR.NO_ERROR:var e=o.getResponseJson();wR("Connection","XHR received:",JSON.stringify(e)),i(e);break;case aR.TIMEOUT:wR("Connection",'RPC "'+a+'" timed out'),s(new CR(kR.DEADLINE_EXCEEDED,"Request time out"));break;case aR.HTTP_ERROR:var t,n=o.getStatus();if(wR("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(kR).indexOf(r)?r:kR.UNKNOWN,s(new CR(t,a.message))):s(new CR(kR.UNKNOWN,"Server responded with status "+o.getStatus()))}else s(new CR(kR.UNAVAILABLE,"Connection failed."));break;default:ER()}}finally{wR("Connection",'RPC "'+a+'" completed.')}var r});var e=JSON.stringify(r);o.send(t,"POST",e,n,15)})}ji(e,t){const n=[this.Fi,"/","google.firestore.v1.Firestore","/",e,"/channel"],r=new eR,i=oR(),s={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&&(s.xmlHttpFactory=new dR({})),this.Ui(s.initMessageHeaders,t),od()||ld()||0<=sd().indexOf("Electron/")||ud()||0<=sd().indexOf("MSAppHost/")||cd()||(s.httpHeadersOverwriteParam="$httpHeaders");var o=n.join("");wR("Connection","Creating WebChannel: "+o,s);const a=r.createWebChannel(o,s);let c=!1,l=!1;const u=new Q1({vi:e=>{l?wR("Connection","Not sending because WebChannel is closed:",e):(c||(wR("Connection","Opening WebChannel transport."),a.open(),c=!0),wR("Connection","WebChannel sending:",e),a.send(e))},Vi:()=>a.close()}),h=(e,t,n)=>{e.listen(t,e=>{try{n(e)}catch(e){setTimeout(()=>{throw e},0)}})};return h(a,fR.EventType.OPEN,()=>{l||wR("Connection","WebChannel transport opened.")}),h(a,fR.EventType.CLOSE,()=>{l||(l=!0,wR("Connection","WebChannel transport closed"),u.$i())}),h(a,fR.EventType.ERROR,e=>{l||(l=!0,IR("Connection","WebChannel transport errored:",e),u.$i(new CR(kR.UNAVAILABLE,"The operation could not be completed")))}),h(a,fR.EventType.MESSAGE,n=>{if(!l){var e=n.data[0];SR(!!e);var r=e.error||(null===(r=e[0])||void 0===r?void 0:r.error);if(r){wR("Connection","WebChannel received error:",r);const n=r.status;let e=function(e){var t=sR[e];if(void 0!==t)return Dx(t)}(n),t=r.message;void 0===e&&(e=kR.INTERNAL,t="Unknown error status: "+n+" with message "+r.message),l=!0,u.$i(new CR(e,t)),a.close()}else wR("Connection","WebChannel received:",e),u.Oi(e)}}),h(i,lR.STAT_EVENT,e=>{e.stat===uR?wR("Connection","Detected buffering proxy"):e.stat===hR&&wR("Connection","Detected no buffering proxy")}),setTimeout(()=>{u.ki()},0),u}}function J1(){return"undefined"!=typeof window?window:null}function X1(){return"undefined"!=typeof document?document:null}function Z1(e){return new rO(e,!0)}class eL{constructor(e,t,n=1e3,r=1.5,i=6e4){this.Oe=e,this.timerId=t,this.Qi=n,this.Wi=r,this.Gi=i,this.zi=0,this.Hi=null,this.Ji=Date.now(),this.reset()}reset(){this.zi=0}Yi(){this.zi=this.Gi}Xi(e){this.cancel();var t=Math.floor(this.zi+this.Zi()),n=Math.max(0,Date.now()-this.Ji),r=Math.max(0,t-n);0<r&&wR("ExponentialBackoff",`Backing off for ${r} ms (base delay: ${this.zi} ms, delay with jitter: ${t} ms, last attempt: ${n} ms ago)`),this.Hi=this.Oe.enqueueAfterDelay(this.timerId,r,()=>(this.Ji=Date.now(),e())),this.zi*=this.Wi,this.zi<this.Qi&&(this.zi=this.Qi),this.zi>this.Gi&&(this.zi=this.Gi)}tr(){null!==this.Hi&&(this.Hi.skipDelay(),this.Hi=null)}cancel(){null!==this.Hi&&(this.Hi.cancel(),this.Hi=null)}Zi(){return(Math.random()-.5)*this.zi}}class tL{constructor(e,t,n,r,i,s,o){this.Oe=e,this.er=n,this.nr=r,this.sr=i,this.credentialsProvider=s,this.listener=o,this.state=0,this.ir=0,this.rr=null,this.cr=null,this.stream=null,this.ar=new eL(e,t)}ur(){return 1===this.state||5===this.state||this.hr()}hr(){return 2===this.state||3===this.state}start(){4!==this.state?this.auth():this.lr()}async stop(){this.ur()&&await this.close(0)}dr(){this.state=0,this.ar.reset()}wr(){this.hr()&&null===this.rr&&(this.rr=this.Oe.enqueueAfterDelay(this.er,6e4,()=>this._r()))}mr(e){this.gr(),this.stream.send(e)}async _r(){if(this.hr())return this.close(0)}gr(){this.rr&&(this.rr.cancel(),this.rr=null)}yr(){this.cr&&(this.cr.cancel(),this.cr=null)}async close(e,t){this.gr(),this.yr(),this.ar.cancel(),this.ir++,4!==e?this.ar.reset():t&&t.code===kR.RESOURCE_EXHAUSTED?(bR(t.toString()),bR("Using maximum backoff delay to prevent overloading the backend."),this.ar.Yi()):t&&t.code===kR.UNAUTHENTICATED&&3!==this.state&&this.credentialsProvider.invalidateToken(),null!==this.stream&&(this.pr(),this.stream.close(),this.stream=null),this.state=e,await this.listener.Ci(t)}pr(){}auth(){this.state=1;const e=this.Tr(this.ir),t=this.ir;this.credentialsProvider.getToken().then(e=>{this.ir===t&&this.Er(e)},t=>{e(()=>{var e=new CR(kR.UNKNOWN,"Fetching auth token failed: "+t.message);return this.Ir(e)})})}Er(e){const t=this.Tr(this.ir);this.stream=this.Ar(e),this.stream.Si(()=>{t(()=>(this.state=2,this.cr=this.Oe.enqueueAfterDelay(this.nr,1e4,()=>(this.hr()&&(this.state=3),Promise.resolve())),this.listener.Si()))}),this.stream.Ci(e=>{t(()=>this.Ir(e))}),this.stream.onMessage(e=>{t(()=>this.onMessage(e))})}lr(){this.state=5,this.ar.Xi(async()=>{this.state=0,this.start()})}Ir(e){return wR("PersistentStream",`close with error: ${e}`),this.stream=null,this.close(4,e)}Tr(t){return e=>{this.Oe.enqueueAndForget(()=>this.ir===t?e():(wR("PersistentStream","stream callback skipped by getCloseGuardedDispatcher."),Promise.resolve()))}}}class nL extends tL{constructor(e,t,n,r,i){super(e,"listen_stream_connection_backoff","listen_stream_idle","health_check_timeout",t,n,i),this.N=r}Ar(e){return this.sr.ji("Listen",e)}onMessage(e){this.ar.reset();var t=function(e,t){let n;if("targetChange"in t){t.targetChange;var r="NO_CHANGE"===(f=t.targetChange.targetChangeType||"NO_CHANGE")?0:"ADD"===f?1:"REMOVE"===f?2:"CURRENT"===f?3:"RESET"===f?4:ER(),i=t.targetChange.targetIds||[],s=(f=t.targetChange.resumeToken,e.D?(SR(void 0===f||"string"==typeof f),YR.fromBase64String(f||"")):(SR(void 0===f||f instanceof Uint8Array),YR.fromUint8Array(f||new Uint8Array))),o=t.targetChange.cause,a=o&&(a=void 0===(f=o).code?kR.UNKNOWN:Dx(f.code),new CR(a,f.message||""));n=new Yx(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=uO(e,c.document.name),l=oO(c.document.updateTime),u=new wP({mapValue:{fields:c.document.fields}}),l=bP.newFoundDocument(a,l,u),u=c.targetIds||[],c=c.removedTargetIds||[];n=new Gx(u,c,l.key,l)}else if("documentDelete"in t){t.documentDelete;u=t.documentDelete;u.document;c=uO(e,u.document),l=u.readTime?oO(u.readTime):VR.min(),l=bP.newNoDocument(c,l),u=u.removedTargetIds||[];n=new Gx([],u,l.key,l)}else if("documentRemove"in t){t.documentRemove;var h=t.documentRemove;h.document;var d=uO(e,h.document),h=h.removedTargetIds||[];n=new Gx([],h,d,null)}else{if(!("filter"in t))return ER();{t.filter;const e=t.filter;e.targetId;h=e.count||0,d=new xx(h),h=e.targetId;n=new Qx(h,d)}}var a,f;return n}(this.N,e),n=function(e){if(!("targetChange"in e))return VR.min();var t=e.targetChange;return(!t.targetIds||!t.targetIds.length)&&t.readTime?oO(t.readTime):VR.min()}(e);return this.listener.Rr(t,n)}br(e){const t={};t.database=fO(this.N),t.addTarget=function(e,t){let n;var r=t.target;return n=kP(r)?{documents:_O(e,r)}:{query:wO(e,r)},n.targetId=t.targetId,0<t.resumeToken.approximateByteSize()?n.resumeToken=sO(e,t.resumeToken):0<t.snapshotVersion.compareTo(VR.min())&&(n.readTime=iO(e,t.snapshotVersion.toTimestamp())),n}(this.N,e);var n,r,r=(this.N,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 ER()}}())?null:{"goog-listen-tags":r});r&&(t.labels=r),this.mr(t)}Pr(e){const t={};t.database=fO(this.N),t.removeTarget=e,this.mr(t)}}class rL extends tL{constructor(e,t,n,r,i){super(e,"write_stream_connection_backoff","write_stream_idle","health_check_timeout",t,n,i),this.N=r,this.vr=!1}get Vr(){return this.vr}start(){this.vr=!1,this.lastStreamToken=void 0,super.start()}pr(){this.vr&&this.Sr([])}Ar(e){return this.sr.ji("Write",e)}onMessage(e){if(SR(!!e.streamToken),this.lastStreamToken=e.streamToken,this.vr){this.ar.reset();var t=(r=e.writeResults,i=e.commitTime,r&&0<r.length?(SR(void 0!==i),r.map(e=>function(e,t){let n=e.updateTime?oO(e.updateTime):oO(t);return n.isEqual(VR.min())&&(n=oO(t)),new vx(n,e.transformResults||[])}(e,i))):[]),n=oO(e.commitTime);return this.listener.Dr(n,t)}var r,i;return SR(!e.writeResults||0===e.writeResults.length),this.vr=!0,this.listener.Cr()}Nr(){const e={};e.database=fO(this.N),this.mr(e)}Sr(e){var t={streamToken:this.lastStreamToken,writes:e.map(e=>vO(this.N,e))};this.mr(t)}}class iL extends class{}{constructor(e,t,n){super(),this.credentials=e,this.sr=t,this.N=n,this.kr=!1}$r(){if(this.kr)throw new CR(kR.FAILED_PRECONDITION,"The client has already been terminated.")}Li(t,n,r){return this.$r(),this.credentials.getToken().then(e=>this.sr.Li(t,n,r,e)).catch(e=>{throw"FirebaseError"===e.name?(e.code===kR.UNAUTHENTICATED&&this.credentials.invalidateToken(),e):new CR(kR.UNKNOWN,e.toString())})}Ki(t,n,r){return this.$r(),this.credentials.getToken().then(e=>this.sr.Ki(t,n,r,e)).catch(e=>{throw"FirebaseError"===e.name?(e.code===kR.UNAUTHENTICATED&&this.credentials.invalidateToken(),e):new CR(kR.UNKNOWN,e.toString())})}terminate(){this.kr=!0}}class sL{constructor(e,t){this.asyncQueue=e,this.onlineStateHandler=t,this.state="Unknown",this.Or=0,this.Fr=null,this.Mr=!0}Lr(){0===this.Or&&(this.Br("Unknown"),this.Fr=this.asyncQueue.enqueueAfterDelay("online_state_timeout",1e4,()=>(this.Fr=null,this.Ur("Backend didn't respond within 10 seconds."),this.Br("Offline"),Promise.resolve())))}qr(e){"Online"===this.state?this.Br("Unknown"):(this.Or++,1<=this.Or&&(this.Kr(),this.Ur(`Connection failed 1 times. Most recent error: ${e.toString()}`),this.Br("Offline")))}set(e){this.Kr(),this.Or=0,"Online"===e&&(this.Mr=!1),this.Br(e)}Br(e){e!==this.state&&(this.state=e,this.onlineStateHandler(e))}Ur(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.Mr?(bR(t),this.Mr=!1):wR("OnlineStateTracker",t)}Kr(){null!==this.Fr&&(this.Fr.cancel(),this.Fr=null)}}class oL{constructor(e,t,n,r,i){this.localStore=e,this.datastore=t,this.asyncQueue=n,this.remoteSyncer={},this.jr=[],this.Qr=new Map,this.Wr=new Set,this.Gr=[],this.zr=i,this.zr.Ti(e=>{n.enqueueAndForget(async()=>{gL(this)&&(wR("RemoteStore","Restarting streams for network reachability change."),await async function(e){const t=e;t.Wr.add(4),await cL(t),t.Hr.set("Unknown"),t.Wr.delete(4),await aL(t)}(this))})}),this.Hr=new sL(n,r)}}async function aL(e){if(gL(e))for(const t of e.Gr)await t(!0)}async function cL(e){for(const t of e.Gr)await t(!1)}function lL(e,t){const n=e;n.Qr.has(t.targetId)||(n.Qr.set(t.targetId,t),pL(n)?fL(n):TL(n).hr()&&hL(n,t))}function uL(e,t){const n=e,r=TL(n);n.Qr.delete(t),r.hr()&&dL(n,t),0===n.Qr.size&&(r.hr()?r.wr():gL(n)&&n.Hr.set("Unknown"))}function hL(e,t){e.Jr.Y(t.targetId),TL(e).br(t)}function dL(e,t){e.Jr.Y(t),TL(e).Pr(t)}function fL(t){t.Jr=new Xx({getRemoteKeysForTarget:e=>t.remoteSyncer.getRemoteKeysForTarget(e),Tt:e=>t.Qr.get(e)||null}),TL(t).start(),t.Hr.Lr()}function pL(e){return gL(e)&&!TL(e).ur()&&0<e.Qr.size}function gL(e){return 0===e.Wr.size}function mL(e){e.Jr=void 0}async function vL(e,t,n){if(!nD(t))throw t;e.Wr.add(1),await cL(e),e.Hr.set("Offline"),n=n||(()=>y1(e.localStore)),e.asyncQueue.enqueueRetryable(async()=>{wR("RemoteStore","Retrying IndexedDB access"),await n(),e.Wr.delete(1),await aL(e)})}function yL(t,n){return n().catch(e=>vL(t,e,n))}async function _L(e){const t=e,n=EL(t);let r=0<t.jr.length?t.jr[t.jr.length-1].batchId:-1;for(;gL(i=t)&&i.jr.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.In.getNextMutationBatchAfterBatchId(e,t)))}(t.localStore,r);if(null===e){0===t.jr.length&&n.wr();break}r=e.batchId,function(e,t){e.jr.push(t);const n=EL(e);n.hr()&&n.Vr&&n.Sr(t.mutations)}(t,e)}catch(e){await vL(t,e)}var i;wL(t)&&bL(t)}function wL(e){return gL(e)&&!EL(e).ur()&&0<e.jr.length}function bL(e){EL(e).start()}async function IL(e,t){const n=e;t?(n.Wr.delete(2),await aL(n)):(n.Wr.add(2),await cL(n),n.Hr.set("Unknown"))}function TL(t){return t.Yr||(t.Yr=function(e,t,n){const r=e;return r.$r(),new nL(t,r.sr,r.credentials,r.N,n)}(t.datastore,t.asyncQueue,{Si:(async function(n){n.Qr.forEach((e,t)=>{hL(n,e)})}).bind(null,t),Ci:(async function(e,t){mL(e),pL(e)?(e.Hr.qr(t),fL(e)):e.Hr.set("Unknown")}).bind(null,t),Rr:(async function(e,r,t){if(e.Hr.set("Online"),r instanceof Yx&&2===r.state&&r.cause)try{await async function(e){var t=r.cause;for(const n of r.targetIds)e.Qr.has(n)&&(await e.remoteSyncer.rejectListen(n,t),e.Qr.delete(n),e.Jr.removeTarget(n))}(e)}catch(t){wR("RemoteStore","Failed to remove targets %s: %s ",r.targetIds.join(","),t),await vL(e,t)}else if(r instanceof Gx?e.Jr.rt(r):r instanceof Qx?e.Jr.ft(r):e.Jr.at(r),!t.isEqual(VR.min()))try{const r=await y1(e.localStore);0<=t.compareTo(r)&&await function(r,i){const e=r.Jr._t(i);return e.targetChanges.forEach((e,t)=>{if(0<e.resumeToken.approximateByteSize()){const n=r.Qr.get(t);n&&r.Qr.set(t,n.withResumeToken(e.resumeToken,i))}}),e.targetMismatches.forEach(e=>{const t=r.Qr.get(e);var n;t&&(r.Qr.set(e,t.withResumeToken(YR.EMPTY_BYTE_STRING,t.snapshotVersion)),dL(r,e),n=new hD(t.target,e,1,t.sequenceNumber),hL(r,n))}),r.remoteSyncer.applyRemoteEvent(e)}(e,t)}catch(r){wR("RemoteStore","Failed to raise snapshot:",r),await vL(e,r)}}).bind(null,t)}),t.Gr.push(async e=>{e?(t.Yr.dr(),pL(t)?fL(t):t.Hr.set("Unknown")):(await t.Yr.stop(),mL(t))})),t.Yr}function EL(t){return t.Xr||(t.Xr=function(e,t,n){const r=e;return r.$r(),new rL(t,r.sr,r.credentials,r.N,n)}(t.datastore,t.asyncQueue,{Si:(async function(e){EL(e).Nr()}).bind(null,t),Ci:(async function(e,t){t&&EL(e).Vr&&await async function(e,t){if(Ox(n=t.code)&&n!==kR.ABORTED){const n=e.jr.shift();EL(e).dr(),await yL(e,()=>e.remoteSyncer.rejectFailedWrite(n.batchId,t)),await _L(e)}var n}(e,t),wL(e)&&bL(e)}).bind(null,t),Cr:(async function(e){const t=EL(e);for(const n of e.jr)t.Sr(n.mutations)}).bind(null,t),Dr:(async function(e,t,n){const r=e.jr.shift(),i=uD.from(r,t,n);await yL(e,()=>e.remoteSyncer.applySuccessfulWrite(i)),await _L(e)}).bind(null,t)}),t.Gr.push(async e=>{e?(t.Xr.dr(),await _L(t)):(await t.Xr.stop(),0<t.jr.length&&(wR("RemoteStore",`Stopping write stream with ${t.jr.length} pending writes`),t.jr=[]))})),t.Xr}class SL{constructor(e,t,n,r,i){this.asyncQueue=e,this.timerId=t,this.targetTimeMs=n,this.op=r,this.removalCallback=i,this.deferred=new AR,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 SL(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 CR(kR.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 kL(e,t){if(bR("AsyncQueue",`${t}: ${e}`),nD(e))return new CR(kR.UNAVAILABLE,`${t}: ${e}`);throw e}class CL{constructor(n){this.comparator=n?(e,t)=>n(e,t)||oP.comparator(e.key,t.key):(e,t)=>oP.comparator(e.key,t.key),this.keyedMap=Vx,this.sortedSet=new Lx(this.comparator)}static emptySet(e){return new CL(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 CL))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 CL;return n.comparator=this.comparator,n.keyedMap=e,n.sortedSet=t,n}}class AL{constructor(){this.Zr=new Lx(oP.comparator)}track(e){var t=e.doc.key,n=this.Zr.get(t);!n||0!==e.type&&3===n.type?this.Zr=this.Zr.insert(t,e):3===e.type&&1!==n.type?this.Zr=this.Zr.insert(t,{type:n.type,doc:e.doc}):2===e.type&&2===n.type?this.Zr=this.Zr.insert(t,{type:2,doc:e.doc}):2===e.type&&0===n.type?this.Zr=this.Zr.insert(t,{type:0,doc:e.doc}):1===e.type&&0===n.type?this.Zr=this.Zr.remove(t):1===e.type&&2===n.type?this.Zr=this.Zr.insert(t,{type:1,doc:n.doc}):0===e.type&&1===n.type?this.Zr=this.Zr.insert(t,{type:2,doc:e.doc}):ER()}eo(){const n=[];return this.Zr.inorderTraversal((e,t)=>{n.push(t)}),n}}class NL{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 NL(e,t,CL.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)&&XP(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 RL{constructor(){this.no=void 0,this.listeners=[]}}class PL{constructor(){this.queries=new JD(e=>ZP(e),XP),this.onlineState="Unknown",this.so=new Set}}async function xL(e,t){const n=e,r=t.query;let i=!1,s=n.queries.get(r);if(s||(i=!0,s=new RL),i)try{s.no=await n.onListen(r)}catch(e){const n=kL(e,`Initialization of query '${ex(t.query)}' failed`);return void t.onError(n)}n.queries.set(r,s),s.listeners.push(t),t.io(n.onlineState),!s.no||t.ro(s.no)&&DL(n)}async function OL(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 DL(e){e.so.forEach(e=>{e.next()})}class LL{constructor(e,t,n){this.query=e,this.oo=t,this.co=!1,this.ao=null,this.onlineState="Unknown",this.options=n||{}}ro(e){if(!this.options.includeMetadataChanges){const t=[];for(const n of e.docChanges)3!==n.type&&t.push(n);e=new NL(e.query,e.docs,e.oldDocs,t,e.mutatedKeys,e.fromCache,e.syncStateChanged,!0)}let t=!1;return this.co?this.uo(e)&&(this.oo.next(e),t=!0):this.ho(e,this.onlineState)&&(this.lo(e),t=!0),this.ao=e,t}onError(e){this.oo.error(e)}io(e){this.onlineState=e;let t=!1;return this.ao&&!this.co&&this.ho(this.ao,e)&&(this.lo(this.ao),t=!0),t}ho(e,t){return!e.fromCache||!(this.options.fo&&"Offline"!==t||e.docs.isEmpty()&&"Offline"!==t)}uo(e){if(0<e.docChanges.length)return!0;var t=this.ao&&this.ao.hasPendingWrites!==e.hasPendingWrites;return!(!e.syncStateChanged&&!t)&&!0===this.options.includeMetadataChanges}lo(e){e=NL.fromInitialDocuments(e.query,e.docs,e.mutatedKeys,e.fromCache),this.co=!0,this.oo.next(e)}}class ML{constructor(e,t){this.payload=e,this.byteLength=t}wo(){return"metadata"in this.payload}}class FL{constructor(e){this.N=e}zn(e){return uO(this.N,e)}Hn(e){return e.metadata.exists?mO(this.N,e.document,!1):bP.newNoDocument(this.zn(e.metadata.name),this.Jn(e.metadata.readTime))}Jn(e){return oO(e)}}class UL{constructor(e,t,n){this._o=e,this.localStore=t,this.N=n,this.queries=[],this.documents=[],this.progress=jL(e)}mo(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}yo(e){const t=new Map,n=new FL(this.N);for(const i of e)if(i.metadata.queries){const e=n.zn(i.metadata.name);for(const n of i.metadata.queries){var r=(t.get(n)||Kx()).add(e);t.set(n,r)}}return t}async complete(){const e=await async function(e,t,n,r){const i=e;let s=Kx(),o=qx,a=Bx;for(const e of n){const n=t.zn(e.metadata.name);e.document&&(s=s.add(n)),o=o.insert(n,t.Hn(e)),a=a.insert(n,t.Jn(e.metadata.readTime))}const c=i.jn.newChangeBuffer({trackRemovals:!0}),l=await b1(i,(r=r,YP($P(WR.fromString(`__bundle__/docs/${r}`)))));return i.persistence.runTransaction("Apply bundle documents","readwrite",t=>w1(t,c,o,VR.min(),a).next(e=>(c.apply(t),e)).next(e=>i.ze.removeMatchingKeysForTargetId(t,l.targetId).next(()=>i.ze.addMatchingKeys(t,s,l.targetId)).next(()=>i.Qn.vn(t,e)).next(()=>e)))}(this.localStore,new FL(this.N),this.documents,this._o.id),t=this.yo(this.documents);for(const e of this.queries)await async function(e,n,r=Kx()){const i=await b1(e,YP(ID(n.bundledQuery))),s=e;return s.persistence.runTransaction("Save named query","readwrite",e=>{var t=oO(n.readTime);if(0<=i.snapshotVersion.compareTo(t))return s.Je.saveNamedQuery(e,n);t=i.withResumeToken(YR.EMPTY_BYTE_STRING,t);return s.Un=s.Un.insert(t.targetId,t),s.ze.updateTargetData(e,t).next(()=>s.ze.removeMatchingKeysForTargetId(e,i.targetId)).next(()=>s.ze.addMatchingKeys(e,r,i.targetId)).next(()=>s.Je.saveNamedQuery(e,n))})}(this.localStore,e,t.get(e.name));return this.progress.taskState="Success",new h1(Object.assign({},this.progress),e)}}function jL(e){return{taskState:"Running",documentsLoaded:0,bytesLoaded:0,totalDocuments:e.totalDocuments,totalBytes:e.totalBytes}}class qL{constructor(e){this.key=e}}class VL{constructor(e){this.key=e}}class BL{constructor(e,t){this.query=e,this.po=t,this.To=null,this.current=!1,this.Eo=Kx(),this.mutatedKeys=Kx(),this.Io=nx(e),this.Ao=new CL(this.Io)}get Ro(){return this.po}bo(e,t){const a=t?t.Po:new AL,c=(t||this).Ao;let l=(t||this).mutatedKeys,u=c,h=!1;const d=KP(this.query)&&c.size===this.query.limit?c.last():null,f=zP(this.query)&&c.size===this.query.limit?c.first():null;if(e.inorderTraversal((e,t)=>{const n=c.get(e),r=tx(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.vo(n,r)||(a.track({type:2,doc:r}),o=!0,(d&&0<this.Io(r,d)||f&&this.Io(r,f)<0)&&(h=!0)):!n&&r?(a.track({type:0,doc:r}),o=!0):n&&!r&&(a.track({type:1,doc:n}),o=!0,(d||f)&&(h=!0)),o&&(l=r?(u=u.add(r),s?l.add(e):l.delete(e)):(u=u.delete(e),l.delete(e)))}),KP(this.query)||zP(this.query))for(;u.size>this.query.limit;){const e=KP(this.query)?u.last():u.first();u=u.delete(e.key),l=l.delete(e.key),a.track({type:1,doc:e})}return{Ao:u,Po:a,Ln:h,mutatedKeys:l}}vo(e,t){return e.hasLocalMutations&&t.hasCommittedMutations&&!t.hasLocalMutations}applyChanges(e,t,n){var r=this.Ao;this.Ao=e.Ao,this.mutatedKeys=e.mutatedKeys;const i=e.Po.eo();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 ER()}};return n(e)-n(t)}(e.type,t.type)||this.Io(e.doc,t.doc)),this.Vo(n);var s=t?this.So():[],o=0===this.Eo.size&&this.current?1:0,a=o!==this.To;return this.To=o,0!==i.length||a?{snapshot:new NL(this.query,e.Ao,r,i,e.mutatedKeys,0==o,a,!1),Do:s}:{Do:s}}io(e){return this.current&&"Offline"===e?(this.current=!1,this.applyChanges({Ao:this.Ao,Po:new AL,mutatedKeys:this.mutatedKeys,Ln:!1},!1)):{Do:[]}}Co(e){return!this.po.has(e)&&!!this.Ao.has(e)&&!this.Ao.get(e).hasLocalMutations}Vo(e){e&&(e.addedDocuments.forEach(e=>this.po=this.po.add(e)),e.modifiedDocuments.forEach(e=>{}),e.removedDocuments.forEach(e=>this.po=this.po.delete(e)),this.current=e.current)}So(){if(!this.current)return[];const t=this.Eo;this.Eo=Kx(),this.Ao.forEach(e=>{this.Co(e.key)&&(this.Eo=this.Eo.add(e.key))});const n=[];return t.forEach(e=>{this.Eo.has(e)||n.push(new VL(e))}),this.Eo.forEach(e=>{t.has(e)||n.push(new qL(e))}),n}No(e){this.po=e.Gn,this.Eo=Kx();var t=this.bo(e.documents);return this.applyChanges(t,!0)}xo(){return NL.fromInitialDocuments(this.query,this.Ao,this.mutatedKeys,0===this.To)}}class $L{constructor(e,t,n){this.query=e,this.targetId=t,this.view=n}}class KL{constructor(e){this.key=e,this.ko=!1}}class zL{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.$o={},this.Oo=new JD(e=>ZP(e),XP),this.Fo=new Map,this.Mo=new Set,this.Lo=new Lx(oP.comparator),this.Bo=new Map,this.Uo=new C1,this.qo={},this.Ko=new Map,this.jo=jD.ie(),this.onlineState="Unknown",this.Qo=void 0}get isPrimaryClient(){return!0===this.Qo}}async function WL(n,e,t,r){n.Wo=(e,s,t)=>async function(e,t,n){let r=t.view.bo(s);r.Ln&&(r=await T1(e.localStore,t.query,!1).then(({documents:e})=>t.view.bo(e,r)));var i=n&&n.targetChanges.get(t.targetId),i=t.view.applyChanges(r,e.isPrimaryClient,i);return tM(e,t.targetId,i.Do),i.snapshot}(n,e,t);const i=await T1(n.localStore,e,!0),s=new BL(e,i.Gn),o=s.bo(i.documents),a=Hx.createSynthesizedTargetChangeForCurrentChange(t,r&&"Offline"!==n.onlineState),c=s.applyChanges(o,n.isPrimaryClient,a);tM(n,t,c.Do);var l=new $L(e,t,s);return n.Oo.set(e,l),n.Fo.has(t)?n.Fo.get(t).push(e):n.Fo.set(t,[e]),c.snapshot}async function HL(e,t,n){const r=cM(e);try{const e=await function(e,r){const i=e,s=qR.now(),t=r.reduce((e,t)=>e.add(t.key),Kx());let o;return i.persistence.runTransaction("Locally write mutations","readwrite",n=>i.Qn.Pn(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=ax(r.transform,e||null);null!=i&&(null==n&&(n=wP.empty()),n.set(r.field,i))}return n||null}(n,o.get(n.key));null!=r&&t.push(new kx(n.key,r,function r(e){const i=[];return $R(e.fields,(e,t)=>{const n=new GR([e]);if(yP(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 QR(i)}(r.value.mapValue),yx.exists(!0)))}return i.In.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 Lx(FR),r=r.insert(t,n),e.qo[e.currentUser.toKey()]=r}(r,e.batchId,n),await rM(r,e.changes),await _L(r.remoteStore)}catch(e){const t=kL(e,"Failed to persist write");n.reject(t)}}async function GL(e,t){const r=e;try{const e=await _1(r.localStore,t);t.targetChanges.forEach((e,t)=>{const n=r.Bo.get(t);n&&(SR(e.addedDocuments.size+e.modifiedDocuments.size+e.removedDocuments.size<=1),0<e.addedDocuments.size?n.ko=!0:0<e.modifiedDocuments.size?SR(n.ko):0<e.removedDocuments.size&&(SR(n.ko),n.ko=!1))}),await rM(r,e,t)}catch(e){await KD(e)}}function QL(r,i,e){const t=r;if(t.isPrimaryClient&&0===e||!t.isPrimaryClient&&1===e){const r=[];t.Oo.forEach((e,t)=>{var n=t.view.io(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.io(n)&&(r=!0)}),r&&DL(t)}(t.eventManager,i),r.length&&t.$o.Rr(r),t.onlineState=i,t.isPrimaryClient&&t.sharedClientState.setOnlineState(i)}}async function YL(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.jn.newChangeBuffer({trackRemovals:!0});return function(e,t,r,i){const s=r.batch,n=s.keys();let o=JO.resolve();return n.forEach(n=>{o=o.next(()=>i.getEntry(t,n)).next(e=>{var t=r.docVersions.get(n);SR(null!==t),e.version.compareTo(t)<0&&(s.applyToRemoteDocument(e,r),e.isValidDocument()&&i.addEntry(e,r.commitVersion))})}),o.next(()=>e.In.removeMutationBatch(t,s))}(i,e,r,n).next(()=>n.apply(e)).next(()=>i.In.performConsistencyCheck(e)).next(()=>i.Qn.Pn(e,t))})}(n.localStore,t);XL(n,r,null),JL(n,r),n.sharedClientState.updateMutationState(r,"acknowledged"),await rM(n,e)}catch(e){await KD(e)}}function JL(e,t){(e.Ko.get(t)||[]).forEach(e=>{e.resolve()}),e.Ko.delete(t)}function XL(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 ZL(t,e,n=null){t.sharedClientState.removeLocalQueryTarget(e);for(const r of t.Fo.get(e))t.Oo.delete(r),n&&t.$o.Go(r,n);t.Fo.delete(e),t.isPrimaryClient&&t.Uo.cs(e).forEach(e=>{t.Uo.containsKey(e)||eM(t,e)})}function eM(e,t){e.Mo.delete(t.path.canonicalString());var n=e.Lo.get(t);null!==n&&(uL(e.remoteStore,n),e.Lo=e.Lo.remove(t),e.Bo.delete(n),nM(e))}function tM(e,t,n){for(const r of n)r instanceof qL?(e.Uo.addReference(r.key,t),function(e,t){const n=t.key,r=n.path.canonicalString();e.Lo.get(n)||e.Mo.has(r)||(wR("SyncEngine","New document in limbo: "+n),e.Mo.add(r),nM(e))}(e,r)):r instanceof VL?(wR("SyncEngine","Document no longer in limbo: "+r.key),e.Uo.removeReference(r.key,t),e.Uo.containsKey(r.key)||eM(e,r.key)):ER()}function nM(e){for(;0<e.Mo.size&&e.Lo.size<e.maxConcurrentLimboResolutions;){var t=e.Mo.values().next().value;e.Mo.delete(t);var n=new oP(WR.fromString(t)),t=e.jo.next();e.Bo.set(t,new KL(n)),e.Lo=e.Lo.insert(n,t),lL(e.remoteStore,new hD(YP($P(n.path)),t,2,LR.T))}}async function rM(e,t,r){const i=e,s=[],o=[],a=[];i.Oo.isEmpty()||(i.Oo.forEach((e,n)=>{a.push(i.Wo(n,t,r).then(e=>{var t;e&&(i.isPrimaryClient&&i.sharedClientState.updateQueryState(n.targetId,e.fromCache?"not-current":"current"),s.push(e),t=f1.kn(n.targetId,e),o.push(t))}))}),await Promise.all(a),i.$o.Rr(s),await async function(e,t){const r=e;try{await r.persistence.runTransaction("notifyLocalViewChanges","readwrite",n=>JO.forEach(t,t=>JO.forEach(t.Nn,e=>r.persistence.referenceDelegate.addReference(n,t.targetId,e)).next(()=>JO.forEach(t.xn,e=>r.persistence.referenceDelegate.removeReference(n,t.targetId,e)))))}catch(e){if(!nD(e))throw e;wR("LocalStore","Failed to update sequence numbers: "+e)}for(const e of t){const t=e.targetId;if(!e.fromCache){const e=r.Un.get(t),n=e.snapshotVersion,i=e.withLastLimboFreeSnapshotVersion(n);r.Un=r.Un.insert(t,i)}}}(i.localStore,o))}async function iM(r,e){const i=r;if(aM(i),cM(i),!0===e&&!0!==i.Qo){const r=i.sharedClientState.getAllActiveQueryTargets(),e=await sM(i,r.toArray());i.Qo=!0,await IL(i.remoteStore,!0);for(const r of e)lL(i.remoteStore,r)}else if(!1===e&&!1!==i.Qo){const r=[];let n=Promise.resolve();i.Fo.forEach((e,t)=>{i.sharedClientState.isLocalQueryTarget(t)?r.push(t):n=n.then(()=>(ZL(i,t),I1(i.localStore,t,!0))),uL(i.remoteStore,t)}),await n,await sM(i,r),function(){const n=i;n.Bo.forEach((e,t)=>{uL(n.remoteStore,t)}),n.Uo.us(),n.Bo=new Map,n.Lo=new Lx(oP.comparator)}(),i.Qo=!1,await IL(i.remoteStore,!1)}}async function sM(t,n){const r=t,i=[],s=[];for(const t of n){let e;const u=r.Fo.get(t);if(u&&0!==u.length){e=await b1(r.localStore,YP(u[0]));for(const t of u){const n=r.Oo.get(t),u=(o=r,a=n,l=c=void 0,l=await T1((c=o).localStore,a.query,!0),l=a.view.No(l),c.isPrimaryClient&&tM(c,a.targetId,l.Do),await l);u.snapshot&&s.push(u.snapshot)}}else{const u=await E1(r.localStore,t);e=await b1(r.localStore,u),await WL(r,oM(u),t,!1)}i.push(e)}var o,a,c,l;return r.$o.Rr(s),i}function oM(e){return BP(e.path,e.collectionGroup,e.orderBy,e.filters,e.limit,"F",e.startAt,e.endAt)}function aM(e){const t=e;return t.remoteStore.remoteSyncer.applyRemoteEvent=GL.bind(null,t),t.remoteStore.remoteSyncer.getRemoteKeysForTarget=(function(e,t){const n=e,r=n.Bo.get(t);if(r&&r.ko)return Kx().add(r.key);{let e=Kx();const r=n.Fo.get(t);if(!r)return e;for(const t of r){const r=n.Oo.get(t);e=e.unionWith(r.view.Ro)}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.Bo.get(t),s=i&&i.key;if(s){let e=new Lx(oP.comparator);e=e.insert(s,bP.newNoDocument(s,VR.min()));const n=Kx().add(s),i=new Wx(VR.min(),new Map,new Ux(FR),e,n);await GL(r,i),r.Lo=r.Lo.remove(s),r.Bo.delete(t),nM(r)}else await I1(r.localStore,t,!1).then(()=>ZL(r,t,n)).catch(KD)}).bind(null,t),t.$o.Rr=(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.ro(e)&&(r=!0);i.no=e}}r&&DL(n)}).bind(null,t.eventManager),t.$o.Go=(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 cM(e){const t=e;return t.remoteStore.remoteSyncer.applySuccessfulWrite=YL.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.In.lookupMutationBatch(t,r).next(e=>(SR(null!==e),n=e.keys(),i.In.removeMutationBatch(t,e))).next(()=>i.In.performConsistencyCheck(t)).next(()=>i.Qn.Pn(t,n))})}(r.localStore,t);XL(r,t,n),JL(r,t),r.sharedClientState.updateMutationState(t,"rejected",n),await rM(r,e)}catch(n){await KD(n)}}).bind(null,t),t}class lM{constructor(){this.synchronizeTabs=!1}async initialize(e){this.N=Z1(e.databaseInfo.databaseId),this.sharedClientState=this.Ho(e),this.persistence=this.Jo(e),await this.persistence.start(),this.gcScheduler=this.Yo(e),this.localStore=this.Xo(e)}Yo(e){return null}Xo(e){return m1(this.persistence,new p1,e.initialUser,this.N)}Jo(e){return new O1(L1.Ns,this.N)}Ho(e){return new z1}async terminate(){this.gcScheduler&&this.gcScheduler.stop(),await this.sharedClientState.shutdown(),await this.persistence.shutdown()}}class uM extends lM{constructor(e,t,n){super(),this.Zo=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=n1(t);let r=VR.min();return e.Kt({index:jO.readTimeIndex,reverse:!0},(e,t,n)=>{t.readTime&&(r=mD(t.readTime)),n.done()}).next(()=>r)}()).then(e=>{t.Kn=e})}(this.localStore),await this.Zo.initialize(this,e),await cM(this.Zo.syncEngine),await _L(this.Zo.remoteStore),await this.persistence.nn(()=>(this.gcScheduler&&!this.gcScheduler.started&&this.gcScheduler.start(this.localStore),Promise.resolve()))}Xo(e){return m1(this.persistence,new p1,e.initialUser,this.N)}Yo(e){var t=this.persistence.referenceDelegate.garbageCollector;return new HD(t,e.asyncQueue)}Jo(e){var t=u1(e.databaseInfo.databaseId,e.databaseInfo.persistenceKey),n=void 0!==this.cacheSizeBytes?PD.withCacheSize(this.cacheSizeBytes):PD.DEFAULT;return new a1(this.synchronizeTabs,t,e.clientId,n,e.asyncQueue,J1(),X1(),this.N,this.sharedClientState,!!this.forceOwnership)}Ho(e){return new z1}}class hM extends uM{constructor(e,t){super(e,t,!1),this.Zo=e,this.cacheSizeBytes=t,this.synchronizeTabs=!0}async initialize(e){await super.initialize(e);var t=this.Zo.syncEngine;this.sharedClientState instanceof K1&&(this.sharedClientState.syncEngine={_i:(async function(e,t,n,r){var i=e,s=await function(e,n){const r=e,i=r.In;return r.persistence.runTransaction("Lookup mutation documents","readonly",t=>i.Xt(t,n).next(e=>e?r.Qn.Pn(t,e):JO.resolve(null)))}(i.localStore,t);null!==s?("pending"===n?await _L(i.remoteStore):"acknowledged"===n||"rejected"===n?(XL(i,t,r||null),JL(i,t),i.localStore.In.te(t)):ER(),await rM(i,s)):wR("SyncEngine","Cannot apply mutation batch with id: "+t)}).bind(null,t),mi:(async function(e,t,n,r){const i=e;if(i.Qo)wR("SyncEngine","Ignoring unexpected query state notification.");else if(i.Fo.has(t))switch(n){case"current":case"not-current":{const e=await S1(i.localStore),r=Wx.createSynthesizedRemoteEventForCurrentChange(t,"current"===n);await rM(i,e,r);break}case"rejected":await I1(i.localStore,t,!0),ZL(i,t,r);break;default:ER()}}).bind(null,t),gi:(async function(e,t,n){const r=aM(e);if(r.Qo){for(const e of t)if(r.Fo.has(e))wR("SyncEngine","Adding an already active target "+e);else{const t=await E1(r.localStore,e),n=await b1(r.localStore,t);await WL(r,oM(t),n.targetId,!1),lL(r.remoteStore,n)}for(const e of n)r.Fo.has(e)&&await I1(r.localStore,e,!1).then(()=>{uL(r.remoteStore,e),ZL(r,e)}).catch(KD)}}).bind(null,t),pn:(function(e){return e.localStore.persistence.pn()}).bind(null,t),wi:(async function(e){const t=e;return S1(t.localStore).then(e=>rM(t,e))}).bind(null,t)},await this.sharedClientState.start()),await this.persistence.nn(async e=>{await iM(this.Zo.syncEngine,e),this.gcScheduler&&(e&&!this.gcScheduler.started?this.gcScheduler.start(this.localStore):e||this.gcScheduler.stop())})}Ho(e){var t=J1();if(!K1.bt(t))throw new CR(kR.UNIMPLEMENTED,"IndexedDB persistence is only available on platforms that support LocalStorage.");var n=u1(e.databaseInfo.databaseId,e.databaseInfo.persistenceKey);return new K1(t,e.asyncQueue,n,e.clientId,e.initialUser)}}class dM{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=>QL(this.syncEngine,e,1),this.remoteStore.remoteSyncer.handleCredentialChange=(async function(e,t){const n=e;if(!n.currentUser.isEqual(t)){wR("SyncEngine","User change. New user:",t.toKey());const r=await v1(n.localStore,t);n.currentUser=t,(e=n).Ko.forEach(e=>{e.forEach(e=>{e.reject(new CR(kR.CANCELLED,"'waitForPendingWrites' promise is rejected due to a user change."))})}),e.Ko.clear(),n.sharedClientState.handleUserChange(t,r.removedBatchIds,r.addedBatchIds),await rM(n,r.Wn)}}).bind(null,this.syncEngine),await IL(this.remoteStore,this.syncEngine.isPrimaryClient))}createEventManager(e){return new PL}createDatastore(e){var t,n,r,i=Z1(e.databaseInfo.databaseId),t=(t=e.databaseInfo,new Y1(t));return n=e.credentials,r=t,e=i,new iL(n,r,e)}createRemoteStore(e){return t=this.localStore,n=this.datastore,r=e.asyncQueue,i=e=>QL(this.syncEngine,e,0),s=new(H1.bt()?H1:W1),new oL(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 zL(e,t,n,r,i,s);return o&&(a.Qo=!0),a}(this.localStore,this.remoteStore,this.eventManager,this.sharedClientState,e.initialUser,e.maxConcurrentLimboResolutions,t)}terminate(){return async function(e){const t=e;wR("RemoteStore","RemoteStore shutting down."),t.Wr.add(5),await cL(t),t.zr.shutdown(),t.Hr.set("Unknown")}(this.remoteStore)}}function fM(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 pM{constructor(e){this.observer=e,this.muted=!1}next(e){this.observer.next&&this.tc(this.observer.next,e)}error(e){this.observer.error?this.tc(this.observer.error,e):console.error("Uncaught Error in snapshot listener:",e)}ec(){this.muted=!0}tc(e,t){this.muted||setTimeout(()=>{this.muted||e(t)},0)}}class gM{constructor(e,t){this.nc=e,this.N=t,this.metadata=new AR,this.buffer=new Uint8Array,this.sc=new TextDecoder("utf-8"),this.ic().then(e=>{e&&e.wo()?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.nc.cancel()}async getMetadata(){return this.metadata.promise}async zo(){return await this.getMetadata(),this.ic()}async ic(){var e=await this.rc();if(null===e)return null;var t=this.sc.decode(e),n=Number(t);isNaN(n)&&this.oc(`length string (${t}) is not valid number`);t=await this.cc(n);return new ML(JSON.parse(t),e.length+n)}ac(){return this.buffer.findIndex(e=>e==="{".charCodeAt(0))}async rc(){for(;this.ac()<0&&!await this.uc(););if(0===this.buffer.length)return null;var e=this.ac();e<0&&this.oc("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 cc(e){for(;this.buffer.length<e;)await this.uc()&&this.oc("Reached the end of bundle when more is expected.");var t=this.sc.decode(this.buffer.slice(0,e));return this.buffer=this.buffer.slice(e),t}oc(e){throw this.nc.cancel(),new Error(`Invalid bundle format: ${e}`)}async uc(){var e=await this.nc.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 mM{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 CR(kR.INVALID_ARGUMENT,"Firestore transactions require all reads to be executed before all writes.");const t=await async function(e,t){const r=e,n=fO(r.N)+"/documents",i={documents:t.map(e=>lO(r.N,e))},s=await r.Ki("BatchGetDocuments",n,i),o=new Map;s.forEach(e=>{const t=(n=r.N,"found"in(e=e)?function(e,t){SR(!!t.found),t.found.name,t.found.updateTime;var n=uO(e,t.found.name),r=oO(t.found.updateTime),i=new wP({mapValue:{fields:t.found.fields}});return bP.newFoundDocument(n,r,i)}(n,e):"missing"in e?function(e,t){SR(!!t.missing),SR(!!t.readTime);var n=uO(e,t.missing),r=oO(t.readTime);return bP.newNoDocument(n,r)}(n,e):ER());var n;o.set(t.key.toString(),t)});const a=[];return t.forEach(e=>{var t=o.get(e.toString());SR(!!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 Rx(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=oP.fromPath(t);this.mutations.push(new Px(n,this.precondition(n)))}),await async function(e,t){const n=e,r=fO(n.N)+"/documents",i={writes:t.map(e=>vO(n.N,e))};await n.Li("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 ER();t=VR.min()}var n=this.readVersions.get(e.key.toString());if(n){if(!t.isEqual(n))throw new CR(kR.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?yx.updateTime(t):yx.none()}preconditionForUpdate(e){const t=this.readVersions.get(e.toString());if(this.writtenDocs.has(e.toString())||!t)return yx.exists(!0);if(t.isEqual(VR.min()))throw new CR(kR.INVALID_ARGUMENT,"Can't update a document that doesn't exist.");return yx.updateTime(t)}write(e){this.ensureCommitNotCalled(),this.mutations.push(e)}ensureCommitNotCalled(){}}class vM{constructor(e,t,n,r){this.asyncQueue=e,this.datastore=t,this.updateFunction=n,this.deferred=r,this.hc=5,this.ar=new eL(this.asyncQueue,"transaction_retry")}run(){--this.hc,this.lc()}lc(){this.ar.Xi(async()=>{const t=new mM(this.datastore),e=this.fc(t);e&&e.then(e=>{this.asyncQueue.enqueueAndForget(()=>t.commit().then(()=>{this.deferred.resolve(e)}).catch(e=>{this.dc(e)}))}).catch(e=>{this.dc(e)})})}fc(e){try{var t=this.updateFunction(e);return!rP(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}}dc(e){0<this.hc&&this.wc(e)?(--this.hc,this.asyncQueue.enqueueAndForget(()=>(this.lc(),Promise.resolve()))):this.deferred.reject(e)}wc(e){if("FirebaseError"!==e.name)return!1;var t=e.code;return"aborted"===t||"failed-precondition"===t||!Ox(t)}}class yM{constructor(e,t,n){this.credentials=e,this.asyncQueue=t,this.databaseInfo=n,this.user=mR.UNAUTHENTICATED,this.clientId=MR.I(),this.credentialListener=()=>Promise.resolve(),this.credentials.start(t,async e=>{wR("FirestoreClient","Received user=",e.uid),await this.credentialListener(e),this.user=e})}async getConfiguration(){return{asyncQueue:this.asyncQueue,databaseInfo:this.databaseInfo,clientId:this.clientId,credentials:this.credentials,initialUser:this.user,maxConcurrentLimboResolutions:100}}setCredentialChangeListener(e){this.credentialListener=e}verifyNotTerminated(){if(this.asyncQueue.isShuttingDown)throw new CR(kR.FAILED_PRECONDITION,"The client has already been terminated.")}terminate(){this.asyncQueue.enterRestrictedMode();const n=new AR;return this.asyncQueue.enqueueAndForgetEvenWhileRestricted(async()=>{try{this.onlineComponents&&await this.onlineComponents.terminate(),this.offlineComponents&&await this.offlineComponents.terminate(),this.credentials.shutdown(),n.resolve()}catch(e){var t=kL(e,"Failed to shutdown persistence");n.reject(t)}}),n.promise}}async function _M(e,t){e.asyncQueue.verifyOperationInProgress(),wR("FirestoreClient","Initializing OfflineComponentProvider");var n=await e.getConfiguration();await t.initialize(n);let r=n.initialUser;e.setCredentialChangeListener(async e=>{r.isEqual(e)||(await v1(t.localStore,e),r=e)}),t.persistence.setDatabaseDeletedListener(()=>e.terminate()),e.offlineComponents=t}async function wM(e,t){e.asyncQueue.verifyOperationInProgress();var n=await bM(e);wR("FirestoreClient","Initializing OnlineComponentProvider");var r=await e.getConfiguration();await t.initialize(n,r),e.setCredentialChangeListener(e=>async function(e,t){const n=e;n.asyncQueue.verifyOperationInProgress(),wR("RemoteStore","RemoteStore received new credentials");var r=gL(n);n.Wr.add(3),await cL(n),r&&n.Hr.set("Unknown"),await n.remoteSyncer.handleCredentialChange(t),n.Wr.delete(3),await aL(n)}(t.remoteStore,e)),e.onlineComponents=t}async function bM(e){return e.offlineComponents||(wR("FirestoreClient","Using default OfflineComponentProvider"),await _M(e,new lM)),e.offlineComponents}async function IM(e){return e.onlineComponents||(wR("FirestoreClient","Using default OnlineComponentProvider"),await wM(e,new dM)),e.onlineComponents}function TM(e){return bM(e).then(e=>e.persistence)}function EM(e){return bM(e).then(e=>e.localStore)}function SM(e){return IM(e).then(e=>e.remoteStore)}function kM(e){return IM(e).then(e=>e.syncEngine)}async function CM(e){const t=await IM(e),n=t.eventManager;return n.onListen=(async function(e,t){const n=aM(e);let r,i;const s=n.Oo.get(t);if(s)r=s.targetId,n.sharedClientState.addLocalQueryTarget(r),i=s.view.xo();else{const e=await b1(n.localStore,YP(t)),s=n.sharedClientState.addLocalQueryTarget(e.targetId);r=e.targetId,i=await WL(n,t,r,"current"===s),n.isPrimaryClient&&lL(n.remoteStore,e)}return i}).bind(null,t.syncEngine),n.onUnlisten=(async function(e,t){const n=e,r=n.Oo.get(t),i=n.Fo.get(r.targetId);if(1<i.length)return n.Fo.set(r.targetId,i.filter(e=>!XP(e,t))),void n.Oo.delete(t);n.isPrimaryClient?(n.sharedClientState.removeLocalQueryTarget(r.targetId),n.sharedClientState.isActiveQueryTarget(r.targetId)||await I1(n.localStore,r.targetId,!1).then(()=>{n.sharedClientState.clearQueryState(r.targetId),uL(n.remoteStore,r.targetId),ZL(n,r.targetId)}).catch(KD)):(ZL(n,r.targetId),await I1(n.localStore,r.targetId,!0))}).bind(null,t.syncEngine),n}function AM(e,t,n={}){const r=new AR;return e.asyncQueue.enqueueAndForget(async()=>function(n,r,i,s,o){const e=new pM({next:e=>{r.enqueueAndForget(()=>OL(n,a));var t=e.docs.has(i);!t&&e.fromCache?o.reject(new CR(kR.UNAVAILABLE,"Failed to get document because the client is offline.")):t&&e.fromCache&&s&&"server"===s.source?o.reject(new CR(kR.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 LL($P(i.path),e,{includeMetadataChanges:!0,fo:!0});return xL(n,a)}(await CM(e),e.asyncQueue,t,n,r)),r.promise}function NM(e,t,n={}){const r=new AR;return e.asyncQueue.enqueueAndForget(async()=>function(t,n,e,r,i){const s=new pM({next:e=>{n.enqueueAndForget(()=>OL(t,o)),e.fromCache&&"server"===r.source?i.reject(new CR(kR.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 LL(e,s,{includeMetadataChanges:!0,fo:!0});return xL(t,o)}(await CM(e),e.asyncQueue,t,n,r)),r.promise}function RM(e,t,n,r){const i=(n=n,t=Z1(t),s="string"==typeof n?(new TextEncoder).encode(n):n,n=function(e){if(e instanceof Uint8Array)return fM(e,void 0);if(e instanceof ArrayBuffer)return fM(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 gM(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=oO(t.createTime);return n.persistence.runTransaction("hasNewerBundle","readonly",e=>n.Je.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 UL(i,t.localStore,n.N);let e=await n.zo();for(;e;){const t=await o.mo(e);t&&r._updateProgress(t),e=await n.zo()}var s=await o.complete();await rM(t,s.En,void 0),await function(e,t){const n=e;return n.persistence.runTransaction("Save bundle","readwrite",e=>n.Je.saveBundleMetadata(e,t))}(t.localStore,i),r._completeWith(s.progress)}catch(t){IR("SyncEngine",`Loading bundle failed with ${t}`),r._failWith(t)}}(r,t,n).then(()=>{r.sharedClientState.notifyBundleLoaded()})}(await kM(e),i,r)})}class PM{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 xM{constructor(e,t){this.projectId=e,this.database=t||"(default)"}get isDefaultDatabase(){return"(default)"===this.database}isEqual(e){return e instanceof xM&&e.projectId===this.projectId&&e.database===this.database}}const OM=new Map;function DM(e,t,n){if(!n)throw new CR(kR.INVALID_ARGUMENT,`Function ${e}() cannot be called with an empty ${t}.`)}function LM(e,t,n,r){if(!0===t&&!0===r)throw new CR(kR.INVALID_ARGUMENT,`${e} and ${n} cannot be used together.`)}function MM(e){if(!oP.isDocumentKey(e))throw new CR(kR.INVALID_ARGUMENT,`Invalid document reference. Document references must have an even number of segments, but ${e} has ${e.length}.`)}function FM(e){if(oP.isDocumentKey(e))throw new CR(kR.INVALID_ARGUMENT,`Invalid collection reference. Collection references must have an odd number of segments, but ${e} has ${e.length}.`)}function UM(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":ER();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 jM(e,t){if((e="_delegate"in e?e._delegate:e)instanceof t)return e;if(t.name===e.constructor.name)throw new CR(kR.INVALID_ARGUMENT,"Type does not match the expected instance. Did you pass a reference from a different Firestore SDK?");var n=UM(e);throw new CR(kR.INVALID_ARGUMENT,`Expected type '${t.name}', but it was: ${n}`)}function qM(e,t){if(t<=0)throw new CR(kR.INVALID_ARGUMENT,`Function ${e}() requires a positive number, but it was: ${t}.`)}class VM{constructor(e){var t;if(void 0===e.host){if(void 0!==e.ssl)throw new CR(kR.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 CR(kR.INVALID_ARGUMENT,"cacheSizeBytes must be at least 1048576");this.cacheSizeBytes=e.cacheSizeBytes}this.experimentalForceLongPolling=!!e.experimentalForceLongPolling,this.experimentalAutoDetectLongPolling=!!e.experimentalAutoDetectLongPolling,this.useFetchStreams=!!e.useFetchStreams,LM("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 BM{constructor(e,t){this._credentials=t,this.type="firestore-lite",this._persistenceKey="(lite)",this._settings=new VM({}),this._settingsFrozen=!1,e instanceof xM?this._databaseId=e:(this._app=e,this._databaseId=function(e){if(!Object.prototype.hasOwnProperty.apply(e.options,["projectId"]))throw new CR(kR.INVALID_ARGUMENT,'"projectId" not provided in firebase.initializeApp.');return new xM(e.options.projectId)}(e))}get app(){if(!this._app)throw new CR(kR.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 CR(kR.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 VM(e),void 0!==e.credentials&&(this._credentials=function(e){if(!e)return new RR;switch(e.type){case"gapi":var t=e.client;return SR(!("object"!=typeof t||null===t||!t.auth||!t.auth.getAuthHeaderValueForFirstParty)),new DR(t,e.sessionIndex||"0",e.iamToken||null);case"provider":return e.client;default:throw new CR(kR.INVALID_ARGUMENT,"makeCredentialsProvider 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=OM.get(e);t&&(wR("ComponentProvider","Removing Datastore"),OM.delete(e),t.terminate())}(this),Promise.resolve()}}class $M{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 zM(this.firestore,this.converter,this._key.path.popLast())}withConverter(e){return new $M(this.firestore,e,this._key)}}class KM{constructor(e,t,n){this.converter=t,this._query=n,this.type="query",this.firestore=e}withConverter(e){return new KM(this.firestore,e,this._query)}}class zM extends KM{constructor(e,t,n){super(e,t,$P(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 $M(this.firestore,null,new oP(e))}withConverter(e){return new zM(this.firestore,e,this._path)}}function WM(e,t,...n){if(e=Kd(e),DM("collection","path",t),e instanceof BM){var r=WR.fromString(t,...n);return FM(r),new zM(e,null,r)}if(!(e instanceof $M||e instanceof zM))throw new CR(kR.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");r=e._path.child(WR.fromString(t,...n));return FM(r),new zM(e.firestore,null,r)}function HM(e,t,...n){if(e=Kd(e),DM("doc","path",t=1===arguments.length?MR.I():t),e instanceof BM){var r=WR.fromString(t,...n);return MM(r),new $M(e,null,new oP(r))}if(!(e instanceof $M||e instanceof zM))throw new CR(kR.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");r=e._path.child(WR.fromString(t,...n));return MM(r),new $M(e.firestore,e instanceof zM?e.converter:null,new oP(r))}function GM(e,t){return e=Kd(e),t=Kd(t),(e instanceof $M||e instanceof zM)&&(t instanceof $M||t instanceof zM)&&e.firestore===t.firestore&&e.path===t.path&&e.converter===t.converter}function QM(e,t){return e=Kd(e),t=Kd(t),e instanceof KM&&t instanceof KM&&e.firestore===t.firestore&&XP(e._query,t._query)&&e.converter===t.converter}class YM{constructor(){this._c=Promise.resolve(),this.mc=[],this.gc=!1,this.yc=[],this.Tc=null,this.Ec=!1,this.Ic=!1,this.Ac=[],this.ar=new eL(this,"async_queue_retry"),this.Rc=()=>{var e=X1();e&&wR("AsyncQueue","Visibility state changed to "+e.visibilityState),this.ar.tr()};const e=X1();e&&"function"==typeof e.addEventListener&&e.addEventListener("visibilitychange",this.Rc)}get isShuttingDown(){return this.gc}enqueueAndForget(e){this.enqueue(e)}enqueueAndForgetEvenWhileRestricted(e){this.bc(),this.Pc(e)}enterRestrictedMode(e){if(!this.gc){this.gc=!0,this.Ic=e||!1;const t=X1();t&&"function"==typeof t.removeEventListener&&t.removeEventListener("visibilitychange",this.Rc)}}enqueue(e){if(this.bc(),this.gc)return new Promise(()=>{});const t=new AR;return this.Pc(()=>this.gc&&this.Ic?Promise.resolve():(e().then(t.resolve,t.reject),t.promise)).then(()=>t.promise)}enqueueRetryable(e){this.enqueueAndForget(()=>(this.mc.push(e),this.vc()))}async vc(){if(0!==this.mc.length){try{await this.mc[0](),this.mc.shift(),this.ar.reset()}catch(e){if(!nD(e))throw e;wR("AsyncQueue","Operation failed with retryable error: "+e)}0<this.mc.length&&this.ar.Xi(()=>this.vc())}}Pc(e){var t=this._c.then(()=>(this.Ec=!0,e().catch(e=>{throw this.Tc=e,this.Ec=!1,bR("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.Ec=!1,e))));return this._c=t}enqueueAfterDelay(e,t,n){this.bc(),-1<this.Ac.indexOf(e)&&(t=0);var r=SL.createAndSchedule(this,e,t,n,e=>this.Vc(e));return this.yc.push(r),r}bc(){this.Tc&&ER()}verifyOperationInProgress(){}async Sc(){for(var e;await(e=this._c),e!==this._c;);}Dc(e){for(const t of this.yc)if(t.timerId===e)return!0;return!1}Cc(t){return this.Sc().then(()=>{this.yc.sort((e,t)=>e.targetTimeMs-t.targetTimeMs);for(const e of this.yc)if(e.skipDelay(),"all"!==t&&e.timerId===t)break;return this.Sc()})}Nc(e){this.Ac.push(e)}Vc(e){var t=this.yc.indexOf(e);this.yc.splice(t,1)}}function JM(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 XM{constructor(){this._progressObserver={},this._taskCompletionResolver=new AR,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 ZM,eF,tF,nF;class rF extends BM{constructor(e,t){super(e,t),this.type="firestore",this._queue=new YM,this._persistenceKey="name"in e?e.name:"[DEFAULT]"}_terminate(){return this._firestoreClient||sF(this),this._firestoreClient.terminate()}}function iF(e){return e._firestoreClient||sF(e),e._firestoreClient.verifyNotTerminated(),e._firestoreClient}function sF(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 PM(n,r,i,s.host,s.ssl,s.experimentalForceLongPolling,s.experimentalAutoDetectLongPolling,s.useFetchStreams));e._firestoreClient=new yM(e._credentials,e._queue,o)}function oF(e,n,r){const i=new AR;return e.asyncQueue.enqueue(async()=>{try{await _M(e,r),await wM(e,n),i.resolve()}catch(e){if(!("FirebaseError"===(t=e).name?t.code===kR.FAILED_PRECONDITION||t.code===kR.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 aF(e){return function(e){const t=new AR;return e.asyncQueue.enqueueAndForget(async()=>async function(e,t){const n=e;gL(n.remoteStore)||wR("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.In.getHighestUnacknowledgedBatchId(e))}();if(-1===e)return void t.resolve();const r=n.Ko.get(e)||[];r.push(t),n.Ko.set(e,r)}catch(e){const n=kL(e,"Initialization of waitForPendingWrites() operation failed");t.reject(n)}}(await kM(e),t)),t.promise}(iF(e=jM(e,rF)))}function cF(e){return(n=iF(e=jM(e,rF))).asyncQueue.enqueue(async()=>{const e=await TM(n),t=await SM(n);return e.setNetworkEnabled(!0),function(){const e=t;return e.Wr.delete(0),aL(e)}()});var n}function lF(e){return(n=iF(e=jM(e,rF))).asyncQueue.enqueue(async()=>{const e=await TM(n),t=await SM(n);return e.setNetworkEnabled(!1),async function(){const e=t;e.Wr.add(0),await cL(e),e.Hr.set("Offline")}()});var n}function uF(t,e){return n=iF(t=jM(t,rF)),r=e,n.asyncQueue.enqueue(async()=>function(e,t){const n=e;return n.persistence.runTransaction("Get named query","readonly",e=>n.Je.getNamedQuery(e,t))}(await EM(n),r)).then(e=>e?new KM(t,null,e.query):null);var n,r}function hF(e){if(e._initialized||e._terminated)throw new CR(kR.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 dF{constructor(...e){for(let t=0;t<e.length;++t)if(0===e[t].length)throw new CR(kR.INVALID_ARGUMENT,"Invalid field name at argument $(i + 1). Field names must not be empty.");this._internalPath=new GR(e)}isEqual(e){return this._internalPath.isEqual(e._internalPath)}}class fF{constructor(e){this._byteString=e}static fromBase64String(e){try{return new fF(YR.fromBase64String(e))}catch(e){throw new CR(kR.INVALID_ARGUMENT,"Failed to construct data from Base64 string: "+e)}}static fromUint8Array(e){return new fF(YR.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 pF{constructor(e){this._methodName=e}}class gF{constructor(e,t){if(!isFinite(e)||e<-90||90<e)throw new CR(kR.INVALID_ARGUMENT,"Latitude must be a number between -90 and 90, but was: "+e);if(!isFinite(t)||t<-180||180<t)throw new CR(kR.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 FR(this._lat,e._lat)||FR(this._long,e._long)}}const mF=/^__.*__$/;class vF{constructor(e,t,n){this.data=e,this.fieldMask=t,this.fieldTransforms=n}toMutation(e,t){return null!==this.fieldMask?new kx(e,this.data,this.fieldMask,t,this.fieldTransforms):new Sx(e,this.data,t,this.fieldTransforms)}}class yF{constructor(e,t,n){this.data=e,this.fieldMask=t,this.fieldTransforms=n}toMutation(e,t){return new kx(e,this.data,this.fieldMask,t,this.fieldTransforms)}}function _F(e){switch(e){case 0:case 2:case 1:return 1;case 3:case 4:return;default:throw ER()}}class wF{constructor(e,t,n,r,i,s){this.settings=e,this.databaseId=t,this.N=n,this.ignoreUndefinedProperties=r,void 0===i&&this.xc(),this.fieldTransforms=i||[],this.fieldMask=s||[]}get path(){return this.settings.path}get kc(){return this.settings.kc}$c(e){return new wF(Object.assign(Object.assign({},this.settings),e),this.databaseId,this.N,this.ignoreUndefinedProperties,this.fieldTransforms,this.fieldMask)}Oc(e){var t;const n=null===(t=this.path)||void 0===t?void 0:t.child(e),r=this.$c({path:n,Fc:!1});return r.Mc(e),r}Lc(e){var t;const n=null===(t=this.path)||void 0===t?void 0:t.child(e),r=this.$c({path:n,Fc:!1});return r.xc(),r}Bc(e){return this.$c({path:void 0,Fc:!0})}Uc(e){return qF(e,this.settings.methodName,this.settings.qc||!1,this.path,this.settings.Kc)}contains(t){return void 0!==this.fieldMask.find(e=>t.isPrefixOf(e))||void 0!==this.fieldTransforms.find(e=>t.isPrefixOf(e.field))}xc(){if(this.path)for(let e=0;e<this.path.length;e++)this.Mc(this.path.get(e))}Mc(e){if(0===e.length)throw this.Uc("Document fields must not be empty");if(_F(this.kc)&&mF.test(e))throw this.Uc('Document fields cannot begin and end with "__"')}}class bF{constructor(e,t,n){this.databaseId=e,this.ignoreUndefinedProperties=t,this.N=n||Z1(e)}jc(e,t,n,r=!1){return new wF({kc:e,methodName:t,Kc:n,path:GR.emptyPath(),Fc:!1,qc:r},this.databaseId,this.N,this.ignoreUndefinedProperties)}}function IF(e){var t=e._freezeSettings(),n=Z1(e._databaseId);return new bF(e._databaseId,!!t.ignoreUndefinedProperties,n)}function TF(e,t,n,r,i,s={}){const o=e.jc(s.merge||s.mergeFields?2:0,t,n,i);MF("Data must be an object, but it was:",o,r);var a=DF(r,o);let c,l;if(s.merge)c=new QR(o.fieldMask),l=o.fieldTransforms;else if(s.mergeFields){const e=[];for(const r of s.mergeFields){const i=FF(t,r,n);if(!o.contains(i))throw new CR(kR.INVALID_ARGUMENT,`Field '${i}' is specified in your field mask but missing from your input data.`);VF(e,i)||e.push(i)}c=new QR(e),l=o.fieldTransforms.filter(e=>c.covers(e.field))}else c=null,l=o.fieldTransforms;return new vF(new wP(a),c,l)}class EF extends pF{_toFieldTransform(e){if(2!==e.kc)throw 1===e.kc?e.Uc(`${this._methodName}() can only appear at the top level of your update data`):e.Uc(`${this._methodName}() cannot be used with set() unless you pass {merge:true}`);return e.fieldMask.push(e.path),null}isEqual(e){return e instanceof EF}}function SF(e,t,n){return new wF({kc:3,Kc:t.settings.Kc,methodName:e._methodName,Fc:n},t.databaseId,t.N,t.ignoreUndefinedProperties)}class kF extends pF{_toFieldTransform(e){return new mx(e.path,new cx)}isEqual(e){return e instanceof kF}}class CF extends pF{constructor(e,t){super(e),this.Qc=t}_toFieldTransform(e){const t=SF(this,e,!0),n=this.Qc.map(e=>OF(e,t)),r=new lx(n);return new mx(e.path,r)}isEqual(e){return this===e}}class AF extends pF{constructor(e,t){super(e),this.Qc=t}_toFieldTransform(e){const t=SF(this,e,!0),n=this.Qc.map(e=>OF(e,t)),r=new hx(n);return new mx(e.path,r)}isEqual(e){return this===e}}class NF extends pF{constructor(e,t){super(e),this.Wc=t}_toFieldTransform(e){var t=new fx(e.N,sx(e.N,this.Wc));return new mx(e.path,t)}isEqual(e){return this===e}}function RF(e,i,s,t){const o=e.jc(1,i,s);MF("Data must be an object, but it was:",o,t);const a=[],c=wP.empty();$R(t,(e,t)=>{var n=jF(i,e,s);t=Kd(t);var r=o.Lc(n);if(t instanceof EF)a.push(n);else{const e=OF(t,r);null!=e&&(a.push(n),c.set(n,e))}});var n=new QR(a);return new yF(c,n,o.fieldTransforms)}function PF(e,t,n,r,i,s){const o=e.jc(1,t,n),a=[FF(t,r,n)],c=[i];if(s.length%2!=0)throw new CR(kR.INVALID_ARGUMENT,`Function ${t}() needs to be called with an even number of arguments that alternate between field names and values.`);for(let f=0;f<s.length;f+=2)a.push(FF(t,s[f])),c.push(s[f+1]);const l=[],u=wP.empty();for(let p=a.length-1;0<=p;--p)if(!VF(l,a[p])){const t=a[p];var h=Kd(h=c[p]);const r=o.Lc(t);if(h instanceof EF)l.push(t);else{const e=OF(h,r);null!=e&&(l.push(t),u.set(t,e))}}var d=new QR(l);return new yF(u,d,o.fieldTransforms)}function xF(e,t,n,r=!1){return OF(n,e.jc(r?4:3,t))}function OF(s,e){if(LF(s=Kd(s)))return MF("Unsupported field value:",e,s),DF(s,e);if(s instanceof pF)return function(e,t){if(!_F(t.kc))throw t.Uc(`${e._methodName}() can only be used with update() and set()`);if(!t.path)throw t.Uc(`${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.Fc&&4!==e.kc)throw e.Uc("Nested arrays are not supported");return function(t){const n=[];let r=0;for(const i of s){let e=OF(i,t.Bc(r));null==e&&(e={nullValue:"NULL_VALUE"}),n.push(e),r++}return{arrayValue:{values:n}}}(e)}return function(e,t){if(null===(e=Kd(s)))return{nullValue:"NULL_VALUE"};if("number"==typeof e)return sx(t.N,e);if("boolean"==typeof e)return{booleanValue:e};if("string"==typeof e)return{stringValue:e};if(e instanceof Date){var n=qR.fromDate(e);return{timestampValue:iO(t.N,n)}}if(e instanceof qR){n=new qR(e.seconds,1e3*Math.floor(e.nanoseconds/1e3));return{timestampValue:iO(t.N,n)}}if(e instanceof gF)return{geoPointValue:{latitude:e.latitude,longitude:e.longitude}};if(e instanceof fF)return{bytesValue:sO(t.N,e._byteString)};if(e instanceof $M){const r=t.databaseId,i=e.firestore._databaseId;if(!i.isEqual(r))throw t.Uc(`Document reference is for database ${i.projectId}/${i.database} but should be for database ${r.projectId}/${r.database}`);return{referenceValue:aO(e.firestore._databaseId||t.databaseId,e._key.path)}}throw t.Uc(`Unsupported field value: ${UM(e)}`)}(0,e)}function DF(e,r){const i={};return KR(e)?r.path&&0<r.path.length&&r.fieldMask.push(r.path):$R(e,(e,t)=>{var n=OF(t,r.Oc(e));null!=n&&(i[e]=n)}),{mapValue:{fields:i}}}function LF(e){return!("object"!=typeof e||null===e||e instanceof Array||e instanceof Date||e instanceof qR||e instanceof gF||e instanceof fF||e instanceof $M||e instanceof pF)}function MF(e,t,n){if(!LF(n)||("object"!=typeof(i=n)||null===i||Object.getPrototypeOf(i)!==Object.prototype&&null!==Object.getPrototypeOf(i))){var r=UM(n);throw"an object"===r?t.Uc(e+" a custom object"):t.Uc(e+" "+r)}var i}function FF(e,t,n){if((t=Kd(t))instanceof dF)return t._internalPath;if("string"==typeof t)return jF(e,t);throw qF("Field path arguments must be of type string or FieldPath.",e,!1,void 0,n)}const UF=new RegExp("[~\\*/\\[\\]]");function jF(t,n,r){if(0<=n.search(UF))throw qF(`Invalid field path (${n}). Paths must not contain '~', '*', '/', '[', or ']'`,t,!1,void 0,r);try{return new dF(...n.split("."))._internalPath}catch(e){throw qF(`Invalid field path (${n}). Paths must not be empty, begin with '.', end with '.', or contain '..'`,t,!1,void 0,r)}}function qF(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 CR(kR.INVALID_ARGUMENT,a+e+c)}function VF(e,t){return e.some(e=>e.isEqual(t))}class BF{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 $M(this._firestore,this._converter,this._key)}exists(){return null!==this._document}data(){if(this._document){if(this._converter){var e=new $F(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(KF("DocumentSnapshot.get",e));if(null!==t)return this._userDataWriter.convertValue(t)}}}class $F extends BF{data(){return super.data()}}function KF(e,t){return"string"==typeof t?jF(e,t):(t instanceof dF?t:t._delegate)._internalPath}class zF{constructor(e,t){this.hasPendingWrites=e,this.fromCache=t}isEqual(e){return this.hasPendingWrites===e.hasPendingWrites&&this.fromCache===e.fromCache}}class WF extends BF{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 HF(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(KF("DocumentSnapshot.get",e));if(null!==n)return this._userDataWriter.convertValue(n,t.serverTimestamps)}}}class HF extends WF{data(e={}){return super.data(e)}}class GF{constructor(e,t,n,r){this._firestore=e,this._userDataWriter=t,this._snapshot=r,this.metadata=new zF(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 HF(this._firestore,this._userDataWriter,e.key,e,new zF(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 CR(kR.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 HF(s._firestore,s._userDataWriter,e.doc.key,e.doc,new zF(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 HF(s._firestore,s._userDataWriter,e.doc.key,e.doc,new zF(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 ER()}}(e.type),doc:t,oldIndex:n,newIndex:r}})}}(this,t),this._cachedChangesIncludeMetadataChanges=t),this._cachedChanges}}function QF(e,t){return e instanceof WF&&t instanceof WF?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 GF&&t instanceof GF&&e._firestore===t._firestore&&QM(e.query,t.query)&&e.metadata.isEqual(t.metadata)&&e._snapshot.isEqual(t._snapshot)}function YF(e){if(zP(e)&&0===e.explicitOrderBy.length)throw new CR(kR.UNIMPLEMENTED,"limitToLast() queries require specifying at least one orderBy() clause")}class JF{}function XF(e,...t){for(const n of t)e=n._apply(e);return e}class ZF extends JF{constructor(e,t,n){super(),this.Gc=e,this.zc=t,this.Hc=n,this.type="where"}_apply(e){var t=IF(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 CR(kR.INVALID_ARGUMENT,`Invalid Query. You can't perform '${s}' queries on FieldPath.documentId().`);if("in"===s||"not-in"===s){oU(o,s);const t=[];for(const n of o)t.push(sU(r,e,n));a={arrayValue:{values:t}}}else a=sU(r,e,o)}else"in"!==s&&"not-in"!==s&&"array-contains-any"!==s||oU(o,s),a=xF(n,t,o,"in"===s||"not-in"===s);var c=CP.create(i,s,a);return function(e,t){if(t.v()){const r=HP(e);if(null!==r&&!r.isEqual(t.field))throw new CR(kR.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=WP(e);null!==n&&aU(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 CR(kR.INVALID_ARGUMENT,`Invalid query. You cannot use more than one '${t.op.toString()}' filter.`):new CR(kR.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.Gc,this.zc,this.Hc);return new KM(e.firestore,e.converter,(e=e._query,t=e.filters.concat([t]),new VP(e.path,e.collectionGroup,e.explicitOrderBy.slice(),t,e.limit,e.limitType,e.startAt,e.endAt)))}}class eU extends JF{constructor(e,t){super(),this.Gc=e,this.Jc=t,this.type="orderBy"}_apply(e){var t=function(e,t,n){if(null!==e.startAt)throw new CR(kR.INVALID_ARGUMENT,"Invalid query. You must not call startAt() or startAfter() before calling orderBy().");if(null!==e.endAt)throw new CR(kR.INVALID_ARGUMENT,"Invalid query. You must not call endAt() or endBefore() before calling orderBy().");var r,i=new UP(t,n);return n=i,null!==WP(e=e)||null!==(r=HP(e))&&aU(0,r,n.field),i}(e._query,this.Gc,this.Jc);return new KM(e.firestore,e.converter,(e=e._query,t=e.explicitOrderBy.concat([t]),new VP(e.path,e.collectionGroup,t,e.filters.slice(),e.limit,e.limitType,e.startAt,e.endAt)))}}class tU extends JF{constructor(e,t,n){super(),this.type=e,this.Yc=t,this.Xc=n}_apply(e){return new KM(e.firestore,e.converter,JP(e._query,this.Yc,this.Xc))}}class nU extends JF{constructor(e,t,n){super(),this.type=e,this.Zc=t,this.ta=n}_apply(e){var t,n=iU(e,this.type,this.Zc,this.ta);return new KM(e.firestore,e.converter,(t=e._query,e=n,new VP(t.path,t.collectionGroup,t.explicitOrderBy.slice(),t.filters.slice(),t.limit,t.limitType,e,t.endAt)))}}class rU extends JF{constructor(e,t,n){super(),this.type=e,this.Zc=t,this.ta=n}_apply(e){var t,n=iU(e,this.type,this.Zc,this.ta);return new KM(e.firestore,e.converter,(t=e._query,e=n,new VP(t.path,t.collectionGroup,t.explicitOrderBy.slice(),t.filters.slice(),t.limit,t.limitType,t.startAt,e)))}}function iU(e,t,n,r){if(n[0]=Kd(n[0]),n[0]instanceof BF)return function(e,t,n,r,i){if(!r)throw new CR(kR.NOT_FOUND,`Can't use a DocumentSnapshot that doesn't exist for ${n}().`);const s=[];for(const n of QP(e))if(n.field.isKeyField())s.push(fP(t,r.key));else{const e=r.data.field(n.field);if(tP(e))throw new CR(kR.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 CR(kR.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 MP(s,i)}(e._query,e.firestore._databaseId,t,n[0]._document,r);var i=IF(e.firestore);return function(e,t,n,r,i,s){const o=e.explicitOrderBy;if(i.length>o.length)throw new CR(kR.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 CR(kR.INVALID_ARGUMENT,`Invalid query. Expected a string for document ID in ${r}(), but got a ${typeof l}`);if(!GP(e)&&-1!==l.indexOf("/"))throw new CR(kR.INVALID_ARGUMENT,`Invalid query. When querying a collection and ordering by FieldPath.documentId(), the value passed to ${r}() must be a plain document ID, but '${l}' contains a slash.`);const n=e.path.child(WR.fromString(l));if(!oP.isDocumentKey(n))throw new CR(kR.INVALID_ARGUMENT,`Invalid query. When querying a collection group and ordering by FieldPath.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 oP(n);a.push(fP(t,i))}else{const e=xF(n,r,l);a.push(e)}}return new MP(a,s)}(e._query,e.firestore._databaseId,i,t,n,r)}function sU(e,t,n){if("string"==typeof(n=Kd(n))){if(""===n)throw new CR(kR.INVALID_ARGUMENT,"Invalid query. When querying with FieldPath.documentId(), you must provide a valid document ID, but it was an empty string.");if(!GP(t)&&-1!==n.indexOf("/"))throw new CR(kR.INVALID_ARGUMENT,`Invalid query. When querying a collection by FieldPath.documentId(), you must provide a plain document ID, but '${n}' contains a '/' character.`);var r=t.path.child(WR.fromString(n));if(!oP.isDocumentKey(r))throw new CR(kR.INVALID_ARGUMENT,`Invalid query. When querying a collection group by FieldPath.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 fP(e,new oP(r))}if(n instanceof $M)return fP(e,n._key);throw new CR(kR.INVALID_ARGUMENT,`Invalid query. When querying with FieldPath.documentId(), you must provide a valid string or a DocumentReference, but it was: ${UM(n)}.`)}function oU(e,t){if(!Array.isArray(e)||0===e.length)throw new CR(kR.INVALID_ARGUMENT,`Invalid Query. A non-empty array is required for '${t.toString()}' filters.`);if(10<e.length)throw new CR(kR.INVALID_ARGUMENT,`Invalid Query. '${t.toString()}' filters support a maximum of 10 elements in the value array.`)}function aU(e,t,n){if(!n.isEqual(t))throw new CR(kR.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 cU{convertValue(e,t="none"){switch(aP(e)){case 0:return null;case 1:return e.booleanValue;case 2:return ZR(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(eP(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 ER()}}convertObject(e,n){const r={};return $R(e.fields,(e,t)=>{r[e]=this.convertValue(t,n)}),r}convertGeoPoint(e){return new gF(ZR(e.latitude),ZR(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 tP(n)?e(n):n}(e);return null==n?null:this.convertValue(n,t);case"estimate":return this.convertTimestamp(nP(e));default:return null}}convertTimestamp(e){var t=XR(e);return new qR(t.seconds,t.nanos)}convertDocumentKey(e,t){const n=WR.fromString(e);SR(AO(n));const r=new xM(n.get(1),n.get(3)),i=new oP(n.popFirst(5));return r.isEqual(t)||bR(`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 lU(e,t,n){return e?n&&(n.merge||n.mergeFields)?e.toFirestore(t,n):e.toFirestore(t):t}class uU extends cU{constructor(e){super(),this.firestore=e}convertBytes(e){return new fF(e)}convertReference(e){var t=this.convertDocumentKey(e,this.firestore._databaseId);return new $M(this.firestore,null,t)}}class hU{constructor(e,t){this._firestore=e,this._commitHandler=t,this._mutations=[],this._committed=!1,this._dataReader=IF(e)}set(e,t,n){this._verifyNotCommitted();const r=dU(e,this._firestore),i=lU(r.converter,t,n),s=TF(this._dataReader,"WriteBatch.set",r._key,i,null!==r.converter,n);return this._mutations.push(s.toMutation(r._key,yx.none())),this}update(e,t,n,...r){this._verifyNotCommitted();var i=dU(e,this._firestore);let s;return s="string"==typeof(t=Kd(t))||t instanceof dF?PF(this._dataReader,"WriteBatch.update",i._key,t,n,r):RF(this._dataReader,"WriteBatch.update",i._key,t),this._mutations.push(s.toMutation(i._key,yx.exists(!0))),this}delete(e){this._verifyNotCommitted();var t=dU(e,this._firestore);return this._mutations=this._mutations.concat(new Rx(t._key,yx.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 CR(kR.FAILED_PRECONDITION,"A write batch can no longer be used after commit() has been called.")}}function dU(e,t){if((e=Kd(e)).firestore!==t)throw new CR(kR.INVALID_ARGUMENT,"Provided document reference is from a different Firestore instance.");return e}class fU extends cU{constructor(e){super(),this.firestore=e}convertBytes(e){return new fF(e)}convertReference(e){var t=this.convertDocumentKey(e,this.firestore._databaseId);return new $M(this.firestore,null,t)}}function pU(t){t=jM(t,$M);const n=jM(t.firestore,rF),e=iF(n),r=new fU(n);return function(e,t){const n=new AR;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.Qn.An(e,t))}(t);i.isFoundDocument()?n.resolve(i):i.isNoDocument()?n.resolve(null):n.reject(new CR(kR.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=kL(e,`Failed to get document '${t} from cache`);n.reject(r)}}(await EM(e),t,n)),n.promise}(e,t._key).then(e=>new WF(n,r,t._key,e,new zF(null!==e&&e.hasLocalMutations,!0),t.converter))}function gU(t){t=jM(t,KM);const n=jM(t.firestore,rF),e=iF(n),r=new fU(n);return function(e,t){const n=new AR;return e.asyncQueue.enqueueAndForget(async()=>async function(e,t,n){try{const i=await T1(e,t,!0),s=new BL(t,i.Gn),o=s.bo(i.documents),a=s.applyChanges(o,!1);n.resolve(a.snapshot)}catch(e){var r=kL(e,`Failed to execute query '${t} against cache`);n.reject(r)}}(await EM(e),t,n)),n.promise}(e,t._query).then(e=>new GF(n,r,t,e))}function mU(e,t,n){e=jM(e,$M);var r=jM(e.firestore,rF),i=lU(e.converter,t,n);return wU(r,[TF(IF(r),"setDoc",e._key,i,null!==e.converter,n).toMutation(e._key,yx.none())])}function vU(e,t,n,...r){e=jM(e,$M);var i=jM(e.firestore,rF),s=IF(i);let o;return o="string"==typeof(t=Kd(t))||t instanceof dF?PF(s,"updateDoc",e._key,t,n,r):RF(s,"updateDoc",e._key,t),wU(i,[o.toMutation(e._key,yx.exists(!0))])}function yU(t,...n){var e;t=Kd(t);let r={includeMetadataChanges:!1},i=0;"object"!=typeof n[i]||JM(n[i])||(r=n[i],i++);var s={includeMetadataChanges:r.includeMetadataChanges};if(JM(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 $M)a=jM(t.firestore,rF),c=$P(t._key.path),o={next:e=>{n[i]&&n[i](bU(a,t,e))},error:n[i+1],complete:n[i+2]};else{const l=jM(t,KM);a=jM(l.firestore,rF),c=l._query;const u=new fU(a);o={next:e=>{n[i]&&n[i](new GF(a,u,l,e))},error:n[i+1],complete:n[i+2]},YF(t._query)}return function(e,t,n,r){const i=new pM(r),s=new LL(t,i,n);return e.asyncQueue.enqueueAndForget(async()=>xL(await CM(e),s)),()=>{i.ec(),e.asyncQueue.enqueueAndForget(async()=>OL(await CM(e),s))}}(iF(a),c,s,o)}function _U(e,t){return function(e,t){const n=new pM(t);return e.asyncQueue.enqueueAndForget(async()=>function(e,t){e.so.add(t),t.next()}(await CM(e),n)),()=>{n.ec(),e.asyncQueue.enqueueAndForget(async()=>function(e,t){e.so.delete(t)}(await CM(e),n))}}(iF(e=jM(e,rF)),JM(t)?t:{next:t})}function wU(e,t){return function(e,t){const n=new AR;return e.asyncQueue.enqueueAndForget(async()=>HL(await kM(e),t,n)),n.promise}(iF(e),t)}function bU(e,t,n){var r=n.docs.get(t._key),i=new fU(e);return new WF(e,i,t._key,r,new zF(n.hasPendingWrites,n.fromCache),t.converter)}class IU extends class{constructor(e,t){this._firestore=e,this._transaction=t,this._dataReader=IF(e)}get(e){const n=dU(e,this._firestore),r=new uU(this._firestore);return this._transaction.lookup([n._key]).then(e=>{if(!e||1!==e.length)return ER();const t=e[0];if(t.isFoundDocument())return new BF(this._firestore,r,t.key,t,n.converter);if(t.isNoDocument())return new BF(this._firestore,r,n._key,null,n.converter);throw ER()})}set(e,t,n){var r=dU(e,this._firestore),i=lU(r.converter,t,n),i=TF(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=dU(e,this._firestore),s="string"==typeof(t=Kd(t))||t instanceof dF?PF(this._dataReader,"Transaction.update",i._key,t,n,r):RF(this._dataReader,"Transaction.update",i._key,t);return this._transaction.update(i._key,s),this}delete(e){var t=dU(e,this._firestore);return this._transaction.delete(t._key),this}}{constructor(e,t){super(e,t),this._firestore=e}get(e){const t=dU(e,this._firestore),n=new fU(this._firestore);return super.get(e).then(e=>new WF(this._firestore,n,t._key,e._document,new zF(!1,!1),t.converter))}}function TU(t,n){return function(t,n){const r=new AR;return t.asyncQueue.enqueueAndForget(async()=>{var e=await IM(t).then(e=>e.datastore);new vM(t.asyncQueue,e,n,r).run()}),r.promise}(iF(t=jM(t,rF)),e=>n(new IU(t,e)))}W=mf,vR=W,df(new zd("firestore",(e,{options:t})=>{const n=e.getProvider("app").getImmediate(),r=new rF(n,new xR(e.getProvider("auth-internal")));return t=Object.assign({useFetchStreams:!0},t),r._setSettings(t),r},"PUBLIC")),wf(gR,"3.3.0",void 0),wf(gR,"3.3.0","esm2017");function EU(e,t){if(void 0===t)return{merge:!1};if(void 0!==t.mergeFields&&void 0!==t.merge)throw new CR("invalid-argument",`Invalid options passed to function ${e}(): You cannot `+'specify both "merge" and "mergeFields".');return t}function SU(){if("undefined"==typeof Uint8Array)throw new CR("unimplemented","Uint8Arrays are not available in this environment.")}function kU(){if("undefined"==typeof atob)throw new CR("unimplemented","Blobs are unavailable in Firestore in this environment.")}class CU{constructor(e){this._delegate=e}static fromBase64String(e){return kU(),new CU(fF.fromBase64String(e))}static fromUint8Array(e){return SU(),new CU(fF.fromUint8Array(e))}toBase64(){return kU(),this._delegate.toBase64()}toUint8Array(){return SU(),this._delegate.toUint8Array()}isEqual(e){return this._delegate.isEqual(e._delegate)}toString(){return"Blob(base64: "+this.toBase64()+")"}}function AU(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 NU{enableIndexedDbPersistence(e,t){return function(e,t){hF(e=jM(e,rF));var n=iF(e),r=e._freezeSettings(),i=new dM;return oF(n,i,new uM(i,r.cacheSizeBytes,null==t?void 0:t.forceOwnership))}(e._delegate,{forceOwnership:t})}enableMultiTabIndexedDbPersistence(e){return function(e){hF(e=jM(e,rF));var t=iF(e),n=e._freezeSettings(),r=new dM;return oF(t,r,new hM(r,n.cacheSizeBytes))}(e._delegate)}clearIndexedDbPersistence(e){return function(e){if(e._initialized&&!e._terminated)throw new CR(kR.FAILED_PRECONDITION,"Persistence can only be cleared before a Firestore instance is initialized or after it is terminated.");const t=new AR;return e._queue.enqueueAndForgetEvenWhileRestricted(async()=>{try{await async function(e){if(!ZO.bt())return Promise.resolve();var t=e+"main";await ZO.delete(t)}(u1(e._databaseId,e._persistenceKey)),t.resolve()}catch(e){t.reject(e)}}),t.promise}(e._delegate)}}class RU{constructor(e,t,n){this._delegate=t,this._persistenceProvider=n,this.INTERNAL={delete:()=>this.terminate()},e instanceof xM||(this._appCompat=e)}get _databaseId(){return this._delegate._databaseId}settings(e){var t=this._delegate._getSettings();e.merge||t.host===e.host||IR("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=jM(n,BM))._getSettings();if("firestore.googleapis.com"!==s.host&&s.host!==e&&IR("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=mR.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 CR(kR.INVALID_ARGUMENT,"mockUserToken must contain 'sub' or 'user_id' field!");t=new mR(s)}n._credentials=new PR(new NR(e,t))}}(this._delegate,e,t,n)}enableNetwork(){return cF(this._delegate)}disableNetwork(){return lF(this._delegate)}enablePersistence(e){let t=!1,n=!1;return e&&(t=!!e.synchronizeTabs,n=!!e.experimentalForceOwningTab,LM("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 aF(this._delegate)}onSnapshotsInSync(e){return _U(this._delegate,e)}get app(){if(!this._appCompat)throw new CR("failed-precondition","Firestore was not initialized using the Firebase SDK. 'app' is not available");return this._appCompat}collection(e){try{return new KU(this,WM(this._delegate,e))}catch(e){throw MU(e,"collection()","Firestore.collection()")}}doc(e){try{return new LU(this,HM(this._delegate,e))}catch(e){throw MU(e,"doc()","Firestore.doc()")}}collectionGroup(e){try{return new VU(this,function(e,t){if(e=jM(e,BM),DM("collectionGroup","collection id",t),0<=t.indexOf("/"))throw new CR(kR.INVALID_ARGUMENT,`Invalid collection ID '${t}' passed to function collectionGroup(). Collection IDs must not contain '/'.`);return new KM(e,null,(t=t,new VP(WR.emptyPath(),t)))}(this._delegate,e))}catch(e){throw MU(e,"collectionGroup()","Firestore.collectionGroup()")}}runTransaction(t){return TU(this._delegate,e=>t(new xU(this,e)))}batch(){return iF(this._delegate),new OU(new hU(this._delegate,e=>wU(this._delegate,e)))}loadBundle(e){return t=this._delegate,e=e,n=iF(t=jM(t,rF)),r=new XM,RM(n,t._databaseId,e,r),r;var t,n,r}namedQuery(e){return uF(this._delegate,e).then(e=>e?new VU(this,e):null)}}class PU extends cU{constructor(e){super(),this.firestore=e}convertBytes(e){return new CU(new fF(e))}convertReference(e){var t=this.convertDocumentKey(e,this.firestore._databaseId);return LU.forKey(t,this.firestore,null)}}class xU{constructor(e,t){this._firestore=e,this._delegate=t,this._userDataWriter=new PU(e)}get(e){const t=zU(e);return this._delegate.get(t).then(e=>new jU(this._firestore,new WF(this._firestore._delegate,this._userDataWriter,e._key,e._document,e.metadata,t.converter)))}set(e,t,n){var r=zU(e);return n?(EU("Transaction.set",n),this._delegate.set(r,t,n)):this._delegate.set(r,t),this}update(e,t,n,...r){var i=zU(e);return 2===arguments.length?this._delegate.update(i,t):this._delegate.update(i,t,n,...r),this}delete(e){var t=zU(e);return this._delegate.delete(t),this}}class OU{constructor(e){this._delegate=e}set(e,t,n){var r=zU(e);return n?(EU("WriteBatch.set",n),this._delegate.set(r,t,n)):this._delegate.set(r,t),this}update(e,t,n,...r){var i=zU(e);return 2===arguments.length?this._delegate.update(i,t):this._delegate.update(i,t,n,...r),this}delete(e){var t=zU(e);return this._delegate.delete(t),this}commit(){return this._delegate.commit()}}class DU{constructor(e,t,n){this._firestore=e,this._userDataWriter=t,this._delegate=n}fromFirestore(e,t){var n=new HF(this._firestore._delegate,this._userDataWriter,e._key,e._document,e.metadata,null);return this._delegate.fromFirestore(new qU(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=DU.INSTANCES;let r=n.get(e);r||(r=new WeakMap,n.set(e,r));let i=r.get(t);return i||(i=new DU(e,new PU(e),t),r.set(t,i)),i}}DU.INSTANCES=new WeakMap;class LU{constructor(e,t){this.firestore=e,this._delegate=t,this._userDataWriter=new PU(e)}static forPath(e,t,n){if(e.length%2!=0)throw new CR("invalid-argument","Invalid document reference. Document references must have an even number of segments, but "+`${e.canonicalString()} has ${e.length}`);return new LU(t,new $M(t._delegate,n,new oP(e)))}static forKey(e,t,n){return new LU(t,new $M(t._delegate,n,e))}get id(){return this._delegate.id}get parent(){return new KU(this.firestore,this._delegate.parent)}get path(){return this._delegate.path}collection(e){try{return new KU(this.firestore,WM(this._delegate,e))}catch(e){throw MU(e,"collection()","DocumentReference.collection()")}}isEqual(e){return(e=Kd(e))instanceof $M&&GM(this._delegate,e)}set(e,t){t=EU("DocumentReference.set",t);try{return t?mU(this._delegate,e,t):mU(this._delegate,e)}catch(e){throw MU(e,"setDoc()","DocumentReference.set()")}}update(e,t,...n){try{return 1===arguments.length?vU(this._delegate,e):vU(this._delegate,e,t,...n)}catch(e){throw MU(e,"updateDoc()","DocumentReference.update()")}}delete(){return wU(jM((e=this._delegate).firestore,rF),[new Rx(e._key,yx.none())]);var e}onSnapshot(...e){var t=FU(e),n=UU(e,e=>new jU(this.firestore,new WF(this.firestore._delegate,this._userDataWriter,e._key,e._document,e.metadata,this._delegate.converter)));return yU(this._delegate,t,n)}get(e){let t;return t=("cache"===(null==e?void 0:e.source)?pU:"server"===(null==e?void 0:e.source)?function(t){t=jM(t,$M);const n=jM(t.firestore,rF);return AM(iF(n),t._key,{source:"server"}).then(e=>bU(n,t,e))}:function(t){t=jM(t,$M);const n=jM(t.firestore,rF);return AM(iF(n),t._key).then(e=>bU(n,t,e))})(this._delegate),t.then(e=>new jU(this.firestore,new WF(this.firestore._delegate,this._userDataWriter,e._key,e._document,e.metadata,this._delegate.converter)))}withConverter(e){return new LU(this.firestore,e?this._delegate.withConverter(DU.getInstance(this.firestore,e)):this._delegate.withConverter(null))}}function MU(e,t,n){return e.message=e.message.replace(t,n),e}function FU(e){for(const t of e)if("object"==typeof t&&!AU(t))return t;return{}}function UU(e,t){var n;let r;return r=AU(e[0])?e[0]:AU(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 jU{constructor(e,t){this._firestore=e,this._delegate=t}get ref(){return new LU(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 QF(this._delegate,e._delegate)}}class qU extends jU{data(e){var t=this._delegate.data(e);return void 0!==t||ER(),t}}class VU{constructor(e,t){this.firestore=e,this._delegate=t,this._userDataWriter=new PU(e)}where(e,t,n){try{return new VU(this.firestore,XF(this._delegate,(r=n,i=t,s=KF("where",e),new ZF(s,i,r))))}catch(e){throw MU(e,/(orderBy|where)\(\)/,"Query.$1()")}var r,i,s}orderBy(e,t){try{return new VU(this.firestore,XF(this._delegate,([n,r="asc"]=[e,t],i=r,s=KF("orderBy",n),new eU(s,i))))}catch(e){throw MU(e,/(orderBy|where)\(\)/,"Query.$1()")}var n,r,i,s}limit(e){try{return new VU(this.firestore,XF(this._delegate,(qM("limit",t=e),new tU("limit",t,"F"))))}catch(e){throw MU(e,"limit()","Query.limit()")}var t}limitToLast(e){try{return new VU(this.firestore,XF(this._delegate,(qM("limitToLast",t=e),new tU("limitToLast",t,"L"))))}catch(e){throw MU(e,"limitToLast()","Query.limitToLast()")}var t}startAt(...e){try{return new VU(this.firestore,XF(this._delegate,function(...e){return new nU("startAt",e,!0)}(...e)))}catch(e){throw MU(e,"startAt()","Query.startAt()")}}startAfter(...e){try{return new VU(this.firestore,XF(this._delegate,function(...e){return new nU("startAfter",e,!1)}(...e)))}catch(e){throw MU(e,"startAfter()","Query.startAfter()")}}endBefore(...e){try{return new VU(this.firestore,XF(this._delegate,function(...e){return new rU("endBefore",e,!0)}(...e)))}catch(e){throw MU(e,"endBefore()","Query.endBefore()")}}endAt(...e){try{return new VU(this.firestore,XF(this._delegate,function(...e){return new rU("endAt",e,!1)}(...e)))}catch(e){throw MU(e,"endAt()","Query.endAt()")}}isEqual(e){return QM(this._delegate,e._delegate)}get(e){let t;return t=("cache"===(null==e?void 0:e.source)?gU:"server"===(null==e?void 0:e.source)?function(t){t=jM(t,KM);const n=jM(t.firestore,rF),e=iF(n),r=new fU(n);return NM(e,t._query,{source:"server"}).then(e=>new GF(n,r,t,e))}:function(t){t=jM(t,KM);const n=jM(t.firestore,rF),e=iF(n),r=new fU(n);return YF(t._query),NM(e,t._query).then(e=>new GF(n,r,t,e))})(this._delegate),t.then(e=>new $U(this.firestore,new GF(this.firestore._delegate,this._userDataWriter,this._delegate,e._snapshot)))}onSnapshot(...e){var t=FU(e),n=UU(e,e=>new $U(this.firestore,new GF(this.firestore._delegate,this._userDataWriter,this._delegate,e._snapshot)));return yU(this._delegate,t,n)}withConverter(e){return new VU(this.firestore,e?this._delegate.withConverter(DU.getInstance(this.firestore,e)):this._delegate.withConverter(null))}}class BU{constructor(e,t){this._firestore=e,this._delegate=t}get type(){return this._delegate.type}get doc(){return new qU(this._firestore,this._delegate.doc)}get oldIndex(){return this._delegate.oldIndex}get newIndex(){return this._delegate.newIndex}}class $U{constructor(e,t){this._firestore=e,this._delegate=t}get query(){return new VU(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 qU(this._firestore,e))}docChanges(e){return this._delegate.docChanges(e).map(e=>new BU(this._firestore,e))}forEach(t,n){this._delegate.forEach(e=>{t.call(n,new qU(this._firestore,e))})}isEqual(e){return QF(this._delegate,e._delegate)}}class KU extends VU{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 LU(this.firestore,e):null}doc(e){try{return void 0===e?new LU(this.firestore,HM(this._delegate)):new LU(this.firestore,HM(this._delegate,e))}catch(e){throw MU(e,"doc()","CollectionReference.doc()")}}add(e){return function(e,t){const n=jM(e.firestore,rF),r=HM(e),i=lU(e.converter,t);return wU(n,[TF(IF(e.firestore),"addDoc",r._key,i,null!==e.converter,{}).toMutation(r._key,yx.exists(!1))]).then(()=>r)}(this._delegate,e).then(e=>new LU(this.firestore,e))}isEqual(e){return GM(this._delegate,e._delegate)}withConverter(e){return new KU(this.firestore,e?this._delegate.withConverter(DU.getInstance(this.firestore,e)):this._delegate.withConverter(null))}}function zU(e){return jM(e,$M)}const WU={Firestore:RU,GeoPoint:gF,Timestamp:qR,Blob:CU,Transaction:xU,WriteBatch:OU,DocumentReference:LU,DocumentSnapshot:jU,Query:VU,QueryDocumentSnapshot:qU,QuerySnapshot:$U,CollectionReference:KU,FieldPath:class K${constructor(...e){this._delegate=new dF(...e)}static documentId(){return new K$(GR.keyField().canonicalString())}isEqual(e){return(e=Kd(e))instanceof dF&&this._delegate._internalPath.isEqual(e._internalPath)}},FieldValue:class z${constructor(e){this._delegate=e}static serverTimestamp(){const e=new kF("serverTimestamp");return e._methodName="FieldValue.serverTimestamp",new z$(e)}static delete(){const e=new EF("deleteField");return e._methodName="FieldValue.delete",new z$(e)}static arrayUnion(...e){const t=function(...e){return new CF("arrayUnion",e)}(...e);return t._methodName="FieldValue.arrayUnion",new z$(t)}static arrayRemove(...e){const t=function(...e){return new AF("arrayRemove",e)}(...e);return t._methodName="FieldValue.arrayRemove",new z$(t)}static increment(e){const t=new NF("increment",e);return t._methodName="FieldValue.increment",new z$(t)}isEqual(e){return this._delegate.isEqual(e._delegate)}},setLogLevel:function(e){e=e,yR.setLogLevel(e)},CACHE_SIZE_UNLIMITED:-1};ZM=Af,eF=(e,t)=>new RU(e,t,new NU),ZM.INTERNAL.registerComponent(new zd("firestore-compat",e=>{var t=e.getProvider("app-compat").getImmediate(),n=e.getProvider("firestore").getImmediate();return eF(t,n)},"PUBLIC").setServiceProps(Object.assign({},WU))),ZM.registerVersion("@firebase/firestore-compat","0.1.7");function HU(e,t){const n={};for(const r in e)e.hasOwnProperty(r)&&(n[r]=t(e[r]));return n}function GU(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=>GU(e)):"function"==typeof e||"object"==typeof e?HU(e,e=>GU(e)):e}const QU="functions",YU={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 JU extends gd{constructor(e,t,n){super(`${QU}/${e}`,t||""),this.details=n}}function XU(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(!YU[e])return new JU("internal","internal");n=YU[e],r=e}var o=s.message;"string"==typeof o&&(r=o),i=s.details,void 0!==i&&(i=GU(i))}}catch(e){}return"ok"===n?null:new JU(n,r,i)}class ZU{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 ej="us-central1";class tj{constructor(e,t,n,r,i=ej,s){this.app=e,this.fetchImpl=s,this.emulatorOrigin=null,this.contextProvider=new ZU(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=ej}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 nj(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 HU(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 JU("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 JU("cancelled","Firebase Functions instance was deleted.");var h=XU(u.status,u.json);if(h)throw h;if(!u.json)throw new JU("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 JU("internal","Response is missing data field.");h=GU(d);return{data:h}}(t,n,e,r||{})}const rj="@firebase/functions";function ij(e,t,n){Kd(e).emulatorOrigin=`http://${t}:${n}`}tF=fetch.bind(self),df(new zd(QU,(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 tj(n,r,i,s,t,tF)},"PUBLIC").setMultipleInstances(!0)),wf(rj,"0.7.6",nF),wf(rj,"0.7.6","esm2017");var sj,oj,aj,cj;class lj{constructor(e,t){this.app=e,this._delegate=t,this._region=this._delegate.region,this._customDomain=this._delegate.customDomain}httpsCallable(e,t){return nj(Kd(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 ij(this._delegate,t[1],Number(t[2]))}useEmulator(e,t){return ij(this._delegate,e,t)}}const uj="us-central1",hj=(e,{instanceIdentifier:t})=>{var n=e.getProvider("app-compat").getImmediate(),r=e.getProvider("functions").getImmediate({identifier:null!=t?t:uj});return new lj(n,r)};sj={Functions:lj},Af.INTERNAL.registerComponent(new zd("functions-compat",hj,"PUBLIC").setServiceProps(sj).setMultipleInstances(!0)),Af.registerVersion("@firebase/functions-compat","0.1.7");const dj="/firebase-messaging-sw.js",fj="/firebase-cloud-messaging-push-scope",pj="BDOU99-h67HcA6JeFXHbSNMu7e2yNNu3RzoMj8TM4W88jITfq7ZmPvIM1Iv-4_l2LxQcYwhqby2xGpWwzjfAnG4",gj="https://fcmregistrations.googleapis.com/v1",mj="google.c.a.c_id",vj="google.c.a.e";function yj(e){var t=new Uint8Array(e);const n=btoa(String.fromCharCode(...t));return n.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}(yt=kB=kB||{})[yt.DATA_MESSAGE=1]="DATA_MESSAGE",yt[yt.DISPLAY_NOTIFICATION=3]="DISPLAY_NOTIFICATION",(yt=oj=oj||{}).PUSH_RECEIVED="push-received",yt.NOTIFICATION_CLICKED="notification-clicked";const _j="fcm_token_details_db",wj="fcm_token_object_Store";async function bj(s){if("databases"in indexedDB){const t=await indexedDB.databases(),n=t.map(e=>e.name);if(!n.includes(_j))return null}let o=null;const e=await Vf(_j,5,async e=>{var t;if(!(e.oldVersion<2)&&e.objectStoreNames.contains(wj)){const i=e.transaction.objectStore(wj);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:yj(n.vapidKey)}}):3===e.oldVersion?(n=r,o={token:n.fcmToken,createTime:n.createTime,subscriptionOptions:{auth:yj(n.auth),p256dh:yj(n.p256dh),endpoint:n.endpoint,swScope:n.swScope,vapidKey:yj(n.vapidKey)}}):4===e.oldVersion&&(r=r,o={token:r.fcmToken,createTime:r.createTime,subscriptionOptions:{auth:yj(r.auth),p256dh:yj(r.p256dh),endpoint:r.endpoint,swScope:r.swScope,vapidKey:yj(r.vapidKey)}}))}});return e.close(),await Bf(_j),await Bf("fcm_vapid_details_db"),await Bf("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 Ij="firebase-messaging-database",Tj=1,Ej="firebase-messaging-store";let Sj=null;function kj(){return Sj=Sj||Vf(Ij,Tj,e=>{0===e.oldVersion&&e.createObjectStore(Ej)}),Sj}async function Cj(e){var t=Nj(e);const n=await kj();t=await n.transaction(Ej).objectStore(Ej).get(t);if(t)return t;t=await bj(e.appConfig.senderId);return t?(await Aj(e,t),t):void 0}async function Aj(e,t){var n=Nj(e);const r=await kj(),i=r.transaction(Ej,"readwrite");return await i.objectStore(Ej).put(t,n),await i.complete,t}function Nj({appConfig:e}){return e.appId}const Rj=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 Pj(e,t){var n={method:"DELETE",headers:await Oj(e)};try{const s=await fetch(`${xj(e.appConfig)}/${t}`,n);var r=await s.json();if(r.error){var i=r.error.message;throw Rj.create("token-unsubscribe-failed",{errorInfo:i})}}catch(e){throw Rj.create("token-unsubscribe-failed",{errorInfo:e})}}function xj({projectId:e}){return`${gj}/projects/${e}/registrations`}async function Oj({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 Dj({p256dh:e,auth:t,endpoint:n,vapidKey:r}){const i={web:{endpoint:n,auth:t,p256dh:e}};return r!==pj&&(i.web.applicationPubKey=r),i}const Lj=6048e5;async function Mj(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:yj(t.getKey("auth")),p256dh:yj(t.getKey("p256dh"))},c=await Cj(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+Lj?async function(t,e){try{var n=await async function(e,t){var n=await Oj(e),r=Dj(t.subscriptionOptions),r={method:"PATCH",headers:n,body:JSON.stringify(r)};let i;try{const s=await fetch(`${xj(e.appConfig)}/${t.token}`,r);i=await s.json()}catch(e){throw Rj.create("token-update-failed",{errorInfo:e})}if(i.error){r=i.error.message;throw Rj.create("token-update-failed",{errorInfo:r})}if(!i.token)throw Rj.create("token-update-no-token");return i.token}(t.firebaseDependencies,e),r=Object.assign(Object.assign({},e),{token:n,createTime:Date.now()});return await Aj(t.firebaseDependencies,r),n}catch(e){throw await Fj(t),e}}(e,{token:c.token,createTime:Date.now(),subscriptionOptions:a}):c.token;try{await Pj(e.firebaseDependencies,c.token)}catch(e){console.warn(e)}return Uj(e.firebaseDependencies,a)}return Uj(e.firebaseDependencies,a)}async function Fj(e){var t=await Cj(e.firebaseDependencies);t&&(await Pj(e.firebaseDependencies,t.token),await async function(e){var t=Nj(e);const n=await kj(),r=n.transaction(Ej,"readwrite");await r.objectStore(Ej).delete(t),await r.complete}(e.firebaseDependencies));const n=await e.swRegistration.pushManager.getSubscription();return!n||n.unsubscribe()}async function Uj(e,t){var n={token:await async function(e,t){var n=await Oj(e),r=Dj(t),r={method:"POST",headers:n,body:JSON.stringify(r)};let i;try{const s=await fetch(xj(e.appConfig),r);i=await s.json()}catch(e){throw Rj.create("token-subscribe-failed",{errorInfo:e})}if(i.error){r=i.error.message;throw Rj.create("token-subscribe-failed",{errorInfo:r})}if(!i.token)throw Rj.create("token-subscribe-no-token");return i.token}(e,t),createTime:Date.now(),subscriptionOptions:t};return await Aj(e,n),n.token}function jj(e){var t,n,r,i={from:e.from,collapseKey:e.collapse_key,messageId:e.fcm_message_id};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 qj(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 Vj(e){return Rj.create("missing-app-config-values",{valueName:e})}qj("hts/frbslgigp.ogepscmv/ieo/eaylg","tp:/ieaeogn-agolai.o/1frlglgc/o"),qj("AzSCbw63g1R0nCw85jG8","Iaya3yLKwmgvh7cF0q4");class Bj{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 Vj("App Configuration Object");if(!e.name)throw Vj("App Name");var t=e["options"];for(const n of["projectId","apiKey","appId","messagingSenderId"])if(!t[n])throw Vj(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 $j(e){try{e.swRegistration=await navigator.serviceWorker.register(dj,{scope:fj}),e.swRegistration.update().catch(()=>{})}catch(e){throw Rj.create("failed-service-worker-registration",{browserErrorMessage:e.message})}}async function Kj(e,t){if(!navigator)throw Rj.create("only-available-in-window");if("default"===Notification.permission&&await Notification.requestPermission(),"granted"!==Notification.permission)throw Rj.create("permission-blocked");var n,r;return n=e,await((r=null==t?void 0:t.vapidKey)?n.vapidKey=r:n.vapidKey||(n.vapidKey=pj)),await async function(e,t){if(t||e.swRegistration||await $j(e),t||!e.swRegistration){if(!(t instanceof ServiceWorkerRegistration))throw Rj.create("invalid-sw-registration");e.swRegistration=t}}(e,null==t?void 0:t.serviceWorkerRegistration),Mj(e)}async function zj(e,t,n){var r=function(e){switch(e){case oj.NOTIFICATION_CLICKED:return"notification_open";case oj.PUSH_RECEIVED:return"notification_foreground";default:throw new Error}}(t);const i=await e.firebaseDependencies.analyticsProvider.get();i.logEvent(r,{message_id:n[mj],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 Wj(e,t){var n,r=t.data;r.isFirebaseMessaging&&(e.onMessageHandler&&r.messageType===oj.PUSH_RECEIVED&&("function"==typeof e.onMessageHandler?e.onMessageHandler(jj(r)):e.onMessageHandler.next(jj(r))),n=r.data,"object"==typeof(t=n)&&t&&mj in t&&"1"===n[vj]&&await zj(e,r.messageType,n))}const Hj="@firebase/messaging",Gj=e=>{const t=new Bj(e.getProvider("app").getImmediate(),e.getProvider("installations-internal").getImmediate(),e.getProvider("analytics-internal"));return navigator.serviceWorker.addEventListener("message",e=>Wj(t,e)),t},Qj=e=>{const t=e.getProvider("messaging").getImmediate();return{getToken:e=>Kj(t,e)}};function Yj(e){return async function(e){if(!navigator)throw Rj.create("only-available-in-window");return e.swRegistration||await $j(e),Fj(e)}(e=Kd(e))}function Jj(e,t){return function(e,t){if(!navigator)throw Rj.create("only-available-in-window");return e.onMessageHandler=t,()=>{e.onMessageHandler=null}}(e=Kd(e),t)}df(new zd("messaging",Gj,"PUBLIC")),df(new zd("messaging-internal",Qj,"PRIVATE")),wf(Hj,"0.9.4"),wf(Hj,"0.9.4","esm2017");const Xj="BDOU99-h67HcA6JeFXHbSNMu7e2yNNu3RzoMj8TM4W88jITfq7ZmPvIM1Iv-4_l2LxQcYwhqby2xGpWwzjfAnG4",Zj="https://fcmregistrations.googleapis.com/v1",eq="FCM_MSG",tq="google.c.a.c_id",nq=3,rq=1;function iq(e){var t=new Uint8Array(e);const n=btoa(String.fromCharCode(...t));return n.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}(yt=aj=aj||{})[yt.DATA_MESSAGE=1]="DATA_MESSAGE",yt[yt.DISPLAY_NOTIFICATION=3]="DISPLAY_NOTIFICATION",(c=cj=cj||{}).PUSH_RECEIVED="push-received",c.NOTIFICATION_CLICKED="notification-clicked";const sq="fcm_token_details_db",oq="fcm_token_object_Store";async function aq(s){if("databases"in indexedDB){const t=await indexedDB.databases(),n=t.map(e=>e.name);if(!n.includes(sq))return null}let o=null;const e=await Vf(sq,5,async e=>{var t;if(!(e.oldVersion<2)&&e.objectStoreNames.contains(oq)){const i=e.transaction.objectStore(oq);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:iq(n.vapidKey)}}):3===e.oldVersion?(n=r,o={token:n.fcmToken,createTime:n.createTime,subscriptionOptions:{auth:iq(n.auth),p256dh:iq(n.p256dh),endpoint:n.endpoint,swScope:n.swScope,vapidKey:iq(n.vapidKey)}}):4===e.oldVersion&&(r=r,o={token:r.fcmToken,createTime:r.createTime,subscriptionOptions:{auth:iq(r.auth),p256dh:iq(r.p256dh),endpoint:r.endpoint,swScope:r.swScope,vapidKey:iq(r.vapidKey)}}))}});return e.close(),await Bf(sq),await Bf("fcm_vapid_details_db"),await Bf("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 cq="firebase-messaging-database",lq=1,uq="firebase-messaging-store";let hq=null;function dq(){return hq=hq||Vf(cq,lq,e=>{0===e.oldVersion&&e.createObjectStore(uq)}),hq}async function fq(e){var t=gq(e);const n=await dq();t=await n.transaction(uq).objectStore(uq).get(t);if(t)return t;t=await aq(e.appConfig.senderId);return t?(await pq(e,t),t):void 0}async function pq(e,t){var n=gq(e);const r=await dq(),i=r.transaction(uq,"readwrite");return await i.objectStore(uq).put(t,n),await i.complete,t}function gq({appConfig:e}){return e.appId}const mq=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 vq(e,t){var n={method:"DELETE",headers:await _q(e)};try{const s=await fetch(`${yq(e.appConfig)}/${t}`,n);var r=await s.json();if(r.error){var i=r.error.message;throw mq.create("token-unsubscribe-failed",{errorInfo:i})}}catch(e){throw mq.create("token-unsubscribe-failed",{errorInfo:e})}}function yq({projectId:e}){return`${Zj}/projects/${e}/registrations`}async function _q({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 wq({p256dh:e,auth:t,endpoint:n,vapidKey:r}){const i={web:{endpoint:n,auth:t,p256dh:e}};return r!==Xj&&(i.web.applicationPubKey=r),i}async function bq(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:iq(t.getKey("auth")),p256dh:iq(t.getKey("p256dh"))},c=await fq(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 _q(e),r=wq(t.subscriptionOptions),r={method:"PATCH",headers:n,body:JSON.stringify(r)};let i;try{const s=await fetch(`${yq(e.appConfig)}/${t.token}`,r);i=await s.json()}catch(e){throw mq.create("token-update-failed",{errorInfo:e})}if(i.error){r=i.error.message;throw mq.create("token-update-failed",{errorInfo:r})}if(!i.token)throw mq.create("token-update-no-token");return i.token}(t.firebaseDependencies,e),r=Object.assign(Object.assign({},e),{token:n,createTime:Date.now()});return await pq(t.firebaseDependencies,r),n}catch(e){throw await Iq(t),e}}(e,{token:c.token,createTime:Date.now(),subscriptionOptions:a}):c.token;try{await vq(e.firebaseDependencies,c.token)}catch(e){console.warn(e)}return Tq(e.firebaseDependencies,a)}return Tq(e.firebaseDependencies,a)}async function Iq(e){var t=await fq(e.firebaseDependencies);t&&(await vq(e.firebaseDependencies,t.token),await async function(e){var t=gq(e);const n=await dq(),r=n.transaction(uq,"readwrite");await r.objectStore(uq).delete(t),await r.complete}(e.firebaseDependencies));const n=await e.swRegistration.pushManager.getSubscription();return!n||n.unsubscribe()}async function Tq(e,t){var n={token:await async function(e,t){var n=await _q(e),r=wq(t),r={method:"POST",headers:n,body:JSON.stringify(r)};let i;try{const s=await fetch(yq(e.appConfig),r);i=await s.json()}catch(e){throw mq.create("token-subscribe-failed",{errorInfo:e})}if(i.error){r=i.error.message;throw mq.create("token-subscribe-failed",{errorInfo:r})}if(!i.token)throw mq.create("token-subscribe-no-token");return i.token}(e,t),createTime:Date.now(),subscriptionOptions:t};return await pq(e,n),n.token}async function Eq(e,t){var n=function(e,t){var n;const r={};e.from&&(r.project_number=e.from);e.fcm_message_id&&(r.message_id=e.fcm_message_id);r.instance_id=t,e.notification?r.message_type=aj.DISPLAY_NOTIFICATION.toString():r.message_type=aj.DATA_MESSAGE.toString();r.sdk_platform=nq.toString(),r.package_name=self.origin.replace(/(^\w+:|^)\/\//,""),e.collapse_key&&(r.collapse_key=e.collapse_key);r.event=rq.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 Sq(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 kq(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 Eq(t,n);var r,i,s=await Aq();if(s.some(e=>"visible"===e.visibilityState&&!e.url.startsWith("chrome-extension://")))return function(e,t){t.isFirebaseMessaging=!0,t.messageType=cj.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={[eq]:e},t}(n)),t&&t.onBackgroundMessageHandler&&(s={from:(r=n).from,collapseKey:r.collapse_key,messageId:r.fcm_message_id},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 Cq(e){const t=null===(s=null===(i=e.notification)||void 0===i?void 0:i.data)||void 0===s?void 0:s[eq];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&&tq 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 Aq();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=cj.NOTIFICATION_CLICKED,t.isFirebaseMessaging=!0,e.postMessage(t)}}}}function Aq(){return self.clients.matchAll({type:"window",includeUncontrolled:!0})}function Nq(e){return mq.create("missing-app-config-values",{valueName:e})}Sq("hts/frbslgigp.ogepscmv/ieo/eaylg","tp:/ieaeogn-agolai.o/1frlglgc/o"),Sq("AzSCbw63g1R0nCw85jG8","Iaya3yLKwmgvh7cF0q4");class Rq{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 Nq("App Configuration Object");if(!e.name)throw Nq("App Name");var t=e["options"];for(const n of["projectId","apiKey","appId","messagingSenderId"])if(!t[n])throw Nq(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 Pq=e=>{const t=new Rq(e.getProvider("app").getImmediate(),e.getProvider("installations-internal").getImmediate(),e.getProvider("analytics-internal"));return self.addEventListener("push",e=>{e.waitUntil(kq(e,t))}),self.addEventListener("pushsubscriptionchange",e=>{e.waitUntil(async function(e,t){var n;(n=e["newSubscription"])?(n=await fq(t.firebaseDependencies),await Iq(t),t.vapidKey=null!==(n=null===(n=null==n?void 0:n.subscriptionOptions)||void 0===n?void 0:n.vapidKey)&&void 0!==n?n:Xj,await bq(t)):await Iq(t)}(e,t))}),self.addEventListener("notificationclick",e=>{e.waitUntil(Cq(e))}),t};function xq(e,t){return function(e,t){if(void 0!==self.document)throw mq.create("only-available-in-sw");return e.onBackgroundMessageHandler=t,()=>{e.onBackgroundMessageHandler=null}}(e=Kd(e),t)}df(new zd("messaging-sw",Pq,"PUBLIC"));var Oq,Dq,Lq;class Mq{constructor(e,t){this.app=e,this._delegate=t,this.app=e,this._delegate=t}async getToken(e){return async function(e,t){return Kj(e=Kd(e),t)}(this._delegate,e)}async deleteToken(){return Yj(this._delegate)}onMessage(e){return Jj(this._delegate,e)}onBackgroundMessage(e){return xq(this._delegate,e)}}const Fq=e=>self&&"ServiceWorkerGlobalScope"in self?new Mq(e.getProvider("app-compat").getImmediate(),e.getProvider("messaging-sw").getImmediate()):new Mq(e.getProvider("app-compat").getImmediate(),e.getProvider("messaging").getImmediate()),Uq={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()&&pd()&&"serviceWorker"in navigator&&"PushManager"in window&&"Notification"in window&&"fetch"in window&&ServiceWorkerRegistration.prototype.hasOwnProperty("showNotification")&&PushSubscription.prototype.hasOwnProperty("getKey")}};Af.INTERNAL.registerComponent(new zd("messaging-compat",Fq,"PUBLIC").setServiceProps(Uq)),Af.registerVersion("@firebase/messaging-compat","0.1.4");const jq="firebasestorage.googleapis.com",qq="storageBucket";class Vq extends gd{constructor(e,t){super(Bq(e),`Firebase Storage: ${t} (${Bq(e)})`),this.customData={serverResponse:null},this._baseMessage=this.message,Object.setPrototypeOf(this,Vq.prototype)}_codeEquals(e){return Bq(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 Bq(e){return"storage/"+e}function $q(){return new Vq("unknown","An unknown error occurred, please check the error payload for server response.")}function Kq(){return new Vq("canceled","User canceled the upload/download.")}function zq(){return new Vq("cannot-slice-blob","Cannot slice blob for upload. Please retry the upload.")}function Wq(e){return new Vq("invalid-argument",e)}function Hq(){return new Vq("app-deleted","The Firebase app was deleted.")}function Gq(e){return new Vq("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 Qq(e,t){return new Vq("invalid-format","String does not match format '"+e+"': "+t)}function Yq(e){throw new Vq("internal-error","Internal error: "+e)}class Jq{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=Jq.makeFromUrl(t,e)}catch(e){return new Jq(t,"")}if(""===n.path)return n;throw t=t,new Vq("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===jq?"(?: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 Jq(u,e),d.postModify(n);break}}if(null==n)throw t=e,new Vq("invalid-url","Invalid URL '"+t+"'.");return n}}class Xq{constructor(e){this.promise_=Promise.reject(e)}getPromise(){return this.promise_}cancel(e=0){}}function Zq(e){return"string"==typeof e||e instanceof String}function eV(e){return tV()&&e instanceof Blob}function tV(){return"undefined"!=typeof Blob}function nV(e,t,n,r){if(r<t)throw Wq(`Invalid value for '${e}'. Expected ${t} or greater.`);if(n<r)throw Wq(`Invalid value for '${e}'. Expected ${n} or less.`)}function rV(e,t,n){let r=null==n?`https://${t}`:t;return`${n}://${r}/v0${e}`}function iV(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=Oq=Oq||{})[c.NO_ERROR=0]="NO_ERROR",c[c.NETWORK_ERROR=1]="NETWORK_ERROR",c[c.ABORT=2]="ABORT";class sV{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 oV(!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()===Oq.NO_ERROR,n=i.getStatus();t&&!this.isRetryStatusCode_(n)?(e=-1!==this.successCodes_.indexOf(n),r(!0,new oV(e,i))):(e=i.getErrorCode()===Oq.ABORT,r(!1,new oV(!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.getResponseText());void 0!==s?n(s):n()}catch(e){r(e)}else if(null!==i){const a=$q();a.serverResponse=i.getResponseText(),this.errorCallback_?r(this.errorCallback_(i,a)):r(a)}else{var o;t.canceled?(o=(this.appDelete_?Hq:Kq)(),r(o)):(o=new Vq("retry-limit-exceeded","Max retry time for operation exceeded, please try again."),r(o))}};this.canceled_?t(0,new oV(!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(f,c())},e)}function d(){s&&clearTimeout(s)}function f(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 p=!1;function g(e){p||(p=!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 oV{constructor(e,t,n){this.wasSuccessCode=e,this.connection=t,this.canceled=!!n}}function aV(...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(tV())return new Blob(t);throw new Vq("unsupported-environment","This browser doesn't seem to support creating Blobs")}const cV={RAW:"raw",BASE64:"base64",BASE64URL:"base64url",DATA_URL:"data_url"};class lV{constructor(e,t){this.data=e,this.contentType=t||null}}function uV(e,t){switch(e){case cV.RAW:return new lV(hV(t));case cV.BASE64:case cV.BASE64URL:return new lV(dV(e,t));case cV.DATA_URL:return new lV((n=t,(r=new fV(n)).base64?dV(cV.BASE64,r.rest):function(e){let t;try{t=decodeURIComponent(e)}catch(e){throw Qq(cV.DATA_URL,"Malformed data URL.")}return hV(t)}(r.rest)),(n=t,new fV(n).contentType))}var n,r;throw $q()}function hV(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 dV(t,e){switch(t){case cV.BASE64:var n=-1!==e.indexOf("-"),r=-1!==e.indexOf("_");if(n||r)throw Qq(t,"Invalid character '"+(n?"-":"_")+"' found: is it base64url encoded?");break;case cV.BASE64URL:r=-1!==e.indexOf("+"),n=-1!==e.indexOf("/");if(r||n)throw Qq(t,"Invalid character '"+(r?"+":"/")+"' found: is it base64 encoded?");e=e.replace(/-/g,"+").replace(/_/g,"/")}let i;try{i=atob(e)}catch(e){throw Qq(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 fV{constructor(e){this.base64=!1,this.contentType=null;var t,n,r=e.match(/^data:([^,]+)?,/);if(null===r)throw Qq(cV.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 pV{constructor(e,t){let n=0,r="";eV(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(eV(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 pV(n)}var r,i,s,n=new Uint8Array(this.data_.buffer,e,t-e);return new pV(n,!0)}static getBlob(...e){if(tV()){var t=e.map(e=>e instanceof pV?e.data_:e);return new pV(aV.apply(null,t))}{const r=e.map(e=>Zq(e)?uV(cV.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 pV(i,!0)}}uploadData(){return this.data_}}function gV(e){let t;try{t=JSON.parse(e)}catch(e){return null}return"object"!=typeof(e=t)||Array.isArray(e)?null:t}function mV(e){var t=e.lastIndexOf("/",e.length-2);return-1===t?e:e.slice(t+1)}function vV(e,t){return t}class yV{constructor(e,t,n,r){this.server=e,this.local=t||e,this.writable=!!n,this.xform=r||vV}}let _V=null;function wV(){if(_V)return _V;const e=[];e.push(new yV("bucket")),e.push(new yV("generation")),e.push(new yV("metageneration")),e.push(new yV("name","fullPath",!0));const t=new yV("name");t.xform=function(e,t){return!Zq(t=t)||t.length<2?t:mV(t)},e.push(t);const n=new yV("size");return n.xform=function(e,t){return void 0!==t?Number(t):t},e.push(n),e.push(new yV("timeCreated")),e.push(new yV("updated")),e.push(new yV("md5Hash",null,!0)),e.push(new yV("cacheControl",null,!0)),e.push(new yV("contentDisposition",null,!0)),e.push(new yV("contentEncoding",null,!0)),e.push(new yV("contentLanguage",null,!0)),e.push(new yV("contentType",null,!0)),e.push(new yV("metadata","customMetadata",!0)),_V=e,_V}function bV(n,r){Object.defineProperty(n,"ref",{get:function(){var e=n.bucket,t=n.fullPath,t=new Jq(e,t);return r._makeStorageReference(t)}})}function IV(e,t,n){var r=gV(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 bV(r,e),r}(e,r,n)}function TV(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 EV(e,t,n){var r=gV(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 Jq(t,i));r.prefixes.push(i)}if(n.items)for(const a of n.items){var s=e._makeStorageReference(new Jq(t,a.name));r.items.push(s)}return r}(e,t,r)}class SV{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 kV(e){if(!e)throw $q()}function CV(r,i){return function(e,t){var n=IV(r,t,i);return kV(null!==n),n}}function AV(r,i){return function(e,t){var n=EV(r,i,t);return kV(null!==n),n}}function NV(r,i){return function(e,t){var n=IV(r,t,i);return kV(null!==n),function(r,e,i,s){var t=gV(e);if(null===t)return null;if(!Zq(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 rV("/b/"+o(t)+"/o/"+o(n),i,s)+iV({alt:"media",token:e})})[0]}(n,t,r.host,r._protocol)}}function RV(i){return function(e,t){let n;var r;return n=401===e.getStatus()?e.getResponseText().includes("Firebase App Check token is invalid")?new Vq("unauthorized-app","This app does not have permission to access Firebase Storage on this project."):new Vq("unauthenticated","User is not authenticated, please authenticate using Firebase Authentication and try again."):402===e.getStatus()?(r=i.bucket,new Vq("quota-exceeded","Quota for bucket '"+r+"' exceeded, please view quota on https://firebase.google.com/pricing/.")):403===e.getStatus()?(e=i.path,new Vq("unauthorized","User does not have permission to access '"+e+"'.")):t,n.serverResponse=t.serverResponse,n}}function PV(r){const i=RV(r);return function(e,t){let n=i(e,t);return 404===e.getStatus()&&(n=(e=r.path,new Vq("object-not-found","Object '"+e+"' does not exist."))),n.serverResponse=t.serverResponse,n}}function xV(e,t,n){var r=rV(t.fullServerUrl(),e.host,e._protocol),i=e.maxOperationRetryTime;const s=new SV(r,"GET",CV(e,n),i);return s.errorHandler=PV(t),s}function OV(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 DV(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=OV(t,r,i),l="--"+a+"\r\nContent-Type: application/json; charset=utf-8\r\n\r\n"+TV(c,n)+"\r\n--"+a+"\r\nContent-Type: "+c.contentType+"\r\n\r\n",a="\r\n--"+a+"--";const u=pV.getBlob(l,r,a);if(null===u)throw zq();a={name:c.fullPath},c=rV(s,e.host,e._protocol),s=e.maxUploadRetryTime;const h=new SV(c,"POST",CV(e,n),s);return h.urlParams=a,h.headers=o,h.body=u.uploadData(),h.errorHandler=RV(t),h}class LV{constructor(e,t,n,r){this.current=e,this.total=t,this.finalized=!!n,this.metadata=r||null}}function MV(e,t){let n=null;try{n=e.getResponseHeader("X-Goog-Upload-Status")}catch(e){kV(!1)}const r=t||["active"];return kV(!!n&&-1!==r.indexOf(n)),n}function FV(e,t,n,r,i){var s=t.bucketOnlyServerUrl(),o=OV(t,r,i),a={name:o.fullPath},c=rV(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=TV(o,n),o=e.maxUploadRetryTime;const u=new SV(c,"POST",function(e){MV(e);let t;try{t=e.getResponseHeader("X-Goog-Upload-URL")}catch(e){kV(!1)}return kV(Zq(t)),t},o);return u.urlParams=a,u.headers=l,u.body=s,u.errorHandler=RV(t),u}function UV(e,t,n,i){var r=e.maxUploadRetryTime;const s=new SV(n,"POST",function(e){var t=MV(e,["active","final"]);let n=null;try{n=e.getResponseHeader("X-Goog-Upload-Size-Received")}catch(e){kV(!1)}n||kV(!1);var r=Number(n);return kV(!isNaN(r)),new LV(r,i.size(),"final"===t)},r);return s.headers={"X-Goog-Upload-Command":"query"},s.errorHandler=RV(t),s}function jV(e,o,t,a,n,c,r,i){const l=new LV(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 Vq("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 f=a.slice(h,d);if(null===f)throw zq();d=o.maxUploadRetryTime;const p=new SV(t,"POST",function(e,t){var n=MV(e,["active","final"]),r=l.current+u,i=a.size();let s;return s="final"===n?CV(o,c)(e,t):null,new LV(r,i,"final"===n,s)},d);return p.headers=s,p.body=f.uploadData(),p.progressCallback=i||null,p.errorHandler=RV(e),p}const qV={STATE_CHANGED:"state_changed"},VV={RUNNING:"running",PAUSED:"paused",SUCCESS:"success",CANCELED:"canceled",ERROR:"error"};function BV(e){switch(e){case"running":case"pausing":case"canceling":return VV.RUNNING;case"paused":return VV.PAUSED;case"success":return VV.SUCCESS;case"canceled":return VV.CANCELED;default:return VV.ERROR}}class $V{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 KV(t){return(...e)=>{Promise.resolve().then(()=>t(...e))}}class zV{constructor(){this.sent_=!1,this.xhr_=new XMLHttpRequest,this.errorCode_=Oq.NO_ERROR,this.sendPromise_=new Promise(e=>{this.xhr_.addEventListener("abort",()=>{this.errorCode_=Oq.ABORT,e()}),this.xhr_.addEventListener("error",()=>{this.errorCode_=Oq.NETWORK_ERROR,e()}),this.xhr_.addEventListener("load",()=>{e()})})}send(e,t,n,r){if(this.sent_)throw Yq("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 Yq("cannot .getErrorCode() before sending");return this.errorCode_}getStatus(){if(!this.sent_)throw Yq("cannot .getStatus() before sending");try{return this.xhr_.status}catch(e){return-1}}getResponseText(){if(!this.sent_)throw Yq("cannot .getResponseText() before sending");return this.xhr_.responseText}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)}}function WV(){return new zV}class HV{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=wV(),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=FV(this._ref.storage,this._ref._location,this._mappings,this._blob,this._metadata);const r=this._ref.storage._makeRequest(n,WV,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=UV(this._ref.storage,this._ref._location,i,this._blob);const r=this._ref.storage._makeRequest(n,WV,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 LV(this._transferred,this._blob.size()),o=this._uploadUrl;this._resolveToken((e,t)=>{let n;try{n=jV(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,WV,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=xV(this._ref.storage,this._ref._location,this._mappings);const r=this._ref.storage._makeRequest(n,WV,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=DV(this._ref.storage,this._ref._location,this._mappings,this._blob,this._metadata);const r=this._ref.storage._makeRequest(n,WV,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=Kq(),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=BV(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 $V(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(BV(this._state)){case VV.SUCCESS:KV(this._resolve.bind(null,this.snapshot))();break;case VV.CANCELED:case VV.ERROR:const t=this._reject;KV(t.bind(null,this._error))();break;default:e=!1}e&&(this._resolve=void 0,this._reject=void 0)}}_notifyObserver(e){switch(BV(this._state)){case VV.RUNNING:case VV.PAUSED:e.next&&KV(e.next.bind(e,this.snapshot))();break;case VV.SUCCESS:e.complete&&KV(e.complete.bind(e))();break;case VV.CANCELED:case VV.ERROR:default:e.error&&KV(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 GV{constructor(e,t){this._service=e,t instanceof Jq?this._location=t:this._location=Jq.makeFromUrl(t,e.host)}toString(){return"gs://"+this._location.bucket+"/"+this._location.path}_newRef(e,t){return new GV(e,t)}get root(){var e=new Jq(this._location.bucket,"");return this._newRef(this._service,e)}get bucket(){return this._location.bucket}get fullPath(){return this._location.path}get name(){return mV(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 Jq(this._location.bucket,e);return new GV(this._service,e)}_throwIfRoot(e){if(""===this._location.path)throw Gq(e)}}function QV(e){const t={prefixes:[],items:[]};return async function e(t,n,r){const i={pageToken:r};const s=await YV(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 YV(e,t){null!=t&&"number"==typeof t.maxResults&&nV("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=rV(t.bucketOnlyServerUrl(),e.host,e._protocol),a=e.maxOperationRetryTime;const c=new SV(o,"GET",AV(e,t.bucket),a);return c.urlParams=s,c.errorHandler=RV(t),c}(e.storage,e._location,"/",n.pageToken,n.maxResults);return e.storage.makeRequestWithTokens(n,WV)}function JV(e,t){e._throwIfRoot("updateMetadata");var n=function(e,t,n,r){var i=rV(t.fullServerUrl(),e.host,e._protocol),s=TV(n,r),o=e.maxOperationRetryTime;const a=new SV(i,"PATCH",CV(e,r),o);return a.headers={"Content-Type":"application/json; charset=utf-8"},a.body=s,a.errorHandler=PV(t),a}(e.storage,e._location,t,wV());return e.storage.makeRequestWithTokens(n,WV)}function XV(e){e._throwIfRoot("getDownloadURL");var t=function(e,t,n){var r=rV(t.fullServerUrl(),e.host,e._protocol),i=e.maxOperationRetryTime;const s=new SV(r,"GET",NV(e,n),i);return s.errorHandler=PV(t),s}(e.storage,e._location,wV());return e.storage.makeRequestWithTokens(t,WV).then(e=>{if(null===e)throw new Vq("no-download-url","The given file does not have any download URLs.");return e})}function ZV(e){e._throwIfRoot("deleteObject");var t=function(e,t){var n=rV(t.fullServerUrl(),e.host,e._protocol),r=e.maxOperationRetryTime;const i=new SV(n,"DELETE",function(e,t){},r);return i.successCodes=[200,204],i.errorHandler=PV(t),i}(e.storage,e._location);return e.storage.makeRequestWithTokens(t,WV)}function eB(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 Jq(e._location.bucket,r);return new GV(e.storage,r)}function tB(e,t){if(e instanceof iB){var n=e;if(null==n._bucket)throw new Vq("no-default-bucket","No default bucket found. Did you set the '"+qq+"' property when initializing the app?");n=new GV(n,n._bucket);return null!=t?tB(n,t):n}return void 0!==t?eB(e,t):e}function nB(e,t){if(t&&/^[A-Za-z]+:\/\//.test(t)){if(e instanceof iB)return n=e,r=t,new GV(n,r);throw Wq("To use ref(service, url), the first argument must be a Storage instance.")}return tB(e,t);var n,r}function rB(e,t){var n=null==t?void 0:t[qq];return null==n?null:Jq.makeFromBucketSpec(n,e)}class iB{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=jq,this._protocol="https",this._appId=null,this._deleted=!1,this._maxOperationRetryTime=12e4,this._maxUploadRetryTime=6e5,this._requests=new Set,this._bucket=null!=r?Jq.makeFromBucketSpec(r,this._host):rB(this._host,this.app.options)}get host(){return this._host}set host(e){this._host=e,null!=this._url?this._bucket=Jq.makeFromBucketSpec(this._url,e):this._bucket=rB(e,this.app.options)}get maxUploadRetryTime(){return this._maxUploadRetryTime}set maxUploadRetryTime(e){nV("time",0,Number.POSITIVE_INFINITY,e),this._maxUploadRetryTime=e}get maxOperationRetryTime(){return this._maxOperationRetryTime}set maxOperationRetryTime(e){nV("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 GV(this,e)}_makeRequest(e,t,n,r){if(this._deleted)return new Xq(Hq());{const l=(i=e,s=this._appId,o=n,e=r,n=t,r=this._firebaseVersion,a=iV(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 sV(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 sB="@firebase/storage";function oB(e,t,n){return e=Kd(e),t=t,n=n,(e=e)._throwIfRoot("uploadBytesResumable"),new HV(e,new pV(t),n)}function aB(e){return function(e){e._throwIfRoot("getMetadata");var t=xV(e.storage,e._location,wV());return e.storage.makeRequestWithTokens(t,WV)}(e=Kd(e))}function cB(e,t){return nB(e=Kd(e),t)}function lB(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 uB(e,{instanceIdentifier:t}){var n=e.getProvider("app").getImmediate(),r=e.getProvider("auth-internal"),i=e.getProvider("app-check-internal");return new iB(n,r,i,t,mf)}df(new zd("storage",uB,"PUBLIC").setMultipleInstances(!0)),wf(sB,"0.8.7",""),wf(sB,"0.8.7","esm2017");class hB{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 dB{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 hB(this._delegate.snapshot,this,this._ref)}then(t,e){return this._delegate.then(e=>{if(t)return t(new hB(e,this,this._ref))},e)}on(e,t,n,r){let i=void 0;return t&&(i="function"==typeof t?e=>t(new hB(e,this,this._ref)):{next:t.next?e=>t.next(new hB(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 fB{constructor(e,t){this._delegate=e,this._service=t}get prefixes(){return this._delegate.prefixes.map(e=>new pB(e,this._service))}get items(){return this._delegate.items.map(e=>new pB(e,this._service))}get nextPageToken(){return this._delegate.nextPageToken||null}}class pB{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=eB(this._delegate,e);return new pB(t,this.storage)}get root(){return new pB(this._delegate.root,this.storage)}get parent(){var e=this._delegate.parent;return null==e?null:new pB(e,this.storage)}put(e,t){return this._throwIfRoot("put"),new dB(oB(this._delegate,e,t),this)}putString(e,t=cV.RAW,n){this._throwIfRoot("putString");var r=uV(t,e);const i=Object.assign({},n);return null==i.contentType&&null!=r.contentType&&(i.contentType=r.contentType),new dB(new HV(this._delegate,new pV(r.data,!0),i),this)}listAll(){return QV(Kd(this._delegate)).then(e=>new fB(e,this.storage))}list(e){return t=this._delegate,e=e||void 0,YV(t=Kd(t),e).then(e=>new fB(e,this.storage));var t}getMetadata(){return aB(this._delegate)}updateMetadata(e){return JV(Kd(this._delegate),e)}getDownloadURL(){return XV(Kd(this._delegate))}delete(){return this._throwIfRoot("delete"),ZV(Kd(this._delegate))}_throwIfRoot(e){if(""===this._delegate._location.path)throw Gq(e)}}class gB{constructor(e,t){this.app=e,this._delegate=t}get maxOperationRetryTime(){return this._delegate.maxOperationRetryTime}get maxUploadRetryTime(){return this._delegate.maxUploadRetryTime}ref(e){if(mB(e))throw Wq("ref() expected a child path but got a URL, use refFromURL instead.");return new pB(cB(this._delegate,e),this)}refFromURL(e){if(!mB(e))throw Wq("refFromURL() expected a full URL but got a child path, use ref() instead.");try{Jq.makeFromUrl(e,this._delegate.host)}catch(e){throw Wq("refFromUrl() expected a valid full URL but got an invalid one.")}return new pB(cB(this._delegate,e),this)}setMaxUploadRetryTime(e){this._delegate.maxUploadRetryTime=e}setMaxOperationRetryTime(e){this._delegate.maxOperationRetryTime=e}useEmulator(e,t,n={}){lB(this._delegate,e,t,n)}}function mB(e){return/^[A-Za-z]+:\/\//.test(e)}function vB(e,{instanceIdentifier:t}){var n=e.getProvider("app-compat").getImmediate(),r=e.getProvider("storage").getImmediate({identifier:t});return new gB(n,r)}Dq=Af,Lq={TaskState:VV,TaskEvent:qV,StringFormat:cV,Storage:gB,Reference:pB},Dq.INTERNAL.registerComponent(new zd("storage-compat",vB,"PUBLIC").setServiceProps(Lq).setMultipleInstances(!0)),Dq.registerVersion("@firebase/storage-compat","0.1.7");const yB="@firebase/performance",_B="0.5.4",wB="FB-PERF-TRACE-MEASURE",bB="@firebase/performance/config",IB="@firebase/performance/configexpire";var TB,EB,SB,kB="Performance";const CB=new md("performance",kB,{"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."}),AB=new ef(kB);AB.logLevel=Kh.INFO;let NB,RB;class PB{constructor(e){if(!(this.window=e))throw CB.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&&pd()?!!dd()||(AB.info("IndexedDB is not supported by current browswer"),!1):(AB.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===NB&&(NB=new PB(RB)),NB}}let xB;function OB(e,t){var n=e.length-t.length;if(n<0||1<n)throw CB.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 DB;class LB{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=OB("hts/frbslgigp.ogepscmv/ieo/eaylg","tp:/ieaeogn-agolai.o/1frlglgc/o"),this.transportKey=OB("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===DB&&(DB=new LB),DB}}(c=TB=TB||{})[c.UNKNOWN=0]="UNKNOWN",c[c.VISIBLE=1]="VISIBLE",c[c.HIDDEN=2]="HIDDEN";const MB=["firebase_","google_","ga_"],FB=new RegExp("^[a-zA-Z]\\w*$");function UB(){switch(PB.getInstance().document.visibilityState){case"visible":return TB.VISIBLE;case"hidden":return TB.HIDDEN;default:return TB.UNKNOWN}}function jB(e){var t=null===(t=e.options)||void 0===t?void 0:t.appId;if(!t)throw CB.create("no app id");return t}const qB="0.0.1",VB={loggingEnabled:!0},BB="FIREBASE_INSTALLATIONS_AUTH";function $B(e,t){var r,i,n=function(){const e=PB.getInstance().localStorage;if(e){var t=e.getItem(IB);if(t&&function(e){return Number(e)>Date.now()}(t)){t=e.getItem(bB);if(t)try{return JSON.parse(t)}catch(e){return}}}}();return n?(zB(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 CB.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 CB.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:`${BB} ${e}`},body:JSON.stringify({app_instance_id:i,app_instance_id_token:e,app_id:jB(r.app),app_version:_B,sdk_version:qB})});return fetch(n).then(e=>{if(e.ok)return e.json();throw CB.create("RC response not ok")})}).catch(()=>{AB.info(KB)}).then(zB).then(e=>function(e){const t=PB.getInstance().localStorage;e&&t&&(t.setItem(bB,JSON.stringify(e)),t.setItem(IB,String(Date.now()+60*LB.getInstance().configTimeToLive*60*1e3)))}(e),()=>{}))}const KB="Could not fetch config, will use default configs";function zB(e){if(!e)return e;const t=LB.getInstance();var n=e.entries||{};return void 0!==n.fpr_enabled?t.loggingEnabled="true"===String(n.fpr_enabled):t.loggingEnabled=VB.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=WB(t.tracesSamplingRate),t.logNetworkAfterSampling=WB(t.networkRequestsSamplingRate),e}function WB(e){return Math.random()<=e}let HB=1,GB;function QB(e){var t;return HB=2,GB=GB||(t=e,function(){const n=PB.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=>{xB=e}),t}(t.installations)).then(e=>$B(t,e)).then(()=>YB(),()=>YB())),GB}function YB(){HB=3}const JB=1e4,XB=3,ZB=1e3;let e$=XB,t$=[],n$=!1;function r$(e){setTimeout(()=>{if(0!==e$)return t$.length?void function(){const e=t$.splice(0,ZB),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:LB.getInstance().logSource,log_event:t};!function(e,r){return function(e){var t=LB.getInstance().getFlTransportFullUrl();return fetch(t,{method:"POST",body:JSON.stringify(e)})}(e).then(e=>(e.ok||AB.info("Call to Firebase backend failed."),e.json())).then(e=>{var t=Number(e.nextRequestWaitMillis);let n=JB;isNaN(t)||(n=Math.max(t,n));t=e.logResponseDetails;Array.isArray(t)&&0<t.length&&"RETRY_REQUEST_LATER"===t[0].responseAction&&(t$=[...r,...t$],AB.info("Retry transport request later.")),e$=XB,r$(n)})}(n,e).catch(()=>{t$=[...e,...t$],e$--,AB.info(`Tries left: ${e$}.`),r$(JB)})}():r$(JB)},e)}function i$(t){return(...e)=>{!function(e){if(!e.eventTime||!e.message)throw CB.create("invalid cc log");t$=[...t$,e]}({message:t(...e),eventTime:Date.now()})}}let s$;function o$(e,t){s$=s$||i$(l$),s$(e,t)}function a$(e){var t=LB.getInstance();!t.instrumentationEnabled&&e.isAuto||(t.dataCollectionEnabled||e.isAuto)&&PB.getInstance().requiredApisAvailable()&&(e.isAuto&&UB()!==TB.VISIBLE||(3===HB?c$(e):QB(e.performanceController).then(()=>c$(e),()=>c$(e))))}function c$(e){var t;!xB||(t=LB.getInstance()).loggingEnabled&&t.logTraceAfterSampling&&setTimeout(()=>o$(e,1),0)}function l$(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:u$(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:u$(e.performanceController.app),trace_metric:t};return JSON.stringify(n)}(e);var n}function u$(e){return{google_app_id:jB(e),app_instance_id:xB,web_app_info:{sdk_version:_B,page_url:PB.getInstance().getUrl(),service_worker_status:"serviceWorker"in(t=PB.getInstance().navigator)?t.serviceWorker.controller?2:3:1,visibility_state:UB(),effective_connection_type:function(){var e=PB.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 h$=["_fp","_fcp","_fid"];class d${constructor(e,t,n=!1,r){this.performanceController=e,this.name=t,this.isAuto=n,this.state=1,this.customAttributes={},this.counters={},this.api=PB.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||`${wB}-${this.randomId}-${this.name}`,r&&this.calculateTraceMetrics())}start(){if(1!==this.state)throw CB.create("trace started",{traceName:this.name});this.api.mark(this.traceStartMark),this.state=2}stop(){if(2!==this.state)throw CB.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(),a$(this)}record(e,t,n){if(e<=0)throw CB.create("nonpositive trace startTime",{traceName:this.name});if(t<=0)throw CB.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]=Number(Math.floor(n.metrics[r])));a$(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<h$.indexOf(r))&&r.startsWith("_"))throw CB.create("invalid custom metric name",{customMetricName:e});var n,r,i;this.counters[e]=(t=t,(n=Math.floor(t))<t&&AB.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)&&(!MB.some(e=>n.startsWith(e))&&!!n.match(FB)),s=0!==(r=t).length&&r.length<=100;if(i&&s)this.customAttributes[e]=t;else{if(!i)throw CB.create("invalid attribute name",{attributeName:e});if(!s)throw CB.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=PB.getInstance().getUrl();if(i){const s=new d$(e,"_wt_"+i,!0);i=Math.floor(1e3*PB.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))),a$(s)}}static createUserTimingTrace(e,t){a$(new d$(e,t,!1,t))}}function f$(e,t){const n=t;var r,i,s;n&&void 0!==n.responseStart&&(s=PB.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=LB.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(()=>o$(e,0),0))}({performanceController:e,url:n.name&&n.name.split("?")[0],responsePayloadBytes:n.transferSize,startTimeUs:r,timeToResponseInitiatedUs:i,timeToResponseCompletedUs:s}))}const p$=5e3;function g$(e){xB&&(setTimeout(()=>function(n){const e=PB.getInstance(),r=e.getEntriesByType("navigation"),i=e.getEntriesByType("paint");if(e.onFirstInputDelay){let t=setTimeout(()=>{d$.createOobTrace(n,r,i),t=void 0},p$);e.onFirstInputDelay(e=>{t&&(clearTimeout(t),d$.createOobTrace(n,r,i,e))})}else d$.createOobTrace(n,r,i)}(e),0),setTimeout(()=>function(t){const e=PB.getInstance(),n=e.getEntriesByType("resource");for(const r of n)f$(t,r);e.setupObserver("resource",e=>f$(t,e))}(e),0),setTimeout(()=>function(t){const e=PB.getInstance(),n=e.getEntriesByType("measure");for(const r of n)m$(t,r);e.setupObserver("measure",e=>m$(t,e))}(e),0))}function m$(e,t){const n=t.name;n.substring(0,wB.length)!==wB&&d$.createUserTimingTrace(e,n)}class v${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),PB.getInstance().requiredApisAvailable()?fd().then(e=>{e&&(n$||(r$(5500),n$=!0),QB(this).then(()=>g$(this),()=>g$(this)),this.initialized=!0)}).catch(e=>{AB.info(`Environment doesn't support IndexedDB: ${e}`)}):AB.info('Firebase Performance cannot start if the browser does not support "Fetch" and "Promise", or cookies are disabled.'))}set instrumentationEnabled(e){LB.getInstance().instrumentationEnabled=e}get instrumentationEnabled(){return LB.getInstance().instrumentationEnabled}set dataCollectionEnabled(e){LB.getInstance().dataCollectionEnabled=e}get dataCollectionEnabled(){return LB.getInstance().dataCollectionEnabled}}const y$="[DEFAULT]";const _$=(e,{options:t})=>{var n=e.getProvider("app").getImmediate(),r=e.getProvider("installations-internal").getImmediate();if(n.name!==y$)throw CB.create("FB not default");if("undefined"==typeof window)throw CB.create("no window");e=window,RB=e;const i=new v$(n,r);return i._init(t),i};df(new zd("performance",_$,"PUBLIC")),wf(yB,"0.5.4"),wf(yB,"0.5.4","esm2017");class w${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=Kd(t),new d$(t,e);var t}}function b$(e){var t=e.getProvider("app-compat").getImmediate(),n=e.getProvider("performance").getImmediate();return new w$(t,n)}(EB=Af).INTERNAL.registerComponent(new zd("performance-compat",b$,"PUBLIC")),EB.registerVersion("@firebase/performance-compat","0.1.4");const I$="@firebase/remote-config";class T${constructor(){this.listeners=[]}addEventListener(e){this.listeners.push(e)}abort(){this.listeners.forEach(e=>e())}}const E$=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 S$=["1","true","t","yes","y","on"];class k${constructor(e,t=""){this._source=e,this._value=t}asString(){return this._value}asBoolean(){return"static"!==this._source&&0<=S$.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 C$(e){const t=Kd(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 A$(e){const t=Kd(e);return t._initializePromise||(t._initializePromise=t._storageCache.loadFromStorage().then(()=>{t._isInitializationComplete=!0})),t._initializePromise}async function N$(t){const n=Kd(t),e=new T$;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 R$(n){const e=Kd(n);return[t={},r={}]=[e._storageCache.getActiveConfig(),e.defaultConfig],Object.keys(Object.assign(Object.assign({},t),r)).reduce((e,t)=>(e[t]=P$(n,t),e),{});var t,r}function P$(e,t){const n=Kd(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 k$("remote",r[t]):n.defaultConfig&&void 0!==n.defaultConfig[t]?new k$("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 k$("static"))}class x${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 O${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"),E$.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 E$.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 E$.create("fetch-status",{httpStatus:a});return{status:a,eTag:i,config:c}}}class D${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(E$.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()+$d(n),backoffCount:n+1};return await this.storage.setThrottleMetadata(r),this.attemptFetch(t,r)}}}class L${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 M$(e,t){var n=e.target.error||void 0;return E$.create(t,{originalErrorMessage:n&&n.message})}const F$="app_namespace_store";class U${constructor(e,t,n,r=function(){return new Promise((t,n)=>{try{const e=indexedDB.open("firebase_remote_config",1);e.onerror=e=>{n(M$(e,"storage-open"))},e.onsuccess=e=>{t(e.target.result)},e.onupgradeneeded=e=>{const t=e.target.result;0===e.oldVersion&&t.createObjectStore(F$,{keyPath:"compositeKey"})}}catch(e){n(E$.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([F$],"readonly"),r=e.objectStore(F$);var i=this.createCompositeKey(o);try{const s=r.get(i);s.onerror=e=>{t(M$(e,"storage-get"))},s.onsuccess=e=>{var t=e.target.result;n(t?t.value:void 0)}}catch(e){t(E$.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([F$],"readwrite"),r=n.objectStore(F$);var i=this.createCompositeKey(o);try{const s=r.put({compositeKey:i,value:a});s.onerror=e=>{t(M$(e,"storage-set"))},s.onsuccess=()=>{e()}}catch(e){t(E$.create("storage-set",{originalErrorMessage:e&&e.message}))}})}async delete(o){const a=await this.openDbPromise;return new Promise((e,t)=>{const n=a.transaction([F$],"readwrite"),r=n.objectStore(F$);var i=this.createCompositeKey(o);try{const s=r.delete(i);s.onerror=e=>{t(M$(e,"storage-delete"))},s.onsuccess=()=>{e()}}catch(e){t(E$.create("storage-delete",{originalErrorMessage:e&&e.message}))}})}createCompositeKey(e){return[this.appId,this.appName,this.namespace,e].join()}}class j${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 q$(){if(!dd())return!1;try{return await fd()}catch(e){return!1}}df(new zd("remote-config",function(e,{instanceIdentifier:t}){var n=e.getProvider("app").getImmediate(),r=e.getProvider("installations-internal").getImmediate();if("undefined"==typeof window)throw E$.create("registration-window");if(!dd())throw E$.create("indexed-db-unavailable");var{projectId:i,apiKey:s,appId:o}=n.options;if(!i)throw E$.create("registration-project-id");if(!s)throw E$.create("registration-api-key");if(!o)throw E$.create("registration-app-id");t=t||"firebase";const a=new U$(o,n.name,t),c=new j$(a),l=new ef(I$);l.logLevel=Kh.ERROR;o=new O$(r,mf,t,i,s,o),o=new D$(o,a),o=new x$(o,a,c,l),o=new L$(n,o,c,a,l);return A$(o),o},"PUBLIC").setMultipleInstances(!0)),wf(I$,"0.3.3"),wf(I$,"0.3.3","esm2017");class V${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 C$(this._delegate)}ensureInitialized(){return A$(this._delegate)}fetch(){return N$(this._delegate)}fetchAndActivate(){return async function(e){return await N$(e=Kd(e)),C$(e)}(this._delegate)}getAll(){return R$(this._delegate)}getBoolean(e){return P$(Kd(this._delegate),e).asBoolean()}getNumber(e){return P$(Kd(this._delegate),e).asNumber()}getString(e){return P$(Kd(this._delegate),e).asString()}getValue(e){return P$(this._delegate,e)}setLogLevel(e){!function(e,t){const n=Kd(e);switch(t){case"debug":n._logger.logLevel=Kh.DEBUG;break;case"silent":n._logger.logLevel=Kh.SILENT;break;default:n._logger.logLevel=Kh.ERROR}}(this._delegate,e)}}function B$(e,{instanceIdentifier:t}){var n=e.getProvider("app-compat").getImmediate(),r=e.getProvider("remote-config").getImmediate({identifier:t});return new V$(n,r)}return(SB=Af).INTERNAL.registerComponent(new zd("remoteConfig-compat",B$,"PUBLIC").setMultipleInstances(!0).setServiceProps({isSupported:q$})),SB.registerVersion("@firebase/remote-config-compat","0.1.4"),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"),Af.registerVersion("firebase","9.4.1","compat-cdn"),Af});
9
+ `)}function Kg(){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 zg={error:"UNKNOWN_ERROR"};async function Wg(e,t=!1){var n=e.app;Sg(n);const r=vg(n);let i=r.token,s=void 0;if(i||(a=await r.cachedTokenPromise)&&Jg(a)&&(i=a),!t&&i&&Jg(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 $g()),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)}(zg),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&&Jg(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 Wg(n,!0):await Wg(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 Jg(e){return 0<e.expireTimeMillis-Date.now()}class Xg{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){Sg(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:kg(this._throttleData.allowRequestsAfter-Date.now()),httpStatus:this._throttleData.httpStatus})):e}return this._throttleData=null,e}initialize(e){this._app=e,this._platformLoggerProvider=ff(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:kg(this._throttleData.allowRequestsAfter-Date.now()),httpStatus:this._throttleData.httpStatus})):e}return this._throttleData=null,e}initialize(e){this._app=e,this._platformLoggerProvider=ff(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=$d(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:kg(e.allowRequestsAfter-Date.now()),httpStatus:e.httpStatus})}function hm(e=yf(),t){const n=ff(e=Kd(e),"app-check");if(mg.initialized||Kg(),Bg()&&$g().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&&Jg(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";df(new zd("app-check",e=>{var t,n=e.getProvider("app").getImmediate(),r=e.getProvider("platform-logger");return t=n,e=r,new Xg(t,e)},"PUBLIC").setInstantiationMode("EXPLICIT").setInstanceCreatedCallback((e,t,n)=>{e.getProvider(dm).initialize()})),df(new zd(dm,e=>{var t,n=e.getProvider("app-check").getImmediate();return t=n,{getToken:e=>Wg(t,e),addTokenListener:e=>Hg(t,"INTERNAL",e),removeTokenListener:e=>Gg(t.app,e)}},"PUBLIC").setInstantiationMode("EXPLICIT")),wf("@firebase/app-check","0.5.2");const fm=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 pm{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 fm.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 fm.create("use-before-activation",{appName:this.app.name});return async function(e,t){var n=await Wg(e,t);if(n.error)throw n.error;return{token:n.token}}(this._delegate,e)}onTokenChanged(e,t,n){if(!this._delegate)throw fm.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 pm(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}Af.INTERNAL.registerComponent(new zd("appCheck-compat",gm,"PUBLIC").setServiceProps({ReCaptchaEnterpriseProvider:am,ReCaptchaV3Provider:om,CustomProvider:cm})),Af.registerVersion("@firebase/app-check-compat","0.2.2");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 ef("@firebase/auth");function Em(e,...t){Tm.logLevel<=Kh.ERROR&&Tm.error(`Auth (${mf}): ${e}`,...t)}function Sm(e,...t){throw Nm(e,...t)}function km(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&&Sm(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 Dm=new Map;function Om(e){xm(e instanceof Function,"Expected a class definition");let t=Dm.get(e);return t?xm(t instanceof e,"Instance stored in cache mismatched with class"):(t=new e,Dm.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 $m(e,t){return e.tenantId&&!t.tenantId?Object.assign(Object.assign({},t),{tenantId:e.tenantId}):t}async function Km(i,s,o,a,e={}){return zm(i,e,()=>{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=new(qm.headers());return r.set("Content-Type","application/json"),r.set("X-Client-Version",i._getSdkClientVersion()),i.languageCode&&r.set("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 zm(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);Sm(t,s)}}catch(e){if(e instanceof gd)throw e;Sm(t,"network-request-failed")}}async function Wm(e,t,n,r,i={}){var s=await Km(e,t,n,r,i);return"mfaPendingCredential"in s&&Sm(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(km(this.auth,"timeout")),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=km(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 Jm(e){return 1e3*Number(e)}function Xm(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 Km(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=Xm(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 r,i,{accessToken:n,refreshToken:s,expiresIn:o}=(i=t,await{accessToken:(o=await zm(r=e,{},()=>{var e=Cd({grant_type:"refresh_token",refresh_token:i}).slice(1),{tokenApiHost:t,apiKey:n}=r.config,n=Hm(r,t,"/v1/token",`key=${n}`);return qm.fetch()(n,{method:"POST",headers:{"X-Client-Version":r._getSdkClientVersion(),"Content-Type":"application/x-www-form-urlencoded"},body:e})})).access_token,expiresIn:o.expires_in,refreshToken:o.refresh_token});this.updateTokensAndExpiration(n,s,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.emailVerified=!1,this.isAnonymous=!1,this.tenantId=null,this.providerData=[],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.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=Kd(e);var r=await n.getIdToken(t),i=Xm(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(Jm(i.auth_time)),issuedAtTime:Ym(Jm(i.iat)),expirationTime:Ym(Jm(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=Kd(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 Km(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:f,stsTokenManager:p}=t;Rm(u&&p,e,"internal-error");var g=rv.fromJSON(this.name,p);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 f&&Array.isArray(f)&&(m.providerData=f.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(Om(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]||Om(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(pv(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/")||fv(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 fv(e=sd()){return/crios\//i.test(e)}function pv(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)||pv(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/${mf}/${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=Om(n)),this._initializationPromise=this.queue(async()=>{var e;this._deleted||(this.persistenceManager=await lv.create(this,t),this._deleted||(null!==(e=this._popupRedirectResolver)&&void 0!==e&&e._shouldInitProactively&&await this._popupRedirectResolver._initialize(this),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?Kd(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(Om(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&&Om(e)||this._popupRedirectResolver,this,"argument-error"),this.redirectPersistenceManager=await lv.create(this,[Om(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}_getSdkClientVersion(){return this.clientVersion}}function Iv(e){return Kd(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=Sv(t);var{host:o,port:a}=function(e){const t=Sv(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:kv(r.substr(s.length+1))}}var[o,s]=r.split(":");return{host:o,port:kv(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 Sv(e){var t=e.indexOf(":");return t<0?"":e.substr(0,t+1)}function kv(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 Km(e,"POST","/v1/accounts:resetPassword",$m(e,t))}async function Nv(e,t){return Km(e,"POST","/v1/accounts:update",t)}async function Rv(e,t){return Km(e,"POST","/v1/accounts:sendOobCode",$m(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 Wm(e,"POST","/v1/accounts:signInWithPassword",$m(e,t))}(e,{returnSecureToken:!0,email:this._email,password:this._password});case"emailLink":return async function(e,t){return Wm(e,"POST","/v1/accounts:signInWithEmailLink",$m(e,t))}(e,{email:this._email,oobCode:this._password});default:Sm(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 Wm(e,"POST","/v1/accounts:signInWithEmailLink",$m(e,t))}(e,{idToken:t,email:this._email,oobCode:this._password});default:Sm(e,"internal-error")}}_getReauthenticationResolver(e){return this._getIdTokenResponse(e)}}async function xv(e,t){return Wm(e,"POST","/v1/accounts:signInWithIdp",$m(e,t))}class Dv extends Cv{constructor(){super(...arguments),this.pendingToken=null}static _fromParams(e){const t=new Dv(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):Sm("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 Dv(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 Ov={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 Wm(e,"POST","/v1/accounts:signInWithPhoneNumber",$m(e,t))}(e,this._makeVerificationRequest())}_linkToIdToken(e,t){return async function(e,t){var n=await Wm(e,"POST","/v1/accounts:signInWithPhoneNumber",$m(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 Wm(e,"POST","/v1/accounts:signInWithPhoneNumber",$m(e,Object.assign(Object.assign({},t),{operation:"REAUTH"})),Ov)}(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"),Dv._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"),Dv._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 Dv._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 Dv._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 $v extends jv{constructor(){super("github.com")}static credential(e){return Dv._fromParams({providerId:$v.PROVIDER_ID,signInMethod:$v.GITHUB_SIGN_IN_METHOD,accessToken:e})}static credentialFromResult(e){return $v.credentialFromTaggedObject(e)}static credentialFromError(e){return $v.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!(e&&"oauthAccessToken"in e))return null;if(!e.oauthAccessToken)return null;try{return $v.credential(e.oauthAccessToken)}catch(e){return null}}}$v.GITHUB_SIGN_IN_METHOD="github.com",$v.PROVIDER_ID="github.com";class Kv 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 Kv(t,r):null}static _create(e,t){return new Kv(e,t)}buildRequest(){return{requestUri:"http://localhost",returnSecureToken:!0,pendingToken:this.pendingToken}}}class zv extends Uv{constructor(e){Rm(e.startsWith("saml."),"argument-error"),super(e)}static credentialFromResult(e){return zv.samlCredentialFromTaggedObject(e)}static credentialFromError(e){return zv.samlCredentialFromTaggedObject(e.customData||{})}static credentialFromJSON(e){var t=Kv.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 Kv._create(n,t)}catch(e){return null}}}class Wv extends jv{constructor(){super("twitter.com")}static credential(e,t){return Dv._fromParams({providerId:Wv.PROVIDER_ID,signInMethod:Wv.TWITTER_SIGN_IN_METHOD,oauthToken:e,oauthTokenSecret:t})}static credentialFromResult(e){return Wv.credentialFromTaggedObject(e)}static credentialFromError(e){return Wv.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;var{oauthAccessToken:t,oauthTokenSecret:n}=e;if(!t||!n)return null;try{return Wv.credential(t,n)}catch(e){return null}}}async function Hv(e,t){return Wm(e,"POST","/v1/accounts:signUp",$m(e,t))}Wv.TWITTER_SIGN_IN_METHOD="twitter.com",Wv.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 Jv(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 Xv(e){return new Set(e.map(({providerId:e})=>e).filter(e=>!!e))}async function Zv(e,t){const n=Kd(e);await ty(!0,n,t);var r=(e=n.auth,t={idToken:await n.getIdToken(),deleteProvider:[t]},await Km(e,"POST","/v1/accounts:update",t))["providerUserInfo"];const i=Xv(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=Xv(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,Jv(r,i,t,e),n);Rm(s.idToken,r,"internal-error");var o=Xm(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)&&Sm(r,"user-mismatch"),e}}async function ry(e,t,n=!1){var r=await Jv(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=Kd(e);return await ty(!1,n,t.providerId),ey(n,t)}async function oy(e,t){return ny(Kd(e),t)}async function ay(e,t){const n=Iv(e);var r=await Wm(n,"POST","/v1/accounts:signInWithCustomToken",$m(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):Sm(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=Kd(e),i={requestType:"PASSWORD_RESET",email:t};n&&uy(r,i,n),await Rv(r,i)}async function dy(e,t){await Km(e=Kd(e),"POST","/v1/accounts:update",$m(e,{oobCode:t}))}async function fy(e,t){var n=Kd(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 py(e,t,n){var r=Kd(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 Km(e=Kd(e),"POST","/v1/accounts:createAuthUri",$m(e,{identifier:t,continueUri:n})))["signinMethods"];return n||[]}async function my(e,t){var n=Kd(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=Kd(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=Kd(e);var r=await i.getIdToken(),r=await Zm(i,async function(e,t){return Km(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 Sy extends by{constructor(e,t,n){super(e,"twitter.com",t,n)}}function ky(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=Xm(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 Sy(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:Sm(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},Km(n,"POST","/v2/accounts/mfaEnrollment:withdraw",$m(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 Dy 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]}}Dy.type="LOCAL";const Oy=Dy;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",$y="firebaseLocalStorage",Ky="fbase_key";class zy{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 Wy(e,t){return e.transaction([$y],t?"readwrite":"readonly").objectStore($y)}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($y,{keyPath:Ky})}catch(e){t(e)}}),r.addEventListener("success",async()=>{const e=r.result;var t;e.objectStoreNames.contains($y)?n(e):(e.close(),t=indexedDB.deleteDatabase(By),await new zy(t).toPromise(),n(await Hy()))})})}async function Gy(e,t,n){var r=Wy(e,!0).put({fbase_key:t,value:n});return new zy(r).toPromise()}function Qy(e,t){var n=Wy(e,!0).delete(t);return new zy(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=Wy(e,!1).get(t);return void 0===(n=await new zy(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=Wy(e,!1).getAll();return new zy(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 Jy=Yy;function Xy(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=km("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(km(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(km(s,"internal-error"))},Xy(`https://www.google.com/recaptcha/api.js??${Cd({onload:n_,render:"explicit",hl:o})}`).catch(()=>{clearTimeout(i),n(km(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 Km(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 Km(c,"POST","/v2/accounts/mfaEnrollment:start",$m(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 Km(t,"POST","/v2/accounts/mfaSignIn:start",$m(t,a))).phoneResponseInfo.sessionInfo}var f=(s=t,o={phoneNumber:e.phoneNumber,recaptchaToken:u},await Km(s,"POST","/v1/accounts:sendVerificationCode",$m(s,o)))["sessionInfo"];return f}finally{r._reset()}}class h_{constructor(e){this.providerId=h_.PROVIDER_ID,this.auth=Iv(e)}verifyPhoneNumber(e,t){return u_(this.auth,e,Kd(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?Om(t):(Rm(e._popupRedirectResolver,e,"argument-error"),e._popupRedirectResolver)}h_.PROVIDER_ID="phone",h_.PHONE_SIGN_IN_METHOD="phone";class f_ 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 p_(e){return ry(e.auth,new f_(e),e.bypassAuthState)}function g_(e){var{auth:t,user:n}=e;return Rm(n,t,"internal-error"),ny(n,new f_(e),e.bypassAuthState)}async function m_(e){var{auth:t,user:n}=e;return Rm(n,t,"internal-error"),ey(n,new f_(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 p_;case"linkViaPopup":case"linkViaRedirect":return m_;case"reauthViaPopup":case"reauthViaRedirect":return g_;default:Sm(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(km(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(km(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(km(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=S_(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(S_(t),"true")}function E_(e){return Om(e._redirectPersistence)}function S_(e){return cv(w_,e.config.apiKey,e.name)}function k_(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=Kd(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=Kd(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 D_(e);default:return!1}}(t)||(this.hasHandledPotentialRedirect=!0,n||(this.queuedRedirectEvent=t,n=!0)),n}sendToConsumer(e,t){var n;e.error&&!D_(e)?(n=(null===(n=e.error.code)||void 0===n?void 0:n.split("auth/")[1])||"internal-error",t.onError(km(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 D_({type:e,error:t}){return"unknown"===e&&"auth/no-auth-event"===(null==t?void 0:t.code)}async function O_(e,t={}){return Km(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 O_(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){}Sm(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(km(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(km(i,"network-request-failed"))},Xy(`https://apis.google.com/js/api.js?onload=${r}`)}n()}}).catch(e=>{throw q_=null,e})),q_}const B_=new Um(5e3,15e3),$_="__/auth/iframe",K_="emulator/auth/iframe",z_={style:{position:"absolute",top:"-100px",width:"1px",height:"1px"},"aria-hidden":"true",tabindex:"-1"},W_=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,K_):`https://${e.config.authDomain}/${$_}`;const r={apiKey:t.apiKey,appName:e.name,v:mf};(t=W_.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:z_,dontclear:!0},s=>new Promise(async(e,t)=>{await s.restyle({setHideOnLeave:!1});const n=km(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=fv(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 J_="__/auth/handler",X_="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:mf,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,X_):`https://${e.authDomain}/${J_}`}?${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){var 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}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),Sm(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()},Km(e,"POST","/v2/accounts/mfaEnrollment:finalize",$m(e,n))}_finalizeSignIn(e,t){return e=e,t={mfaPendingCredential:t,phoneVerificationInfo:this.credential._makeVerificationRequest()},Km(e,"POST","/v2/accounts/mfaSignIn:finalize",$m(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",df(new zd("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(Om);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()})),df(new zd("auth-internal",e=>{var t=Iv(e.getProvider("auth").getImmediate());return e=t,new ow(e)},"PRIVATE").setInstantiationMode("EXPLICIT")),wf(sw,"0.19.3",function(e){switch(e){case"Node":return"node";case"ReactNative":return"rn";case"Worker":return"webworker";case"Cordova":return"cordova";default:return}}(iw)),wf(sw,"0.19.3","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:Sm(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:km(e,"no-auth-event")}}async function fw(e){var t=await gw()._get(mw(e));return t&&await gw()._remove(mw(e)),t}function pw(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?km(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 Om(Oy)}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){Sm(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(km(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:Sm(e,"operation-not-supported-in-this-environment"),await O_(e,n)}(e)),this.originValidationPromises[t]}attachCallbackListeners(r,i){const{universalLinks:e,handleOpenURL:t,BuildInfo:n}=aw(),s=setTimeout(async()=>{await fw(r),i.onEvent(_w())},500),o=async e=>{clearTimeout(s);var t=await fw(r);let n=null;t&&null!=e&&e.url&&(n=pw(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:km("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 Sw()&&dd()}return!1}function Sw(){return"undefined"!=typeof global&&"WorkerGlobalScope"in global&&"importScripts"in global}function kw(){return("http:"===bw()||"https:"===bw()||cd()||Iw())&&!(ld()||ad())&&Ew()&&!Sw()}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);null!==t&&void 0!==t&&t.sessionStorage&&t.sessionStorage.setItem(n,e._getPersistence())}function xw(){return"undefined"!=typeof window?window:null}const Dw=Rm;class Ow{constructor(){this.browserResolver=Om(tw),this.cordovaResolver=Om(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 Dw(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=Kd(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=$v;break;case vm.TWITTER:r=Wv;break;default:var{oauthIdToken:i,oauthAccessToken:s,oauthTokenSecret:o,pendingToken:a,nonce:c}=t;return s||o||i||a?a?n.startsWith("saml.")?Kv._create(n,a):Dv._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:ky(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=Kd(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=Kd(e);await ty(!1,r,"phone");var i=await u_(r.auth,t,Kd(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=Kd(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,Ow))}async linkWithRedirect(e){return await Pw(Iv(this.auth)),A_(this._delegate,e,Ow)}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=Kd(e);var i=await u_(r.auth,t,Kd(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=Kd(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,Ow))}async reauthenticateWithRedirect(e){return await Pw(Iv(this.auth)),C_(this._delegate,e,Ow)}sendEmailVerification(e){return my(this._delegate,e)}async unlink(e){return await Zv(this._delegate,e),this}updateEmail(e){return _y(Kd(this._delegate),e,null)}updatePassword(e){return _y(Kd(this._delegate),null,e)}updatePhoneNumber(e){return async function(e,t){await ey(Kd(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 $w{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});let r=[av];if("undefined"!=typeof window){r=function(e,t){const n=xw();if(null===n||void 0===n||!n.sessionStorage)return[];var r=cv(Rw,e,t);switch(n.sessionStorage.getItem(r)){case Aw.NONE:return[av];case Aw.LOCAL:return[Jy,My];case Aw.SESSION:return[My];default:return[]}}(n,e.name);for(const i of[Jy,Oy,My])r.includes(i)||r.push(i)}Bw(n,"invalid-api-key",{appName:e.name});n="undefined"!=typeof window?Ow:void 0;this._delegate=t.initialize({options:{persistence:r,popupRedirectResolver:n}}),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 fy(this._delegate,e)}confirmPasswordReset(e,t){return async function(e,t,n){await Av(Kd(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(kw(),this._delegate,"operation-not-supported-in-this-environment");var e,t,n=(e=this._delegate,t=Ow,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}=Kw(e,t,n);return this._delegate.onAuthStateChanged(r,i,s)}onIdTokenChanged(e,t,n){var{next:r,error:i,complete:s}=Kw(e,t,n);return this._delegate.onIdTokenChanged(r,i,s)}sendSignInLinkToEmail(e,t){return py(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"):Sw()?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 Om(Jy)._isAvailable();r=i?Jy:Oy;break;case Aw.NONE:r=av;break;default:return Sm("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(Kd(n),Fv.credential(e,t))));var n}signInWithEmailLink(e,t){return Uw(this._delegate,async function(e,t,n){var r=Kd(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,Kd(n));return new l_(i,e=>iy(r,e))}(this._delegate,e,t))}async signInWithPopup(e){return Bw(kw(),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,Ow))}async signInWithRedirect(e){return Bw(kw(),this._delegate,"operation-not-supported-in-this-environment"),await Pw(this._delegate),k_(this._delegate,e,Ow)}updateCurrentUser(e){return this._delegate.updateCurrentUser(e)}verifyPasswordResetCode(e){return async function(e,t){var n=(await fy(Kd(e),t))["data"];return n.email}(this._delegate,e)}unwrap(){return this._delegate}_delete(){return this._delegate._delete()}linkUnderlyingAuth(){this._delegate.wrapped=()=>this}}function Kw(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}}$w.Persistence=Aw;class zw{constructor(){this.providerId="phone",this._delegate=new h_(Lw(Af.auth()))}static credential(e,t){return h_.credential(e,t)}verifyPhoneNumber(e,t){return this._delegate.verifyPhoneNumber(e,t)}unwrap(){return this._delegate}}zw.PHONE_SIGN_IN_METHOD=h_.PHONE_SIGN_IN_METHOD,zw.PROVIDER_ID=h_.PROVIDER_ID;const Ww=Rm;class Hw{constructor(e,t,n=Af.app()){var r;Ww(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=Af).INTERNAL.registerComponent(new zd("auth-compat",e=>{var t=e.getProvider("app-compat").getImmediate(),n=e.getProvider("auth");return new $w(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:$v,GoogleAuthProvider:Bv,OAuthProvider:qv,SAMLAuthProvider:zv,PhoneAuthProvider:zw,PhoneMultiFactorGenerator:rw,RecaptchaVerifier:Hw,TwitterAuthProvider:Wv,Auth:$w,AuthCredential:Cv,Error:gd}).setInstantiationMode("LAZY").setMultipleInstances(!1)),ww.registerVersion("@firebase/auth-compat","0.2.3");const Gw="@firebase/database";let Qw="";function Yw(e){Qw=e}class Jw{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 Xw{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 Jw(t)}}catch(e){}return new Xw};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++,Jh(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 ef("@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 fb(t){return function(...e){wb(t,...e)}}function pb(...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){Jh(!t||!0===e||!1===e,"Can't turn on custom loggers persistently."),!0===e?(cb.logLevel=Kh.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)},Sb="[MIN_NAME]",kb="[MAX_NAME]",Cb=function(e,t){if(e===t)return 0;if(e===Sb||t===kb)return-1;if(t===Sb||e===kb)return 1;var n=Ob(e),r=Ob(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){Jh(!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,Db=2147483647,Ob=function(e){if(Pb.test(e)){var t=Number(e);if(t>=xb&&t<=Db)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 $b(e,t,n){Jh("string"==typeof t,"typeof type must == string"),Jh("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 Kb{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 zb={},Wb={};function Hb(e){var t=e.toString();return zb[t]||(zb[t]=new Kb),zb[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_=fb(e),this.stats_=Hb(t),this.urlFn=e=>(this.appCheckToken&&(e.ac=this.appCheckToken),$b(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 Jb=null;"undefined"!=typeof MozWebSocket?Jb=MozWebSocket:"undefined"!=typeof WebSocket&&(Jb=WebSocket);class Xb{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_=fb(this.connId),this.stats_=Hb(t),this.connURL=Xb.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),$b(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 Jb(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(){Xb.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!==Jb&&!Xb.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(Jh(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)}}}Xb.responsesRequiredToBeHealthy=2,Xb.healthyTimeout=3e4;class Zb{constructor(e){this.initTransports_(e)}static get ALL_TRANSPORTS(){return[Qb,Xb]}initTransports_(e){var t=Xb&&Xb.isAvailable();let n=t&&!Xb.previouslyFailed();if(e.webSocketOnly&&(t||Ib("wss:// URL used, but browser isn't known to support websockets. Trying anyway."),n=!0),n)this.transports_=[Xb];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_=fb("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?pb("Server Error: "+n):"o"===t?(this.log_("got pong on primary."),this.onPrimaryResponse_(),this.sendPingOnPrimaryIfNecessary_()):pb("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_={},Jh(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){Jh(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 Jh("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 fI(e){return e.pieceNum_>=e.pieces_.length}function pI(e,t){var n=oI(e),r=oI(t);if(null===n)return t;if(n===r)return pI(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 Jh("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_=fb("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)),Jh(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),Jh(e._queryParams.isDefault()||!e._queryParams.loadsAllData(),"listen() called for non-default but complete query"),Jh(!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),Jh(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):pb("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){Jh(!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){Jh(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(Sb,e),r=new TI(Sb,t);return 0!==this.compare(n,r)}minPost(){return TI.MIN}}let SI;class kI extends EI{static get __EMPTY_NODE(){return SI}static set __EMPTY_NODE(e){SI=e}compare(e,t){return Cb(e.name,t.name)}isDefinedOn(e){throw Xh("KeyIndex.isDefinedOn not expected to be called.")}indexedValueChanged(e,t){return!1}minPost(){return TI.MIN}maxPost(){return new TI(kb,SI)}makePost(e,t){return Jh("string"==typeof e,"KeyIndex indexValue must always be a string."),new TI(e,SI)}toString(){return".key"}}const CI=new kI;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 DI;function OI(e){return"number"==typeof e?"number:"+Nb(e):"string:"+e}function LI(e){var t;e.isLeafNode()?(t=e.val(),Jh("string"==typeof t||"number"==typeof t||"object"==typeof t&&bd(t,".sv"),"Priority must be a string or number.")):Jh(e===DI||e.isEmpty(),"priority of unexpected type."),Jh(e===DI||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,Jh(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 fI(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:(Jh(".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:"+OI(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:(Jh(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 Jh(0<=r,"Unknown leaf type: "+t),Jh(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(kb,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 $I(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 KI;const zI={};class WI{constructor(e,t){this.indexes_=e,this.indexSet_=t}static get Default(){return Jh((zI,qI),"ChildrenNode.ts has not been loaded"),KI=KI||new WI({".priority":zI},{".priority":qI}),KI}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){Jh(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?$I(n,e.getCompare()):zI;var a=e.toString();const c=Object.assign({},this.indexSet_);c[a]=e;const l=Object.assign({},this.indexes_);return l[a]=o,new WI(l,c)}addToIndexes(o,a){var e=Ed(this.indexes_,(t,e)=>{const n=Id(this.indexSet_,e);if(Jh(n,"Missing index implementation for "+e),t===zI){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),$I(i,n.getCompare())}return zI}{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 WI(e,this.indexSet_)}removeFromIndexes(n,r){var e=Ed(this.indexes_,e=>{if(e===zI)return e;var t=r.get(n.name);return t?e.remove(new TI(n.name,t)):e});return new WI(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()&&Jh(!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,WI.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(Jh(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;Jh(".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:"+OI(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,WI.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(Sb,GI.EMPTY_NODE)},MAX:{value:new TI(kb,YI)}}),kI.__EMPTY_NODE=GI.EMPTY_NODE,FI.__childrenNodeConstructor=GI,Zw=YI,DI=Zw,eb=YI,jI=eb;const JI=!0;function XI(i,e=null){if(null===i)return GI.EMPTY_NODE;if("object"==typeof i&&".priority"in i&&(e=i[".priority"]),Jh(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,XI(e))}if(i instanceof Array||!JI){let r=GI.EMPTY_NODE;return Ab(i,(e,t)=>{if(bd(i,e)&&"."!==e.substring(0,1)){const n=XI(t);!n.isLeafNode()&&n.isEmpty()||(r=r.updateImmediateChild(e,n))}}),r.updatePriority(XI(e))}{const s=[];let r=!1;if(Ab(i,(e,t)=>{if("."!==e.substring(0,1)){const n=XI(t);n.isEmpty()||(r=r||!n.getPriority().isEmpty(),s.push(new TI(e,n)))}}),0===s.length)return GI.EMPTY_NODE;var n=$I(s,PI,e=>e.name,xI);if(r){t=$I(s,qI.getCompare());return new GI(n,XI(e),new WI({".priority":t},{".priority":qI}))}return new GI(n,XI(e),WI.Default)}}UI=XI;class ZI extends EI{constructor(e){super(),this.indexPath_=e,Jh(!fI(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=XI(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(kb,e)}toString(){return uI(this.indexPath_,0).join("/")}}function eT(e){if(e===""+Db)return iT;var t=Ob(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?kb:(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 Sb;var t=Ob(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?""+Db:(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=XI(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);Jh(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 Jh(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){Jh(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)):Jh(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 fT{constructor(e){this.indexedFilter_=new dT(e.getIndex()),this.index_=e.getIndex(),this.startPost_=fT.getStartPost_(e),this.endPost_=fT.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 pT{constructor(e){this.rangedFilter_=new fT(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;Jh(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 f=o.updateImmediateChild(t,GI.EMPTY_NODE);return null!=e&&this.rangedFilter_.matches(e)?(null!=i&&i.trackChildChange(lT(e.name,e.node)),f.updateImmediateChild(e.name,e.node)):f}}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 Jh(this.startSet_,"Only valid if start has been set"),this.indexStartValue_}getIndexStartName(){return Jh(this.startSet_,"Only valid if start has been set"),this.startNameSet_?this.indexStartName_:Sb}hasEnd(){return this.endSet_}getIndexEndValue(){return Jh(this.endSet_,"Only valid if end has been set"),this.indexEndValue_}getIndexEndName(){return Jh(this.endSet_,"Only valid if end has been set"),this.endNameSet_?this.indexEndName_:kb}hasLimit(){return this.limitSet_}hasAnchoredLimit(){return this.limitSet_&&""!==this.viewFrom_}getLimit(){return Jh(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":(Jh(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_=fb("p:rest:"),this.listens_={}}reportStats(e){throw new Error("Method not implemented.")}static getListenId_(e,t){return void 0!==t?"tag$"+t:(Jh(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;fI(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 ST(e,n,r){var i;null!==e.value?r(n,e.value):(i=(e,t)=>{ST(t,new iI(n.toString()+"/"+e),r)},e.children.forEach((e,t)=>{i(t,e)}))}class kT{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 kT(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}}(W=tb=tb||{})[W.OVERWRITE=0]="OVERWRITE",W[W.MERGE=1]="MERGE",W[W.ACK_USER_WRITE=2]="ACK_USER_WRITE",W[W.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(fI(this.path)){if(null!=this.affectedTree.value)return Jh(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 Jh(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 fI(this.path)?new xT(this.source,sI()):new xT(this.source,cI(this.path))}}class DT{constructor(e,t,n){this.source=e,this.path=t,this.snap=n,this.type=tb.OVERWRITE}operationForChild(e){return fI(this.path)?new DT(this.source,sI(),this.snap.getImmediateChild(e)):new DT(this.source,cI(this.path),this.snap)}}class OT{constructor(e,t,n){this.source=e,this.path=t,this.children=n,this.type=tb.MERGE}operationForChild(e){if(fI(this.path)){const t=this.children.subtree(new iI(e));return t.isEmpty()?null:t.value?new DT(this.source,sI(),t.value):new OT(this.source,sI(),t)}return Jh(oI(this.path)===e,"Can't get a merge for a child not on the path of the operation"),new OT(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(fI(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 Xh("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 $T(e){return e.serverCache.isFullyInitialized()?e.serverCache.getNode():null}let KT;class zT{constructor(e,t=(KT=KT||new RI(gb),KT)){this.value=e,this.children=t}static fromObject(e){let n=new zT(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(fI(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(fI(e))return this;{var t=oI(e);const n=this.children.get(t);return null!==n?n.subtree(cI(e)):new zT(null)}}set(e,t){if(fI(e))return new zT(t,this.children);{var n=oI(e);const i=this.children.get(n)||new zT(null);var r=i.set(cI(e),t),r=this.children.insert(n,r);return new zT(this.value,r)}}remove(t){if(fI(t))return this.children.isEmpty()?new zT(null):new zT(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 zT(null):new zT(this.value,e)}return this}}get(e){if(fI(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(fI(t))return n;{var r=oI(t);const i=this.children.get(r)||new zT(null),s=i.setTree(cI(t),n);let e;return e=s.isEmpty()?this.children.remove(r):this.children.insert(r,s),new zT(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(fI(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(fI(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 zT(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 WT{constructor(e){this.writeTree_=e}static empty(){return new WT(new zT(null))}}function HT(t,n,r){if(fI(n))return new WT(new zT(r));var i=t.writeTree_.findRootMostValueAndPath(n);if(null!=i){var s=i.path;let e=i.value;i=pI(s,n);return e=e.updateChild(i,r),new WT(t.writeTree_.set(s,e))}s=new zT(r),s=t.writeTree_.setTree(n,s);return new WT(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(fI(t))return WT.empty();var n=e.writeTree_.setTree(t,new zT(null));return new WT(n)}function YT(e,t){return null!=JT(e,t)}function JT(e,t){var n=e.writeTree_.findRootMostValueAndPath(t);return null!=n?e.writeTree_.get(n.path).getChild(pI(n.path,t)):null}function XT(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(fI(t))return e;var n=JT(e,t);return null!=n?new WT(new zT(n)):new WT(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?(Jh(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 p0(t,e)}function r0(t,n){var e,r=t.allWrites.findIndex(e=>e.writeId===n);Jh(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=WT.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=pI(n,i),r=HT(r,e,o.snap)):vI(i,n)&&(e=pI(i,n),r=HT(r,sI(),o.snap.getChild(e)));else{if(!o.children)throw Xh("WriteRecord should have .snap or .children");if(vI(n,i))e=pI(n,i),r=GT(r,e,o.children);else if(vI(i,n))if(e=pI(i,n),fI(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=JT(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=JT(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)}),XT(s).forEach(e=>{r=r.updateImmediateChild(e.name,e.node)}),r}return XT(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){Jh(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),JT(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=JT(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=JT(r.visibleWrites,i))?s:n.isCompleteForChild(t)?t0(ZT(r.visibleWrites,i),n.getNode().getImmediateChild(t)):null;var r,i,s}function f0(e,t){return p0(dI(e.treePath,t),e.writeTree)}function p0(e,t){return{treePath:e,writeTree:t}}class g0{constructor(){this.changeMap=new Map}trackChildChange(e){var t=e.type,n=e.childName;Jh("child_added"===t||"child_changed"===t||"child_removed"===t,"Only child changes supported for tracking"),Jh(".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 Xh("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_:$T(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):(Jh(c.source.fromServer,"Unknown source."),a=c.source.tagged||t.serverCache.isFiltered()&&!fI(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):(Jh(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(fI(i)||".priority"===oI(i)){let e;e=r.serverCache.isFullyInitialized()?a0(s,$T(r)):(l=r.serverCache.getNode(),Jh(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,$T(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(fI(i)&&l.isFullyInitialized()||l.isCompleteForPath(i))return w0(e,t,i,l.getNode().getChild(i),s,o,c,a);if(fI(i)){let n=new zT(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 zT(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 Xh("Unknown operation type: "+n.type);o=function(e,t,n,r,i){const s=t.serverCache,o=VT(t,s.getNode(),s.isFullyInitialized()||fI(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(fI(s)){var e;Jh(i.serverCache.isFullyInitialized(),"If change path is empty, we must have complete server data"),t=i.serverCache.isFiltered()?(e=c0(o,(e=$T(i))instanceof GI?e:GI.EMPTY_NODE),r.filter.updateFullNode(i.eventCache.getNode(),e,c)):(u=a0(o,$T(i)),r.filter.updateFullNode(i.eventCache.getNode(),u,c))}else{var u=oI(s);if(".priority"===u){Jh(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()||fI(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(fI(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 f=cI(n);const p=c.getNode().getImmediateChild(d);h=p.updateChild(f,r);l=".priority"===d?u.updatePriority(c.getNode(),h):u.updateChild(c.getNode(),d,h,f,m0,null)}f=VT(t,l,c.isFullyInitialized()||fI(n),u.filtersNodes());return _0(e,f,n,i,new v0(i,f,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(fI(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 f=a.getNode().getImmediateChild(h);let e;if(fI(d))e=i;else{const p=u.getCompleteChild(h);e=null!=p?".priority"===lI(d)&&p.getChild(hI(d)).isEmpty()?p:p.updateChild(d,i):GI.EMPTY_NODE}c=f.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=fI(e)?t:new zT(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 S0{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()?pT:fT)(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 k0(e){return 0===e.eventRegistrations_.length}function C0(n,r,i){const s=[];if(i){Jh(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&&(Jh($T(e.viewCache_),"We should always have a full cache before handling merges"),Jh(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,Jh(r.eventCache.getNode().isIndexed(n.filter.getIndex()),"Event snap not indexed"),Jh(r.serverCache.getNode().isIndexed(n.filter.getIndex()),"Server snap not indexed"),Jh(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 Jh(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 D0(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 S0(n,o)}}function O0(e,t,n,r,i,s){var o=D0(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)),k0(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)),k0(u)&&(e.views.delete(i),u.query._queryParams.loadsAllData()||s.push(u.query)))}return a&&!q0(e)&&s.push((Jh(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=$T(e.viewCache_);return n&&(e.query._queryParams.loadsAllData()||!fI(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 $0=1;class K0{constructor(e){this.listenProvider_=e,this.syncPointTree_=new zT(null),this.pendingWriteTree_={visibleWrites:WT.empty(),allWrites:[],lastWriteId:-1},this.tagToQueryMap=new Map,this.queryToTagMap=new Map}}function z0(e,t,n,r,i){var s,o,a,c;return s=e.pendingWriteTree_,o=t,a=n,c=r,r=i,Jh(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 DT(AT(),t,n)):[]}function W0(e,t,n,r){var i,s,o;i=e.pendingWriteTree_,s=t,o=n,r=r,Jh(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=zT.fromObject(n);return Z0(e,new OT(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 zT(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 DT(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=pI(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),Jh(!e.queryToTagMap.has(u),"View does not exist, but we have a tag"),c=$0++,e.queryToTagMap.set(u,c),e.tagToQueryMap.set(c,u));var u=n0(e.pendingWriteTree_,r);let h=O0(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)Jh(!q0(a.value),"If we're adding a query, it shouldn't be shadowed");else{var c=a.fold((e,t,r)=>{if(!fI(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 J0(e,r,t){var n=e.pendingWriteTree_,i=e.syncPointTree_.findOnPath(r,(e,t)=>{var n=F0(t,pI(e,r));if(n)return n});return o0(n,r,i,t,!0)}function X0(e,t){const r=t._path;let i=null;e.syncPointTree_.foreachOnPath(r,(e,t)=>{var n=pI(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(D0(n,t,a,s?o.getNode():GI.EMPTY_NODE,s).viewCache_)}function Z0(e,t){return function t(n,r,i,s){{if(fI(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=f0(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=f0(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=pI(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 Jh(-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 Jh(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()?(Jh(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 J0(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?(Jh(".sv"in e,"Unexpected leaf node or priority contents"),"string"==typeof e[".sv"]?dE(e[".sv"],t,n):"object"==typeof e[".sv"]?fE(e[".sv"],t):void Jh(!1,"Unexpected server value: "+JSON.stringify(e,null,2))):e}const dE=function(e,t,n){if("timestamp"===e)return n.timestamp;Jh(!1,"Unexpected server value: "+e)},fE=function(e,t,n){e.hasOwnProperty("increment")||Jh(!1,"Unexpected server value: "+JSON.stringify(e,null,2));var r=e.increment;"number"!=typeof r&&Jh(!1,"Unexpected increment value: "+r);const i=t.node();if(Jh(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},pE=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,XI(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 SE(e,t,n,r){r&&void 0===t||UE(Ld(e,"value"),t,n)}function kE(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)&&!OE(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||OE(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]/,DE=10485760,OE=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>DE/3&&Ud(e)>DE)throw new Error(o+"contains a string greater than "+DE+" 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,!OE(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||!OE(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 $E(e,t,n){BE(e,n),zE(e,e=>mI(e,t))}function KE(e,t,n){BE(e,n),zE(e,e=>vI(e,t)||vI(t,e))}function zE(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 WE="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)=>{XE(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)=>{XE(o,e,t,n,r)},e=>{ZE(o,e)},e=>{var n;n=o,Ab(e,(e,t)=>{eS(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(),Wb[n]||(Wb[n]=t()),Wb[n]),o.infoData_=new IT,o.infoSyncTree_=new K0({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:()=>{}}),eS(o,"connected",!1),o.serverSyncTree_=new K0({startListening:(r,e,t,i)=>(o.server_.listen(r,t,e,(e,t)=>{var n=i(e,t);KE(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 JE(e){return uE({timestamp:YE(e)})}function XE(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=>XI(e)),function(e,t,n,r){if(a=iE(e,r)){var i=sE(a),s=i.path,o=i.queryId,a=pI(s,t),i=zT.fromObject(n);return oE(e,s,new OT(RT(o),a,i))}return[]}(e.serverSyncTree_,a,s,i)):(s=XI(n),function(e,t,n,r){if(null==(s=iE(e,r)))return[];var i=(o=sE(s)).path,s=o.queryId,o=pI(i,t);return oE(e,i,new DT(RT(s),o,n))}(e.serverSyncTree_,a,s,i)):r?(o=Ed(n,e=>XI(e)),t=e.serverSyncTree_,i=a,r=o,o=zT.fromObject(r),Z0(t,new OT(NT(),i,o))):(o=XI(n),G0(e.serverSyncTree_,a,o));let l=a;0<c.length&&(l=hS(e,a)),KE(e.eventQueue_,l,c)}function ZE(e,t){eS(e,"connected",t),!1===t&&function(r){aS(r,"onDisconnectEvents");const i=JE(r),s=TT();ST(r.onDisconnect_,sI(),(e,t)=>{var n=pE(e,t,r.serverSyncTree_,i);ET(s,e,n)});let o=[];ST(s,sI(),(e,t)=>{o=o.concat(G0(r.serverSyncTree_,e,t));var n=gS(r,e);hS(r,n)}),r.onDisconnect_=TT(),KE(r.eventQueue_,sI(),o)}(e)}function eS(e,t,n){var r=new iI("/.info/"+t),i=XI(n);e.infoData_.updateSnapshot(r,i);i=G0(e.infoSyncTree_,r,i);KE(e.eventQueue_,r,i)}function tS(e){return e.nextWriteId_++}function nS(r,i,e,t,s){aS(r,"set",{path:i.toString(),value:e,priority:t});var n=JE(r);const o=XI(e,t);var a=J0(r.serverSyncTree_,i),n=gE(o,a,n);const c=tS(r);n=z0(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);KE(r.eventQueue_,i,n),cS(0,s,e,t)});n=gS(r,i);hS(r,n),KE(r.eventQueue_,n,[])}function rS(n,r,i){n.server_.onDisconnectCancel(r.toString(),(e,t)=>{"ok"===e&&!function e(n,t){if(fI(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),cS(0,i,e,t)})}function iS(n,r,e,i){const s=XI(e);n.server_.onDisconnectPut(r.toString(),s.val(!0),(e,t)=>{"ok"===e&&ET(n.onDisconnect_,r,s),cS(0,i,e,t)})}function sS(e,t,n){let r;r=".info"===oI(t._path)?Q0(e.infoSyncTree_,t,n):Q0(e.serverSyncTree_,t,n),$E(e.eventQueue_,t._path,r)}function oS(e){e.persistentConnection_&&e.persistentConnection_.interrupt(WE)}function aS(e,...t){let n="";e.persistentConnection_&&(n=e.persistentConnection_.id+":"),wb(n,...t)}function cS(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 lS(e,t,n){return J0(e.serverSyncTree_,t,n)||GI.EMPTY_NODE}function uS(t,e=t.transactionQueueTree_){if(e||pS(t,e),_E(e)){const n=fS(t,e);Jh(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=lS(i,s,e);let n=t;var r=t.hash();for(let u=0;u<o.length;u++){const h=o[u];Jh(0===h.status,"tryToSendTransactionQueue_: items in queue should all be run."),h.status=1,h.retryCount++;var a=pI(s,h.path);n=n.updateChild(a,h.currentOutputSnapshotRaw)}const c=n.val(!0),l=s;i.server_.put(l.toString(),c,t=>{aS(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();pS(i,yE(i.transactionQueueTree_,s)),uS(i,i.transactionQueueTree_),KE(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}hS(i,s)}},r)}(t,TE(e),n)}else bE(e)&&IE(e,e=>{uS(t,e)})}function hS(e,t){var n=dS(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=pI(o,h.path);let e=!1,t;if(Jh(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=lS(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=XI(c);"object"==typeof c&&null!=c&&bd(c,".priority")||(e=e.updatePriority(d.getPriority()));a=h.currentWriteId,c=JE(i),c=gE(e,d,c);h.currentOutputSnapshotRaw=e,h.currentOutputSnapshotResolved=c,h.currentWriteId=tS(i),u.splice(u.indexOf(a),1),n=n.concat(z0(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))}KE(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))))}pS(i,i.transactionQueueTree_);for(let e=0;e<l.length;e++)Lb(l[e]);uS(i,i.transactionQueueTree_)}}(e,fS(e,n),r),r}function dS(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 fS(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 pS(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=>{pS(t,e)})}function gS(t,e){var n=TE(dS(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=>{mS(t,e)}),mS(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=>{mS(t,e)}),n}function mS(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?(Jh(t===n-1,"All SENT items should be at beginning of queue."),t=n,o[n].status=3,o[n].abortReason="set"):(Jh(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,KE(i.eventQueue_,TE(s),e);for(let r=0;r<a.length;r++)Lb(a[r])}}const vS=function(e,t){var n=yS(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)}},yS=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,f=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 p=i.slice(0,e);"localhost"===p.toLowerCase()?s="localhost":p.split(".").length<=2?s=p:(d=i.indexOf("."),o=i.substring(0,d).toLowerCase(),s=i.substring(d+1),c=o),"ns"in f&&(c=f.ns)}return{host:i,port:h,domain:s,subdomain:o,secure:l,scheme:u,pathString:a,namespace:c}};class _S{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 wS{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 bS{constructor(e,t){this.snapshotCallback=e,this.cancelCallback=t}onValue(e,t){this.snapshotCallback.call(null,e,t)}onCancel(e){return Jh(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 IS{constructor(e,t){this._repo=e,this._path=t}cancel(){const e=new rd;return rS(this._repo,this._path,e.wrapCallback(()=>{})),e.promise}remove(){RE("OnDisconnect.remove",this._path);const e=new rd;return iS(this._repo,this._path,null,e.wrapCallback(()=>{})),e.promise}set(e){RE("OnDisconnect.set",this._path),SE("OnDisconnect.set",e,this._path,!1);const t=new rd;return iS(this._repo,this._path,e,t.wrapCallback(()=>{})),t.promise}setWithPriority(e,t){RE("OnDisconnect.setWithPriority",this._path),SE("OnDisconnect.setWithPriority",e,this._path,!1),CE("OnDisconnect.setWithPriority",t,!1);const n=new rd;return function(n,r,e,t,i){const s=XI(e,t);n.server_.onDisconnectPut(r.toString(),s.val(!0),(e,t)=>{"ok"===e&&ET(n.onDisconnect_,r,s),cS(0,i,e,t)})}(this._repo,this._path,e,t,n.wrapCallback(()=>{})),n.promise}update(e){RE("OnDisconnect.update",this._path),kE("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."),cS(0,s,"ok",void 0);r.server_.onDisconnectMerge(i.toString(),n,(e,t)=>{"ok"===e&&Ab(n,(e,t)=>{var n=XI(t);ET(r.onDisconnect_,dI(i,e),n)}),cS(0,s,e,t)})}(this._repo,this._path,e,t.wrapCallback(()=>{})),t.promise}}class TS{constructor(e,t,n,r){this._repo=e,this._path=t,this._queryParams=n,this._orderByCalled=r}get key(){return fI(this._path)?null:lI(this._path)}get ref(){return new CS(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=Kd(e))instanceof TS))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 ES(e,t){if(!0===e._orderByCalled)throw new Error(t+": You can't combine multiple orderBy calls.")}function SS(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()!==Sb)throw new Error(r);if("string"!=typeof t)throw new Error(i)}if(e.hasEnd()){if(e.getIndexEndName()!==kb)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(Jh(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 kS(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 CS extends TS{constructor(e,t){super(e,t,new gT,!1)}get parent(){var e=hI(this._path);return null===e?null:new CS(this._repo,e)}get root(){let e=this;for(;null!==e.parent;)e=e.parent;return e}}class AS{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=PS(this.ref,e);return new AS(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 AS(t,PS(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 NS(e,t){return(e=Kd(e))._checkNotDeleted("ref"),void 0!==t?PS(e._root,t):e._root}function RS(e,t){(e=Kd(e))._checkNotDeleted("refFromURL");const n=vS(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+")"),NS(e,n.path.toString())}function PS(e,t){return(null===oI((e=Kd(e))._path)?NE:jE)("child","path",t,!1),new CS(e._repo,dI(e._path,t))}function xS(e,t){e=Kd(e),RE("set",e._path),SE("set",t,e._path,!1);const n=new rd;return nS(e._repo,e._path,t,null,n.wrapCallback(()=>{})),n.promise}function DS(e,t){kE("update",t,e._path,!1);const n=new rd;return function(i,s,e,o){aS(i,"update",{path:s.toString(),value:e});let n=!0;const r=JE(i),a={};if(Ab(e,(e,t)=>{n=!1,a[e]=pE(dI(s,e),XI(t),i.serverSyncTree_,r)}),n)wb("update() called with empty data. Don't do anything."),cS(0,o,"ok",void 0);else{const c=tS(i);var t=W0(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?hS(i,s):s;KE(i.eventQueue_,n,r),cS(0,o,e,t)}),Ab(e,e=>{var t=gS(i,dI(s,e));hS(i,t)}),KE(i.eventQueue_,s,[])}}(e._repo,e._path,t,n.wrapCallback(()=>{})),n.promise}function OS(t){return t=Kd(t),r=t._repo,i=t,(null!=(e=X0(r.serverSyncTree_,i))?Promise.resolve(e):r.server_.get(i).then(e=>{var t=XI(e).withIndex(i._queryParams.getIndex()),n=G0(r.serverSyncTree_,i._path,t);return $E(r.eventQueue_,i._path,n),Promise.resolve(t)},e=>(aS(r,"get for query "+_d(i)+" failed: "+e),Promise.reject(new Error(e))))).then(e=>new AS(e,new CS(t._repo,t._path),t._queryParams.getIndex()));var r,i,e}class LS{constructor(e){this.callbackContext=e}respondsTo(e){return"value"===e}createEvent(e,t){var n=t._queryParams.getIndex();return new _S("value",this,new AS(e.snapshotNode,new CS(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 wS(this,e,t):null}matches(e){return e instanceof LS&&(!e.callbackContext||!this.callbackContext||e.callbackContext.matches(this.callbackContext))}hasAnyCallback(){return null!==this.callbackContext}}class MS{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 wS(this,e,t):null}createEvent(e,t){Jh(null!=e.childName,"Child events should have a childName.");var n=PS(new CS(t._repo,t._path),e.childName),r=t._queryParams.getIndex();return new _S(e.type,this,new AS(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 MS&&(this.eventType===e.eventType&&(!this.callbackContext||!e.callbackContext||this.callbackContext.matches(e.callbackContext)))}hasAnyCallback(){return!!this.callbackContext}}function FS(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)=>{sS(n._repo,n,a),c(e,t)};o.userCallback=t.userCallback,o.context=t.context,t=o}o=new bS(t,s||void 0);const a="value"===e?new LS(o):new MS(e,o);return function(e,t,n){let r;r=".info"===oI(t._path)?Y0(e.infoSyncTree_,t,n):Y0(e.serverSyncTree_,t,n),$E(e.eventQueue_,t._path,r)}(n._repo,n,a),()=>sS(n._repo,n,a)}function US(e,t,n,r){return FS(e,"value",t,n,r)}function jS(e,t,n,r){return FS(e,"child_added",t,n,r)}function qS(e,t,n,r){return FS(e,"child_changed",t,n,r)}function VS(e,t,n,r){return FS(e,"child_moved",t,n,r)}function BS(e,t,n,r){return FS(e,"child_removed",t,n,r)}function $S(e,t,n){let r=null;var i=n?new bS(n):null;"value"===t?r=new LS(i):t&&(r=new MS(t,i)),sS(e._repo,e,r)}class KS{}class zS extends KS{constructor(e,t){super(),this._value=e,this._key=t}_apply(e){SE("endAt",this._value,e._path,!0);var t=vT(e._queryParams,this._value,this._key);if(kS(t),SS(t),e._queryParams.hasEnd())throw new Error("endAt: Starting point was already set (by another call to endAt, endBefore or equalTo).");return new TS(e._repo,e._path,t,e._orderByCalled)}}class WS extends KS{constructor(e,t){super(),this._value=e,this._key=t}_apply(e){SE("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?Sb:tT(n),vT(e,t,r)),i.endBeforeSet_=!0,i}(e._queryParams,this._value,this._key);if(kS(t),SS(t),e._queryParams.hasEnd())throw new Error("endBefore: Starting point was already set (by another call to endAt, endBefore or equalTo).");return new TS(e._repo,e._path,t,e._orderByCalled)}}class HS extends KS{constructor(e,t){super(),this._value=e,this._key=t}_apply(e){SE("startAt",this._value,e._path,!0);var t=mT(e._queryParams,this._value,this._key);if(kS(t),SS(t),e._queryParams.hasStart())throw new Error("startAt: Starting point was already set (by another call to startAt, startBefore or equalTo).");return new TS(e._repo,e._path,t,e._orderByCalled)}}class GS extends KS{constructor(e,t){super(),this._value=e,this._key=t}_apply(e){SE("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?kb:eT(r),i=mT(t,n,e)}return i.startAfterSet_=!0,i}(e._queryParams,this._value,this._key);if(kS(t),SS(t),e._queryParams.hasStart())throw new Error("startAfter: Starting point was already set (by another call to startAt, startAfter, or equalTo).");return new TS(e._repo,e._path,t,e._orderByCalled)}}class QS extends KS{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 TS(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 YS extends KS{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 TS(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 JS extends KS{constructor(e){super(),this._path=e}_apply(e){ES(e,"orderByChild");var t=new iI(this._path);if(fI(t))throw new Error("orderByChild: cannot pass in empty path. Use orderByValue() instead.");t=new ZI(t),t=yT(e._queryParams,t);return SS(t),new TS(e._repo,e._path,t,!0)}}class XS extends KS{_apply(e){ES(e,"orderByKey");var t=yT(e._queryParams,CI);return SS(t),new TS(e._repo,e._path,t,!0)}}class ZS extends KS{_apply(e){ES(e,"orderByPriority");var t=yT(e._queryParams,qI);return SS(t),new TS(e._repo,e._path,t,!0)}}class ek extends KS{_apply(e){ES(e,"orderByValue");var t=yT(e._queryParams,nT);return SS(t),new TS(e._repo,e._path,t,!0)}}class tk extends KS{constructor(e,t){super(),this._value=e,this._key=t}_apply(e){if(SE("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 zS(this._value,this._key)._apply(new HS(this._value,this._key)._apply(e))}}function nk(e,...t){let n=Kd(e);for(const r of t)n=r._apply(n);return n}nb=CS,Jh(!R0,"__referenceConstructor has already been defined"),R0=nb,rb=CS,Jh(!B0,"__referenceConstructor has already been defined"),B0=rb;const rk="FIREBASE_DATABASE_EMULATOR_HOST",ik={};let sk=!1;function ok(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=vS(s,i),a=o.repoInfo,c,l=void 0;"undefined"!=typeof process&&(l=process.env[rk]),l?(c=!0,s=`http://${l}?ns=${a.namespace}`,o=vS(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),fI(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=ik[t.name];i||(i={},ik[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,sk,n,r),i[e.toURLString()]=s}(a,e,u,new Mb(e.name,n));return new ak(u,e)}class ak{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 CS(this._repo,sI())),this._rootInternal}_delete(){return null!==this._rootInternal&&(function(e,t){const n=ik[t];n&&n[e.key]===e||bb(`Database ${t}(${e.repoInfo_}) has already been deleted.`),oS(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 ck(e,t,n,r={}){(e=Kd(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 lk(e){(e=Kd(e))._checkNotDeleted("goOnline"),(e=e._repo).persistentConnection_&&e.persistentConnection_.resume(WE)}function uk(e,t){_b(e,t)}const hk={".sv":"timestamp"};class dk{constructor(e,t){this.committed=e,this.snapshot=t}toJSON(){return{committed:this.committed,snapshot:this.snapshot.toJSON()}}}function fk(i,e,t){if(i=Kd(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=US(i,()=>{});return function(t,n,e,r,i,s){aS(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=lS(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"),Jh(FE(e),"Invalid priority returned by transaction. Priority must be a valid string, finite number, server value, or null.");else{const h=J0(t.serverSyncTree_,n)||GI.EMPTY_NODE;e=h.getPriority().val()}l=JE(t),c=XI(c,e),l=gE(c,a,l);o.currentOutputSnapshotRaw=c,o.currentOutputSnapshotResolved=l,o.currentWriteId=tS(t);l=z0(t.serverSyncTree_,n,l,o.currentWriteId,o.applyLocally);KE(t.eventQueue_,n,l),uS(t,t.transactionQueueTree_)}}(i._repo,i._path,e,(e,t,n)=>{var r;e?s.reject(e):(r=new AS(n,new CS(i._repo,i._path),qI),s.resolve(new dk(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(mf),df(new zd("database",(e,{instanceIdentifier:t})=>{return ok(e.getProvider("app").getImmediate(),e.getProvider("auth-internal"),e.getProvider("app-check-internal"),t)},"PUBLIC").setMultipleInstances(!0)),wf(Gw,"0.12.4",ib),wf(Gw,"0.12.4","esm2017");function pk(e){var t="FIREBASE WARNING: "+e;gk.warn(t)}const gk=new ef("@firebase/database-compat");class mk{constructor(e){this._delegate=e}cancel(t){Od("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){Od("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){Od("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){Od("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(Od("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,pk("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 vk{constructor(e,t){this.committed=e,this.snapshot=t}toJSON(){return Od("TransactionResult.toJSON",0,1,arguments.length),{committed:this.committed,snapshot:this.snapshot.toJSON()}}}class yk{constructor(e,t){this._database=e,this._delegate=t}val(){return Od("DataSnapshot.val",0,0,arguments.length),this._delegate.val()}exportVal(){return Od("DataSnapshot.exportVal",0,0,arguments.length),this._delegate.exportVal()}toJSON(){return Od("DataSnapshot.toJSON",0,1,arguments.length),this._delegate.toJSON()}exists(){return Od("DataSnapshot.exists",0,0,arguments.length),this._delegate.exists()}child(e){return Od("DataSnapshot.child",0,1,arguments.length),e=String(e),jE("DataSnapshot.child","path",e,!1),new yk(this._database,this._delegate.child(e))}hasChild(e){return Od("DataSnapshot.hasChild",1,1,arguments.length),jE("DataSnapshot.hasChild","path",e,!1),this._delegate.hasChild(e)}getPriority(){return Od("DataSnapshot.getPriority",0,0,arguments.length),this._delegate.priority}forEach(t){return Od("DataSnapshot.forEach",1,1,arguments.length),Md("DataSnapshot.forEach","action",t,!1),this._delegate.forEach(e=>t(new yk(this._database,e)))}hasChildren(){return Od("DataSnapshot.hasChildren",0,0,arguments.length),this._delegate.hasChildren()}get key(){return this._delegate.key}numChildren(){return Od("DataSnapshot.numChildren",0,0,arguments.length),this._delegate.size}getRef(){return Od("DataSnapshot.ref",0,0,arguments.length),new wk(this._database,this._delegate.ref)}get ref(){return this.getRef()}}class _k{constructor(e,t){this.database=e,this._delegate=t}on(e,n,t,r){var i;Od("Query.on",2,4,arguments.length),Md("Query.on","callback",n,!1);const s=_k.getCancelAndContextArgs_("Query.on",t,r);var o=(e,t)=>{n.call(s.context,new yk(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 US(this._delegate,o,a),n;case"child_added":return jS(this._delegate,o,a),n;case"child_removed":return BS(this._delegate,o,a),n;case"child_changed":return qS(this._delegate,o,a),n;case"child_moved":return VS(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;Od("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,$S(this._delegate,e,r)):$S(this._delegate,e)}get(){return OS(this._delegate).then(e=>new yk(this.database,e))}once(e,r,t,n){Od("Query.once",1,4,arguments.length),Md("Query.once","callback",r,!0);const i=_k.getCancelAndContextArgs_("Query.once",t,n),s=new rd;var o=(e,t)=>{var n=new yk(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":US(this._delegate,o,a,{onlyOnce:!0});break;case"child_added":jS(this._delegate,o,a,{onlyOnce:!0});break;case"child_removed":BS(this._delegate,o,a,{onlyOnce:!0});break;case"child_changed":qS(this._delegate,o,a,{onlyOnce:!0});break;case"child_moved":VS(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 Od("Query.limitToFirst",1,1,arguments.length),new _k(this.database,nk(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 QS(e)}(e)))}limitToLast(e){return Od("Query.limitToLast",1,1,arguments.length),new _k(this.database,nk(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 YS(e)}(e)))}orderByChild(e){return Od("Query.orderByChild",1,1,arguments.length),new _k(this.database,nk(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 JS(e)}(e)))}orderByKey(){return Od("Query.orderByKey",0,0,arguments.length),new _k(this.database,nk(this._delegate,new XS))}orderByPriority(){return Od("Query.orderByPriority",0,0,arguments.length),new _k(this.database,nk(this._delegate,new ZS))}orderByValue(){return Od("Query.orderByValue",0,0,arguments.length),new _k(this.database,nk(this._delegate,new ek))}startAt(e=null,t){return Od("Query.startAt",0,2,arguments.length),new _k(this.database,nk(this._delegate,([e=null,t]=[e,t],AE("startAt","key",t,!0),new HS(e,t))))}startAfter(e=null,t){return Od("Query.startAfter",0,2,arguments.length),new _k(this.database,nk(this._delegate,(e=e,t=t,AE("startAfter","key",t,!0),new GS(e,t))))}endAt(e=null,t){return Od("Query.endAt",0,2,arguments.length),new _k(this.database,nk(this._delegate,(e=e,t=t,AE("endAt","key",t,!0),new zS(e,t))))}endBefore(e=null,t){return Od("Query.endBefore",0,2,arguments.length),new _k(this.database,nk(this._delegate,(e=e,t=t,AE("endBefore","key",t,!0),new WS(e,t))))}equalTo(e,t){return Od("Query.equalTo",1,2,arguments.length),new _k(this.database,nk(this._delegate,(e=e,t=t,AE("equalTo","key",t,!0),new tk(e,t))))}toString(){return Od("Query.toString",0,0,arguments.length),this._delegate.toString()}toJSON(){return Od("Query.toJSON",0,1,arguments.length),this._delegate.toJSON()}isEqual(e){if(Od("Query.isEqual",1,1,arguments.length),e instanceof _k)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 wk(this.database,new CS(this._delegate._repo,this._delegate._path))}}class wk extends _k{constructor(e,t){super(e,new TS(t._repo,t._path,new gT,!1)),this.database=e,this._delegate=t}getKey(){return Od("Reference.key",0,0,arguments.length),this._delegate.key}child(e){return Od("Reference.child",1,1,arguments.length),"number"==typeof e&&(e=String(e)),new wk(this.database,PS(this._delegate,e))}getParent(){Od("Reference.parent",0,0,arguments.length);var e=this._delegate.parent;return e?new wk(this.database,e):null}getRoot(){return Od("Reference.root",0,0,arguments.length),new wk(this.database,this._delegate.root)}set(e,t){Od("Reference.set",1,2,arguments.length),Md("Reference.set","onComplete",t,!0);const n=xS(this._delegate,e);return t&&n.then(()=>t(null),e=>t(e)),n}update(t,n){if(Od("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,pk("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=DS(this._delegate,t);return n&&e.then(()=>n(null),e=>n(e)),e}setWithPriority(e,t,n){Od("Reference.setWithPriority",2,3,arguments.length),Md("Reference.setWithPriority","onComplete",n,!0);const r=function(e,t,n){if(RE("setWithPriority",e._path),SE("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 nS(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){Od("Reference.remove",0,1,arguments.length),Md("Reference.remove","onComplete",t,!0);const e=(n=this._delegate,RE("remove",n._path),xS(n,null));var n;return t&&e.then(()=>t(null),e=>t(e)),e}transaction(e,t,n){Od("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=fk(this._delegate,e,{applyLocally:n}).then(e=>new vk(e.committed,new yk(this.database,e.snapshot)));return t&&r.then(e=>t(null,e.committed,e.snapshot),e=>t(e,!1,null)),r}setPriority(e,t){Od("Reference.setPriority",1,2,arguments.length),Md("Reference.setPriority","onComplete",t,!0);const n=function(e,t){e=Kd(e),RE("setPriority",e._path),CE("setPriority",t,!1);const n=new rd;return nS(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){Od("Reference.push",0,2,arguments.length),Md("Reference.push","onComplete",t,!0);const n=function(e,t){e=Kd(e),RE("push",e._path),SE("push",t,e._path,!0);var n=YE(e._repo),n=aT(n);const r=PS(e,n),i=PS(e,n);let s;return s=null!=t?xS(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 wk(this.database,e));t&&r.then(()=>t(null),e=>t(e));const i=new wk(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 mk(new IS(this._delegate._repo,this._delegate._path))}get key(){return this.getKey()}get parent(){return this.getParent()}get root(){return this.getRoot()}}class bk{constructor(e,t){this._delegate=e,this.app=t,this.INTERNAL={delete:()=>this._delegate._delete()}}useEmulator(e,t,n={}){ck(this._delegate,e,t,n)}ref(e){if(Od("database.ref",0,1,arguments.length),e instanceof wk){var t=RS(this._delegate,e.toString());return new wk(this,t)}t=NS(this._delegate,e);return new wk(this,t)}refFromURL(e){Od("database.refFromURL",1,1,arguments.length);var t=RS(this._delegate,e);return new wk(this,t)}goOffline(){var e;Od("database.goOffline",0,0,arguments.length),(e=Kd(e=this._delegate))._checkNotDeleted("goOffline"),oS(e._repo)}goOnline(){return Od("database.goOnline",0,0,arguments.length),lk(this._delegate)}}bk.ServerValue={TIMESTAMP:hk,increment:e=>({".sv":{increment:e}})};var Ik,Tk=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 zd("auth-internal",()=>r,"PRIVATE")),{instance:new bk(ok(e,o,void 0,t,s),e),namespace:i}}});const Ek=bk.ServerValue;(Ik=Af).INTERNAL.registerComponent(new zd("database-compat",(e,{instanceIdentifier:t})=>{var n=e.getProvider("app-compat").getImmediate(),r=e.getProvider("database").getImmediate({identifier:t});return new bk(r,n)},"PUBLIC").setServiceProps({Reference:wk,Query:_k,Database:bk,DataSnapshot:yk,enableLogging:uk,INTERNAL:Tk,ServerValue:Ek}).setMultipleInstances(!0)),Ik.registerVersion("@firebase/database-compat","0.1.4");var l="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},Sk={},kk=l||self;function Ck(){}function Ak(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 Nk(e){var t=typeof e;return"object"==t&&null!=e||"function"==t}var Rk="closure_uid_"+(1e9*Math.random()>>>0),Pk=0;function xk(e,t,n){return e.call.apply(e.bind,arguments)}function Dk(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 Ok(e,t,n){return(Ok=Function.prototype.bind&&-1!=Function.prototype.bind.toString().indexOf("native code")?xk:Dk).apply(null,arguments)}function Lk(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 Mk(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 Fk(){this.s=this.s,this.o=this.o}var Uk={};Fk.prototype.s=!1,Fk.prototype.na=function(){var e,t;!this.s&&(this.s=!0,this.M(),0)&&(t=this,e=Object.prototype.hasOwnProperty.call(t,Rk)&&t[Rk]||(t[Rk]=++Pk),delete Uk[e])},Fk.prototype.M=function(){if(this.o)for(;this.o.length;)this.o.shift()()};const jk=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},qk=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 Vk(){return Array.prototype.concat.apply([],arguments)}function Bk(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 $k(e){return/^[\s\xa0]*$/.test(e)}var Kk,zk=String.prototype.trim?function(e){return e.trim()}:function(e){return/^[\s\xa0]*([\s\S]*?)[\s\xa0]*$/.exec(e)[1]};function Wk(e,t){return-1!=e.indexOf(t)}function Hk(e,t){return e<t?-1:t<e?1:0}e:{var Gk=kk.navigator;if(Gk){Gk=Gk.userAgent;if(Gk){Kk=Gk;break e}}Kk=""}function Qk(e,t,n){for(const r in e)t.call(n,e[r],r,e)}function Yk(e){const t={};for(const n in e)t[n]=e[n];return t}var Jk="constructor hasOwnProperty isPrototypeOf propertyIsEnumerable toLocaleString toString valueOf".split(" ");function Xk(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<Jk.length;e++)n=Jk[e],Object.prototype.hasOwnProperty.call(r,n)&&(t[n]=r[n])}}function Zk(e){return Zk[" "](e),e}Zk[" "]=Ck;var eC,tC=Wk(Kk,"Opera"),nC=Wk(Kk,"Trident")||Wk(Kk,"MSIE"),rC=Wk(Kk,"Edge"),iC=rC||nC,sC=Wk(Kk,"Gecko")&&!(Wk(Kk.toLowerCase(),"webkit")&&!Wk(Kk,"Edge"))&&!(Wk(Kk,"Trident")||Wk(Kk,"MSIE"))&&!Wk(Kk,"Edge"),oC=Wk(Kk.toLowerCase(),"webkit")&&!Wk(Kk,"Edge");function aC(){var e=kk.document;return e?e.documentMode:void 0}e:{var cC="",lC=(lC=Kk,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=zk(String(eC)).split("."),n=zk("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=Hk(0==i[1].length?0:parseInt(i[1],10),0==s[1].length?0:parseInt(s[1],10))||Hk(0==i[2].length,0==s[2].length)||Hk(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=kk.document&&nC&&(aC()||parseInt(eC,10))||void 0,fC=function(){if(!kk.addEventListener||!Object.defineProperty)return!1;var e=!1,t=Object.defineProperty({},"passive",{get:function(){e=!0}});try{kk.addEventListener("test",Ck,t),kk.removeEventListener("test",Ck,t)}catch(e){}return e}();function pC(e,t){this.type=e,this.g=this.target=t,this.defaultPrevented=!1}function gC(e,t){if(pC.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{Zk(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)}}pC.prototype.h=function(){this.defaultPrevented=!0},Mk(gC,pC);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=jk(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),SC={};function kC(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=DC(r);return t&&t[vC]?t.O(n,r,Nk(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++)kC(e,t[s],n,r,i);return null}return n=DC(n),e&&e[vC]?e.N(t,n,Nk(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=Nk(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=!fC?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 SC?SC[e]:SC[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 DC(t){return"function"==typeof t?t:(t[xC]||(t[xC]=function(e){return t.handleEvent(e)}),t[xC])}function OC(){Fk.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 pC(t,e):t instanceof pC?t.target=t.target||e:(o=t,Xk(t=new pC(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}Mk(OC,Fk),OC.prototype[vC]=!0,OC.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=Nk(i)?!!i.capture:!!i,r=DC(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)},OC.prototype.M=function(){if(OC.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},OC.prototype.N=function(e,t,n,r){return this.i.add(String(e),t,!1,n,r)},OC.prototype.O=function(e,t,n,r){return this.i.add(String(e),t,!0,n,r)};var FC=kk.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=kk.Promise.resolve(void 0),UC=function(){n.then(KC)}),BC||(UC(),BC=!0),$C.add(e,t)}var BC=!1,$C=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 KC(){for(var e;e=function(){var e=$C;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){kk.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 zC(e,t){OC.call(this),this.h=e||1,this.g=t||kk,this.j=Ok(this.kb,this),this.l=Date.now()}function WC(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=Ok(e,n));else{if(!e||"function"!=typeof e.handleEvent)throw Error("Invalid listener argument");e=Ok(e.handleEvent,e)}return 2147483647<Number(t)?-1:kk.setTimeout(e,t||0)}Mk(zC,OC),(We=zC.prototype).da=!1,We.S=null,We.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&&(WC(this),this.start())))},We.start=function(){this.da=!0,this.S||(this.S=this.g.setTimeout(this.j,this.h),this.l=Date.now())},We.M=function(){zC.Z.M.call(this),WC(this),delete this.g};class GC extends Fk{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&&(kk.clearTimeout(this.g),this.g=null,this.i=!1,this.h=null)}}function QC(e){Fk.call(this),this.h=e,this.g={}}Mk(QC,Fk);var YC=[];function JC(e,t,n,r){Array.isArray(n)||(n&&(YC[0]=n.toString()),n=YC);for(var i=0;i<n.length;i++){var s=kC(t,n[i],r||e.handleEvent,!1,e.h||e);if(!s)break;e.g[s.key]=s}}function XC(e){Qk(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),XC(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 OC}function iA(e){pC.call(this,tA.Ma,e)}function sA(){var e=rA();LC(e,new iA(e))}function oA(e,t){pC.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){pC.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 kk.setTimeout(function(){e()},t)}tA.Ma="serverreachability",Mk(iA,pC),tA.STAT_EVENT="statevent",Mk(oA,pC),tA.Na="timingevent",Mk(cA,pC);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 fA(){pC.call(this,"d")}function pA(){pC.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 zC(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}Mk(fA,pC),Mk(pA,pC),Mk(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=KA(UA(t)),e.s=n,e.U=!0,TA(e,null)}function TA(e,t){e.F=Date.now(),kA(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(Ok(e.Ia,e,e.g),e.O)),JC(e.V,e.g,"readystatechange",e.gb),t=e.H?Yk(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 SA(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 kA(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(Ok(e.eb,e),t)}function AA(e){e.B&&(kk.clearTimeout(e.B),e.B=null)}function NA(e){0==e.l.G||e.I||XN(e.l,e)}function RA(e){AA(e);var t=e.L;t&&"function"==typeof t.na&&t.na(),e.L=null,WC(e.W),XC(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;JN(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(Ok(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||JN(n),!$k(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&&(Wk(c,"spdy")||Wk(c,"quic")||Wk(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,$A(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,f,p=e;(r=n).oa=nR(r,r.H?r.la:null,r.W),p.J?(dN(r.i,p),d=p,(f=r.K)&&d.setTimeout(f),d.B&&(AA(d),kA(d)),r.g=p):HN(r),0<n.l.length&&$N(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(Ak(e)||"string"==typeof e)qk(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(Ak(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(Ak(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 DA(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 DA)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 OA(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)}(We=mA.prototype).setTimeout=function(e){this.P=e},We.gb=function(e){e=e.target;const t=this.L;t&&3==ON(e)?t.l():this.Ia(e)},We.Ia=function(e){try{if(e==this.g)e:{var t=ON(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==ON(this.g);if(!this.h.i){if("undefined"==typeof TextDecoder){RA(this),NA(this);var a="";break t}this.h.i=new kk.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,f=this.A,p=this.m,g=this.X,m=t,v=r,h.info(function(){return"XMLHTTP RESP ("+p+") [ attempt "+g+"]: "+d+"\n"+f+"\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)&&!$k(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?(SA(this,t,a),iC&&this.i&&3==t&&(JC(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?XN(this.l,this):(this.i=!1,kA(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,f,p,g,m,v},We.fb=function(){var e,t;this.g&&(e=ON(this.g),t=this.g.ga(),this.C<t.length&&(AA(this),SA(this,e,t),this.i&&4!=e&&kA(this)))},We.cancel=function(){this.I=!0,RA(this)},We.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)},(We=DA.prototype).R=function(){OA(this);for(var e=[],t=0;t<this.g.length;t++)e.push(this.h[this.g[t]]);return e},We.T=function(){return OA(this),this.g.concat()},We.get=function(e,t){return LA(this.h,e)?this.h[e]:t},We.set=function(e,t){LA(this.h,e)||(this.i++,this.g.push(e)),this.h[e]=t},We.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 DA(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=zA(n[2]||""),qA(this,n[3]||"",!0),VA(this,n[4]),this.l=zA(n[5]||"",!0),BA(this,n[6]||"",!0),this.o=zA(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?zA(t,!0):t,e.j&&(e.j=e.j.replace(/:$/,""))}function qA(e,t,n){e.i=n?zA(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=WA(t,JA)),e.h=new ZA(t,e.g))}function $A(e,t,n){e.h.set(t,n)}function KA(e){return $A(e,"zx",Math.floor(2147483648*Math.random()).toString(36)+Math.abs(Math.floor(2147483648*Math.random())^Date.now()).toString(36)),e}function zA(e,t){return e?t?decodeURI(e.replace(/%25/g,"%2525")):decodeURIComponent(e):""}function WA(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(WA(t,GA,!0),":");var n=this.i;return!n&&"file"!=t||(e.push("//"),(t=this.s)&&e.push(WA(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(WA(n,"/"==n.charAt(0)?YA:QA,!0))),(n=this.h.toString())&&e.push("?",n),(n=this.o)&&e.push("#",WA(n,XA)),e.join("")};var GA=/[#\/\?@]/g,QA=/[#\?:]/g,YA=/[#\?]/g,JA=/[#\?@]/g,XA=/#/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 DA,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&&OA(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),Bk(n)),e.h+=n.length)}function iN(e,t){return t=String(t),t=e.j?t.toLowerCase():t}(We=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},We.forEach=function(n,r){eN(this),this.g.forEach(function(e,t){qk(e,function(e){n.call(r,e,t,this)},this)},this)},We.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},We.R=function(e){eN(this);var t=[];if("string"==typeof e)nN(this,e)&&(t=Vk(t,this.g.get(iN(this,e))));else{e=this.g.R();for(var n=0;n<e.length;n++)t=Vk(t,e[n])}return t},We.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},We.get=function(e,t){return e&&0<(e=this.R(e)).length?String(e[0]):t},We.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=kk.PerformanceNavigationTiming?0<(e=kk.performance.getEntriesByType("navigation")).length&&("hq"==e[0].nextHopProtocol||"h2"==e[0].nextHopProtocol):!!(kk.g&&kk.g.Ea&&kk.g.Ea()&&kk.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 fN(t){if(null!=t.h)return t.i.concat(t.h.D);if(null==t.g||0===t.g.size)return Bk(t.i);{let e=t.i;for(const n of t.g.values())e=e.concat(n.D);return e}}function pN(){}function gN(){this.g=new pN}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){OC.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=fN(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()}},pN.prototype.stringify=function(e){return kk.JSON.stringify(e,void 0)},pN.prototype.parse=function(e){return kk.JSON.parse(e,void 0)},Mk(vN,uA),vN.prototype.g=function(){return new yN(this.l,this.j)},vN.prototype.i=(aN={},function(){return aN}),Mk(yN,OC);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)}(We=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)},We.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||kk).fetch(new Request(this.B,t)).then(this.Va.bind(this),this.ha.bind(this))},We.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},We.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!==kk.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))},We.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))},We.Ua=function(e){this.g&&(this.response=this.responseText=e,bN(this))},We.Ta=function(e){this.g&&(this.response=e,bN(this))},We.ha=function(){this.g&&bN(this)},We.setRequestHeader=function(e,t){this.v.append(e,t)},We.getResponseHeader=function(e){return this.h&&this.h.get(e.toLowerCase())||""},We.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=kk.JSON.parse;function EN(e){OC.call(this),this.headers=new DA,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=SN,this.K=this.L=!1}Mk(EN,OC);var SN="",kN=/^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!==Sk&&(!e.C[1]||4!=ON(e)||2!=e.ba()))if(e.v&&4==ON(e))HC(e.Fa,0,e);else if(LC(e,"readystatechange"),4==ON(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)&&kk.self&&kk.self.location&&(i=(r=kk.self.location.protocol).substr(0,r.length-1)),n=!kN.test(i?i.toLowerCase():"")),t=n),t)LC(e,"complete"),LC(e,"success");else{e.m=6;try{var a=2<ON(e)?e.g.statusText:""}catch(e){a=""}e.j=a+" ["+e.ba()+"]",RN(e)}}finally{xN(e)}}}function xN(e,t){if(e.g){DN(e);const n=e.g,r=e.C[0]?Ck:null;e.g=null,e.C=null,t||LC(e,"ready");try{n.onreadystatechange=r}catch(e){}}}function DN(e){e.g&&e.K&&(e.g.ontimeout=null),e.A&&(kk.clearTimeout(e.A),e.A=null)}function ON(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 SN: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 Qk(e,function(e,t){n+=t,n+=":",n+=e,n+="\r\n"}),n}(n),"string"==typeof e?null!=n&&encodeURIComponent(String(n)):$A(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++,$A(n=UA(e.F),"SID",e.J),$A(n,"RID",t),$A(n,"TYPE","terminate"),zN(e,n),(t=new mA(e,e.h,t,void 0)).K=2,t.v=KA(UA(n)),n=!1,!(n=kk.navigator&&kk.navigator.sendBeacon?kk.navigator.sendBeacon(t.v.toString(),""):n)&&kk.Image&&((new Image).src=t.v,n=!0),n||(t.g=rR(t.l,null),t.g.ea(t.v)),t.F=Date.now(),kA(t)),tR(e)}function qN(e){e.g&&(QN(e),e.g.cancel(),e.g=null)}function VN(e){qN(e),e.u&&(kk.clearTimeout(e.u),e.u=null),JN(e),e.i.cancel(),e.m&&("number"==typeof e.m&&kk.clearTimeout(e.m),e.m=null)}function BN(e,t){e.l.push(new sN(e.Za++,t)),3==e.G&&$N(e)}function $N(e){cN(e.i)||e.m||(e.m=!0,VC(e.Ha,e),e.C=0)}function KN(e,t){var n=t?t.m:e.V++,r=UA(e.F);$A(r,"SID",e.J),$A(r,"RID",n),$A(r,"AID",e.U),zN(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=WN(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 zN(e,n){e.j&&xA({},function(e,t){$A(n,t,e)})}function WN(e,t,r){r=Math.min(e.l.length,r);var i=e.j?Ok(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;Nk(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(Ok(e.Ga,e),ZN(e,e.A)),e.A++,1)}function QN(e){null!=e.B&&(kk.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);$A(t,"RID","rpc"),$A(t,"SID",e.J),$A(t,"CI",e.N?"0":"1"),$A(t,"AID",e.U),zN(e,t),$A(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=KA(UA(t)),n.s=null,n.U=!0,TA(n,e)}function JN(e){null!=e.v&&(kk.clearTimeout(e.v),e.v=null)}function XN(e,t){var n,r,i,s=null;if(e.g==t){JN(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)),$N(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(Ok(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=Ok(e.jb,e),n||(n=new FA("//www.google.com/images/cleardot.gif"),kk.location&&"http"==kk.location.protocol||jA(n,"https"),KA(n)),function(e,t){var n=new ZC;if(kk.Image){const r=new Image;r.onload=Lk(mN,n,r,"TestLoadImage: loaded",!0,t),r.onerror=Lk(mN,n,r,"TestLoadImage: error",!1,t),r.onabort=Lk(mN,n,r,"TestLoadImage: abort",!1,t),r.ontimeout=Lk(mN,n,r,"TestLoadImage: timeout",!1,t),kk.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==fN(e.i).length&&0==e.l.length||(e.i.i.length=0,Bk(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=kk.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&&Qk(e.aa,function(e,t){$A(r,t,e)}),t=e.D,n=e.sa,t&&n&&$A(r,t,n),$A(r,"VER",e.ma),zN(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){OC.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)&&!$k(e)&&(this.g.o=e),this.A=t&&t.supportsCrossDomainXhr||!1,this.v=t&&t.sendRawJson||!1,(t=t&&t.httpSessionIdParam)&&!$k(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){fA.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(){pA.call(this),this.status=1}function lR(e){this.g=e}(We=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=Ok(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 DA(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=kk.FormData&&e instanceof kk.FormData,0<=jk(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{DN(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=Ok(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},We.pa=function(){void 0!==Sk&&this.g&&(this.j="Timed out after "+this.B+"ms, aborting",this.m=8,LC(this,"timeout"),this.abort(8))},We.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))},We.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)},We.Fa=function(){this.s||(this.F||this.v||this.l?PN(this):this.cb())},We.cb=function(){PN(this)},We.ba=function(){try{return 2<ON(this)?this.g.status:-1}catch(e){return-1}},We.ga=function(){try{return this.g?this.g.responseText:""}catch(e){return""}},We.Qa=function(e){if(this.g){var t=this.g.responseText;return e&&0==t.indexOf(e)&&(t=t.substring(e.length)),TN(t)}},We.Da=function(){return this.m},We.La=function(){return"string"==typeof this.j?this.j:String(this.j)},(We=UN.prototype).ma=8,We.G=1,We.hb=function(e){try{this.h.info("Origin Trials invoked: "+e)}catch(e){}},We.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=Yk(e),Xk(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=WN(this,s,n),$A(r=UA(this.F),"RID",t),$A(r,"CVER",22),this.D&&$A(r,"X-HTTP-Session-Id",this.D),zN(this,r),this.o&&e&&MN(r,this.o,e),hN(this.i,s),this.Ra&&$A(r,"TYPE","init"),this.ja?($A(r,"$req",n),$A(r,"SID","null"),s.$=!0,IA(s,r,null)):IA(s,r,n),this.G=2}}else 3==this.G&&(t?KN(this,t):0==this.l.length||cN(this.i)||KN(this))},We.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(Ok(this.bb,this),e))},We.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))},We.ab=function(){null!=this.v&&(this.v=null,qN(this),GN(this),aA(19))},We.jb=function(e){e?(this.h.info("Successfully pinged google.com"),aA(2)):(this.h.info("Failed to ping google.com"),aA(1))},(We=iR.prototype).xa=function(){},We.wa=function(){},We.va=function(){},We.ua=function(){},We.Oa=function(){},sR.prototype.g=function(e,t){return new oR(e,t)},Mk(oR,OC),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(Ok(e.hb,e,t))),aA(0),e.W=t,e.aa=n||{},e.N=e.X,e.F=nR(e,null,e.W),$N(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)},Mk(aR,fA),Mk(cR,pA),Mk(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",OC.prototype.listen=OC.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,fR=yt,pR=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.5.0";const TR=new ef("@firebase/firestore");function ER(){return TR.logLevel}function SR(e,...t){var n;TR.logLevel<=Kh.DEBUG&&(n=t.map(AR),TR.debug(`Firestore (${IR}): ${e}`,...n))}function kR(e,...t){var n;TR.logLevel<=Kh.ERROR&&(n=t.map(AR),TR.error(`Firestore (${IR}): ${e}`,...n))}function CR(e,...t){var n;TR.logLevel<=Kh.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 kR(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 Error{constructor(e,t){super(t),this.code=e,this.message=t,this.name="FirebaseError",this.toString=()=>`${this.name}: [code=${this.code}]: ${this.message}`}}class DR{constructor(){this.promise=new Promise((e,t)=>{this.resolve=e,this.reject=t})}}class OR{constructor(e,t){this.user=t,this.type="OAuth",this.authHeaders={},this.authHeaders.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 DR;this.o=()=>{this.i++,this.currentUser=this.u(),s.resolve(),s=new DR,t.enqueueRetryable(()=>i(this.currentUser))};const o=()=>{const e=s;t.enqueueRetryable(async()=>{await e.promise,await i(this.currentUser)})},a=e=>{SR("FirebaseCredentialsProvider","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):(SR("FirebaseCredentialsProvider","Auth not yet detected"),s.resolve(),s=new DR))},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?(SR("FirebaseCredentialsProvider","getToken aborted due to token change."),this.getToken()):e?(RR("string"==typeof e.accessToken),new OR(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.h=e,this.l=t,this.m=n,this.type="FirstParty",this.user=bR.FIRST_PARTY}get authHeaders(){const e={"X-Goog-AuthUser":this.l},t=this.h.auth.getAuthHeaderValueForFirstParty([]);return t&&(e.Authorization=t),this.m&&(e["X-Goog-Iam-Authorization-Token"]=this.m),e}}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,t){this.previousValue=e,t&&(t.sequenceNumberHandler=e=>this.g(e),this.p=e=>t.writeSequenceNumber(e))}g(e){return this.previousValue=Math.max(e,this.previousValue),this.previousValue}next(){var e=++this.previousValue;return this.p&&this.p(e),e}}qR.T=-1;class VR{static I(){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 BR(e,t){return e<t?-1:t<e?1:0}function $R(e,n,r){return e.length===n.length&&e.every((e,t)=>r(e,n[t]))}function KR(e){return e+"\0"}class zR{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 zR.fromMillis(Date.now())}static fromDate(e){return zR.fromMillis(e.getTime())}static fromMillis(e){var t=Math.floor(e/1e3),n=Math.floor(1e6*(e-1e3*t));return new zR(t,n)}toDate(){return new Date(this.toMillis())}toMillis(){return 1e3*this.seconds+this.nanoseconds/1e6}_compareTo(e){return this.seconds===e.seconds?BR(this.nanoseconds,e.nanoseconds):BR(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 WR{constructor(e){this.timestamp=e}static fromTimestamp(e){return new WR(e)}static min(){return new WR(new zR(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 HR(e){let t=0;for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&t++;return t}function GR(e,t){for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&t(n,e[n])}function QR(e){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}class YR{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===YR.comparator(this,e)}child(e){const t=this.segments.slice(this.offset,this.limit());return e instanceof YR?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 JR extends YR{construct(e,t,n){return new JR(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 JR(t)}static emptyPath(){return new JR([])}}const XR=/^[_a-zA-Z][_a-zA-Z0-9]*$/;class ZR extends YR{construct(e,t,n){return new ZR(e,t,n)}static isValidIdentifier(e){return XR.test(e)}canonicalString(){return this.toArray().map(e=>(e=e.replace(/\\/g,"\\\\").replace(/`/g,"\\`"),e=!ZR.isValidIdentifier(e)?"`"+e+"`":e)).join(".")}toString(){return this.canonicalString()}isKeyField(){return 1===this.length&&"__name__"===this.get(0)}static keyField(){return new ZR(["__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 ZR(t)}static emptyPath(){return new ZR([])}}class eP{constructor(e){(this.fields=e).sort(ZR.comparator)}covers(e){for(const t of this.fields)if(t.isPrefixOf(e))return!0;return!1}isEqual(e){return $R(this.fields,e.fields,(e,t)=>e.isEqual(t))}}class tP{constructor(e){this.binaryString=e}static fromBase64String(e){var t=atob(e);return new tP(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 tP(t)}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 BR(this.binaryString,e.binaryString)}isEqual(e){return this.binaryString===e.binaryString}}tP.EMPTY_BYTE_STRING=new tP("");const nP=new RegExp(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.(\d+))?Z$/);function rP(t){if(RR(!!t),"string"!=typeof t)return{seconds:iP(t.seconds),nanos:iP(t.nanos)};{let e=0;var n=nP.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 iP(e){return"number"==typeof e?e:"string"==typeof e?Number(e):0}function sP(e){return"string"==typeof e?tP.fromBase64String(e):tP.fromUint8Array(e)}function oP(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 aP(e){var t=rP(e.mapValue.fields.__local_write_time__.timestampValue);return new zR(t.seconds,t.nanos)}function cP(e){return null==e}function lP(e){return 0===e&&1/e==-1/0}function uP(e){return"number"==typeof e&&Number.isInteger(e)&&!lP(e)&&e<=Number.MAX_SAFE_INTEGER&&e>=Number.MIN_SAFE_INTEGER}class hP{constructor(e){this.path=e}static fromPath(e){return new hP(JR.fromString(e))}static fromName(e){return new hP(JR.fromString(e).popFirst(5))}hasCollectionId(e){return 2<=this.path.length&&this.path.get(this.path.length-2)===e}isEqual(e){return null!==e&&0===JR.comparator(this.path,e.path)}toString(){return this.path.toString()}static comparator(e,t){return JR.comparator(e.path,t.path)}static isDocumentKey(e){return e.length%2==0}static fromSegments(e){return new hP(new JR(e.slice()))}}function dP(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?oP(e)?4:10:NR()}function fP(r,i){var e,t,n=dP(r);if(n!==dP(i))return!1;switch(n){case 0:return!0;case 1:return r.booleanValue===i.booleanValue;case 4:return aP(r).isEqual(aP(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=rP(r.timestampValue),n=rP(e.timestampValue);return t.seconds===n.seconds&&t.nanos===n.nanos}(i);case 5:return r.stringValue===i.stringValue;case 6:return t=i,sP(r.bytesValue).isEqual(sP(t.bytesValue));case 7:return r.referenceValue===i.referenceValue;case 8:return e=i,iP((t=r).geoPointValue.latitude)===iP(e.geoPointValue.latitude)&&iP(t.geoPointValue.longitude)===iP(e.geoPointValue.longitude);case 2:return function(e,t){if("integerValue"in e&&"integerValue"in t)return iP(e.integerValue)===iP(t.integerValue);if("doubleValue"in e&&"doubleValue"in t){var n=iP(e.doubleValue),r=iP(t.doubleValue);return n===r?lP(n)===lP(r):isNaN(n)&&isNaN(r)}return!1}(r,i);case 9:return $R(r.arrayValue.values||[],i.arrayValue.values||[],fP);case 10:return function(e){const t=e.mapValue.fields||{},n=i.mapValue.fields||{};if(HR(t)!==HR(n))return!1;for(const e in t)if(t.hasOwnProperty(e)&&(void 0===n[e]||!fP(t[e],n[e])))return!1;return!0}(r);default:return NR()}}function pP(e,t){return void 0!==(e.values||[]).find(e=>fP(e,t))}function gP(e,t){var n,r,i,s,o=dP(e),a=dP(t);if(o!==a)return BR(o,a);switch(o){case 0:return 0;case 1:return BR(e.booleanValue,t.booleanValue);case 2:return r=t,i=iP(e.integerValue||e.doubleValue),s=iP(r.integerValue||r.doubleValue),i<s?-1:s<i?1:i===s?0:isNaN(i)?isNaN(s)?0:-1:1;case 3:return mP(e.timestampValue,t.timestampValue);case 4:return mP(aP(e),aP(t));case 5:return BR(e.stringValue,t.stringValue);case 6:return function(e,t){const n=sP(e),r=sP(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=BR(n[i],r[i]);if(0!==t)return t}return BR(n.length,r.length)}(e.referenceValue,t.referenceValue);case 8:return n=e.geoPointValue,r=t.geoPointValue,0!==(s=BR(iP(n.latitude),iP(r.latitude)))?s:BR(iP(n.longitude),iP(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=gP(n[i],r[i]);if(t)return t}return BR(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=BR(r[a],s[a]);if(0!==t)return t;var o=gP(n[r[a]],i[s[a]]);if(0!==o)return o}return BR(r.length,s.length)}(e.mapValue,t.mapValue);default:throw NR()}}function mP(e,t){if("string"==typeof e&&"string"==typeof t&&e.length===t.length)return BR(e,t);var n=rP(e),r=rP(t),i=BR(n.seconds,r.seconds);return 0!==i?i:BR(n.nanos,r.nanos)}function vP(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=rP(e);return`time(${t.seconds},${t.nanos})`}(e.timestampValue):"stringValue"in e?e.stringValue:"bytesValue"in e?sP(e.bytesValue).toBase64():"referenceValue"in e?(t=e.referenceValue,hP.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 yP(e,t){return{referenceValue:`projects/${e.projectId}/databases/${e.database}/documents/${t.path.canonicalString()}`}}function _P(e){return e&&"integerValue"in e}function wP(e){return!!e&&"arrayValue"in e}function bP(e){return e&&"nullValue"in e}function IP(e){return e&&"doubleValue"in e&&isNaN(Number(e.doubleValue))}function TP(e){return e&&"mapValue"in e}function EP(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 GR(t.mapValue.fields,(e,t)=>n.mapValue.fields[e]=EP(t)),n}if(t.arrayValue){const r={arrayValue:{values:[]}};for(let e=0;e<(t.arrayValue.values||[]).length;++e)r.arrayValue.values[e]=EP(t.arrayValue.values[e]);return r}return Object.assign({},t)}class SP{constructor(e){this.value=e}static empty(){return new SP({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)],!TP(e))return null;return e=(e.mapValue.fields||{})[n.lastSegment()],e||null}}set(e,t){this.getFieldsMap(e.popLast())[e.lastSegment()]=EP(t)}setAll(e){let n=ZR.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()]=EP(e):i.push(t.lastSegment())});var t=this.getFieldsMap(n);this.applyChanges(t,r,i)}delete(e){const t=this.field(e.popLast());TP(t)&&t.mapValue.fields&&delete t.mapValue.fields[e.lastSegment()]}isEqual(e){return fP(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)];TP(e)&&e.mapValue.fields||(e={mapValue:{fields:{}}},n.mapValue.fields[t.get(r)]=e),n=e}return n.mapValue.fields}applyChanges(n,e,t){GR(e,(e,t)=>n[e]=t);for(const e of t)delete n[e]}clone(){return new SP(EP(this.value))}}class kP{constructor(e,t,n,r,i){this.key=e,this.documentType=t,this.version=n,this.data=r,this.documentState=i}static newInvalidDocument(e){return new kP(e,0,WR.min(),SP.empty(),0)}static newFoundDocument(e,t,n){return new kP(e,1,t,n,0)}static newNoDocument(e,t){return new kP(e,2,t,SP.empty(),0)}static newUnknownDocument(e,t){return new kP(e,3,t,SP.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=SP.empty(),this.documentState=0,this}convertToUnknownDocument(e){return this.version=e,this.documentType=3,this.data=SP.empty(),this.documentState=2,this}setHasCommittedMutations(){return this.documentState=2,this}setHasLocalMutations(){return this.documentState=1,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 kP&&this.key.isEqual(e.key)&&this.version.isEqual(e.version)&&this.documentType===e.documentType&&this.documentState===e.documentState&&this.data.isEqual(e.data)}clone(){return new kP(this.key,this.documentType,this.version,this.data.clone(),this.documentState)}toString(){return`Document(${this.key}, ${this.version}, ${JSON.stringify(this.data.value)}, {documentType: ${this.documentType}}), {documentState: ${this.documentState}})`}}class CP{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.A=null}}function AP(e,t=null,n=[],r=[],i=null,s=null,o=null){return new CP(e,t,n,r,i,s,o)}function NP(e){const t=e;if(null===t.A){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()+vP(e.value)}(e)).join(","),e+="|ob:",e+=t.orderBy.map(e=>function(e){return e.field.canonicalString()+e.dir}(e)).join(","),cP(t.limit)||(e+="|l:",e+=t.limit),t.startAt&&(e+="|lb:",e+=BP(t.startAt)),t.endAt&&(e+="|ub:",e+=BP(t.endAt)),t.A=e}return t.A}function RP(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)||!fP(i.value,s.value))return!1;return e.collectionGroup===t.collectionGroup&&!!e.path.isEqual(t.path)&&!!zP(e.startAt,t.startAt)&&zP(e.endAt,t.endAt)}function PP(e){return hP.isDocumentKey(e.path)&&null===e.collectionGroup&&0===e.filters.length}class xP 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.R(e,t,n):new DP(e,t,n):"array-contains"===t?new FP(e,n):"in"===t?new UP(e,n):"not-in"===t?new jP(e,n):"array-contains-any"===t?new qP(e,n):new xP(e,t,n)}static R(e,t,n){return new("in"===t?OP:LP)(e,n)}matches(e){var t=e.data.field(this.field);return"!="===this.op?null!==t&&this.P(gP(t,this.value)):null!==t&&dP(this.value)===dP(t)&&this.P(gP(t,this.value))}P(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()}}v(){return 0<=["<","<=",">",">=","!=","not-in"].indexOf(this.op)}}class DP extends xP{constructor(e,t,n){super(e,t,n),this.key=hP.fromName(n.referenceValue)}matches(e){var t=hP.comparator(e.key,this.key);return this.P(t)}}class OP extends xP{constructor(e,t){super(e,"in",t),this.keys=MP(0,t)}matches(t){return this.keys.some(e=>e.isEqual(t.key))}}class LP extends xP{constructor(e,t){super(e,"not-in",t),this.keys=MP(0,t)}matches(t){return!this.keys.some(e=>e.isEqual(t.key))}}function MP(e,t){var n;return((null===(n=t.arrayValue)||void 0===n?void 0:n.values)||[]).map(e=>hP.fromName(e.referenceValue))}class FP extends xP{constructor(e,t){super(e,"array-contains",t)}matches(e){var t=e.data.field(this.field);return wP(t)&&pP(t.arrayValue,this.value)}}class UP extends xP{constructor(e,t){super(e,"in",t)}matches(e){var t=e.data.field(this.field);return null!==t&&pP(this.value.arrayValue,t)}}class jP extends xP{constructor(e,t){super(e,"not-in",t)}matches(e){if(pP(this.value.arrayValue,{nullValue:"NULL_VALUE"}))return!1;var t=e.data.field(this.field);return null!==t&&!pP(this.value.arrayValue,t)}}class qP extends xP{constructor(e,t){super(e,"array-contains-any",t)}matches(e){const t=e.data.field(this.field);return!(!wP(t)||!t.arrayValue.values)&&t.arrayValue.values.some(e=>pP(this.value.arrayValue,e))}}class VP{constructor(e,t){this.position=e,this.before=t}}function BP(e){return`${e.before?"b":"a"}:${e.position.map(e=>vP(e)).join(",")}`}class $P{constructor(e,t="asc"){this.field=e,this.dir=t}}function KP(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()?hP.comparator(hP.fromName(o.referenceValue),n.key):gP(o,n.data.field(s.field)),"desc"===s.dir&&(r*=-1),0!==r)break}return e.before?r<=0:r<0}function zP(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(!fP(e.position[n],t.position[n]))return!1;return!0}class WP{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.V=null,this.S=null,this.startAt,this.endAt}}function HP(e,t,n,r,i,s,o,a){return new WP(e,t,n,r,i,s,o,a)}function GP(e){return new WP(e)}function QP(e){return!cP(e.limit)&&"F"===e.limitType}function YP(e){return!cP(e.limit)&&"L"===e.limitType}function JP(e){return 0<e.explicitOrderBy.length?e.explicitOrderBy[0].field:null}function XP(e){for(const t of e.filters)if(t.v())return t.field;return null}function ZP(e){return null!==e.collectionGroup}function ex(t){const n=t;if(null===n.V){n.V=[];const t=XP(n),e=JP(n);if(null!==t&&null===e)t.isKeyField()||n.V.push(new $P(t)),n.V.push(new $P(ZR.keyField(),"asc"));else{let e=!1;for(const r of n.explicitOrderBy)n.V.push(r),r.field.isKeyField()&&(e=!0);if(!e){const t=0<n.explicitOrderBy.length?n.explicitOrderBy[n.explicitOrderBy.length-1].dir:"asc";n.V.push(new $P(ZR.keyField(),t))}}}return n.V}function tx(e){const t=e;if(!t.S)if("F"===t.limitType)t.S=AP(t.path,t.collectionGroup,ex(t),t.filters,t.limit,t.startAt,t.endAt);else{const e=[];for(const i of ex(t)){const t="desc"===i.dir?"asc":"desc";e.push(new $P(i.field,t))}var n=t.endAt?new VP(t.endAt.position,!t.endAt.before):null,r=t.startAt?new VP(t.startAt.position,!t.startAt.before):null;t.S=AP(t.path,t.collectionGroup,e,t.filters,t.limit,n,r)}return t.S}function nx(e,t,n){return new WP(e.path,e.collectionGroup,e.explicitOrderBy.slice(),e.filters.slice(),t,n,e.startAt,e.endAt)}function rx(e,t){return RP(tx(e),tx(t))&&e.limitType===t.limitType}function ix(e){return`${NP(tx(e))}|lt:${e.limitType}`}function sx(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} ${vP(t.value)}`;var t}).join(", ")}]`),cP(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: "+BP(e.startAt)),e.endAt&&(t+=", endAt: "+BP(e.endAt)),`Target(${t})`}(tx(e))}; limitType=${e.limitType})`}function ox(n,e){return e.isFoundDocument()&&(t=n,i=(r=e).key.path,null!==t.collectionGroup?r.key.hasCollectionId(t.collectionGroup)&&t.path.isPrefixOf(i):hP.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||KP(e.startAt,ex(e),t))&&(!e.endAt||!KP(e.endAt,ex(e),t)));var t,r,i}function ax(i){return(e,t)=>{let n=!1;for(const r of ex(i)){const i=function(e,i,t){var n=e.field.isKeyField()?hP.comparator(i.key,t.key):function(e,t){var n=i.data.field(e),r=t.data.field(e);return null!==n&&null!==r?gP(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 cx(e,t){if(e.D){if(isNaN(t))return{doubleValue:"NaN"};if(t===1/0)return{doubleValue:"Infinity"};if(t===-1/0)return{doubleValue:"-Infinity"}}return{doubleValue:lP(t)?"-0":t}}function lx(e){return{integerValue:""+e}}function ux(e,t){return uP(t)?lx(t):cx(e,t)}class hx{constructor(){this._=void 0}}function dx(e,t){return e instanceof yx?_P(n=t)||n&&"doubleValue"in n?t:{integerValue:0}:null;var n}class fx extends hx{}class px extends hx{constructor(e){super(),this.elements=e}}function gx(e,t){const n=wx(t);for(const t of e.elements)n.some(e=>fP(e,t))||n.push(t);return{arrayValue:{values:n}}}class mx extends hx{constructor(e){super(),this.elements=e}}function vx(e,t){let n=wx(t);for(const t of e.elements)n=n.filter(e=>!fP(e,t));return{arrayValue:{values:n}}}class yx extends hx{constructor(e,t){super(),this.N=e,this.C=t}}function _x(e){return iP(e.integerValue||e.doubleValue)}function wx(e){return wP(e)&&e.arrayValue.values?e.arrayValue.values.slice():[]}class bx{constructor(e,t){this.field=e,this.transform=t}}class Ix{constructor(e,t){this.version=e,this.transformResults=t}}class Tx{constructor(e,t){this.updateTime=e,this.exists=t}static none(){return new Tx}static exists(e){return new Tx(void 0,e)}static updateTime(e){return new Tx(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 Ex(e,t){return void 0!==e.updateTime?t.isFoundDocument()&&t.version.isEqual(e.updateTime):void 0===e.exists||e.exists===t.isFoundDocument()}class Sx{}function kx(e,t,n){e instanceof Rx?function(e,t,n){const r=e.value.clone(),i=Dx(e.fieldTransforms,t,n.transformResults);r.setAll(i),t.convertToFoundDocument(n.version,r).setHasCommittedMutations()}(e,t,n):e instanceof Px?function(e,t,n){if(!Ex(e.precondition,t))return t.convertToUnknownDocument(n.version);const r=Dx(e.fieldTransforms,t,n.transformResults),i=t.data;i.setAll(xx(e)),i.setAll(r),t.convertToFoundDocument(n.version,i).setHasCommittedMutations()}(e,t,n):t.convertToNoDocument(n.version).setHasCommittedMutations()}function Cx(e,t,n){e instanceof Rx?function(e,t,n){if(Ex(e.precondition,t)){const r=e.value.clone(),i=Ox(e.fieldTransforms,n,t);r.setAll(i),t.convertToFoundDocument(Nx(t),r).setHasLocalMutations()}}(e,t,n):e instanceof Px?function(e,t,n){if(Ex(e.precondition,t)){const r=Ox(e.fieldTransforms,n,t),i=t.data;i.setAll(xx(e)),i.setAll(r),t.convertToFoundDocument(Nx(t),i).setHasLocalMutations()}}(e,t,n):(t=t,Ex(e.precondition,t)&&t.convertToNoDocument(WR.min()))}function Ax(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&&$R(n,r,(e,t)=>function(e,t){return e.field.isEqual(t.field)&&(e=e.transform,t=t.transform,e instanceof px&&t instanceof px||e instanceof mx&&t instanceof mx?$R(e.elements,t.elements,fP):e instanceof yx&&t instanceof yx?fP(e.C,t.C):e instanceof fx&&t instanceof fx)}(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 Nx(e){return e.isFoundDocument()?e.version:WR.min()}class Rx extends Sx{constructor(e,t,n,r=[]){super(),this.key=e,this.value=t,this.precondition=n,this.fieldTransforms=r,this.type=0}}class Px extends Sx{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 xx(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 Dx(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 px?gx(a,c):a instanceof mx?vx(a,c):l))}var a,c,l;return r}function Ox(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 fx?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 px?gx(i,s):i instanceof mx?vx(i,s):(a=dx(i=i,s),c=_x(a)+_x(i.C),_P(a)&&_P(i.C)?lx(c):cx(i.N,c))))}var i,s,o,a,c;return r}class Lx extends Sx{constructor(e,t){super(),this.key=e,this.precondition=t,this.type=2,this.fieldTransforms=[]}}class Mx extends Sx{constructor(e,t){super(),this.key=e,this.precondition=t,this.type=3,this.fieldTransforms=[]}}class Fx{constructor(e){this.count=e}}function Ux(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 jx(e){if(void 0===e)return kR("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 qx{constructor(e,t){this.comparator=e,this.root=t||Bx.EMPTY}insert(e,t){return new qx(this.comparator,this.root.insert(e,t,this.comparator).copy(null,null,Bx.BLACK,null,null))}remove(e){return new qx(this.comparator,this.root.remove(e,this.comparator).copy(null,null,Bx.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 Vx(this.root,null,this.comparator,!1)}getIteratorFrom(e){return new Vx(this.root,e,this.comparator,!1)}getReverseIterator(){return new Vx(this.root,null,this.comparator,!0)}getReverseIteratorFrom(e){return new Vx(this.root,e,this.comparator,!0)}}class Vx{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 Bx{constructor(e,t,n,r,i){this.key=e,this.value=t,this.color=null!=n?n:Bx.RED,this.left=null!=r?r:Bx.EMPTY,this.right=null!=i?i:Bx.EMPTY,this.size=this.left.size+1+this.right.size}copy(e,t,n,r,i){return new Bx(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 Bx.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 Bx.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,Bx.RED,null,this.right.left);return this.right.copy(null,null,this.color,e,null)}rotateRight(){var e=this.copy(null,null,Bx.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)}}Bx.EMPTY=null,Bx.RED=!0,Bx.BLACK=!1,Bx.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 Bx(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 $x{constructor(e){this.comparator=e,this.data=new qx(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 Kx(this.data.getIterator())}getIteratorFrom(e){return new Kx(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 $x))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 $x(this.comparator);return t.data=e,t}}class Kx{constructor(e){this.iter=e}getNext(){return this.iter.getNext().key}hasNext(){return this.iter.hasNext()}}const zx=new qx(hP.comparator);const Wx=new qx(hP.comparator);const Hx=new qx(hP.comparator);const Gx=new $x(hP.comparator);function Qx(...e){let t=Gx;for(const n of e)t=t.add(n);return t}const Yx=new $x(BR);class Jx{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,Xx.createSynthesizedTargetChangeForCurrentChange(e,t)),new Jx(WR.min(),n,Yx,zx,Qx())}}class Xx{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 Xx(tP.EMPTY_BYTE_STRING,t,Qx(),Qx(),Qx())}}class Zx{constructor(e,t,n,r){this.k=e,this.removedTargetIds=t,this.key=n,this.$=r}}class eD{constructor(e,t){this.targetId=e,this.O=t}}class tD{constructor(e,t,n=tP.EMPTY_BYTE_STRING,r=null){this.state=e,this.targetIds=t,this.resumeToken=n,this.cause=r}}class nD{constructor(){this.F=0,this.M=sD(),this.L=tP.EMPTY_BYTE_STRING,this.B=!1,this.U=!0}get current(){return this.B}get resumeToken(){return this.L}get q(){return 0!==this.F}get K(){return this.U}j(e){0<e.approximateByteSize()&&(this.U=!0,this.L=e)}W(){let n=Qx(),r=Qx(),i=Qx();return this.M.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 Xx(this.L,this.B,n,r,i)}G(){this.U=!1,this.M=sD()}H(e,t){this.U=!0,this.M=this.M.insert(e,t)}J(e){this.U=!0,this.M=this.M.remove(e)}Y(){this.F+=1}X(){--this.F}Z(){this.U=!0,this.B=!0}}class rD{constructor(e){this.tt=e,this.et=new Map,this.nt=zx,this.st=iD(),this.it=new $x(BR)}rt(e){for(const t of e.k)e.$&&e.$.isFoundDocument()?this.ot(t,e.$):this.ct(t,e.key,e.$);for(const n of e.removedTargetIds)this.ct(n,e.key,e.$)}at(n){this.forEachTarget(n,e=>{const t=this.ut(e);switch(n.state){case 0:this.ht(e)&&t.j(n.resumeToken);break;case 1:t.X(),t.q||t.G(),t.j(n.resumeToken);break;case 2:t.X(),t.q||this.removeTarget(e);break;case 3:this.ht(e)&&(t.Z(),t.j(n.resumeToken));break;case 4:this.ht(e)&&(this.lt(e),t.j(n.resumeToken));break;default:NR()}})}forEachTarget(e,n){0<e.targetIds.length?e.targetIds.forEach(n):this.et.forEach((e,t)=>{this.ht(t)&&n(t)})}ft(e){const t=e.targetId,n=e.O.count,r=this.dt(t);if(r){const e=r.target;if(PP(e))if(0===n){const n=new hP(e.path);this.ct(t,n,kP.newNoDocument(n,WR.min()))}else RR(1===n);else this.wt(t)!==n&&(this.lt(t),this.it=this.it.add(t))}}_t(r){const i=new Map;this.et.forEach((e,t)=>{var n=this.dt(t);if(n){if(e.current&&PP(n.target)){const i=new hP(n.target.path);null!==this.nt.get(i)||this.gt(t,i)||this.ct(t,i,kP.newNoDocument(i,r))}e.K&&(i.set(t,e.W()),e.G())}});let s=Qx();this.st.forEach((e,t)=>{let n=!0;t.forEachWhile(e=>{var t=this.dt(e);return!t||2===t.purpose||(n=!1)}),n&&(s=s.add(e))});var e=new Jx(r,i,this.it,this.nt,s);return this.nt=zx,this.st=iD(),this.it=new $x(BR),e}ot(e,t){var n;this.ht(e)&&(n=this.gt(e,t.key)?2:0,this.ut(e).H(t.key,n),this.nt=this.nt.insert(t.key,t),this.st=this.st.insert(t.key,this.yt(t.key).add(e)))}ct(e,t,n){if(this.ht(e)){const r=this.ut(e);this.gt(e,t)?r.H(t,1):r.J(t),this.st=this.st.insert(t,this.yt(t).delete(e)),n&&(this.nt=this.nt.insert(t,n))}}removeTarget(e){this.et.delete(e)}wt(e){var t=this.ut(e).W();return this.tt.getRemoteKeysForTarget(e).size+t.addedDocuments.size-t.removedDocuments.size}Y(e){this.ut(e).Y()}ut(e){let t=this.et.get(e);return t||(t=new nD,this.et.set(e,t)),t}yt(e){let t=this.st.get(e);return t||(t=new $x(BR),this.st=this.st.insert(e,t)),t}ht(e){var t=null!==this.dt(e);return t||SR("WatchChangeAggregator","Detected inactive target",e),t}dt(e){var t=this.et.get(e);return t&&t.q?null:this.tt.Tt(e)}lt(t){this.et.set(t,new nD),this.tt.getRemoteKeysForTarget(t).forEach(e=>{this.ct(t,e,null)})}gt(e,t){return this.tt.getRemoteKeysForTarget(e).has(t)}}function iD(){return new qx(hP.comparator)}function sD(){return new qx(hP.comparator)}const oD={asc:"ASCENDING",desc:"DESCENDING"},aD={"<":"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 cD{constructor(e,t){this.databaseId=e,this.D=t}}function lD(e,t){return e.D?`${new Date(1e3*t.seconds).toISOString().replace(/\.\d*/,"").replace("Z","")}.${("000000000"+t.nanoseconds).slice(-9)}Z`:{seconds:""+t.seconds,nanos:t.nanoseconds}}function uD(e,t){return e.D?t.toBase64():t.toUint8Array()}function hD(e){return RR(!!e),WR.fromTimestamp((t=rP(e),new zR(t.seconds,t.nanos)));var t}function dD(e,t){return e=e,new JR(["projects",e.projectId,"databases",e.database]).child("documents").child(t).canonicalString()}function fD(e){var t=JR.fromString(e);return RR(DD(t)),t}function pD(e,t){return dD(e.databaseId,t.path)}function gD(e,t){const n=fD(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 hP(_D(n))}function mD(e,t){return dD(e.databaseId,t)}function vD(e){var t=fD(e);return 4===t.length?JR.emptyPath():_D(t)}function yD(e){return new JR(["projects",e.databaseId.projectId,"databases",e.databaseId.database]).canonicalString()}function _D(e){return RR(4<e.length&&"documents"===e.get(4)),e.popFirst(5)}function wD(e,t,n){return{name:pD(e,t),fields:n.value.mapValue.fields}}function bD(e,t,n){const r=gD(e,t.name),i=hD(t.updateTime),s=new SP({mapValue:{fields:t.fields}}),o=kP.newFoundDocument(r,i,s);return n&&o.setHasCommittedMutations(),n?o.setHasCommittedMutations():o}function ID(e,t){let n;if(t instanceof Rx)n={update:wD(e,t.key,t.value)};else if(t instanceof Lx)n={delete:pD(e,t.key)};else if(t instanceof Px)n={update:wD(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 Mx))return NR();n={verify:pD(e,t.key)}}return 0<t.fieldTransforms.length&&(n.updateTransforms=t.fieldTransforms.map(e=>function(e){var t=e.transform;if(t instanceof fx)return{fieldPath:e.field.canonicalString(),setToServerValue:"REQUEST_TIME"};if(t instanceof px)return{fieldPath:e.field.canonicalString(),appendMissingElements:{values:t.elements}};if(t instanceof mx)return{fieldPath:e.field.canonicalString(),removeAllFromArray:{values:t.elements}};if(t instanceof yx)return{fieldPath:e.field.canonicalString(),increment:t.C};throw NR()}(e))),t.precondition.isNone||(n.currentDocument=void 0!==(r=t.precondition).updateTime?{updateTime:(t=r.updateTime,lD(e,t.toTimestamp()))}:void 0!==r.exists?{exists:r.exists}:NR()),n;var r}function TD(t,n){const e=n.currentDocument?void 0!==(i=n.currentDocument).updateTime?Tx.updateTime(hD(i.updateTime)):void 0!==i.exists?Tx.exists(i.exists):Tx.none():Tx.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 fx;else if("appendMissingElements"in t){const e=t.appendMissingElements.values||[];n=new px(e)}else if("removeAllFromArray"in t){const e=t.removeAllFromArray.values||[];n=new mx(e)}else"increment"in t?n=new yx(e,t.increment):NR();var r=ZR.fromServerFormat(t.fieldPath);return new bx(r,n)}(t,e)):[];var i;if(n.update){n.update.name;var s=gD(t,n.update.name),o=new SP({mapValue:{fields:n.update.fields}});if(n.updateMask){const t=function(){const e=n.updateMask.fieldPaths||[];return new eP(e.map(e=>ZR.fromServerFormat(e)))}();return new Px(s,o,t,e,r)}return new Rx(s,o,e,r)}if(n.delete){const r=gD(t,n.delete);return new Lx(r,e)}if(n.verify){const r=gD(t,n.verify);return new Mx(r,e)}return NR()}function ED(e,t){return{documents:[mD(e,t.path)]}}function SD(e,t){const n={structuredQuery:{}},r=t.path;null!==t.collectionGroup?(n.parent=mD(e,r),n.structuredQuery.from=[{collectionId:t.collectionGroup,allDescendants:!0}]):(n.parent=mD(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(IP(e.value))return{unaryFilter:{field:ND(e.field),op:"IS_NAN"}};if(bP(e.value))return{unaryFilter:{field:ND(e.field),op:"IS_NULL"}}}else if("!="===e.op){if(IP(e.value))return{unaryFilter:{field:ND(e.field),op:"IS_NOT_NAN"}};if(bP(e.value))return{unaryFilter:{field:ND(e.field),op:"IS_NOT_NULL"}}}return{fieldFilter:{field:ND(e.field),op:(t=e.op,aD[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:ND(e.field),direction:(e=e.dir,oD[e])}}(e))}(t.orderBy);i&&(n.structuredQuery.orderBy=i);var s,i=(s=t.limit,e.D||cP(s)?s:{value:s});return null!==i&&(n.structuredQuery.limit=i),t.startAt&&(n.structuredQuery.startAt=CD(t.startAt)),t.endAt&&(n.structuredQuery.endAt=CD(t.endAt)),n}function kD(e){let t=vD(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?[xD(e)]:void 0!==e.fieldFilter?[PD(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 $P(RD(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,cP(c="object"==typeof e?e.value:e)?null:c));let l=null;n.startAt&&(l=AD(n.startAt));let u=null;return n.endAt&&(u=AD(n.endAt)),HP(t,i,o,s,a,"F",l,u)}function CD(e){return{before:e.before,values:e.position}}function AD(e){var t=!!e.before,n=e.values||[];return new VP(n,t)}function ND(e){return{fieldPath:e.canonicalString()}}function RD(e){return ZR.fromServerFormat(e.fieldPath)}function PD(e){return xP.create(RD(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 xD(e){switch(e.unaryFilter.op){case"IS_NAN":var t=RD(e.unaryFilter.field);return xP.create(t,"==",{doubleValue:NaN});case"IS_NULL":t=RD(e.unaryFilter.field);return xP.create(t,"==",{nullValue:"NULL_VALUE"});case"IS_NOT_NAN":var n=RD(e.unaryFilter.field);return xP.create(n,"!=",{doubleValue:NaN});case"IS_NOT_NULL":n=RD(e.unaryFilter.field);return xP.create(n,"!=",{nullValue:"NULL_VALUE"});default:return NR()}}function DD(e){return 4<=e.length&&"projects"===e.get(0)&&"databases"===e.get(2)}function OD(e){let t="";for(let n=0;n<e.length;n++)0<t.length&&(t=LD(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 LD(t)}function LD(e){return e+""}function MD(t){const n=t.length;if(RR(2<=n),2===n)return RR(""===t.charAt(0)&&""===t.charAt(1)),JR.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 JR(i)}class FD{constructor(e,t){this.seconds=e,this.nanoseconds=t}}class UD{constructor(e,t,n){this.ownerId=e,this.allowTabSynchronization=t,this.leaseTimestampMs=n}}UD.store="owner",UD.key="owner";class jD{constructor(e,t,n){this.userId=e,this.lastAcknowledgedBatchId=t,this.lastStreamToken=n}}jD.store="mutationQueues",jD.keyPath="userId";class qD{constructor(e,t,n,r,i){this.userId=e,this.batchId=t,this.localWriteTimeMs=n,this.baseMutations=r,this.mutations=i}}qD.store="mutations",qD.keyPath="batchId",qD.userMutationsIndex="userMutationsIndex",qD.userMutationsKeyPath=["userId","batchId"];class VD{constructor(){}static prefixForUser(e){return[e]}static prefixForPath(e,t){return[e,OD(t)]}static key(e,t,n){return[e,OD(t),n]}}VD.store="documentMutations",VD.PLACEHOLDER=new VD;class BD{constructor(e,t){this.path=e,this.readTime=t}}class $D{constructor(e,t){this.path=e,this.version=t}}class KD{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}}KD.store="remoteDocuments",KD.readTimeIndex="readTimeIndex",KD.readTimeIndexPath="readTime",KD.collectionReadTimeIndex="collectionReadTimeIndex",KD.collectionReadTimeIndexPath=["parentPath","readTime"];class zD{constructor(e){this.byteSize=e}}zD.store="remoteDocumentGlobal",zD.key="remoteDocumentGlobalKey";class WD{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}}WD.store="targets",WD.keyPath="targetId",WD.queryTargetsIndexName="queryTargetsIndex",WD.queryTargetsKeyPath=["canonicalId","targetId"];class HD{constructor(e,t,n){this.targetId=e,this.path=t,this.sequenceNumber=n}}HD.store="targetDocuments",HD.keyPath=["targetId","path"],HD.documentTargetsIndex="documentTargetsIndex",HD.documentTargetsKeyPath=["path","targetId"];class GD{constructor(e,t,n,r){this.highestTargetId=e,this.highestListenSequenceNumber=t,this.lastRemoteSnapshotVersion=n,this.targetCount=r}}GD.key="targetGlobalKey",GD.store="targetGlobal";class QD{constructor(e,t){this.collectionId=e,this.parent=t}}QD.store="collectionParents",QD.keyPath=["collectionId","parent"];class YD{constructor(e,t,n,r){this.clientId=e,this.updateTimeMs=t,this.networkEnabled=n,this.inForeground=r}}YD.store="clientMetadata",YD.keyPath="clientId";class JD{constructor(e,t,n){this.bundleId=e,this.createTime=t,this.version=n}}JD.store="bundles",JD.keyPath="bundleId";class XD{constructor(e,t,n){this.name=e,this.readTime=t,this.bundledQuery=n}}XD.store="namedQueries",XD.keyPath="name";const ZD=[jD.store,qD.store,VD.store,KD.store,WD.store,UD.store,GD.store,HD.store,YD.store,zD.store,QD.store,JD.store,XD.store],eO="The current tab is not in the required state to perform this operation. It might be necessary to refresh the browser tab.";class tO{constructor(){this.onCommittedListeners=[]}addOnCommittedListener(e){this.onCommittedListeners.push(e)}raiseOnCommittedEvent(){this.onCommittedListeners.forEach(e=>e())}}class nO{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 nO((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 nO?t:nO.resolve(t)}catch(e){return nO.reject(e)}}wrapSuccess(e,t){return e?this.wrapUserFunction(()=>e(t)):nO.resolve(t)}wrapFailure(e,t){return e?this.wrapUserFunction(()=>e(t)):nO.reject(t)}static resolve(n){return new nO((e,t)=>{e(n)})}static reject(n){return new nO((e,t)=>{t(n)})}static waitFor(e){return new nO((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=nO.resolve(!1);for(const n of e)t=t.next(e=>e?nO.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 rO{constructor(n,e){this.action=n,this.transaction=e,this.aborted=!1,this.Et=new DR,this.transaction.oncomplete=()=>{this.Et.resolve()},this.transaction.onabort=()=>{e.error?this.Et.reject(new oO(n,e.error)):this.Et.resolve()},this.transaction.onerror=e=>{var t=hO(e.target.error);this.Et.reject(new oO(n,t))}}static open(e,t,n,r){try{return new rO(t,e.transaction(r,n))}catch(e){throw new oO(t,e)}}get It(){return this.Et.promise}abort(e){e&&this.Et.reject(e),this.aborted||(SR("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 cO(t)}}class iO{constructor(e,t,n){this.name=e,this.version=t,this.At=n,12.2===iO.Rt(sd())&&kR("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 SR("SimpleDb","Removing database:",e),lO(window.indexedDB.deleteDatabase(e)).toPromise()}static bt(){if(!dd())return!1;if(iO.Pt())return!0;const e=sd(),t=iO.Rt(e),n=0<t&&t<10,r=iO.vt(e),i=0<r&&r<4.5;return!(0<e.indexOf("MSIE ")||0<e.indexOf("Trident/")||0<e.indexOf("Edge/")||n||i)}static Pt(){var e;return"undefined"!=typeof process&&"YES"===(null===(e=process.env)||void 0===e?void 0:e.Vt)}static St(e,t){return e.store(t)}static Rt(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 vt(e){const t=e.match(/Android ([\d.]+)/i),n=t?t[1].split(".").slice(0,2).join("."):"-1";return Number(n)}async Dt(s){return this.db||(SR("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 oO(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 oO(s,t))},i.onupgradeneeded=e=>{SR("SimpleDb",'Database "'+this.name+'" requires upgrade from version:',e.oldVersion);var t=e.target.result;this.At.Ct(t,i.transaction,e.oldVersion,this.version).next(()=>{SR("SimpleDb","Database upgrade to version "+this.version+" complete")})}})),this.Nt&&(this.db.onversionchange=e=>this.Nt(e)),this.db}xt(t){this.Nt=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.Dt(e);const t=rO.open(this.db,e,i?"readonly":"readwrite",n),s=r(t).catch(e=>(t.abort(e),nO.reject(e))).toPromise();return s.catch(()=>{}),await t.It,s}catch(e){const t="FirebaseError"!==e.name&&s<3;if(SR("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 sO{constructor(e){this.kt=e,this.$t=!1,this.Ot=null}get isDone(){return this.$t}get Ft(){return this.Ot}set cursor(e){this.kt=e}done(){this.$t=!0}Mt(e){this.Ot=e}delete(){return lO(this.kt.delete())}}class oO extends xR{constructor(e,t){super(PR.UNAVAILABLE,`IndexedDB transaction '${e}' failed: ${t}`),this.name="IndexedDbTransactionError"}}function aO(e){return"IndexedDbTransactionError"===e.name}class cO{constructor(e){this.store=e}put(e,t){let n;return n=void 0!==t?(SR("SimpleDb","PUT",this.store.name,e,t),this.store.put(t,e)):(SR("SimpleDb","PUT",this.store.name,"<auto-key>",e),this.store.put(e)),lO(n)}add(e){return SR("SimpleDb","ADD",this.store.name,e,e),lO(this.store.add(e))}get(t){return lO(this.store.get(t)).next(e=>(SR("SimpleDb","GET",this.store.name,t,e=void 0===e?null:e),e))}delete(e){return SR("SimpleDb","DELETE",this.store.name,e),lO(this.store.delete(e))}count(){return SR("SimpleDb","COUNT",this.store.name),lO(this.store.count())}Lt(e,t){const n=this.cursor(this.options(e,t)),r=[];return this.Bt(n,(e,t)=>{r.push(t)}).next(()=>r)}Ut(e,t){SR("SimpleDb","DELETE ALL",this.store.name);const n=this.options(e,t);n.qt=!1;var r=this.cursor(n);return this.Bt(r,(e,t,n)=>n.delete())}Kt(e,t){let n;t?n=e:(n={},t=e);var r=this.cursor(n);return this.Bt(r,t)}jt(i){const e=this.cursor({});return new nO((n,r)=>{e.onerror=e=>{var t=hO(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()}})}Bt(e,s){const o=[];return new nO((i,t)=>{e.onerror=e=>{t(e.target.error)},e.onsuccess=e=>{const t=e.target.result;if(t){const n=new sO(t),r=s(t.primaryKey,t.value,n);if(r instanceof nO){const e=r.catch(e=>(n.done(),nO.reject(e)));o.push(e)}n.isDone?i():null===n.Ft?t.continue():t.continue(n.Ft)}else i()}}).next(()=>nO.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 lO(e){return new nO((n,r)=>{e.onsuccess=e=>{var t=e.target.result;n(t)},e.onerror=e=>{var t=hO(e.target.error);r(t)}})}let uO=!1;function hO(e){const t=iO.Rt(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 uO||(uO=!0,setTimeout(()=>{throw e},0)),e}}return e}class dO extends tO{constructor(e,t){super(),this.Qt=e,this.currentSequenceNumber=t}}function fO(e,t){var n=e;return iO.St(n.Qt,t)}class pO{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)&&kx(i,e,n[r])}}applyToLocalView(e){for(const t of this.baseMutations)t.key.isEqual(e.key)&&Cx(t,e,this.localWriteTime);for(const n of this.mutations)n.key.isEqual(e.key)&&Cx(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(WR.min())})}keys(){return this.mutations.reduce((e,t)=>e.add(t.key),Qx())}isEqual(e){return this.batchId===e.batchId&&$R(this.mutations,e.mutations,(e,t)=>Ax(e,t))&&$R(this.baseMutations,e.baseMutations,(e,t)=>Ax(e,t))}}class gO{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=Hx;var i=e.mutations;for(let s=0;s<i.length;s++)r=r.insert(i[s].key,n[s].version);return new gO(e,t,n,r)}}class mO{constructor(e,t,n,r,i=WR.min(),s=WR.min(),o=tP.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 mO(this.target,this.targetId,this.purpose,e,this.snapshotVersion,this.lastLimboFreeSnapshotVersion,this.resumeToken)}withResumeToken(e,t){return new mO(this.target,this.targetId,this.purpose,this.sequenceNumber,t,this.lastLimboFreeSnapshotVersion,e)}withLastLimboFreeSnapshotVersion(e){return new mO(this.target,this.targetId,this.purpose,this.sequenceNumber,this.snapshotVersion,e,this.resumeToken)}}class vO{constructor(e){this.Wt=e}}function yO(e,t){if(t.document)return bD(e.Wt,t.document,!!t.hasCommittedMutations);if(t.noDocument){const e=hP.fromSegments(t.noDocument.path),n=TO(t.noDocument.readTime),r=kP.newNoDocument(e,n);return t.hasCommittedMutations?r.setHasCommittedMutations():r}if(t.unknownDocument){const e=hP.fromSegments(t.unknownDocument.path),i=TO(t.unknownDocument.version);return kP.newUnknownDocument(e,i)}return NR()}function _O(e,t,n){var r=wO(n),i=t.key.path.popLast().toArray();if(t.isFoundDocument()){const s={name:pD(n=e.Wt,(e=t).key),fields:e.data.value.mapValue.fields,updateTime:lD(n,e.version.toTimestamp())},o=t.hasCommittedMutations;return new KD(null,null,s,o,r,i)}if(t.isNoDocument()){const a=t.key.path.toArray(),s=IO(t.version),c=t.hasCommittedMutations;return new KD(null,new BD(a,s),null,c,r,i)}if(t.isUnknownDocument()){const a=t.key.path.toArray(),s=IO(t.version);return new KD(new $D(a,s),null,null,!0,r,i)}return NR()}function wO(e){var t=e.toTimestamp();return[t.seconds,t.nanoseconds]}function bO(e){var t=new zR(e[0],e[1]);return WR.fromTimestamp(t)}function IO(e){var t=e.toTimestamp();return new FD(t.seconds,t.nanoseconds)}function TO(e){var t=new zR(e.seconds,e.nanoseconds);return WR.fromTimestamp(t)}function EO(t,e){const n=(e.baseMutations||[]).map(e=>TD(t.Wt,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=>TD(t.Wt,e)),i=zR.fromMillis(e.localWriteTimeMs);return new pO(e.batchId,i,n,r)}function SO(e){var t,n=TO(e.readTime),r=void 0!==e.lastLimboFreeSnapshotVersion?TO(e.lastLimboFreeSnapshotVersion):WR.min();let i;return i=void 0!==e.query.documents?(RR(1===(t=e.query).documents.length),tx(GP(vD(t.documents[0])))):tx(kD(e.query)),new mO(i,e.targetId,0,e.lastListenSequenceNumber,n,r,tP.fromBase64String(e.resumeToken))}function kO(e,t){var n=IO(t.snapshotVersion),r=IO(t.lastLimboFreeSnapshotVersion),i=(PP(t.target)?ED:SD)(e.Wt,t.target),s=t.resumeToken.toBase64();return new WD(t.targetId,NP(t.target),n,s,t.sequenceNumber,r,i)}function CO(e){var t=kD({parent:e.parent,structuredQuery:e.structuredQuery});return"LAST"===e.limitType?nx(t,t.limit,"L"):t}class AO{getBundleMetadata(e,t){return NO(e).get(t).next(e=>{if(e)return{id:(t=e).bundleId,createTime:TO(t.createTime),version:t.version};var t})}saveBundleMetadata(e,t){return NO(e).put({bundleId:(n=t).id,createTime:IO(hD(n.createTime)),version:n.version});var n}getNamedQuery(e,t){return RO(e).get(t).next(e=>{if(e)return{name:(t=e).name,query:CO(t.bundledQuery),readTime:TO(t.readTime)};var t})}saveNamedQuery(e,t){return RO(e).put({name:(t=t).name,readTime:IO(hD(t.readTime)),bundledQuery:t.bundledQuery})}}function NO(e){return fO(e,JD.store)}function RO(e){return fO(e,XD.store)}class PO{constructor(){this.Gt=new xO}addToCollectionParentIndex(e,t){return this.Gt.add(t),nO.resolve()}getCollectionParents(e,t){return nO.resolve(this.Gt.getEntries(t))}}class xO{constructor(){this.index={}}add(e){const t=e.lastSegment(),n=e.popLast(),r=this.index[t]||new $x(JR.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 $x(JR.comparator)).toArray()}}class DO{constructor(){this.zt=new xO}addToCollectionParentIndex(e,t){if(this.zt.has(t))return nO.resolve();var n=t.lastSegment(),r=t.popLast();e.addOnCommittedListener(()=>{this.zt.add(t)});r={collectionId:n,parent:OD(r)};return OO(e).put(r)}getCollectionParents(e,n){const r=[],t=IDBKeyRange.bound([n,""],[KR(n),""],!1,!0);return OO(e).Lt(t).next(e=>{for(const t of e){if(t.collectionId!==n)break;r.push(MD(t.parent))}return r})}}function OO(e){return fO(e,QD.store)}const LO={didRun:!1,sequenceNumbersCollected:0,targetsRemoved:0,documentsRemoved:0};class MO{constructor(e,t,n){this.cacheSizeCollectionThreshold=e,this.percentileToCollect=t,this.maximumSequenceNumbersToCollect=n}static withCacheSize(e){return new MO(e,MO.DEFAULT_COLLECTION_PERCENTILE,MO.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT)}}function FO(e,t,n){const r=e.store(qD.store),i=e.store(VD.store),s=[],o=IDBKeyRange.only(n.batchId);let a=0;const c=r.Kt({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=VD.key(t,e.key.path,n.batchId);s.push(i.delete(r)),l.push(e.key)}return nO.waitFor(s).next(()=>l)}function UO(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}MO.DEFAULT_COLLECTION_PERCENTILE=10,MO.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT=1e3,MO.DEFAULT=new MO(41943040,MO.DEFAULT_COLLECTION_PERCENTILE,MO.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT),MO.DISABLED=new MO(-1,0,0);class jO{constructor(e,t,n,r){this.userId=e,this.N=t,this.Ht=n,this.referenceDelegate=r,this.Jt={}}static Yt(e,t,n,r){RR(""!==e.uid);var i=e.isAuthenticated()?e.uid:"";return new jO(i,t,n,r)}checkEmpty(e){let r=!0;var t=IDBKeyRange.bound([this.userId,Number.NEGATIVE_INFINITY],[this.userId,Number.POSITIVE_INFINITY]);return VO(e).Kt({index:qD.userMutationsIndex,range:t},(e,t,n)=>{r=!1,n.done()}).next(()=>r)}addMutationBatch(u,h,d,f){const p=BO(u),g=VO(u);return g.add({}).next(e=>{RR("number"==typeof e);const t=new pO(e,h,d,f),n=(i=this.N,s=this.userId,o=t,a=o.baseMutations.map(e=>ID(i.Wt,e)),c=o.mutations.map(e=>ID(i.Wt,e)),new qD(s,o.batchId,o.localWriteTime.toMillis(),a,c)),r=[];var i,s,o,a,c;let l=new $x((e,t)=>BR(e.canonicalString(),t.canonicalString()));for(const u of f){const h=VD.key(this.userId,u.key.path,e);l=l.add(u.key.path.popLast()),r.push(g.put(n)),r.push(p.put(h,VD.PLACEHOLDER))}return l.forEach(e=>{r.push(this.Ht.addToCollectionParentIndex(u,e))}),u.addOnCommittedListener(()=>{this.Jt[e]=t.keys()}),nO.waitFor(r).next(()=>t)})}lookupMutationBatch(e,t){return VO(e).get(t).next(e=>e?(RR(e.userId===this.userId),EO(this.N,e)):null)}Xt(e,n){return this.Jt[n]?nO.resolve(this.Jt[n]):this.lookupMutationBatch(e,n).next(e=>{if(e){var t=e.keys();return this.Jt[n]=t}return null})}getNextMutationBatchAfterBatchId(e,t){const r=t+1,n=IDBKeyRange.lowerBound([this.userId,r]);let i=null;return VO(e).Kt({index:qD.userMutationsIndex,range:n},(e,t,n)=>{t.userId===this.userId&&(RR(t.batchId>=r),i=EO(this.N,t)),n.done()}).next(()=>i)}getHighestUnacknowledgedBatchId(e){var t=IDBKeyRange.upperBound([this.userId,Number.POSITIVE_INFINITY]);let r=-1;return VO(e).Kt({index:qD.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 VO(e).Lt(qD.userMutationsIndex,t).next(e=>e.map(e=>EO(this.N,e)))}getAllMutationBatchesAffectingDocumentKey(o,a){const e=VD.prefixForPath(this.userId,a.path),t=IDBKeyRange.lowerBound(e),c=[];return BO(o).Kt({range:t},(e,t,n)=>{var[r,i,s]=e,i=MD(i);if(r===this.userId&&a.path.isEqual(i))return VO(o).get(s).next(e=>{if(!e)throw NR();RR(e.userId===this.userId),c.push(EO(this.N,e))});n.done()}).next(()=>c)}getAllMutationBatchesAffectingDocumentKeys(t,e){let a=new $x(BR);const n=[];return e.forEach(o=>{var e=VD.prefixForPath(this.userId,o.path),e=IDBKeyRange.lowerBound(e),e=BO(t).Kt({range:e},(e,t,n)=>{var[r,i,s]=e,i=MD(i);r===this.userId&&o.path.isEqual(i)?a=a.add(s):n.done()});n.push(e)}),nO.waitFor(n).next(()=>this.Zt(t,a))}getAllMutationBatchesAffectingQuery(e,t){const o=t.path,a=o.length+1,n=VD.prefixForPath(this.userId,o),r=IDBKeyRange.lowerBound(n);let c=new $x(BR);return BO(e).Kt({range:r},(e,t,n)=>{var[r,i,s]=e,i=MD(i);r===this.userId&&o.isPrefixOf(i)?i.length===a&&(c=c.add(s)):n.done()}).next(()=>this.Zt(e,c))}Zt(t,e){const n=[],r=[];return e.forEach(e=>{r.push(VO(t).get(e).next(e=>{if(null===e)throw NR();RR(e.userId===this.userId),n.push(EO(this.N,e))}))}),nO.waitFor(r).next(()=>n)}removeMutationBatch(t,n){return FO(t.Qt,this.userId,n).next(e=>(t.addOnCommittedListener(()=>{this.te(n.batchId)}),nO.forEach(e,e=>this.referenceDelegate.markPotentiallyOrphaned(t,e))))}te(e){delete this.Jt[e]}performConsistencyCheck(n){return this.checkEmpty(n).next(e=>{if(!e)return nO.resolve();const t=IDBKeyRange.lowerBound(VD.prefixForUser(this.userId)),r=[];return BO(n).Kt({range:t},(e,t,n)=>{if(e[0]===this.userId){const t=MD(e[1]);r.push(t)}else n.done()}).next(()=>{RR(0===r.length)})})}containsKey(e,t){return qO(e,this.userId,t)}ee(e){return $O(e).get(this.userId).next(e=>e||new jD(this.userId,-1,""))}}function qO(e,s,t){const n=VD.prefixForPath(s,t.path),o=n[1],r=IDBKeyRange.lowerBound(n);let a=!1;return BO(e).Kt({range:r,qt:!0},(e,t,n)=>{var[r,i]=e;r===s&&i===o&&(a=!0),n.done()}).next(()=>a)}function VO(e){return fO(e,qD.store)}function BO(e){return fO(e,VD.store)}function $O(e){return fO(e,jD.store)}class KO{constructor(e){this.ne=e}next(){return this.ne+=2,this.ne}static se(){return new KO(0)}static ie(){return new KO(-1)}}class zO{constructor(e,t){this.referenceDelegate=e,this.N=t}allocateTargetId(n){return this.re(n).next(e=>{const t=new KO(e.highestTargetId);return e.highestTargetId=t.next(),this.oe(n,e).next(()=>e.highestTargetId)})}getLastRemoteSnapshotVersion(e){return this.re(e).next(e=>WR.fromTimestamp(new zR(e.lastRemoteSnapshotVersion.seconds,e.lastRemoteSnapshotVersion.nanoseconds)))}getHighestSequenceNumber(e){return this.re(e).next(e=>e.highestListenSequenceNumber)}setTargetsMetadata(t,n,r){return this.re(t).next(e=>(e.highestListenSequenceNumber=n,r&&(e.lastRemoteSnapshotVersion=r.toTimestamp()),n>e.highestListenSequenceNumber&&(e.highestListenSequenceNumber=n),this.oe(t,e)))}addTargetData(t,n){return this.ce(t,n).next(()=>this.re(t).next(e=>(e.targetCount+=1,this.ae(n,e),this.oe(t,e))))}updateTargetData(e,t){return this.ce(e,t)}removeTargetData(t,e){return this.removeMatchingKeysForTargetId(t,e.targetId).next(()=>WO(t).delete(e.targetId)).next(()=>this.re(t)).next(e=>(RR(0<e.targetCount),--e.targetCount,this.oe(t,e)))}removeTargets(r,i,s){let o=0;const a=[];return WO(r).Kt((e,t)=>{var n=SO(t);n.sequenceNumber<=i&&null===s.get(n.targetId)&&(o++,a.push(this.removeTargetData(r,n)))}).next(()=>nO.waitFor(a)).next(()=>o)}forEachTarget(e,r){return WO(e).Kt((e,t)=>{var n=SO(t);r(n)})}re(e){return HO(e).get(GD.key).next(e=>(RR(null!==e),e))}oe(e,t){return HO(e).put(GD.key,t)}ce(e,t){return WO(e).put(kO(this.N,t))}ae(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.re(e).next(e=>e.targetCount)}getTargetData(e,i){var t=NP(i),t=IDBKeyRange.bound([t,Number.NEGATIVE_INFINITY],[t,Number.POSITIVE_INFINITY]);let s=null;return WO(e).Kt({range:t,index:WD.queryTargetsIndexName},(e,t,n)=>{var r=SO(t);RP(i,r.target)&&(s=r,n.done())}).next(()=>s)}addMatchingKeys(n,e,r){const i=[],s=GO(n);return e.forEach(e=>{var t=OD(e.path);i.push(s.put(new HD(r,t))),i.push(this.referenceDelegate.addReference(n,r,e))}),nO.waitFor(i)}removeMatchingKeys(n,e,r){const i=GO(n);return nO.forEach(e,e=>{var t=OD(e.path);return nO.waitFor([i.delete([r,t]),this.referenceDelegate.removeReference(n,r,e)])})}removeMatchingKeysForTargetId(e,t){const n=GO(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=GO(e);let i=Qx();return r.Kt({range:n,qt:!0},(e,t,n)=>{var r=MD(e[1]),r=new hP(r);i=i.add(r)}).next(()=>i)}containsKey(e,t){var n=OD(t.path),n=IDBKeyRange.bound([n],[KR(n)],!1,!0);let r=0;return GO(e).Kt({index:HD.documentTargetsIndex,qt:!0,range:n},([e],t,n)=>{0!==e&&(r++,n.done())}).next(()=>0<r)}Tt(e,t){return WO(e).get(t).next(e=>e?SO(e):null)}}function WO(e){return fO(e,WD.store)}function HO(e){return fO(e,GD.store)}function GO(e){return fO(e,HD.store)}async function QO(e){if(e.code!==PR.FAILED_PRECONDITION||e.message!==eO)throw e;SR("LocalStore","Unexpectedly lost primary lease")}function YO([e,t],[n,r]){var i=BR(e,n);return 0===i?BR(t,r):i}class JO{constructor(e){this.ue=e,this.buffer=new $x(YO),this.he=0}le(){return++this.he}fe(e){var t=[e,this.le()];if(this.buffer.size<this.ue)this.buffer=this.buffer.add(t);else{const e=this.buffer.last();YO(t,e)<0&&(this.buffer=this.buffer.delete(e).add(t))}}get maxValue(){return this.buffer.last()[0]}}class XO{constructor(e,t){this.garbageCollector=e,this.asyncQueue=t,this.de=!1,this.we=null}start(e){-1!==this.garbageCollector.params.cacheSizeCollectionThreshold&&this._e(e)}stop(){this.we&&(this.we.cancel(),this.we=null)}get started(){return null!==this.we}_e(e){var t=this.de?3e5:6e4;SR("LruGarbageCollector",`Garbage collection scheduled in ${t}ms`),this.we=this.asyncQueue.enqueueAfterDelay("lru_garbage_collection",t,async()=>{this.we=null,this.de=!0;try{await e.collectGarbage(this.garbageCollector)}catch(e){aO(e)?SR("LruGarbageCollector","Ignoring IndexedDB error during garbage collection: ",e):await QO(e)}await this._e(e)})}}class ZO{constructor(e,t){this.me=e,this.params=t}calculateTargetCount(e,t){return this.me.ge(e).next(e=>Math.floor(t/100*e))}nthSequenceNumber(e,t){if(0===t)return nO.resolve(qR.T);const n=new JO(t);return this.me.forEachTarget(e,e=>n.fe(e.sequenceNumber)).next(()=>this.me.ye(e,e=>n.fe(e))).next(()=>n.maxValue)}removeTargets(e,t,n){return this.me.removeTargets(e,t,n)}removeOrphanedDocuments(e,t){return this.me.removeOrphanedDocuments(e,t)}collect(t,n){return-1===this.params.cacheSizeCollectionThreshold?(SR("LruGarbageCollector","Garbage collection skipped; disabled"),nO.resolve(LO)):this.getCacheSize(t).next(e=>e<this.params.cacheSizeCollectionThreshold?(SR("LruGarbageCollector",`Garbage collection skipped; Cache size ${e} is lower than threshold ${this.params.cacheSizeCollectionThreshold}`),LO):this.pe(t,n))}getCacheSize(e){return this.me.getCacheSize(e)}pe(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?(SR("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()<=Kh.DEBUG&&SR("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`),nO.resolve({didRun:!0,sequenceNumbersCollected:i,targetsRemoved:s,documentsRemoved:e})))}}class e1{constructor(e,t){this.db=e,this.garbageCollector=(e=this,t=t,new ZO(e,t))}ge(e){const n=this.Te(e);return this.db.getTargetCache().getTargetCount(e).next(t=>n.next(e=>t+e))}Te(e){let t=0;return this.ye(e,e=>{t++}).next(()=>t)}forEachTarget(e,t){return this.db.getTargetCache().forEachTarget(e,t)}ye(e,n){return this.Ee(e,(e,t)=>n(t))}addReference(e,t,n){return t1(e,n)}removeReference(e,t,n){return t1(e,n)}removeTargets(e,t,n){return this.db.getTargetCache().removeTargets(e,t,n)}markPotentiallyOrphaned(e,t){return t1(e,t)}Ie(t,n){let r=!1;return $O(t).jt(e=>qO(t,e,n).next(e=>(e&&(r=!0),nO.resolve(!e)))).next(()=>r)}removeOrphanedDocuments(n,r){const i=this.db.getRemoteDocumentCache().newChangeBuffer(),s=[];let o=0;return this.Ee(n,(t,e)=>{if(e<=r){const r=this.Ie(n,t).next(e=>{if(!e)return o++,i.getEntry(n,t).next(()=>(i.removeEntry(t),GO(n).delete([0,OD(t.path)])))});s.push(r)}}).next(()=>nO.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 t1(e,t)}Ee(e,r){const t=GO(e);let i,s=qR.T;return t.Kt({index:HD.documentTargetsIndex},([e],{path:t,sequenceNumber:n})=>{0===e?(s!==qR.T&&r(new hP(MD(i)),s),s=n,i=t):s=qR.T}).next(()=>{s!==qR.T&&r(new hP(MD(i)),s)})}getCacheSize(e){return this.db.getRemoteDocumentCache().getSize(e)}}function t1(e,t){return GO(e).put((t=t,e=e.currentSequenceNumber,new HD(0,OD(t.path),e)))}class n1{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){GR(this.inner,(e,t)=>{for(const[e,n]of t)r(e,n)})}isEmpty(){return QR(this.inner)}}class r1{constructor(){this.changes=new n1(e=>e.toString(),(e,t)=>e.isEqual(t)),this.changesApplied=!1}getReadTime(e){var t=this.changes.get(e);return t?t.readTime:WR.min()}addEntry(e,t){this.assertNotApplied(),this.changes.set(e.key,{document:e,readTime:t})}removeEntry(e,t=null){this.assertNotApplied(),this.changes.set(e,{document:kP.newInvalidDocument(e),readTime:t})}getEntry(e,t){this.assertNotApplied();var n=this.changes.get(t);return void 0!==n?nO.resolve(n.document):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 i1{constructor(e,t){this.N=e,this.Ht=t}addEntry(e,t,n){return a1(e).put(c1(t),n)}removeEntry(e,t){const n=a1(e),r=c1(t);return n.delete(r)}updateMetadata(t,n){return this.getMetadata(t).next(e=>(e.byteSize+=n,this.Ae(t,e)))}getEntry(e,t){return a1(e).get(c1(t)).next(e=>this.Re(t,e))}be(e,t){return a1(e).get(c1(t)).next(e=>({document:this.Re(t,e),size:UO(e)}))}getEntries(e,t){let r=zx;return this.Pe(e,t,(e,t)=>{var n=this.Re(e,t);r=r.insert(e,n)}).next(()=>r)}ve(e,t){let r=zx,i=new qx(hP.comparator);return this.Pe(e,t,(e,t)=>{var n=this.Re(e,t);r=r.insert(e,n),i=i.insert(e,UO(t))}).next(()=>({documents:r,Ve:i}))}Pe(e,t,i){if(t.isEmpty())return nO.resolve();const n=IDBKeyRange.bound(t.first().path.toArray(),t.last().path.toArray()),s=t.getIterator();let o=s.getNext();return a1(e).Kt({range:n},(e,t,n)=>{for(var r=hP.fromSegments(e);o&&hP.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.Mt(o.path.toArray()):n.done()}).next(()=>{for(;o;)i(o,null),o=s.hasNext()?s.getNext():null})}getDocumentsMatchingQuery(e,i,t){let s=zx;const o=i.path.length+1,n={};if(t.isEqual(WR.min())){const e=i.path.toArray();n.range=IDBKeyRange.lowerBound(e)}else{const e=i.path.toArray(),s=wO(t);n.range=IDBKeyRange.lowerBound([e,s],!0),n.index=KD.collectionReadTimeIndex}return a1(e).Kt(n,(e,t,n)=>{var r;e.length===o&&(r=yO(this.N,t),i.path.isPrefixOf(r.key.path)?ox(i,r)&&(s=s.insert(r.key,r)):n.done())}).next(()=>s)}newChangeBuffer(e){return new s1(this,!!e&&e.trackRemovals)}getSize(e){return this.getMetadata(e).next(e=>e.byteSize)}getMetadata(e){return o1(e).get(zD.key).next(e=>(RR(!!e),e))}Ae(e,t){return o1(e).put(zD.key,t)}Re(e,t){if(t){const e=yO(this.N,t);if(!e.isNoDocument()||!e.version.isEqual(WR.min()))return e}return kP.newInvalidDocument(e)}}class s1 extends r1{constructor(e,t){super(),this.Se=e,this.trackRemovals=t,this.De=new n1(e=>e.toString(),(e,t)=>e.isEqual(t))}applyChanges(s){const o=[];let a=0,c=new $x((e,t)=>BR(e.canonicalString(),t.canonicalString()));return this.changes.forEach((e,t)=>{var n=this.De.get(e);if(t.document.isValidDocument()){var r=_O(this.Se.N,t.document,this.getReadTime(e));c=c.add(e.path.popLast());var i=UO(r);a+=i-n,o.push(this.Se.addEntry(s,e,r))}else if(a-=n,this.trackRemovals){const a=_O(this.Se.N,kP.newNoDocument(e,WR.min()),this.getReadTime(e));o.push(this.Se.addEntry(s,e,a))}else o.push(this.Se.removeEntry(s,e))}),c.forEach(e=>{o.push(this.Se.Ht.addToCollectionParentIndex(s,e))}),o.push(this.Se.updateMetadata(s,a)),nO.waitFor(o)}getFromCache(e,t){return this.Se.be(e,t).next(e=>(this.De.set(t,e.size),e.document))}getAllFromCache(e,t){return this.Se.ve(e,t).next(({documents:e,Ve:t})=>(t.forEach((e,t)=>{this.De.set(e,t)}),e))}}function o1(e){return fO(e,zD.store)}function a1(e){return fO(e,KD.store)}function c1(e){return e.path.toArray()}class l1{constructor(e){this.N=e}Ct(t,n,e,r){RR(e<r&&0<=e&&r<=11);const i=new rO("createOrUpgrade",n);var s;e<1&&1<=r&&(t.createObjectStore(UD.store),(s=t).createObjectStore(jD.store,{keyPath:jD.keyPath}),s.createObjectStore(qD.store,{keyPath:qD.keyPath,autoIncrement:!0}).createIndex(qD.userMutationsIndex,qD.userMutationsKeyPath,{unique:!0}),s.createObjectStore(VD.store),u1(t),t.createObjectStore(KD.store));let o=nO.resolve();return e<3&&3<=r&&(0!==e&&((s=t).deleteObjectStore(HD.store),s.deleteObjectStore(WD.store),s.deleteObjectStore(GD.store),u1(t)),o=o.next(()=>function(){const e=i.store(GD.store),t=new GD(0,0,WR.min().toTimestamp(),0);return e.put(GD.key,t)}())),e<4&&4<=r&&(0!==e&&(o=o.next(()=>function(r,i){return i.store(qD.store).Lt().next(e=>{r.deleteObjectStore(qD.store),r.createObjectStore(qD.store,{keyPath:qD.keyPath,autoIncrement:!0}).createIndex(qD.userMutationsIndex,qD.userMutationsKeyPath,{unique:!0});const t=i.store(qD.store),n=e.map(e=>t.put(e));return nO.waitFor(n)})}(t,i))),o=o.next(()=>{t.createObjectStore(YD.store,{keyPath:YD.keyPath})})),e<5&&5<=r&&(o=o.next(()=>this.Ce(i))),e<6&&6<=r&&(o=o.next(()=>(t.createObjectStore(zD.store),this.Ne(i)))),e<7&&7<=r&&(o=o.next(()=>this.xe(i))),e<8&&8<=r&&(o=o.next(()=>this.ke(t,i))),e<9&&9<=r&&(o=o.next(()=>{var e;(e=t).objectStoreNames.contains("remoteDocumentChanges")&&e.deleteObjectStore("remoteDocumentChanges"),function(){const e=n.objectStore(KD.store);e.createIndex(KD.readTimeIndex,KD.readTimeIndexPath,{unique:!1}),e.createIndex(KD.collectionReadTimeIndex,KD.collectionReadTimeIndexPath,{unique:!1})}()})),e<10&&10<=r&&(o=o.next(()=>this.$e(i))),e<11&&11<=r&&(o=o.next(()=>{t.createObjectStore(JD.store,{keyPath:JD.keyPath}),t.createObjectStore(XD.store,{keyPath:XD.keyPath})})),o}Ne(t){let n=0;return t.store(KD.store).Kt((e,t)=>{n+=UO(t)}).next(()=>{var e=new zD(n);return t.store(zD.store).put(zD.key,e)})}Ce(r){const e=r.store(jD.store),t=r.store(qD.store);return e.Lt().next(e=>nO.forEach(e,n=>{var e=IDBKeyRange.bound([n.userId,-1],[n.userId,n.lastAcknowledgedBatchId]);return t.Lt(qD.userMutationsIndex,e).next(e=>nO.forEach(e,e=>{RR(e.userId===n.userId);var t=EO(this.N,e);return FO(r,n.userId,t).next(()=>{})}))}))}xe(e){const o=e.store(HD.store),t=e.store(KD.store);return e.store(GD.store).get(GD.key).next(i=>{const s=[];return t.Kt((e,t)=>{const n=new JR(e),r=[0,OD(n)];s.push(o.get(r).next(e=>e?nO.resolve():(e=>o.put(new HD(0,OD(e),i.highestListenSequenceNumber)))(n)))}).next(()=>nO.waitFor(s))})}ke(e,t){e.createObjectStore(QD.store,{keyPath:QD.keyPath});const n=t.store(QD.store),r=new xO,i=e=>{if(r.add(e)){const t=e.lastSegment(),r=e.popLast();return n.put({collectionId:t,parent:OD(r)})}};return t.store(KD.store).Kt({qt:!0},(e,t)=>{const n=new JR(e);return i(n.popLast())}).next(()=>t.store(VD.store).Kt({qt:!0},([,e],t)=>{const n=MD(e);return i(n.popLast())}))}$e(e){const r=e.store(WD.store);return r.Kt((e,t)=>{var n=SO(t),n=kO(this.N,n);return r.put(n)})}}function u1(e){e.createObjectStore(HD.store,{keyPath:HD.keyPath}).createIndex(HD.documentTargetsIndex,HD.documentTargetsKeyPath,{unique:!0}),e.createObjectStore(WD.store,{keyPath:WD.keyPath}).createIndex(WD.queryTargetsIndexName,WD.queryTargetsKeyPath,{unique:!0}),e.createObjectStore(GD.store)}const h1="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 d1{constructor(e,t,n,r,i,s,o,a,c,l){if(this.allowTabSynchronization=e,this.persistenceKey=t,this.clientId=n,this.Oe=i,this.window=s,this.document=o,this.Fe=c,this.Me=l,this.Le=null,this.Be=!1,this.isPrimary=!1,this.networkEnabled=!0,this.Ue=null,this.inForeground=!1,this.qe=null,this.Ke=null,this.je=Number.NEGATIVE_INFINITY,this.Qe=e=>Promise.resolve(),!d1.bt())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 e1(this,r),this.We=t+"main",this.N=new vO(a),this.Ge=new iO(this.We,11,new l1(this.N)),this.ze=new zO(this.referenceDelegate,this.N),this.Ht=new DO,this.He=(t=this.N,a=this.Ht,new i1(t,a)),this.Je=new AO,this.window&&this.window.localStorage?this.Ye=this.window.localStorage:(this.Ye=null,!1===l&&kR("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.Xe().then(()=>{if(!this.isPrimary&&!this.allowTabSynchronization)throw new xR(PR.FAILED_PRECONDITION,h1);return this.Ze(),this.tn(),this.en(),this.runTransaction("getHighestListenSequenceNumber","readonly",e=>this.ze.getHighestSequenceNumber(e))}).then(e=>{this.Le=new qR(e,this.Fe)}).then(()=>{this.Be=!0}).catch(e=>(this.Ge&&this.Ge.close(),Promise.reject(e)))}nn(t){return this.Qe=async e=>{if(this.started)return t(e)},t(this.isPrimary)}setDatabaseDeletedListener(t){this.Ge.xt(async e=>{null===e.newVersion&&await t()})}setNetworkEnabled(e){this.networkEnabled!==e&&(this.networkEnabled=e,this.Oe.enqueueAndForget(async()=>{this.started&&await this.Xe()}))}Xe(){return this.runTransaction("updateClientMetadataAndTryBecomePrimary","readwrite",t=>p1(t).put(new YD(this.clientId,Date.now(),this.networkEnabled,this.inForeground)).next(()=>{if(this.isPrimary)return this.sn(t).next(e=>{e||(this.isPrimary=!1,this.Oe.enqueueRetryable(()=>this.Qe(!1)))})}).next(()=>this.rn(t)).next(e=>this.isPrimary&&!e?this.on(t).next(()=>!1):!!e&&this.cn(t).next(()=>!0))).catch(e=>{if(aO(e))return SR("IndexedDbPersistence","Failed to extend owner lease: ",e),this.isPrimary;if(!this.allowTabSynchronization)throw e;return SR("IndexedDbPersistence","Releasing owner lease after error during lease refresh",e),!1}).then(e=>{this.isPrimary!==e&&this.Oe.enqueueRetryable(()=>this.Qe(e)),this.isPrimary=e})}sn(e){return f1(e).get(UD.key).next(e=>nO.resolve(this.an(e)))}un(e){return p1(e).delete(this.clientId)}async hn(){if(this.isPrimary&&!this.ln(this.je,18e5)){this.je=Date.now();var e=await this.runTransaction("maybeGarbageCollectMultiClientState","readwrite-primary",e=>{const r=fO(e,YD.store);return r.Lt().next(e=>{const t=this.fn(e,18e5),n=e.filter(e=>-1===t.indexOf(e));return nO.forEach(n,e=>r.delete(e.clientId)).next(()=>n)})}).catch(()=>[]);if(this.Ye)for(const t of e)this.Ye.removeItem(this.dn(t.clientId))}}en(){this.Ke=this.Oe.enqueueAfterDelay("client_metadata_refresh",4e3,()=>this.Xe().then(()=>this.hn()).then(()=>this.en()))}an(e){return!!e&&e.ownerId===this.clientId}rn(t){return this.Me?nO.resolve(!0):f1(t).get(UD.key).next(e=>{if(null!==e&&this.ln(e.leaseTimestampMs,5e3)&&!this.wn(e.ownerId)){if(this.an(e)&&this.networkEnabled)return!0;if(!this.an(e)){if(!e.allowTabSynchronization)throw new xR(PR.FAILED_PRECONDITION,h1);return!1}}return!(!this.networkEnabled||!this.inForeground)||p1(t).Lt().next(e=>void 0===this.fn(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&&SR("IndexedDbPersistence",`Client ${e?"is":"is not"} eligible for a primary lease.`),e))}async shutdown(){this.Be=!1,this._n(),this.Ke&&(this.Ke.cancel(),this.Ke=null),this.mn(),this.gn(),await this.Ge.runTransaction("shutdown","readwrite",[UD.store,YD.store],e=>{const t=new dO(e,qR.T);return this.on(t).next(()=>this.un(t))}),this.Ge.close(),this.yn()}fn(e,t){return e.filter(e=>this.ln(e.updateTimeMs,t)&&!this.wn(e.clientId))}pn(){return this.runTransaction("getActiveClients","readonly",e=>p1(e).Lt().next(e=>this.fn(e,18e5).map(e=>e.clientId)))}get started(){return this.Be}getMutationQueue(e){return jO.Yt(e,this.N,this.Ht,this.referenceDelegate)}getTargetCache(){return this.ze}getRemoteDocumentCache(){return this.He}getIndexManager(){return this.Ht}getBundleCache(){return this.Je}runTransaction(t,n,r){SR("IndexedDbPersistence","Starting transaction:",t);let i;return this.Ge.runTransaction(t,"readonly"===n?"readonly":"readwrite",ZD,e=>(i=new dO(e,this.Le?this.Le.next():qR.T),"readwrite-primary"===n?this.sn(i).next(e=>!!e||this.rn(i)).next(e=>{if(!e)throw kR(`Failed to obtain primary lease for action '${t}'.`),this.isPrimary=!1,this.Oe.enqueueRetryable(()=>this.Qe(!1)),new xR(PR.FAILED_PRECONDITION,eO);return r(i)}).next(e=>this.cn(i).next(()=>e)):this.Tn(i).next(()=>r(i)))).then(e=>(i.raiseOnCommittedEvent(),e))}Tn(e){return f1(e).get(UD.key).next(e=>{if(null!==e&&this.ln(e.leaseTimestampMs,5e3)&&!this.wn(e.ownerId)&&!this.an(e)&&!(this.Me||this.allowTabSynchronization&&e.allowTabSynchronization))throw new xR(PR.FAILED_PRECONDITION,h1)})}cn(e){var t=new UD(this.clientId,this.allowTabSynchronization,Date.now());return f1(e).put(UD.key,t)}static bt(){return iO.bt()}on(e){const t=f1(e);return t.get(UD.key).next(e=>this.an(e)?(SR("IndexedDbPersistence","Releasing primary lease."),t.delete(UD.key)):nO.resolve())}ln(e,t){var n=Date.now();return!(e<n-t||n<e&&(kR(`Detected an update time that is in the future: ${e} > ${n}`),1))}Ze(){null!==this.document&&"function"==typeof this.document.addEventListener&&(this.qe=()=>{this.Oe.enqueueAndForget(()=>(this.inForeground="visible"===this.document.visibilityState,this.Xe()))},this.document.addEventListener("visibilitychange",this.qe),this.inForeground="visible"===this.document.visibilityState)}mn(){this.qe&&(this.document.removeEventListener("visibilitychange",this.qe),this.qe=null)}tn(){var e;"function"==typeof(null===(e=this.window)||void 0===e?void 0:e.addEventListener)&&(this.Ue=()=>{this._n(),!ad()&&navigator.userAgent.includes("Safari")&&!navigator.userAgent.includes("Chrome")&&navigator.appVersion.match(/Version\/1[45]/)&&this.Oe.enterRestrictedMode(!0),this.Oe.enqueueAndForget(()=>this.shutdown())},this.window.addEventListener("pagehide",this.Ue))}gn(){this.Ue&&(this.window.removeEventListener("pagehide",this.Ue),this.Ue=null)}wn(e){var t;try{var n=null!==(null===(t=this.Ye)||void 0===t?void 0:t.getItem(this.dn(e)));return SR("IndexedDbPersistence",`Client '${e}' ${n?"is":"is not"} zombied in LocalStorage`),n}catch(e){return kR("IndexedDbPersistence","Failed to get zombied client id.",e),!1}}_n(){if(this.Ye)try{this.Ye.setItem(this.dn(this.clientId),String(Date.now()))}catch(e){kR("Failed to set zombie client id.",e)}}yn(){if(this.Ye)try{this.Ye.removeItem(this.dn(this.clientId))}catch(e){}}dn(e){return`firestore_zombie_${this.persistenceKey}_${e}`}}function f1(e){return fO(e,UD.store)}function p1(e){return fO(e,YD.store)}function g1(e,t){let n=e.projectId;return e.isDefaultDatabase||(n+="."+e.database),"firestore/"+t+"/"+n+"/"}class m1{constructor(e,t){this.progress=e,this.En=t}}class v1{constructor(e,t,n){this.He=e,this.In=t,this.Ht=n}An(t,n){return this.In.getAllMutationBatchesAffectingDocumentKey(t,n).next(e=>this.Rn(t,n,e))}Rn(e,t,n){return this.He.getEntry(e,t).next(e=>{for(const t of n)t.applyToLocalView(e);return e})}bn(e,n){e.forEach((e,t)=>{for(const e of n)e.applyToLocalView(t)})}Pn(t,e){return this.He.getEntries(t,e).next(e=>this.vn(t,e).next(()=>e))}vn(e,t){return this.In.getAllMutationBatchesAffectingDocumentKeys(e,t).next(e=>this.bn(t,e))}getDocumentsMatchingQuery(e,t,n){return r=t,hP.isDocumentKey(r.path)&&null===r.collectionGroup&&0===r.filters.length?this.Vn(e,t.path):ZP(t)?this.Sn(e,t,n):this.Dn(e,t,n);var r}Vn(e,t){return this.An(e,new hP(t)).next(e=>{let t=Wx;return e.isFoundDocument()&&(t=t.insert(e.key,e)),t})}Sn(r,i,s){const o=i.collectionGroup;let a=Wx;return this.Ht.getCollectionParents(r,o).next(e=>nO.forEach(e,e=>{var t,n=(t=i,e=e.child(o),new WP(e,null,t.explicitOrderBy.slice(),t.filters.slice(),t.limit,t.limitType,t.startAt,t.endAt));return this.Dn(r,n,s).next(e=>{e.forEach((e,t)=>{a=a.insert(e,t)})})}).next(()=>a))}Dn(t,n,e){let i,s;return this.He.getDocumentsMatchingQuery(t,n,e).next(e=>(i=e,this.In.getAllMutationBatchesAffectingQuery(t,n))).next(e=>(s=e,this.Cn(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=kP.newInvalidDocument(n),i=i.insert(n,e)),Cx(r,e,t.localWriteTime),e.isFoundDocument()||(i=i.remove(n))}}))).next(()=>(i.forEach((e,t)=>{ox(n,t)||(i=i.remove(e))}),i))}Cn(e,t,n){let r=Qx();for(const e of t)for(const t of e.mutations)t instanceof Px&&null===n.get(t.key)&&(r=r.add(t.key));let i=n;return this.He.getEntries(e,r).next(e=>(e.forEach((e,t)=>{t.isFoundDocument()&&(i=i.insert(e,t))}),i))}}class y1{constructor(e,t,n,r){this.targetId=e,this.fromCache=t,this.Nn=n,this.xn=r}static kn(e,t){let n=Qx(),r=Qx();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 y1(e,t.fromCache,n,r)}}class _1{$n(e){this.On=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(WR.min())?this.Fn(t,r):this.On.Pn(t,s).next(e=>{const n=this.Mn(r,e);return(QP(r)||YP(r))&&this.Ln(r.limitType,n,s,i)?this.Fn(t,r):(ER()<=Kh.DEBUG&&SR("QueryEngine","Re-using previous result from %s to execute query: %s",i.toString(),sx(r)),this.On.getDocumentsMatchingQuery(t,r,i).next(t=>(n.forEach(e=>{t=t.insert(e.key,e)}),t)))});var e}Mn(n,e){let r=new $x(ax(n));return e.forEach((e,t)=>{ox(n,t)&&(r=r.add(t))}),r}Ln(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))}Fn(e,t){return ER()<=Kh.DEBUG&&SR("QueryEngine","Using full collection scan to execute query:",sx(t)),this.On.getDocumentsMatchingQuery(e,t,WR.min())}}class w1{constructor(e,t,n,r){this.persistence=e,this.Bn=t,this.N=r,this.Un=new qx(BR),this.qn=new n1(e=>NP(e),RP),this.Kn=WR.min(),this.In=e.getMutationQueue(n),this.jn=e.getRemoteDocumentCache(),this.ze=e.getTargetCache(),this.Qn=new v1(this.jn,this.In,this.persistence.getIndexManager()),this.Je=e.getBundleCache(),this.Bn.$n(this.Qn)}collectGarbage(t){return this.persistence.runTransaction("Collect garbage","readwrite-primary",e=>t.collect(e,this.Un))}}function b1(e,t,n,r){return new w1(e,t,n,r)}async function I1(e,t){const n=e;let r=n.In,o=n.Qn;var i=await n.persistence.runTransaction("Handle user change","readonly",i=>{let s;return n.In.getAllMutationBatches(i).next(e=>(s=e,r=n.persistence.getMutationQueue(t),o=new v1(n.jn,r,n.persistence.getIndexManager()),r.getAllMutationBatches(i))).next(e=>{const t=[],n=[];let r=Qx();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.Pn(i,r).next(e=>({Wn:e,removedBatchIds:t,addedBatchIds:n}))})});return n.In=r,n.Qn=o,n.Bn.$n(n.Qn),i}function T1(e){const t=e;return t.persistence.runTransaction("Get last remote snapshot version","readonly",e=>t.ze.getLastRemoteSnapshotVersion(e))}function E1(e,n){const u=e,h=n.snapshotVersion;let d=u.Un;return u.persistence.runTransaction("Apply remote event","readwrite-primary",c=>{const e=u.jn.newChangeBuffer({trackRemovals:!0});d=u.Un;const l=[];n.targetChanges.forEach((e,t)=>{const n=d.get(t);if(n){l.push(u.ze.removeMatchingKeys(c,e.removedDocuments,t).next(()=>u.ze.addMatchingKeys(c,e.addedDocuments,t)));const a=e.resumeToken;var r,i,s,o;0<a.approximateByteSize()&&(r=n.withResumeToken(a,h).withSequenceNumber(c.currentSequenceNumber),d=d.insert(t,r),i=n,o=e,RR(0<(s=r).resumeToken.approximateByteSize()),0!==i.resumeToken.approximateByteSize()&&!(3e8<=s.snapshotVersion.toMicroseconds()-i.snapshotVersion.toMicroseconds()||0<o.addedDocuments.size+o.modifiedDocuments.size+o.removedDocuments.size)||l.push(u.ze.updateTargetData(c,r)))}});let t=zx;if(n.documentUpdates.forEach((e,t)=>{n.resolvedLimboDocuments.has(e)&&l.push(u.persistence.referenceDelegate.updateLimboDocument(c,e))}),l.push(S1(c,e,n.documentUpdates,h,void 0).next(e=>{t=e})),!h.isEqual(WR.min())){const n=u.ze.getLastRemoteSnapshotVersion(c).next(e=>u.ze.setTargetsMetadata(c,c.currentSequenceNumber,h));l.push(n)}return nO.waitFor(l).next(()=>e.apply(c)).next(()=>u.Qn.vn(c,t)).next(()=>t)}).then(e=>(u.Un=d,e))}function S1(e,o,t,a,c){let n=Qx();return t.forEach(e=>n=n.add(e)),o.getEntries(e,n).next(i=>{let s=zx;return t.forEach((e,t)=>{const n=i.get(e),r=(null==c?void 0:c.get(e))||a;t.isNoDocument()&&t.version.isEqual(WR.min())?(o.removeEntry(e,r),s=s.insert(e,t)):!n.isValidDocument()||0<t.version.compareTo(n.version)||0===t.version.compareTo(n.version)&&n.hasPendingWrites?(o.addEntry(t,r),s=s.insert(e,t)):SR("LocalStore","Ignoring outdated watch update for ",e,". Current version:",n.version," Watch version:",t.version)}),s})}function k1(e,r){const i=e;return i.persistence.runTransaction("Allocate target","readwrite",t=>{let n;return i.ze.getTargetData(t,r).next(e=>e?(n=e,nO.resolve(n)):i.ze.allocateTargetId(t).next(e=>(n=new mO(r,e,0,t.currentSequenceNumber),i.ze.addTargetData(t,n).next(()=>n))))}).then(e=>{var t=i.Un.get(e.targetId);return(null===t||0<e.snapshotVersion.compareTo(t.snapshotVersion))&&(i.Un=i.Un.insert(e.targetId,e),i.qn.set(r,e.targetId)),e})}async function C1(e,t,n){const r=e,i=r.Un.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(!aO(e))throw e;SR("LocalStore",`Failed to update sequence numbers for target ${t}: ${e}`)}r.Un=r.Un.remove(t),r.qn.delete(i.target)}function A1(e,n,r){const i=e;let s=WR.min(),o=Qx();return i.persistence.runTransaction("Execute query","readonly",t=>function(e,t,n){const r=e,i=r.qn.get(n);return void 0!==i?nO.resolve(r.Un.get(i)):r.ze.getTargetData(t,n)}(i,t,tx(n)).next(e=>{if(e)return s=e.lastLimboFreeSnapshotVersion,i.ze.getMatchingKeysForTargetId(t,e.targetId).next(e=>{o=e})}).next(()=>i.Bn.getDocumentsMatchingQuery(t,n,r?s:WR.min(),r?o:Qx())).next(e=>({documents:e,Gn:o})))}function N1(e,t){const n=e,r=n.ze,i=n.Un.get(t);return i?Promise.resolve(i.target):n.persistence.runTransaction("Get target data","readonly",e=>r.Tt(e,t).next(e=>e?e.target:null))}function R1(e){const n=e;return n.persistence.runTransaction("Get new document changes","readonly",e=>function(e,t,n){const r=e;let i=zx,s=wO(n);const o=a1(t),a=IDBKeyRange.lowerBound(s,!0);return o.Kt({index:KD.readTimeIndex,range:a},(e,t)=>{var n=yO(r.N,t);i=i.insert(n.key,n),s=t.readTime}).next(()=>({En:i,readTime:bO(s)}))}(n.jn,e,n.Kn)).then(({En:e,readTime:t})=>(n.Kn=t,e))}class P1{constructor(e){this.N=e,this.Yn=new Map,this.Xn=new Map}getBundleMetadata(e,t){return nO.resolve(this.Yn.get(t))}saveBundleMetadata(e,t){return this.Yn.set(t.id,{id:t.id,version:t.version,createTime:hD(t.createTime)}),nO.resolve()}getNamedQuery(e,t){return nO.resolve(this.Xn.get(t))}saveNamedQuery(e,t){return this.Xn.set(t.name,{name:(t=t).name,query:CO(t.bundledQuery),readTime:hD(t.readTime)}),nO.resolve()}}class x1{constructor(){this.Zn=new $x(D1.ts),this.es=new $x(D1.ns)}isEmpty(){return this.Zn.isEmpty()}addReference(e,t){var n=new D1(e,t);this.Zn=this.Zn.add(n),this.es=this.es.add(n)}ss(e,t){e.forEach(e=>this.addReference(e,t))}removeReference(e,t){this.rs(new D1(e,t))}os(e,t){e.forEach(e=>this.removeReference(e,t))}cs(e){const t=new hP(new JR([])),n=new D1(t,e),r=new D1(t,e+1),i=[];return this.es.forEachInRange([n,r],e=>{this.rs(e),i.push(e.key)}),i}us(){this.Zn.forEach(e=>this.rs(e))}rs(e){this.Zn=this.Zn.delete(e),this.es=this.es.delete(e)}hs(e){var t=new hP(new JR([])),n=new D1(t,e),t=new D1(t,e+1);let r=Qx();return this.es.forEachInRange([n,t],e=>{r=r.add(e.key)}),r}containsKey(e){var t=new D1(e,0),t=this.Zn.firstAfterOrEqual(t);return null!==t&&e.isEqual(t.key)}}class D1{constructor(e,t){this.key=e,this.ls=t}static ts(e,t){return hP.comparator(e.key,t.key)||BR(e.ls,t.ls)}static ns(e,t){return BR(e.ls,t.ls)||hP.comparator(e.key,t.key)}}class O1{constructor(e,t){this.Ht=e,this.referenceDelegate=t,this.In=[],this.fs=1,this.ds=new $x(D1.ts)}checkEmpty(e){return nO.resolve(0===this.In.length)}addMutationBatch(e,t,n,r){var i=this.fs;this.fs++,0<this.In.length&&this.In[this.In.length-1];var s=new pO(i,t,n,r);this.In.push(s);for(const t of r)this.ds=this.ds.add(new D1(t.key,i)),this.Ht.addToCollectionParentIndex(e,t.key.path.popLast());return nO.resolve(s)}lookupMutationBatch(e,t){return nO.resolve(this.ws(t))}getNextMutationBatchAfterBatchId(e,t){var n=this._s(t+1),n=n<0?0:n;return nO.resolve(this.In.length>n?this.In[n]:null)}getHighestUnacknowledgedBatchId(){return nO.resolve(0===this.In.length?-1:this.fs-1)}getAllMutationBatches(e){return nO.resolve(this.In.slice())}getAllMutationBatchesAffectingDocumentKey(e,t){const n=new D1(t,0),r=new D1(t,Number.POSITIVE_INFINITY),i=[];return this.ds.forEachInRange([n,r],e=>{var t=this.ws(e.ls);i.push(t)}),nO.resolve(i)}getAllMutationBatchesAffectingDocumentKeys(e,t){let r=new $x(BR);return t.forEach(e=>{var t=new D1(e,0),n=new D1(e,Number.POSITIVE_INFINITY);this.ds.forEachInRange([t,n],e=>{r=r.add(e.ls)})}),nO.resolve(this.gs(r))}getAllMutationBatchesAffectingQuery(e,t){const n=t.path,r=n.length+1;let i=n;hP.isDocumentKey(i)||(i=i.child(""));var s=new D1(new hP(i),0);let o=new $x(BR);return this.ds.forEachWhile(e=>{var t=e.key.path;return!!n.isPrefixOf(t)&&(t.length===r&&(o=o.add(e.ls)),!0)},s),nO.resolve(this.gs(o))}gs(e){const n=[];return e.forEach(e=>{var t=this.ws(e);null!==t&&n.push(t)}),n}removeMutationBatch(n,r){RR(0===this.ys(r.batchId,"removed")),this.In.shift();let i=this.ds;return nO.forEach(r.mutations,e=>{var t=new D1(e.key,r.batchId);return i=i.delete(t),this.referenceDelegate.markPotentiallyOrphaned(n,e.key)}).next(()=>{this.ds=i})}te(e){}containsKey(e,t){var n=new D1(t,0),n=this.ds.firstAfterOrEqual(n);return nO.resolve(t.isEqual(n&&n.key))}performConsistencyCheck(e){return this.In.length,nO.resolve()}ys(e,t){return this._s(e)}_s(e){return 0===this.In.length?0:e-this.In[0].batchId}ws(e){var t=this._s(e);return t<0||t>=this.In.length?null:this.In[t]}}class L1{constructor(e,t){this.Ht=e,this.ps=t,this.docs=new qx(hP.comparator),this.size=0}addEntry(e,t,n){const r=t.key,i=this.docs.get(r),s=i?i.size:0,o=this.ps(t);return this.docs=this.docs.insert(r,{document:t.clone(),size:o,readTime:n}),this.size+=o-s,this.Ht.addToCollectionParentIndex(e,r.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 nO.resolve(n?n.document.clone():kP.newInvalidDocument(t))}getEntries(e,t){let n=zx;return t.forEach(e=>{const t=this.docs.get(e);n=n.insert(e,t?t.document.clone():kP.newInvalidDocument(e))}),nO.resolve(n)}getDocumentsMatchingQuery(e,t,n){let r=zx;const i=new hP(t.path.child("")),s=this.docs.getIteratorFrom(i);for(;s.hasNext();){const{key:e,value:{document:i,readTime:o}}=s.getNext();if(!t.path.isPrefixOf(e.path))break;o.compareTo(n)<=0||ox(t,i)&&(r=r.insert(i.key,i.clone()))}return nO.resolve(r)}Ts(e,t){return nO.forEach(this.docs,e=>t(e))}newChangeBuffer(e){return new M1(this)}getSize(e){return nO.resolve(this.size)}}class M1 extends r1{constructor(e){super(),this.Se=e}applyChanges(n){const r=[];return this.changes.forEach((e,t)=>{t.document.isValidDocument()?r.push(this.Se.addEntry(n,t.document,this.getReadTime(e))):this.Se.removeEntry(e)}),nO.waitFor(r)}getFromCache(e,t){return this.Se.getEntry(e,t)}getAllFromCache(e,t){return this.Se.getEntries(e,t)}}class F1{constructor(e){this.persistence=e,this.Es=new n1(e=>NP(e),RP),this.lastRemoteSnapshotVersion=WR.min(),this.highestTargetId=0,this.Is=0,this.As=new x1,this.targetCount=0,this.Rs=KO.se()}forEachTarget(e,n){return this.Es.forEach((e,t)=>n(t)),nO.resolve()}getLastRemoteSnapshotVersion(e){return nO.resolve(this.lastRemoteSnapshotVersion)}getHighestSequenceNumber(e){return nO.resolve(this.Is)}allocateTargetId(e){return this.highestTargetId=this.Rs.next(),nO.resolve(this.highestTargetId)}setTargetsMetadata(e,t,n){return n&&(this.lastRemoteSnapshotVersion=n),t>this.Is&&(this.Is=t),nO.resolve()}ce(e){this.Es.set(e.target,e);var t=e.targetId;t>this.highestTargetId&&(this.Rs=new KO(t),this.highestTargetId=t),e.sequenceNumber>this.Is&&(this.Is=e.sequenceNumber)}addTargetData(e,t){return this.ce(t),this.targetCount+=1,nO.resolve()}updateTargetData(e,t){return this.ce(t),nO.resolve()}removeTargetData(e,t){return this.Es.delete(t.target),this.As.cs(t.targetId),--this.targetCount,nO.resolve()}removeTargets(n,r,i){let s=0;const o=[];return this.Es.forEach((e,t)=>{t.sequenceNumber<=r&&null===i.get(t.targetId)&&(this.Es.delete(e),o.push(this.removeMatchingKeysForTargetId(n,t.targetId)),s++)}),nO.waitFor(o).next(()=>s)}getTargetCount(e){return nO.resolve(this.targetCount)}getTargetData(e,t){var n=this.Es.get(t)||null;return nO.resolve(n)}addMatchingKeys(e,t,n){return this.As.ss(t,n),nO.resolve()}removeMatchingKeys(t,e,n){this.As.os(e,n);const r=this.persistence.referenceDelegate,i=[];return r&&e.forEach(e=>{i.push(r.markPotentiallyOrphaned(t,e))}),nO.waitFor(i)}removeMatchingKeysForTargetId(e,t){return this.As.cs(t),nO.resolve()}getMatchingKeysForTargetId(e,t){var n=this.As.hs(t);return nO.resolve(n)}containsKey(e,t){return nO.resolve(this.As.containsKey(t))}}class U1{constructor(e,t){var n;this.bs={},this.Le=new qR(0),this.Be=!1,this.Be=!0,this.referenceDelegate=e(this),this.ze=new F1(this),this.Ht=new PO,this.He=(n=this.Ht,e=e=>this.referenceDelegate.Ps(e),new L1(n,e)),this.N=new vO(t),this.Je=new P1(this.N)}start(){return Promise.resolve()}shutdown(){return this.Be=!1,Promise.resolve()}get started(){return this.Be}setDatabaseDeletedListener(){}setNetworkEnabled(){}getIndexManager(){return this.Ht}getMutationQueue(e){let t=this.bs[e.toKey()];return t||(t=new O1(this.Ht,this.referenceDelegate),this.bs[e.toKey()]=t),t}getTargetCache(){return this.ze}getRemoteDocumentCache(){return this.He}getBundleCache(){return this.Je}runTransaction(e,t,n){SR("MemoryPersistence","Starting transaction:",e);const r=new j1(this.Le.next());return this.referenceDelegate.vs(),n(r).next(e=>this.referenceDelegate.Vs(r).next(()=>e)).toPromise().then(e=>(r.raiseOnCommittedEvent(),e))}Ss(t,n){return nO.or(Object.values(this.bs).map(e=>()=>e.containsKey(t,n)))}}class j1 extends tO{constructor(e){super(),this.currentSequenceNumber=e}}class q1{constructor(e){this.persistence=e,this.Ds=new x1,this.Cs=null}static Ns(e){return new q1(e)}get xs(){if(this.Cs)return this.Cs;throw NR()}addReference(e,t,n){return this.Ds.addReference(n,t),this.xs.delete(n.toString()),nO.resolve()}removeReference(e,t,n){return this.Ds.removeReference(n,t),this.xs.add(n.toString()),nO.resolve()}markPotentiallyOrphaned(e,t){return this.xs.add(t.toString()),nO.resolve()}removeTarget(e,t){this.Ds.cs(t.targetId).forEach(e=>this.xs.add(e.toString()));const n=this.persistence.getTargetCache();return n.getMatchingKeysForTargetId(e,t.targetId).next(e=>{e.forEach(e=>this.xs.add(e.toString()))}).next(()=>n.removeTargetData(e,t))}vs(){this.Cs=new Set}Vs(n){const r=this.persistence.getRemoteDocumentCache().newChangeBuffer();return nO.forEach(this.xs,e=>{const t=hP.fromPath(e);return this.ks(n,t).next(e=>{e||r.removeEntry(t)})}).next(()=>(this.Cs=null,r.apply(n)))}updateLimboDocument(e,t){return this.ks(e,t).next(e=>{e?this.xs.delete(t.toString()):this.xs.add(t.toString())})}Ps(e){return 0}ks(e,t){return nO.or([()=>nO.resolve(this.Ds.containsKey(t)),()=>this.persistence.getTargetCache().containsKey(e,t),()=>this.persistence.Ss(e,t)])}}function V1(e,t){return`firestore_clients_${e}_${t}`}function B1(e,t,n){let r=`firestore_mutations_${e}_${n}`;return t.isAuthenticated()&&(r+=`_${t.uid}`),r}function $1(e,t){return`firestore_targets_${e}_${t}`}class K1{constructor(e,t,n,r){this.user=e,this.batchId=t,this.state=n,this.error=r}static $s(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 K1(e,t,r.state,i):(kR("SharedClientState",`Failed to parse mutation state for ID '${t}': ${n}`),null)}Os(){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,n){this.targetId=e,this.state=t,this.error=n}static $s(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 z1(e,n.state,r):(kR("SharedClientState",`Failed to parse target state for ID '${e}': ${t}`),null)}Os(){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 W1{constructor(e,t){this.clientId=e,this.activeTargetIds=t}static $s(e,t){var n=JSON.parse(t);let r="object"==typeof n&&n.activeTargetIds instanceof Array,i=Yx;for(let s=0;r&&s<n.activeTargetIds.length;++s)r=uP(n.activeTargetIds[s]),i=i.add(n.activeTargetIds[s]);return r?new W1(e,i):(kR("SharedClientState",`Failed to parse client data for instance '${e}': ${t}`),null)}}class H1{constructor(e,t){this.clientId=e,this.onlineState=t}static $s(e){var t=JSON.parse(e);return"object"==typeof t&&-1!==["Unknown","Online","Offline"].indexOf(t.onlineState)&&"string"==typeof t.clientId?new H1(t.clientId,t.onlineState):(kR("SharedClientState",`Failed to parse online state: ${e}`),null)}}class G1{constructor(){this.activeTargetIds=Yx}Fs(e){this.activeTargetIds=this.activeTargetIds.add(e)}Ms(e){this.activeTargetIds=this.activeTargetIds.delete(e)}Os(){var e={activeTargetIds:this.activeTargetIds.toArray(),updateTimeMs:Date.now()};return JSON.stringify(e)}}class Q1{constructor(e,t,n,r,i){this.window=e,this.Oe=t,this.persistenceKey=n,this.Ls=r,this.syncEngine=null,this.onlineStateHandler=null,this.sequenceNumberHandler=null,this.Bs=this.Us.bind(this),this.qs=new qx(BR),this.started=!1,this.Ks=[];var s=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");this.storage=this.window.localStorage,this.currentUser=i,this.js=V1(this.persistenceKey,this.Ls),this.Qs=`firestore_sequence_number_${this.persistenceKey}`,this.qs=this.qs.insert(this.Ls,new G1),this.Ws=new RegExp(`^firestore_clients_${s}_([^_]*)$`),this.Gs=new RegExp(`^firestore_mutations_${s}_(\\d+)(?:_(.*))?$`),this.zs=new RegExp(`^firestore_targets_${s}_(\\d+)$`),this.Hs=`firestore_online_state_${this.persistenceKey}`,this.Js=`firestore_bundle_loaded_${this.persistenceKey}`,this.window.addEventListener("storage",this.Bs)}static bt(e){return!(!e||!e.localStorage)}async start(){const e=await this.syncEngine.pn();for(const n of e)if(n!==this.Ls){const e=this.getItem(V1(this.persistenceKey,n));var t;!e||(t=W1.$s(n,e))&&(this.qs=this.qs.insert(t.clientId,t))}this.Ys();const n=this.storage.getItem(this.Hs);if(n){const e=this.Xs(n);e&&this.Zs(e)}for(const e of this.Ks)this.Us(e);this.Ks=[],this.window.addEventListener("pagehide",()=>this.shutdown()),this.started=!0}writeSequenceNumber(e){this.setItem(this.Qs,JSON.stringify(e))}getAllActiveQueryTargets(){return this.ti(this.qs)}isActiveQueryTarget(n){let r=!1;return this.qs.forEach((e,t)=>{t.activeTargetIds.has(n)&&(r=!0)}),r}addPendingMutation(e){this.ei(e,"pending")}updateMutationState(e,t,n){this.ei(e,t,n),this.ni(e)}addLocalQueryTarget(e){let t="not-current";var n;return this.isActiveQueryTarget(e)&&(!(n=this.storage.getItem($1(this.persistenceKey,e)))||(n=z1.$s(e,n))&&(t=n.state)),this.si.Fs(e),this.Ys(),t}removeLocalQueryTarget(e){this.si.Ms(e),this.Ys()}isLocalQueryTarget(e){return this.si.activeTargetIds.has(e)}clearQueryState(e){this.removeItem($1(this.persistenceKey,e))}updateQueryState(e,t,n){this.ii(e,t,n)}handleUserChange(e,t,n){t.forEach(e=>{this.ni(e)}),this.currentUser=e,n.forEach(e=>{this.addPendingMutation(e)})}setOnlineState(e){this.ri(e)}notifyBundleLoaded(){this.oi()}shutdown(){this.started&&(this.window.removeEventListener("storage",this.Bs),this.removeItem(this.js),this.started=!1)}getItem(e){var t=this.storage.getItem(e);return SR("SharedClientState","READ",e,t),t}setItem(e,t){SR("SharedClientState","SET",e,t),this.storage.setItem(e,t)}removeItem(e){SR("SharedClientState","REMOVE",e),this.storage.removeItem(e)}Us(e){const r=e;r.storageArea===this.storage&&(SR("SharedClientState","EVENT",r.key,r.newValue),r.key!==this.js?this.Oe.enqueueRetryable(async()=>{if(this.started){if(null!==r.key)if(this.Ws.test(r.key)){if(null==r.newValue){var e=this.ci(r.key);return this.ai(e,null)}e=this.ui(r.key,r.newValue);if(e)return this.ai(e.clientId,e)}else if(this.Gs.test(r.key)){if(null!==r.newValue){var t=this.hi(r.key,r.newValue);if(t)return this.li(t)}}else if(this.zs.test(r.key)){if(null!==r.newValue){t=this.fi(r.key,r.newValue);if(t)return this.di(t)}}else if(r.key===this.Hs){if(null!==r.newValue){var n=this.Xs(r.newValue);if(n)return this.Zs(n)}}else if(r.key===this.Qs){n=function(e){let t=qR.T;if(null!=e)try{var n=JSON.parse(e);RR("number"==typeof n),t=n}catch(e){kR("SharedClientState","Failed to read sequence number from WebStorage",e)}return t}(r.newValue);n!==qR.T&&this.sequenceNumberHandler(n)}else if(r.key===this.Js)return this.syncEngine.wi()}else this.Ks.push(r)}):kR("Received WebStorage notification for local change. Another client might have garbage-collected our state"))}get si(){return this.qs.get(this.Ls)}Ys(){this.setItem(this.js,this.si.Os())}ei(e,t,n){const r=new K1(this.currentUser,e,t,n),i=B1(this.persistenceKey,this.currentUser,e);this.setItem(i,r.Os())}ni(e){var t=B1(this.persistenceKey,this.currentUser,e);this.removeItem(t)}ri(e){var t={clientId:this.Ls,onlineState:e};this.storage.setItem(this.Hs,JSON.stringify(t))}ii(e,t,n){const r=$1(this.persistenceKey,e),i=new z1(e,t,n);this.setItem(r,i.Os())}oi(){this.setItem(this.Js,"value-not-used")}ci(e){var t=this.Ws.exec(e);return t?t[1]:null}ui(e,t){var n=this.ci(e);return W1.$s(n,t)}hi(e,t){var n=this.Gs.exec(e),r=Number(n[1]),n=void 0!==n[2]?n[2]:null;return K1.$s(new bR(n),r,t)}fi(e,t){var n=this.zs.exec(e),n=Number(n[1]);return z1.$s(n,t)}Xs(e){return H1.$s(e)}async li(e){if(e.user.uid===this.currentUser.uid)return this.syncEngine._i(e.batchId,e.state,e.error);SR("SharedClientState",`Ignoring mutation for non-active user ${e.user.uid}`)}di(e){return this.syncEngine.mi(e.targetId,e.state,e.error)}ai(e,t){const n=t?this.qs.insert(e,t):this.qs.remove(e),r=this.ti(this.qs),i=this.ti(n),s=[],o=[];return i.forEach(e=>{r.has(e)||s.push(e)}),r.forEach(e=>{i.has(e)||o.push(e)}),this.syncEngine.gi(s,o).then(()=>{this.qs=n})}Zs(e){this.qs.get(e.clientId)&&this.onlineStateHandler(e.onlineState)}ti(e){let n=Yx;return e.forEach((e,t)=>{n=n.unionWith(t.activeTargetIds)}),n}}class Y1{constructor(){this.yi=new G1,this.pi={},this.onlineStateHandler=null,this.sequenceNumberHandler=null}addPendingMutation(e){}updateMutationState(e,t,n){}addLocalQueryTarget(e){return this.yi.Fs(e),this.pi[e]||"not-current"}updateQueryState(e,t,n){this.pi[e]=t}removeLocalQueryTarget(e){this.yi.Ms(e)}isLocalQueryTarget(e){return this.yi.activeTargetIds.has(e)}clearQueryState(e){delete this.pi[e]}getAllActiveQueryTargets(){return this.yi.activeTargetIds}isActiveQueryTarget(e){return this.yi.activeTargetIds.has(e)}start(){return this.yi=new G1,Promise.resolve()}handleUserChange(e,t,n){}setOnlineState(e){}shutdown(){}writeSequenceNumber(e){}notifyBundleLoaded(){}}class J1{Ti(e){}shutdown(){}}class X1{constructor(){this.Ei=()=>this.Ii(),this.Ai=()=>this.Ri(),this.bi=[],this.Pi()}Ti(e){this.bi.push(e)}shutdown(){window.removeEventListener("online",this.Ei),window.removeEventListener("offline",this.Ai)}Pi(){window.addEventListener("online",this.Ei),window.addEventListener("offline",this.Ai)}Ii(){SR("ConnectivityMonitor","Network connectivity changed: AVAILABLE");for(const e of this.bi)e(0)}Ri(){SR("ConnectivityMonitor","Network connectivity changed: UNAVAILABLE");for(const e of this.bi)e(1)}static bt(){return"undefined"!=typeof window&&void 0!==window.addEventListener&&void 0!==window.removeEventListener}}const Z1={BatchGetDocuments:"batchGet",Commit:"commit",RunQuery:"runQuery"};class eL{constructor(e){this.vi=e.vi,this.Vi=e.Vi}Si(e){this.Di=e}Ci(e){this.Ni=e}onMessage(e){this.xi=e}close(){this.Vi()}send(e){this.vi(e)}ki(){this.Di()}$i(e){this.Ni(e)}Oi(e){this.xi(e)}}class tL extends class{constructor(e){this.databaseInfo=e,this.databaseId=e.databaseId;var t=e.ssl?"https":"http";this.Fi=t+"://"+e.host,this.Mi="projects/"+this.databaseId.projectId+"/databases/"+this.databaseId.database+"/documents"}Li(t,e,n,r){const i=this.Bi(t,e);SR("RestConnection","Sending: ",i,n);var s={};return this.Ui(s,r),this.qi(t,i,s,n).then(e=>(SR("RestConnection","Received: ",e),e),e=>{throw CR("RestConnection",`${t} failed with error: `,e,"url: ",i,"request:",n),e})}Ki(e,t,n,r){return this.Li(e,t,n,r)}Ui(e,t){if(e["X-Goog-Api-Client"]="gl-js/ fire/"+IR,e["Content-Type"]="text/plain",this.databaseInfo.appId&&(e["X-Firebase-GMPID"]=this.databaseInfo.appId),t)for(const n in t.authHeaders)t.authHeaders.hasOwnProperty(n)&&(e[n]=t.authHeaders[n])}Bi(e,t){var n=Z1[e];return`${this.Fi}/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(fR.COMPLETE,()=>{try{switch(o.getLastErrorCode()){case dR.NO_ERROR:var e=o.getResponseJson();SR("Connection","XHR received:",JSON.stringify(e)),i(e);break;case dR.TIMEOUT:SR("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(SR("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{SR("Connection",'RPC "'+a+'" completed.')}var r});var e=JSON.stringify(r);o.send(t,"POST",e,n,15)})}ji(e,t){const n=[this.Fi,"/","google.firestore.v1.Firestore","/",e,"/channel"],r=new sR,i=hR(),s={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&&(s.xmlHttpFactory=new vR({})),this.Ui(s.initMessageHeaders,t),od()||ld()||0<=sd().indexOf("Electron/")||ud()||0<=sd().indexOf("MSAppHost/")||cd()||(s.httpHeadersOverwriteParam="$httpHeaders");var o=n.join("");SR("Connection","Creating WebChannel: "+o,s);const a=r.createWebChannel(o,s);let c=!1,l=!1;const u=new eL({vi:e=>{l?SR("Connection","Not sending because WebChannel is closed:",e):(c||(SR("Connection","Opening WebChannel transport."),a.open(),c=!0),SR("Connection","WebChannel sending:",e),a.send(e))},Vi:()=>a.close()}),h=(e,t,n)=>{e.listen(t,e=>{try{n(e)}catch(e){setTimeout(()=>{throw e},0)}})};return h(a,yR.EventType.OPEN,()=>{l||SR("Connection","WebChannel transport opened.")}),h(a,yR.EventType.CLOSE,()=>{l||(l=!0,SR("Connection","WebChannel transport closed"),u.$i())}),h(a,yR.EventType.ERROR,e=>{l||(l=!0,CR("Connection","WebChannel transport errored:",e),u.$i(new xR(PR.UNAVAILABLE,"The operation could not be completed")))}),h(a,yR.EventType.MESSAGE,n=>{if(!l){var e=n.data[0];RR(!!e);var r=e.error||(null===(r=e[0])||void 0===r?void 0:r.error);if(r){SR("Connection","WebChannel received error:",r);const n=r.status;let e=function(e){var t=uR[e];if(void 0!==t)return jx(t)}(n),t=r.message;void 0===e&&(e=PR.INTERNAL,t="Unknown error status: "+n+" with message "+r.message),l=!0,u.$i(new xR(e,t)),a.close()}else SR("Connection","WebChannel received:",e),u.Oi(e)}}),h(i,pR.STAT_EVENT,e=>{e.stat===gR?SR("Connection","Detected buffering proxy"):e.stat===mR&&SR("Connection","Detected no buffering proxy")}),setTimeout(()=>{u.ki()},0),u}}function nL(){return"undefined"!=typeof window?window:null}function rL(){return"undefined"!=typeof document?document:null}function iL(e){return new cD(e,!0)}class sL{constructor(e,t,n=1e3,r=1.5,i=6e4){this.Oe=e,this.timerId=t,this.Qi=n,this.Wi=r,this.Gi=i,this.zi=0,this.Hi=null,this.Ji=Date.now(),this.reset()}reset(){this.zi=0}Yi(){this.zi=this.Gi}Xi(e){this.cancel();var t=Math.floor(this.zi+this.Zi()),n=Math.max(0,Date.now()-this.Ji),r=Math.max(0,t-n);0<r&&SR("ExponentialBackoff",`Backing off for ${r} ms (base delay: ${this.zi} ms, delay with jitter: ${t} ms, last attempt: ${n} ms ago)`),this.Hi=this.Oe.enqueueAfterDelay(this.timerId,r,()=>(this.Ji=Date.now(),e())),this.zi*=this.Wi,this.zi<this.Qi&&(this.zi=this.Qi),this.zi>this.Gi&&(this.zi=this.Gi)}tr(){null!==this.Hi&&(this.Hi.skipDelay(),this.Hi=null)}cancel(){null!==this.Hi&&(this.Hi.cancel(),this.Hi=null)}Zi(){return(Math.random()-.5)*this.zi}}class oL{constructor(e,t,n,r,i,s,o){this.Oe=e,this.er=n,this.nr=r,this.sr=i,this.credentialsProvider=s,this.listener=o,this.state=0,this.ir=0,this.rr=null,this.cr=null,this.stream=null,this.ar=new sL(e,t)}ur(){return 1===this.state||5===this.state||this.hr()}hr(){return 2===this.state||3===this.state}start(){4!==this.state?this.auth():this.lr()}async stop(){this.ur()&&await this.close(0)}dr(){this.state=0,this.ar.reset()}wr(){this.hr()&&null===this.rr&&(this.rr=this.Oe.enqueueAfterDelay(this.er,6e4,()=>this._r()))}mr(e){this.gr(),this.stream.send(e)}async _r(){if(this.hr())return this.close(0)}gr(){this.rr&&(this.rr.cancel(),this.rr=null)}yr(){this.cr&&(this.cr.cancel(),this.cr=null)}async close(e,t){this.gr(),this.yr(),this.ar.cancel(),this.ir++,4!==e?this.ar.reset():t&&t.code===PR.RESOURCE_EXHAUSTED?(kR(t.toString()),kR("Using maximum backoff delay to prevent overloading the backend."),this.ar.Yi()):t&&t.code===PR.UNAUTHENTICATED&&3!==this.state&&this.credentialsProvider.invalidateToken(),null!==this.stream&&(this.pr(),this.stream.close(),this.stream=null),this.state=e,await this.listener.Ci(t)}pr(){}auth(){this.state=1;const e=this.Tr(this.ir),t=this.ir;this.credentialsProvider.getToken().then(e=>{this.ir===t&&this.Er(e)},t=>{e(()=>{var e=new xR(PR.UNKNOWN,"Fetching auth token failed: "+t.message);return this.Ir(e)})})}Er(e){const t=this.Tr(this.ir);this.stream=this.Ar(e),this.stream.Si(()=>{t(()=>(this.state=2,this.cr=this.Oe.enqueueAfterDelay(this.nr,1e4,()=>(this.hr()&&(this.state=3),Promise.resolve())),this.listener.Si()))}),this.stream.Ci(e=>{t(()=>this.Ir(e))}),this.stream.onMessage(e=>{t(()=>this.onMessage(e))})}lr(){this.state=5,this.ar.Xi(async()=>{this.state=0,this.start()})}Ir(e){return SR("PersistentStream",`close with error: ${e}`),this.stream=null,this.close(4,e)}Tr(t){return e=>{this.Oe.enqueueAndForget(()=>this.ir===t?e():(SR("PersistentStream","stream callback skipped by getCloseGuardedDispatcher."),Promise.resolve()))}}}class aL extends oL{constructor(e,t,n,r,i){super(e,"listen_stream_connection_backoff","listen_stream_idle","health_check_timeout",t,n,i),this.N=r}Ar(e){return this.sr.ji("Listen",e)}onMessage(e){this.ar.reset();var t=function(e,t){let n;if("targetChange"in t){t.targetChange;var r="NO_CHANGE"===(f=t.targetChange.targetChangeType||"NO_CHANGE")?0:"ADD"===f?1:"REMOVE"===f?2:"CURRENT"===f?3:"RESET"===f?4:NR(),i=t.targetChange.targetIds||[],s=(f=t.targetChange.resumeToken,e.D?(RR(void 0===f||"string"==typeof f),tP.fromBase64String(f||"")):(RR(void 0===f||f instanceof Uint8Array),tP.fromUint8Array(f||new Uint8Array))),o=t.targetChange.cause,a=o&&(a=void 0===(f=o).code?PR.UNKNOWN:jx(f.code),new xR(a,f.message||""));n=new tD(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=gD(e,c.document.name),l=hD(c.document.updateTime),u=new SP({mapValue:{fields:c.document.fields}}),l=kP.newFoundDocument(a,l,u),u=c.targetIds||[],c=c.removedTargetIds||[];n=new Zx(u,c,l.key,l)}else if("documentDelete"in t){t.documentDelete;u=t.documentDelete;u.document;c=gD(e,u.document),l=u.readTime?hD(u.readTime):WR.min(),l=kP.newNoDocument(c,l),u=u.removedTargetIds||[];n=new Zx([],u,l.key,l)}else if("documentRemove"in t){t.documentRemove;var h=t.documentRemove;h.document;var d=gD(e,h.document),h=h.removedTargetIds||[];n=new Zx([],h,d,null)}else{if(!("filter"in t))return NR();{t.filter;const e=t.filter;e.targetId;h=e.count||0,d=new Fx(h),h=e.targetId;n=new eD(h,d)}}var a,f;return n}(this.N,e),n=function(e){if(!("targetChange"in e))return WR.min();var t=e.targetChange;return(!t.targetIds||!t.targetIds.length)&&t.readTime?hD(t.readTime):WR.min()}(e);return this.listener.Rr(t,n)}br(e){const t={};t.database=yD(this.N),t.addTarget=function(e,t){let n;var r=t.target;return n=PP(r)?{documents:ED(e,r)}:{query:SD(e,r)},n.targetId=t.targetId,0<t.resumeToken.approximateByteSize()?n.resumeToken=uD(e,t.resumeToken):0<t.snapshotVersion.compareTo(WR.min())&&(n.readTime=lD(e,t.snapshotVersion.toTimestamp())),n}(this.N,e);var n,r,r=(this.N,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.mr(t)}Pr(e){const t={};t.database=yD(this.N),t.removeTarget=e,this.mr(t)}}class cL extends oL{constructor(e,t,n,r,i){super(e,"write_stream_connection_backoff","write_stream_idle","health_check_timeout",t,n,i),this.N=r,this.vr=!1}get Vr(){return this.vr}start(){this.vr=!1,this.lastStreamToken=void 0,super.start()}pr(){this.vr&&this.Sr([])}Ar(e){return this.sr.ji("Write",e)}onMessage(e){if(RR(!!e.streamToken),this.lastStreamToken=e.streamToken,this.vr){this.ar.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?hD(e.updateTime):hD(t);return n.isEqual(WR.min())&&(n=hD(t)),new Ix(n,e.transformResults||[])}(e,i))):[]),n=hD(e.commitTime);return this.listener.Dr(n,t)}var r,i;return RR(!e.writeResults||0===e.writeResults.length),this.vr=!0,this.listener.Cr()}Nr(){const e={};e.database=yD(this.N),this.mr(e)}Sr(e){var t={streamToken:this.lastStreamToken,writes:e.map(e=>ID(this.N,e))};this.mr(t)}}class lL extends class{}{constructor(e,t,n){super(),this.credentials=e,this.sr=t,this.N=n,this.kr=!1}$r(){if(this.kr)throw new xR(PR.FAILED_PRECONDITION,"The client has already been terminated.")}Li(t,n,r){return this.$r(),this.credentials.getToken().then(e=>this.sr.Li(t,n,r,e)).catch(e=>{throw"FirebaseError"===e.name?(e.code===PR.UNAUTHENTICATED&&this.credentials.invalidateToken(),e):new xR(PR.UNKNOWN,e.toString())})}Ki(t,n,r){return this.$r(),this.credentials.getToken().then(e=>this.sr.Ki(t,n,r,e)).catch(e=>{throw"FirebaseError"===e.name?(e.code===PR.UNAUTHENTICATED&&this.credentials.invalidateToken(),e):new xR(PR.UNKNOWN,e.toString())})}terminate(){this.kr=!0}}class uL{constructor(e,t){this.asyncQueue=e,this.onlineStateHandler=t,this.state="Unknown",this.Or=0,this.Fr=null,this.Mr=!0}Lr(){0===this.Or&&(this.Br("Unknown"),this.Fr=this.asyncQueue.enqueueAfterDelay("online_state_timeout",1e4,()=>(this.Fr=null,this.Ur("Backend didn't respond within 10 seconds."),this.Br("Offline"),Promise.resolve())))}qr(e){"Online"===this.state?this.Br("Unknown"):(this.Or++,1<=this.Or&&(this.Kr(),this.Ur(`Connection failed 1 times. Most recent error: ${e.toString()}`),this.Br("Offline")))}set(e){this.Kr(),this.Or=0,"Online"===e&&(this.Mr=!1),this.Br(e)}Br(e){e!==this.state&&(this.state=e,this.onlineStateHandler(e))}Ur(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.Mr?(kR(t),this.Mr=!1):SR("OnlineStateTracker",t)}Kr(){null!==this.Fr&&(this.Fr.cancel(),this.Fr=null)}}class hL{constructor(e,t,n,r,i){this.localStore=e,this.datastore=t,this.asyncQueue=n,this.remoteSyncer={},this.jr=[],this.Qr=new Map,this.Wr=new Set,this.Gr=[],this.zr=i,this.zr.Ti(e=>{n.enqueueAndForget(async()=>{wL(this)&&(SR("RemoteStore","Restarting streams for network reachability change."),await async function(e){const t=e;t.Wr.add(4),await fL(t),t.Hr.set("Unknown"),t.Wr.delete(4),await dL(t)}(this))})}),this.Hr=new uL(n,r)}}async function dL(e){if(wL(e))for(const t of e.Gr)await t(!0)}async function fL(e){for(const t of e.Gr)await t(!1)}function pL(e,t){const n=e;n.Qr.has(t.targetId)||(n.Qr.set(t.targetId,t),_L(n)?yL(n):AL(n).hr()&&mL(n,t))}function gL(e,t){const n=e,r=AL(n);n.Qr.delete(t),r.hr()&&vL(n,t),0===n.Qr.size&&(r.hr()?r.wr():wL(n)&&n.Hr.set("Unknown"))}function mL(e,t){e.Jr.Y(t.targetId),AL(e).br(t)}function vL(e,t){e.Jr.Y(t),AL(e).Pr(t)}function yL(t){t.Jr=new rD({getRemoteKeysForTarget:e=>t.remoteSyncer.getRemoteKeysForTarget(e),Tt:e=>t.Qr.get(e)||null}),AL(t).start(),t.Hr.Lr()}function _L(e){return wL(e)&&!AL(e).ur()&&0<e.Qr.size}function wL(e){return 0===e.Wr.size}function bL(e){e.Jr=void 0}async function IL(e,t,n){if(!aO(t))throw t;e.Wr.add(1),await fL(e),e.Hr.set("Offline"),n=n||(()=>T1(e.localStore)),e.asyncQueue.enqueueRetryable(async()=>{SR("RemoteStore","Retrying IndexedDB access"),await n(),e.Wr.delete(1),await dL(e)})}function TL(t,n){return n().catch(e=>IL(t,e,n))}async function EL(e){const t=e,n=NL(t);let r=0<t.jr.length?t.jr[t.jr.length-1].batchId:-1;for(;wL(i=t)&&i.jr.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.In.getNextMutationBatchAfterBatchId(e,t)))}(t.localStore,r);if(null===e){0===t.jr.length&&n.wr();break}r=e.batchId,function(e,t){e.jr.push(t);const n=NL(e);n.hr()&&n.Vr&&n.Sr(t.mutations)}(t,e)}catch(e){await IL(t,e)}var i;SL(t)&&kL(t)}function SL(e){return wL(e)&&!NL(e).ur()&&0<e.jr.length}function kL(e){NL(e).start()}async function CL(e,t){const n=e;t?(n.Wr.delete(2),await dL(n)):(n.Wr.add(2),await fL(n),n.Hr.set("Unknown"))}function AL(t){return t.Yr||(t.Yr=function(e,t,n){const r=e;return r.$r(),new aL(t,r.sr,r.credentials,r.N,n)}(t.datastore,t.asyncQueue,{Si:(async function(n){n.Qr.forEach((e,t)=>{mL(n,e)})}).bind(null,t),Ci:(async function(e,t){bL(e),_L(e)?(e.Hr.qr(t),yL(e)):e.Hr.set("Unknown")}).bind(null,t),Rr:(async function(e,r,t){if(e.Hr.set("Online"),r instanceof tD&&2===r.state&&r.cause)try{await async function(e){var t=r.cause;for(const n of r.targetIds)e.Qr.has(n)&&(await e.remoteSyncer.rejectListen(n,t),e.Qr.delete(n),e.Jr.removeTarget(n))}(e)}catch(t){SR("RemoteStore","Failed to remove targets %s: %s ",r.targetIds.join(","),t),await IL(e,t)}else if(r instanceof Zx?e.Jr.rt(r):r instanceof eD?e.Jr.ft(r):e.Jr.at(r),!t.isEqual(WR.min()))try{const r=await T1(e.localStore);0<=t.compareTo(r)&&await function(r,i){const e=r.Jr._t(i);return e.targetChanges.forEach((e,t)=>{if(0<e.resumeToken.approximateByteSize()){const n=r.Qr.get(t);n&&r.Qr.set(t,n.withResumeToken(e.resumeToken,i))}}),e.targetMismatches.forEach(e=>{const t=r.Qr.get(e);var n;t&&(r.Qr.set(e,t.withResumeToken(tP.EMPTY_BYTE_STRING,t.snapshotVersion)),vL(r,e),n=new mO(t.target,e,1,t.sequenceNumber),mL(r,n))}),r.remoteSyncer.applyRemoteEvent(e)}(e,t)}catch(r){SR("RemoteStore","Failed to raise snapshot:",r),await IL(e,r)}}).bind(null,t)}),t.Gr.push(async e=>{e?(t.Yr.dr(),_L(t)?yL(t):t.Hr.set("Unknown")):(await t.Yr.stop(),bL(t))})),t.Yr}function NL(t){return t.Xr||(t.Xr=function(e,t,n){const r=e;return r.$r(),new cL(t,r.sr,r.credentials,r.N,n)}(t.datastore,t.asyncQueue,{Si:(async function(e){NL(e).Nr()}).bind(null,t),Ci:(async function(e,t){t&&NL(e).Vr&&await async function(e,t){if(Ux(n=t.code)&&n!==PR.ABORTED){const n=e.jr.shift();NL(e).dr(),await TL(e,()=>e.remoteSyncer.rejectFailedWrite(n.batchId,t)),await EL(e)}var n}(e,t),SL(e)&&kL(e)}).bind(null,t),Cr:(async function(e){const t=NL(e);for(const n of e.jr)t.Sr(n.mutations)}).bind(null,t),Dr:(async function(e,t,n){const r=e.jr.shift(),i=gO.from(r,t,n);await TL(e,()=>e.remoteSyncer.applySuccessfulWrite(i)),await EL(e)}).bind(null,t)}),t.Gr.push(async e=>{e?(t.Xr.dr(),await EL(t)):(await t.Xr.stop(),0<t.jr.length&&(SR("RemoteStore",`Stopping write stream with ${t.jr.length} pending writes`),t.jr=[]))})),t.Xr}class RL{constructor(e,t,n,r,i){this.asyncQueue=e,this.timerId=t,this.targetTimeMs=n,this.op=r,this.removalCallback=i,this.deferred=new DR,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 RL(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 PL(e,t){if(kR("AsyncQueue",`${t}: ${e}`),aO(e))return new xR(PR.UNAVAILABLE,`${t}: ${e}`);throw e}class xL{constructor(n){this.comparator=n?(e,t)=>n(e,t)||hP.comparator(e.key,t.key):(e,t)=>hP.comparator(e.key,t.key),this.keyedMap=Wx,this.sortedSet=new qx(this.comparator)}static emptySet(e){return new xL(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 xL))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 xL;return n.comparator=this.comparator,n.keyedMap=e,n.sortedSet=t,n}}class DL{constructor(){this.Zr=new qx(hP.comparator)}track(e){var t=e.doc.key,n=this.Zr.get(t);!n||0!==e.type&&3===n.type?this.Zr=this.Zr.insert(t,e):3===e.type&&1!==n.type?this.Zr=this.Zr.insert(t,{type:n.type,doc:e.doc}):2===e.type&&2===n.type?this.Zr=this.Zr.insert(t,{type:2,doc:e.doc}):2===e.type&&0===n.type?this.Zr=this.Zr.insert(t,{type:0,doc:e.doc}):1===e.type&&0===n.type?this.Zr=this.Zr.remove(t):1===e.type&&2===n.type?this.Zr=this.Zr.insert(t,{type:1,doc:n.doc}):0===e.type&&1===n.type?this.Zr=this.Zr.insert(t,{type:2,doc:e.doc}):NR()}eo(){const n=[];return this.Zr.inorderTraversal((e,t)=>{n.push(t)}),n}}class OL{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 OL(e,t,xL.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)&&rx(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 LL{constructor(){this.no=void 0,this.listeners=[]}}class ML{constructor(){this.queries=new n1(e=>ix(e),rx),this.onlineState="Unknown",this.so=new Set}}async function FL(e,t){const n=e,r=t.query;let i=!1,s=n.queries.get(r);if(s||(i=!0,s=new LL),i)try{s.no=await n.onListen(r)}catch(e){const n=PL(e,`Initialization of query '${sx(t.query)}' failed`);return void t.onError(n)}n.queries.set(r,s),s.listeners.push(t),t.io(n.onlineState),!s.no||t.ro(s.no)&&jL(n)}async function UL(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 jL(e){e.so.forEach(e=>{e.next()})}class qL{constructor(e,t,n){this.query=e,this.oo=t,this.co=!1,this.ao=null,this.onlineState="Unknown",this.options=n||{}}ro(e){if(!this.options.includeMetadataChanges){const t=[];for(const n of e.docChanges)3!==n.type&&t.push(n);e=new OL(e.query,e.docs,e.oldDocs,t,e.mutatedKeys,e.fromCache,e.syncStateChanged,!0)}let t=!1;return this.co?this.uo(e)&&(this.oo.next(e),t=!0):this.ho(e,this.onlineState)&&(this.lo(e),t=!0),this.ao=e,t}onError(e){this.oo.error(e)}io(e){this.onlineState=e;let t=!1;return this.ao&&!this.co&&this.ho(this.ao,e)&&(this.lo(this.ao),t=!0),t}ho(e,t){return!e.fromCache||!(this.options.fo&&"Offline"!==t||e.docs.isEmpty()&&"Offline"!==t)}uo(e){if(0<e.docChanges.length)return!0;var t=this.ao&&this.ao.hasPendingWrites!==e.hasPendingWrites;return!(!e.syncStateChanged&&!t)&&!0===this.options.includeMetadataChanges}lo(e){e=OL.fromInitialDocuments(e.query,e.docs,e.mutatedKeys,e.fromCache),this.co=!0,this.oo.next(e)}}class VL{constructor(e,t){this.payload=e,this.byteLength=t}wo(){return"metadata"in this.payload}}class BL{constructor(e){this.N=e}zn(e){return gD(this.N,e)}Hn(e){return e.metadata.exists?bD(this.N,e.document,!1):kP.newNoDocument(this.zn(e.metadata.name),this.Jn(e.metadata.readTime))}Jn(e){return hD(e)}}class $L{constructor(e,t,n){this._o=e,this.localStore=t,this.N=n,this.queries=[],this.documents=[],this.progress=KL(e)}mo(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}yo(e){const t=new Map,n=new BL(this.N);for(const i of e)if(i.metadata.queries){const e=n.zn(i.metadata.name);for(const n of i.metadata.queries){var r=(t.get(n)||Qx()).add(e);t.set(n,r)}}return t}async complete(){const e=await async function(e,t,n,r){const i=e;let s=Qx(),o=zx,a=Hx;for(const e of n){const n=t.zn(e.metadata.name);e.document&&(s=s.add(n)),o=o.insert(n,t.Hn(e)),a=a.insert(n,t.Jn(e.metadata.readTime))}const c=i.jn.newChangeBuffer({trackRemovals:!0}),l=await k1(i,(r=r,tx(GP(JR.fromString(`__bundle__/docs/${r}`)))));return i.persistence.runTransaction("Apply bundle documents","readwrite",t=>S1(t,c,o,WR.min(),a).next(e=>(c.apply(t),e)).next(e=>i.ze.removeMatchingKeysForTargetId(t,l.targetId).next(()=>i.ze.addMatchingKeys(t,s,l.targetId)).next(()=>i.Qn.vn(t,e)).next(()=>e)))}(this.localStore,new BL(this.N),this.documents,this._o.id),t=this.yo(this.documents);for(const e of this.queries)await async function(e,n,r=Qx()){const i=await k1(e,tx(CO(n.bundledQuery))),s=e;return s.persistence.runTransaction("Save named query","readwrite",e=>{var t=hD(n.readTime);if(0<=i.snapshotVersion.compareTo(t))return s.Je.saveNamedQuery(e,n);t=i.withResumeToken(tP.EMPTY_BYTE_STRING,t);return s.Un=s.Un.insert(t.targetId,t),s.ze.updateTargetData(e,t).next(()=>s.ze.removeMatchingKeysForTargetId(e,i.targetId)).next(()=>s.ze.addMatchingKeys(e,r,i.targetId)).next(()=>s.Je.saveNamedQuery(e,n))})}(this.localStore,e,t.get(e.name));return this.progress.taskState="Success",new m1(Object.assign({},this.progress),e)}}function KL(e){return{taskState:"Running",documentsLoaded:0,bytesLoaded:0,totalDocuments:e.totalDocuments,totalBytes:e.totalBytes}}class zL{constructor(e){this.key=e}}class WL{constructor(e){this.key=e}}class HL{constructor(e,t){this.query=e,this.po=t,this.To=null,this.current=!1,this.Eo=Qx(),this.mutatedKeys=Qx(),this.Io=ax(e),this.Ao=new xL(this.Io)}get Ro(){return this.po}bo(e,t){const a=t?t.Po:new DL,c=(t||this).Ao;let l=(t||this).mutatedKeys,u=c,h=!1;const d=QP(this.query)&&c.size===this.query.limit?c.last():null,f=YP(this.query)&&c.size===this.query.limit?c.first():null;if(e.inorderTraversal((e,t)=>{const n=c.get(e),r=ox(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.vo(n,r)||(a.track({type:2,doc:r}),o=!0,(d&&0<this.Io(r,d)||f&&this.Io(r,f)<0)&&(h=!0)):!n&&r?(a.track({type:0,doc:r}),o=!0):n&&!r&&(a.track({type:1,doc:n}),o=!0,(d||f)&&(h=!0)),o&&(l=r?(u=u.add(r),s?l.add(e):l.delete(e)):(u=u.delete(e),l.delete(e)))}),QP(this.query)||YP(this.query))for(;u.size>this.query.limit;){const e=QP(this.query)?u.last():u.first();u=u.delete(e.key),l=l.delete(e.key),a.track({type:1,doc:e})}return{Ao:u,Po:a,Ln:h,mutatedKeys:l}}vo(e,t){return e.hasLocalMutations&&t.hasCommittedMutations&&!t.hasLocalMutations}applyChanges(e,t,n){var r=this.Ao;this.Ao=e.Ao,this.mutatedKeys=e.mutatedKeys;const i=e.Po.eo();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.Io(e.doc,t.doc)),this.Vo(n);var s=t?this.So():[],o=0===this.Eo.size&&this.current?1:0,a=o!==this.To;return this.To=o,0!==i.length||a?{snapshot:new OL(this.query,e.Ao,r,i,e.mutatedKeys,0==o,a,!1),Do:s}:{Do:s}}io(e){return this.current&&"Offline"===e?(this.current=!1,this.applyChanges({Ao:this.Ao,Po:new DL,mutatedKeys:this.mutatedKeys,Ln:!1},!1)):{Do:[]}}Co(e){return!this.po.has(e)&&!!this.Ao.has(e)&&!this.Ao.get(e).hasLocalMutations}Vo(e){e&&(e.addedDocuments.forEach(e=>this.po=this.po.add(e)),e.modifiedDocuments.forEach(e=>{}),e.removedDocuments.forEach(e=>this.po=this.po.delete(e)),this.current=e.current)}So(){if(!this.current)return[];const t=this.Eo;this.Eo=Qx(),this.Ao.forEach(e=>{this.Co(e.key)&&(this.Eo=this.Eo.add(e.key))});const n=[];return t.forEach(e=>{this.Eo.has(e)||n.push(new WL(e))}),this.Eo.forEach(e=>{t.has(e)||n.push(new zL(e))}),n}No(e){this.po=e.Gn,this.Eo=Qx();var t=this.bo(e.documents);return this.applyChanges(t,!0)}xo(){return OL.fromInitialDocuments(this.query,this.Ao,this.mutatedKeys,0===this.To)}}class GL{constructor(e,t,n){this.query=e,this.targetId=t,this.view=n}}class QL{constructor(e){this.key=e,this.ko=!1}}class YL{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.$o={},this.Oo=new n1(e=>ix(e),rx),this.Fo=new Map,this.Mo=new Set,this.Lo=new qx(hP.comparator),this.Bo=new Map,this.Uo=new x1,this.qo={},this.Ko=new Map,this.jo=KO.ie(),this.onlineState="Unknown",this.Qo=void 0}get isPrimaryClient(){return!0===this.Qo}}async function JL(n,e,t,r){n.Wo=(e,s,t)=>async function(e,t,n){let r=t.view.bo(s);r.Ln&&(r=await A1(e.localStore,t.query,!1).then(({documents:e})=>t.view.bo(e,r)));var i=n&&n.targetChanges.get(t.targetId),i=t.view.applyChanges(r,e.isPrimaryClient,i);return oM(e,t.targetId,i.Do),i.snapshot}(n,e,t);const i=await A1(n.localStore,e,!0),s=new HL(e,i.Gn),o=s.bo(i.documents),a=Xx.createSynthesizedTargetChangeForCurrentChange(t,r&&"Offline"!==n.onlineState),c=s.applyChanges(o,n.isPrimaryClient,a);oM(n,t,c.Do);var l=new GL(e,t,s);return n.Oo.set(e,l),n.Fo.has(t)?n.Fo.get(t).push(e):n.Fo.set(t,[e]),c.snapshot}async function XL(e,t,n){const r=fM(e);try{const e=await function(e,r){const i=e,s=zR.now(),t=r.reduce((e,t)=>e.add(t.key),Qx());let o;return i.persistence.runTransaction("Locally write mutations","readwrite",n=>i.Qn.Pn(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=dx(r.transform,e||null);null!=i&&(null==n&&(n=SP.empty()),n.set(r.field,i))}return n||null}(n,o.get(n.key));null!=r&&t.push(new Px(n.key,r,function r(e){const i=[];return GR(e.fields,(e,t)=>{const n=new ZR([e]);if(TP(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 eP(i)}(r.value.mapValue),Tx.exists(!0)))}return i.In.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 qx(BR),r=r.insert(t,n),e.qo[e.currentUser.toKey()]=r}(r,e.batchId,n),await cM(r,e.changes),await EL(r.remoteStore)}catch(e){const t=PL(e,"Failed to persist write");n.reject(t)}}async function ZL(e,t){const r=e;try{const e=await E1(r.localStore,t);t.targetChanges.forEach((e,t)=>{const n=r.Bo.get(t);n&&(RR(e.addedDocuments.size+e.modifiedDocuments.size+e.removedDocuments.size<=1),0<e.addedDocuments.size?n.ko=!0:0<e.modifiedDocuments.size?RR(n.ko):0<e.removedDocuments.size&&(RR(n.ko),n.ko=!1))}),await cM(r,e,t)}catch(e){await QO(e)}}function eM(r,i,e){const t=r;if(t.isPrimaryClient&&0===e||!t.isPrimaryClient&&1===e){const r=[];t.Oo.forEach((e,t)=>{var n=t.view.io(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.io(n)&&(r=!0)}),r&&jL(t)}(t.eventManager,i),r.length&&t.$o.Rr(r),t.onlineState=i,t.isPrimaryClient&&t.sharedClientState.setOnlineState(i)}}async function tM(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.jn.newChangeBuffer({trackRemovals:!0});return function(e,t,r,i){const s=r.batch,n=s.keys();let o=nO.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()&&i.addEntry(e,r.commitVersion))})}),o.next(()=>e.In.removeMutationBatch(t,s))}(i,e,r,n).next(()=>n.apply(e)).next(()=>i.In.performConsistencyCheck(e)).next(()=>i.Qn.Pn(e,t))})}(n.localStore,t);rM(n,r,null),nM(n,r),n.sharedClientState.updateMutationState(r,"acknowledged"),await cM(n,e)}catch(e){await QO(e)}}function nM(e,t){(e.Ko.get(t)||[]).forEach(e=>{e.resolve()}),e.Ko.delete(t)}function rM(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 iM(t,e,n=null){t.sharedClientState.removeLocalQueryTarget(e);for(const r of t.Fo.get(e))t.Oo.delete(r),n&&t.$o.Go(r,n);t.Fo.delete(e),t.isPrimaryClient&&t.Uo.cs(e).forEach(e=>{t.Uo.containsKey(e)||sM(t,e)})}function sM(e,t){e.Mo.delete(t.path.canonicalString());var n=e.Lo.get(t);null!==n&&(gL(e.remoteStore,n),e.Lo=e.Lo.remove(t),e.Bo.delete(n),aM(e))}function oM(e,t,n){for(const r of n)r instanceof zL?(e.Uo.addReference(r.key,t),function(e,t){const n=t.key,r=n.path.canonicalString();e.Lo.get(n)||e.Mo.has(r)||(SR("SyncEngine","New document in limbo: "+n),e.Mo.add(r),aM(e))}(e,r)):r instanceof WL?(SR("SyncEngine","Document no longer in limbo: "+r.key),e.Uo.removeReference(r.key,t),e.Uo.containsKey(r.key)||sM(e,r.key)):NR()}function aM(e){for(;0<e.Mo.size&&e.Lo.size<e.maxConcurrentLimboResolutions;){var t=e.Mo.values().next().value;e.Mo.delete(t);var n=new hP(JR.fromString(t)),t=e.jo.next();e.Bo.set(t,new QL(n)),e.Lo=e.Lo.insert(n,t),pL(e.remoteStore,new mO(tx(GP(n.path)),t,2,qR.T))}}async function cM(e,t,r){const i=e,s=[],o=[],a=[];i.Oo.isEmpty()||(i.Oo.forEach((e,n)=>{a.push(i.Wo(n,t,r).then(e=>{var t;e&&(i.isPrimaryClient&&i.sharedClientState.updateQueryState(n.targetId,e.fromCache?"not-current":"current"),s.push(e),t=y1.kn(n.targetId,e),o.push(t))}))}),await Promise.all(a),i.$o.Rr(s),await async function(e,t){const r=e;try{await r.persistence.runTransaction("notifyLocalViewChanges","readwrite",n=>nO.forEach(t,t=>nO.forEach(t.Nn,e=>r.persistence.referenceDelegate.addReference(n,t.targetId,e)).next(()=>nO.forEach(t.xn,e=>r.persistence.referenceDelegate.removeReference(n,t.targetId,e)))))}catch(e){if(!aO(e))throw e;SR("LocalStore","Failed to update sequence numbers: "+e)}for(const e of t){const t=e.targetId;if(!e.fromCache){const e=r.Un.get(t),n=e.snapshotVersion,i=e.withLastLimboFreeSnapshotVersion(n);r.Un=r.Un.insert(t,i)}}}(i.localStore,o))}async function lM(r,e){const i=r;if(dM(i),fM(i),!0===e&&!0!==i.Qo){const r=i.sharedClientState.getAllActiveQueryTargets(),e=await uM(i,r.toArray());i.Qo=!0,await CL(i.remoteStore,!0);for(const r of e)pL(i.remoteStore,r)}else if(!1===e&&!1!==i.Qo){const r=[];let n=Promise.resolve();i.Fo.forEach((e,t)=>{i.sharedClientState.isLocalQueryTarget(t)?r.push(t):n=n.then(()=>(iM(i,t),C1(i.localStore,t,!0))),gL(i.remoteStore,t)}),await n,await uM(i,r),function(){const n=i;n.Bo.forEach((e,t)=>{gL(n.remoteStore,t)}),n.Uo.us(),n.Bo=new Map,n.Lo=new qx(hP.comparator)}(),i.Qo=!1,await CL(i.remoteStore,!1)}}async function uM(t,n){const r=t,i=[],s=[];for(const t of n){let e;const u=r.Fo.get(t);if(u&&0!==u.length){e=await k1(r.localStore,tx(u[0]));for(const t of u){const n=r.Oo.get(t),u=(o=r,a=n,l=c=void 0,l=await A1((c=o).localStore,a.query,!0),l=a.view.No(l),c.isPrimaryClient&&oM(c,a.targetId,l.Do),await l);u.snapshot&&s.push(u.snapshot)}}else{const u=await N1(r.localStore,t);e=await k1(r.localStore,u),await JL(r,hM(u),t,!1)}i.push(e)}var o,a,c,l;return r.$o.Rr(s),i}function hM(e){return HP(e.path,e.collectionGroup,e.orderBy,e.filters,e.limit,"F",e.startAt,e.endAt)}function dM(e){const t=e;return t.remoteStore.remoteSyncer.applyRemoteEvent=ZL.bind(null,t),t.remoteStore.remoteSyncer.getRemoteKeysForTarget=(function(e,t){const n=e,r=n.Bo.get(t);if(r&&r.ko)return Qx().add(r.key);{let e=Qx();const r=n.Fo.get(t);if(!r)return e;for(const t of r){const r=n.Oo.get(t);e=e.unionWith(r.view.Ro)}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.Bo.get(t),s=i&&i.key;if(s){let e=new qx(hP.comparator);e=e.insert(s,kP.newNoDocument(s,WR.min()));const n=Qx().add(s),i=new Jx(WR.min(),new Map,new $x(BR),e,n);await ZL(r,i),r.Lo=r.Lo.remove(s),r.Bo.delete(t),aM(r)}else await C1(r.localStore,t,!1).then(()=>iM(r,t,n)).catch(QO)}).bind(null,t),t.$o.Rr=(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.ro(e)&&(r=!0);i.no=e}}r&&jL(n)}).bind(null,t.eventManager),t.$o.Go=(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 fM(e){const t=e;return t.remoteStore.remoteSyncer.applySuccessfulWrite=tM.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.In.lookupMutationBatch(t,r).next(e=>(RR(null!==e),n=e.keys(),i.In.removeMutationBatch(t,e))).next(()=>i.In.performConsistencyCheck(t)).next(()=>i.Qn.Pn(t,n))})}(r.localStore,t);rM(r,t,n),nM(r,t),r.sharedClientState.updateMutationState(t,"rejected",n),await cM(r,e)}catch(n){await QO(n)}}).bind(null,t),t}class pM{constructor(){this.synchronizeTabs=!1}async initialize(e){this.N=iL(e.databaseInfo.databaseId),this.sharedClientState=this.Ho(e),this.persistence=this.Jo(e),await this.persistence.start(),this.gcScheduler=this.Yo(e),this.localStore=this.Xo(e)}Yo(e){return null}Xo(e){return b1(this.persistence,new _1,e.initialUser,this.N)}Jo(e){return new U1(q1.Ns,this.N)}Ho(e){return new Y1}async terminate(){this.gcScheduler&&this.gcScheduler.stop(),await this.sharedClientState.shutdown(),await this.persistence.shutdown()}}class gM extends pM{constructor(e,t,n){super(),this.Zo=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=a1(t);let r=WR.min();return e.Kt({index:KD.readTimeIndex,reverse:!0},(e,t,n)=>{t.readTime&&(r=bO(t.readTime)),n.done()}).next(()=>r)}()).then(e=>{t.Kn=e})}(this.localStore),await this.Zo.initialize(this,e),await fM(this.Zo.syncEngine),await EL(this.Zo.remoteStore),await this.persistence.nn(()=>(this.gcScheduler&&!this.gcScheduler.started&&this.gcScheduler.start(this.localStore),Promise.resolve()))}Xo(e){return b1(this.persistence,new _1,e.initialUser,this.N)}Yo(e){var t=this.persistence.referenceDelegate.garbageCollector;return new XO(t,e.asyncQueue)}Jo(e){var t=g1(e.databaseInfo.databaseId,e.databaseInfo.persistenceKey),n=void 0!==this.cacheSizeBytes?MO.withCacheSize(this.cacheSizeBytes):MO.DEFAULT;return new d1(this.synchronizeTabs,t,e.clientId,n,e.asyncQueue,nL(),rL(),this.N,this.sharedClientState,!!this.forceOwnership)}Ho(e){return new Y1}}class mM extends gM{constructor(e,t){super(e,t,!1),this.Zo=e,this.cacheSizeBytes=t,this.synchronizeTabs=!0}async initialize(e){await super.initialize(e);var t=this.Zo.syncEngine;this.sharedClientState instanceof Q1&&(this.sharedClientState.syncEngine={_i:(async function(e,t,n,r){var i=e,s=await function(e,n){const r=e,i=r.In;return r.persistence.runTransaction("Lookup mutation documents","readonly",t=>i.Xt(t,n).next(e=>e?r.Qn.Pn(t,e):nO.resolve(null)))}(i.localStore,t);null!==s?("pending"===n?await EL(i.remoteStore):"acknowledged"===n||"rejected"===n?(rM(i,t,r||null),nM(i,t),i.localStore.In.te(t)):NR(),await cM(i,s)):SR("SyncEngine","Cannot apply mutation batch with id: "+t)}).bind(null,t),mi:(async function(e,t,n,r){const i=e;if(i.Qo)SR("SyncEngine","Ignoring unexpected query state notification.");else if(i.Fo.has(t))switch(n){case"current":case"not-current":{const e=await R1(i.localStore),r=Jx.createSynthesizedRemoteEventForCurrentChange(t,"current"===n);await cM(i,e,r);break}case"rejected":await C1(i.localStore,t,!0),iM(i,t,r);break;default:NR()}}).bind(null,t),gi:(async function(e,t,n){const r=dM(e);if(r.Qo){for(const e of t)if(r.Fo.has(e))SR("SyncEngine","Adding an already active target "+e);else{const t=await N1(r.localStore,e),n=await k1(r.localStore,t);await JL(r,hM(t),n.targetId,!1),pL(r.remoteStore,n)}for(const e of n)r.Fo.has(e)&&await C1(r.localStore,e,!1).then(()=>{gL(r.remoteStore,e),iM(r,e)}).catch(QO)}}).bind(null,t),pn:(function(e){return e.localStore.persistence.pn()}).bind(null,t),wi:(async function(e){const t=e;return R1(t.localStore).then(e=>cM(t,e))}).bind(null,t)},await this.sharedClientState.start()),await this.persistence.nn(async e=>{await lM(this.Zo.syncEngine,e),this.gcScheduler&&(e&&!this.gcScheduler.started?this.gcScheduler.start(this.localStore):e||this.gcScheduler.stop())})}Ho(e){var t=nL();if(!Q1.bt(t))throw new xR(PR.UNIMPLEMENTED,"IndexedDB persistence is only available on platforms that support LocalStorage.");var n=g1(e.databaseInfo.databaseId,e.databaseInfo.persistenceKey);return new Q1(t,e.asyncQueue,n,e.clientId,e.initialUser)}}class vM{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=>eM(this.syncEngine,e,1),this.remoteStore.remoteSyncer.handleCredentialChange=(async function(e,t){const n=e;if(!n.currentUser.isEqual(t)){SR("SyncEngine","User change. New user:",t.toKey());const r=await I1(n.localStore,t);n.currentUser=t,(e=n).Ko.forEach(e=>{e.forEach(e=>{e.reject(new xR(PR.CANCELLED,"'waitForPendingWrites' promise is rejected due to a user change."))})}),e.Ko.clear(),n.sharedClientState.handleUserChange(t,r.removedBatchIds,r.addedBatchIds),await cM(n,r.Wn)}}).bind(null,this.syncEngine),await CL(this.remoteStore,this.syncEngine.isPrimaryClient))}createEventManager(e){return new ML}createDatastore(e){var t,n,r,i=iL(e.databaseInfo.databaseId),t=(t=e.databaseInfo,new tL(t));return n=e.credentials,r=t,e=i,new lL(n,r,e)}createRemoteStore(e){return t=this.localStore,n=this.datastore,r=e.asyncQueue,i=e=>eM(this.syncEngine,e,0),s=new(X1.bt()?X1:J1),new hL(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 YL(e,t,n,r,i,s);return o&&(a.Qo=!0),a}(this.localStore,this.remoteStore,this.eventManager,this.sharedClientState,e.initialUser,e.maxConcurrentLimboResolutions,t)}terminate(){return async function(e){const t=e;SR("RemoteStore","RemoteStore shutting down."),t.Wr.add(5),await fL(t),t.zr.shutdown(),t.Hr.set("Unknown")}(this.remoteStore)}}function yM(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 _M{constructor(e){this.observer=e,this.muted=!1}next(e){this.observer.next&&this.tc(this.observer.next,e)}error(e){this.observer.error?this.tc(this.observer.error,e):console.error("Uncaught Error in snapshot listener:",e)}ec(){this.muted=!0}tc(e,t){this.muted||setTimeout(()=>{this.muted||e(t)},0)}}class wM{constructor(e,t){this.nc=e,this.N=t,this.metadata=new DR,this.buffer=new Uint8Array,this.sc=new TextDecoder("utf-8"),this.ic().then(e=>{e&&e.wo()?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.nc.cancel()}async getMetadata(){return this.metadata.promise}async zo(){return await this.getMetadata(),this.ic()}async ic(){var e=await this.rc();if(null===e)return null;var t=this.sc.decode(e),n=Number(t);isNaN(n)&&this.oc(`length string (${t}) is not valid number`);t=await this.cc(n);return new VL(JSON.parse(t),e.length+n)}ac(){return this.buffer.findIndex(e=>e==="{".charCodeAt(0))}async rc(){for(;this.ac()<0&&!await this.uc(););if(0===this.buffer.length)return null;var e=this.ac();e<0&&this.oc("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 cc(e){for(;this.buffer.length<e;)await this.uc()&&this.oc("Reached the end of bundle when more is expected.");var t=this.sc.decode(this.buffer.slice(0,e));return this.buffer=this.buffer.slice(e),t}oc(e){throw this.nc.cancel(),new Error(`Invalid bundle format: ${e}`)}async uc(){var e=await this.nc.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 bM{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=yD(r.N)+"/documents",i={documents:t.map(e=>pD(r.N,e))},s=await r.Ki("BatchGetDocuments",n,i),o=new Map;s.forEach(e=>{const t=(n=r.N,"found"in(e=e)?function(e,t){RR(!!t.found),t.found.name,t.found.updateTime;var n=gD(e,t.found.name),r=hD(t.found.updateTime),i=new SP({mapValue:{fields:t.found.fields}});return kP.newFoundDocument(n,r,i)}(n,e):"missing"in e?function(e,t){RR(!!t.missing),RR(!!t.readTime);var n=gD(e,t.missing),r=hD(t.readTime);return kP.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 Lx(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=hP.fromPath(t);this.mutations.push(new Mx(n,this.precondition(n)))}),await async function(e,t){const n=e,r=yD(n.N)+"/documents",i={writes:t.map(e=>ID(n.N,e))};await n.Li("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=WR.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?Tx.updateTime(t):Tx.none()}preconditionForUpdate(e){const t=this.readVersions.get(e.toString());if(this.writtenDocs.has(e.toString())||!t)return Tx.exists(!0);if(t.isEqual(WR.min()))throw new xR(PR.INVALID_ARGUMENT,"Can't update a document that doesn't exist.");return Tx.updateTime(t)}write(e){this.ensureCommitNotCalled(),this.mutations.push(e)}ensureCommitNotCalled(){}}class IM{constructor(e,t,n,r){this.asyncQueue=e,this.datastore=t,this.updateFunction=n,this.deferred=r,this.hc=5,this.ar=new sL(this.asyncQueue,"transaction_retry")}run(){--this.hc,this.lc()}lc(){this.ar.Xi(async()=>{const t=new bM(this.datastore),e=this.fc(t);e&&e.then(e=>{this.asyncQueue.enqueueAndForget(()=>t.commit().then(()=>{this.deferred.resolve(e)}).catch(e=>{this.dc(e)}))}).catch(e=>{this.dc(e)})})}fc(e){try{var t=this.updateFunction(e);return!cP(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}}dc(e){0<this.hc&&this.wc(e)?(--this.hc,this.asyncQueue.enqueueAndForget(()=>(this.lc(),Promise.resolve()))):this.deferred.reject(e)}wc(e){if("FirebaseError"!==e.name)return!1;var t=e.code;return"aborted"===t||"failed-precondition"===t||!Ux(t)}}class TM{constructor(e,t,n){this.credentials=e,this.asyncQueue=t,this.databaseInfo=n,this.user=bR.UNAUTHENTICATED,this.clientId=VR.I(),this.credentialListener=()=>Promise.resolve(),this.credentials.start(t,async e=>{SR("FirestoreClient","Received user=",e.uid),await this.credentialListener(e),this.user=e})}async getConfiguration(){return{asyncQueue:this.asyncQueue,databaseInfo:this.databaseInfo,clientId:this.clientId,credentials:this.credentials,initialUser:this.user,maxConcurrentLimboResolutions:100}}setCredentialChangeListener(e){this.credentialListener=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 DR;return this.asyncQueue.enqueueAndForgetEvenWhileRestricted(async()=>{try{this.onlineComponents&&await this.onlineComponents.terminate(),this.offlineComponents&&await this.offlineComponents.terminate(),this.credentials.shutdown(),n.resolve()}catch(e){var t=PL(e,"Failed to shutdown persistence");n.reject(t)}}),n.promise}}async function EM(e,t){e.asyncQueue.verifyOperationInProgress(),SR("FirestoreClient","Initializing OfflineComponentProvider");var n=await e.getConfiguration();await t.initialize(n);let r=n.initialUser;e.setCredentialChangeListener(async e=>{r.isEqual(e)||(await I1(t.localStore,e),r=e)}),t.persistence.setDatabaseDeletedListener(()=>e.terminate()),e.offlineComponents=t}async function SM(e,t){e.asyncQueue.verifyOperationInProgress();var n=await kM(e);SR("FirestoreClient","Initializing OnlineComponentProvider");var r=await e.getConfiguration();await t.initialize(n,r),e.setCredentialChangeListener(e=>async function(e,t){const n=e;n.asyncQueue.verifyOperationInProgress(),SR("RemoteStore","RemoteStore received new credentials");var r=wL(n);n.Wr.add(3),await fL(n),r&&n.Hr.set("Unknown"),await n.remoteSyncer.handleCredentialChange(t),n.Wr.delete(3),await dL(n)}(t.remoteStore,e)),e.onlineComponents=t}async function kM(e){return e.offlineComponents||(SR("FirestoreClient","Using default OfflineComponentProvider"),await EM(e,new pM)),e.offlineComponents}async function CM(e){return e.onlineComponents||(SR("FirestoreClient","Using default OnlineComponentProvider"),await SM(e,new vM)),e.onlineComponents}function AM(e){return kM(e).then(e=>e.persistence)}function NM(e){return kM(e).then(e=>e.localStore)}function RM(e){return CM(e).then(e=>e.remoteStore)}function PM(e){return CM(e).then(e=>e.syncEngine)}async function xM(e){const t=await CM(e),n=t.eventManager;return n.onListen=(async function(e,t){const n=dM(e);let r,i;const s=n.Oo.get(t);if(s)r=s.targetId,n.sharedClientState.addLocalQueryTarget(r),i=s.view.xo();else{const e=await k1(n.localStore,tx(t)),s=n.sharedClientState.addLocalQueryTarget(e.targetId);r=e.targetId,i=await JL(n,t,r,"current"===s),n.isPrimaryClient&&pL(n.remoteStore,e)}return i}).bind(null,t.syncEngine),n.onUnlisten=(async function(e,t){const n=e,r=n.Oo.get(t),i=n.Fo.get(r.targetId);if(1<i.length)return n.Fo.set(r.targetId,i.filter(e=>!rx(e,t))),void n.Oo.delete(t);n.isPrimaryClient?(n.sharedClientState.removeLocalQueryTarget(r.targetId),n.sharedClientState.isActiveQueryTarget(r.targetId)||await C1(n.localStore,r.targetId,!1).then(()=>{n.sharedClientState.clearQueryState(r.targetId),gL(n.remoteStore,r.targetId),iM(n,r.targetId)}).catch(QO)):(iM(n,r.targetId),await C1(n.localStore,r.targetId,!0))}).bind(null,t.syncEngine),n}function DM(e,t,n={}){const r=new DR;return e.asyncQueue.enqueueAndForget(async()=>function(n,r,i,s,o){const e=new _M({next:e=>{r.enqueueAndForget(()=>UL(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 qL(GP(i.path),e,{includeMetadataChanges:!0,fo:!0});return FL(n,a)}(await xM(e),e.asyncQueue,t,n,r)),r.promise}function OM(e,t,n={}){const r=new DR;return e.asyncQueue.enqueueAndForget(async()=>function(t,n,e,r,i){const s=new _M({next:e=>{n.enqueueAndForget(()=>UL(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 qL(e,s,{includeMetadataChanges:!0,fo:!0});return FL(t,o)}(await xM(e),e.asyncQueue,t,n,r)),r.promise}function LM(e,t,n,r){const i=(n=n,t=iL(t),s="string"==typeof n?(new TextEncoder).encode(n):n,n=function(e){if(e instanceof Uint8Array)return yM(e,void 0);if(e instanceof ArrayBuffer)return yM(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 wM(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=hD(t.createTime);return n.persistence.runTransaction("hasNewerBundle","readonly",e=>n.Je.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(KL(i));const o=new $L(i,t.localStore,n.N);let e=await n.zo();for(;e;){const t=await o.mo(e);t&&r._updateProgress(t),e=await n.zo()}var s=await o.complete();await cM(t,s.En,void 0),await function(e,t){const n=e;return n.persistence.runTransaction("Save bundle","readwrite",e=>n.Je.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 PM(e),i,r)})}class MM{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 FM{constructor(e,t){this.projectId=e,this.database=t||"(default)"}get isDefaultDatabase(){return"(default)"===this.database}isEqual(e){return e instanceof FM&&e.projectId===this.projectId&&e.database===this.database}}const UM=new Map;function jM(e,t,n){if(!n)throw new xR(PR.INVALID_ARGUMENT,`Function ${e}() cannot be called with an empty ${t}.`)}function qM(e,t,n,r){if(!0===t&&!0===r)throw new xR(PR.INVALID_ARGUMENT,`${e} and ${n} cannot be used together.`)}function VM(e){if(!hP.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 BM(e){if(hP.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 $M(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 KM(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=$M(e);throw new xR(PR.INVALID_ARGUMENT,`Expected type '${t.name}', but it was: ${n}`)}function zM(e,t){if(t<=0)throw new xR(PR.INVALID_ARGUMENT,`Function ${e}() requires a positive number, but it was: ${t}.`)}class WM{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,qM("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 HM{constructor(e,t){this._credentials=t,this.type="firestore-lite",this._persistenceKey="(lite)",this._settings=new WM({}),this._settingsFrozen=!1,e instanceof FM?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 FM(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 WM(e),void 0!==e.credentials&&(this._credentials=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,"makeCredentialsProvider 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=UM.get(e);t&&(SR("ComponentProvider","Removing Datastore"),UM.delete(e),t.terminate())}(this),Promise.resolve()}}class GM{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 YM(this.firestore,this.converter,this._key.path.popLast())}withConverter(e){return new GM(this.firestore,e,this._key)}}class QM{constructor(e,t,n){this.converter=t,this._query=n,this.type="query",this.firestore=e}withConverter(e){return new QM(this.firestore,e,this._query)}}class YM extends QM{constructor(e,t,n){super(e,t,GP(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 GM(this.firestore,null,new hP(e))}withConverter(e){return new YM(this.firestore,e,this._path)}}function JM(e,t,...n){if(e=Kd(e),jM("collection","path",t),e instanceof HM){var r=JR.fromString(t,...n);return BM(r),new YM(e,null,r)}if(!(e instanceof GM||e instanceof YM))throw new xR(PR.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");r=e._path.child(JR.fromString(t,...n));return BM(r),new YM(e.firestore,null,r)}function XM(e,t,...n){if(e=Kd(e),jM("doc","path",t=1===arguments.length?VR.I():t),e instanceof HM){var r=JR.fromString(t,...n);return VM(r),new GM(e,null,new hP(r))}if(!(e instanceof GM||e instanceof YM))throw new xR(PR.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");r=e._path.child(JR.fromString(t,...n));return VM(r),new GM(e.firestore,e instanceof YM?e.converter:null,new hP(r))}function ZM(e,t){return e=Kd(e),t=Kd(t),(e instanceof GM||e instanceof YM)&&(t instanceof GM||t instanceof YM)&&e.firestore===t.firestore&&e.path===t.path&&e.converter===t.converter}function eF(e,t){return e=Kd(e),t=Kd(t),e instanceof QM&&t instanceof QM&&e.firestore===t.firestore&&rx(e._query,t._query)&&e.converter===t.converter}class tF{constructor(){this._c=Promise.resolve(),this.mc=[],this.gc=!1,this.yc=[],this.Tc=null,this.Ec=!1,this.Ic=!1,this.Ac=[],this.ar=new sL(this,"async_queue_retry"),this.Rc=()=>{var e=rL();e&&SR("AsyncQueue","Visibility state changed to "+e.visibilityState),this.ar.tr()};const e=rL();e&&"function"==typeof e.addEventListener&&e.addEventListener("visibilitychange",this.Rc)}get isShuttingDown(){return this.gc}enqueueAndForget(e){this.enqueue(e)}enqueueAndForgetEvenWhileRestricted(e){this.bc(),this.Pc(e)}enterRestrictedMode(e){if(!this.gc){this.gc=!0,this.Ic=e||!1;const t=rL();t&&"function"==typeof t.removeEventListener&&t.removeEventListener("visibilitychange",this.Rc)}}enqueue(e){if(this.bc(),this.gc)return new Promise(()=>{});const t=new DR;return this.Pc(()=>this.gc&&this.Ic?Promise.resolve():(e().then(t.resolve,t.reject),t.promise)).then(()=>t.promise)}enqueueRetryable(e){this.enqueueAndForget(()=>(this.mc.push(e),this.vc()))}async vc(){if(0!==this.mc.length){try{await this.mc[0](),this.mc.shift(),this.ar.reset()}catch(e){if(!aO(e))throw e;SR("AsyncQueue","Operation failed with retryable error: "+e)}0<this.mc.length&&this.ar.Xi(()=>this.vc())}}Pc(e){var t=this._c.then(()=>(this.Ec=!0,e().catch(e=>{throw this.Tc=e,this.Ec=!1,kR("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.Ec=!1,e))));return this._c=t}enqueueAfterDelay(e,t,n){this.bc(),-1<this.Ac.indexOf(e)&&(t=0);var r=RL.createAndSchedule(this,e,t,n,e=>this.Vc(e));return this.yc.push(r),r}bc(){this.Tc&&NR()}verifyOperationInProgress(){}async Sc(){for(var e;await(e=this._c),e!==this._c;);}Dc(e){for(const t of this.yc)if(t.timerId===e)return!0;return!1}Cc(t){return this.Sc().then(()=>{this.yc.sort((e,t)=>e.targetTimeMs-t.targetTimeMs);for(const e of this.yc)if(e.skipDelay(),"all"!==t&&e.timerId===t)break;return this.Sc()})}Nc(e){this.Ac.push(e)}Vc(e){var t=this.yc.indexOf(e);this.yc.splice(t,1)}}function nF(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 rF{constructor(){this._progressObserver={},this._taskCompletionResolver=new DR,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 iF,sF,oF,aF;class cF extends HM{constructor(e,t){super(e,t),this.type="firestore",this._queue=new tF,this._persistenceKey="name"in e?e.name:"[DEFAULT]"}_terminate(){return this._firestoreClient||uF(this),this._firestoreClient.terminate()}}function lF(e){return e._firestoreClient||uF(e),e._firestoreClient.verifyNotTerminated(),e._firestoreClient}function uF(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 MM(n,r,i,s.host,s.ssl,s.experimentalForceLongPolling,s.experimentalAutoDetectLongPolling,s.useFetchStreams));e._firestoreClient=new TM(e._credentials,e._queue,o)}function hF(e,n,r){const i=new DR;return e.asyncQueue.enqueue(async()=>{try{await EM(e,r),await SM(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 dF(e){return function(e){const t=new DR;return e.asyncQueue.enqueueAndForget(async()=>async function(e,t){const n=e;wL(n.remoteStore)||SR("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.In.getHighestUnacknowledgedBatchId(e))}();if(-1===e)return void t.resolve();const r=n.Ko.get(e)||[];r.push(t),n.Ko.set(e,r)}catch(e){const n=PL(e,"Initialization of waitForPendingWrites() operation failed");t.reject(n)}}(await PM(e),t)),t.promise}(lF(e=KM(e,cF)))}function fF(e){return(n=lF(e=KM(e,cF))).asyncQueue.enqueue(async()=>{const e=await AM(n),t=await RM(n);return e.setNetworkEnabled(!0),function(){const e=t;return e.Wr.delete(0),dL(e)}()});var n}function pF(e){return(n=lF(e=KM(e,cF))).asyncQueue.enqueue(async()=>{const e=await AM(n),t=await RM(n);return e.setNetworkEnabled(!1),async function(){const e=t;e.Wr.add(0),await fL(e),e.Hr.set("Offline")}()});var n}function gF(t,e){return n=lF(t=KM(t,cF)),r=e,n.asyncQueue.enqueue(async()=>function(e,t){const n=e;return n.persistence.runTransaction("Get named query","readonly",e=>n.Je.getNamedQuery(e,t))}(await NM(n),r)).then(e=>e?new QM(t,null,e.query):null);var n,r}function mF(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 vF{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 ZR(e)}isEqual(e){return this._internalPath.isEqual(e._internalPath)}}class yF{constructor(e){this._byteString=e}static fromBase64String(e){try{return new yF(tP.fromBase64String(e))}catch(e){throw new xR(PR.INVALID_ARGUMENT,"Failed to construct data from Base64 string: "+e)}}static fromUint8Array(e){return new yF(tP.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 _F{constructor(e){this._methodName=e}}class wF{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 BR(this._lat,e._lat)||BR(this._long,e._long)}}const bF=/^__.*__$/;class IF{constructor(e,t,n){this.data=e,this.fieldMask=t,this.fieldTransforms=n}toMutation(e,t){return null!==this.fieldMask?new Px(e,this.data,this.fieldMask,t,this.fieldTransforms):new Rx(e,this.data,t,this.fieldTransforms)}}class TF{constructor(e,t,n){this.data=e,this.fieldMask=t,this.fieldTransforms=n}toMutation(e,t){return new Px(e,this.data,this.fieldMask,t,this.fieldTransforms)}}function EF(e){switch(e){case 0:case 2:case 1:return 1;case 3:case 4:return;default:throw NR()}}class SF{constructor(e,t,n,r,i,s){this.settings=e,this.databaseId=t,this.N=n,this.ignoreUndefinedProperties=r,void 0===i&&this.xc(),this.fieldTransforms=i||[],this.fieldMask=s||[]}get path(){return this.settings.path}get kc(){return this.settings.kc}$c(e){return new SF(Object.assign(Object.assign({},this.settings),e),this.databaseId,this.N,this.ignoreUndefinedProperties,this.fieldTransforms,this.fieldMask)}Oc(e){var t;const n=null===(t=this.path)||void 0===t?void 0:t.child(e),r=this.$c({path:n,Fc:!1});return r.Mc(e),r}Lc(e){var t;const n=null===(t=this.path)||void 0===t?void 0:t.child(e),r=this.$c({path:n,Fc:!1});return r.xc(),r}Bc(e){return this.$c({path:void 0,Fc:!0})}Uc(e){return zF(e,this.settings.methodName,this.settings.qc||!1,this.path,this.settings.Kc)}contains(t){return void 0!==this.fieldMask.find(e=>t.isPrefixOf(e))||void 0!==this.fieldTransforms.find(e=>t.isPrefixOf(e.field))}xc(){if(this.path)for(let e=0;e<this.path.length;e++)this.Mc(this.path.get(e))}Mc(e){if(0===e.length)throw this.Uc("Document fields must not be empty");if(EF(this.kc)&&bF.test(e))throw this.Uc('Document fields cannot begin and end with "__"')}}class kF{constructor(e,t,n){this.databaseId=e,this.ignoreUndefinedProperties=t,this.N=n||iL(e)}jc(e,t,n,r=!1){return new SF({kc:e,methodName:t,Kc:n,path:ZR.emptyPath(),Fc:!1,qc:r},this.databaseId,this.N,this.ignoreUndefinedProperties)}}function CF(e){var t=e._freezeSettings(),n=iL(e._databaseId);return new kF(e._databaseId,!!t.ignoreUndefinedProperties,n)}function AF(e,t,n,r,i,s={}){const o=e.jc(s.merge||s.mergeFields?2:0,t,n,i);VF("Data must be an object, but it was:",o,r);var a=jF(r,o);let c,l;if(s.merge)c=new eP(o.fieldMask),l=o.fieldTransforms;else if(s.mergeFields){const e=[];for(const r of s.mergeFields){const i=BF(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.`);WF(e,i)||e.push(i)}c=new eP(e),l=o.fieldTransforms.filter(e=>c.covers(e.field))}else c=null,l=o.fieldTransforms;return new IF(new SP(a),c,l)}class NF extends _F{_toFieldTransform(e){if(2!==e.kc)throw 1===e.kc?e.Uc(`${this._methodName}() can only appear at the top level of your update data`):e.Uc(`${this._methodName}() cannot be used with set() unless you pass {merge:true}`);return e.fieldMask.push(e.path),null}isEqual(e){return e instanceof NF}}function RF(e,t,n){return new SF({kc:3,Kc:t.settings.Kc,methodName:e._methodName,Fc:n},t.databaseId,t.N,t.ignoreUndefinedProperties)}class PF extends _F{_toFieldTransform(e){return new bx(e.path,new fx)}isEqual(e){return e instanceof PF}}class xF extends _F{constructor(e,t){super(e),this.Qc=t}_toFieldTransform(e){const t=RF(this,e,!0),n=this.Qc.map(e=>UF(e,t)),r=new px(n);return new bx(e.path,r)}isEqual(e){return this===e}}class DF extends _F{constructor(e,t){super(e),this.Qc=t}_toFieldTransform(e){const t=RF(this,e,!0),n=this.Qc.map(e=>UF(e,t)),r=new mx(n);return new bx(e.path,r)}isEqual(e){return this===e}}class OF extends _F{constructor(e,t){super(e),this.Wc=t}_toFieldTransform(e){var t=new yx(e.N,ux(e.N,this.Wc));return new bx(e.path,t)}isEqual(e){return this===e}}function LF(e,i,s,t){const o=e.jc(1,i,s);VF("Data must be an object, but it was:",o,t);const a=[],c=SP.empty();GR(t,(e,t)=>{var n=KF(i,e,s);t=Kd(t);var r=o.Lc(n);if(t instanceof NF)a.push(n);else{const e=UF(t,r);null!=e&&(a.push(n),c.set(n,e))}});var n=new eP(a);return new TF(c,n,o.fieldTransforms)}function MF(e,t,n,r,i,s){const o=e.jc(1,t,n),a=[BF(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 f=0;f<s.length;f+=2)a.push(BF(t,s[f])),c.push(s[f+1]);const l=[],u=SP.empty();for(let p=a.length-1;0<=p;--p)if(!WF(l,a[p])){const t=a[p];var h=Kd(h=c[p]);const r=o.Lc(t);if(h instanceof NF)l.push(t);else{const e=UF(h,r);null!=e&&(l.push(t),u.set(t,e))}}var d=new eP(l);return new TF(u,d,o.fieldTransforms)}function FF(e,t,n,r=!1){return UF(n,e.jc(r?4:3,t))}function UF(s,e){if(qF(s=Kd(s)))return VF("Unsupported field value:",e,s),jF(s,e);if(s instanceof _F)return function(e,t){if(!EF(t.kc))throw t.Uc(`${e._methodName}() can only be used with update() and set()`);if(!t.path)throw t.Uc(`${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.Fc&&4!==e.kc)throw e.Uc("Nested arrays are not supported");return function(t){const n=[];let r=0;for(const i of s){let e=UF(i,t.Bc(r));null==e&&(e={nullValue:"NULL_VALUE"}),n.push(e),r++}return{arrayValue:{values:n}}}(e)}return function(e,t){if(null===(e=Kd(s)))return{nullValue:"NULL_VALUE"};if("number"==typeof e)return ux(t.N,e);if("boolean"==typeof e)return{booleanValue:e};if("string"==typeof e)return{stringValue:e};if(e instanceof Date){var n=zR.fromDate(e);return{timestampValue:lD(t.N,n)}}if(e instanceof zR){n=new zR(e.seconds,1e3*Math.floor(e.nanoseconds/1e3));return{timestampValue:lD(t.N,n)}}if(e instanceof wF)return{geoPointValue:{latitude:e.latitude,longitude:e.longitude}};if(e instanceof yF)return{bytesValue:uD(t.N,e._byteString)};if(e instanceof GM){const r=t.databaseId,i=e.firestore._databaseId;if(!i.isEqual(r))throw t.Uc(`Document reference is for database ${i.projectId}/${i.database} but should be for database ${r.projectId}/${r.database}`);return{referenceValue:dD(e.firestore._databaseId||t.databaseId,e._key.path)}}throw t.Uc(`Unsupported field value: ${$M(e)}`)}(0,e)}function jF(e,r){const i={};return QR(e)?r.path&&0<r.path.length&&r.fieldMask.push(r.path):GR(e,(e,t)=>{var n=UF(t,r.Oc(e));null!=n&&(i[e]=n)}),{mapValue:{fields:i}}}function qF(e){return!("object"!=typeof e||null===e||e instanceof Array||e instanceof Date||e instanceof zR||e instanceof wF||e instanceof yF||e instanceof GM||e instanceof _F)}function VF(e,t,n){if(!qF(n)||("object"!=typeof(i=n)||null===i||Object.getPrototypeOf(i)!==Object.prototype&&null!==Object.getPrototypeOf(i))){var r=$M(n);throw"an object"===r?t.Uc(e+" a custom object"):t.Uc(e+" "+r)}var i}function BF(e,t,n){if((t=Kd(t))instanceof vF)return t._internalPath;if("string"==typeof t)return KF(e,t);throw zF("Field path arguments must be of type string or FieldPath.",e,!1,void 0,n)}const $F=new RegExp("[~\\*/\\[\\]]");function KF(t,n,r){if(0<=n.search($F))throw zF(`Invalid field path (${n}). Paths must not contain '~', '*', '/', '[', or ']'`,t,!1,void 0,r);try{return new vF(...n.split("."))._internalPath}catch(e){throw zF(`Invalid field path (${n}). Paths must not be empty, begin with '.', end with '.', or contain '..'`,t,!1,void 0,r)}}function zF(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 WF(e,t){return e.some(e=>e.isEqual(t))}class HF{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 GM(this._firestore,this._converter,this._key)}exists(){return null!==this._document}data(){if(this._document){if(this._converter){var e=new GF(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(QF("DocumentSnapshot.get",e));if(null!==t)return this._userDataWriter.convertValue(t)}}}class GF extends HF{data(){return super.data()}}function QF(e,t){return"string"==typeof t?KF(e,t):(t instanceof vF?t:t._delegate)._internalPath}class YF{constructor(e,t){this.hasPendingWrites=e,this.fromCache=t}isEqual(e){return this.hasPendingWrites===e.hasPendingWrites&&this.fromCache===e.fromCache}}class JF extends HF{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 XF(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(QF("DocumentSnapshot.get",e));if(null!==n)return this._userDataWriter.convertValue(n,t.serverTimestamps)}}}class XF extends JF{data(e={}){return super.data(e)}}class ZF{constructor(e,t,n,r){this._firestore=e,this._userDataWriter=t,this._snapshot=r,this.metadata=new YF(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 XF(this._firestore,this._userDataWriter,e.key,e,new YF(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 XF(s._firestore,s._userDataWriter,e.doc.key,e.doc,new YF(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 XF(s._firestore,s._userDataWriter,e.doc.key,e.doc,new YF(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 eU(e,t){return e instanceof JF&&t instanceof JF?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 ZF&&t instanceof ZF&&e._firestore===t._firestore&&eF(e.query,t.query)&&e.metadata.isEqual(t.metadata)&&e._snapshot.isEqual(t._snapshot)}function tU(e){if(YP(e)&&0===e.explicitOrderBy.length)throw new xR(PR.UNIMPLEMENTED,"limitToLast() queries require specifying at least one orderBy() clause")}class nU{}function rU(e,...t){for(const n of t)e=n._apply(e);return e}class iU extends nU{constructor(e,t,n){super(),this.Gc=e,this.zc=t,this.Hc=n,this.type="where"}_apply(e){var t=CF(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 FieldPath.documentId().`);if("in"===s||"not-in"===s){hU(o,s);const t=[];for(const n of o)t.push(uU(r,e,n));a={arrayValue:{values:t}}}else a=uU(r,e,o)}else"in"!==s&&"not-in"!==s&&"array-contains-any"!==s||hU(o,s),a=FF(n,t,o,"in"===s||"not-in"===s);var c=xP.create(i,s,a);return function(e,t){if(t.v()){const r=XP(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=JP(e);null!==n&&dU(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.Gc,this.zc,this.Hc);return new QM(e.firestore,e.converter,(e=e._query,t=e.filters.concat([t]),new WP(e.path,e.collectionGroup,e.explicitOrderBy.slice(),t,e.limit,e.limitType,e.startAt,e.endAt)))}}class sU extends nU{constructor(e,t){super(),this.Gc=e,this.Jc=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 $P(t,n);return n=i,null!==JP(e=e)||null!==(r=XP(e))&&dU(0,r,n.field),i}(e._query,this.Gc,this.Jc);return new QM(e.firestore,e.converter,(e=e._query,t=e.explicitOrderBy.concat([t]),new WP(e.path,e.collectionGroup,t,e.filters.slice(),e.limit,e.limitType,e.startAt,e.endAt)))}}class oU extends nU{constructor(e,t,n){super(),this.type=e,this.Yc=t,this.Xc=n}_apply(e){return new QM(e.firestore,e.converter,nx(e._query,this.Yc,this.Xc))}}class aU extends nU{constructor(e,t,n){super(),this.type=e,this.Zc=t,this.ta=n}_apply(e){var t,n=lU(e,this.type,this.Zc,this.ta);return new QM(e.firestore,e.converter,(t=e._query,e=n,new WP(t.path,t.collectionGroup,t.explicitOrderBy.slice(),t.filters.slice(),t.limit,t.limitType,e,t.endAt)))}}class cU extends nU{constructor(e,t,n){super(),this.type=e,this.Zc=t,this.ta=n}_apply(e){var t,n=lU(e,this.type,this.Zc,this.ta);return new QM(e.firestore,e.converter,(t=e._query,e=n,new WP(t.path,t.collectionGroup,t.explicitOrderBy.slice(),t.filters.slice(),t.limit,t.limitType,t.startAt,e)))}}function lU(e,t,n,r){if(n[0]=Kd(n[0]),n[0]instanceof HF)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 ex(e))if(n.field.isKeyField())s.push(yP(t,r.key));else{const e=r.data.field(n.field);if(oP(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 VP(s,i)}(e._query,e.firestore._databaseId,t,n[0]._document,r);var i=CF(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(!ZP(e)&&-1!==l.indexOf("/"))throw new xR(PR.INVALID_ARGUMENT,`Invalid query. When querying a collection and ordering by FieldPath.documentId(), the value passed to ${r}() must be a plain document ID, but '${l}' contains a slash.`);const n=e.path.child(JR.fromString(l));if(!hP.isDocumentKey(n))throw new xR(PR.INVALID_ARGUMENT,`Invalid query. When querying a collection group and ordering by FieldPath.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 hP(n);a.push(yP(t,i))}else{const e=FF(n,r,l);a.push(e)}}return new VP(a,s)}(e._query,e.firestore._databaseId,i,t,n,r)}function uU(e,t,n){if("string"==typeof(n=Kd(n))){if(""===n)throw new xR(PR.INVALID_ARGUMENT,"Invalid query. When querying with FieldPath.documentId(), you must provide a valid document ID, but it was an empty string.");if(!ZP(t)&&-1!==n.indexOf("/"))throw new xR(PR.INVALID_ARGUMENT,`Invalid query. When querying a collection by FieldPath.documentId(), you must provide a plain document ID, but '${n}' contains a '/' character.`);var r=t.path.child(JR.fromString(n));if(!hP.isDocumentKey(r))throw new xR(PR.INVALID_ARGUMENT,`Invalid query. When querying a collection group by FieldPath.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 yP(e,new hP(r))}if(n instanceof GM)return yP(e,n._key);throw new xR(PR.INVALID_ARGUMENT,`Invalid query. When querying with FieldPath.documentId(), you must provide a valid string or a DocumentReference, but it was: ${$M(n)}.`)}function hU(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 dU(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 fU{convertValue(e,t="none"){switch(dP(e)){case 0:return null;case 1:return e.booleanValue;case 2:return iP(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(sP(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 GR(e.fields,(e,t)=>{r[e]=this.convertValue(t,n)}),r}convertGeoPoint(e){return new wF(iP(e.latitude),iP(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 oP(n)?e(n):n}(e);return null==n?null:this.convertValue(n,t);case"estimate":return this.convertTimestamp(aP(e));default:return null}}convertTimestamp(e){var t=rP(e);return new zR(t.seconds,t.nanos)}convertDocumentKey(e,t){const n=JR.fromString(e);RR(DD(n));const r=new FM(n.get(1),n.get(3)),i=new hP(n.popFirst(5));return r.isEqual(t)||kR(`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 pU(e,t,n){return e?n&&(n.merge||n.mergeFields)?e.toFirestore(t,n):e.toFirestore(t):t}class gU extends fU{constructor(e){super(),this.firestore=e}convertBytes(e){return new yF(e)}convertReference(e){var t=this.convertDocumentKey(e,this.firestore._databaseId);return new GM(this.firestore,null,t)}}class mU{constructor(e,t){this._firestore=e,this._commitHandler=t,this._mutations=[],this._committed=!1,this._dataReader=CF(e)}set(e,t,n){this._verifyNotCommitted();const r=vU(e,this._firestore),i=pU(r.converter,t,n),s=AF(this._dataReader,"WriteBatch.set",r._key,i,null!==r.converter,n);return this._mutations.push(s.toMutation(r._key,Tx.none())),this}update(e,t,n,...r){this._verifyNotCommitted();var i=vU(e,this._firestore);let s;return s="string"==typeof(t=Kd(t))||t instanceof vF?MF(this._dataReader,"WriteBatch.update",i._key,t,n,r):LF(this._dataReader,"WriteBatch.update",i._key,t),this._mutations.push(s.toMutation(i._key,Tx.exists(!0))),this}delete(e){this._verifyNotCommitted();var t=vU(e,this._firestore);return this._mutations=this._mutations.concat(new Lx(t._key,Tx.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 vU(e,t){if((e=Kd(e)).firestore!==t)throw new xR(PR.INVALID_ARGUMENT,"Provided document reference is from a different Firestore instance.");return e}class yU extends fU{constructor(e){super(),this.firestore=e}convertBytes(e){return new yF(e)}convertReference(e){var t=this.convertDocumentKey(e,this.firestore._databaseId);return new GM(this.firestore,null,t)}}function _U(t){t=KM(t,GM);const n=KM(t.firestore,cF),e=lF(n),r=new yU(n);return function(e,t){const n=new DR;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.Qn.An(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=PL(e,`Failed to get document '${t} from cache`);n.reject(r)}}(await NM(e),t,n)),n.promise}(e,t._key).then(e=>new JF(n,r,t._key,e,new YF(null!==e&&e.hasLocalMutations,!0),t.converter))}function wU(t){t=KM(t,QM);const n=KM(t.firestore,cF),e=lF(n),r=new yU(n);return function(e,t){const n=new DR;return e.asyncQueue.enqueueAndForget(async()=>async function(e,t,n){try{const i=await A1(e,t,!0),s=new HL(t,i.Gn),o=s.bo(i.documents),a=s.applyChanges(o,!1);n.resolve(a.snapshot)}catch(e){var r=PL(e,`Failed to execute query '${t} against cache`);n.reject(r)}}(await NM(e),t,n)),n.promise}(e,t._query).then(e=>new ZF(n,r,t,e))}function bU(e,t,n){e=KM(e,GM);var r=KM(e.firestore,cF),i=pU(e.converter,t,n);return SU(r,[AF(CF(r),"setDoc",e._key,i,null!==e.converter,n).toMutation(e._key,Tx.none())])}function IU(e,t,n,...r){e=KM(e,GM);var i=KM(e.firestore,cF),s=CF(i);let o;return o="string"==typeof(t=Kd(t))||t instanceof vF?MF(s,"updateDoc",e._key,t,n,r):LF(s,"updateDoc",e._key,t),SU(i,[o.toMutation(e._key,Tx.exists(!0))])}function TU(t,...n){var e;t=Kd(t);let r={includeMetadataChanges:!1},i=0;"object"!=typeof n[i]||nF(n[i])||(r=n[i],i++);var s={includeMetadataChanges:r.includeMetadataChanges};if(nF(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 GM)a=KM(t.firestore,cF),c=GP(t._key.path),o={next:e=>{n[i]&&n[i](kU(a,t,e))},error:n[i+1],complete:n[i+2]};else{const l=KM(t,QM);a=KM(l.firestore,cF),c=l._query;const u=new yU(a);o={next:e=>{n[i]&&n[i](new ZF(a,u,l,e))},error:n[i+1],complete:n[i+2]},tU(t._query)}return function(e,t,n,r){const i=new _M(r),s=new qL(t,i,n);return e.asyncQueue.enqueueAndForget(async()=>FL(await xM(e),s)),()=>{i.ec(),e.asyncQueue.enqueueAndForget(async()=>UL(await xM(e),s))}}(lF(a),c,s,o)}function EU(e,t){return function(e,t){const n=new _M(t);return e.asyncQueue.enqueueAndForget(async()=>function(e,t){e.so.add(t),t.next()}(await xM(e),n)),()=>{n.ec(),e.asyncQueue.enqueueAndForget(async()=>function(e,t){e.so.delete(t)}(await xM(e),n))}}(lF(e=KM(e,cF)),nF(t)?t:{next:t})}function SU(e,t){return function(e,t){const n=new DR;return e.asyncQueue.enqueueAndForget(async()=>XL(await PM(e),t,n)),n.promise}(lF(e),t)}function kU(e,t,n){var r=n.docs.get(t._key),i=new yU(e);return new JF(e,i,t._key,r,new YF(n.hasPendingWrites,n.fromCache),t.converter)}class CU extends class{constructor(e,t){this._firestore=e,this._transaction=t,this._dataReader=CF(e)}get(e){const n=vU(e,this._firestore),r=new gU(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 HF(this._firestore,r,t.key,t,n.converter);if(t.isNoDocument())return new HF(this._firestore,r,n._key,null,n.converter);throw NR()})}set(e,t,n){var r=vU(e,this._firestore),i=pU(r.converter,t,n),i=AF(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=vU(e,this._firestore),s="string"==typeof(t=Kd(t))||t instanceof vF?MF(this._dataReader,"Transaction.update",i._key,t,n,r):LF(this._dataReader,"Transaction.update",i._key,t);return this._transaction.update(i._key,s),this}delete(e){var t=vU(e,this._firestore);return this._transaction.delete(t._key),this}}{constructor(e,t){super(e,t),this._firestore=e}get(e){const t=vU(e,this._firestore),n=new yU(this._firestore);return super.get(e).then(e=>new JF(this._firestore,n,t._key,e._document,new YF(!1,!1),t.converter))}}function AU(t,n){return function(t,n){const r=new DR;return t.asyncQueue.enqueueAndForget(async()=>{var e=await CM(t).then(e=>e.datastore);new IM(t.asyncQueue,e,n,r).run()}),r.promise}(lF(t=KM(t,cF)),e=>n(new CU(t,e)))}W=mf,IR=W,df(new zd("firestore",(e,{options:t})=>{const n=e.getProvider("app").getImmediate(),r=new cF(n,new FR(e.getProvider("auth-internal")));return t=Object.assign({useFetchStreams:!0},t),r._setSettings(t),r},"PUBLIC")),wf(wR,"3.3.1",void 0),wf(wR,"3.3.1","esm2017");function NU(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 RU(){if("undefined"==typeof Uint8Array)throw new xR("unimplemented","Uint8Arrays are not available in this environment.")}function PU(){if("undefined"==typeof atob)throw new xR("unimplemented","Blobs are unavailable in Firestore in this environment.")}class xU{constructor(e){this._delegate=e}static fromBase64String(e){return PU(),new xU(yF.fromBase64String(e))}static fromUint8Array(e){return RU(),new xU(yF.fromUint8Array(e))}toBase64(){return PU(),this._delegate.toBase64()}toUint8Array(){return RU(),this._delegate.toUint8Array()}isEqual(e){return this._delegate.isEqual(e._delegate)}toString(){return"Blob(base64: "+this.toBase64()+")"}}function DU(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 OU{enableIndexedDbPersistence(e,t){return function(e,t){mF(e=KM(e,cF));var n=lF(e),r=e._freezeSettings(),i=new vM;return hF(n,i,new gM(i,r.cacheSizeBytes,null==t?void 0:t.forceOwnership))}(e._delegate,{forceOwnership:t})}enableMultiTabIndexedDbPersistence(e){return function(e){mF(e=KM(e,cF));var t=lF(e),n=e._freezeSettings(),r=new vM;return hF(t,r,new mM(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 DR;return e._queue.enqueueAndForgetEvenWhileRestricted(async()=>{try{await async function(e){if(!iO.bt())return Promise.resolve();var t=e+"main";await iO.delete(t)}(g1(e._databaseId,e._persistenceKey)),t.resolve()}catch(e){t.reject(e)}}),t.promise}(e._delegate)}}class LU{constructor(e,t,n){this._delegate=t,this._persistenceProvider=n,this.INTERNAL={delete:()=>this.terminate()},e instanceof FM||(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=KM(n,HM))._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._credentials=new MR(new OR(e,t))}}(this._delegate,e,t,n)}enableNetwork(){return fF(this._delegate)}disableNetwork(){return pF(this._delegate)}enablePersistence(e){let t=!1,n=!1;return e&&(t=!!e.synchronizeTabs,n=!!e.experimentalForceOwningTab,qM("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 dF(this._delegate)}onSnapshotsInSync(e){return EU(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 QU(this,JM(this._delegate,e))}catch(e){throw VU(e,"collection()","Firestore.collection()")}}doc(e){try{return new qU(this,XM(this._delegate,e))}catch(e){throw VU(e,"doc()","Firestore.doc()")}}collectionGroup(e){try{return new WU(this,function(e,t){if(e=KM(e,HM),jM("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 QM(e,null,(t=t,new WP(JR.emptyPath(),t)))}(this._delegate,e))}catch(e){throw VU(e,"collectionGroup()","Firestore.collectionGroup()")}}runTransaction(t){return AU(this._delegate,e=>t(new FU(this,e)))}batch(){return lF(this._delegate),new UU(new mU(this._delegate,e=>SU(this._delegate,e)))}loadBundle(e){return t=this._delegate,e=e,n=lF(t=KM(t,cF)),r=new rF,LM(n,t._databaseId,e,r),r;var t,n,r}namedQuery(e){return gF(this._delegate,e).then(e=>e?new WU(this,e):null)}}class MU extends fU{constructor(e){super(),this.firestore=e}convertBytes(e){return new xU(new yF(e))}convertReference(e){var t=this.convertDocumentKey(e,this.firestore._databaseId);return qU.forKey(t,this.firestore,null)}}class FU{constructor(e,t){this._firestore=e,this._delegate=t,this._userDataWriter=new MU(e)}get(e){const t=YU(e);return this._delegate.get(t).then(e=>new KU(this._firestore,new JF(this._firestore._delegate,this._userDataWriter,e._key,e._document,e.metadata,t.converter)))}set(e,t,n){var r=YU(e);return n?(NU("Transaction.set",n),this._delegate.set(r,t,n)):this._delegate.set(r,t),this}update(e,t,n,...r){var i=YU(e);return 2===arguments.length?this._delegate.update(i,t):this._delegate.update(i,t,n,...r),this}delete(e){var t=YU(e);return this._delegate.delete(t),this}}class UU{constructor(e){this._delegate=e}set(e,t,n){var r=YU(e);return n?(NU("WriteBatch.set",n),this._delegate.set(r,t,n)):this._delegate.set(r,t),this}update(e,t,n,...r){var i=YU(e);return 2===arguments.length?this._delegate.update(i,t):this._delegate.update(i,t,n,...r),this}delete(e){var t=YU(e);return this._delegate.delete(t),this}commit(){return this._delegate.commit()}}class jU{constructor(e,t,n){this._firestore=e,this._userDataWriter=t,this._delegate=n}fromFirestore(e,t){var n=new XF(this._firestore._delegate,this._userDataWriter,e._key,e._document,e.metadata,null);return this._delegate.fromFirestore(new zU(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=jU.INSTANCES;let r=n.get(e);r||(r=new WeakMap,n.set(e,r));let i=r.get(t);return i||(i=new jU(e,new MU(e),t),r.set(t,i)),i}}jU.INSTANCES=new WeakMap;class qU{constructor(e,t){this.firestore=e,this._delegate=t,this._userDataWriter=new MU(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 qU(t,new GM(t._delegate,n,new hP(e)))}static forKey(e,t,n){return new qU(t,new GM(t._delegate,n,e))}get id(){return this._delegate.id}get parent(){return new QU(this.firestore,this._delegate.parent)}get path(){return this._delegate.path}collection(e){try{return new QU(this.firestore,JM(this._delegate,e))}catch(e){throw VU(e,"collection()","DocumentReference.collection()")}}isEqual(e){return(e=Kd(e))instanceof GM&&ZM(this._delegate,e)}set(e,t){t=NU("DocumentReference.set",t);try{return t?bU(this._delegate,e,t):bU(this._delegate,e)}catch(e){throw VU(e,"setDoc()","DocumentReference.set()")}}update(e,t,...n){try{return 1===arguments.length?IU(this._delegate,e):IU(this._delegate,e,t,...n)}catch(e){throw VU(e,"updateDoc()","DocumentReference.update()")}}delete(){return SU(KM((e=this._delegate).firestore,cF),[new Lx(e._key,Tx.none())]);var e}onSnapshot(...e){var t=BU(e),n=$U(e,e=>new KU(this.firestore,new JF(this.firestore._delegate,this._userDataWriter,e._key,e._document,e.metadata,this._delegate.converter)));return TU(this._delegate,t,n)}get(e){let t;return t=("cache"===(null==e?void 0:e.source)?_U:"server"===(null==e?void 0:e.source)?function(t){t=KM(t,GM);const n=KM(t.firestore,cF);return DM(lF(n),t._key,{source:"server"}).then(e=>kU(n,t,e))}:function(t){t=KM(t,GM);const n=KM(t.firestore,cF);return DM(lF(n),t._key).then(e=>kU(n,t,e))})(this._delegate),t.then(e=>new KU(this.firestore,new JF(this.firestore._delegate,this._userDataWriter,e._key,e._document,e.metadata,this._delegate.converter)))}withConverter(e){return new qU(this.firestore,e?this._delegate.withConverter(jU.getInstance(this.firestore,e)):this._delegate.withConverter(null))}}function VU(e,t,n){return e.message=e.message.replace(t,n),e}function BU(e){for(const t of e)if("object"==typeof t&&!DU(t))return t;return{}}function $U(e,t){var n;let r;return r=DU(e[0])?e[0]:DU(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 KU{constructor(e,t){this._firestore=e,this._delegate=t}get ref(){return new qU(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 eU(this._delegate,e._delegate)}}class zU extends KU{data(e){var t=this._delegate.data(e);return void 0!==t||NR(),t}}class WU{constructor(e,t){this.firestore=e,this._delegate=t,this._userDataWriter=new MU(e)}where(e,t,n){try{return new WU(this.firestore,rU(this._delegate,(r=n,i=t,s=QF("where",e),new iU(s,i,r))))}catch(e){throw VU(e,/(orderBy|where)\(\)/,"Query.$1()")}var r,i,s}orderBy(e,t){try{return new WU(this.firestore,rU(this._delegate,([n,r="asc"]=[e,t],i=r,s=QF("orderBy",n),new sU(s,i))))}catch(e){throw VU(e,/(orderBy|where)\(\)/,"Query.$1()")}var n,r,i,s}limit(e){try{return new WU(this.firestore,rU(this._delegate,(zM("limit",t=e),new oU("limit",t,"F"))))}catch(e){throw VU(e,"limit()","Query.limit()")}var t}limitToLast(e){try{return new WU(this.firestore,rU(this._delegate,(zM("limitToLast",t=e),new oU("limitToLast",t,"L"))))}catch(e){throw VU(e,"limitToLast()","Query.limitToLast()")}var t}startAt(...e){try{return new WU(this.firestore,rU(this._delegate,function(...e){return new aU("startAt",e,!0)}(...e)))}catch(e){throw VU(e,"startAt()","Query.startAt()")}}startAfter(...e){try{return new WU(this.firestore,rU(this._delegate,function(...e){return new aU("startAfter",e,!1)}(...e)))}catch(e){throw VU(e,"startAfter()","Query.startAfter()")}}endBefore(...e){try{return new WU(this.firestore,rU(this._delegate,function(...e){return new cU("endBefore",e,!0)}(...e)))}catch(e){throw VU(e,"endBefore()","Query.endBefore()")}}endAt(...e){try{return new WU(this.firestore,rU(this._delegate,function(...e){return new cU("endAt",e,!1)}(...e)))}catch(e){throw VU(e,"endAt()","Query.endAt()")}}isEqual(e){return eF(this._delegate,e._delegate)}get(e){let t;return t=("cache"===(null==e?void 0:e.source)?wU:"server"===(null==e?void 0:e.source)?function(t){t=KM(t,QM);const n=KM(t.firestore,cF),e=lF(n),r=new yU(n);return OM(e,t._query,{source:"server"}).then(e=>new ZF(n,r,t,e))}:function(t){t=KM(t,QM);const n=KM(t.firestore,cF),e=lF(n),r=new yU(n);return tU(t._query),OM(e,t._query).then(e=>new ZF(n,r,t,e))})(this._delegate),t.then(e=>new GU(this.firestore,new ZF(this.firestore._delegate,this._userDataWriter,this._delegate,e._snapshot)))}onSnapshot(...e){var t=BU(e),n=$U(e,e=>new GU(this.firestore,new ZF(this.firestore._delegate,this._userDataWriter,this._delegate,e._snapshot)));return TU(this._delegate,t,n)}withConverter(e){return new WU(this.firestore,e?this._delegate.withConverter(jU.getInstance(this.firestore,e)):this._delegate.withConverter(null))}}class HU{constructor(e,t){this._firestore=e,this._delegate=t}get type(){return this._delegate.type}get doc(){return new zU(this._firestore,this._delegate.doc)}get oldIndex(){return this._delegate.oldIndex}get newIndex(){return this._delegate.newIndex}}class GU{constructor(e,t){this._firestore=e,this._delegate=t}get query(){return new WU(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 zU(this._firestore,e))}docChanges(e){return this._delegate.docChanges(e).map(e=>new HU(this._firestore,e))}forEach(t,n){this._delegate.forEach(e=>{t.call(n,new zU(this._firestore,e))})}isEqual(e){return eU(this._delegate,e._delegate)}}class QU extends WU{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 qU(this.firestore,e):null}doc(e){try{return void 0===e?new qU(this.firestore,XM(this._delegate)):new qU(this.firestore,XM(this._delegate,e))}catch(e){throw VU(e,"doc()","CollectionReference.doc()")}}add(e){return function(e,t){const n=KM(e.firestore,cF),r=XM(e),i=pU(e.converter,t);return SU(n,[AF(CF(e.firestore),"addDoc",r._key,i,null!==e.converter,{}).toMutation(r._key,Tx.exists(!1))]).then(()=>r)}(this._delegate,e).then(e=>new qU(this.firestore,e))}isEqual(e){return ZM(this._delegate,e._delegate)}withConverter(e){return new QU(this.firestore,e?this._delegate.withConverter(jU.getInstance(this.firestore,e)):this._delegate.withConverter(null))}}function YU(e){return KM(e,GM)}const JU={Firestore:LU,GeoPoint:wF,Timestamp:zR,Blob:xU,Transaction:FU,WriteBatch:UU,DocumentReference:qU,DocumentSnapshot:KU,Query:WU,QueryDocumentSnapshot:zU,QuerySnapshot:GU,CollectionReference:QU,FieldPath:class Q${constructor(...e){this._delegate=new vF(...e)}static documentId(){return new Q$(ZR.keyField().canonicalString())}isEqual(e){return(e=Kd(e))instanceof vF&&this._delegate._internalPath.isEqual(e._internalPath)}},FieldValue:class Y${constructor(e){this._delegate=e}static serverTimestamp(){const e=new PF("serverTimestamp");return e._methodName="FieldValue.serverTimestamp",new Y$(e)}static delete(){const e=new NF("deleteField");return e._methodName="FieldValue.delete",new Y$(e)}static arrayUnion(...e){const t=function(...e){return new xF("arrayUnion",e)}(...e);return t._methodName="FieldValue.arrayUnion",new Y$(t)}static arrayRemove(...e){const t=function(...e){return new DF("arrayRemove",e)}(...e);return t._methodName="FieldValue.arrayRemove",new Y$(t)}static increment(e){const t=new OF("increment",e);return t._methodName="FieldValue.increment",new Y$(t)}isEqual(e){return this._delegate.isEqual(e._delegate)}},setLogLevel:function(e){e=e,TR.setLogLevel(e)},CACHE_SIZE_UNLIMITED:-1};iF=Af,sF=(e,t)=>new LU(e,t,new OU),iF.INTERNAL.registerComponent(new zd("firestore-compat",e=>{var t=e.getProvider("app-compat").getImmediate(),n=e.getProvider("firestore").getImmediate();return sF(t,n)},"PUBLIC").setServiceProps(Object.assign({},JU))),iF.registerVersion("@firebase/firestore-compat","0.1.8");function XU(e,t){const n={};for(const r in e)e.hasOwnProperty(r)&&(n[r]=t(e[r]));return n}function ZU(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=>ZU(e)):"function"==typeof e||"object"==typeof e?XU(e,e=>ZU(e)):e}const ej="functions",tj={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 nj extends gd{constructor(e,t,n){super(`${ej}/${e}`,t||""),this.details=n}}function rj(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(!tj[e])return new nj("internal","internal");n=tj[e],r=e}var o=s.message;"string"==typeof o&&(r=o),i=s.details,void 0!==i&&(i=ZU(i))}}catch(e){}return"ok"===n?null:new nj(n,r,i)}class ij{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 sj="us-central1";class oj{constructor(e,t,n,r,i=sj,s){this.app=e,this.fetchImpl=s,this.emulatorOrigin=null,this.contextProvider=new ij(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=sj}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 aj(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 XU(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 nj("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 nj("cancelled","Firebase Functions instance was deleted.");var h=rj(u.status,u.json);if(h)throw h;if(!u.json)throw new nj("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 nj("internal","Response is missing data field.");h=ZU(d);return{data:h}}(t,n,e,r||{})}const cj="@firebase/functions";function lj(e,t,n){Kd(e).emulatorOrigin=`http://${t}:${n}`}oF=fetch.bind(self),df(new zd(ej,(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 oj(n,r,i,s,t,oF)},"PUBLIC").setMultipleInstances(!0)),wf(cj,"0.7.6",aF),wf(cj,"0.7.6","esm2017");var uj,hj,dj,fj;class pj{constructor(e,t){this.app=e,this._delegate=t,this._region=this._delegate.region,this._customDomain=this._delegate.customDomain}httpsCallable(e,t){return aj(Kd(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 lj(this._delegate,t[1],Number(t[2]))}useEmulator(e,t){return lj(this._delegate,e,t)}}const gj="us-central1",mj=(e,{instanceIdentifier:t})=>{var n=e.getProvider("app-compat").getImmediate(),r=e.getProvider("functions").getImmediate({identifier:null!=t?t:gj});return new pj(n,r)};uj={Functions:pj},Af.INTERNAL.registerComponent(new zd("functions-compat",mj,"PUBLIC").setServiceProps(uj).setMultipleInstances(!0)),Af.registerVersion("@firebase/functions-compat","0.1.7");const vj="/firebase-messaging-sw.js",yj="/firebase-cloud-messaging-push-scope",_j="BDOU99-h67HcA6JeFXHbSNMu7e2yNNu3RzoMj8TM4W88jITfq7ZmPvIM1Iv-4_l2LxQcYwhqby2xGpWwzjfAnG4",wj="https://fcmregistrations.googleapis.com/v1",bj="google.c.a.c_id",Ij="google.c.a.e";function Tj(e){var t=new Uint8Array(e);const n=btoa(String.fromCharCode(...t));return n.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}(yt=PB=PB||{})[yt.DATA_MESSAGE=1]="DATA_MESSAGE",yt[yt.DISPLAY_NOTIFICATION=3]="DISPLAY_NOTIFICATION",(yt=hj=hj||{}).PUSH_RECEIVED="push-received",yt.NOTIFICATION_CLICKED="notification-clicked";const Ej="fcm_token_details_db",Sj="fcm_token_object_Store";async function kj(s){if("databases"in indexedDB){const t=await indexedDB.databases(),n=t.map(e=>e.name);if(!n.includes(Ej))return null}let o=null;const e=await Vf(Ej,5,async e=>{var t;if(!(e.oldVersion<2)&&e.objectStoreNames.contains(Sj)){const i=e.transaction.objectStore(Sj);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:Tj(n.vapidKey)}}):3===e.oldVersion?(n=r,o={token:n.fcmToken,createTime:n.createTime,subscriptionOptions:{auth:Tj(n.auth),p256dh:Tj(n.p256dh),endpoint:n.endpoint,swScope:n.swScope,vapidKey:Tj(n.vapidKey)}}):4===e.oldVersion&&(r=r,o={token:r.fcmToken,createTime:r.createTime,subscriptionOptions:{auth:Tj(r.auth),p256dh:Tj(r.p256dh),endpoint:r.endpoint,swScope:r.swScope,vapidKey:Tj(r.vapidKey)}}))}});return e.close(),await Bf(Ej),await Bf("fcm_vapid_details_db"),await Bf("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 Cj="firebase-messaging-database",Aj=1,Nj="firebase-messaging-store";let Rj=null;function Pj(){return Rj=Rj||Vf(Cj,Aj,e=>{0===e.oldVersion&&e.createObjectStore(Nj)}),Rj}async function xj(e){var t=Oj(e);const n=await Pj();t=await n.transaction(Nj).objectStore(Nj).get(t);if(t)return t;t=await kj(e.appConfig.senderId);return t?(await Dj(e,t),t):void 0}async function Dj(e,t){var n=Oj(e);const r=await Pj(),i=r.transaction(Nj,"readwrite");return await i.objectStore(Nj).put(t,n),await i.complete,t}function Oj({appConfig:e}){return e.appId}const Lj=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 Mj(e,t){var n={method:"DELETE",headers:await Uj(e)};try{const s=await fetch(`${Fj(e.appConfig)}/${t}`,n);var r=await s.json();if(r.error){var i=r.error.message;throw Lj.create("token-unsubscribe-failed",{errorInfo:i})}}catch(e){throw Lj.create("token-unsubscribe-failed",{errorInfo:e})}}function Fj({projectId:e}){return`${wj}/projects/${e}/registrations`}async function Uj({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 jj({p256dh:e,auth:t,endpoint:n,vapidKey:r}){const i={web:{endpoint:n,auth:t,p256dh:e}};return r!==_j&&(i.web.applicationPubKey=r),i}const qj=6048e5;async function Vj(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:Tj(t.getKey("auth")),p256dh:Tj(t.getKey("p256dh"))},c=await xj(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+qj?async function(t,e){try{var n=await async function(e,t){var n=await Uj(e),r=jj(t.subscriptionOptions),r={method:"PATCH",headers:n,body:JSON.stringify(r)};let i;try{const s=await fetch(`${Fj(e.appConfig)}/${t.token}`,r);i=await s.json()}catch(e){throw Lj.create("token-update-failed",{errorInfo:e})}if(i.error){r=i.error.message;throw Lj.create("token-update-failed",{errorInfo:r})}if(!i.token)throw Lj.create("token-update-no-token");return i.token}(t.firebaseDependencies,e),r=Object.assign(Object.assign({},e),{token:n,createTime:Date.now()});return await Dj(t.firebaseDependencies,r),n}catch(e){throw await Bj(t),e}}(e,{token:c.token,createTime:Date.now(),subscriptionOptions:a}):c.token;try{await Mj(e.firebaseDependencies,c.token)}catch(e){console.warn(e)}return $j(e.firebaseDependencies,a)}return $j(e.firebaseDependencies,a)}async function Bj(e){var t=await xj(e.firebaseDependencies);t&&(await Mj(e.firebaseDependencies,t.token),await async function(e){var t=Oj(e);const n=await Pj(),r=n.transaction(Nj,"readwrite");await r.objectStore(Nj).delete(t),await r.complete}(e.firebaseDependencies));const n=await e.swRegistration.pushManager.getSubscription();return!n||n.unsubscribe()}async function $j(e,t){var n={token:await async function(e,t){var n=await Uj(e),r=jj(t),r={method:"POST",headers:n,body:JSON.stringify(r)};let i;try{const s=await fetch(Fj(e.appConfig),r);i=await s.json()}catch(e){throw Lj.create("token-subscribe-failed",{errorInfo:e})}if(i.error){r=i.error.message;throw Lj.create("token-subscribe-failed",{errorInfo:r})}if(!i.token)throw Lj.create("token-subscribe-no-token");return i.token}(e,t),createTime:Date.now(),subscriptionOptions:t};return await Dj(e,n),n.token}function Kj(e){var t,n,r,i={from:e.from,collapseKey:e.collapse_key,messageId:e.fcm_message_id};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 zj(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 Wj(e){return Lj.create("missing-app-config-values",{valueName:e})}zj("hts/frbslgigp.ogepscmv/ieo/eaylg","tp:/ieaeogn-agolai.o/1frlglgc/o"),zj("AzSCbw63g1R0nCw85jG8","Iaya3yLKwmgvh7cF0q4");class Hj{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 Wj("App Configuration Object");if(!e.name)throw Wj("App Name");var t=e["options"];for(const n of["projectId","apiKey","appId","messagingSenderId"])if(!t[n])throw Wj(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 Gj(e){try{e.swRegistration=await navigator.serviceWorker.register(vj,{scope:yj}),e.swRegistration.update().catch(()=>{})}catch(e){throw Lj.create("failed-service-worker-registration",{browserErrorMessage:e.message})}}async function Qj(e,t){if(!navigator)throw Lj.create("only-available-in-window");if("default"===Notification.permission&&await Notification.requestPermission(),"granted"!==Notification.permission)throw Lj.create("permission-blocked");var n,r;return n=e,await((r=null==t?void 0:t.vapidKey)?n.vapidKey=r:n.vapidKey||(n.vapidKey=_j)),await async function(e,t){if(t||e.swRegistration||await Gj(e),t||!e.swRegistration){if(!(t instanceof ServiceWorkerRegistration))throw Lj.create("invalid-sw-registration");e.swRegistration=t}}(e,null==t?void 0:t.serviceWorkerRegistration),Vj(e)}async function Yj(e,t,n){var r=function(e){switch(e){case hj.NOTIFICATION_CLICKED:return"notification_open";case hj.PUSH_RECEIVED:return"notification_foreground";default:throw new Error}}(t);const i=await e.firebaseDependencies.analyticsProvider.get();i.logEvent(r,{message_id:n[bj],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 Jj(e,t){var n,r=t.data;r.isFirebaseMessaging&&(e.onMessageHandler&&r.messageType===hj.PUSH_RECEIVED&&("function"==typeof e.onMessageHandler?e.onMessageHandler(Kj(r)):e.onMessageHandler.next(Kj(r))),n=r.data,"object"==typeof(t=n)&&t&&bj in t&&"1"===n[Ij]&&await Yj(e,r.messageType,n))}const Xj="@firebase/messaging",Zj=e=>{const t=new Hj(e.getProvider("app").getImmediate(),e.getProvider("installations-internal").getImmediate(),e.getProvider("analytics-internal"));return navigator.serviceWorker.addEventListener("message",e=>Jj(t,e)),t},eq=e=>{const t=e.getProvider("messaging").getImmediate();return{getToken:e=>Qj(t,e)}};function tq(e){return async function(e){if(!navigator)throw Lj.create("only-available-in-window");return e.swRegistration||await Gj(e),Bj(e)}(e=Kd(e))}function nq(e,t){return function(e,t){if(!navigator)throw Lj.create("only-available-in-window");return e.onMessageHandler=t,()=>{e.onMessageHandler=null}}(e=Kd(e),t)}df(new zd("messaging",Zj,"PUBLIC")),df(new zd("messaging-internal",eq,"PRIVATE")),wf(Xj,"0.9.4"),wf(Xj,"0.9.4","esm2017");const rq="BDOU99-h67HcA6JeFXHbSNMu7e2yNNu3RzoMj8TM4W88jITfq7ZmPvIM1Iv-4_l2LxQcYwhqby2xGpWwzjfAnG4",iq="https://fcmregistrations.googleapis.com/v1",sq="FCM_MSG",oq="google.c.a.c_id",aq=3,cq=1;function lq(e){var t=new Uint8Array(e);const n=btoa(String.fromCharCode(...t));return n.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}(yt=dj=dj||{})[yt.DATA_MESSAGE=1]="DATA_MESSAGE",yt[yt.DISPLAY_NOTIFICATION=3]="DISPLAY_NOTIFICATION",(c=fj=fj||{}).PUSH_RECEIVED="push-received",c.NOTIFICATION_CLICKED="notification-clicked";const uq="fcm_token_details_db",hq="fcm_token_object_Store";async function dq(s){if("databases"in indexedDB){const t=await indexedDB.databases(),n=t.map(e=>e.name);if(!n.includes(uq))return null}let o=null;const e=await Vf(uq,5,async e=>{var t;if(!(e.oldVersion<2)&&e.objectStoreNames.contains(hq)){const i=e.transaction.objectStore(hq);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:lq(n.vapidKey)}}):3===e.oldVersion?(n=r,o={token:n.fcmToken,createTime:n.createTime,subscriptionOptions:{auth:lq(n.auth),p256dh:lq(n.p256dh),endpoint:n.endpoint,swScope:n.swScope,vapidKey:lq(n.vapidKey)}}):4===e.oldVersion&&(r=r,o={token:r.fcmToken,createTime:r.createTime,subscriptionOptions:{auth:lq(r.auth),p256dh:lq(r.p256dh),endpoint:r.endpoint,swScope:r.swScope,vapidKey:lq(r.vapidKey)}}))}});return e.close(),await Bf(uq),await Bf("fcm_vapid_details_db"),await Bf("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 fq="firebase-messaging-database",pq=1,gq="firebase-messaging-store";let mq=null;function vq(){return mq=mq||Vf(fq,pq,e=>{0===e.oldVersion&&e.createObjectStore(gq)}),mq}async function yq(e){var t=wq(e);const n=await vq();t=await n.transaction(gq).objectStore(gq).get(t);if(t)return t;t=await dq(e.appConfig.senderId);return t?(await _q(e,t),t):void 0}async function _q(e,t){var n=wq(e);const r=await vq(),i=r.transaction(gq,"readwrite");return await i.objectStore(gq).put(t,n),await i.complete,t}function wq({appConfig:e}){return e.appId}const bq=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 Iq(e,t){var n={method:"DELETE",headers:await Eq(e)};try{const s=await fetch(`${Tq(e.appConfig)}/${t}`,n);var r=await s.json();if(r.error){var i=r.error.message;throw bq.create("token-unsubscribe-failed",{errorInfo:i})}}catch(e){throw bq.create("token-unsubscribe-failed",{errorInfo:e})}}function Tq({projectId:e}){return`${iq}/projects/${e}/registrations`}async function Eq({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 Sq({p256dh:e,auth:t,endpoint:n,vapidKey:r}){const i={web:{endpoint:n,auth:t,p256dh:e}};return r!==rq&&(i.web.applicationPubKey=r),i}async function kq(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:lq(t.getKey("auth")),p256dh:lq(t.getKey("p256dh"))},c=await yq(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 Eq(e),r=Sq(t.subscriptionOptions),r={method:"PATCH",headers:n,body:JSON.stringify(r)};let i;try{const s=await fetch(`${Tq(e.appConfig)}/${t.token}`,r);i=await s.json()}catch(e){throw bq.create("token-update-failed",{errorInfo:e})}if(i.error){r=i.error.message;throw bq.create("token-update-failed",{errorInfo:r})}if(!i.token)throw bq.create("token-update-no-token");return i.token}(t.firebaseDependencies,e),r=Object.assign(Object.assign({},e),{token:n,createTime:Date.now()});return await _q(t.firebaseDependencies,r),n}catch(e){throw await Cq(t),e}}(e,{token:c.token,createTime:Date.now(),subscriptionOptions:a}):c.token;try{await Iq(e.firebaseDependencies,c.token)}catch(e){console.warn(e)}return Aq(e.firebaseDependencies,a)}return Aq(e.firebaseDependencies,a)}async function Cq(e){var t=await yq(e.firebaseDependencies);t&&(await Iq(e.firebaseDependencies,t.token),await async function(e){var t=wq(e);const n=await vq(),r=n.transaction(gq,"readwrite");await r.objectStore(gq).delete(t),await r.complete}(e.firebaseDependencies));const n=await e.swRegistration.pushManager.getSubscription();return!n||n.unsubscribe()}async function Aq(e,t){var n={token:await async function(e,t){var n=await Eq(e),r=Sq(t),r={method:"POST",headers:n,body:JSON.stringify(r)};let i;try{const s=await fetch(Tq(e.appConfig),r);i=await s.json()}catch(e){throw bq.create("token-subscribe-failed",{errorInfo:e})}if(i.error){r=i.error.message;throw bq.create("token-subscribe-failed",{errorInfo:r})}if(!i.token)throw bq.create("token-subscribe-no-token");return i.token}(e,t),createTime:Date.now(),subscriptionOptions:t};return await _q(e,n),n.token}async function Nq(e,t){var n=function(e,t){var n;const r={};e.from&&(r.project_number=e.from);e.fcm_message_id&&(r.message_id=e.fcm_message_id);r.instance_id=t,e.notification?r.message_type=dj.DISPLAY_NOTIFICATION.toString():r.message_type=dj.DATA_MESSAGE.toString();r.sdk_platform=aq.toString(),r.package_name=self.origin.replace(/(^\w+:|^)\/\//,""),e.collapse_key&&(r.collapse_key=e.collapse_key);r.event=cq.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 Rq(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 Pq(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 Nq(t,n);var r,i,s=await Dq();if(s.some(e=>"visible"===e.visibilityState&&!e.url.startsWith("chrome-extension://")))return function(e,t){t.isFirebaseMessaging=!0,t.messageType=fj.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={[sq]:e},t}(n)),t&&t.onBackgroundMessageHandler&&(s={from:(r=n).from,collapseKey:r.collapse_key,messageId:r.fcm_message_id},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 xq(e){const t=null===(s=null===(i=e.notification)||void 0===i?void 0:i.data)||void 0===s?void 0:s[sq];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&&oq 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 Dq();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=fj.NOTIFICATION_CLICKED,t.isFirebaseMessaging=!0,e.postMessage(t)}}}}function Dq(){return self.clients.matchAll({type:"window",includeUncontrolled:!0})}function Oq(e){return bq.create("missing-app-config-values",{valueName:e})}Rq("hts/frbslgigp.ogepscmv/ieo/eaylg","tp:/ieaeogn-agolai.o/1frlglgc/o"),Rq("AzSCbw63g1R0nCw85jG8","Iaya3yLKwmgvh7cF0q4");class Lq{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 Oq("App Configuration Object");if(!e.name)throw Oq("App Name");var t=e["options"];for(const n of["projectId","apiKey","appId","messagingSenderId"])if(!t[n])throw Oq(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 Mq=e=>{const t=new Lq(e.getProvider("app").getImmediate(),e.getProvider("installations-internal").getImmediate(),e.getProvider("analytics-internal"));return self.addEventListener("push",e=>{e.waitUntil(Pq(e,t))}),self.addEventListener("pushsubscriptionchange",e=>{e.waitUntil(async function(e,t){var n;(n=e["newSubscription"])?(n=await yq(t.firebaseDependencies),await Cq(t),t.vapidKey=null!==(n=null===(n=null==n?void 0:n.subscriptionOptions)||void 0===n?void 0:n.vapidKey)&&void 0!==n?n:rq,await kq(t)):await Cq(t)}(e,t))}),self.addEventListener("notificationclick",e=>{e.waitUntil(xq(e))}),t};function Fq(e,t){return function(e,t){if(void 0!==self.document)throw bq.create("only-available-in-sw");return e.onBackgroundMessageHandler=t,()=>{e.onBackgroundMessageHandler=null}}(e=Kd(e),t)}df(new zd("messaging-sw",Mq,"PUBLIC"));var Uq,jq,qq;class Vq{constructor(e,t){this.app=e,this._delegate=t,this.app=e,this._delegate=t}async getToken(e){return async function(e,t){return Qj(e=Kd(e),t)}(this._delegate,e)}async deleteToken(){return tq(this._delegate)}onMessage(e){return nq(this._delegate,e)}onBackgroundMessage(e){return Fq(this._delegate,e)}}const Bq=e=>self&&"ServiceWorkerGlobalScope"in self?new Vq(e.getProvider("app-compat").getImmediate(),e.getProvider("messaging-sw").getImmediate()):new Vq(e.getProvider("app-compat").getImmediate(),e.getProvider("messaging").getImmediate()),$q={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()&&pd()&&"serviceWorker"in navigator&&"PushManager"in window&&"Notification"in window&&"fetch"in window&&ServiceWorkerRegistration.prototype.hasOwnProperty("showNotification")&&PushSubscription.prototype.hasOwnProperty("getKey")}};Af.INTERNAL.registerComponent(new zd("messaging-compat",Bq,"PUBLIC").setServiceProps($q)),Af.registerVersion("@firebase/messaging-compat","0.1.4");const Kq="firebasestorage.googleapis.com",zq="storageBucket";class Wq extends gd{constructor(e,t){super(Hq(e),`Firebase Storage: ${t} (${Hq(e)})`),this.customData={serverResponse:null},this._baseMessage=this.message,Object.setPrototypeOf(this,Wq.prototype)}_codeEquals(e){return Hq(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 Hq(e){return"storage/"+e}function Gq(){return new Wq("unknown","An unknown error occurred, please check the error payload for server response.")}function Qq(){return new Wq("canceled","User canceled the upload/download.")}function Yq(){return new Wq("cannot-slice-blob","Cannot slice blob for upload. Please retry the upload.")}function Jq(e){return new Wq("invalid-argument",e)}function Xq(){return new Wq("app-deleted","The Firebase app was deleted.")}function Zq(e){return new Wq("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 eV(e,t){return new Wq("invalid-format","String does not match format '"+e+"': "+t)}function tV(e){throw new Wq("internal-error","Internal error: "+e)}class nV{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=nV.makeFromUrl(t,e)}catch(e){return new nV(t,"")}if(""===n.path)return n;throw t=t,new Wq("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===Kq?"(?: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 nV(u,e),d.postModify(n);break}}if(null==n)throw t=e,new Wq("invalid-url","Invalid URL '"+t+"'.");return n}}class rV{constructor(e){this.promise_=Promise.reject(e)}getPromise(){return this.promise_}cancel(e=0){}}function iV(e){return"string"==typeof e||e instanceof String}function sV(e){return oV()&&e instanceof Blob}function oV(){return"undefined"!=typeof Blob}function aV(e,t,n,r){if(r<t)throw Jq(`Invalid value for '${e}'. Expected ${t} or greater.`);if(n<r)throw Jq(`Invalid value for '${e}'. Expected ${n} or less.`)}function cV(e,t,n){let r=null==n?`https://${t}`:t;return`${n}://${r}/v0${e}`}function lV(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=Uq=Uq||{})[c.NO_ERROR=0]="NO_ERROR",c[c.NETWORK_ERROR=1]="NETWORK_ERROR",c[c.ABORT=2]="ABORT";class uV{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 hV(!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()===Uq.NO_ERROR,n=i.getStatus();t&&!this.isRetryStatusCode_(n)?(e=-1!==this.successCodes_.indexOf(n),r(!0,new hV(e,i))):(e=i.getErrorCode()===Uq.ABORT,r(!1,new hV(!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=Gq();a.serverResponse=i.getErrorText(),this.errorCallback_?r(this.errorCallback_(i,a)):r(a)}else{var o;t.canceled?(o=(this.appDelete_?Xq:Qq)(),r(o)):(o=new Wq("retry-limit-exceeded","Max retry time for operation exceeded, please try again."),r(o))}};this.canceled_?t(0,new hV(!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(f,c())},e)}function d(){s&&clearTimeout(s)}function f(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 p=!1;function g(e){p||(p=!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 hV{constructor(e,t,n){this.wasSuccessCode=e,this.connection=t,this.canceled=!!n}}function dV(...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(oV())return new Blob(t);throw new Wq("unsupported-environment","This browser doesn't seem to support creating Blobs")}const fV={RAW:"raw",BASE64:"base64",BASE64URL:"base64url",DATA_URL:"data_url"};class pV{constructor(e,t){this.data=e,this.contentType=t||null}}function gV(e,t){switch(e){case fV.RAW:return new pV(mV(t));case fV.BASE64:case fV.BASE64URL:return new pV(vV(e,t));case fV.DATA_URL:return new pV((n=t,(r=new yV(n)).base64?vV(fV.BASE64,r.rest):function(e){let t;try{t=decodeURIComponent(e)}catch(e){throw eV(fV.DATA_URL,"Malformed data URL.")}return mV(t)}(r.rest)),(n=t,new yV(n).contentType))}var n,r;throw Gq()}function mV(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 vV(t,e){switch(t){case fV.BASE64:var n=-1!==e.indexOf("-"),r=-1!==e.indexOf("_");if(n||r)throw eV(t,"Invalid character '"+(n?"-":"_")+"' found: is it base64url encoded?");break;case fV.BASE64URL:r=-1!==e.indexOf("+"),n=-1!==e.indexOf("/");if(r||n)throw eV(t,"Invalid character '"+(r?"+":"/")+"' found: is it base64 encoded?");e=e.replace(/-/g,"+").replace(/_/g,"/")}let i;try{i=atob(e)}catch(e){throw eV(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 yV{constructor(e){this.base64=!1,this.contentType=null;var t,n,r=e.match(/^data:([^,]+)?,/);if(null===r)throw eV(fV.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 _V{constructor(e,t){let n=0,r="";sV(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(sV(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 _V(n)}var r,i,s,n=new Uint8Array(this.data_.buffer,e,t-e);return new _V(n,!0)}static getBlob(...e){if(oV()){var t=e.map(e=>e instanceof _V?e.data_:e);return new _V(dV.apply(null,t))}{const r=e.map(e=>iV(e)?gV(fV.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 _V(i,!0)}}uploadData(){return this.data_}}function wV(e){let t;try{t=JSON.parse(e)}catch(e){return null}return"object"!=typeof(e=t)||Array.isArray(e)?null:t}function bV(e){var t=e.lastIndexOf("/",e.length-2);return-1===t?e:e.slice(t+1)}function IV(e,t){return t}class TV{constructor(e,t,n,r){this.server=e,this.local=t||e,this.writable=!!n,this.xform=r||IV}}let EV=null;function SV(){if(EV)return EV;const e=[];e.push(new TV("bucket")),e.push(new TV("generation")),e.push(new TV("metageneration")),e.push(new TV("name","fullPath",!0));const t=new TV("name");t.xform=function(e,t){return!iV(t=t)||t.length<2?t:bV(t)},e.push(t);const n=new TV("size");return n.xform=function(e,t){return void 0!==t?Number(t):t},e.push(n),e.push(new TV("timeCreated")),e.push(new TV("updated")),e.push(new TV("md5Hash",null,!0)),e.push(new TV("cacheControl",null,!0)),e.push(new TV("contentDisposition",null,!0)),e.push(new TV("contentEncoding",null,!0)),e.push(new TV("contentLanguage",null,!0)),e.push(new TV("contentType",null,!0)),e.push(new TV("metadata","customMetadata",!0)),EV=e,EV}function kV(n,r){Object.defineProperty(n,"ref",{get:function(){var e=n.bucket,t=n.fullPath,t=new nV(e,t);return r._makeStorageReference(t)}})}function CV(e,t,n){var r=wV(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 kV(r,e),r}(e,r,n)}function AV(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 NV(e,t,n){var r=wV(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 nV(t,i));r.prefixes.push(i)}if(n.items)for(const a of n.items){var s=e._makeStorageReference(new nV(t,a.name));r.items.push(s)}return r}(e,t,r)}class RV{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 PV(e){if(!e)throw Gq()}function xV(r,i){return function(e,t){var n=CV(r,t,i);return PV(null!==n),n}}function DV(r,i){return function(e,t){var n=NV(r,i,t);return PV(null!==n),n}}function OV(r,i){return function(e,t){var n=CV(r,t,i);return PV(null!==n),function(r,e,i,s){var t=wV(e);if(null===t)return null;if(!iV(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 cV("/b/"+o(t)+"/o/"+o(n),i,s)+lV({alt:"media",token:e})})[0]}(n,t,r.host,r._protocol)}}function LV(i){return function(e,t){let n;var r;return n=401===e.getStatus()?e.getErrorText().includes("Firebase App Check token is invalid")?new Wq("unauthorized-app","This app does not have permission to access Firebase Storage on this project."):new Wq("unauthenticated","User is not authenticated, please authenticate using Firebase Authentication and try again."):402===e.getStatus()?(r=i.bucket,new Wq("quota-exceeded","Quota for bucket '"+r+"' exceeded, please view quota on https://firebase.google.com/pricing/.")):403===e.getStatus()?(e=i.path,new Wq("unauthorized","User does not have permission to access '"+e+"'.")):t,n.serverResponse=t.serverResponse,n}}function MV(r){const i=LV(r);return function(e,t){let n=i(e,t);return 404===e.getStatus()&&(n=(e=r.path,new Wq("object-not-found","Object '"+e+"' does not exist."))),n.serverResponse=t.serverResponse,n}}function FV(e,t,n){var r=cV(t.fullServerUrl(),e.host,e._protocol),i=e.maxOperationRetryTime;const s=new RV(r,"GET",xV(e,n),i);return s.errorHandler=MV(t),s}function UV(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 jV(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=UV(t,r,i),l="--"+a+"\r\nContent-Type: application/json; charset=utf-8\r\n\r\n"+AV(c,n)+"\r\n--"+a+"\r\nContent-Type: "+c.contentType+"\r\n\r\n",a="\r\n--"+a+"--";const u=_V.getBlob(l,r,a);if(null===u)throw Yq();a={name:c.fullPath},c=cV(s,e.host,e._protocol),s=e.maxUploadRetryTime;const h=new RV(c,"POST",xV(e,n),s);return h.urlParams=a,h.headers=o,h.body=u.uploadData(),h.errorHandler=LV(t),h}class qV{constructor(e,t,n,r){this.current=e,this.total=t,this.finalized=!!n,this.metadata=r||null}}function VV(e,t){let n=null;try{n=e.getResponseHeader("X-Goog-Upload-Status")}catch(e){PV(!1)}const r=t||["active"];return PV(!!n&&-1!==r.indexOf(n)),n}function BV(e,t,n,r,i){var s=t.bucketOnlyServerUrl(),o=UV(t,r,i),a={name:o.fullPath},c=cV(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=AV(o,n),o=e.maxUploadRetryTime;const u=new RV(c,"POST",function(e){VV(e);let t;try{t=e.getResponseHeader("X-Goog-Upload-URL")}catch(e){PV(!1)}return PV(iV(t)),t},o);return u.urlParams=a,u.headers=l,u.body=s,u.errorHandler=LV(t),u}function $V(e,t,n,i){var r=e.maxUploadRetryTime;const s=new RV(n,"POST",function(e){var t=VV(e,["active","final"]);let n=null;try{n=e.getResponseHeader("X-Goog-Upload-Size-Received")}catch(e){PV(!1)}n||PV(!1);var r=Number(n);return PV(!isNaN(r)),new qV(r,i.size(),"final"===t)},r);return s.headers={"X-Goog-Upload-Command":"query"},s.errorHandler=LV(t),s}function KV(e,o,t,a,n,c,r,i){const l=new qV(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 Wq("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 f=a.slice(h,d);if(null===f)throw Yq();d=o.maxUploadRetryTime;const p=new RV(t,"POST",function(e,t){var n=VV(e,["active","final"]),r=l.current+u,i=a.size();let s;return s="final"===n?xV(o,c)(e,t):null,new qV(r,i,"final"===n,s)},d);return p.headers=s,p.body=f.uploadData(),p.progressCallback=i||null,p.errorHandler=LV(e),p}const zV={STATE_CHANGED:"state_changed"},WV={RUNNING:"running",PAUSED:"paused",SUCCESS:"success",CANCELED:"canceled",ERROR:"error"};function HV(e){switch(e){case"running":case"pausing":case"canceling":return WV.RUNNING;case"paused":return WV.PAUSED;case"success":return WV.SUCCESS;case"canceled":return WV.CANCELED;default:return WV.ERROR}}class GV{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 QV(t){return(...e)=>{Promise.resolve().then(()=>t(...e))}}class YV extends class{constructor(){this.sent_=!1,this.xhr_=new XMLHttpRequest,this.initXhr(),this.errorCode_=Uq.NO_ERROR,this.sendPromise_=new Promise(e=>{this.xhr_.addEventListener("abort",()=>{this.errorCode_=Uq.ABORT,e()}),this.xhr_.addEventListener("error",()=>{this.errorCode_=Uq.NETWORK_ERROR,e()}),this.xhr_.addEventListener("load",()=>{e()})})}send(e,t,n,r){if(this.sent_)throw tV("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 tV("cannot .getErrorCode() before sending");return this.errorCode_}getStatus(){if(!this.sent_)throw tV("cannot .getStatus() before sending");try{return this.xhr_.status}catch(e){return-1}}getResponse(){if(!this.sent_)throw tV("cannot .getResponse() before sending");return this.xhr_.response}getErrorText(){if(!this.sent_)throw tV("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 JV(){return new YV}class XV{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=SV(),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=BV(this._ref.storage,this._ref._location,this._mappings,this._blob,this._metadata);const r=this._ref.storage._makeRequest(n,JV,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=$V(this._ref.storage,this._ref._location,i,this._blob);const r=this._ref.storage._makeRequest(n,JV,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 qV(this._transferred,this._blob.size()),o=this._uploadUrl;this._resolveToken((e,t)=>{let n;try{n=KV(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,JV,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=FV(this._ref.storage,this._ref._location,this._mappings);const r=this._ref.storage._makeRequest(n,JV,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=jV(this._ref.storage,this._ref._location,this._mappings,this._blob,this._metadata);const r=this._ref.storage._makeRequest(n,JV,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=Qq(),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=HV(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 GV(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(HV(this._state)){case WV.SUCCESS:QV(this._resolve.bind(null,this.snapshot))();break;case WV.CANCELED:case WV.ERROR:const t=this._reject;QV(t.bind(null,this._error))();break;default:e=!1}e&&(this._resolve=void 0,this._reject=void 0)}}_notifyObserver(e){switch(HV(this._state)){case WV.RUNNING:case WV.PAUSED:e.next&&QV(e.next.bind(e,this.snapshot))();break;case WV.SUCCESS:e.complete&&QV(e.complete.bind(e))();break;case WV.CANCELED:case WV.ERROR:default:e.error&&QV(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 ZV{constructor(e,t){this._service=e,t instanceof nV?this._location=t:this._location=nV.makeFromUrl(t,e.host)}toString(){return"gs://"+this._location.bucket+"/"+this._location.path}_newRef(e,t){return new ZV(e,t)}get root(){var e=new nV(this._location.bucket,"");return this._newRef(this._service,e)}get bucket(){return this._location.bucket}get fullPath(){return this._location.path}get name(){return bV(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 nV(this._location.bucket,e);return new ZV(this._service,e)}_throwIfRoot(e){if(""===this._location.path)throw Zq(e)}}function eB(e){const t={prefixes:[],items:[]};return async function e(t,n,r){const i={pageToken:r};const s=await tB(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 tB(e,t){null!=t&&"number"==typeof t.maxResults&&aV("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=cV(t.bucketOnlyServerUrl(),e.host,e._protocol),a=e.maxOperationRetryTime;const c=new RV(o,"GET",DV(e,t.bucket),a);return c.urlParams=s,c.errorHandler=LV(t),c}(e.storage,e._location,"/",n.pageToken,n.maxResults);return e.storage.makeRequestWithTokens(n,JV)}function nB(e,t){e._throwIfRoot("updateMetadata");var n=function(e,t,n,r){var i=cV(t.fullServerUrl(),e.host,e._protocol),s=AV(n,r),o=e.maxOperationRetryTime;const a=new RV(i,"PATCH",xV(e,r),o);return a.headers={"Content-Type":"application/json; charset=utf-8"},a.body=s,a.errorHandler=MV(t),a}(e.storage,e._location,t,SV());return e.storage.makeRequestWithTokens(n,JV)}function rB(e){e._throwIfRoot("getDownloadURL");var t=function(e,t,n){var r=cV(t.fullServerUrl(),e.host,e._protocol),i=e.maxOperationRetryTime;const s=new RV(r,"GET",OV(e,n),i);return s.errorHandler=MV(t),s}(e.storage,e._location,SV());return e.storage.makeRequestWithTokens(t,JV).then(e=>{if(null===e)throw new Wq("no-download-url","The given file does not have any download URLs.");return e})}function iB(e){e._throwIfRoot("deleteObject");var t=function(e,t){var n=cV(t.fullServerUrl(),e.host,e._protocol),r=e.maxOperationRetryTime;const i=new RV(n,"DELETE",function(e,t){},r);return i.successCodes=[200,204],i.errorHandler=MV(t),i}(e.storage,e._location);return e.storage.makeRequestWithTokens(t,JV)}function sB(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 nV(e._location.bucket,r);return new ZV(e.storage,r)}function oB(e,t){if(e instanceof lB){var n=e;if(null==n._bucket)throw new Wq("no-default-bucket","No default bucket found. Did you set the '"+zq+"' property when initializing the app?");n=new ZV(n,n._bucket);return null!=t?oB(n,t):n}return void 0!==t?sB(e,t):e}function aB(e,t){if(t&&/^[A-Za-z]+:\/\//.test(t)){if(e instanceof lB)return n=e,r=t,new ZV(n,r);throw Jq("To use ref(service, url), the first argument must be a Storage instance.")}return oB(e,t);var n,r}function cB(e,t){var n=null==t?void 0:t[zq];return null==n?null:nV.makeFromBucketSpec(n,e)}class lB{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=Kq,this._protocol="https",this._appId=null,this._deleted=!1,this._maxOperationRetryTime=12e4,this._maxUploadRetryTime=6e5,this._requests=new Set,this._bucket=null!=r?nV.makeFromBucketSpec(r,this._host):cB(this._host,this.app.options)}get host(){return this._host}set host(e){this._host=e,null!=this._url?this._bucket=nV.makeFromBucketSpec(this._url,e):this._bucket=cB(e,this.app.options)}get maxUploadRetryTime(){return this._maxUploadRetryTime}set maxUploadRetryTime(e){aV("time",0,Number.POSITIVE_INFINITY,e),this._maxUploadRetryTime=e}get maxOperationRetryTime(){return this._maxOperationRetryTime}set maxOperationRetryTime(e){aV("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 ZV(this,e)}_makeRequest(e,t,n,r){if(this._deleted)return new rV(Xq());{const l=(i=e,s=this._appId,o=n,e=r,n=t,r=this._firebaseVersion,a=lV(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 uV(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 uB="@firebase/storage";function hB(e,t,n){return e=Kd(e),t=t,n=n,(e=e)._throwIfRoot("uploadBytesResumable"),new XV(e,new _V(t),n)}function dB(e){return function(e){e._throwIfRoot("getMetadata");var t=FV(e.storage,e._location,SV());return e.storage.makeRequestWithTokens(t,JV)}(e=Kd(e))}function fB(e,t){return aB(e=Kd(e),t)}function pB(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 gB(e,{instanceIdentifier:t}){var n=e.getProvider("app").getImmediate(),r=e.getProvider("auth-internal"),i=e.getProvider("app-check-internal");return new lB(n,r,i,t,mf)}df(new zd("storage",gB,"PUBLIC").setMultipleInstances(!0)),wf(uB,"0.9.0",""),wf(uB,"0.9.0","esm2017");class mB{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 vB{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 mB(this._delegate.snapshot,this,this._ref)}then(t,e){return this._delegate.then(e=>{if(t)return t(new mB(e,this,this._ref))},e)}on(e,t,n,r){let i=void 0;return t&&(i="function"==typeof t?e=>t(new mB(e,this,this._ref)):{next:t.next?e=>t.next(new mB(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 yB{constructor(e,t){this._delegate=e,this._service=t}get prefixes(){return this._delegate.prefixes.map(e=>new _B(e,this._service))}get items(){return this._delegate.items.map(e=>new _B(e,this._service))}get nextPageToken(){return this._delegate.nextPageToken||null}}class _B{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=sB(this._delegate,e);return new _B(t,this.storage)}get root(){return new _B(this._delegate.root,this.storage)}get parent(){var e=this._delegate.parent;return null==e?null:new _B(e,this.storage)}put(e,t){return this._throwIfRoot("put"),new vB(hB(this._delegate,e,t),this)}putString(e,t=fV.RAW,n){this._throwIfRoot("putString");var r=gV(t,e);const i=Object.assign({},n);return null==i.contentType&&null!=r.contentType&&(i.contentType=r.contentType),new vB(new XV(this._delegate,new _V(r.data,!0),i),this)}listAll(){return eB(Kd(this._delegate)).then(e=>new yB(e,this.storage))}list(e){return t=this._delegate,e=e||void 0,tB(t=Kd(t),e).then(e=>new yB(e,this.storage));var t}getMetadata(){return dB(this._delegate)}updateMetadata(e){return nB(Kd(this._delegate),e)}getDownloadURL(){return rB(Kd(this._delegate))}delete(){return this._throwIfRoot("delete"),iB(Kd(this._delegate))}_throwIfRoot(e){if(""===this._delegate._location.path)throw Zq(e)}}class wB{constructor(e,t){this.app=e,this._delegate=t}get maxOperationRetryTime(){return this._delegate.maxOperationRetryTime}get maxUploadRetryTime(){return this._delegate.maxUploadRetryTime}ref(e){if(bB(e))throw Jq("ref() expected a child path but got a URL, use refFromURL instead.");return new _B(fB(this._delegate,e),this)}refFromURL(e){if(!bB(e))throw Jq("refFromURL() expected a full URL but got a child path, use ref() instead.");try{nV.makeFromUrl(e,this._delegate.host)}catch(e){throw Jq("refFromUrl() expected a valid full URL but got an invalid one.")}return new _B(fB(this._delegate,e),this)}setMaxUploadRetryTime(e){this._delegate.maxUploadRetryTime=e}setMaxOperationRetryTime(e){this._delegate.maxOperationRetryTime=e}useEmulator(e,t,n={}){pB(this._delegate,e,t,n)}}function bB(e){return/^[A-Za-z]+:\/\//.test(e)}function IB(e,{instanceIdentifier:t}){var n=e.getProvider("app-compat").getImmediate(),r=e.getProvider("storage").getImmediate({identifier:t});return new wB(n,r)}jq=Af,qq={TaskState:WV,TaskEvent:zV,StringFormat:fV,Storage:wB,Reference:_B},jq.INTERNAL.registerComponent(new zd("storage-compat",IB,"PUBLIC").setServiceProps(qq).setMultipleInstances(!0)),jq.registerVersion("@firebase/storage-compat","0.1.8");const TB="@firebase/performance",EB="0.5.4",SB="FB-PERF-TRACE-MEASURE",kB="@firebase/performance/config",CB="@firebase/performance/configexpire";var AB,NB,RB,PB="Performance";const xB=new md("performance",PB,{"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."}),DB=new ef(PB);DB.logLevel=Kh.INFO;let OB,LB;class MB{constructor(e){if(!(this.window=e))throw xB.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&&pd()?!!dd()||(DB.info("IndexedDB is not supported by current browswer"),!1):(DB.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===OB&&(OB=new MB(LB)),OB}}let FB;function UB(e,t){var n=e.length-t.length;if(n<0||1<n)throw xB.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 jB;class qB{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=UB("hts/frbslgigp.ogepscmv/ieo/eaylg","tp:/ieaeogn-agolai.o/1frlglgc/o"),this.transportKey=UB("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===jB&&(jB=new qB),jB}}(c=AB=AB||{})[c.UNKNOWN=0]="UNKNOWN",c[c.VISIBLE=1]="VISIBLE",c[c.HIDDEN=2]="HIDDEN";const VB=["firebase_","google_","ga_"],BB=new RegExp("^[a-zA-Z]\\w*$");function $B(){switch(MB.getInstance().document.visibilityState){case"visible":return AB.VISIBLE;case"hidden":return AB.HIDDEN;default:return AB.UNKNOWN}}function KB(e){var t=null===(t=e.options)||void 0===t?void 0:t.appId;if(!t)throw xB.create("no app id");return t}const zB="0.0.1",WB={loggingEnabled:!0},HB="FIREBASE_INSTALLATIONS_AUTH";function GB(e,t){var r,i,n=function(){const e=MB.getInstance().localStorage;if(e){var t=e.getItem(CB);if(t&&function(e){return Number(e)>Date.now()}(t)){t=e.getItem(kB);if(t)try{return JSON.parse(t)}catch(e){return}}}}();return n?(YB(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 xB.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 xB.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:`${HB} ${e}`},body:JSON.stringify({app_instance_id:i,app_instance_id_token:e,app_id:KB(r.app),app_version:EB,sdk_version:zB})});return fetch(n).then(e=>{if(e.ok)return e.json();throw xB.create("RC response not ok")})}).catch(()=>{DB.info(QB)}).then(YB).then(e=>function(e){const t=MB.getInstance().localStorage;e&&t&&(t.setItem(kB,JSON.stringify(e)),t.setItem(CB,String(Date.now()+60*qB.getInstance().configTimeToLive*60*1e3)))}(e),()=>{}))}const QB="Could not fetch config, will use default configs";function YB(e){if(!e)return e;const t=qB.getInstance();var n=e.entries||{};return void 0!==n.fpr_enabled?t.loggingEnabled="true"===String(n.fpr_enabled):t.loggingEnabled=WB.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=JB(t.tracesSamplingRate),t.logNetworkAfterSampling=JB(t.networkRequestsSamplingRate),e}function JB(e){return Math.random()<=e}let XB=1,ZB;function e$(e){var t;return XB=2,ZB=ZB||(t=e,function(){const n=MB.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=>{FB=e}),t}(t.installations)).then(e=>GB(t,e)).then(()=>t$(),()=>t$())),ZB}function t$(){XB=3}const n$=1e4,r$=3,i$=1e3;let s$=r$,o$=[],a$=!1;function c$(e){setTimeout(()=>{if(0!==s$)return o$.length?void function(){const e=o$.splice(0,i$),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:qB.getInstance().logSource,log_event:t};!function(e,r){return function(e){var t=qB.getInstance().getFlTransportFullUrl();return fetch(t,{method:"POST",body:JSON.stringify(e)})}(e).then(e=>(e.ok||DB.info("Call to Firebase backend failed."),e.json())).then(e=>{var t=Number(e.nextRequestWaitMillis);let n=n$;isNaN(t)||(n=Math.max(t,n));t=e.logResponseDetails;Array.isArray(t)&&0<t.length&&"RETRY_REQUEST_LATER"===t[0].responseAction&&(o$=[...r,...o$],DB.info("Retry transport request later.")),s$=r$,c$(n)})}(n,e).catch(()=>{o$=[...e,...o$],s$--,DB.info(`Tries left: ${s$}.`),c$(n$)})}():c$(n$)},e)}function l$(t){return(...e)=>{!function(e){if(!e.eventTime||!e.message)throw xB.create("invalid cc log");o$=[...o$,e]}({message:t(...e),eventTime:Date.now()})}}let u$;function h$(e,t){u$=u$||l$(p$),u$(e,t)}function d$(e){var t=qB.getInstance();!t.instrumentationEnabled&&e.isAuto||(t.dataCollectionEnabled||e.isAuto)&&MB.getInstance().requiredApisAvailable()&&(e.isAuto&&$B()!==AB.VISIBLE||(3===XB?f$(e):e$(e.performanceController).then(()=>f$(e),()=>f$(e))))}function f$(e){var t;!FB||(t=qB.getInstance()).loggingEnabled&&t.logTraceAfterSampling&&setTimeout(()=>h$(e,1),0)}function p$(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:g$(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:g$(e.performanceController.app),trace_metric:t};return JSON.stringify(n)}(e);var n}function g$(e){return{google_app_id:KB(e),app_instance_id:FB,web_app_info:{sdk_version:EB,page_url:MB.getInstance().getUrl(),service_worker_status:"serviceWorker"in(t=MB.getInstance().navigator)?t.serviceWorker.controller?2:3:1,visibility_state:$B(),effective_connection_type:function(){var e=MB.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 m$=["_fp","_fcp","_fid"];class v${constructor(e,t,n=!1,r){this.performanceController=e,this.name=t,this.isAuto=n,this.state=1,this.customAttributes={},this.counters={},this.api=MB.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||`${SB}-${this.randomId}-${this.name}`,r&&this.calculateTraceMetrics())}start(){if(1!==this.state)throw xB.create("trace started",{traceName:this.name});this.api.mark(this.traceStartMark),this.state=2}stop(){if(2!==this.state)throw xB.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(),d$(this)}record(e,t,n){if(e<=0)throw xB.create("nonpositive trace startTime",{traceName:this.name});if(t<=0)throw xB.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]=Number(Math.floor(n.metrics[r])));d$(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<m$.indexOf(r))&&r.startsWith("_"))throw xB.create("invalid custom metric name",{customMetricName:e});var n,r,i;this.counters[e]=(t=t,(n=Math.floor(t))<t&&DB.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)&&(!VB.some(e=>n.startsWith(e))&&!!n.match(BB)),s=0!==(r=t).length&&r.length<=100;if(i&&s)this.customAttributes[e]=t;else{if(!i)throw xB.create("invalid attribute name",{attributeName:e});if(!s)throw xB.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=MB.getInstance().getUrl();if(i){const s=new v$(e,"_wt_"+i,!0);i=Math.floor(1e3*MB.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))),d$(s)}}static createUserTimingTrace(e,t){d$(new v$(e,t,!1,t))}}function y$(e,t){const n=t;var r,i,s;n&&void 0!==n.responseStart&&(s=MB.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=qB.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(()=>h$(e,0),0))}({performanceController:e,url:n.name&&n.name.split("?")[0],responsePayloadBytes:n.transferSize,startTimeUs:r,timeToResponseInitiatedUs:i,timeToResponseCompletedUs:s}))}const _$=5e3;function w$(e){FB&&(setTimeout(()=>function(n){const e=MB.getInstance(),r=e.getEntriesByType("navigation"),i=e.getEntriesByType("paint");if(e.onFirstInputDelay){let t=setTimeout(()=>{v$.createOobTrace(n,r,i),t=void 0},_$);e.onFirstInputDelay(e=>{t&&(clearTimeout(t),v$.createOobTrace(n,r,i,e))})}else v$.createOobTrace(n,r,i)}(e),0),setTimeout(()=>function(t){const e=MB.getInstance(),n=e.getEntriesByType("resource");for(const r of n)y$(t,r);e.setupObserver("resource",e=>y$(t,e))}(e),0),setTimeout(()=>function(t){const e=MB.getInstance(),n=e.getEntriesByType("measure");for(const r of n)b$(t,r);e.setupObserver("measure",e=>b$(t,e))}(e),0))}function b$(e,t){const n=t.name;n.substring(0,SB.length)!==SB&&v$.createUserTimingTrace(e,n)}class I${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),MB.getInstance().requiredApisAvailable()?fd().then(e=>{e&&(a$||(c$(5500),a$=!0),e$(this).then(()=>w$(this),()=>w$(this)),this.initialized=!0)}).catch(e=>{DB.info(`Environment doesn't support IndexedDB: ${e}`)}):DB.info('Firebase Performance cannot start if the browser does not support "Fetch" and "Promise", or cookies are disabled.'))}set instrumentationEnabled(e){qB.getInstance().instrumentationEnabled=e}get instrumentationEnabled(){return qB.getInstance().instrumentationEnabled}set dataCollectionEnabled(e){qB.getInstance().dataCollectionEnabled=e}get dataCollectionEnabled(){return qB.getInstance().dataCollectionEnabled}}const T$="[DEFAULT]";const E$=(e,{options:t})=>{var n=e.getProvider("app").getImmediate(),r=e.getProvider("installations-internal").getImmediate();if(n.name!==T$)throw xB.create("FB not default");if("undefined"==typeof window)throw xB.create("no window");e=window,LB=e;const i=new I$(n,r);return i._init(t),i};df(new zd("performance",E$,"PUBLIC")),wf(TB,"0.5.4"),wf(TB,"0.5.4","esm2017");class S${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=Kd(t),new v$(t,e);var t}}function k$(e){var t=e.getProvider("app-compat").getImmediate(),n=e.getProvider("performance").getImmediate();return new S$(t,n)}(NB=Af).INTERNAL.registerComponent(new zd("performance-compat",k$,"PUBLIC")),NB.registerVersion("@firebase/performance-compat","0.1.4");const C$="@firebase/remote-config";class A${constructor(){this.listeners=[]}addEventListener(e){this.listeners.push(e)}abort(){this.listeners.forEach(e=>e())}}const N$=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 R$=["1","true","t","yes","y","on"];class P${constructor(e,t=""){this._source=e,this._value=t}asString(){return this._value}asBoolean(){return"static"!==this._source&&0<=R$.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 x$(e){const t=Kd(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 D$(e){const t=Kd(e);return t._initializePromise||(t._initializePromise=t._storageCache.loadFromStorage().then(()=>{t._isInitializationComplete=!0})),t._initializePromise}async function O$(t){const n=Kd(t),e=new A$;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 L$(n){const e=Kd(n);return[t={},r={}]=[e._storageCache.getActiveConfig(),e.defaultConfig],Object.keys(Object.assign(Object.assign({},t),r)).reduce((e,t)=>(e[t]=M$(n,t),e),{});var t,r}function M$(e,t){const n=Kd(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 P$("remote",r[t]):n.defaultConfig&&void 0!==n.defaultConfig[t]?new P$("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 P$("static"))}class F${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 U${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"),N$.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 N$.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 N$.create("fetch-status",{httpStatus:a});return{status:a,eTag:i,config:c}}}class j${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(N$.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()+$d(n),backoffCount:n+1};return await this.storage.setThrottleMetadata(r),this.attemptFetch(t,r)}}}class q${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 V$(e,t){var n=e.target.error||void 0;return N$.create(t,{originalErrorMessage:n&&n.message})}const B$="app_namespace_store";class $${constructor(e,t,n,r=function(){return new Promise((t,n)=>{try{const e=indexedDB.open("firebase_remote_config",1);e.onerror=e=>{n(V$(e,"storage-open"))},e.onsuccess=e=>{t(e.target.result)},e.onupgradeneeded=e=>{const t=e.target.result;0===e.oldVersion&&t.createObjectStore(B$,{keyPath:"compositeKey"})}}catch(e){n(N$.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([B$],"readonly"),r=e.objectStore(B$);var i=this.createCompositeKey(o);try{const s=r.get(i);s.onerror=e=>{t(V$(e,"storage-get"))},s.onsuccess=e=>{var t=e.target.result;n(t?t.value:void 0)}}catch(e){t(N$.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([B$],"readwrite"),r=n.objectStore(B$);var i=this.createCompositeKey(o);try{const s=r.put({compositeKey:i,value:a});s.onerror=e=>{t(V$(e,"storage-set"))},s.onsuccess=()=>{e()}}catch(e){t(N$.create("storage-set",{originalErrorMessage:e&&e.message}))}})}async delete(o){const a=await this.openDbPromise;return new Promise((e,t)=>{const n=a.transaction([B$],"readwrite"),r=n.objectStore(B$);var i=this.createCompositeKey(o);try{const s=r.delete(i);s.onerror=e=>{t(V$(e,"storage-delete"))},s.onsuccess=()=>{e()}}catch(e){t(N$.create("storage-delete",{originalErrorMessage:e&&e.message}))}})}createCompositeKey(e){return[this.appId,this.appName,this.namespace,e].join()}}class K${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 z$(){if(!dd())return!1;try{return await fd()}catch(e){return!1}}df(new zd("remote-config",function(e,{instanceIdentifier:t}){var n=e.getProvider("app").getImmediate(),r=e.getProvider("installations-internal").getImmediate();if("undefined"==typeof window)throw N$.create("registration-window");if(!dd())throw N$.create("indexed-db-unavailable");var{projectId:i,apiKey:s,appId:o}=n.options;if(!i)throw N$.create("registration-project-id");if(!s)throw N$.create("registration-api-key");if(!o)throw N$.create("registration-app-id");t=t||"firebase";const a=new $$(o,n.name,t),c=new K$(a),l=new ef(C$);l.logLevel=Kh.ERROR;o=new U$(r,mf,t,i,s,o),o=new j$(o,a),o=new F$(o,a,c,l),o=new q$(n,o,c,a,l);return D$(o),o},"PUBLIC").setMultipleInstances(!0)),wf(C$,"0.3.3"),wf(C$,"0.3.3","esm2017");class W${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 x$(this._delegate)}ensureInitialized(){return D$(this._delegate)}fetch(){return O$(this._delegate)}fetchAndActivate(){return async function(e){return await O$(e=Kd(e)),x$(e)}(this._delegate)}getAll(){return L$(this._delegate)}getBoolean(e){return M$(Kd(this._delegate),e).asBoolean()}getNumber(e){return M$(Kd(this._delegate),e).asNumber()}getString(e){return M$(Kd(this._delegate),e).asString()}getValue(e){return M$(this._delegate,e)}setLogLevel(e){!function(e,t){const n=Kd(e);switch(t){case"debug":n._logger.logLevel=Kh.DEBUG;break;case"silent":n._logger.logLevel=Kh.SILENT;break;default:n._logger.logLevel=Kh.ERROR}}(this._delegate,e)}}function H$(e,{instanceIdentifier:t}){var n=e.getProvider("app-compat").getImmediate(),r=e.getProvider("remote-config").getImmediate({identifier:t});return new W$(n,r)}return(RB=Af).INTERNAL.registerComponent(new zd("remoteConfig-compat",H$,"PUBLIC").setMultipleInstances(!0).setServiceProps({isSupported:z$})),RB.registerVersion("@firebase/remote-config-compat","0.1.4"),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"),Af.registerVersion("firebase","9.5.0","compat-cdn"),Af});
10
10
  //# sourceMappingURL=firebase-compat.js.map