firebase
Version:
Firebase JavaScript library for web and Node.js
4 lines • 134 kB
JavaScript
import{_isFirebaseServerApp as e,getApp as i,_getProvider,_removeServiceInstance as s,_registerComponent as T,registerVersion as E,SDK_VERSION as V}from"https://www.gstatic.com/firebasejs/12.19.0/firebase-app.js";const stringToByteArray$1=function(e){const i=[];let s=0;for(let T=0;T<e.length;T++){let E=e.charCodeAt(T);E<128?i[s++]=E:E<2048?(i[s++]=E>>6|192,i[s++]=63&E|128):55296==(64512&E)&&T+1<e.length&&56320==(64512&e.charCodeAt(T+1))?(E=65536+((1023&E)<<10)+(1023&e.charCodeAt(++T)),i[s++]=E>>18|240,i[s++]=E>>12&63|128,i[s++]=E>>6&63|128,i[s++]=63&E|128):(i[s++]=E>>12|224,i[s++]=E>>6&63|128,i[s++]=63&E|128)}return i},R={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(e,i){if(!Array.isArray(e))throw Error("encodeByteArray takes an array as a parameter");this.init_();const s=i?this.byteToCharMapWebSafe_:this.byteToCharMap_,T=[];for(let i=0;i<e.length;i+=3){const E=e[i],V=i+1<e.length,R=V?e[i+1]:0,N=i+2<e.length,O=N?e[i+2]:0,M=E>>2,L=(3&E)<<4|R>>4;let U=(15&R)<<2|O>>6,Q=63&O;N||(Q=64,V||(U=64)),T.push(s[M],s[L],s[U],s[Q])}return T.join("")},encodeString(e,i){return this.HAS_NATIVE_SUPPORT&&!i?btoa(e):this.encodeByteArray(stringToByteArray$1(e),i)},decodeString(e,i){return this.HAS_NATIVE_SUPPORT&&!i?atob(e):function(e){const i=[];let s=0,T=0;for(;s<e.length;){const E=e[s++];if(E<128)i[T++]=String.fromCharCode(E);else if(E>191&&E<224){const V=e[s++];i[T++]=String.fromCharCode((31&E)<<6|63&V)}else if(E>239&&E<365){const V=((7&E)<<18|(63&e[s++])<<12|(63&e[s++])<<6|63&e[s++])-65536;i[T++]=String.fromCharCode(55296+(V>>10)),i[T++]=String.fromCharCode(56320+(1023&V))}else{const V=e[s++],R=e[s++];i[T++]=String.fromCharCode((15&E)<<12|(63&V)<<6|63&R)}}return i.join("")}(this.decodeStringToByteArray(e,i))},decodeStringToByteArray(e,i){this.init_();const s=i?this.charToByteMapWebSafe_:this.charToByteMap_,T=[];for(let i=0;i<e.length;){const E=s[e.charAt(i++)],V=i<e.length?s[e.charAt(i)]:0;++i;const R=i<e.length?s[e.charAt(i)]:64;++i;const N=i<e.length?s[e.charAt(i)]:64;if(++i,null==E||null==V||null==R||null==N)throw new DecodeBase64StringError;const O=E<<2|V>>4;if(T.push(O),64!==R){const e=V<<4&240|R>>2;if(T.push(e),64!==N){const e=R<<6&192|N;T.push(e)}}}return T},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)}}};class DecodeBase64StringError extends Error{constructor(){super(...arguments),this.name="DecodeBase64StringError"}}const base64urlEncodeWithoutPadding=function(e){return function(e){const i=stringToByteArray$1(e);return R.encodeByteArray(i,!0)}(e).replace(/\./g,"")};const getDefaultsFromGlobal=()=>function getGlobal(){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.")}().__FIREBASE_DEFAULTS__,getDefaultsFromCookie=()=>{if("undefined"==typeof document)return;let e;try{e=document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/)}catch(e){return}const i=e&&function(e){try{return R.decodeString(e,!0)}catch(e){console.error("base64Decode failed: ",e)}return null}(e[1]);return i&&JSON.parse(i)},getDefaults=()=>{try{return getDefaultsFromGlobal()||(()=>{if("undefined"==typeof process||void 0===process.env)return;const e=process.env.__FIREBASE_DEFAULTS__;return e?JSON.parse(e):void 0})()||getDefaultsFromCookie()}catch(e){return void console.info(`Unable to get __FIREBASE_DEFAULTS__ due to: ${e}`)}},getDefaultEmulatorHostnameAndPort=e=>{const i=(e=>getDefaults()?.emulatorHosts?.[e])(e);if(!i)return;const s=i.lastIndexOf(":");if(s<=0||s+1===i.length)throw new Error(`Invalid host ${i} with no separate hostname and port!`);const T=parseInt(i.substring(s+1),10);return"["===i[0]?[i.substring(1,s-1),T]:[i.substring(0,s),T]};class FirebaseError extends Error{constructor(e,i,s){super(i),this.code=e,this.customData=s,this.name="FirebaseError",Object.setPrototypeOf(this,FirebaseError.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,ErrorFactory.prototype.create)}}class ErrorFactory{constructor(e,i,s){this.service=e,this.serviceName=i,this.errors=s}create(e,...i){const s=i[0]||{},T=`${this.service}/${e}`,E=this.errors[e],V=E?function replaceTemplate(e,i){try{let s=0,T="";for(;s<e.length;){const E=e.indexOf("{$",s);if(-1===E){T+=e.substring(s);break}const V=e.indexOf("}",E+2);if(-1===V){T+=e.substring(s);break}const R=e.substring(E+2,V),N=i[R];T+=e.substring(s,E)+(null!=N?String(N):`<${R}?>`),s=V+1}return T}catch(i){return e}}(E,s):"Error",R=`${this.serviceName}: ${V} (${T}).`;return new FirebaseError(T,R,s)}}function deepEqual(e,i){if(e===i)return!0;const s=Object.keys(e),T=Object.keys(i);for(const E of s){if(!T.includes(E))return!1;const s=e[E],V=i[E];if(isObject(s)&&isObject(V)){if(!deepEqual(s,V))return!1}else if(s!==V)return!1}for(const e of T)if(!s.includes(e))return!1;return!0}function isObject(e){return null!==e&&"object"==typeof e}function getModularInstance(e){return e&&e._delegate?e._delegate:e}function isCloudWorkstation(e){try{return(e.startsWith("http://")||e.startsWith("https://")?new URL(e).hostname:e).endsWith(".cloudworkstations.dev")}catch{return!1}}class Component{constructor(e,i,s){this.name=e,this.instanceFactory=i,this.type=s,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}}var N,O,M;!function(e){e.LAZY="LAZY",e.EAGER="EAGER",e.EXPLICIT="EXPLICIT"}(N||(N={})),function(e){e.PUBLIC="PUBLIC",e.PRIVATE="PRIVATE",e.VERSION="VERSION"}(O||(O={})),function(e){e[e.DEBUG=0]="DEBUG",e[e.VERBOSE=1]="VERBOSE",e[e.INFO=2]="INFO",e[e.WARN=3]="WARN",e[e.ERROR=4]="ERROR",e[e.SILENT=5]="SILENT"}(M||(M={}));const L={debug:M.DEBUG,verbose:M.VERBOSE,info:M.INFO,warn:M.WARN,error:M.ERROR,silent:M.SILENT},U=M.INFO,Q={[M.DEBUG]:"log",[M.VERBOSE]:"log",[M.INFO]:"info",[M.WARN]:"warn",[M.ERROR]:"error"},defaultLogHandler=(e,i,...s)=>{if(i<e.logLevel)return;const T=(new Date).toISOString(),E=Q[i];if(!E)throw new Error(`Attempted to log a message with an invalid logType (value: ${i})`);console[E](`[${T}] ${e.name}:`,...s)};var $,W="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};(function(){var e;function m(){this.blockSize=-1,this.blockSize=64,this.g=Array(4),this.C=Array(this.blockSize),this.o=this.h=0,this.u()}function n(e,i,s){s||(s=0);const T=Array(16);if("string"==typeof i)for(var E=0;E<16;++E)T[E]=i.charCodeAt(s++)|i.charCodeAt(s++)<<8|i.charCodeAt(s++)<<16|i.charCodeAt(s++)<<24;else for(E=0;E<16;++E)T[E]=i[s++]|i[s++]<<8|i[s++]<<16|i[s++]<<24;i=e.g[0],s=e.g[1],E=e.g[2];let V,R=e.g[3];V=i+(R^s&(E^R))+T[0]+3614090360&4294967295,V=R+(E^(i=s+(V<<7&4294967295|V>>>25))&(s^E))+T[1]+3905402710&4294967295,R=i+(V<<12&4294967295|V>>>20),V=E+(s^R&(i^s))+T[2]+606105819&4294967295,V=s+(i^(E=R+(V<<17&4294967295|V>>>15))&(R^i))+T[3]+3250441966&4294967295,V=i+(R^(s=E+(V<<22&4294967295|V>>>10))&(E^R))+T[4]+4118548399&4294967295,V=R+(E^(i=s+(V<<7&4294967295|V>>>25))&(s^E))+T[5]+1200080426&4294967295,R=i+(V<<12&4294967295|V>>>20),V=E+(s^R&(i^s))+T[6]+2821735955&4294967295,V=s+(i^(E=R+(V<<17&4294967295|V>>>15))&(R^i))+T[7]+4249261313&4294967295,V=i+(R^(s=E+(V<<22&4294967295|V>>>10))&(E^R))+T[8]+1770035416&4294967295,V=R+(E^(i=s+(V<<7&4294967295|V>>>25))&(s^E))+T[9]+2336552879&4294967295,R=i+(V<<12&4294967295|V>>>20),V=E+(s^R&(i^s))+T[10]+4294925233&4294967295,V=s+(i^(E=R+(V<<17&4294967295|V>>>15))&(R^i))+T[11]+2304563134&4294967295,V=i+(R^(s=E+(V<<22&4294967295|V>>>10))&(E^R))+T[12]+1804603682&4294967295,V=R+(E^(i=s+(V<<7&4294967295|V>>>25))&(s^E))+T[13]+4254626195&4294967295,R=i+(V<<12&4294967295|V>>>20),V=E+(s^R&(i^s))+T[14]+2792965006&4294967295,V=s+(i^(E=R+(V<<17&4294967295|V>>>15))&(R^i))+T[15]+1236535329&4294967295,V=i+(E^R&((s=E+(V<<22&4294967295|V>>>10))^E))+T[1]+4129170786&4294967295,V=R+(s^E&((i=s+(V<<5&4294967295|V>>>27))^s))+T[6]+3225465664&4294967295,R=i+(V<<9&4294967295|V>>>23),V=E+(i^s&(R^i))+T[11]+643717713&4294967295,V=s+(R^i&((E=R+(V<<14&4294967295|V>>>18))^R))+T[0]+3921069994&4294967295,V=i+(E^R&((s=E+(V<<20&4294967295|V>>>12))^E))+T[5]+3593408605&4294967295,V=R+(s^E&((i=s+(V<<5&4294967295|V>>>27))^s))+T[10]+38016083&4294967295,R=i+(V<<9&4294967295|V>>>23),V=E+(i^s&(R^i))+T[15]+3634488961&4294967295,V=s+(R^i&((E=R+(V<<14&4294967295|V>>>18))^R))+T[4]+3889429448&4294967295,V=i+(E^R&((s=E+(V<<20&4294967295|V>>>12))^E))+T[9]+568446438&4294967295,V=R+(s^E&((i=s+(V<<5&4294967295|V>>>27))^s))+T[14]+3275163606&4294967295,R=i+(V<<9&4294967295|V>>>23),V=E+(i^s&(R^i))+T[3]+4107603335&4294967295,V=s+(R^i&((E=R+(V<<14&4294967295|V>>>18))^R))+T[8]+1163531501&4294967295,V=i+(E^R&((s=E+(V<<20&4294967295|V>>>12))^E))+T[13]+2850285829&4294967295,V=R+(s^E&((i=s+(V<<5&4294967295|V>>>27))^s))+T[2]+4243563512&4294967295,R=i+(V<<9&4294967295|V>>>23),V=E+(i^s&(R^i))+T[7]+1735328473&4294967295,V=s+(R^i&((E=R+(V<<14&4294967295|V>>>18))^R))+T[12]+2368359562&4294967295,V=i+((s=E+(V<<20&4294967295|V>>>12))^E^R)+T[5]+4294588738&4294967295,V=R+((i=s+(V<<4&4294967295|V>>>28))^s^E)+T[8]+2272392833&4294967295,R=i+(V<<11&4294967295|V>>>21),V=E+(R^i^s)+T[11]+1839030562&4294967295,V=s+((E=R+(V<<16&4294967295|V>>>16))^R^i)+T[14]+4259657740&4294967295,V=i+((s=E+(V<<23&4294967295|V>>>9))^E^R)+T[1]+2763975236&4294967295,V=R+((i=s+(V<<4&4294967295|V>>>28))^s^E)+T[4]+1272893353&4294967295,R=i+(V<<11&4294967295|V>>>21),V=E+(R^i^s)+T[7]+4139469664&4294967295,V=s+((E=R+(V<<16&4294967295|V>>>16))^R^i)+T[10]+3200236656&4294967295,V=i+((s=E+(V<<23&4294967295|V>>>9))^E^R)+T[13]+681279174&4294967295,V=R+((i=s+(V<<4&4294967295|V>>>28))^s^E)+T[0]+3936430074&4294967295,R=i+(V<<11&4294967295|V>>>21),V=E+(R^i^s)+T[3]+3572445317&4294967295,V=s+((E=R+(V<<16&4294967295|V>>>16))^R^i)+T[6]+76029189&4294967295,V=i+((s=E+(V<<23&4294967295|V>>>9))^E^R)+T[9]+3654602809&4294967295,V=R+((i=s+(V<<4&4294967295|V>>>28))^s^E)+T[12]+3873151461&4294967295,R=i+(V<<11&4294967295|V>>>21),V=E+(R^i^s)+T[15]+530742520&4294967295,V=s+((E=R+(V<<16&4294967295|V>>>16))^R^i)+T[2]+3299628645&4294967295,V=i+(E^((s=E+(V<<23&4294967295|V>>>9))|~R))+T[0]+4096336452&4294967295,V=R+(s^((i=s+(V<<6&4294967295|V>>>26))|~E))+T[7]+1126891415&4294967295,R=i+(V<<10&4294967295|V>>>22),V=E+(i^(R|~s))+T[14]+2878612391&4294967295,V=s+(R^((E=R+(V<<15&4294967295|V>>>17))|~i))+T[5]+4237533241&4294967295,V=i+(E^((s=E+(V<<21&4294967295|V>>>11))|~R))+T[12]+1700485571&4294967295,V=R+(s^((i=s+(V<<6&4294967295|V>>>26))|~E))+T[3]+2399980690&4294967295,R=i+(V<<10&4294967295|V>>>22),V=E+(i^(R|~s))+T[10]+4293915773&4294967295,V=s+(R^((E=R+(V<<15&4294967295|V>>>17))|~i))+T[1]+2240044497&4294967295,V=i+(E^((s=E+(V<<21&4294967295|V>>>11))|~R))+T[8]+1873313359&4294967295,V=R+(s^((i=s+(V<<6&4294967295|V>>>26))|~E))+T[15]+4264355552&4294967295,R=i+(V<<10&4294967295|V>>>22),V=E+(i^(R|~s))+T[6]+2734768916&4294967295,V=s+(R^((E=R+(V<<15&4294967295|V>>>17))|~i))+T[13]+1309151649&4294967295,V=i+(E^((s=E+(V<<21&4294967295|V>>>11))|~R))+T[4]+4149444226&4294967295,V=R+(s^((i=s+(V<<6&4294967295|V>>>26))|~E))+T[11]+3174756917&4294967295,R=i+(V<<10&4294967295|V>>>22),V=E+(i^(R|~s))+T[2]+718787259&4294967295,V=s+(R^((E=R+(V<<15&4294967295|V>>>17))|~i))+T[9]+3951481745&4294967295,e.g[0]=e.g[0]+i&4294967295,e.g[1]=e.g[1]+(E+(V<<21&4294967295|V>>>11))&4294967295,e.g[2]=e.g[2]+E&4294967295,e.g[3]=e.g[3]+R&4294967295}function t(e,i){this.h=i;const s=[];let T=!0;for(let E=e.length-1;E>=0;E--){const V=0|e[E];T&&V==i||(s[E]=V,T=!1)}this.g=s}!function k(e,i){function c(){}c.prototype=i.prototype,e.F=i.prototype,e.prototype=new c,e.prototype.constructor=e,e.D=function(e,s,T){for(var E=Array(arguments.length-2),V=2;V<arguments.length;V++)E[V-2]=arguments[V];return i.prototype[s].apply(e,E)}}(m,(function l(){this.blockSize=-1})),m.prototype.u=function(){this.g[0]=1732584193,this.g[1]=4023233417,this.g[2]=2562383102,this.g[3]=271733878,this.o=this.h=0},m.prototype.v=function(e,i){void 0===i&&(i=e.length);const s=i-this.blockSize,T=this.C;let E=this.h,V=0;for(;V<i;){if(0==E)for(;V<=s;)n(this,e,V),V+=this.blockSize;if("string"==typeof e){for(;V<i;)if(T[E++]=e.charCodeAt(V++),E==this.blockSize){n(this,T),E=0;break}}else for(;V<i;)if(T[E++]=e[V++],E==this.blockSize){n(this,T),E=0;break}}this.h=E,this.o+=i},m.prototype.A=function(){var e=Array((this.h<56?this.blockSize:2*this.blockSize)-this.h);e[0]=128;for(var i=1;i<e.length-8;++i)e[i]=0;i=8*this.o;for(var s=e.length-8;s<e.length;++s)e[s]=255&i,i/=256;for(this.v(e),e=Array(16),i=0,s=0;s<4;++s)for(let T=0;T<32;T+=8)e[i++]=this.g[s]>>>T&255;return e};var i={};function u(e){return-128<=e&&e<128?function p(e,s){var T=i;return Object.prototype.hasOwnProperty.call(T,e)?T[e]:T[e]=s(e)}(e,(function(e){return new t([0|e],e<0?-1:0)})):new t([0|e],e<0?-1:0)}function v(e){if(isNaN(e)||!isFinite(e))return s;if(e<0)return x(v(-e));const i=[];let T=1;for(let s=0;e>=T;s++)i[s]=e/T|0,T*=4294967296;return new t(i,0)}var s=u(0),T=u(1),E=u(16777216);function C(e){if(0!=e.h)return!1;for(let i=0;i<e.g.length;i++)if(0!=e.g[i])return!1;return!0}function B(e){return-1==e.h}function x(e){const i=e.g.length,s=[];for(let T=0;T<i;T++)s[T]=~e.g[T];return new t(s,~e.h).add(T)}function F(e,i){return e.add(x(i))}function G(e,i){for(;(65535&e[i])!=e[i];)e[i+1]+=e[i]>>>16,e[i]&=65535,i++}function H(e,i){this.g=e,this.h=i}function D(e,i){if(C(i))throw Error("division by zero");if(C(e))return new H(s,s);if(B(e))return i=D(x(e),i),new H(x(i.g),x(i.h));if(B(i))return i=D(e,x(i)),new H(x(i.g),i.h);if(e.g.length>30){if(B(e)||B(i))throw Error("slowDivide_ only works with positive integers.");for(var E=T,V=i;V.l(e)<=0;)E=I(E),V=I(V);var R=J(E,1),N=J(V,1);for(V=J(V,2),E=J(E,2);!C(V);){var O=N.add(V);O.l(e)<=0&&(R=R.add(E),N=O),V=J(V,1),E=J(E,1)}return i=F(e,R.j(i)),new H(R,i)}for(R=s;e.l(i)>=0;){for(E=Math.max(1,Math.floor(e.m()/i.m())),V=(V=Math.ceil(Math.log(E)/Math.LN2))<=48?1:Math.pow(2,V-48),O=(N=v(E)).j(i);B(O)||O.l(e)>0;)O=(N=v(E-=V)).j(i);C(N)&&(N=T),R=R.add(N),e=F(e,O)}return new H(R,e)}function I(e){const i=e.g.length+1,s=[];for(let T=0;T<i;T++)s[T]=e.i(T)<<1|e.i(T-1)>>>31;return new t(s,e.h)}function J(e,i){const s=i>>5;i%=32;const T=e.g.length-s,E=[];for(let V=0;V<T;V++)E[V]=i>0?e.i(V+s)>>>i|e.i(V+s+1)<<32-i:e.i(V+s);return new t(E,e.h)}(e=t.prototype).m=function(){if(B(this))return-x(this).m();let e=0,i=1;for(let s=0;s<this.g.length;s++){const T=this.i(s);e+=(T>=0?T:4294967296+T)*i,i*=4294967296}return e},e.toString=function(e){if((e=e||10)<2||36<e)throw Error("radix out of range: "+e);if(C(this))return"0";if(B(this))return"-"+x(this).toString(e);const i=v(Math.pow(e,6));var s=this;let T="";for(;;){const E=D(s,i).g;let V=(((s=F(s,E.j(i))).g.length>0?s.g[0]:s.h)>>>0).toString(e);if(C(s=E))return V+T;for(;V.length<6;)V="0"+V;T=V+T}},e.i=function(e){return e<0?0:e<this.g.length?this.g[e]:this.h},e.l=function(e){return B(e=F(this,e))?-1:C(e)?0:1},e.abs=function(){return B(this)?x(this):this},e.add=function(e){const i=Math.max(this.g.length,e.g.length),s=[];let T=0;for(let E=0;E<=i;E++){let i=T+(65535&this.i(E))+(65535&e.i(E)),V=(i>>>16)+(this.i(E)>>>16)+(e.i(E)>>>16);T=V>>>16,i&=65535,V&=65535,s[E]=V<<16|i}return new t(s,-2147483648&s[s.length-1]?-1:0)},e.j=function(e){if(C(this)||C(e))return s;if(B(this))return B(e)?x(this).j(x(e)):x(x(this).j(e));if(B(e))return x(this.j(x(e)));if(this.l(E)<0&&e.l(E)<0)return v(this.m()*e.m());const i=this.g.length+e.g.length,T=[];for(var V=0;V<2*i;V++)T[V]=0;for(V=0;V<this.g.length;V++)for(let i=0;i<e.g.length;i++){const s=this.i(V)>>>16,E=65535&this.i(V),R=e.i(i)>>>16,N=65535&e.i(i);T[2*V+2*i]+=E*N,G(T,2*V+2*i),T[2*V+2*i+1]+=s*N,G(T,2*V+2*i+1),T[2*V+2*i+1]+=E*R,G(T,2*V+2*i+1),T[2*V+2*i+2]+=s*R,G(T,2*V+2*i+2)}for(e=0;e<i;e++)T[e]=T[2*e+1]<<16|T[2*e];for(e=i;e<2*i;e++)T[e]=0;return new t(T,0)},e.B=function(e){return D(this,e).h},e.and=function(e){const i=Math.max(this.g.length,e.g.length),s=[];for(let T=0;T<i;T++)s[T]=this.i(T)&e.i(T);return new t(s,this.h&e.h)},e.or=function(e){const i=Math.max(this.g.length,e.g.length),s=[];for(let T=0;T<i;T++)s[T]=this.i(T)|e.i(T);return new t(s,this.h|e.h)},e.xor=function(e){const i=Math.max(this.g.length,e.g.length),s=[];for(let T=0;T<i;T++)s[T]=this.i(T)^e.i(T);return new t(s,this.h^e.h)},m.prototype.digest=m.prototype.A,m.prototype.reset=m.prototype.u,m.prototype.update=m.prototype.v,t.prototype.add=t.prototype.add,t.prototype.multiply=t.prototype.j,t.prototype.modulo=t.prototype.B,t.prototype.compare=t.prototype.l,t.prototype.toNumber=t.prototype.m,t.prototype.toString=t.prototype.toString,t.prototype.getBits=t.prototype.i,t.fromNumber=v,t.fromString=function y(e,i){if(0==e.length)throw Error("number format error: empty string");if((i=i||10)<2||36<i)throw Error("radix out of range: "+i);if("-"==e.charAt(0))return x(y(e.substring(1),i));if(e.indexOf("-")>=0)throw Error('number format error: interior "-" character');const T=v(Math.pow(i,8));let E=s;for(let s=0;s<e.length;s+=8){var V=Math.min(8,e.length-s);const R=parseInt(e.substring(s,s+V),i);V<8?(V=v(Math.pow(i,V)),E=E.j(V).add(v(R))):(E=E.j(T),E=E.add(v(R)))}return E},$=t}).apply(void 0!==W?W:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{});class User{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}}User.UNAUTHENTICATED=new User(null),User.GOOGLE_CREDENTIALS=new User("google-credentials-uid"),User.FIRST_PARTY=new User("first-party-uid"),User.MOCK_USER=new User("mock-user");let K="12.19.0";const Y=new class Logger{constructor(e){this.name=e,this._logLevel=U,this._logHandler=defaultLogHandler,this._userLogHandler=null}get logLevel(){return this._logLevel}set logLevel(e){if(!(e in M))throw new TypeError(`Invalid value "${e}" assigned to \`logLevel\``);this._logLevel=e}setLogLevel(e){this._logLevel="string"==typeof e?L[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,M.DEBUG,...e),this._logHandler(this,M.DEBUG,...e)}log(...e){this._userLogHandler&&this._userLogHandler(this,M.VERBOSE,...e),this._logHandler(this,M.VERBOSE,...e)}info(...e){this._userLogHandler&&this._userLogHandler(this,M.INFO,...e),this._logHandler(this,M.INFO,...e)}warn(...e){this._userLogHandler&&this._userLogHandler(this,M.WARN,...e),this._logHandler(this,M.WARN,...e)}error(...e){this._userLogHandler&&this._userLogHandler(this,M.ERROR,...e),this._logHandler(this,M.ERROR,...e)}}("@firebase/firestore");function setLogLevel(e){Y.setLogLevel(e)}function a(e,...i){if(Y.logLevel<=M.DEBUG){const s=i.map(__PRIVATE_argToString);Y.debug(`Firestore (${K}): ${e}`,...s)}}function st(e,...i){if(Y.logLevel<=M.ERROR){const s=i.map(__PRIVATE_argToString);Y.error(`Firestore (${K}): ${e}`,...s)}}function __PRIVATE_logWarn(e,...i){if(Y.logLevel<=M.WARN){const s=i.map(__PRIVATE_argToString);Y.warn(`Firestore (${K}): ${e}`,...s)}}function __PRIVATE_argToString(e){if("string"==typeof e)return e;try{return function __PRIVATE_formatJSON(e){return JSON.stringify(e)}(e)}catch(i){return e}}function z(e,i,s){let T="Unexpected state";"string"==typeof i?T=i:s=i,__PRIVATE__fail(e,T,s)}function __PRIVATE__fail(e,i,s){let T=`FIRESTORE (${K}) INTERNAL ASSERTION FAILED: ${i} (ID: ${e.toString(16)})`;if(void 0!==s)try{T+=" CONTEXT: "+JSON.stringify(s)}catch(e){T+=" CONTEXT: "+s}throw st(T),new Error(T)}function __PRIVATE_hardAssert(e,i,s,T){let E="Unexpected state";"string"==typeof s?E=s:T=s,e||__PRIVATE__fail(i,E,T)}function __PRIVATE_debugCast(e,i){return e}const X="ok",Z="cancelled",ee="unknown",te="invalid-argument",re="deadline-exceeded",ne="not-found",ie="already-exists",se="permission-denied",oe="unauthenticated",ae="resource-exhausted",ue="failed-precondition",le="aborted",ce="out-of-range",he="unimplemented",_e="internal",de="unavailable",fe="data-loss";class k extends FirebaseError{constructor(e,i){super(e,i),this.code=e,this.message=i,this.toString=()=>`${this.name}: [code=${this.code}]: ${this.message}`}}class __PRIVATE_OAuthToken{constructor(e,i){this.user=i,this.type="OAuth",this.headers=new Map,this.headers.set("Authorization",`Bearer ${e}`)}}class __PRIVATE_EmptyAuthCredentialsProvider{getToken(){return Promise.resolve(null)}invalidateToken(){}start(e,i){e.enqueueRetryable((()=>i(User.UNAUTHENTICATED)))}shutdown(){}}class __PRIVATE_EmulatorAuthCredentialsProvider{constructor(e){this.token=e,this.changeListener=null}getToken(){return Promise.resolve(this.token)}invalidateToken(){}start(e,i){this.changeListener=i,e.enqueueRetryable((()=>i(this.token.user)))}shutdown(){this.changeListener=null}}class r{constructor(e){this.auth=null,e.onInit((e=>{this.auth=e}))}getToken(){return this.auth?this.auth.getToken().then((e=>e?(__PRIVATE_hardAssert("string"==typeof e.accessToken,42297,{Z:e}),new __PRIVATE_OAuthToken(e.accessToken,new User(this.auth.getUid()))):null)):Promise.resolve(null)}invalidateToken(){}start(e,i){}shutdown(){}}class __PRIVATE_FirstPartyToken{constructor(e,i,s){this.ee=e,this.te=i,this.re=s,this.type="FirstParty",this.user=User.FIRST_PARTY,this.ne=new Map}ie(){return this.re?this.re():null}get headers(){this.ne.set("X-Goog-AuthUser",this.ee);const e=this.ie();return e&&this.ne.set("Authorization",e),this.te&&this.ne.set("X-Goog-Iam-Authorization-Token",this.te),this.ne}}class __PRIVATE_FirstPartyAuthCredentialsProvider{constructor(e,i,s){this.ee=e,this.te=i,this.re=s}getToken(){return Promise.resolve(new __PRIVATE_FirstPartyToken(this.ee,this.te,this.re))}start(e,i){e.enqueueRetryable((()=>i(User.FIRST_PARTY)))}shutdown(){}invalidateToken(){}}class AppCheckToken{constructor(e){this.value=e,this.type="AppCheck",this.headers=new Map,e&&e.length>0&&this.headers.set("x-firebase-appcheck",this.value)}}class o{constructor(i,s){this.se=s,this.appCheck=null,this.oe=null,e(i)&&i.settings.appCheckToken&&(this.oe=i.settings.appCheckToken),s.onInit((e=>{this.appCheck=e}))}getToken(){return this.oe?Promise.resolve(new AppCheckToken(this.oe)):this.appCheck?this.appCheck.getToken().then((e=>e?(__PRIVATE_hardAssert("string"==typeof e.token,3470,{tokenResult:e}),new AppCheckToken(e.token)):null)):Promise.resolve(null)}invalidateToken(){}start(e,i){}shutdown(){}}class DatabaseInfo{constructor(e,i,s,T,E,V,R,N,O,M,L,U,Q){this.databaseId=e,this.appId=i,this.persistenceKey=s,this.host=T,this.ssl=E,this.forceLongPolling=V,this.autoDetectLongPolling=R,this.longPollingOptions=N,this.useFetchStreams=O,this.isUsingEmulator=M,this.apiKey=L,this._customHeaders=U,this.grpcFlowControlWindow=Q}}const me="(default)";class DatabaseId{constructor(e,i){this.projectId=e,this.database=i||me}static empty(){return new DatabaseId("","")}get isDefaultDatabase(){return this.database===me}isEqual(e){return e instanceof DatabaseId&&e.projectId===this.projectId&&e.database===this.database}}function __PRIVATE_randomBytes(e){const i="undefined"!=typeof self&&(self.crypto||self.msCrypto),s=new Uint8Array(e);if(i&&"function"==typeof i.getRandomValues)i.getRandomValues(s);else for(let i=0;i<e;i++)s[i]=Math.floor(256*Math.random());return s}class __PRIVATE_AutoId{static newId(){const e=62*Math.floor(256/62);let i="";for(;i.length<20;){const s=__PRIVATE_randomBytes(40);for(let T=0;T<s.length;++T)i.length<20&&s[T]<e&&(i+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".charAt(s[T]%62))}return i}}function __PRIVATE_primitiveComparator(e,i){return e<i?-1:e>i?1:0}function __PRIVATE_compareUtf8Strings(e,i){const s=Math.min(e.length,i.length);for(let T=0;T<s;T++){const s=e.charAt(T),E=i.charAt(T);if(s!==E)return __PRIVATE_isSurrogate(s)===__PRIVATE_isSurrogate(E)?__PRIVATE_primitiveComparator(s,E):__PRIVATE_isSurrogate(s)?1:-1}return __PRIVATE_primitiveComparator(e.length,i.length)}const pe=55296,ge=57343;function __PRIVATE_isSurrogate(e){const i=e.charCodeAt(0);return i>=pe&&i<=ge}function __PRIVATE_arrayEquals(e,i,s){return e.length===i.length&&e.every(((e,T)=>s(e,i[T])))}const ye="__name__";class BasePath{constructor(e,i,s){void 0===i?i=0:i>e.length&&z(637,{offset:i,range:e.length}),void 0===s?s=e.length-i:s>e.length-i&&z(1746,{length:s,range:e.length-i}),this.segments=e,this.offset=i,this.len=s}get length(){return this.len}isEqual(e){return 0===BasePath.comparator(this,e)}child(e){const i=this.segments.slice(this.offset,this.limit());return e instanceof BasePath?e.forEach((e=>{i.push(e)})):i.push(e),this.construct(i)}limit(){return this.offset+this.length}popFirst(e){return e=void 0===e?1:e,this.construct(this.segments,this.offset+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 i=0;i<this.length;i++)if(this.get(i)!==e.get(i))return!1;return!0}isImmediateParentOf(e){if(this.length+1!==e.length)return!1;for(let i=0;i<this.length;i++)if(this.get(i)!==e.get(i))return!1;return!0}forEach(e){for(let i=this.offset,s=this.limit();i<s;i++)e(this.segments[i])}toArray(){return this.segments.slice(this.offset,this.limit())}static comparator(e,i){const s=Math.min(e.length,i.length);for(let T=0;T<s;T++){const s=BasePath.compareSegments(e.get(T),i.get(T));if(0!==s)return s}return __PRIVATE_primitiveComparator(e.length,i.length)}static compareSegments(e,i){const s=BasePath.isNumericId(e),T=BasePath.isNumericId(i);return s&&!T?-1:!s&&T?1:s&&T?BasePath.extractNumericId(e).compare(BasePath.extractNumericId(i)):__PRIVATE_compareUtf8Strings(e,i)}static isNumericId(e){return e.startsWith("__id")&&e.endsWith("__")}static extractNumericId(e){return $.fromString(e.substring(4,e.length-2))}}class ResourcePath extends BasePath{construct(e,i,s){return new ResourcePath(e,i,s)}canonicalString(){return this.toArray().join("/")}toString(){return this.canonicalString()}toStringWithLeadingSlash(){return`/${this.canonicalString()}`}toUriEncodedString(){return this.toArray().map(encodeURIComponent).join("/")}static fromString(...e){const i=[];for(const s of e){if(s.indexOf("//")>=0)throw new k(te,`Invalid segment (${s}). Paths must not contain // in them.`);i.push(...s.split("/").filter((e=>e.length>0)))}return new ResourcePath(i)}static emptyPath(){return new ResourcePath([])}}const Te=/^[_a-zA-Z][_a-zA-Z0-9]*$/;let Ee=class FieldPath extends BasePath{construct(e,i,s){return new FieldPath(e,i,s)}static isValidIdentifier(e){return Te.test(e)}canonicalString(){return this.toArray().map((e=>(e=e.replace(/\\/g,"\\\\").replace(/`/g,"\\`"),FieldPath.isValidIdentifier(e)||(e="`"+e+"`"),e))).join(".")}toString(){return this.canonicalString()}isKeyField(){return 1===this.length&&this.get(0)===ye}static keyField(){return new FieldPath([ye])}static fromServerFormat(e){const i=[];let s="",T=0;const __PRIVATE_addCurrentSegment=()=>{if(0===s.length)throw new k(te,`Invalid field path (${e}). Paths must not be empty, begin with '.', end with '.', or contain '..'`);i.push(s),s=""};let E=!1;for(;T<e.length;){const i=e[T];if("\\"===i){if(T+1===e.length)throw new k(te,"Path has trailing escape character: "+e);const i=e[T+1];if("\\"!==i&&"."!==i&&"`"!==i)throw new k(te,"Path has invalid escape sequence: "+e);s+=i,T+=2}else"`"===i?(E=!E,T++):"."!==i||E?(s+=i,T++):(__PRIVATE_addCurrentSegment(),T++)}if(__PRIVATE_addCurrentSegment(),E)throw new k(te,"Unterminated ` in path: "+e);return new FieldPath(i)}static emptyPath(){return new FieldPath([])}};class x{constructor(e){this.path=e}static fromPath(e){return new x(ResourcePath.fromString(e))}static fromName(e){return new x(ResourcePath.fromString(e).popFirst(5))}static empty(){return new x(ResourcePath.emptyPath())}get collectionGroup(){return this.path.popLast().lastSegment()}hasCollectionId(e){return this.path.length>=2&&this.path.get(this.path.length-2)===e}getCollectionGroup(){return this.path.get(this.path.length-2)}getCollectionPath(){return this.path.popLast()}isEqual(e){return null!==e&&0===ResourcePath.comparator(this.path,e.path)}toString(){return this.path.toString()}static comparator(e,i){return ResourcePath.comparator(e.path,i.path)}static isDocumentKey(e){return e.length%2==0}static fromSegments(e){return new x(new ResourcePath(e.slice()))}}function __PRIVATE_validateNonEmptyArgument(e,i,s){if(!s)throw new k(te,`Function ${e}() cannot be called with an empty ${i}.`)}function __PRIVATE_validateDocumentPath(e){if(!x.isDocumentKey(e))throw new k(te,`Invalid document reference. Document references must have an even number of segments, but ${e} has ${e.length}.`)}function __PRIVATE_validateCollectionPath(e){if(x.isDocumentKey(e))throw new k(te,`Invalid collection reference. Collection references must have an odd number of segments, but ${e} has ${e.length}.`)}function __PRIVATE_isPlainObject(e){return"object"==typeof e&&null!==e&&(Object.getPrototypeOf(e)===Object.prototype||null===Object.getPrototypeOf(e))}function __PRIVATE_valueDescription(e){if(void 0===e)return"undefined";if(null===e)return"null";if("string"==typeof e)return e.length>20&&(e=`${e.substring(0,20)}...`),JSON.stringify(e);if("number"==typeof e||"boolean"==typeof e)return""+e;if("object"==typeof e){if(e instanceof Array)return"an array";{const i=function __PRIVATE_tryGetCustomObjectType(e){return e.constructor?e.constructor.name:null}(e);return i?`a custom ${i} object`:"an object"}}return"function"==typeof e?"a function":z(12329,{type:typeof e})}function f(e,i){if("_delegate"in e&&(e=e._delegate),!(e instanceof i)){if(i.name===e.constructor.name)throw new k(te,"Type does not match the expected instance. Did you pass a reference from a different Firestore SDK?");{const s=__PRIVATE_valueDescription(e);throw new k(te,`Expected type '${i.name}', but it was: ${s}`)}}return e}function __PRIVATE_validatePositiveNumber(e,i){if(i<=0)throw new k(te,`Function ${e}() requires a positive number, but it was: ${i}.`)}function __PRIVATE_cloneLongPollingOptions(e){const i={};return void 0!==e.timeoutSeconds&&(i.timeoutSeconds=e.timeoutSeconds),i}let Ae=null;function tt(e){return null==e}function __PRIVATE_isNegativeZero(e){return 0===e&&1/e==-1/0}const Ie="RestConnection",Ve={BatchGetDocuments:"batchGet",Commit:"commit",RunQuery:"runQuery",RunAggregationQuery:"runAggregationQuery",ExecutePipeline:"executePipeline"};class __PRIVATE_RestConnection{get ae(){return!1}constructor(e){this.databaseInfo=e,this.databaseId=e.databaseId;const i=e.ssl?"https":"http",s=encodeURIComponent(this.databaseId.projectId),T=encodeURIComponent(this.databaseId.database);this.ue=i+"://"+e.host,this._e=`projects/${s}/databases/${T}`,this.ce=this.databaseId.database===me?`project_id=${s}`:`project_id=${s}&database_id=${T}`}le(e,i,s,T,E){const V=function __PRIVATE_generateUniqueDebugId(){return null===Ae?Ae=function __PRIVATE_generateInitialUniqueDebugId(){return 268435456+Math.round(2147483648*Math.random())}():Ae++,"0x"+Ae.toString(16)}(),R=this.he(e,i.toUriEncodedString());a(Ie,`Sending RPC '${e}' ${V}:`,R,s);const N={"google-cloud-resource-prefix":this._e,"x-goog-request-params":this.ce};this.fe(N,T,E);const{host:O}=new URL(R),M=isCloudWorkstation(O);return this.me(e,R,N,s,M).then((i=>(a(Ie,`Received RPC '${e}' ${V}: `,i),i)),(i=>{throw __PRIVATE_logWarn(Ie,`RPC '${e}' ${V} failed with error: `,i,"url: ",R,"request:",s),i}))}de(e,i,s,T,E,V){return this.le(e,i,s,T,E)}fe(e,i,s){if(e["X-Goog-Api-Client"]=function __PRIVATE_getGoogApiClientValue(){return"gl-js/ fire/"+K}(),e["Content-Type"]="text/plain",this.databaseInfo.appId&&(e["X-Firebase-GMPID"]=this.databaseInfo.appId),i&&i.headers.forEach(((i,s)=>e[s]=i)),s&&s.headers.forEach(((i,s)=>e[s]=i)),this.databaseInfo._customHeaders)for(const i of Object.keys(this.databaseInfo._customHeaders))e[i]=this.databaseInfo._customHeaders[i]}he(e,i){const s=Ve[e];let T=`${this.ue}/v1/${i}:${s}`;return this.databaseInfo.apiKey&&(T=`${T}?key=${encodeURIComponent(this.databaseInfo.apiKey)}`),T}terminate(){}}var Pe,Re;function __PRIVATE_mapCodeFromHttpStatus(e){if(void 0===e)return st("RPC_ERROR","HTTP error has no status"),ee;switch(e){case 200:return X;case 400:return ue;case 401:return oe;case 403:return se;case 404:return ne;case 409:return le;case 416:return ce;case 429:return ae;case 499:return Z;case 500:return ee;case 501:return he;case 503:return de;case 504:return re;default:return e>=200&&e<300?X:e>=400&&e<500?ue:e>=500&&e<600?_e:ee}}(Re=Pe||(Pe={}))[Re.OK=0]="OK",Re[Re.CANCELLED=1]="CANCELLED",Re[Re.UNKNOWN=2]="UNKNOWN",Re[Re.INVALID_ARGUMENT=3]="INVALID_ARGUMENT",Re[Re.DEADLINE_EXCEEDED=4]="DEADLINE_EXCEEDED",Re[Re.NOT_FOUND=5]="NOT_FOUND",Re[Re.ALREADY_EXISTS=6]="ALREADY_EXISTS",Re[Re.PERMISSION_DENIED=7]="PERMISSION_DENIED",Re[Re.UNAUTHENTICATED=16]="UNAUTHENTICATED",Re[Re.RESOURCE_EXHAUSTED=8]="RESOURCE_EXHAUSTED",Re[Re.FAILED_PRECONDITION=9]="FAILED_PRECONDITION",Re[Re.ABORTED=10]="ABORTED",Re[Re.OUT_OF_RANGE=11]="OUT_OF_RANGE",Re[Re.UNIMPLEMENTED=12]="UNIMPLEMENTED",Re[Re.INTERNAL=13]="INTERNAL",Re[Re.UNAVAILABLE=14]="UNAVAILABLE",Re[Re.DATA_LOSS=15]="DATA_LOSS";class __PRIVATE_FetchConnection extends __PRIVATE_RestConnection{Ee(e,i){throw new Error("Not supported by FetchConnection")}async me(e,i,s,T,E){const V=JSON.stringify(T);let R;try{const e={method:"POST",headers:s,body:V};E&&(e.credentials="include"),R=await fetch(i,e)}catch(e){const i=e,s=i?.message,T=i?.cause?String(i.cause):void 0,E=(s&&T?`${s} (${T})`:s??T)??i?.statusText??String(e);throw new k(__PRIVATE_mapCodeFromHttpStatus(i?.status),`Request failed with error: ${E}`)}if(!R.ok){let e=await R.json();Array.isArray(e)&&(e=e[0]);const i=e?.error?.message;throw new k(__PRIVATE_mapCodeFromHttpStatus(R.status),`Request failed with error: ${i??R.statusText}`)}return R.json()}}function __PRIVATE_objectSize(e){let i=0;for(const s in e)Object.prototype.hasOwnProperty.call(e,s)&&i++;return i}function forEach(e,i){for(const s in e)Object.prototype.hasOwnProperty.call(e,s)&&i(s,e[s])}class __PRIVATE_Base64DecodeError extends Error{constructor(){super(...arguments),this.name="Base64DecodeError"}}class ByteString{constructor(e){this.binaryString=e}static fromBase64String(e){const i=function __PRIVATE_decodeBase64(e){try{return atob(e)}catch(e){throw"undefined"!=typeof DOMException&&e instanceof DOMException?new __PRIVATE_Base64DecodeError("Invalid base64 string: "+e):e}}(e);return new ByteString(i)}static fromUint8Array(e){const i=function __PRIVATE_binaryStringFromUint8Array(e){let i="";for(let s=0;s<e.length;++s)i+=String.fromCharCode(e[s]);return i}(e);return new ByteString(i)}[Symbol.iterator](){let e=0;return{next:()=>e<this.binaryString.length?{value:this.binaryString.charCodeAt(e++),done:!1}:{value:void 0,done:!0}}}toBase64(){return function __PRIVATE_encodeBase64(e){return btoa(e)}(this.binaryString)}toUint8Array(){return function __PRIVATE_uint8ArrayFromBinaryString(e){const i=new Uint8Array(e.length);for(let s=0;s<e.length;s++)i[s]=e.charCodeAt(s);return i}(this.binaryString)}approximateByteSize(){return 2*this.binaryString.length}compareTo(e){return __PRIVATE_primitiveComparator(this.binaryString,e.binaryString)}isEqual(e){return this.binaryString===e.binaryString}}ByteString.EMPTY_BYTE_STRING=new ByteString("");const we=new RegExp(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.(\d+))?Z$/);function __PRIVATE_normalizeTimestamp(e){if(__PRIVATE_hardAssert(!!e,39018),"string"==typeof e){let i=0;const s=we.exec(e);if(__PRIVATE_hardAssert(!!s,46558,{timestamp:e}),s[1]){let e=s[1];e=(e+"000000000").substr(0,9),i=Number(e)}const T=new Date(e);return{seconds:Math.floor(T.getTime()/1e3),nanos:i}}return{seconds:__PRIVATE_normalizeNumber(e.seconds),nanos:__PRIVATE_normalizeNumber(e.nanos)}}function __PRIVATE_normalizeNumber(e){return"number"==typeof e?e:"string"==typeof e?Number(e):0}function __PRIVATE_normalizeByteString(e){return"string"==typeof e?ByteString.fromBase64String(e):ByteString.fromUint8Array(e)}function property(e,i){const s={typeString:e};return i&&(s.value=i),s}function __PRIVATE_validateJSON(e,i){if(!__PRIVATE_isPlainObject(e))throw new k(te,"JSON must be an object");let s;for(const T in i)if(i[T]){const E=i[T].typeString,V="value"in i[T]?{value:i[T].value}:void 0;if(!(T in e)){s=`JSON missing required field: '${T}'`;break}const R=e[T];if(E&&typeof R!==E){s=`JSON field '${T}' must be a ${E}.`;break}if(void 0!==V&&R!==V.value){s=`Expected '${T}' field to equal '${V.value}'`;break}}if(s)throw new k(te,s);return!0}const ve=-62135596800,Se=1e6;class Timestamp{static now(){return Timestamp.fromMillis(Date.now())}static fromDate(e){return Timestamp.fromMillis(e.getTime())}static fromMillis(e){const i=Math.floor(e/1e3),s=Math.floor((e-1e3*i)*Se);return new Timestamp(i,s)}static fromInstant(e){if(!e||"bigint"!=typeof e.Te)throw new k(te,"Invalid Temporal.Instant object provided.");return Timestamp._fromEpochNanoseconds(e.Te)}static _fromEpochNanoseconds(e){let i,s;if(e>=0n)i=Number(e/1000000000n),s=Number(e%1000000000n);else{const T=e%1000000000n;0n===T?(i=Number(e/1000000000n),s=0):(i=Number(e/1000000000n-1n),s=Number(T+1000000000n))}return new Timestamp(i,s)}constructor(e,i){if(this.seconds=e,this.nanoseconds=i,i<0)throw new k(te,"Timestamp nanoseconds out of range: "+i);if(i>=1e9)throw new k(te,"Timestamp nanoseconds out of range: "+i);if(e<ve)throw new k(te,"Timestamp seconds out of range: "+e);if(e>=253402300800)throw new k(te,"Timestamp seconds out of range: "+e)}toDate(){return new Date(this.toMillis())}toMillis(){return 1e3*this.seconds+this.nanoseconds/Se}toInstant(){if("undefined"==typeof Temporal||!Temporal.Instant)throw new k(ue,"The Temporal object is not available in the current environment.");const e=1000000000n*BigInt(this.seconds)+BigInt(this.nanoseconds);return Temporal.Instant.__PRIVATE_fromEpochNanoseconds(e)}_compareTo(e){return this.seconds===e.seconds?__PRIVATE_primitiveComparator(this.nanoseconds,e.nanoseconds):__PRIVATE_primitiveComparator(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{type:Timestamp._jsonSchemaVersion,seconds:this.seconds,nanoseconds:this.nanoseconds}}static fromJSON(e){if(__PRIVATE_validateJSON(e,Timestamp._jsonSchema))return new Timestamp(e.seconds,e.nanoseconds)}valueOf(){const e=this.seconds-ve;return String(e).padStart(12,"0")+"."+String(this.nanoseconds).padStart(9,"0")}}function __PRIVATE_isServerTimestamp(e){const i=(e?.mapValue?.fields||{}).__type__?.stringValue;return"server_timestamp"===i}function __PRIVATE_getPreviousValue(e){const i=e.mapValue.fields.__previous_value__;return __PRIVATE_isServerTimestamp(i)?__PRIVATE_getPreviousValue(i):i}function __PRIVATE_getLocalWriteTime(e){const i=__PRIVATE_normalizeTimestamp(e.mapValue.fields.__local_write_time__.timestampValue);return new Timestamp(i.seconds,i.nanos)}Timestamp._jsonSchemaVersion="firestore/timestamp/1.0",Timestamp._jsonSchema={type:property("string",Timestamp._jsonSchemaVersion),seconds:property("number"),nanoseconds:property("number")};const be="__type__",Fe={},Ce="__vector__",ke="value";function __PRIVATE_typeOrder(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?__PRIVATE_isServerTimestamp(e)?4:function __PRIVATE_isMaxValue(e){return"__max__"===(((e.mapValue||{}).fields||{}).__type__||{}).stringValue}(e)?9007199254740991:function __PRIVATE_isVectorValue(e){const i=(e?.mapValue?.fields||{})[be]?.stringValue;return i===Ce}(e)?10:11:z(28295,{value:e})}function __PRIVATE_valueEquals(e,i,s){if(e===i)return!0;const T=__PRIVATE_typeOrder(e);if(T!==__PRIVATE_typeOrder(i))return!1;switch(T){case 0:case 9007199254740991:return!0;case 1:return e.booleanValue===i.booleanValue;case 4:return __PRIVATE_getLocalWriteTime(e).isEqual(__PRIVATE_getLocalWriteTime(i));case 3:return function __PRIVATE_timestampEquals(e,i){if("string"==typeof e.timestampValue&&"string"==typeof i.timestampValue&&e.timestampValue.length===i.timestampValue.length)return e.timestampValue===i.timestampValue;const s=__PRIVATE_normalizeTimestamp(e.timestampValue),T=__PRIVATE_normalizeTimestamp(i.timestampValue);return s.seconds===T.seconds&&s.nanos===T.nanos}(e,i);case 5:return e.stringValue===i.stringValue;case 6:return function __PRIVATE_blobEquals(e,i){return __PRIVATE_normalizeByteString(e.bytesValue).isEqual(__PRIVATE_normalizeByteString(i.bytesValue))}(e,i);case 7:return e.referenceValue===i.referenceValue;case 8:return function __PRIVATE_geoPointEquals(e,i){return __PRIVATE_normalizeNumber(e.geoPointValue.latitude)===__PRIVATE_normalizeNumber(i.geoPointValue.latitude)&&__PRIVATE_normalizeNumber(e.geoPointValue.longitude)===__PRIVATE_normalizeNumber(i.geoPointValue.longitude)}(e,i);case 2:return function __PRIVATE_numberEquals(e,i,s){if("integerValue"in e&&"integerValue"in i)return __PRIVATE_normalizeNumber(e.integerValue)===__PRIVATE_normalizeNumber(i.integerValue);let T,E;return"doubleValue"in e&&"doubleValue"in i&&(T=__PRIVATE_normalizeNumber(e.doubleValue),E=__PRIVATE_normalizeNumber(i.doubleValue),T===E?__PRIVATE_isNegativeZero(T)===__PRIVATE_isNegativeZero(E):!(void 0!==s&&!s.Pe)&&isNaN(T)&&isNaN(E))}(e,i,s);case 9:return __PRIVATE_arrayEquals(e.arrayValue.values||[],i.arrayValue.values||[],((e,i)=>__PRIVATE_valueEquals(e,i,s)));case 10:case 11:return function __PRIVATE_objectEquals(e,i,s){const T=e.mapValue.fields||{},E=i.mapValue.fields||{};if(__PRIVATE_objectSize(T)!==__PRIVATE_objectSize(E))return!1;for(const e in T)if(T.hasOwnProperty(e)&&(void 0===E[e]||!__PRIVATE_valueEquals(T[e],E[e],s)))return!1;return!0}(e,i,s);default:return z(52216,{left:e})}}function __PRIVATE_arrayValueContains(e,i){return void 0!==(e.values||[]).find((e=>__PRIVATE_valueEquals(e,i)))}function __PRIVATE_valueCompare(e,i){if(e===i)return 0;const s=__PRIVATE_typeOrder(e),T=__PRIVATE_typeOrder(i);if(s!==T)return __PRIVATE_primitiveComparator(s,T);switch(s){case 0:case 9007199254740991:return 0;case 1:return __PRIVATE_primitiveComparator(e.booleanValue,i.booleanValue);case 2:return function __PRIVATE_compareNumbers(e,i){const s=__PRIVATE_normalizeNumber(e.integerValue||e.doubleValue),T=__PRIVATE_normalizeNumber(i.integerValue||i.doubleValue);return s<T?-1:s>T?1:s===T?0:isNaN(s)?isNaN(T)?0:-1:1}(e,i);case 3:return __PRIVATE_compareTimestamps(e.timestampValue,i.timestampValue);case 4:return __PRIVATE_compareTimestamps(__PRIVATE_getLocalWriteTime(e),__PRIVATE_getLocalWriteTime(i));case 5:return __PRIVATE_compareUtf8Strings(e.stringValue,i.stringValue);case 6:return function __PRIVATE_compareBlobs(e,i){const s=__PRIVATE_normalizeByteString(e),T=__PRIVATE_normalizeByteString(i);return s.compareTo(T)}(e.bytesValue,i.bytesValue);case 7:return function __PRIVATE_compareReferences(e,i){const s=e.split("/"),T=i.split("/");for(let e=0;e<s.length&&e<T.length;e++){const i=__PRIVATE_primitiveComparator(s[e],T[e]);if(0!==i)return i}return __PRIVATE_primitiveComparator(s.length,T.length)}(e.referenceValue,i.referenceValue);case 8:return function __PRIVATE_compareGeoPoints(e,i){const s=__PRIVATE_primitiveComparator(__PRIVATE_normalizeNumber(e.latitude),__PRIVATE_normalizeNumber(i.latitude));return 0!==s?s:__PRIVATE_primitiveComparator(__PRIVATE_normalizeNumber(e.longitude),__PRIVATE_normalizeNumber(i.longitude))}(e.geoPointValue,i.geoPointValue);case 9:return __PRIVATE_compareArrays(e.arrayValue,i.arrayValue);case 10:return function __PRIVATE_compareVectors(e,i){const s=e.fields||{},T=i.fields||{},E=s[ke]?.arrayValue,V=T[ke]?.arrayValue,R=__PRIVATE_primitiveComparator(E?.values?.length||0,V?.values?.length||0);return 0!==R?R:__PRIVATE_compareArrays(E,V)}(e.mapValue,i.mapValue);case 11:return function __PRIVATE_compareMaps(e,i){if(e===Fe&&i===Fe)return 0;if(e===Fe)return 1;if(i===Fe)return-1;const s=e.fields||{},T=Object.keys(s),E=i.fields||{},V=Object.keys(E);T.sort(),V.sort();for(let e=0;e<T.length&&e<V.length;++e){const i=__PRIVATE_compareUtf8Strings(T[e],V[e]);if(0!==i)return i;const R=__PRIVATE_valueCompare(s[T[e]],E[V[e]]);if(0!==R)return R}return __PRIVATE_primitiveComparator(T.length,V.length)}(e.mapValue,i.mapValue);default:throw z(23264,{Re:s})}}function __PRIVATE_compareTimestamps(e,i){if("string"==typeof e&&"string"==typeof i&&e.length===i.length)return __PRIVATE_primitiveComparator(e,i);const s=__PRIVATE_normalizeTimestamp(e),T=__PRIVATE_normalizeTimestamp(i),E=__PRIVATE_primitiveComparator(s.seconds,T.seconds);return 0!==E?E:__PRIVATE_primitiveComparator(s.nanos,T.nanos)}function __PRIVATE_compareArrays(e,i){const s=e.values||[],T=i.values||[];for(let e=0;e<s.length&&e<T.length;++e){const i=__PRIVATE_valueCompare(s[e],T[e]);if(void 0!==i&&0!==i)return i}return __PRIVATE_primitiveComparator(s.length,T.length)}function __PRIVATE_refValue(e,i){return{referenceValue:`projects/${e.projectId}/databases/${e.database}/documents/${i.path.canonicalString()}`}}function isArray(e){return!!e&&"arrayValue"in e}function __PRIVATE_isNullValue(e){return!!e&&"nullValue"in e}function __PRIVATE_isNanValue(e){return!!e&&"doubleValue"in e&&isNaN(Number(e.doubleValue))}function __PRIVATE_isMapValue(e){return!!e&&"mapValue"in e}function __PRIVATE_deepClone(e){if(e.geoPointValue)return{geoPointValue:{...e.geoPointValue}};if(e.timestampValue&&"object"==typeof e.timestampValue)return{timestampValue:{...e.timestampValue}};if(e.mapValue){const i={mapValue:{fields:{}}};return forEach(e.mapValue.fields,((e,s)=>i.mapValue.fields[e]=__PRIVATE_deepClone(s))),i}if(e.arrayValue){const i={arrayValue:{values:[]}};for(let s=0;s<(e.arrayValue.values||[]).length;++s)i.arrayValue.values[s]=__PRIVATE_deepClone(e.arrayValue.values[s]);return i}return{...e}}class Bound{constructor(e,i){this.position=e,this.inclusive=i}}function __PRIVATE_boundEquals(e,i){if(null===e)return null===i;if(null===i)return!1;if(e.inclusive!==i.inclusive||e.position.length!==i.position.length)return!1;for(let s=0;s<e.position.length;s++)if(!__PRIVATE_valueEquals(e.position[s],i.position[s]))return!1;return!0}class Filter{}class FieldFilter extends Filter{constructor(e,i,s){super(),this.field=e,this.op=i,this.value=s}static create(e,i,s){return e.isKeyField()?"in"===i||"not-in"===i?this.createKeyFieldInFilter(e,i,s):new __PRIVATE_KeyFieldFilter(e,i,s):"array-contains"===i?new __PRIVATE_ArrayContainsFilter(e,s):"in"===i?new __PRIVATE_InFilter(e,s):"not-in"===i?new __PRIVATE_NotInFilter(e,s):"array-contains-any"===i?new __PRIVATE_ArrayContainsAnyFilter(e,s):new FieldFilter(e,i,s)}static createKeyFieldInFilter(e,i,s){return"in"===i?new __PRIVATE_KeyFieldInFilter(e,s):new __PRIVATE_KeyFieldNotInFilter(e,s)}matches(e){const i=e.data.field(this.field);return"!="===this.op?null!==i&&void 0===i.nullValue&&this.matchesComparison(__PRIVATE_valueCompare(i,this.value)):null!==i&&__PRIVATE_typeOrder(this.value)===__PRIVATE_typeOrder(i)&&this.matchesComparison(__PRIVATE_valueCompare(i,this.value))}matchesComparison(e){switch(this.op){case"<":return e<0;case"<=":return e<=0;case"==":return 0===e;case"!=":return 0!==e;case">":return e>0;case">=":return e>=0;default:return z(47266,{operator:this.op})}}isInequality(){return["<","<=",">",">=","!=","not-in"].indexOf(this.op)>=0}getFlattenedFilters(){return[this]}getFilters(){return[this]}}class CompositeFilter extends Filter{constructor(e,i){super(),this.filters=e,this.op=i,this.Ae=null}static create(e,i){return new CompositeFilter(e,i)}matches(e){return function __PRIVATE_compositeFilterIsConjunction(e){return"and"===e.op}(this)?void 0===this.filters.find((i=>!i.matches(e))):void 0!==this.filters.find((i=>i.matches(e)))}getFlattenedFilters(){return null!==this.Ae||(this.Ae=this.filters.reduce(((e,i)=>e.concat(i.getFlattenedFilters())),[])),this.Ae}getFilters(){return Object.assign([],this.filters)}}function __PRIVATE_filterEquals(e,i){return e instanceof FieldFilter?function __PRIVATE_fieldFilterEquals(e,i){return i instanceof FieldFilter&&e.op===i.op&&e.field.isEqual(i.field)&&__PRIVATE_valueEquals(e.value,i.value)}(e,i):e instanceof CompositeFilter?function __PRIVATE_compositeFilterEquals(e,i){return i instanceof CompositeFilter&&e.op===i.op&&e.filters.length===i.filters.length&&e.filters.reduce(((e,s,T)=>e&&__PRIVATE_filterEquals(s,i.filters[T])),!0)}(e,i):void z(19439)}class __PRIVATE_KeyFieldFilter extends FieldFilter{constructor(e,i,s){super(e,i,s),this.key=x.fromName(s.referenceValue)}matches(e){const i=x.comparator(e.key,this.key);return this.matchesComparison(i)}}class __PRIVATE_KeyFieldInFilter extends FieldFilter{constructor(e,i){super(e,"in",i),this.keys=__PRIVATE_extractDocumentKeysFromArrayValue("in",i)}matches(e){return this.keys.some((i=>i.isEqual(e.key)))}}class __PRIVATE_KeyFieldNotInFilter extends FieldFilter{constructor(e,i){super(e,"not-in",i),this.keys=__PRIVATE_extractDocumentKeysFromArrayValue("not-in",i)}matches(e){return!this.keys.some((i=>i.isEqual(e.key)))}}function __PRIVATE_extractDocumentKeysFromArrayValue(e,i){return(i.arrayValue?.values||[]).map((e=>x.fromName(e.referenceValue)))}class __PRIVATE_ArrayContainsFilter extends FieldFilter{constructor(e,i){super(e,"array-contains",i)}matches(e){const i=e.data.field(this.field);return isArray(i)&&__PRIVATE_arrayValueContains(i.arrayValue,this.value)}}class __PRIVATE_InFilter extends FieldFilter{constructor(e,i){super(e,"in",i)}matches(e){const i=e.data.field(this.field);return null!==i&&__PRIVATE_arrayValueContains(this.value.arrayValue,i)}}class __PRIVATE_NotInFilter extends FieldFilter{constructor(e,i){super(e,"not-in",i)}matches(e){if(__PRIVATE_arrayValueContains(this.value.arrayValue,{nullValue:"NULL_VALUE"}))return!1;const i=e.data.field(this.field);return null!==i&&void 0===i.nullValue&&!__PRIVATE_arrayValueContains(this.value.arrayValue,i)}}class __PRIVATE_ArrayContainsAnyFilter extends FieldFilter{constructor(e,i){super(e,"array-contains-any",i)}matches(e){const i=e.data.field(this.field);return!(!isArray(i)||!i.arrayValue.values)&&i.arrayValue.values.some((e=>__PRIVATE_arrayValueContains(this.value.arrayValue,e)))}}class OrderBy{constructor(e,i="asc"){this.field=e,this.dir=i}}function __PRIVATE_orderByEquals(e,i){return e.dir===i.dir&&e.field.isEqual(i.field)}class j{static fromTimestamp(e){return new j(e)}static min(){return new j(new Timestamp(0,0))}static max(){return new j(new Timestamp(253402300799,999999999))}constructor(e){this.timestamp=e}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}}class SortedMap{constructor(e,i){this.comparator=e,this.root=i||LLRBNode.EMPTY}insert(e,i){return new SortedMap(this.comparator,this.root.insert(e,i,this.comparator).copy(null,null,LLRBNode.BLACK,null,null))}remove(e){return new SortedMap(this.comparator,this.root.remove(e,this.comparator).copy(null,null,LLRBNode.BLACK,null,null))}get(e){let i=this.root;for(;!i.isEmpty();){const s=this.comparator(e,i.key);if(0===s)return i.value;s<0?i=i.left:s>0&&(i=i.right)}return null}indexOf(e){let i=0,s=this.root;for(;!s.isEmpty();){const T=this.comparator(e,s.key);if(0===T)return i+s.left.size;T<0?s=s.left:(i+=s.left.size+1,s=s.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(e){this.inorderTraversal(((i,s)=>(e(i,s),!1)))}toString(){const e=[];return this.inorderTraversal(((i,s)=>(e.push(`${i}:${s}`),!1))),`{${e.join(", ")}}`}reverseTraversal(e){return this.root.reverseTraversal(e)}getIterator(){return new SortedMapIterator(this.root,null,this.comparator,!1)}getIteratorFrom(e){return new SortedMapIterator(this.root,e,this.comparator,!1)}getReverseIterator(){return new SortedMapIterator(this.root,null,this.comparator,!0)}getReverseIteratorFrom(e){return new SortedMapIterator(this.root,e,this.comparator,!0)}}class SortedMapIterator{constructor(e,i,s,T){this.isReverse=T,this.nodeStack=[];let E=1;for(;!e.isEmpty();)if(E=i?s(e.key,i):1,i&&T&&(E*=-1),E<0)e=this.isReverse?e.left:e.right;else{if(0===E){this.nodeStack.push(e);break}this.nodeStack.push(e),e=this.isReverse?e.right:e.left}}getNext(){let e=this.nodeStack.pop();const i={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 i}hasNext(){return this.nodeStack.length>0}peek(){if(0===this.nodeStack.length)return null;const e=this.nodeStack[this.nodeStack.length-1];return{key:e.key,value:e.value}}}class LLRBNode{constructor(e,i,s,T,E){this.key=e,this.value=i,this.color=null!=s?s:LLRBNode.RED,this.left=null!=T?T:LLRBNode.EMPTY,this.right=null!=E?E:LLRBNode.EMPTY,this.size=this.left.size+1+this.right.size}copy(e,i,s,T,E){return new LLRBNode(null!=e?e:this.key,null!=i?i:this.value,null!=s?s:this.color,null!=T?T:this.left,null!=E?E: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,i,s){let T=this;const E=s(e,T.key);return T=E<0?T.copy(null,null,null,T.left.insert(e,i,s),null):0===E?T.copy(null,i,null,null,null):T.copy(null,null,null,null,T.right.insert(e,i,s)),T.fixUp()}removeMin(){if(this.left.isEmpty())return LLRBNode.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,i){let s,T=this;if(i(e,T.key)<0)T.left.isEmpty()||T.left.isRed()||T.left.left.isRed()||(T=T.moveRedLeft()),T=T.copy(null,null,null,T.left.remove(e,i),null);else{if(T.left.isRed()&&(T=T.rotateRight()),T.right.isEmpty()||T.right.isRed()||T.right.left.isRed()||(T=T.moveRedRight()),0===i(e,T.key)){if(T.right.isEmpty())return LLRBNode.EMPTY;s=T.right.min(),T=T.copy(s.key,s.value,null,null,T.right.removeMin())}T=T.copy(null,null,null,null,T.right.remove(e,i))}return T.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(){const e=this.copy(null,null,LLRBNode.RED,null,this.right.left);return this.right.copy(null,null,this.color,e,null)}rotateRight(){const e=this.copy(null,null,LLRBNode.RED,this.left.right,null);return this.left.copy(null,null,this.color,null,e)}colorFlip(){const e=this.left.copy(null,null,!this.left.color,null,null),i=this.right.copy(null,null,!this.right.color,null,null);return this.copy(null,null,!this.color,e,i)}checkMaxDepth(){const e=this.check();return Math.pow(2,e)<=this.size+1}check(){if(this.isRed()&&this.left.isRed())throw z(43730,{key:this.key,value:this.value});if(this.right.isRed())throw z(14113,{key:this.key,value:this.value});const e=this.left.check();if(e!==this.right.check())throw z(27949);return e+(this.isRed()?0:1)}}LLRBNode.EMPTY=null,LLRBNode.RED=!0,LLRBNode.BLACK=!1,LLRBNode.EMPTY=new class LLRBEmptyNode{constructor(){this.size=0}get key(){throw z(57766)}get value(){throw z(16141)}get color(){throw z(16727)}get left(){throw z(29726)}get right(){throw z(36894)}copy(e,i,s,T,E){return this}insert(e,i,s){return new LLRBNode(e,i)}remove(e,i){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 SortedSet{constructor(e){this.comparator=e,this.data=new SortedMap(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(e){this.data.inorderTraversal(((i,s)=>(e(i),!1)))}forEachInRange(e,i){const s=this.data.getIteratorFrom(e[0]);for(;s.hasNext();){const T=s.getNext();if(this.comparator(T.key,e[1])>=0)return;i(T.key)}}forEachWhile(e,i){let s;for(s=void 0!==i?this.data.getIteratorFrom(i):this.data.getIterator();s.hasNext();)if(!e(s.getNext().key))return}firstAfterOrEqual(e){const i=this.data.getIteratorFrom(e);return i.hasNext()?i.getNext().key:null}getIterator(){return new SortedSetIterator(this.data.getIterator())}getIteratorFrom(e){return new SortedSetIterator(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 i=this;return i.size<e.size&&(i=e,e=this),e.forEach((e=>{i=i.add(e)})),i}isEqual(e){if(!(e instanceof SortedSet))return!1;if(this.size!==e.size)return!1;const i=this.data.getIterator(),s=e.data.getIterator();for(;i.hasNext();){const e=i.getNext().key,T=s.getNext().key;if(0!==this.comparator(e,T))return!1}return!0}toArray(){const e=[];return this.forEach((i=>{e.push(i)})),e}toString(){const e=[];return this.forEach((i=>e.push(i))),"SortedSet("+e.toString()+")"}copy(e){const i=new SortedSet(this.comparator);return i.data=e,i}}class SortedSetIterator{constructor(e){this.iter=e}getNext(){return this.iter.getNext().key}hasNext(){return this.iter.hasNext()}}class FieldMask{constructor(e){this.fields=e,e.sort(Ee.comparator)}static empty(){return new FieldMask([])}unionWith(e){let i=new SortedSet(Ee.comparator);for(const e of this.fields)i=i.add(e);for(const s of e)i=i.add(s);return new FieldMask(i.toArray())}covers(e){for(const i of this.fields)if(i.isPrefixOf(e))return!0;return!1}isEqual(e){return __PRIVATE_arrayEquals(this.fields,e.fields,((e,i)=>e.isEqual(i)))}}class u{constructor(e){this.value=e}static empty(){return new u({mapValue:{}})}field(e){if(e.isEmpty())return this.value;{let i=this.value;for(let s=0;s<e.length-1;++s)if(i=(i.mapValue.fields||{})[e.get(s)],!__PRIVATE_isMapValue(i))return null;return i=(i.mapValue.fields||{})[e.lastSegment()],i||null}}set(e,i){this.getFieldsMap(e.popLast())[e.lastSegment()]=__PRIVATE_deepClone(i)}setAll(e){let i=Ee.emptyPath(),s={},T=[];e.forEach(((e,E)=>{if(!i.isImmediateParentOf(E)){const e=this.getFieldsMap(i);this.applyChanges(e,s,T),s={},T=[],i=E.popLast()}e?s[E.lastSegment()]=__PRIVATE_deepClone(e):T.push(E.lastSegment())}));const E=this.getFieldsMap(i);this.applyChanges(E,s,T)}delete(e){const i=this.field(e.popLast());__PRIVATE_isMapValue(i)&&i.mapValue.fields&&delete i.mapValue.fields[e.lastSegment()]}isEqual(e){return __PRIVATE_valueEquals(this.value,e.value)}getFieldsMap(e){let i=this.value;i.mapValue.fields||(i.mapValue={fields:{}});for(let s=0;s<e.length;++s){let T=i.mapValue.fields[e.get(s)];__PRIVATE_isMapValue(T)&&T.mapValue.fields||(T={mapValue:{fields:{}}},i.mapValue.fields[e.get(s)]=T),i=T}return i.mapValue.fields}applyChanges(e,i,s){forEach(i,((i,s)=>e[i]=s));for(const i of s)delete e[i]}clone(){return new u(__PRIVATE_deepClone(this.value))}}class MutableDocument{constructor(e,i,s,T,E,V,R){this.key=e,this.documentType=i,this.version=s,this.readTime=T,this.createTime=E,this.data=V,this.documentState=R}static newInvalidDocument(e){return new MutableDocument(e,0,j.min(),j.min(),j.min(),u.empty(),0)}static newFoundDocument(e,i,s,T){return new MutableDocument(e,1,i,j.min(),s,T,0)}static newNoDocument(e,i){return new MutableDocument(e,2,i,j.min(),j.min(),u.empty(),0)}static newUnknownDocument(e,i){return new MutableDocument(e,3,i,j.min(),j.min(),u.empty(),2)}convertToFoundDocument(e,i){return!this.createTime.isEqual(j.min())||2!==this.documentType&&0!==this.documentType||(this.createTime=e),this.version=e,this.documentType=1,this.data=i,this.documentState=0,this}convertToNoDocument(e){return this.version=e,this.documentType=2,this.data=u.empty(),this.documentState=0,this}convertToUnknownDocument(e){return this.version=e,this.documentType=3,this.data=u.empty(),this.documentState=2,this}setHasCommittedMutations(){return this.documentState=2,this}setHasLocalMutations(){return this.documentState=1,this.version=j.min(),this}setReadTime(e){return this.readTime=e,this}get hasLocalMutations(){return 1===this.documentState}get hasCommittedMutations(){return 2===this.documentState}get hasPendingWrites(){return this.hasLocalMutations||this.hasCommittedMutations}isValidDocument(){return 0!==this.documentType}isFoundDocument(){return 1===this.documentType}isNoDocument(){return 2===this.documentType}isUnknownDocument(){return 3===this.documentType}isEqual(e){return e instanceof MutableDocument&&this.key.isEqual(e.key)&&this.version.isEqual(e.version)&&this.documentType===e.documentType&&this.documentState===e.documentState&&this.data.isEqual(e.data)}mutableCopy(){return new MutableDocument(this.key,this.documentType,this.version,this.readTime,this.createTime,this.data.clone(),this.documentState)}toString(){return`Document(${this.key}, ${this.version}, ${JSON.stringify(this.data.value)}, {createTime: ${this.createTime}}), {documentType: ${this.documentType}}), {documentState: ${this.documentState}})`}}class __PRIVATE_TargetImpl{constructor(e,i=null,s=[],T=[],E=null,V=null,R=null){this.path=e,this.collectionGroup=i,this.orderBy=s,this.filters=T,this.limit=E,this.startAt=V,this.endAt=R,this.Ie=null}}function __PRIVATE_newTarget(e,i=null,s=[],T=[],E=null,V=null,R=null){return new __PRIVATE_TargetImpl(e,i,s,T,E,V,R)}class __PRIVATE_QueryImpl{constructor(e,i=null,s=[],T=[],E=null,V="F",R=null,N=null){this.path=e,this.collectionGroup=i,this.explicitOrderBy=s,this.filters=T,this.limit=E,this.limitType=V,this.startAt=R,this.endAt=N,this.pe=null,this.ye=null,this.we=null,this.startAt,this.endAt}}function __PRIVATE_isCollectionGroupQuery(e){return null!==e.collectionGroup}function __PRIVATE_queryNormalizedOrderBy(e){const i=__PRIVATE_debugCast(e);if(null===i.pe){i.pe=[];const e=new Set;for(const s of i.explicitOrderBy)i.pe.push(s),e.add(s.field.canonicalString());const s=i.explicitOrderBy.length>0?i.explicitOrderBy[i.explicitOrderBy.length-1].dir:"asc",T=function __PRIVATE_getInequalityFilterFields(e){let i=new SortedSet(Ee.comparator);return e.filters.forEach((e=>{e.getFlattenedFilters().forEach((e=>{e.isInequality()&&(i=i.add(e.field))}))})),i}(i);T.forEach((T=>{e.has(T.canonicalString())||T.isKeyField()||i.pe.push(new OrderBy(T,s))})),e.has(Ee.keyField().canonicalString())||i.pe.push(new OrderBy(Ee.keyField(),s))}return i.pe}function __PRIVATE_queryToTarget(e){const i=__PRIVATE_debugCast(e);return i.ye||(i.ye=__PRIVATE__queryToTarget(i,__PRIVATE_queryNormalizedOrderBy(e))),i.ye}function __PRIVATE__queryToTarget(e,i){if("F"===e.limitType)return __PRIVATE_newTarget(e.path,e.collectionGroup,i,e.filters,e.limit,e.startAt,e.endAt);{i=i.map((e=>{const i="desc"===e.dir?"asc":"desc";return new OrderBy(e.field,i)}));const s=e.endAt?new Bound(e.endAt.position,e.endAt.inclusive):null,T=e.startAt?new Bound(e.startAt.position,e.startAt.inclusive):null;return __PRIVATE_newTarget(e.path,e.collectionGroup,i,e.filters,e.limit,s,T)}}function __PRIVATE_queryWithAddedFilter(e,i){const s=e.filters.concat([i]);return new __PRIVATE_QueryImpl(e.path,e.collectionGroup,e.explicitOrderBy.slice(),s,e.limit,e.limitType,e.startAt,e.endAt)}function __PRIVATE_toDouble(e,i){if(e.useProto3Json){if(isNaN(i))return{doubleValue:"NaN"};if(i===1/0)return{doubleValue:"Infinity"};if(i===-1/0)return{doubleValue:"-Infinity"}}return{doubleValue:__PRIVATE_isNegativeZero(i)?"-0":i}}function toNumber(e,i,s){return function isSafeInteger(e){return"number"==typeof e&&Number.isInteger(e)&&!__PRIVATE_isNegativeZero(e)&&e<=Number.MAX_SAFE_INTEGER&&e>=Number.MIN_SAFE_INTEGER}(i)?function __PRIVATE_toInteger(e){return{integerValue:""+e}}(i):__PRIVATE_toDouble(e,i)}class TransformOperation{constructor(){this._=void 0}}class __PRIVATE_ServerTimestampTransform extends TransformOperation{}class __PRIVATE_ArrayUnionTransformOperation extends TransformOperation{constructor(e){super(),this.elements=e}}class __PRIVATE_ArrayRemoveTransformOperation extends TransformOperation{constructor(e){super(),this.elements=e}}class __PRIVATE_NumericTransformOperation extends TransformOperation{constructor(e,i){super(),this.serializer=e,this.ge=i}}class __PRIVATE_NumericIncrementTransformOperation extends __PRIVATE_NumericTransformOperation{}class __PRIVATE_NumericMinimumTransformOperation extends __PRIVATE_NumericTransformOperation{}class __PRIVATE_NumericMaximumTransformOperation extends __PRIVATE_NumericTransformOperation{}class FieldTransform{constructor(e,i){this.field=e,this.transform=i}}class P{constructor(e,i){this.updateTime=e,this.exists=i}static none(){return new P}static exists(e){return new P(void 0,e)}static updateTime(e){return new P(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)}}class Mutation{}class __PRIVATE_SetMutation extends Mutation{constructor(e,i,s,T=[]){super(),this.key=e,this.value=i,this.precondition=s,this.fieldTransforms=T,this.type=0}getFieldMask(){return null}}class __PRIVATE_PatchMutation extends Mutation{constructor(e,i,s,T,E=[]){super(),this.key=e,this.data=i,this.fieldMask=s,this.precondition=T,this.fieldTransforms=E,this.type=1}getFieldMask(){return this.fieldMask}}class F extends Mutation{constructor(e,i){super(),this.key=e,this.precondition=i,this.type=2,this.fieldTransforms=[]}getFieldMask(){return null}}class C extends Mutation{constructor(e,i){super(),this.key=e,this.precondition=i,this.type=3,this.fieldTransforms=[]}getFieldMask(){return null}}const Ne={asc:"ASCENDING",desc:"DESCENDING"},De={"<":"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"},Oe={and:"AND",or:"OR"};class JsonProtoSerializer{constructor(e,i){this.databaseId=e,this.useProto3Json=i}}function toTimestamp(e,i){return e.useProto3Json?`${new Date(1e3*i.seconds).toISOString().replace(/\.\d*/,"").replace("Z","")}.${("000000000"+i.nanoseconds).slice(-9)}Z`:{seconds:""+i.seconds,nanos:i.nanoseconds}}function __PRIVATE_toBytes(e,i){return e.useProto3Json?i.toBase64():i.toUint8Array()}function __PRIVATE_toVersion(e,i){return toTimestamp(e,i.toTimestamp())}function __PRIVATE_fromVersion(e){return __PRIVATE_hardAssert(!!e,49232),j.fromTimestamp(function fromTimestamp(e){const i=__PRIVATE_normalizeTimestamp(e);return new Timestamp(i.seconds,i.nanos)}(e))}function __PRIVATE_toResourceName(e,i){return __PRIVATE_toResourcePath(e,i).canonicalString()}function __PRIVATE_toResourcePath(e,i){const s=function __PRIVATE_fullyQualifiedPrefixPath(e){return new ResourcePath(["projects",e.projectId,"databases",e.database])}(e).child("documents");return void 0===i?s:s.child(i)}function __PRIVATE_toName(e,i){return __PRIVATE_toResourceName(e.databaseId,i.path)}function fromName(e,i){const s=function __PRIVATE_fromResourceName(e){const i=ResourcePath.fromString(e);return __PRIVATE_hardAssert(__PRIVATE_isValidResourceName(i),10190,{key:i.toString()}),i}(i);if(s.get(1)!==e.databaseId.projectId)throw new k(te,"Tried to deserialize key from different project: "+s.get(1)+" vs "+e.databaseId.projectId);if(s.get(3)!==e.databaseId.database)throw new k(te,"Tried to deserialize key from different database: "+s.get(3)+" vs "+e.databaseId.database);return new x(function __PRIVATE_extractLocalPathFromResourceName(e){return __PRIVATE_hardAssert(e.length>4&&"documents"===e.get(4),29091,{key:e.toString()}),e.popFirst(5)}(s))}function __PRIVATE_toMutationDocument(e,i,s){return{name:__PRIVATE_toName(e,i),fields:s.value.mapValue.fields}}function __PRIVATE_toQueryTarget(e,i){const s={structuredQuery:{}},T=i.path;let E;null!==i.collectionGroup?(E=T,s.structuredQuery.from=[{collectionId:i.collectionGroup,allDescendants:!0}]):(E=T.popLast(),s.structuredQuery.from=[{collectionId:T.lastSegment()}]),s.parent=function __PRIVATE_toQueryPath(e,i){return __PRIVATE_toResourceName(e.databaseId,i)}(e,E);const V=function __PRIVATE_toFilters(e){if(0!==e.length)return __PRIVATE_toFilter(CompositeFilter.create(e,"and"))}(i.filters);V&&(s.structuredQuery.where=V);const R=function __PRIVATE_toOrder(e){if(0!==e.length)return e.map((e=>function __PRIVATE_toPropertyOrder(e){return{field:__PRIVATE_toFieldPathReference(e.field),direction:__PRIVATE_toDirection(e.dir)}}(e)))}(i.orderBy);R&&(s.structuredQuery.orderBy=R);const N=function __PRIVATE_toInt32Proto(e,i){return e.useProto3Json||tt(i)?i:{value:i}}(e,i.limit);return null!==N&&(s.structuredQuery.limit=N),i.startAt&&(s.structuredQuery.startAt=function __PRIVATE_toStartAtCursor(e){return{before:e.inclusive,values:e.position}}(i.startAt)),i.endAt&&(s.structuredQuery.endAt=function __PRIVATE_toEndAtCursor(e){return{before:!e.inclusive,values:e.position}}(i.endAt)),{ve:s,parent:E}}function __PRIVATE_toDirection(e){return Ne[e]}function __PRIVATE_toOperatorName(e){return De[e]}function __PRIVATE_toCompositeOperatorName(e){return Oe[e]}function __PRIVATE_toFieldPathReference(e){return{fieldPath:e.canonicalString()}}function __PRIVATE_toFilter(e){return e instanceof FieldFilter?function __PRIVATE_toUnaryOrFieldFilter(e){if("=="===e.op){if(__PRIVATE_isNanValue(e.value))return{unaryFilter:{field:__PRIVATE_toFieldPathReference(e.field),op:"IS_NAN"}};if(__PRIVATE_isNullValue(e.value))return{unaryFilter:{field:__PRIVATE_toFieldPathReference(e.field),op:"IS_NULL"}}}else if("!="===e.op){if(__PRIVATE_isNanValue(e.value))return{unaryFilter:{field:__PRIVATE_toFieldPathReference(e.field),op:"IS_NOT_NAN"}};if(__PRIVATE_isNullValue(e.value))return{unaryFilter:{field:__PRIVATE_toFieldPathReference(e.field),op:"IS_NOT_NULL"}}}return{fieldFilter:{field:__PRIVATE_toFieldPathReference(e.field),op:__PRIVATE_toOperatorName(e.op),value:e.value}}}(e):e instanceof CompositeFilter?function __PRIVATE_toCompositeFilter(e){const i=e.getFilters().map((e=>__PRIVATE_toFilter(e)));return 1===i.length?i[0]:{compositeFilter:{op:__PRIVATE_toCompositeOperatorName(e.op),filters:i}}}(e):z(54877,{filter:e})}function __PRIVATE_toDocumentMask(e){const i=[];return e.fields.forEach((e=>i.push(e.canonicalString()))),{fieldPaths:i}}function __PRIVATE_isValidResourceName(e){return e.length>=4&&"projects"===e.get(0)&&"databases"===e.get(2)}function __PRIVATE_isProtoValueSerializable(e){return!!e&&"function"==typeof e._toProto&&"ProtoValue"===e._protoValueType}function __PRIVATE_newSerializer(e){return new JsonProtoSerializer(e,!0)}class Datastore{}class __PRIVATE_DatastoreImpl extends Datastore{constructor(e,i,s,T){super(),this.authCredentials=e,this.appCheckCredentials=i,this.connection=s,this.serializer=T,this.be=!1}De(){if(this.be)throw new k(ue,"The client has already been terminated.")}le(e,i,s,T){return this.De(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then((([E,V])=>this.connection.le(e,__PRIVATE_toResourcePath(i,s),T,E,V))).catch((e=>{throw"FirebaseError"===e.name?(e.code===oe&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),e):new k(ee,e.toString())}))}de(e,i,s,T,E){return this.De(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then((([V,R])=>this.connection.de(e,__PRIVATE_toResourcePath(i,s),T,V,R,E))).catch((e=>{throw"FirebaseError"===e.name?(e.code===oe&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),e):new k(ee,e.toString())}))}terminate(){this.be=!0,this.connection.terminate()}}async function S(e,i){const s=__PRIVATE_debugCast(e),T={writes:i.map((e=>function toMutation(e,i){let s;if(i instanceof __PRIVATE_SetMutation)s={update:__PRIVATE_toMutationDocument(e,i.key,i.value)};else if(i instanceof F)s={delete:__PRIVATE_toName(e,i.key)};else if(i instanceof __PRIVATE_PatchMutation)s={update:__PRIVATE_toMutationDocument(e,i.key,i.data),updateMask:__PRIVATE_toDocumentMask(i.fieldMask)};else{if(!(i instanceof C))return z(16599,{Fe:i.type});s={verify:__PRIVATE_toName(e,i.key)}}return i.fieldTransforms.length>0&&(s.updateTransforms=i.fieldTransforms.map((e=>function __PRIVATE_toFieldTransform(e,i){const s=i.transform;if(s instanceof __PRIVATE_ServerTimestampTransform)return{fieldPath:i.field.canonicalString(),setToServerValue:"REQUEST_TIME"};if(s instanceof __PRIVATE_ArrayUnionTransformOperation)return{fieldPath:i.field.canonicalString(),appendMissingElements:{values:s.elements}};if(s instanceof __PRIVATE_ArrayRemoveTransformOperation)return{fieldPath:i.field.canonicalString(),removeAllFromArray:{values:s.elements}};if(s instanceof __PRIVATE_NumericIncrementTransformOperation)return{fieldPath:i.field.canonicalString(),increment:s.ge};if(s instanceof __PRIVATE_NumericMinimumTransformOperation)return{fieldPath:i.field.canonicalString(),minimum:s.ge};if(s instanceof __PRIVATE_NumericMaximumTransformOperation)return{fieldPath:i.field.canonicalString(),maximum:s.ge};throw z(20930,{transform:i.transform})}(0,e)))),i.precondition.isNone||(s.currentDocument=function __PRIVATE_toPrecondition(e,i){return void 0!==i.updateTime?{updateTime:__PRIVATE_toVersion(e,i.updateTime)}:void 0!==i.exists?{exists:i.exists}:z(27497)}(e,i.precondition)),s}(s.serializer,e)))};await s.le("Commit",s.serializer.databaseId,ResourcePath.emptyPath(),T)}async function q(e,i){const s=__PRIVATE_debugCast(e),T={documents:i.map((e=>__PRIVATE_toName(s.serializer,e)))},E=await s.de("BatchGetDocuments",s.serializer.databaseId,ResourcePath.emptyPath(),T,i.length),V=new Map;E.forEach((e=>{const i=function __PRIVATE_fromBatchGetDocumentsResponse(e,i){return"found"in i?function __PRIVATE_fromFound(e,i){__PRIVATE_hardAssert(!!i.found,43571),i.found.name,i.found.updateTime;const s=fromName(e,i.found.name),T=__PRIVATE_fromVersion(i.found.updateTime),E=i.found.createTime?__PRIVATE_fromVersion(i.found.createTime):j.min(),V=new u({mapValue:{fields:i.found.fields}});return MutableDocument.newFoundDocument(s,T,E,V)}(e,i):"missing"in i?function __PRIVATE_fromMissing(e,i){__PRIVATE_hardAssert(!!i.missing,3894),__PRIVATE_hardAssert(!!i.readTime,22933);const s=fromName(e,i.missing),T=__PRIVATE_fromVersion(i.readTime);return MutableDocument.newNoDocument(s,T)}(e,i):z(7234,{result:i})}(s.serializer,e);V.set(i.key.toString(),i)}));const R=[];return i.forEach((e=>{const i=V.get(e.toString());__PRIVATE_hardAssert(!!i,55234,{key:e}),R.push(i)})),R}const xe="ComponentProvider",Be=new Map;function d(e){if(e._terminated)throw new k(ue,"The client has already been terminated.");if(!Be.has(e)){a(xe,"Initializing Datastore");const i=function __PRIVATE_newConnection(e){return new __PRIVATE_FetchConnection(e)}(function __PRIVATE_makeDatabaseInfo(e,i,s,T,E){return new DatabaseInfo(e,i,s,E.host,E.ssl,E.experimentalForceLongPolling,E.experimentalAutoDetectLongPolling,__PRIVATE_cloneLongPollingOptions(E.experimentalLongPollingOptions),E.useFetchStreams,E.isUsingEmulator,T,E._customHeaders,E.grpcFlowControlWindow)}(e._databaseId,e.app.options.appId||"",e._persistenceKey,e.app.options.apiKey,e._freezeSettings())),s=__PRIVATE_newSerializer(e._databaseId),T=function __PRIVATE_newDatastore(e,i,s,T){return new __PRIVATE_DatastoreImpl(e,i,s,T)}(e._authCredentials,e._appCheckCredentials,i,s);Be.set(e,T)}return Be.get(e)}const Me="firestore.googleapis.com",Le=!0;class FirestoreSettingsImpl{constructor(e){if(void 0===e.host){if(void 0!==e.ssl)throw new k(te,"Can't provide ssl option if host option is not set");this.host=Me,this.ssl=Le}else this.host=e.host,this.ssl=e.ssl??Le;if(this.isUsingEmulator=void 0!==e.emulatorOptions,this.credentials=e.credentials,this.ignoreUndefinedProperties=!!e.ignoreUndefinedProperties,this.localCache=e.localCache,e._customHeaders&&(this._customHeaders={...e._customHeaders}),void 0===e.cacheSizeBytes)this.cacheSizeBytes=41943040;else{if(-1!==e.cacheSizeBytes&&e.cacheSizeBytes<1048576)throw new k(te,"cacheSizeBytes must be at least 1048576");this.cacheSizeBytes=e.cacheSizeBytes}if(function __PRIVATE_validateIsNotUsedTogether(e,i,s,T){if(!0===i&&!0===T)throw new k(te,`${e} and ${s} cannot be used together.`)}("experimentalForceLongPolling",e.experimentalForceLongPolling,"experimentalAutoDetectLongPolling",e.experimentalAutoDetectLongPolling),this.experimentalForceLongPolling=!!e.experimentalForceLongPolling,this.experimentalForceLongPolling?this.experimentalAutoDetectLongPolling=!1:void 0===e.experimentalAutoDetectLongPolling?this.experimentalAutoDetectLongPolling=!0:this.experimentalAutoDetectLongPolling=!!e.experimentalAutoDetectLongPolling,this.experimentalLongPollingOptions=__PRIVATE_cloneLongPollingOptions(e.experimentalLongPollingOptions??{}),function __PRIVATE_validateLongPollingOptions(e){if(void 0!==e.timeoutSeconds){if(isNaN(e.timeoutSeconds))throw new k(te,`invalid long polling timeout: ${e.timeoutSeconds} (must not be NaN)`);if(e.timeoutSeconds<5)throw new k(te,`invalid long polling timeout: ${e.timeoutSeconds} (minimum allowed value is 5)`);if(e.timeoutSeconds>30)throw new k(te,`invalid long polling timeout: ${e.timeoutSeconds} (maximum allowed value is 30)`)}}(this.experimentalLongPollingOptions),this.useFetchStreams=!!e.useFetchStreams,void 0!==e.grpcFlowControlWindow){if("number"!=typeof e.grpcFlowControlWindow||e.grpcFlowControlWindow<=0||e.grpcFlowControlWindow>2147483647||!Number.isInteger(e.grpcFlowControlWindow))throw new k(te,"grpcFlowControlWindow must be a positive integer and cannot exceed 2147483647");this.grpcFlowControlWindow=e.grpcFlowControlWindow}}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&&function __PRIVATE_longPollingOptionsEqual(e,i){return e.timeoutSeconds===i.timeoutSeconds}(this.experimentalLongPollingOptions,e.experimentalLongPollingOptions)&&this.ignoreUndefinedProperties===e.ignoreUndefinedProperties&&this.useFetchStreams===e.useFetchStreams&&this.grpcFlowControlWindow===e.grpcFlowControlWindow&&function __PRIVATE_customHeadersEqual(e,i){if(e===i)return!0;if(!e||!i)return!1;const s=Object.keys(e),T=Object.keys(i);if(s.length!==T.length)return!1;for(const T of s)if(e[T]!==i[T])return!1;return!0}(this._customHeaders,e._customHeaders)}}class n{constructor(e,i,s,T){this._authCredentials=e,this._appCheckCredentials=i,this._databaseId=s,this._app=T,this.type="firestore-lite",this._persistenceKey="(lite)",this._settings=new FirestoreSettingsImpl({}),this._settingsFrozen=!1,this._emulatorOptions={},this._terminateTask="notTerminated"}get app(){if(!this._app)throw new k(ue,"Firestore was not initialized using the Firebase SDK. 'app' is not available");return this._app}get _initialized(){return this._settingsFrozen}get _terminated(){return"notTerminated"!==this._terminateTask}_setSettings(e){if(this._settingsFrozen)throw new k(ue,"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 FirestoreSettingsImpl(e),this._emulatorOptions=e.emulatorOptions||{},void 0!==e.credentials&&(this._authCredentials=function __PRIVATE_makeAuthCredentialsProvider(e){if(!e)return new __PRIVATE_EmptyAuthCredentialsProvider;switch(e.type){case"firstParty":return new __PRIVATE_FirstPartyAuthCredentialsProvider(e.sessionIndex||"0",e.iamToken||null,e.authTokenFactory||null);case"provider":return e.client;default:throw new k(te,"makeAuthCredentialsProvider failed due to invalid credential type")}}(e.credentials))}_getSettings(){return this._settings}_getEmulatorOptions(){return this._emulatorOptions}_freezeSettings(){return this._settingsFrozen=!0,this._settings}_delete(){return"notTerminated"===this._terminateTask&&(this._terminateTask=this._terminate()),this._terminateTask}async _restart(){"notTerminated"===this._terminateTask?await this._terminate():this._terminateTask="notTerminated"}toJSON(){return{app:this._app,databaseId:this._databaseId,settings:this._settings}}_terminate(){return function __PRIVATE_removeComponents(e){const i=Be.get(e);i&&(a(xe,"Removing Datastore"),Be.delete(e),i.terminate())}(this),Promise.resolve()}}function initializeFirestore(e,i,s){s||(s=me);const T=_getProvider(e,"firestore/lite");if(T.isInitialized(s))throw new k(ue,"Firestore can only be initialized once per app.");return T.initialize({options:i,instanceIdentifier:s})}function getFirestore(e,s){const T="object"==typeof e?e:i(),E="string"==typeof e?e:s||"(default)",V=_getProvider(T,"firestore/lite").getImmediate({identifier:E});if(!V._initialized){const e=getDefaultEmulatorHostnameAndPort("firestore");e&&connectFirestoreEmulator(V,...e)}return V}function connectFirestoreEmulator(e,i,s,T={}){e=f(e,n);const E=isCloudWorkstation(i),V=e._getSettings(),R={...V,emulatorOptions:e._getEmulatorOptions()},N=`${i}:${s}`;E&&async function pingServer(e){return(await fetch(e,{credentials:"include"})).ok}(`https://${N}`),V.host!==Me&&V.host!==N&&__PRIVATE_logWarn("Host has been set in both settings() and connectFirestoreEmulator(), emulator host will be used.");const O={...V,host:N,ssl:E,emulatorOptions:T};if(!deepEqual(O,R)&&(e._setSettings(O),T.mockUserToken)){let i,s;if("string"==typeof T.mockUserToken)i=T.mockUserToken,s=User.MOCK_USER;else{i=function createMockUserToken(e,i){if(e.uid)throw new Error('The "uid" field is no longer supported by mockUserToken. Please use "sub" instead for Firebase Auth User ID.');const s=i||"demo-project",T=e.iat||0,E=e.sub||e.user_id;if(!E)throw new Error("mockUserToken must contain 'sub' or 'user_id' field!");const V={iss:`https://securetoken.google.com/${s}`,aud:s,iat:T,exp:T+3600,auth_time:T,sub:E,user_id:E,firebase:{sign_in_provider:"custom",identities:{}},...e};return[base64urlEncodeWithoutPadding(JSON.stringify({alg:"none",type:"JWT"})),base64urlEncodeWithoutPadding(JSON.stringify(V)),""].join(".")}(T.mockUserToken,e._app?.options.projectId);const E=T.mockUserToken.sub||T.mockUserToken.user_id;if(!E)throw new k(te,"mockUserToken must contain 'sub' or 'user_id' field!");s=new User(E)}e._authCredentials=new __PRIVATE_EmulatorAuthCredentialsProvider(new __PRIVATE_OAuthToken(i,s))}}function terminate(e){return e=f(e,n),s(e.app,"firestore/lite"),e._delete()}class Query{constructor(e,i,s){this.converter=i,this._query=s,this.type="query",this.firestore=e}withConverter(e){return new Query(this.firestore,e,this._query)}}class DocumentReference{constructor(e,i,s){this.converter=i,this._key=s,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 CollectionReference(this.firestore,this.converter,this._key.path.popLast())}withConverter(e){return new DocumentReference(this.firestore,e,this._key)}toJSON(){return{type:DocumentReference._jsonSchemaVersion,referencePath:this._key.toString()}}static fromJSON(e,i,s){if(__PRIVATE_validateJSON(i,DocumentReference._jsonSchema))return new DocumentReference(e,s||null,new x(ResourcePath.fromString(i.referencePath)))}}DocumentReference._jsonSchemaVersion="firestore/documentReference/1.0",DocumentReference._jsonSchema={type:property("string",DocumentReference._jsonSchemaVersion),referencePath:property("string")};class CollectionReference extends Query{constructor(e,i,s){super(e,i,function __PRIVATE_newQueryForPath(e){return new __PRIVATE_QueryImpl(e)}(s)),this._path=s,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 DocumentReference(this.firestore,null,new x(e))}withConverter(e){return new CollectionReference(this.firestore,e,this._path)}}function collection(e,i,...s){if(e=getModularInstance(e),__PRIVATE_validateNonEmptyArgument("collection","path",i),e instanceof n){const T=ResourcePath.fromString(i,...s);return __PRIVATE_validateCollectionPath(T),new CollectionReference(e,null,T)}{if(!(e instanceof DocumentReference||e instanceof CollectionReference))throw new k(te,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");const T=e._path.child(ResourcePath.fromString(i,...s));return __PRIVATE_validateCollectionPath(T),new CollectionReference(e.firestore,null,T)}}function collectionGroup(e,i){if(e=f(e,n),__PRIVATE_validateNonEmptyArgument("collectionGroup","collection id",i),i.indexOf("/")>=0)throw new k(te,`Invalid collection ID '${i}' passed to function collectionGroup(). Collection IDs must not contain '/'.`);return new Query(e,null,function __PRIVATE_newQueryForCollectionGroup(e){return new __PRIVATE_QueryImpl(ResourcePath.emptyPath(),e)}(i))}function doc(e,i,...s){if(e=getModularInstance(e),1===arguments.length&&(i=__PRIVATE_AutoId.newId()),__PRIVATE_validateNonEmptyArgument("doc","path",i),e instanceof n){const T=ResourcePath.fromString(i,...s);return __PRIVATE_validateDocumentPath(T),new DocumentReference(e,null,new x(T))}{if(!(e instanceof DocumentReference||e instanceof CollectionReference))throw new k(te,"Expected first argument to doc() to be a CollectionReference, a DocumentReference or FirebaseFirestore");const T=e._path.child(ResourcePath.fromString(i,...s));return __PRIVATE_validateDocumentPath(T),new DocumentReference(e.firestore,e instanceof CollectionReference?e.converter:null,new x(T))}}function refEqual(e,i){return e=getModularInstance(e),i=getModularInstance(i),(e instanceof DocumentReference||e instanceof CollectionReference)&&(i instanceof DocumentReference||i instanceof CollectionReference)&&e.firestore===i.firestore&&e.path===i.path&&e.converter===i.converter}function l(e,i){return e=getModularInstance(e),i=getModularInstance(i),e instanceof Query&&i instanceof Query&&e.firestore===i.firestore&&function __PRIVATE_queryEquals(e,i){return function __PRIVATE_targetEquals(e,i){if(e.limit!==i.limit)return!1;if(e.orderBy.length!==i.orderBy.length)return!1;for(let s=0;s<e.orderBy.length;s++)if(!__PRIVATE_orderByEquals(e.orderBy[s],i.orderBy[s]))return!1;if(e.filters.length!==i.filters.length)return!1;for(let s=0;s<e.filters.length;s++)if(!__PRIVATE_filterEquals(e.filters[s],i.filters[s]))return!1;return e.collectionGroup===i.collectionGroup&&!!e.path.isEqual(i.path)&&!!__PRIVATE_boundEquals(e.startAt,i.startAt)&&__PRIVATE_boundEquals(e.endAt,i.endAt)}(__PRIVATE_queryToTarget(e),__PRIVATE_queryToTarget(i))&&e.limitType===i.limitType}(e._query,i._query)&&e.converter===i.converter}class Bytes{constructor(e){this._byteString=e}static fromBase64String(e){try{return new Bytes(ByteString.fromBase64String(e))}catch(e){throw new k(te,"Failed to construct data from Base64 string: "+e)}}static fromUint8Array(e){return new Bytes(ByteString.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)}toJSON(){return{type:Bytes._jsonSchemaVersion,bytes:this.toBase64()}}static fromJSON(e){if(__PRIVATE_validateJSON(e,Bytes._jsonSchema))return Bytes.fromBase64String(e.bytes)}}Bytes._jsonSchemaVersion="firestore/bytes/1.0",Bytes._jsonSchema={type:property("string",Bytes._jsonSchemaVersion),bytes:property("string")};class D{constructor(...e){for(let i=0;i<e.length;++i)if(0===e[i].length)throw new k(te,"Invalid field name at argument $(i + 1). Field names must not be empty.");this._internalPath=new Ee(e)}isEqual(e){return this._internalPath.isEqual(e._internalPath)}}function documentId(){return new D(ye)}class FieldValue{constructor(e){this._methodName=e}}class GeoPoint{constructor(e,i){if(!isFinite(e)||e<-90||e>90)throw new k(te,"Latitude must be a number between -90 and 90, but was: "+e);if(!isFinite(i)||i<-180||i>180)throw new k(te,"Longitude must be a number between -180 and 180, but was: "+i);this._lat=e,this._long=i}get latitude(){return this._lat}get longitude(){return this._long}isEqual(e){return this._lat===e._lat&&this._long===e._long}_compareTo(e){return __PRIVATE_primitiveComparator(this._lat,e._lat)||__PRIVATE_primitiveComparator(this._long,e._long)}toJSON(){return{latitude:this._lat,longitude:this._long,type:GeoPoint._jsonSchemaVersion}}static fromJSON(e){if(__PRIVATE_validateJSON(e,GeoPoint._jsonSchema))return new GeoPoint(e.latitude,e.longitude)}}GeoPoint._jsonSchemaVersion="firestore/geoPoint/1.0",GeoPoint._jsonSchema={type:property("string",GeoPoint._jsonSchemaVersion),latitude:property("number"),longitude:property("number")};class VectorValue{constructor(e){this._values=(e||[]).map((e=>e))}toArray(){return this._values.map((e=>e))}isEqual(e){return function __PRIVATE_isPrimitiveArrayEqual(e,i){if(e.length!==i.length)return!1;for(let s=0;s<e.length;++s)if(e[s]!==i[s])return!1;return!0}(this._values,e._values)}toJSON(){return{type:VectorValue._jsonSchemaVersion,vectorValues:this._values}}static fromJSON(e){if(__PRIVATE_validateJSON(e,VectorValue._jsonSchema)){if(Array.isArray(e.vectorValues)&&e.vectorValues.every((e=>"number"==typeof e)))return new VectorValue(e.vectorValues);throw new k(te,"Expected 'vectorValues' field to be a number array")}}}VectorValue._jsonSchemaVersion="firestore/vectorValue/1.0",VectorValue._jsonSchema={type:property("string",VectorValue._jsonSchemaVersion),vectorValues:property("object")};const qe=/^__.*__$/;class ParsedSetData{constructor(e,i,s){this.data=e,this.fieldMask=i,this.fieldTransforms=s}toMutation(e,i){return null!==this.fieldMask?new __PRIVATE_PatchMutation(e,this.data,this.fieldMask,i,this.fieldTransforms):new __PRIVATE_SetMutation(e,this.data,i,this.fieldTransforms)}}class ParsedUpdateData{constructor(e,i,s){this.data=e,this.fieldMask=i,this.fieldTransforms=s}toMutation(e,i){return new __PRIVATE_PatchMutation(e,this.data,this.fieldMask,i,this.fieldTransforms)}}function __PRIVATE_isWrite(e){switch(e){case 0:case 2:case 1:return!0;case 3:case 4:return!1;default:throw z(40011,{dataSource:e})}}class ParseContextImpl{constructor(e,i,s,T,E,V){this.settings=e,this.databaseId=i,this.serializer=s,this.ignoreUndefinedProperties=T,void 0===E&&this.validatePath(),this.fieldTransforms=E||[],this.fieldMask=V||[]}get path(){return this.settings.path}get dataSource(){return this.settings.dataSource}contextWith(e){return new ParseContextImpl({...this.settings,...e},this.databaseId,this.serializer,this.ignoreUndefinedProperties,this.fieldTransforms,this.fieldMask)}childContextForField(e){const i=this.path?.child(e),s=this.contextWith({path:i,arrayElement:!1});return s.validatePathSegment(e),s}childContextForFieldPath(e){const i=this.path?.child(e),s=this.contextWith({path:i,arrayElement:!1});return s.validatePath(),s}childContextForArray(e){return this.contextWith({path:void 0,arrayElement:!0})}createError(e){return createError(e,this.settings.methodName,this.settings.hasConverter||!1,this.path,this.settings.targetDoc)}contains(e){return void 0!==this.fieldMask.find((i=>e.isPrefixOf(i)))||void 0!==this.fieldTransforms.find((i=>e.isPrefixOf(i.field)))}validatePath(){if(this.path)for(let e=0;e<this.path.length;e++)this.validatePathSegment(this.path.get(e))}validatePathSegment(e){if(0===e.length)throw this.createError("Document fields must not be empty");if(__PRIVATE_isWrite(this.dataSource)&&qe.test(e))throw this.createError('Document fields cannot begin and end with "__"')}}class UserDataReader{constructor(e,i,s){this.databaseId=e,this.ignoreUndefinedProperties=i,this.serializer=s||__PRIVATE_newSerializer(e)}createContext(e,i,s,T=!1){return new ParseContextImpl({dataSource:e,methodName:i,targetDoc:s,path:Ee.emptyPath(),arrayElement:!1,hasConverter:T},this.databaseId,this.serializer,this.ignoreUndefinedProperties)}}function p(e){const i=e._freezeSettings(),s=__PRIVATE_newSerializer(e._databaseId);return new UserDataReader(e._databaseId,!!i.ignoreUndefinedProperties,s)}function y(e,i,s,T,E,V={}){const R=e.createContext(V.merge||V.mergeFields?2:0,i,s,E);__PRIVATE_validatePlainObject("Data must be an object, but it was:",R,T);const N=__PRIVATE_parseObject(T,R);let O,M;if(V.merge)O=new FieldMask(R.fieldMask),M=R.fieldTransforms;else if(V.mergeFields){const e=[];for(const T of V.mergeFields){const E=_(i,T,s);if(!R.contains(E))throw new k(te,`Field '${E}' is specified in your field mask but missing from your input data.`);__PRIVATE_fieldMaskContains(e,E)||e.push(E)}O=new FieldMask(e),M=R.fieldTransforms.filter((e=>O.covers(e.field)))}else O=null,M=R.fieldTransforms;return new ParsedSetData(new u(N),O,M)}class __PRIVATE_DeleteFieldValueImpl extends FieldValue{_toFieldTransform(e){if(2!==e.dataSource)throw 1===e.dataSource?e.createError(`${this._methodName}() can only appear at the top level of your update data`):e.createError(`${this._methodName}() cannot be used with set() unless you pass {merge:true}`);return e.fieldMask.push(e.path),null}isEqual(e){return e instanceof __PRIVATE_DeleteFieldValueImpl}}function __PRIVATE_createSentinelChildContext(e,i,s){return new ParseContextImpl({dataSource:3,targetDoc:i.settings.targetDoc,methodName:e._methodName,arrayElement:s},i.databaseId,i.serializer,i.ignoreUndefinedProperties)}class __PRIVATE_ServerTimestampFieldValueImpl extends FieldValue{_toFieldTransform(e){return new FieldTransform(e.path,new __PRIVATE_ServerTimestampTransform)}isEqual(e){return e instanceof __PRIVATE_ServerTimestampFieldValueImpl}}class __PRIVATE_ArrayUnionFieldValueImpl extends FieldValue{constructor(e,i){super(e),this.Se=i}_toFieldTransform(e){const i=__PRIVATE_createSentinelChildContext(this,e,!0),s=this.Se.map((e=>__PRIVATE_parseData(e,i))),T=new __PRIVATE_ArrayUnionTransformOperation(s);return new FieldTransform(e.path,T)}isEqual(e){return e instanceof __PRIVATE_ArrayUnionFieldValueImpl&&deepEqual(this.Se,e.Se)}}class __PRIVATE_ArrayRemoveFieldValueImpl extends FieldValue{constructor(e,i){super(e),this.Se=i}_toFieldTransform(e){const i=__PRIVATE_createSentinelChildContext(this,e,!0),s=this.Se.map((e=>__PRIVATE_parseData(e,i))),T=new __PRIVATE_ArrayRemoveTransformOperation(s);return new FieldTransform(e.path,T)}isEqual(e){return e instanceof __PRIVATE_ArrayRemoveFieldValueImpl&&deepEqual(this.Se,e.Se)}}class __PRIVATE_NumericIncrementFieldValueImpl extends FieldValue{constructor(e,i){super(e),this.Ce=i}_toFieldTransform(e){const i=new __PRIVATE_NumericIncrementTransformOperation(e.serializer,toNumber(e.serializer,this.Ce));return new FieldTransform(e.path,i)}isEqual(e){return e instanceof __PRIVATE_NumericIncrementFieldValueImpl&&(this.Ce===e.Ce||Number.isNaN(this.Ce)&&Number.isNaN(e.Ce))}}class __PRIVATE_NumericMinimumFieldValueImpl extends FieldValue{constructor(e,i){super(e),this.Ce=i}_toFieldTransform(e){const i=new __PRIVATE_NumericMinimumTransformOperation(e.serializer,toNumber(e.serializer,this.Ce));return new FieldTransform(e.path,i)}isEqual(e){return e instanceof __PRIVATE_NumericMinimumFieldValueImpl&&(this.Ce===e.Ce||Number.isNaN(this.Ce)&&Number.isNaN(e.Ce))}}class __PRIVATE_NumericMaximumFieldValueImpl extends FieldValue{constructor(e,i){super(e),this.Ce=i}_toFieldTransform(e){const i=new __PRIVATE_NumericMaximumTransformOperation(e.serializer,toNumber(e.serializer,this.Ce));return new FieldTransform(e.path,i)}isEqual(e){return e instanceof __PRIVATE_NumericMaximumFieldValueImpl&&(this.Ce===e.Ce||Number.isNaN(this.Ce)&&Number.isNaN(e.Ce))}}function v(e,i,s,T){const E=e.createContext(1,i,s);__PRIVATE_validatePlainObject("Data must be an object, but it was:",E,T);const V=[],R=u.empty();forEach(T,((e,T)=>{const N=__PRIVATE_fieldPathFromDotSeparatedString(i,e,s);T=getModularInstance(T);const O=E.childContextForFieldPath(N);if(T instanceof __PRIVATE_DeleteFieldValueImpl)V.push(N);else{const e=__PRIVATE_parseData(T,O);null!=e&&(V.push(N),R.set(N,e))}}));const N=new FieldMask(V);return new ParsedUpdateData(R,N,E.fieldTransforms)}function b(e,i,s,T,E,V){const R=e.createContext(1,i,s),N=[_(i,T,s)],O=[E];if(V.length%2!=0)throw new k(te,`Function ${i}() needs to be called with an even number of arguments that alternate between field names and values.`);for(let e=0;e<V.length;e+=2)N.push(_(i,V[e])),O.push(V[e+1]);const M=[],L=u.empty();for(let e=N.length-1;e>=0;--e)if(!__PRIVATE_fieldMaskContains(M,N[e])){const i=N[e];let s=O[e];s=getModularInstance(s);const T=R.childContextForFieldPath(i);if(s instanceof __PRIVATE_DeleteFieldValueImpl)M.push(i);else{const e=__PRIVATE_parseData(s,T);null!=e&&(M.push(i),L.set(i,e))}}const U=new FieldMask(M);return new ParsedUpdateData(L,U,R.fieldTransforms)}function __PRIVATE_parseQueryValue(e,i,s,T=!1){return __PRIVATE_parseData(s,e.createContext(T?4:3,i))}function __PRIVATE_parseData(e,i,s){if(__PRIVATE_looksLikeJsonObject(e=getModularInstance(e)))return __PRIVATE_validatePlainObject("Unsupported field value:",i,e),__PRIVATE_parseObject(e,i);if(e instanceof FieldValue)return function __PRIVATE_parseSentinelFieldValue(e,i){if(!__PRIVATE_isWrite(i.dataSource))throw i.createError(`${e._methodName}() can only be used with update() and set()`);if(!i.path)throw i.createError(`${e._methodName}() is not currently supported inside arrays`);const s=e._toFieldTransform(i);s&&i.fieldTransforms.push(s)}(e,i),null;if(void 0===e&&i.ignoreUndefinedProperties)return null;if(i.path&&i.fieldMask.push(i.path),e instanceof Array){if(i.settings.arrayElement&&4!==i.dataSource)throw i.createError("Nested arrays are not supported");return function __PRIVATE_parseArray(e,i){const s=[];let T=0;for(const E of e){let e=__PRIVATE_parseData(E,i.childContextForArray(T));null==e&&(e={nullValue:"NULL_VALUE"}),s.push(e),T++}return{arrayValue:{values:s}}}(e,i)}return function __PRIVATE_parseScalarValue(e,i){if(null===(e=getModularInstance(e)))return{nullValue:"NULL_VALUE"};if("number"==typeof e)return toNumber(i.serializer,e);if("boolean"==typeof e)return{booleanValue:e};if("string"==typeof e)return{stringValue:e};if(e instanceof Date){const s=Timestamp.fromDate(e);return{timestampValue:toTimestamp(i.serializer,s)}}if(e instanceof Timestamp){const s=new Timestamp(e.seconds,1e3*Math.floor(e.nanoseconds/1e3));return{timestampValue:toTimestamp(i.serializer,s)}}if(__PRIVATE_isTemporalInstant(e)){const s=Timestamp.fromInstant(e),T=new Timestamp(s.seconds,1e3*Math.floor(s.nanoseconds/1e3));return{timestampValue:toTimestamp(i.serializer,T)}}if(e instanceof GeoPoint)return{geoPointValue:{latitude:e.latitude,longitude:e.longitude}};if(e instanceof Bytes)return{bytesValue:__PRIVATE_toBytes(i.serializer,e._byteString)};if(e instanceof DocumentReference){const s=i.databaseId,T=e.firestore._databaseId;if(!T.isEqual(s))throw i.createError(`Document reference is for database ${T.projectId}/${T.database} but should be for database ${s.projectId}/${s.database}`);return{referenceValue:__PRIVATE_toResourceName(e.firestore._databaseId||i.databaseId,e._key.path)}}if(e instanceof VectorValue)return function __PRIVATE_parseVectorValue(e,i){const s=e instanceof VectorValue?e.toArray():e,T={fields:{[be]:{stringValue:Ce},[ke]:{arrayValue:{values:s.map((e=>{if("number"!=typeof e)throw i.createError("VectorValues must only contain numeric values.");return __PRIVATE_toDouble(i.serializer,e)}))}}}};return{mapValue:T}}(e,i);if(__PRIVATE_isProtoValueSerializable(e))return e._toProto(i.serializer);throw i.createError(`Unsupported field value: ${__PRIVATE_valueDescription(e)}`)}(e,i)}function __PRIVATE_parseObject(e,i){const s={};return function isEmpty(e){for(const i in e)if(Object.prototype.hasOwnProperty.call(e,i))return!1;return!0}(e)?i.path&&i.path.length>0&&i.fieldMask.push(i.path):forEach(e,((e,T)=>{const E=__PRIVATE_parseData(T,i.childContextForField(e));null!=E&&(s[e]=E)})),{mapValue:{fields:s}}}function __PRIVATE_isTemporalInstant(e){if("object"!=typeof e||null===e)return!1;if("undefined"!=typeof Temporal&&"function"==typeof Temporal.Instant&&e instanceof Temporal.Instant)return!0;const i=e;return"Temporal.Instant"===i[Symbol.toStringTag]&&"bigint"==typeof i.Te}function __PRIVATE_looksLikeJsonObject(e){return!("object"!=typeof e||null===e||e instanceof Array||e instanceof Date||e instanceof Timestamp||e instanceof GeoPoint||e instanceof Bytes||e instanceof DocumentReference||e instanceof FieldValue||e instanceof VectorValue||__PRIVATE_isTemporalInstant(e)||__PRIVATE_isProtoValueSerializable(e))}function __PRIVATE_validatePlainObject(e,i,s){if(!__PRIVATE_looksLikeJsonObject(s)||!__PRIVATE_isPlainObject(s)){const T=__PRIVATE_valueDescription(s);throw"an object"===T?i.createError(e+" a custom object"):i.createError(e+" "+T)}}function _(e,i,s){if((i=getModularInstance(i))instanceof D)return i._internalPath;if("string"==typeof i)return __PRIVATE_fieldPathFromDotSeparatedString(e,i);throw createError("Field path arguments must be of type string or ",e,!1,void 0,s)}const ze=new RegExp("[~\\*/\\[\\]]");function __PRIVATE_fieldPathFromDotSeparatedString(e,i,s){if(i.search(ze)>=0)throw createError(`Invalid field path (${i}). Paths must not contain '~', '*', '/', '[', or ']'`,e,!1,void 0,s);try{return new D(...i.split("."))._internalPath}catch(T){throw createError(`Invalid field path (${i}). Paths must not be empty, begin with '.', end with '.', or contain '..'`,e,!1,void 0,s)}}function createError(e,i,s,T,E){const V=T&&!T.isEmpty(),R=void 0!==E;let N=`Function ${i}() called with invalid data`;s&&(N+=" (via `toFirestore()`)"),N+=". ";let O="";return(V||R)&&(O+=" (found",V&&(O+=` in field ${T}`),R&&(O+=` in document ${E}`),O+=")"),new k(te,N+e+O)}function __PRIVATE_fieldMaskContains(e,i){return e.some((e=>e.isEqual(i)))}class it{constructor(e,i,s,T,E){this._firestore=e,this._userDataWriter=i,this._key=s,this._document=T,this._converter=E}get id(){return this._key.path.lastSegment()}get ref(){return new DocumentReference(this._firestore,this._converter,this._key)}exists(){return null!==this._document}data(){if(this._document){if(this._converter){const e=new QueryDocumentSnapshot(this._firestore,this._userDataWriter,this._key,this._document,null);return this._converter.fromFirestore(e)}return this._userDataWriter.convertValue(this._document.data.value)}}_fieldsProto(){return this._document?.data.clone().value.mapValue.fields??void 0}get(e){if(this._document){const i=this._document.data.field(_("DocumentSnapshot.get",e));if(null!==i)return this._userDataWriter.convertValue(i)}}}class QueryDocumentSnapshot extends it{data(){return super.data()}}class QuerySnapshot{constructor(e,i){this._docs=i,this.query=e}get docs(){return[...this._docs]}get size(){return this.docs.length}get empty(){return 0===this.docs.length}forEach(e,i){this._docs.forEach(e,i)}}function snapshotEqual(e,i){return e=getModularInstance(e),i=getModularInstance(i),e instanceof it&&i instanceof it?e._firestore===i._firestore&&e._key.isEqual(i._key)&&(null===e._document?null===i._document:e._document.isEqual(i._document))&&e._converter===i._converter:e instanceof QuerySnapshot&&i instanceof QuerySnapshot&&l(e.query,i.query)&&__PRIVATE_arrayEquals(e.docs,i.docs,snapshotEqual)}class AppliableConstraint{}class QueryConstraint extends AppliableConstraint{}function query(e,i,...s){let T=[];i instanceof AppliableConstraint&&T.push(i),T=T.concat(s),function __PRIVATE_validateQueryConstraintArray(e){const i=e.filter((e=>e instanceof QueryCompositeFilterConstraint)).length,s=e.filter((e=>e instanceof QueryFieldFilterConstraint)).length;if(i>1||i>0&&s>0)throw new k(te,"InvalidQuery. When using composite filters, you cannot use more than one filter at the top level. Consider nesting the multiple filters within an `and(...)` statement. For example: change `query(query, where(...), or(...))` to `query(query, and(where(...), or(...)))`.")}(T);for(const i of T)e=i._apply(e);return e}class QueryFieldFilterConstraint extends QueryConstraint{constructor(e,i,s){super(),this._field=e,this._op=i,this._value=s,this.type="where"}static _create(e,i,s){return new QueryFieldFilterConstraint(e,i,s)}_apply(e){const i=this._parse(e);return __PRIVATE_validateNewFieldFilter(e._query,i),new Query(e.firestore,e.converter,__PRIVATE_queryWithAddedFilter(e._query,i))}_parse(e){const i=p(e.firestore),s=function __PRIVATE_newQueryFilter(e,i,s,T,E,V,R){let N;if(E.isKeyField()){if("array-contains"===V||"array-contains-any"===V)throw new k(te,`Invalid Query. You can't perform '${V}' queries on documentId().`);if("in"===V||"not-in"===V){__PRIVATE_validateDisjunctiveFilterElements(R,V);const i=[];for(const s of R)i.push(__PRIVATE_parseDocumentIdValue(T,e,s));N={arrayValue:{values:i}}}else N=__PRIVATE_parseDocumentIdValue(T,e,R)}else"in"!==V&&"not-in"!==V&&"array-contains-any"!==V||__PRIVATE_validateDisjunctiveFilterElements(R,V),N=__PRIVATE_parseQueryValue(s,i,R,"in"===V||"not-in"===V);return FieldFilter.create(E,V,N)}(e._query,"where",i,e.firestore._databaseId,this._field,this._op,this._value);return s}}function where(e,i,s){const T=i,E=_("where",e);return QueryFieldFilterConstraint._create(E,T,s)}class QueryCompositeFilterConstraint extends AppliableConstraint{constructor(e,i){super(),this.type=e,this._queryConstraints=i}static _create(e,i){return new QueryCompositeFilterConstraint(e,i)}_parse(e){const i=this._queryConstraints.map((i=>i._parse(e))).filter((e=>e.getFilters().length>0));return 1===i.length?i[0]:CompositeFilter.create(i,this._getOperator())}_apply(e){const i=this._parse(e);return 0===i.getFilters().length?e:(function __PRIVATE_validateNewFilter(e,i){let s=e;const T=i.getFlattenedFilters();for(const e of T)__PRIVATE_validateNewFieldFilter(s,e),s=__PRIVATE_queryWithAddedFilter(s,e)}(e._query,i),new Query(e.firestore,e.converter,__PRIVATE_queryWithAddedFilter(e._query,i)))}_getQueryConstraints(){return this._queryConstraints}_getOperator(){return"and"===this.type?"and":"or"}}function or(...e){return e.forEach((e=>__PRIVATE_validateQueryFilterConstraint("or",e))),QueryCompositeFilterConstraint._create("or",e)}function and(...e){return e.forEach((e=>__PRIVATE_validateQueryFilterConstraint("and",e))),QueryCompositeFilterConstraint._create("and",e)}class QueryOrderByConstraint extends QueryConstraint{constructor(e,i){super(),this._field=e,this._direction=i,this.type="orderBy"}static _create(e,i){return new QueryOrderByConstraint(e,i)}_apply(e){const i=function __PRIVATE_newQueryOrderBy(e,i,s){if(null!==e.startAt)throw new k(te,"Invalid query. You must not call startAt() or startAfter() before calling orderBy().");if(null!==e.endAt)throw new k(te,"Invalid query. You must not call endAt() or endBefore() before calling orderBy().");return new OrderBy(i,s)}(e._query,this._field,this._direction);return new Query(e.firestore,e.converter,function __PRIVATE_queryWithAddedOrderBy(e,i){const s=e.explicitOrderBy.concat([i]);return new __PRIVATE_QueryImpl(e.path,e.collectionGroup,s,e.filters.slice(),e.limit,e.limitType,e.startAt,e.endAt)}(e._query,i))}}function orderBy(e,i="asc"){const s=i,T=_("orderBy",e);return QueryOrderByConstraint._create(T,s)}class QueryLimitConstraint extends QueryConstraint{constructor(e,i,s){super(),this.type=e,this._limit=i,this._limitType=s}static _create(e,i,s){return new QueryLimitConstraint(e,i,s)}_apply(e){return new Query(e.firestore,e.converter,function __PRIVATE_queryWithLimit(e,i,s){return new __PRIVATE_QueryImpl(e.path,e.collectionGroup,e.explicitOrderBy.slice(),e.filters.slice(),i,s,e.startAt,e.endAt)}(e._query,this._limit,this._limitType))}}function limit(e){return __PRIVATE_validatePositiveNumber("limit",e),QueryLimitConstraint._create("limit",e,"F")}function limitToLast(e){return __PRIVATE_validatePositiveNumber("limitToLast",e),QueryLimitConstraint._create("limitToLast",e,"L")}class QueryStartAtConstraint extends QueryConstraint{constructor(e,i,s){super(),this.type=e,this._docOrFields=i,this._inclusive=s}static _create(e,i,s){return new QueryStartAtConstraint(e,i,s)}_apply(e){const i=__PRIVATE_newQueryBoundFromDocOrFields(e,this.type,this._docOrFields,this._inclusive);return new Query(e.firestore,e.converter,function __PRIVATE_queryWithStartAt(e,i){return new __PRIVATE_QueryImpl(e.path,e.collectionGroup,e.explicitOrderBy.slice(),e.filters.slice(),e.limit,e.limitType,i,e.endAt)}(e._query,i))}}function startAt(...e){return QueryStartAtConstraint._create("startAt",e,!0)}function startAfter(...e){return QueryStartAtConstraint._create("startAfter",e,!1)}class QueryEndAtConstraint extends QueryConstraint{constructor(e,i,s){super(),this.type=e,this._docOrFields=i,this._inclusive=s}static _create(e,i,s){return new QueryEndAtConstraint(e,i,s)}_apply(e){const i=__PRIVATE_newQueryBoundFromDocOrFields(e,this.type,this._docOrFields,this._inclusive);return new Query(e.firestore,e.converter,function __PRIVATE_queryWithEndAt(e,i){return new __PRIVATE_QueryImpl(e.path,e.collectionGroup,e.explicitOrderBy.slice(),e.filters.slice(),e.limit,e.limitType,e.startAt,i)}(e._query,i))}}function endBefore(...e){return QueryEndAtConstraint._create("endBefore",e,!1)}function endAt(...e){return QueryEndAtConstraint._create("endAt",e,!0)}function __PRIVATE_newQueryBoundFromDocOrFields(e,i,s,T){if(s[0]=getModularInstance(s[0]),s[0]instanceof it)return function __PRIVATE_newQueryBoundFromDocument(e,i,s,T,E){if(!T)throw new k(ne,`Can't use a DocumentSnapshot that doesn't exist for ${s}().`);const V=[];for(const s of __PRIVATE_queryNormalizedOrderBy(e))if(s.field.isKeyField())V.push(__PRIVATE_refValue(i,T.key));else{const e=T.data.field(s.field);if(__PRIVATE_isServerTimestamp(e))throw new k(te,'Invalid query. You are trying to start or end a query using a document for which the field "'+s.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=s.field.canonicalString();throw new k(te,`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.`)}V.push(e)}return new Bound(V,E)}(e._query,e.firestore._databaseId,i,s[0]._document,T);{const E=p(e.firestore);return function __PRIVATE_newQueryBoundFromFields(e,i,s,T,E,V){const R=e.explicitOrderBy;if(E.length>R.length)throw new k(te,`Too many arguments provided to ${T}(). The number of arguments must be less than or equal to the number of orderBy() clauses`);const N=[];for(let V=0;V<E.length;V++){const O=E[V];if(R[V].field.isKeyField()){if("string"!=typeof O)throw new k(te,`Invalid query. Expected a string for document ID in ${T}(), but got a ${typeof O}`);if(!__PRIVATE_isCollectionGroupQuery(e)&&-1!==O.indexOf("/"))throw new k(te,`Invalid query. When querying a collection and ordering by documentId(), the value passed to ${T}() must be a plain document ID, but '${O}' contains a slash.`);const s=e.path.child(ResourcePath.fromString(O));if(!x.isDocumentKey(s))throw new k(te,`Invalid query. When querying a collection group and ordering by documentId(), the value passed to ${T}() must result in a valid document path, but '${s}' is not because it contains an odd number of segments.`);const E=new x(s);N.push(__PRIVATE_refValue(i,E))}else{const e=__PRIVATE_parseQueryValue(s,T,O);N.push(e)}}return new Bound(N,V)}(e._query,e.firestore._databaseId,E,i,s,T)}}function __PRIVATE_parseDocumentIdValue(e,i,s){if("string"==typeof(s=getModularInstance(s))){if(""===s)throw new k(te,"Invalid query. When querying with documentId(), you must provide a valid document ID, but it was an empty string.");if(!__PRIVATE_isCollectionGroupQuery(i)&&-1!==s.indexOf("/"))throw new k(te,`Invalid query. When querying a collection by documentId(), you must provide a plain document ID, but '${s}' contains a '/' character.`);const T=i.path.child(ResourcePath.fromString(s));if(!x.isDocumentKey(T))throw new k(te,`Invalid query. When querying a collection group by documentId(), the value provided must result in a valid document path, but '${T}' is not because it has an odd number of segments (${T.length}).`);return __PRIVATE_refValue(e,new x(T))}if(s instanceof DocumentReference)return __PRIVATE_refValue(e,s._key);throw new k(te,`Invalid query. When querying with documentId(), you must provide a valid string or a DocumentReference, but it was: ${__PRIVATE_valueDescription(s)}.`)}function __PRIVATE_validateDisjunctiveFilterElements(e,i){if(!Array.isArray(e)||0===e.length)throw new k(te,`Invalid Query. A non-empty array is required for '${i.toString()}' filters.`)}function __PRIVATE_validateNewFieldFilter(e,i){const s=function __PRIVATE_findOpInsideFilters(e,i){for(const s of e)for(const e of s.getFlattenedFilters())if(i.indexOf(e.op)>=0)return e.op;return null}(e.filters,function __PRIVATE_conflictingOps(e){switch(e){case"!=":return["!=","not-in"];case"array-contains-any":case"in":return["not-in"];case"not-in":return["array-contains-any","in","not-in","!="];default:return[]}}(i.op));if(null!==s)throw s===i.op?new k(te,`Invalid query. You cannot use more than one '${i.op.toString()}' filter.`):new k(te,`Invalid query. You cannot use '${i.op.toString()}' filters with '${s.toString()}' filters.`)}function __PRIVATE_validateQueryFilterConstraint(e,i){if(!(i instanceof QueryFieldFilterConstraint||i instanceof QueryCompositeFilterConstraint))throw new k(te,`Function ${e}() requires AppliableConstraints created with a call to 'where(...)', 'or(...)', or 'and(...)'.`)}class AbstractUserDataWriter{convertValue(e,i="none"){switch(__PRIVATE_typeOrder(e)){case 0:return null;case 1:return e.booleanValue;case 2:return __PRIVATE_normalizeNumber(e.integerValue||e.doubleValue);case 3:return this.convertTimestamp(e.timestampValue);case 4:return this.convertServerTimestamp(e,i);case 5:return e.stringValue;case 6:return this.convertBytes(__PRIVATE_normalizeByteString(e.bytesValue));case 7:return this.convertReference(e.referenceValue);case 8:return this.convertGeoPoint(e.geoPointValue);case 9:return this.convertArray(e.arrayValue,i);case 11:return this.convertObject(e.mapValue,i);case 10:return this.convertVectorValue(e.mapValue);default:throw z(62114,{value:e})}}convertObject(e,i){return this.convertObjectMap(e.fields,i)}convertObjectMap(e,i="none"){const s={};return forEach(e,((e,T)=>{s[e]=this.convertValue(T,i)})),s}convertVectorValue(e){const i=e.fields?.[ke].arrayValue?.values?.map((e=>__PRIVATE_normalizeNumber(e.doubleValue)));return new VectorValue(i)}convertGeoPoint(e){return new GeoPoint(__PRIVATE_normalizeNumber(e.latitude),__PRIVATE_normalizeNumber(e.longitude))}convertArray(e,i){return(e.values||[]).map((e=>this.convertValue(e,i)))}convertServerTimestamp(e,i){switch(i){case"previous":const s=__PRIVATE_getPreviousValue(e);return null==s?null:this.convertValue(s,i);case"estimate":return this.convertTimestamp(__PRIVATE_getLocalWriteTime(e));default:return null}}convertTimestamp(e){const i=__PRIVATE_normalizeTimestamp(e);return new Timestamp(i.seconds,i.nanos)}convertDocumentKey(e,i){const s=ResourcePath.fromString(e);__PRIVATE_hardAssert(__PRIVATE_isValidResourceName(s),9688,{name:e});const T=new DatabaseId(s.get(1),s.get(3)),E=new x(s.popFirst(5));return T.isEqual(i)||st(`A document reference to ${E} refers to a different database (${T.projectId}/${T.database}), which is not supported. It will be treated as a reference in the current database (${i.projectId}/${i.database}) instead.`),E}}function w(e,i,s){let T;return T=e?s&&(s.merge||s.mergeFields)?e.toFirestore(i,s):e.toFirestore(i):i,T}class A extends AbstractUserDataWriter{constructor(e){super(),this.firestore=e}convertBytes(e){return new Bytes(e)}convertReference(e){const i=this.convertDocumentKey(e,this.firestore._databaseId);return new DocumentReference(this.firestore,null,i)}}function getDoc(e){const i=d((e=f(e,DocumentReference)).firestore),s=new A(e.firestore);return q(i,[e._key]).then((i=>{__PRIVATE_hardAssert(1===i.length,15618);const T=i[0];return new it(e.firestore,s,e._key,T.isFoundDocument()?T:null,e.converter)}))}function getDocs(e){!function __PRIVATE_validateHasExplicitOrderByForLimitToLast(e){if("L"===e.limitType&&0===e.explicitOrderBy.length)throw new k(he,"limitToLast() queries require specifying at least one orderBy() clause")}((e=f(e,Query))._query);const i=d(e.firestore),s=new A(e.firestore);return async function __PRIVATE_invokeRunQueryRpc(e,i){const s=__PRIVATE_debugCast(e),{ve:T,parent:E}=__PRIVATE_toQueryTarget(s.serializer,__PRIVATE_queryToTarget(i));return(await s.de("RunQuery",s.serializer.databaseId,E,{structuredQuery:T.structuredQuery})).filter((e=>!!e.document)).map((e=>function fromDocument(e,i,s){const T=fromName(e,i.name),E=__PRIVATE_fromVersion(i.updateTime),V=i.createTime?__PRIVATE_fromVersion(i.createTime):j.min(),R=new u({mapValue:{fields:i.fields}}),N=MutableDocument.newFoundDocument(T,E,V,R);return s?N.setHasCommittedMutations():N}(s.serializer,e.document,void 0)))}(i,e._query).then((i=>{const T=i.map((i=>new QueryDocumentSnapshot(e.firestore,s,i.key,i,e.converter)));return"L"===e._query.limitType&&T.reverse(),new QuerySnapshot(e,T)}))}function setDoc(e,i,s){const T=w((e=f(e,DocumentReference)).converter,i,s),E=y(p(e.firestore),"setDoc",e._key,T,null!==e.converter,s);return S(d(e.firestore),[E.toMutation(e._key,P.none())])}function updateDoc(e,i,s,...T){const E=p((e=f(e,DocumentReference)).firestore);let V;return V="string"==typeof(i=getModularInstance(i))||i instanceof D?b(E,"updateDoc",e._key,i,s,T):v(E,"updateDoc",e._key,i),S(d(e.firestore),[V.toMutation(e._key,P.exists(!0))])}function deleteDoc(e){return S(d((e=f(e,DocumentReference)).firestore),[new F(e._key,P.none())])}function addDoc(e,i){const s=doc(e=f(e,CollectionReference)),T=w(e.converter,i),E=y(p(e.firestore),"addDoc",s._key,T,null!==s.converter,{});return S(d(e.firestore),[E.toMutation(s._key,P.exists(!1))]).then((()=>s))}function deleteField(){return new __PRIVATE_DeleteFieldValueImpl("deleteField")}function serverTimestamp(){return new __PRIVATE_ServerTimestampFieldValueImpl("serverTimestamp")}function arrayUnion(...e){return new __PRIVATE_ArrayUnionFieldValueImpl("arrayUnion",e)}function arrayRemove(...e){return new __PRIVATE_ArrayRemoveFieldValueImpl("arrayRemove",e)}function increment(e){return new __PRIVATE_NumericIncrementFieldValueImpl("increment",e)}function minimum(e){return new __PRIVATE_NumericMinimumFieldValueImpl("minimum",e)}function maximum(e){return new __PRIVATE_NumericMaximumFieldValueImpl("maximum",e)}function vector(e){return new VectorValue(e)}const je="4.17.2";class __PRIVATE_Deferred{constructor(){this.promise=new Promise(((e,i)=>{this.resolve=e,this.reject=i}))}}class __PRIVATE_AggregateImpl{constructor(e,i,s){this.alias=e,this.aggregateType=i,this.fieldPath=s}}class __PRIVATE_ExponentialBackoff{constructor(e,i,s=1e3,T=1.5,E=6e4){this.t=e,this.timerId=i,this.i=s,this.o=T,this.h=E,this.u=0,this.l=null,this._=Date.now(),this.reset()}reset(){this.u=0}m(){this.u=this.h}A(e){this.cancel();const i=Math.floor(this.u+this.p()),s=Math.max(0,Date.now()-this._),T=Math.max(0,i-s);T>0&&a("ExponentialBackoff",`Backing off for ${T} ms (base delay: ${this.u} ms, delay with jitter: ${i} ms, last attempt: ${s} ms ago)`),this.l=this.t.enqueueAfterDelay(this.timerId,T,(()=>(this._=Date.now(),e()))),this.u*=this.o,this.u<this.i&&(this.u=this.i),this.u>this.h&&(this.u=this.h)}T(){null!==this.l&&(this.l.skipDelay(),this.l=null)}cancel(){null!==this.l&&(this.l.cancel(),this.l=null)}p(){return(Math.random()-.5)*this.u}}class AggregateField{constructor(e="count",i){this._internalFieldPath=i,this.type="AggregateField",this.aggregateType=e}}class AggregateQuerySnapshot{constructor(e,i,s){this._userDataWriter=i,this._data=s,this.type="AggregateQuerySnapshot",this.query=e}data(){return this._userDataWriter.convertObjectMap(this._data)}_fieldsProto(){return new u({mapValue:{fields:this._data}}).clone().value.mapValue.fields}}function getCount(e){return getAggregate(e,{count:count()})}function getAggregate(e,i){const s=f(e.firestore,n),T=d(s),E=function g(e,i){const s=[];for(const T in e)Object.prototype.hasOwnProperty.call(e,T)&&s.push(i(e[T],T,e));return s}(i,((e,i)=>new __PRIVATE_AggregateImpl(i,e.aggregateType,e._internalFieldPath)));return async function m(e,i,s){const T=__PRIVATE_debugCast(e),{request:E,Ne:V,parent:R}=function __PRIVATE_toRunAggregationQueryRequest(e,i,s){const{ve:T,parent:E}=__PRIVATE_toQueryTarget(e,i),V={},R=[];let N=0;return s.forEach((e=>{const i="aggregate_"+N++;V[i]=e.alias,"count"===e.aggregateType?R.push({alias:i,count:{}}):"avg"===e.aggregateType?R.push({alias:i,avg:{field:__PRIVATE_toFieldPathReference(e.fieldPath)}}):"sum"===e.aggregateType&&R.push({alias:i,sum:{field:__PRIVATE_toFieldPathReference(e.fieldPath)}})})),{request:{structuredAggregationQuery:{aggregations:R,structuredQuery:T.structuredQuery},parent:T.parent},Ne:V,parent:E}}(T.serializer,function __PRIVATE_queryToAggregateTarget(e){const i=__PRIVATE_debugCast(e);return i.we||(i.we=__PRIVATE__queryToTarget(i,e.explicitOrderBy)),i.we}(i),s);T.connection.ae||delete E.parent;const N=(await T.de("RunAggregationQuery",T.serializer.databaseId,R,E,1)).filter((e=>!!e.result));__PRIVATE_hardAssert(1===N.length,64727);const O=N[0].result?.aggregateFields;return Object.keys(O).reduce(((e,i)=>(e[V[i]]=O[i],e)),{})}(T,e._query,E).then((i=>function __PRIVATE_convertToAggregateQuerySnapshot(e,i,s){const T=new A(e);return new AggregateQuerySnapshot(i,T,s)}(s,e,i)))}function sum(e){return new AggregateField("sum",_("sum",e))}function average(e){return new AggregateField("avg",_("average",e))}function count(){return new AggregateField("count")}function aggregateFieldEqual(e,i){return e instanceof AggregateField&&i instanceof AggregateField&&e.aggregateType===i.aggregateType&&e._internalFieldPath?.canonicalString()===i._internalFieldPath?.canonicalString()}function aggregateQuerySnapshotEqual(e,i){return l(e.query,i.query)&&deepEqual(e.data(),i.data())}class WriteBatch{constructor(e,i){this._firestore=e,this._commitHandler=i,this._mutations=[],this._committed=!1,this._dataReader=p(e)}set(e,i,s){this._verifyNotCommitted();const T=__PRIVATE_validateReference(e,this._firestore),E=w(T.converter,i,s),V=y(this._dataReader,"WriteBatch.set",T._key,E,null!==T.converter,s);return this._mutations.push(V.toMutation(T._key,P.none())),this}update(e,i,s,...T){this._verifyNotCommitted();const E=__PRIVATE_validateReference(e,this._firestore);let V;return V="string"==typeof(i=getModularInstance(i))||i instanceof D?b(this._dataReader,"WriteBatch.update",E._key,i,s,T):v(this._dataReader,"WriteBatch.update",E._key,i),this._mutations.push(V.toMutation(E._key,P.exists(!0))),this}delete(e){this._verifyNotCommitted();const i=__PRIVATE_validateReference(e,this._firestore);return this._mutations=this._mutations.concat(new F(i._key,P.none())),this}commit(){return this._verifyNotCommitted(),this._committed=!0,this._mutations.length>0?this._commitHandler(this._mutations):Promise.resolve()}_verifyNotCommitted(){if(this._committed)throw new k(ue,"A write batch can no longer be used after commit() has been called.")}}function __PRIVATE_validateReference(e,i){if((e=getModularInstance(e)).firestore!==i)throw new k(te,"Provided document reference is from a different Firestore instance.");return e}function writeBatch(e){const i=d(e=f(e,n));return new WriteBatch(e,(e=>S(i,e)))}let Ue=class Transaction{constructor(e){this.datastore=e,this.readVersions=new Map,this.mutations=[],this.committed=!1,this.lastTransactionError=null,this.writtenDocs=new Set}async lookup(e){if(this.ensureCommitNotCalled(),this.mutations.length>0)throw this.lastTransactionError=new k(te,"Firestore transactions require all reads to be executed before all writes."),this.lastTransactionError;const i=await q(this.datastore,e);return i.forEach((e=>this.recordVersion(e))),i}set(e,i){this.write(i.toMutation(e,this.precondition(e))),this.writtenDocs.add(e.toString())}update(e,i){try{this.write(i.toMutation(e,this.preconditionForUpdate(e)))}catch(e){this.lastTransactionError=e}this.writtenDocs.add(e.toString())}delete(e){this.write(new F(e,this.precondition(e))),this.writtenDocs.add(e.toString())}async commit(){if(this.ensureCommitNotCalled(),this.lastTransactionError)throw this.lastTransactionError;const e=this.readVersions;this.mutations.forEach((i=>{e.delete(i.key.toString())})),e.forEach(((e,i)=>{const s=x.fromPath(i);this.mutations.push(new C(s,this.precondition(s)))})),await S(this.datastore,this.mutations),this.committed=!0}recordVersion(e){let i;if(e.isFoundDocument())i=e.version;else{if(!e.isNoDocument())throw z(50498,{R:e.constructor.name});i=j.min()}const s=this.readVersions.get(e.key.toString());if(s){if(!i.isEqual(s))throw new k(le,"Document version changed between two reads.")}else this.readVersions.set(e.key.toString(),i)}precondition(e){const i=this.readVersions.get(e.toString());return!this.writtenDocs.has(e.toString())&&i?i.isEqual(j.min())?P.exists(!1):P.updateTime(i):P.none()}preconditionForUpdate(e){const i=this.readVersions.get(e.toString());if(!this.writtenDocs.has(e.toString())&&i){if(i.isEqual(j.min()))throw new k(te,"Can't update a document that doesn't exist.");return P.updateTime(i)}return P.exists(!0)}write(e){this.ensureCommitNotCalled(),this.mutations.push(e)}ensureCommitNotCalled(){}};const Qe={maxAttempts:5};class __PRIVATE_TransactionRunner{constructor(e,i,s,T,E){this.asyncQueue=e,this.datastore=i,this.options=s,this.updateFunction=T,this.deferred=E,this.I=s.maxAttempts,this.P=new __PRIVATE_ExponentialBackoff(this.asyncQueue,"transaction_retry")}V(){this.I-=1,this.D()}D(){this.P.A((async()=>{const e=new Ue(this.datastore),i=this.v(e);i&&i.then((i=>{this.asyncQueue.enqueueAndForget((()=>e.commit().then((()=>{this.deferred.resolve(i)})).catch((e=>{this.F(e)}))))})).catch((e=>{this.F(e)}))}))}v(e){try{const i=this.updateFunction(e);return!tt(i)&&i.catch&&i.then?i:(this.deferred.reject(Error("Transaction callback must return a Promise")),null)}catch(e){return this.deferred.reject(e),null}}F(e){this.I>0&&this.B(e)?(this.I-=1,this.asyncQueue.enqueueAndForget((()=>(this.D(),Promise.resolve())))):this.deferred.reject(e)}B(e){if("FirebaseError"===e?.name){const i=e.code;return"aborted"===i||"failed-precondition"===i||"already-exists"===i||!function et(e){switch(e){case X:return z(64938);case Z:case ee:case re:case ae:case _e:case de:case oe:return!1;case te:case ne:case ie:case se:case ue:case le:case ce:case he:case fe:return!0;default:return z(15467,{code:e})}}(i)}return!1}}function getDocument(){return"undefined"!=typeof document?document:null}class DelayedOperation{constructor(e,i,s,T,E){this.asyncQueue=e,this.timerId=i,this.targetTimeMs=s,this.op=T,this.removalCallback=E,this.deferred=new __PRIVATE_Deferred,this.then=this.deferred.promise.then.bind(this.deferred.promise),this.deferred.promise.catch((e=>{}))}get promise(){return this.deferred.promise}static createAndSchedule(e,i,s,T,E){const V=Date.now()+s,R=new DelayedOperation(e,i,V,T,E);return R.start(s),R}start(e){this.timerHandle=setTimeout((()=>this.handleDelayElapsed()),e)}skipDelay(){return this.handleDelayElapsed()}cancel(e){null!==this.timerHandle&&(this.clearTimeout(),this.deferred.reject(new k(Z,"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)}}const $e="AsyncQueue";class __PRIVATE_AsyncQueueImpl{constructor(e=Promise.resolve()){this.k=[],this.O=!1,this.S=[],this.q=null,this.C=!1,this.M=!1,this.N=[],this.P=new __PRIVATE_ExponentialBackoff(this,"async_queue_retry"),this.L=()=>{const e=getDocument();e&&a($e,"Visibility state changed to "+e.visibilityState),this.P.T()},this.W=e;const i=getDocument();i&&"function"==typeof i.addEventListener&&i.addEventListener("visibilitychange",this.L)}get isShuttingDown(){return this.O}enqueueAndForget(e){this.enqueue(e)}enqueueAndForgetEvenWhileRestricted(e){this.U(),this.j(e)}enterRestrictedMode(e){if(!this.O){this.O=!0,this.M=e||!1;const i=getDocument();i&&"function"==typeof i.removeEventListener&&i.removeEventListener("visibilitychange",this.L)}}enqueue(e){if(this.U(),this.O)return new Promise((()=>{}));const i=new __PRIVATE_Deferred;return this.j((()=>this.O&&this.M?Promise.resolve():(e().then(i.resolve,i.reject),i.promise))).then((()=>i.promise))}enqueueRetryable(e){this.enqueueAndForget((()=>(this.k.push(e),this.$())))}async $(){if(0!==this.k.length){try{await this.k[0](),this.k.shift(),this.P.reset()}catch(e){if(!function __PRIVATE_isIndexedDbTransactionError(e){return"IndexedDbTransactionError"===e.name}(e))throw e;a($e,"Operation failed with retryable error: "+e)}this.k.length>0&&this.P.A((()=>this.$()))}}j(e){const i=this.W.then((()=>(this.C=!0,e().catch((e=>{this.q=e,this.C=!1;throw st("INTERNAL UNHANDLED ERROR: ",__PRIVATE_getMessageOrStack(e)),e})).then((e=>(this.C=!1,e))))));return this.W=i,i}enqueueAfterDelay(e,i,s){this.U(),this.N.indexOf(e)>-1&&(i=0);const T=DelayedOperation.createAndSchedule(this,e,i,s,(e=>this.G(e)));return this.S.push(T),T}U(){this.q&&z(47125,{H:__PRIVATE_getMessageOrStack(this.q)})}verifyOperationInProgress(){}async J(){let e;do{e=this.W,await e}while(e!==this.W)}K(e){for(const i of this.S)if(i.timerId===e)return!0;return!1}X(e){return this.J().then((()=>{this.S.sort(((e,i)=>e.targetTimeMs-i.targetTimeMs));for(const i of this.S)if(i.skipDelay(),"all"!==e&&i.timerId===e)break;return this.J()}))}Y(e){this.N.push(e)}G(e){const i=this.S.indexOf(e);this.S.splice(i,1)}}function __PRIVATE_getMessageOrStack(e){let i=e.message||"";return e.stack&&(i=e.stack.includes(e.message)?e.stack:e.message+"\n"+e.stack),i}class Transaction{constructor(e,i){this._firestore=e,this._transaction=i,this._dataReader=p(e)}get(e){const i=__PRIVATE_validateReference(e,this._firestore),s=new A(this._firestore);return this._transaction.lookup([i._key]).then((e=>{if(!e||1!==e.length)return z(24041);const T=e[0];if(T.isFoundDocument())return new it(this._firestore,s,T.key,T,i.converter);if(T.isNoDocument())return new it(this._firestore,s,i._key,null,i.converter);throw z(18433,{doc:T})}))}set(e,i,s){const T=__PRIVATE_validateReference(e,this._firestore),E=w(T.converter,i,s),V=y(this._dataReader,"Transaction.set",T._key,E,null!==T.converter,s);return this._transaction.set(T._key,V),this}update(e,i,s,...T){const E=__PRIVATE_validateReference(e,this._firestore);let V;return V="string"==typeof(i=getModularInstance(i))||i instanceof D?b(this._dataReader,"Transaction.update",E._key,i,s,T):v(this._dataReader,"Transaction.update",E._key,i),this._transaction.update(E._key,V),this}delete(e){const i=__PRIVATE_validateReference(e,this._firestore);return this._transaction.delete(i._key),this}}function runTransaction(e,i,s){const T=d(e=f(e,n)),E={...Qe,...s};!function __PRIVATE_validateTransactionOptions(e){if(e.maxAttempts<1)throw new k(te,"Max attempts must be at least 1")}(E);const V=new __PRIVATE_Deferred;return new __PRIVATE_TransactionRunner(function __PRIVATE_newAsyncQueue(){return new __PRIVATE_AsyncQueueImpl}(),T,E,(s=>i(new Transaction(e,s))),V).V(),V.promise}!function __PRIVATE_registerFirestore(){(function c(e){K=e})(`${V}_lite`),T(new Component("firestore/lite",((e,{instanceIdentifier:i,options:s})=>{const T=e.getProvider("app").getImmediate(),E=new n(new r(e.getProvider("auth-internal")),new o(T,e.getProvider("app-check-internal")),function h(e,i){if(!Object.prototype.hasOwnProperty.apply(e.options,["projectId"]))throw new k(te,'"projectId" not provided in firebase.initializeApp.');return new DatabaseId(e.options.projectId,i)}(T,i),T);return s&&E._setSettings(s),E}),"PUBLIC").setMultipleInstances(!0)),E("firestore-lite",je,""),E("firestore-lite",je,"esm2020")}();export{AggregateField,AggregateQuerySnapshot,Bytes,CollectionReference,DocumentReference,it as DocumentSnapshot,D as FieldPath,FieldValue,n as Firestore,k as FirestoreError,GeoPoint,Query,QueryCompositeFilterConstraint,QueryConstraint,QueryDocumentSnapshot,QueryEndAtConstraint,QueryFieldFilterConstraint,QueryLimitConstraint,QueryOrderByConstraint,QuerySnapshot,QueryStartAtConstraint,Timestamp,Transaction,VectorValue,WriteBatch,addDoc,aggregateFieldEqual,aggregateQuerySnapshotEqual,and,arrayRemove,arrayUnion,average,collection,collectionGroup,connectFirestoreEmulator,count,deleteDoc,deleteField,doc,documentId,endAt,endBefore,getAggregate,getCount,getDoc,getDocs,getFirestore,increment,initializeFirestore,limit,limitToLast,maximum,minimum,or,orderBy,query,l as queryEqual,refEqual,runTransaction,serverTimestamp,setDoc,setLogLevel,snapshotEqual,startAfter,startAt,sum,terminate,updateDoc,vector,where,writeBatch};
//# sourceMappingURL=firebase-firestore-lite.js.map