mortgage-calculator-package 2.3.2 → 2.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,3 +1,3 @@
1
1
  /*! For license information please see index.js.LICENSE.txt */
2
- !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define("MortgageCalculator",[],t):"object"==typeof exports?exports.MortgageCalculator=t():e.MortgageCalculator=t()}(self,(()=>(()=>{var e={199:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(319),i=n(844),s=n(336),o=n(148);class a{constructor(e){this.container=e}getPlatformInfoString(){return this.container.getProviders().map((e=>{if(function(e){const t=e.getComponent();return"VERSION"===(null==t?void 0:t.type)}(e)){const t=e.getImmediate();return`${t.library}/${t.version}`}return null})).filter((e=>e)).join(" ")}}const c="@firebase/app",u="0.10.17",l=new i.Logger("@firebase/app"),h="@firebase/app-compat",d="@firebase/analytics-compat",f="@firebase/analytics",g="@firebase/app-check-compat",p="@firebase/app-check",m="@firebase/auth",y="@firebase/auth-compat",v="@firebase/database",w="@firebase/data-connect",b="@firebase/database-compat",_="@firebase/functions",I="@firebase/functions-compat",E="@firebase/installations",T="@firebase/installations-compat",S="@firebase/messaging",x="@firebase/messaging-compat",C="@firebase/performance",D="@firebase/performance-compat",A="@firebase/remote-config",k="@firebase/remote-config-compat",N="@firebase/storage",L="@firebase/storage-compat",O="@firebase/firestore",M="@firebase/vertexai",R="@firebase/firestore-compat",P="firebase",F="[DEFAULT]",V={[c]:"fire-core",[h]:"fire-core-compat",[f]:"fire-analytics",[d]:"fire-analytics-compat",[p]:"fire-app-check",[g]:"fire-app-check-compat",[m]:"fire-auth",[y]:"fire-auth-compat",[v]:"fire-rtdb",[w]:"fire-data-connect",[b]:"fire-rtdb-compat",[_]:"fire-fn",[I]:"fire-fn-compat",[E]:"fire-iid",[T]:"fire-iid-compat",[S]:"fire-fcm",[x]:"fire-fcm-compat",[C]:"fire-perf",[D]:"fire-perf-compat",[A]:"fire-rc",[k]:"fire-rc-compat",[N]:"fire-gcs",[L]:"fire-gcs-compat",[O]:"fire-fst",[R]:"fire-fst-compat",[M]:"fire-vertex","fire-js":"fire-js",[P]:"fire-js-all"},q=new Map,B=new Map,U=new Map;function j(e,t){try{e.container.addComponent(t)}catch(n){l.debug(`Component ${t.name} failed to register with FirebaseApp ${e.name}`,n)}}function $(e){const t=e.name;if(U.has(t))return l.debug(`There were multiple attempts to register component ${t}.`),!1;U.set(t,e);for(const t of q.values())j(t,e);for(const t of B.values())j(t,e);return!0}function z(e,t){const n=e.container.getProvider("heartbeat").getImmediate({optional:!0});return n&&n.triggerHeartbeat(),e.container.getProvider(t)}function G(e){return void 0!==e.options}const K=new s.ErrorFactory("app","Firebase",{"no-app":"No Firebase App '{$appName}' has been created - call initializeApp() first","bad-app-name":"Illegal App name: '{$appName}'","duplicate-app":"Firebase App named '{$appName}' already exists with different options or config","app-deleted":"Firebase App named '{$appName}' already deleted","server-app-deleted":"Firebase Server App has been deleted","no-options":"Need to provide options, when not being deployed to hosting via source.","invalid-app-argument":"firebase.{$appName}() takes either no argument or a Firebase App instance.","invalid-log-argument":"First argument to `onLog` must be null or a function.","idb-open":"Error thrown when opening IndexedDB. Original error: {$originalErrorMessage}.","idb-get":"Error thrown when reading from IndexedDB. Original error: {$originalErrorMessage}.","idb-set":"Error thrown when writing to IndexedDB. Original error: {$originalErrorMessage}.","idb-delete":"Error thrown when deleting from IndexedDB. Original error: {$originalErrorMessage}.","finalization-registry-not-supported":"FirebaseServerApp deleteOnDeref field defined but the JS runtime does not support FinalizationRegistry.","invalid-server-app-environment":"FirebaseServerApp is not for use in browser environments."});class Q{constructor(e,t,n){this._isDeleted=!1,this._options=Object.assign({},e),this._config=Object.assign({},t),this._name=t.name,this._automaticDataCollectionEnabled=t.automaticDataCollectionEnabled,this._container=n,this.container.addComponent(new r.Component("app",(()=>this),"PUBLIC"))}get automaticDataCollectionEnabled(){return this.checkDestroyed(),this._automaticDataCollectionEnabled}set automaticDataCollectionEnabled(e){this.checkDestroyed(),this._automaticDataCollectionEnabled=e}get name(){return this.checkDestroyed(),this._name}get options(){return this.checkDestroyed(),this._options}get config(){return this.checkDestroyed(),this._config}get container(){return this._container}get isDeleted(){return this._isDeleted}set isDeleted(e){this._isDeleted=e}checkDestroyed(){if(this.isDeleted)throw K.create("app-deleted",{appName:this._name})}}class H extends Q{constructor(e,t,n,r){const i=void 0!==t.automaticDataCollectionEnabled&&t.automaticDataCollectionEnabled,s={name:n,automaticDataCollectionEnabled:i};void 0!==e.apiKey?super(e,s,r):super(e.options,s,r),this._serverConfig=Object.assign({automaticDataCollectionEnabled:i},t),this._finalizationRegistry=null,"undefined"!=typeof FinalizationRegistry&&(this._finalizationRegistry=new FinalizationRegistry((()=>{this.automaticCleanup()}))),this._refCount=0,this.incRefCount(this._serverConfig.releaseOnDeref),this._serverConfig.releaseOnDeref=void 0,t.releaseOnDeref=void 0,X(c,u,"serverapp")}toJSON(){}get refCount(){return this._refCount}incRefCount(e){this.isDeleted||(this._refCount++,void 0!==e&&null!==this._finalizationRegistry&&this._finalizationRegistry.register(e,this))}decRefCount(){return this.isDeleted?0:--this._refCount}automaticCleanup(){J(this)}get settings(){return this.checkDestroyed(),this._serverConfig}checkDestroyed(){if(this.isDeleted)throw K.create("server-app-deleted")}}function W(e,t={}){let n=e;"object"!=typeof t&&(t={name:t});const i=Object.assign({name:F,automaticDataCollectionEnabled:!1},t),o=i.name;if("string"!=typeof o||!o)throw K.create("bad-app-name",{appName:String(o)});if(n||(n=s.getDefaultAppConfig()),!n)throw K.create("no-options");const a=q.get(o);if(a){if(s.deepEqual(n,a.options)&&s.deepEqual(i,a.config))return a;throw K.create("duplicate-app",{appName:o})}const c=new r.ComponentContainer(o);for(const e of U.values())c.addComponent(e);const u=new Q(n,i,c);return q.set(o,u),u}async function J(e){let t=!1;const n=e.name;q.has(n)?(t=!0,q.delete(n)):B.has(n)&&e.decRefCount()<=0&&(B.delete(n),t=!0),t&&(await Promise.all(e.container.getProviders().map((e=>e.delete()))),e.isDeleted=!0)}function X(e,t,n){var i;let s=null!==(i=V[e])&&void 0!==i?i:e;n&&(s+=`-${n}`);const o=s.match(/\s|\//),a=t.match(/\s|\//);if(o||a){const e=[`Unable to register library "${s}" with version "${t}":`];return o&&e.push(`library name "${s}" contains illegal characters (whitespace or "/")`),o&&a&&e.push("and"),a&&e.push(`version name "${t}" contains illegal characters (whitespace or "/")`),void l.warn(e.join(" "))}$(new r.Component(`${s}-version`,(()=>({library:s,version:t})),"VERSION"))}const Y="firebase-heartbeat-store";let Z=null;function ee(){return Z||(Z=o.openDB("firebase-heartbeat-database",1,{upgrade:(e,t)=>{if(0===t)try{e.createObjectStore(Y)}catch(e){console.warn(e)}}}).catch((e=>{throw K.create("idb-open",{originalErrorMessage:e.message})}))),Z}async function te(e,t){try{const n=(await ee()).transaction(Y,"readwrite"),r=n.objectStore(Y);await r.put(t,ne(e)),await n.done}catch(e){if(e instanceof s.FirebaseError)l.warn(e.message);else{const t=K.create("idb-set",{originalErrorMessage:null==e?void 0:e.message});l.warn(t.message)}}}function ne(e){return`${e.name}!${e.options.appId}`}class re{constructor(e){this.container=e,this._heartbeatsCache=null;const t=this.container.getProvider("app").getImmediate();this._storage=new se(t),this._heartbeatsCachePromise=this._storage.read().then((e=>(this._heartbeatsCache=e,e)))}async triggerHeartbeat(){var e,t;try{const n=this.container.getProvider("platform-logger").getImmediate().getPlatformInfoString(),r=ie();if(null==(null===(e=this._heartbeatsCache)||void 0===e?void 0:e.heartbeats)&&(this._heartbeatsCache=await this._heartbeatsCachePromise,null==(null===(t=this._heartbeatsCache)||void 0===t?void 0:t.heartbeats)))return;if(this._heartbeatsCache.lastSentHeartbeatDate===r||this._heartbeatsCache.heartbeats.some((e=>e.date===r)))return;return this._heartbeatsCache.heartbeats.push({date:r,agent:n}),this._heartbeatsCache.heartbeats=this._heartbeatsCache.heartbeats.filter((e=>{const t=new Date(e.date).valueOf();return Date.now()-t<=2592e6})),this._storage.overwrite(this._heartbeatsCache)}catch(e){l.warn(e)}}async getHeartbeatsHeader(){var e;try{if(null===this._heartbeatsCache&&await this._heartbeatsCachePromise,null==(null===(e=this._heartbeatsCache)||void 0===e?void 0:e.heartbeats)||0===this._heartbeatsCache.heartbeats.length)return"";const t=ie(),{heartbeatsToSend:n,unsentEntries:r}=function(e,t=1024){const n=[];let r=e.slice();for(const i of e){const e=n.find((e=>e.agent===i.agent));if(e){if(e.dates.push(i.date),oe(n)>t){e.dates.pop();break}}else if(n.push({agent:i.agent,dates:[i.date]}),oe(n)>t){n.pop();break}r=r.slice(1)}return{heartbeatsToSend:n,unsentEntries:r}}(this._heartbeatsCache.heartbeats),i=s.base64urlEncodeWithoutPadding(JSON.stringify({version:2,heartbeats:n}));return this._heartbeatsCache.lastSentHeartbeatDate=t,r.length>0?(this._heartbeatsCache.heartbeats=r,await this._storage.overwrite(this._heartbeatsCache)):(this._heartbeatsCache.heartbeats=[],this._storage.overwrite(this._heartbeatsCache)),i}catch(e){return l.warn(e),""}}}function ie(){return(new Date).toISOString().substring(0,10)}class se{constructor(e){this.app=e,this._canUseIndexedDBPromise=this.runIndexedDBEnvironmentCheck()}async runIndexedDBEnvironmentCheck(){return!!s.isIndexedDBAvailable()&&s.validateIndexedDBOpenable().then((()=>!0)).catch((()=>!1))}async read(){if(await this._canUseIndexedDBPromise){const e=await async function(e){try{const t=(await ee()).transaction(Y),n=await t.objectStore(Y).get(ne(e));return await t.done,n}catch(e){if(e instanceof s.FirebaseError)l.warn(e.message);else{const t=K.create("idb-get",{originalErrorMessage:null==e?void 0:e.message});l.warn(t.message)}}}(this.app);return(null==e?void 0:e.heartbeats)?e:{heartbeats:[]}}return{heartbeats:[]}}async overwrite(e){var t;if(await this._canUseIndexedDBPromise){const n=await this.read();return te(this.app,{lastSentHeartbeatDate:null!==(t=e.lastSentHeartbeatDate)&&void 0!==t?t:n.lastSentHeartbeatDate,heartbeats:e.heartbeats})}}async add(e){var t;if(await this._canUseIndexedDBPromise){const n=await this.read();return te(this.app,{lastSentHeartbeatDate:null!==(t=e.lastSentHeartbeatDate)&&void 0!==t?t:n.lastSentHeartbeatDate,heartbeats:[...n.heartbeats,...e.heartbeats]})}}}function oe(e){return s.base64urlEncodeWithoutPadding(JSON.stringify({version:2,heartbeats:e})).length}$(new r.Component("platform-logger",(e=>new a(e)),"PRIVATE")),$(new r.Component("heartbeat",(e=>new re(e)),"PRIVATE")),X(c,u,"node"),X(c,u,"cjs2017"),X("fire-js",""),Object.defineProperty(t,"FirebaseError",{enumerable:!0,get:function(){return s.FirebaseError}}),t.SDK_VERSION="11.1.0",t._DEFAULT_ENTRY_NAME=F,t._addComponent=j,t._addOrOverwriteComponent=function(e,t){e.container.addOrOverwriteComponent(t)},t._apps=q,t._clearComponents=function(){U.clear()},t._components=U,t._getProvider=z,t._isFirebaseApp=G,t._isFirebaseServerApp=function(e){return void 0!==e.settings},t._registerComponent=$,t._removeServiceInstance=function(e,t,n=F){z(e,t).clearInstance(n)},t._serverApps=B,t.deleteApp=J,t.getApp=function(e=F){const t=q.get(e);if(!t&&e===F&&s.getDefaultAppConfig())return W();if(!t)throw K.create("no-app",{appName:e});return t},t.getApps=function(){return Array.from(q.values())},t.initializeApp=W,t.initializeServerApp=function(e,t){if(s.isBrowser()&&!s.isWebWorker())throw K.create("invalid-server-app-environment");let n;void 0===t.automaticDataCollectionEnabled&&(t.automaticDataCollectionEnabled=!1),n=G(e)?e.options:e;const i=Object.assign(Object.assign({},t),n);if(void 0!==i.releaseOnDeref&&delete i.releaseOnDeref,void 0!==t.releaseOnDeref&&"undefined"==typeof FinalizationRegistry)throw K.create("finalization-registry-not-supported",{});const o=""+(a=JSON.stringify(i),[...a].reduce(((e,t)=>Math.imul(31,e)+t.charCodeAt(0)|0),0));var a;const c=B.get(o);if(c)return c.incRefCount(t.releaseOnDeref),c;const u=new r.ComponentContainer(o);for(const e of U.values())u.addComponent(e);const l=new H(n,t,o,u);return B.set(o,l),l},t.onLog=function(e,t){if(null!==e&&"function"!=typeof e)throw K.create("invalid-log-argument");i.setUserLogHandler(e,t)},t.registerVersion=X,t.setLogLevel=function(e){i.setLogLevel(e)}},319:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(336);const i="[DEFAULT]";class s{constructor(e,t){this.name=e,this.container=t,this.component=null,this.instances=new Map,this.instancesDeferred=new Map,this.instancesOptions=new Map,this.onInitCallbacks=new Map}get(e){const t=this.normalizeInstanceIdentifier(e);if(!this.instancesDeferred.has(t)){const e=new r.Deferred;if(this.instancesDeferred.set(t,e),this.isInitialized(t)||this.shouldAutoInitialize())try{const n=this.getOrInitializeService({instanceIdentifier:t});n&&e.resolve(n)}catch(e){}}return this.instancesDeferred.get(t).promise}getImmediate(e){var t;const n=this.normalizeInstanceIdentifier(null==e?void 0:e.identifier),r=null!==(t=null==e?void 0:e.optional)&&void 0!==t&&t;if(!this.isInitialized(n)&&!this.shouldAutoInitialize()){if(r)return null;throw Error(`Service ${this.name} is not available`)}try{return this.getOrInitializeService({instanceIdentifier:n})}catch(e){if(r)return null;throw e}}getComponent(){return this.component}setComponent(e){if(e.name!==this.name)throw Error(`Mismatching Component ${e.name} for Provider ${this.name}.`);if(this.component)throw Error(`Component for ${this.name} has already been provided`);if(this.component=e,this.shouldAutoInitialize()){if(function(e){return"EAGER"===e.instantiationMode}(e))try{this.getOrInitializeService({instanceIdentifier:i})}catch(e){}for(const[e,t]of this.instancesDeferred.entries()){const n=this.normalizeInstanceIdentifier(e);try{const e=this.getOrInitializeService({instanceIdentifier:n});t.resolve(e)}catch(e){}}}}clearInstance(e=i){this.instancesDeferred.delete(e),this.instancesOptions.delete(e),this.instances.delete(e)}async delete(){const e=Array.from(this.instances.values());await Promise.all([...e.filter((e=>"INTERNAL"in e)).map((e=>e.INTERNAL.delete())),...e.filter((e=>"_delete"in e)).map((e=>e._delete()))])}isComponentSet(){return null!=this.component}isInitialized(e=i){return this.instances.has(e)}getOptions(e=i){return this.instancesOptions.get(e)||{}}initialize(e={}){const{options:t={}}=e,n=this.normalizeInstanceIdentifier(e.instanceIdentifier);if(this.isInitialized(n))throw Error(`${this.name}(${n}) has already been initialized`);if(!this.isComponentSet())throw Error(`Component ${this.name} has not been registered yet`);const r=this.getOrInitializeService({instanceIdentifier:n,options:t});for(const[e,t]of this.instancesDeferred.entries())n===this.normalizeInstanceIdentifier(e)&&t.resolve(r);return r}onInit(e,t){var n;const r=this.normalizeInstanceIdentifier(t),i=null!==(n=this.onInitCallbacks.get(r))&&void 0!==n?n:new Set;i.add(e),this.onInitCallbacks.set(r,i);const s=this.instances.get(r);return s&&e(s,r),()=>{i.delete(e)}}invokeOnInitCallbacks(e,t){const n=this.onInitCallbacks.get(t);if(n)for(const r of n)try{r(e,t)}catch(e){}}getOrInitializeService({instanceIdentifier:e,options:t={}}){let n=this.instances.get(e);if(!n&&this.component&&(n=this.component.instanceFactory(this.container,{instanceIdentifier:(r=e,r===i?void 0:r),options:t}),this.instances.set(e,n),this.instancesOptions.set(e,t),this.invokeOnInitCallbacks(n,e),this.component.onInstanceCreated))try{this.component.onInstanceCreated(this.container,e,n)}catch(e){}var r;return n||null}normalizeInstanceIdentifier(e=i){return this.component?this.component.multipleInstances?e:i:e}shouldAutoInitialize(){return!!this.component&&"EXPLICIT"!==this.component.instantiationMode}}t.Component=class{constructor(e,t,n){this.name=e,this.instanceFactory=t,this.type=n,this.multipleInstances=!1,this.serviceProps={},this.instantiationMode="LAZY",this.onInstanceCreated=null}setInstantiationMode(e){return this.instantiationMode=e,this}setMultipleInstances(e){return this.multipleInstances=e,this}setServiceProps(e){return this.serviceProps=e,this}setInstanceCreatedCallback(e){return this.onInstanceCreated=e,this}},t.ComponentContainer=class{constructor(e){this.name=e,this.providers=new Map}addComponent(e){const t=this.getProvider(e.name);if(t.isComponentSet())throw new Error(`Component ${e.name} has already been registered with ${this.name}`);t.setComponent(e)}addOrOverwriteComponent(e){this.getProvider(e.name).isComponentSet()&&this.providers.delete(e.name),this.addComponent(e)}getProvider(e){if(this.providers.has(e))return this.providers.get(e);const t=new s(e,this);return this.providers.set(e,t),t}getProviders(){return Array.from(this.providers.values())}},t.Provider=s},241:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(199),i=n(319),s=n(844),o=n(336),a=n(860),c=n(832);const u="@firebase/firestore";class l{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}}l.UNAUTHENTICATED=new l(null),l.GOOGLE_CREDENTIALS=new l("google-credentials-uid"),l.FIRST_PARTY=new l("first-party-uid"),l.MOCK_USER=new l("mock-user");let h="11.0.2";const d=new s.Logger("@firebase/firestore");function f(){return d.logLevel}function g(e,...t){if(d.logLevel<=s.LogLevel.DEBUG){const n=t.map(y);d.debug(`Firestore (${h}): ${e}`,...n)}}function p(e,...t){if(d.logLevel<=s.LogLevel.ERROR){const n=t.map(y);d.error(`Firestore (${h}): ${e}`,...n)}}function m(e,...t){if(d.logLevel<=s.LogLevel.WARN){const n=t.map(y);d.warn(`Firestore (${h}): ${e}`,...n)}}function y(e){if("string"==typeof e)return e;try{return function(e){return JSON.stringify(e)}(e)}catch(t){return e}}function v(e="Unexpected state"){const t=`FIRESTORE (${h}) INTERNAL ASSERTION FAILED: `+e;throw p(t),new Error(t)}function w(e,t){e||v()}function b(e,t){return e}const _={OK:"ok",CANCELLED:"cancelled",UNKNOWN:"unknown",INVALID_ARGUMENT:"invalid-argument",DEADLINE_EXCEEDED:"deadline-exceeded",NOT_FOUND:"not-found",ALREADY_EXISTS:"already-exists",PERMISSION_DENIED:"permission-denied",UNAUTHENTICATED:"unauthenticated",RESOURCE_EXHAUSTED:"resource-exhausted",FAILED_PRECONDITION:"failed-precondition",ABORTED:"aborted",OUT_OF_RANGE:"out-of-range",UNIMPLEMENTED:"unimplemented",INTERNAL:"internal",UNAVAILABLE:"unavailable",DATA_LOSS:"data-loss"};class I extends o.FirebaseError{constructor(e,t){super(e,t),this.code=e,this.message=t,this.toString=()=>`${this.name}: [code=${this.code}]: ${this.message}`}}class E{constructor(){this.promise=new Promise(((e,t)=>{this.resolve=e,this.reject=t}))}}class T{constructor(e,t){this.user=t,this.type="OAuth",this.headers=new Map,this.headers.set("Authorization",`Bearer ${e}`)}}class S{getToken(){return Promise.resolve(null)}invalidateToken(){}start(e,t){e.enqueueRetryable((()=>t(l.UNAUTHENTICATED)))}shutdown(){}}class x{constructor(e){this.token=e,this.changeListener=null}getToken(){return Promise.resolve(this.token)}invalidateToken(){}start(e,t){this.changeListener=t,e.enqueueRetryable((()=>t(this.token.user)))}shutdown(){this.changeListener=null}}class C{constructor(e){this.t=e,this.currentUser=l.UNAUTHENTICATED,this.i=0,this.forceRefresh=!1,this.auth=null}start(e,t){w(void 0===this.o);let n=this.i;const r=e=>this.i!==n?(n=this.i,t(e)):Promise.resolve();let i=new E;this.o=()=>{this.i++,this.currentUser=this.u(),i.resolve(),i=new E,e.enqueueRetryable((()=>r(this.currentUser)))};const s=()=>{const t=i;e.enqueueRetryable((async()=>{await t.promise,await r(this.currentUser)}))},o=e=>{g("FirebaseAuthCredentialsProvider","Auth detected"),this.auth=e,this.o&&(this.auth.addAuthTokenListener(this.o),s())};this.t.onInit((e=>o(e))),setTimeout((()=>{if(!this.auth){const e=this.t.getImmediate({optional:!0});e?o(e):(g("FirebaseAuthCredentialsProvider","Auth not yet detected"),i.resolve(),i=new E)}}),0),s()}getToken(){const e=this.i,t=this.forceRefresh;return this.forceRefresh=!1,this.auth?this.auth.getToken(t).then((t=>this.i!==e?(g("FirebaseAuthCredentialsProvider","getToken aborted due to token change."),this.getToken()):t?(w("string"==typeof t.accessToken),new T(t.accessToken,this.currentUser)):null)):Promise.resolve(null)}invalidateToken(){this.forceRefresh=!0}shutdown(){this.auth&&this.o&&this.auth.removeAuthTokenListener(this.o),this.o=void 0}u(){const e=this.auth&&this.auth.getUid();return w(null===e||"string"==typeof e),new l(e)}}class D{constructor(e,t,n){this.l=e,this.h=t,this.P=n,this.type="FirstParty",this.user=l.FIRST_PARTY,this.T=new Map}I(){return this.P?this.P():null}get headers(){this.T.set("X-Goog-AuthUser",this.l);const e=this.I();return e&&this.T.set("Authorization",e),this.h&&this.T.set("X-Goog-Iam-Authorization-Token",this.h),this.T}}class A{constructor(e,t,n){this.l=e,this.h=t,this.P=n}getToken(){return Promise.resolve(new D(this.l,this.h,this.P))}start(e,t){e.enqueueRetryable((()=>t(l.FIRST_PARTY)))}shutdown(){}invalidateToken(){}}class k{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 N{constructor(e){this.A=e,this.forceRefresh=!1,this.appCheck=null,this.R=null}start(e,t){w(void 0===this.o);const n=e=>{null!=e.error&&g("FirebaseAppCheckTokenProvider",`Error getting App Check token; using placeholder token instead. Error: ${e.error.message}`);const n=e.token!==this.R;return this.R=e.token,g("FirebaseAppCheckTokenProvider",`Received ${n?"new":"existing"} token.`),n?t(e.token):Promise.resolve()};this.o=t=>{e.enqueueRetryable((()=>n(t)))};const r=e=>{g("FirebaseAppCheckTokenProvider","AppCheck detected"),this.appCheck=e,this.o&&this.appCheck.addTokenListener(this.o)};this.A.onInit((e=>r(e))),setTimeout((()=>{if(!this.appCheck){const e=this.A.getImmediate({optional:!0});e?r(e):g("FirebaseAppCheckTokenProvider","AppCheck not yet detected")}}),0)}getToken(){const e=this.forceRefresh;return this.forceRefresh=!1,this.appCheck?this.appCheck.getToken(e).then((e=>e?(w("string"==typeof e.token),this.R=e.token,new k(e.token)):null)):Promise.resolve(null)}invalidateToken(){this.forceRefresh=!0}shutdown(){this.appCheck&&this.o&&this.appCheck.removeTokenListener(this.o),this.o=void 0}}function L(e){const t="undefined"!=typeof self&&(self.crypto||self.msCrypto),n=new Uint8Array(e);if(t&&"function"==typeof t.getRandomValues)t.getRandomValues(n);else for(let t=0;t<e;t++)n[t]=Math.floor(256*Math.random());return n}class O{static newId(){const e=62*Math.floor(256/62);let t="";for(;t.length<20;){const n=L(40);for(let r=0;r<n.length;++r)t.length<20&&n[r]<e&&(t+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".charAt(n[r]%62))}return t}}function M(e,t){return e<t?-1:e>t?1:0}function R(e,t,n){return e.length===t.length&&e.every(((e,r)=>n(e,t[r])))}function P(e){return e+"\0"}class F{static now(){return F.fromMillis(Date.now())}static fromDate(e){return F.fromMillis(e.getTime())}static fromMillis(e){const t=Math.floor(e/1e3),n=Math.floor(1e6*(e-1e3*t));return new F(t,n)}constructor(e,t){if(this.seconds=e,this.nanoseconds=t,t<0)throw new I(_.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+t);if(t>=1e9)throw new I(_.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+t);if(e<-62135596800)throw new I(_.INVALID_ARGUMENT,"Timestamp seconds out of range: "+e);if(e>=253402300800)throw new I(_.INVALID_ARGUMENT,"Timestamp seconds out of range: "+e)}toDate(){return new Date(this.toMillis())}toMillis(){return 1e3*this.seconds+this.nanoseconds/1e6}_compareTo(e){return this.seconds===e.seconds?M(this.nanoseconds,e.nanoseconds):M(this.seconds,e.seconds)}isEqual(e){return e.seconds===this.seconds&&e.nanoseconds===this.nanoseconds}toString(){return"Timestamp(seconds="+this.seconds+", nanoseconds="+this.nanoseconds+")"}toJSON(){return{seconds:this.seconds,nanoseconds:this.nanoseconds}}valueOf(){const e=this.seconds- -62135596800;return String(e).padStart(12,"0")+"."+String(this.nanoseconds).padStart(9,"0")}}class V{static fromTimestamp(e){return new V(e)}static min(){return new V(new F(0,0))}static max(){return new V(new F(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 q{constructor(e,t,n){void 0===t?t=0:t>e.length&&v(),void 0===n?n=e.length-t:n>e.length-t&&v(),this.segments=e,this.offset=t,this.len=n}get length(){return this.len}isEqual(e){return 0===q.comparator(this,e)}child(e){const t=this.segments.slice(this.offset,this.limit());return e instanceof q?e.forEach((e=>{t.push(e)})):t.push(e),this.construct(t)}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 t=0;t<this.length;t++)if(this.get(t)!==e.get(t))return!1;return!0}isImmediateParentOf(e){if(this.length+1!==e.length)return!1;for(let t=0;t<this.length;t++)if(this.get(t)!==e.get(t))return!1;return!0}forEach(e){for(let t=this.offset,n=this.limit();t<n;t++)e(this.segments[t])}toArray(){return this.segments.slice(this.offset,this.limit())}static comparator(e,t){const n=Math.min(e.length,t.length);for(let r=0;r<n;r++){const n=e.get(r),i=t.get(r);if(n<i)return-1;if(n>i)return 1}return e.length<t.length?-1:e.length>t.length?1:0}}class B extends q{construct(e,t,n){return new B(e,t,n)}canonicalString(){return this.toArray().join("/")}toString(){return this.canonicalString()}toUriEncodedString(){return this.toArray().map(encodeURIComponent).join("/")}static fromString(...e){const t=[];for(const n of e){if(n.indexOf("//")>=0)throw new I(_.INVALID_ARGUMENT,`Invalid segment (${n}). Paths must not contain // in them.`);t.push(...n.split("/").filter((e=>e.length>0)))}return new B(t)}static emptyPath(){return new B([])}}const U=/^[_a-zA-Z][_a-zA-Z0-9]*$/;class j extends q{construct(e,t,n){return new j(e,t,n)}static isValidIdentifier(e){return U.test(e)}canonicalString(){return this.toArray().map((e=>(e=e.replace(/\\/g,"\\\\").replace(/`/g,"\\`"),j.isValidIdentifier(e)||(e="`"+e+"`"),e))).join(".")}toString(){return this.canonicalString()}isKeyField(){return 1===this.length&&"__name__"===this.get(0)}static keyField(){return new j(["__name__"])}static fromServerFormat(e){const t=[];let n="",r=0;const i=()=>{if(0===n.length)throw new I(_.INVALID_ARGUMENT,`Invalid field path (${e}). Paths must not be empty, begin with '.', end with '.', or contain '..'`);t.push(n),n=""};let s=!1;for(;r<e.length;){const t=e[r];if("\\"===t){if(r+1===e.length)throw new I(_.INVALID_ARGUMENT,"Path has trailing escape character: "+e);const t=e[r+1];if("\\"!==t&&"."!==t&&"`"!==t)throw new I(_.INVALID_ARGUMENT,"Path has invalid escape sequence: "+e);n+=t,r+=2}else"`"===t?(s=!s,r++):"."!==t||s?(n+=t,r++):(i(),r++)}if(i(),s)throw new I(_.INVALID_ARGUMENT,"Unterminated ` in path: "+e);return new j(t)}static emptyPath(){return new j([])}}class ${constructor(e){this.path=e}static fromPath(e){return new $(B.fromString(e))}static fromName(e){return new $(B.fromString(e).popFirst(5))}static empty(){return new $(B.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===B.comparator(this.path,e.path)}toString(){return this.path.toString()}static comparator(e,t){return B.comparator(e.path,t.path)}static isDocumentKey(e){return e.length%2==0}static fromSegments(e){return new $(new B(e.slice()))}}class z{constructor(e,t,n,r){this.indexId=e,this.collectionGroup=t,this.fields=n,this.indexState=r}}function G(e){return e.fields.find((e=>2===e.kind))}function K(e){return e.fields.filter((e=>2!==e.kind))}function Q(e,t){let n=M(e.collectionGroup,t.collectionGroup);if(0!==n)return n;for(let r=0;r<Math.min(e.fields.length,t.fields.length);++r)if(n=W(e.fields[r],t.fields[r]),0!==n)return n;return M(e.fields.length,t.fields.length)}z.UNKNOWN_ID=-1;class H{constructor(e,t){this.fieldPath=e,this.kind=t}}function W(e,t){const n=j.comparator(e.fieldPath,t.fieldPath);return 0!==n?n:M(e.kind,t.kind)}class J{constructor(e,t){this.sequenceNumber=e,this.offset=t}static empty(){return new J(0,Z.min())}}function X(e,t){const n=e.toTimestamp().seconds,r=e.toTimestamp().nanoseconds+1,i=V.fromTimestamp(1e9===r?new F(n+1,0):new F(n,r));return new Z(i,$.empty(),t)}function Y(e){return new Z(e.readTime,e.key,-1)}class Z{constructor(e,t,n){this.readTime=e,this.documentKey=t,this.largestBatchId=n}static min(){return new Z(V.min(),$.empty(),-1)}static max(){return new Z(V.max(),$.empty(),-1)}}function ee(e,t){let n=e.readTime.compareTo(t.readTime);return 0!==n?n:(n=$.comparator(e.documentKey,t.documentKey),0!==n?n:M(e.largestBatchId,t.largestBatchId))}const te="The current tab is not in the required state to perform this operation. It might be necessary to refresh the browser tab.";class ne{constructor(){this.onCommittedListeners=[]}addOnCommittedListener(e){this.onCommittedListeners.push(e)}raiseOnCommittedEvent(){this.onCommittedListeners.forEach((e=>e()))}}async function re(e){if(e.code!==_.FAILED_PRECONDITION||e.message!==te)throw e;g("LocalStore","Unexpectedly lost primary lease")}class ie{constructor(e){this.nextCallback=null,this.catchCallback=null,this.result=void 0,this.error=void 0,this.isDone=!1,this.callbackAttached=!1,e((e=>{this.isDone=!0,this.result=e,this.nextCallback&&this.nextCallback(e)}),(e=>{this.isDone=!0,this.error=e,this.catchCallback&&this.catchCallback(e)}))}catch(e){return this.next(void 0,e)}next(e,t){return this.callbackAttached&&v(),this.callbackAttached=!0,this.isDone?this.error?this.wrapFailure(t,this.error):this.wrapSuccess(e,this.result):new ie(((n,r)=>{this.nextCallback=t=>{this.wrapSuccess(e,t).next(n,r)},this.catchCallback=e=>{this.wrapFailure(t,e).next(n,r)}}))}toPromise(){return new Promise(((e,t)=>{this.next(e,t)}))}wrapUserFunction(e){try{const t=e();return t instanceof ie?t:ie.resolve(t)}catch(e){return ie.reject(e)}}wrapSuccess(e,t){return e?this.wrapUserFunction((()=>e(t))):ie.resolve(t)}wrapFailure(e,t){return e?this.wrapUserFunction((()=>e(t))):ie.reject(t)}static resolve(e){return new ie(((t,n)=>{t(e)}))}static reject(e){return new ie(((t,n)=>{n(e)}))}static waitFor(e){return new ie(((t,n)=>{let r=0,i=0,s=!1;e.forEach((e=>{++r,e.next((()=>{++i,s&&i===r&&t()}),(e=>n(e)))})),s=!0,i===r&&t()}))}static or(e){let t=ie.resolve(!1);for(const n of e)t=t.next((e=>e?ie.resolve(e):n()));return t}static forEach(e,t){const n=[];return e.forEach(((e,r)=>{n.push(t.call(this,e,r))})),this.waitFor(n)}static mapArray(e,t){return new ie(((n,r)=>{const i=e.length,s=new Array(i);let o=0;for(let a=0;a<i;a++){const c=a;t(e[c]).next((e=>{s[c]=e,++o,o===i&&n(s)}),(e=>r(e)))}}))}static doWhile(e,t){return new ie(((n,r)=>{const i=()=>{!0===e()?t().next((()=>{i()}),r):n()};i()}))}}class se{static open(e,t,n,r){try{return new se(t,e.transaction(r,n))}catch(e){throw new ue(t,e)}}constructor(e,t){this.action=e,this.transaction=t,this.aborted=!1,this.V=new E,this.transaction.oncomplete=()=>{this.V.resolve()},this.transaction.onabort=()=>{t.error?this.V.reject(new ue(e,t.error)):this.V.resolve()},this.transaction.onerror=t=>{const n=ge(t.target.error);this.V.reject(new ue(e,n))}}get m(){return this.V.promise}abort(e){e&&this.V.reject(e),this.aborted||(g("SimpleDb","Aborting transaction:",e?e.message:"Client-initiated abort"),this.aborted=!0,this.transaction.abort())}g(){const e=this.transaction;this.aborted||"function"!=typeof e.commit||e.commit()}store(e){const t=this.transaction.objectStore(e);return new he(t)}}class oe{static delete(e){return g("SimpleDb","Removing database:",e),de(window.indexedDB.deleteDatabase(e)).toPromise()}static p(){if(!o.isIndexedDBAvailable())return!1;if(oe.S())return!0;const e=o.getUA(),t=oe.D(e),n=0<t&&t<10,r=ae(e),i=0<r&&r<4.5;return!(e.indexOf("MSIE ")>0||e.indexOf("Trident/")>0||e.indexOf("Edge/")>0||n||i)}static S(){var e;return"undefined"!=typeof process&&"YES"===(null===(e=process.__PRIVATE_env)||void 0===e?void 0:e.v)}static C(e,t){return e.store(t)}static D(e){const t=e.match(/i(?:phone|pad|pod) os ([\d_]+)/i),n=t?t[1].split("_").slice(0,2).join("."):"-1";return Number(n)}constructor(e,t,n){this.name=e,this.version=t,this.F=n,12.2===oe.D(o.getUA())&&p("Firestore persistence suffers from a bug in iOS 12.2 Safari that may cause your app to stop working. See https://stackoverflow.com/q/56496296/110915 for details and a potential workaround.")}async M(e){return this.db||(g("SimpleDb","Opening database:",this.name),this.db=await new Promise(((t,n)=>{const r=indexedDB.open(this.name,this.version);r.onsuccess=e=>{const n=e.target.result;t(n)},r.onblocked=()=>{n(new ue(e,"Cannot upgrade IndexedDB schema while another tab is open. Close all tabs that access Firestore and reload this page to proceed."))},r.onerror=t=>{const r=t.target.error;"VersionError"===r.name?n(new I(_.FAILED_PRECONDITION,"A newer version of the Firestore SDK was previously used and so the persisted data is not compatible with the version of the SDK you are now using. The SDK will operate with persistence disabled. If you need persistence, please re-upgrade to a newer version of the SDK or else clear the persisted IndexedDB data for your app to start fresh.")):"InvalidStateError"===r.name?n(new I(_.FAILED_PRECONDITION,"Unable to open an IndexedDB connection. This could be due to running in a private browsing session on a browser whose private browsing sessions do not support IndexedDB: "+r)):n(new ue(e,r))},r.onupgradeneeded=e=>{g("SimpleDb",'Database "'+this.name+'" requires upgrade from version:',e.oldVersion);const t=e.target.result;this.F.O(t,r.transaction,e.oldVersion,this.version).next((()=>{g("SimpleDb","Database upgrade to version "+this.version+" complete")}))}}))),this.N&&(this.db.onversionchange=e=>this.N(e)),this.db}L(e){this.N=e,this.db&&(this.db.onversionchange=t=>e(t))}async runTransaction(e,t,n,r){const i="readonly"===t;let s=0;for(;;){++s;try{this.db=await this.M(e);const t=se.open(this.db,e,i?"readonly":"readwrite",n),s=r(t).next((e=>(t.g(),e))).catch((e=>(t.abort(e),ie.reject(e)))).toPromise();return s.catch((()=>{})),await t.m,s}catch(e){const t=e,n="FirebaseError"!==t.name&&s<3;if(g("SimpleDb","Transaction failed with error:",t.message,"Retrying:",n),this.close(),!n)return Promise.reject(t)}}}close(){this.db&&this.db.close(),this.db=void 0}}function ae(e){const t=e.match(/Android ([\d.]+)/i),n=t?t[1].split(".").slice(0,2).join("."):"-1";return Number(n)}class ce{constructor(e){this.B=e,this.k=!1,this.q=null}get isDone(){return this.k}get K(){return this.q}set cursor(e){this.B=e}done(){this.k=!0}$(e){this.q=e}delete(){return de(this.B.delete())}}class ue extends I{constructor(e,t){super(_.UNAVAILABLE,`IndexedDB transaction '${e}' failed: ${t}`),this.name="IndexedDbTransactionError"}}function le(e){return"IndexedDbTransactionError"===e.name}class he{constructor(e){this.store=e}put(e,t){let n;return void 0!==t?(g("SimpleDb","PUT",this.store.name,e,t),n=this.store.put(t,e)):(g("SimpleDb","PUT",this.store.name,"<auto-key>",e),n=this.store.put(e)),de(n)}add(e){return g("SimpleDb","ADD",this.store.name,e,e),de(this.store.add(e))}get(e){return de(this.store.get(e)).next((t=>(void 0===t&&(t=null),g("SimpleDb","GET",this.store.name,e,t),t)))}delete(e){return g("SimpleDb","DELETE",this.store.name,e),de(this.store.delete(e))}count(){return g("SimpleDb","COUNT",this.store.name),de(this.store.count())}U(e,t){const n=this.options(e,t),r=n.index?this.store.index(n.index):this.store;if("function"==typeof r.getAll){const e=r.getAll(n.range);return new ie(((t,n)=>{e.onerror=e=>{n(e.target.error)},e.onsuccess=e=>{t(e.target.result)}}))}{const e=this.cursor(n),t=[];return this.W(e,((e,n)=>{t.push(n)})).next((()=>t))}}G(e,t){const n=this.store.getAll(e,null===t?void 0:t);return new ie(((e,t)=>{n.onerror=e=>{t(e.target.error)},n.onsuccess=t=>{e(t.target.result)}}))}j(e,t){g("SimpleDb","DELETE ALL",this.store.name);const n=this.options(e,t);n.H=!1;const r=this.cursor(n);return this.W(r,((e,t,n)=>n.delete()))}J(e,t){let n;t?n=e:(n={},t=e);const r=this.cursor(n);return this.W(r,t)}Y(e){const t=this.cursor({});return new ie(((n,r)=>{t.onerror=e=>{const t=ge(e.target.error);r(t)},t.onsuccess=t=>{const r=t.target.result;r?e(r.primaryKey,r.value).next((e=>{e?r.continue():n()})):n()}}))}W(e,t){const n=[];return new ie(((r,i)=>{e.onerror=e=>{i(e.target.error)},e.onsuccess=e=>{const i=e.target.result;if(!i)return void r();const s=new ce(i),o=t(i.primaryKey,i.value,s);if(o instanceof ie){const e=o.catch((e=>(s.done(),ie.reject(e))));n.push(e)}s.isDone?r():null===s.K?i.continue():i.continue(s.K)}})).next((()=>ie.waitFor(n)))}options(e,t){let n;return void 0!==e&&("string"==typeof e?n=e:t=e),{index:n,range:t}}cursor(e){let t="next";if(e.reverse&&(t="prev"),e.index){const n=this.store.index(e.index);return e.H?n.openKeyCursor(e.range,t):n.openCursor(e.range,t)}return this.store.openCursor(e.range,t)}}function de(e){return new ie(((t,n)=>{e.onsuccess=e=>{const n=e.target.result;t(n)},e.onerror=e=>{const t=ge(e.target.error);n(t)}}))}let fe=!1;function ge(e){const t=oe.D(o.getUA());if(t>=12.2&&t<13){const t="An internal error was encountered in the Indexed Database server";if(e.message.indexOf(t)>=0){const e=new I("internal",`IOS_INDEXEDDB_BUG1: IndexedDb has thrown '${t}'. This is likely due to an unavoidable bug in iOS. See https://stackoverflow.com/q/56496296/110915 for details and a potential workaround.`);return fe||(fe=!0,setTimeout((()=>{throw e}),0)),e}}return e}class pe{constructor(e,t){this.asyncQueue=e,this.Z=t,this.task=null}start(){this.X(15e3)}stop(){this.task&&(this.task.cancel(),this.task=null)}get started(){return null!==this.task}X(e){g("IndexBackfiller",`Scheduled in ${e}ms`),this.task=this.asyncQueue.enqueueAfterDelay("index_backfill",e,(async()=>{this.task=null;try{g("IndexBackfiller",`Documents written: ${await this.Z.ee()}`)}catch(e){le(e)?g("IndexBackfiller","Ignoring IndexedDB error during index backfill: ",e):await re(e)}await this.X(6e4)}))}}class me{constructor(e,t){this.localStore=e,this.persistence=t}async ee(e=50){return this.persistence.runTransaction("Backfill Indexes","readwrite-primary",(t=>this.te(t,e)))}te(e,t){const n=new Set;let r=t,i=!0;return ie.doWhile((()=>!0===i&&r>0),(()=>this.localStore.indexManager.getNextCollectionGroupToUpdate(e).next((t=>{if(null!==t&&!n.has(t))return g("IndexBackfiller",`Processing collection: ${t}`),this.ne(e,t,r).next((e=>{r-=e,n.add(t)}));i=!1})))).next((()=>t-r))}ne(e,t,n){return this.localStore.indexManager.getMinOffsetFromCollectionGroup(e,t).next((r=>this.localStore.localDocuments.getNextDocuments(e,t,r,n).next((n=>{const i=n.changes;return this.localStore.indexManager.updateIndexEntries(e,i).next((()=>this.re(r,n))).next((n=>(g("IndexBackfiller",`Updating offset: ${n}`),this.localStore.indexManager.updateCollectionGroup(e,t,n)))).next((()=>i.size))}))))}re(e,t){let n=e;return t.changes.forEach(((e,t)=>{const r=Y(t);ee(r,n)>0&&(n=r)})),new Z(n.readTime,n.documentKey,Math.max(t.batchId,e.largestBatchId))}}class ye{constructor(e,t){this.previousValue=e,t&&(t.sequenceNumberHandler=e=>this.ie(e),this.se=e=>t.writeSequenceNumber(e))}ie(e){return this.previousValue=Math.max(e,this.previousValue),this.previousValue}next(){const e=++this.previousValue;return this.se&&this.se(e),e}}function ve(e){return null==e}function we(e){return 0===e&&1/e==-1/0}function be(e){return"number"==typeof e&&Number.isInteger(e)&&!we(e)&&e<=Number.MAX_SAFE_INTEGER&&e>=Number.MIN_SAFE_INTEGER}function _e(e){let t="";for(let n=0;n<e.length;n++)t.length>0&&(t=Ee(t)),t=Ie(e.get(n),t);return Ee(t)}function Ie(e,t){let n=t;const r=e.length;for(let t=0;t<r;t++){const r=e.charAt(t);switch(r){case"\0":n+="";break;case"":n+="";break;default:n+=r}}return n}function Ee(e){return e+""}function Te(e){const t=e.length;if(w(t>=2),2===t)return w(""===e.charAt(0)&&""===e.charAt(1)),B.emptyPath();const n=t-2,r=[];let i="";for(let s=0;s<t;){const t=e.indexOf("",s);switch((t<0||t>n)&&v(),e.charAt(t+1)){case"":const n=e.substring(s,t);let o;0===i.length?o=n:(i+=n,o=i,i=""),r.push(o);break;case"":i+=e.substring(s,t),i+="\0";break;case"":i+=e.substring(s,t+1);break;default:v()}s=t+2}return new B(r)}ye.oe=-1;const Se=["userId","batchId"];function xe(e,t){return[e,_e(t)]}function Ce(e,t,n){return[e,_e(t),n]}const De={},Ae=["prefixPath","collectionGroup","readTime","documentId"],ke=["prefixPath","collectionGroup","documentId"],Ne=["collectionGroup","readTime","prefixPath","documentId"],Le=["canonicalId","targetId"],Oe=["targetId","path"],Me=["path","targetId"],Re=["collectionId","parent"],Pe=["indexId","uid"],Fe=["uid","sequenceNumber"],Ve=["indexId","uid","arrayValue","directionalValue","orderedDocumentKey","documentKey"],qe=["indexId","uid","orderedDocumentKey"],Be=["userId","collectionPath","documentId"],Ue=["userId","collectionPath","largestBatchId"],je=["userId","collectionGroup","largestBatchId"],$e=["mutationQueues","mutations","documentMutations","remoteDocuments","targets","owner","targetGlobal","targetDocuments","clientMetadata","remoteDocumentGlobal","collectionParents","bundles","namedQueries"],ze=[...$e,"documentOverlays"],Ge=["mutationQueues","mutations","documentMutations","remoteDocumentsV14","targets","owner","targetGlobal","targetDocuments","clientMetadata","remoteDocumentGlobal","collectionParents","bundles","namedQueries","documentOverlays"],Ke=Ge,Qe=[...Ke,"indexConfiguration","indexState","indexEntries"],He=Qe,We=[...Qe,"globals"];class Je extends ne{constructor(e,t){super(),this._e=e,this.currentSequenceNumber=t}}function Xe(e,t){const n=b(e);return oe.C(n._e,t)}function Ye(e){let t=0;for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&t++;return t}function Ze(e,t){for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&t(n,e[n])}function et(e,t){const n=[];for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&n.push(t(e[r],r,e));return n}function tt(e){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}class nt{constructor(e,t){this.comparator=e,this.root=t||it.EMPTY}insert(e,t){return new nt(this.comparator,this.root.insert(e,t,this.comparator).copy(null,null,it.BLACK,null,null))}remove(e){return new nt(this.comparator,this.root.remove(e,this.comparator).copy(null,null,it.BLACK,null,null))}get(e){let t=this.root;for(;!t.isEmpty();){const n=this.comparator(e,t.key);if(0===n)return t.value;n<0?t=t.left:n>0&&(t=t.right)}return null}indexOf(e){let t=0,n=this.root;for(;!n.isEmpty();){const r=this.comparator(e,n.key);if(0===r)return t+n.left.size;r<0?n=n.left:(t+=n.left.size+1,n=n.right)}return-1}isEmpty(){return this.root.isEmpty()}get size(){return this.root.size}minKey(){return this.root.minKey()}maxKey(){return this.root.maxKey()}inorderTraversal(e){return this.root.inorderTraversal(e)}forEach(e){this.inorderTraversal(((t,n)=>(e(t,n),!1)))}toString(){const e=[];return this.inorderTraversal(((t,n)=>(e.push(`${t}:${n}`),!1))),`{${e.join(", ")}}`}reverseTraversal(e){return this.root.reverseTraversal(e)}getIterator(){return new rt(this.root,null,this.comparator,!1)}getIteratorFrom(e){return new rt(this.root,e,this.comparator,!1)}getReverseIterator(){return new rt(this.root,null,this.comparator,!0)}getReverseIteratorFrom(e){return new rt(this.root,e,this.comparator,!0)}}class rt{constructor(e,t,n,r){this.isReverse=r,this.nodeStack=[];let i=1;for(;!e.isEmpty();)if(i=t?n(e.key,t):1,t&&r&&(i*=-1),i<0)e=this.isReverse?e.left:e.right;else{if(0===i){this.nodeStack.push(e);break}this.nodeStack.push(e),e=this.isReverse?e.right:e.left}}getNext(){let e=this.nodeStack.pop();const t={key:e.key,value:e.value};if(this.isReverse)for(e=e.left;!e.isEmpty();)this.nodeStack.push(e),e=e.right;else for(e=e.right;!e.isEmpty();)this.nodeStack.push(e),e=e.left;return t}hasNext(){return 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 it{constructor(e,t,n,r,i){this.key=e,this.value=t,this.color=null!=n?n:it.RED,this.left=null!=r?r:it.EMPTY,this.right=null!=i?i:it.EMPTY,this.size=this.left.size+1+this.right.size}copy(e,t,n,r,i){return new it(null!=e?e:this.key,null!=t?t:this.value,null!=n?n:this.color,null!=r?r:this.left,null!=i?i:this.right)}isEmpty(){return!1}inorderTraversal(e){return this.left.inorderTraversal(e)||e(this.key,this.value)||this.right.inorderTraversal(e)}reverseTraversal(e){return this.right.reverseTraversal(e)||e(this.key,this.value)||this.left.reverseTraversal(e)}min(){return this.left.isEmpty()?this:this.left.min()}minKey(){return this.min().key}maxKey(){return this.right.isEmpty()?this.key:this.right.maxKey()}insert(e,t,n){let r=this;const i=n(e,r.key);return r=i<0?r.copy(null,null,null,r.left.insert(e,t,n),null):0===i?r.copy(null,t,null,null,null):r.copy(null,null,null,null,r.right.insert(e,t,n)),r.fixUp()}removeMin(){if(this.left.isEmpty())return it.EMPTY;let e=this;return e.left.isRed()||e.left.left.isRed()||(e=e.moveRedLeft()),e=e.copy(null,null,null,e.left.removeMin(),null),e.fixUp()}remove(e,t){let n,r=this;if(t(e,r.key)<0)r.left.isEmpty()||r.left.isRed()||r.left.left.isRed()||(r=r.moveRedLeft()),r=r.copy(null,null,null,r.left.remove(e,t),null);else{if(r.left.isRed()&&(r=r.rotateRight()),r.right.isEmpty()||r.right.isRed()||r.right.left.isRed()||(r=r.moveRedRight()),0===t(e,r.key)){if(r.right.isEmpty())return it.EMPTY;n=r.right.min(),r=r.copy(n.key,n.value,null,null,r.right.removeMin())}r=r.copy(null,null,null,null,r.right.remove(e,t))}return r.fixUp()}isRed(){return this.color}fixUp(){let e=this;return e.right.isRed()&&!e.left.isRed()&&(e=e.rotateLeft()),e.left.isRed()&&e.left.left.isRed()&&(e=e.rotateRight()),e.left.isRed()&&e.right.isRed()&&(e=e.colorFlip()),e}moveRedLeft(){let e=this.colorFlip();return e.right.left.isRed()&&(e=e.copy(null,null,null,null,e.right.rotateRight()),e=e.rotateLeft(),e=e.colorFlip()),e}moveRedRight(){let e=this.colorFlip();return e.left.left.isRed()&&(e=e.rotateRight(),e=e.colorFlip()),e}rotateLeft(){const e=this.copy(null,null,it.RED,null,this.right.left);return this.right.copy(null,null,this.color,e,null)}rotateRight(){const e=this.copy(null,null,it.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),t=this.right.copy(null,null,!this.right.color,null,null);return this.copy(null,null,!this.color,e,t)}checkMaxDepth(){const e=this.check();return Math.pow(2,e)<=this.size+1}check(){if(this.isRed()&&this.left.isRed())throw v();if(this.right.isRed())throw v();const e=this.left.check();if(e!==this.right.check())throw v();return e+(this.isRed()?0:1)}}it.EMPTY=null,it.RED=!0,it.BLACK=!1,it.EMPTY=new class{constructor(){this.size=0}get key(){throw v()}get value(){throw v()}get color(){throw v()}get left(){throw v()}get right(){throw v()}copy(e,t,n,r,i){return this}insert(e,t,n){return new it(e,t)}remove(e,t){return this}isEmpty(){return!0}inorderTraversal(e){return!1}reverseTraversal(e){return!1}minKey(){return null}maxKey(){return null}isRed(){return!1}checkMaxDepth(){return!0}check(){return 0}};class st{constructor(e){this.comparator=e,this.data=new nt(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(((t,n)=>(e(t),!1)))}forEachInRange(e,t){const n=this.data.getIteratorFrom(e[0]);for(;n.hasNext();){const r=n.getNext();if(this.comparator(r.key,e[1])>=0)return;t(r.key)}}forEachWhile(e,t){let n;for(n=void 0!==t?this.data.getIteratorFrom(t):this.data.getIterator();n.hasNext();)if(!e(n.getNext().key))return}firstAfterOrEqual(e){const t=this.data.getIteratorFrom(e);return t.hasNext()?t.getNext().key:null}getIterator(){return new ot(this.data.getIterator())}getIteratorFrom(e){return new ot(this.data.getIteratorFrom(e))}add(e){return this.copy(this.data.remove(e).insert(e,!0))}delete(e){return this.has(e)?this.copy(this.data.remove(e)):this}isEmpty(){return this.data.isEmpty()}unionWith(e){let t=this;return t.size<e.size&&(t=e,e=this),e.forEach((e=>{t=t.add(e)})),t}isEqual(e){if(!(e instanceof st))return!1;if(this.size!==e.size)return!1;const t=this.data.getIterator(),n=e.data.getIterator();for(;t.hasNext();){const e=t.getNext().key,r=n.getNext().key;if(0!==this.comparator(e,r))return!1}return!0}toArray(){const e=[];return this.forEach((t=>{e.push(t)})),e}toString(){const e=[];return this.forEach((t=>e.push(t))),"SortedSet("+e.toString()+")"}copy(e){const t=new st(this.comparator);return t.data=e,t}}class ot{constructor(e){this.iter=e}getNext(){return this.iter.getNext().key}hasNext(){return this.iter.hasNext()}}function at(e){return e.hasNext()?e.getNext():void 0}class ct{constructor(e){this.fields=e,e.sort(j.comparator)}static empty(){return new ct([])}unionWith(e){let t=new st(j.comparator);for(const e of this.fields)t=t.add(e);for(const n of e)t=t.add(n);return new ct(t.toArray())}covers(e){for(const t of this.fields)if(t.isPrefixOf(e))return!0;return!1}isEqual(e){return R(this.fields,e.fields,((e,t)=>e.isEqual(t)))}}class ut extends Error{constructor(){super(...arguments),this.name="Base64DecodeError"}}class lt{constructor(e){this.binaryString=e}static fromBase64String(e){const t=function(e){try{return atob(e)}catch(e){throw"undefined"!=typeof DOMException&&e instanceof DOMException?new ut("Invalid base64 string: "+e):e}}(e);return new lt(t)}static fromUint8Array(e){const t=function(e){let t="";for(let n=0;n<e.length;++n)t+=String.fromCharCode(e[n]);return t}(e);return new lt(t)}[Symbol.iterator](){let e=0;return{next:()=>e<this.binaryString.length?{value:this.binaryString.charCodeAt(e++),done:!1}:{value:void 0,done:!0}}}toBase64(){return e=this.binaryString,btoa(e);var e}toUint8Array(){return function(e){const t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t}(this.binaryString)}approximateByteSize(){return 2*this.binaryString.length}compareTo(e){return M(this.binaryString,e.binaryString)}isEqual(e){return this.binaryString===e.binaryString}}lt.EMPTY_BYTE_STRING=new lt("");const ht=new RegExp(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.(\d+))?Z$/);function dt(e){if(w(!!e),"string"==typeof e){let t=0;const n=ht.exec(e);if(w(!!n),n[1]){let e=n[1];e=(e+"000000000").substr(0,9),t=Number(e)}const r=new Date(e);return{seconds:Math.floor(r.getTime()/1e3),nanos:t}}return{seconds:ft(e.seconds),nanos:ft(e.nanos)}}function ft(e){return"number"==typeof e?e:"string"==typeof e?Number(e):0}function gt(e){return"string"==typeof e?lt.fromBase64String(e):lt.fromUint8Array(e)}function pt(e){var t,n;return"server_timestamp"===(null===(n=((null===(t=null==e?void 0:e.mapValue)||void 0===t?void 0:t.fields)||{}).__type__)||void 0===n?void 0:n.stringValue)}function mt(e){const t=e.mapValue.fields.__previous_value__;return pt(t)?mt(t):t}function yt(e){const t=dt(e.mapValue.fields.__local_write_time__.timestampValue);return new F(t.seconds,t.nanos)}class vt{constructor(e,t,n,r,i,s,o,a,c){this.databaseId=e,this.appId=t,this.persistenceKey=n,this.host=r,this.ssl=i,this.forceLongPolling=s,this.autoDetectLongPolling=o,this.longPollingOptions=a,this.useFetchStreams=c}}class wt{constructor(e,t){this.projectId=e,this.database=t||"(default)"}static empty(){return new wt("","")}get isDefaultDatabase(){return"(default)"===this.database}isEqual(e){return e instanceof wt&&e.projectId===this.projectId&&e.database===this.database}}const bt={mapValue:{fields:{__type__:{stringValue:"__max__"}}}},_t={nullValue:"NULL_VALUE"};function It(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?pt(e)?4:qt(e)?9007199254740991:Ft(e)?10:11:v()}function Et(e,t){if(e===t)return!0;const n=It(e);if(n!==It(t))return!1;switch(n){case 0:case 9007199254740991:return!0;case 1:return e.booleanValue===t.booleanValue;case 4:return yt(e).isEqual(yt(t));case 3:return function(e,t){if("string"==typeof e.timestampValue&&"string"==typeof t.timestampValue&&e.timestampValue.length===t.timestampValue.length)return e.timestampValue===t.timestampValue;const n=dt(e.timestampValue),r=dt(t.timestampValue);return n.seconds===r.seconds&&n.nanos===r.nanos}(e,t);case 5:return e.stringValue===t.stringValue;case 6:return function(e,t){return gt(e.bytesValue).isEqual(gt(t.bytesValue))}(e,t);case 7:return e.referenceValue===t.referenceValue;case 8:return function(e,t){return ft(e.geoPointValue.latitude)===ft(t.geoPointValue.latitude)&&ft(e.geoPointValue.longitude)===ft(t.geoPointValue.longitude)}(e,t);case 2:return function(e,t){if("integerValue"in e&&"integerValue"in t)return ft(e.integerValue)===ft(t.integerValue);if("doubleValue"in e&&"doubleValue"in t){const n=ft(e.doubleValue),r=ft(t.doubleValue);return n===r?we(n)===we(r):isNaN(n)&&isNaN(r)}return!1}(e,t);case 9:return R(e.arrayValue.values||[],t.arrayValue.values||[],Et);case 10:case 11:return function(e,t){const n=e.mapValue.fields||{},r=t.mapValue.fields||{};if(Ye(n)!==Ye(r))return!1;for(const e in n)if(n.hasOwnProperty(e)&&(void 0===r[e]||!Et(n[e],r[e])))return!1;return!0}(e,t);default:return v()}}function Tt(e,t){return void 0!==(e.values||[]).find((e=>Et(e,t)))}function St(e,t){if(e===t)return 0;const n=It(e),r=It(t);if(n!==r)return M(n,r);switch(n){case 0:case 9007199254740991:return 0;case 1:return M(e.booleanValue,t.booleanValue);case 2:return function(e,t){const n=ft(e.integerValue||e.doubleValue),r=ft(t.integerValue||t.doubleValue);return n<r?-1:n>r?1:n===r?0:isNaN(n)?isNaN(r)?0:-1:1}(e,t);case 3:return xt(e.timestampValue,t.timestampValue);case 4:return xt(yt(e),yt(t));case 5:return M(e.stringValue,t.stringValue);case 6:return function(e,t){const n=gt(e),r=gt(t);return n.compareTo(r)}(e.bytesValue,t.bytesValue);case 7:return function(e,t){const n=e.split("/"),r=t.split("/");for(let e=0;e<n.length&&e<r.length;e++){const t=M(n[e],r[e]);if(0!==t)return t}return M(n.length,r.length)}(e.referenceValue,t.referenceValue);case 8:return function(e,t){const n=M(ft(e.latitude),ft(t.latitude));return 0!==n?n:M(ft(e.longitude),ft(t.longitude))}(e.geoPointValue,t.geoPointValue);case 9:return Ct(e.arrayValue,t.arrayValue);case 10:return function(e,t){var n,r,i,s;const o=e.fields||{},a=t.fields||{},c=null===(n=o.value)||void 0===n?void 0:n.arrayValue,u=null===(r=a.value)||void 0===r?void 0:r.arrayValue,l=M((null===(i=null==c?void 0:c.values)||void 0===i?void 0:i.length)||0,(null===(s=null==u?void 0:u.values)||void 0===s?void 0:s.length)||0);return 0!==l?l:Ct(c,u)}(e.mapValue,t.mapValue);case 11:return function(e,t){if(e===bt.mapValue&&t===bt.mapValue)return 0;if(e===bt.mapValue)return 1;if(t===bt.mapValue)return-1;const n=e.fields||{},r=Object.keys(n),i=t.fields||{},s=Object.keys(i);r.sort(),s.sort();for(let e=0;e<r.length&&e<s.length;++e){const t=M(r[e],s[e]);if(0!==t)return t;const o=St(n[r[e]],i[s[e]]);if(0!==o)return o}return M(r.length,s.length)}(e.mapValue,t.mapValue);default:throw v()}}function xt(e,t){if("string"==typeof e&&"string"==typeof t&&e.length===t.length)return M(e,t);const n=dt(e),r=dt(t),i=M(n.seconds,r.seconds);return 0!==i?i:M(n.nanos,r.nanos)}function Ct(e,t){const n=e.values||[],r=t.values||[];for(let e=0;e<n.length&&e<r.length;++e){const t=St(n[e],r[e]);if(t)return t}return M(n.length,r.length)}function Dt(e){return At(e)}function At(e){return"nullValue"in e?"null":"booleanValue"in e?""+e.booleanValue:"integerValue"in e?""+e.integerValue:"doubleValue"in e?""+e.doubleValue:"timestampValue"in e?function(e){const t=dt(e);return`time(${t.seconds},${t.nanos})`}(e.timestampValue):"stringValue"in e?e.stringValue:"bytesValue"in e?function(e){return gt(e).toBase64()}(e.bytesValue):"referenceValue"in e?function(e){return $.fromName(e).toString()}(e.referenceValue):"geoPointValue"in e?function(e){return`geo(${e.latitude},${e.longitude})`}(e.geoPointValue):"arrayValue"in e?function(e){let t="[",n=!0;for(const r of e.values||[])n?n=!1:t+=",",t+=At(r);return t+"]"}(e.arrayValue):"mapValue"in e?function(e){const t=Object.keys(e.fields||{}).sort();let n="{",r=!0;for(const i of t)r?r=!1:n+=",",n+=`${i}:${At(e.fields[i])}`;return n+"}"}(e.mapValue):v()}function kt(e){switch(It(e)){case 0:case 1:return 4;case 2:return 8;case 3:case 8:return 16;case 4:const t=mt(e);return t?16+kt(t):16;case 5:return 2*e.stringValue.length;case 6:return gt(e.bytesValue).approximateByteSize();case 7:return e.referenceValue.length;case 9:return function(e){return(e.values||[]).reduce(((e,t)=>e+kt(t)),0)}(e.arrayValue);case 10:case 11:return function(e){let t=0;return Ze(e.fields,((e,n)=>{t+=e.length+kt(n)})),t}(e.mapValue);default:throw v()}}function Nt(e,t){return{referenceValue:`projects/${e.projectId}/databases/${e.database}/documents/${t.path.canonicalString()}`}}function Lt(e){return!!e&&"integerValue"in e}function Ot(e){return!!e&&"arrayValue"in e}function Mt(e){return!!e&&"nullValue"in e}function Rt(e){return!!e&&"doubleValue"in e&&isNaN(Number(e.doubleValue))}function Pt(e){return!!e&&"mapValue"in e}function Ft(e){var t,n;return"__vector__"===(null===(n=((null===(t=null==e?void 0:e.mapValue)||void 0===t?void 0:t.fields)||{}).__type__)||void 0===n?void 0:n.stringValue)}function Vt(e){if(e.geoPointValue)return{geoPointValue:Object.assign({},e.geoPointValue)};if(e.timestampValue&&"object"==typeof e.timestampValue)return{timestampValue:Object.assign({},e.timestampValue)};if(e.mapValue){const t={mapValue:{fields:{}}};return Ze(e.mapValue.fields,((e,n)=>t.mapValue.fields[e]=Vt(n))),t}if(e.arrayValue){const t={arrayValue:{values:[]}};for(let n=0;n<(e.arrayValue.values||[]).length;++n)t.arrayValue.values[n]=Vt(e.arrayValue.values[n]);return t}return Object.assign({},e)}function qt(e){return"__max__"===(((e.mapValue||{}).fields||{}).__type__||{}).stringValue}const Bt={mapValue:{fields:{__type__:{stringValue:"__vector__"},value:{arrayValue:{}}}}};function Ut(e){return"nullValue"in e?_t:"booleanValue"in e?{booleanValue:!1}:"integerValue"in e||"doubleValue"in e?{doubleValue:NaN}:"timestampValue"in e?{timestampValue:{seconds:Number.MIN_SAFE_INTEGER}}:"stringValue"in e?{stringValue:""}:"bytesValue"in e?{bytesValue:""}:"referenceValue"in e?Nt(wt.empty(),$.empty()):"geoPointValue"in e?{geoPointValue:{latitude:-90,longitude:-180}}:"arrayValue"in e?{arrayValue:{}}:"mapValue"in e?Ft(e)?Bt:{mapValue:{}}:v()}function jt(e){return"nullValue"in e?{booleanValue:!1}:"booleanValue"in e?{doubleValue:NaN}:"integerValue"in e||"doubleValue"in e?{timestampValue:{seconds:Number.MIN_SAFE_INTEGER}}:"timestampValue"in e?{stringValue:""}:"stringValue"in e?{bytesValue:""}:"bytesValue"in e?Nt(wt.empty(),$.empty()):"referenceValue"in e?{geoPointValue:{latitude:-90,longitude:-180}}:"geoPointValue"in e?{arrayValue:{}}:"arrayValue"in e?Bt:"mapValue"in e?Ft(e)?{mapValue:{}}:bt:v()}function $t(e,t){const n=St(e.value,t.value);return 0!==n?n:e.inclusive&&!t.inclusive?-1:!e.inclusive&&t.inclusive?1:0}function zt(e,t){const n=St(e.value,t.value);return 0!==n?n:e.inclusive&&!t.inclusive?1:!e.inclusive&&t.inclusive?-1:0}class Gt{constructor(e){this.value=e}static empty(){return new Gt({mapValue:{}})}field(e){if(e.isEmpty())return this.value;{let t=this.value;for(let n=0;n<e.length-1;++n)if(t=(t.mapValue.fields||{})[e.get(n)],!Pt(t))return null;return t=(t.mapValue.fields||{})[e.lastSegment()],t||null}}set(e,t){this.getFieldsMap(e.popLast())[e.lastSegment()]=Vt(t)}setAll(e){let t=j.emptyPath(),n={},r=[];e.forEach(((e,i)=>{if(!t.isImmediateParentOf(i)){const e=this.getFieldsMap(t);this.applyChanges(e,n,r),n={},r=[],t=i.popLast()}e?n[i.lastSegment()]=Vt(e):r.push(i.lastSegment())}));const i=this.getFieldsMap(t);this.applyChanges(i,n,r)}delete(e){const t=this.field(e.popLast());Pt(t)&&t.mapValue.fields&&delete t.mapValue.fields[e.lastSegment()]}isEqual(e){return Et(this.value,e.value)}getFieldsMap(e){let t=this.value;t.mapValue.fields||(t.mapValue={fields:{}});for(let n=0;n<e.length;++n){let r=t.mapValue.fields[e.get(n)];Pt(r)&&r.mapValue.fields||(r={mapValue:{fields:{}}},t.mapValue.fields[e.get(n)]=r),t=r}return t.mapValue.fields}applyChanges(e,t,n){Ze(t,((t,n)=>e[t]=n));for(const t of n)delete e[t]}clone(){return new Gt(Vt(this.value))}}function Kt(e){const t=[];return Ze(e.fields,((e,n)=>{const r=new j([e]);if(Pt(n)){const e=Kt(n.mapValue).fields;if(0===e.length)t.push(r);else for(const n of e)t.push(r.child(n))}else t.push(r)})),new ct(t)}class Qt{constructor(e,t,n,r,i,s,o){this.key=e,this.documentType=t,this.version=n,this.readTime=r,this.createTime=i,this.data=s,this.documentState=o}static newInvalidDocument(e){return new Qt(e,0,V.min(),V.min(),V.min(),Gt.empty(),0)}static newFoundDocument(e,t,n,r){return new Qt(e,1,t,V.min(),n,r,0)}static newNoDocument(e,t){return new Qt(e,2,t,V.min(),V.min(),Gt.empty(),0)}static newUnknownDocument(e,t){return new Qt(e,3,t,V.min(),V.min(),Gt.empty(),2)}convertToFoundDocument(e,t){return!this.createTime.isEqual(V.min())||2!==this.documentType&&0!==this.documentType||(this.createTime=e),this.version=e,this.documentType=1,this.data=t,this.documentState=0,this}convertToNoDocument(e){return this.version=e,this.documentType=2,this.data=Gt.empty(),this.documentState=0,this}convertToUnknownDocument(e){return this.version=e,this.documentType=3,this.data=Gt.empty(),this.documentState=2,this}setHasCommittedMutations(){return this.documentState=2,this}setHasLocalMutations(){return this.documentState=1,this.version=V.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 Qt&&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 Qt(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 Ht{constructor(e,t){this.position=e,this.inclusive=t}}function Wt(e,t,n){let r=0;for(let i=0;i<e.position.length;i++){const s=t[i],o=e.position[i];if(r=s.field.isKeyField()?$.comparator($.fromName(o.referenceValue),n.key):St(o,n.data.field(s.field)),"desc"===s.dir&&(r*=-1),0!==r)break}return r}function Jt(e,t){if(null===e)return null===t;if(null===t)return!1;if(e.inclusive!==t.inclusive||e.position.length!==t.position.length)return!1;for(let n=0;n<e.position.length;n++)if(!Et(e.position[n],t.position[n]))return!1;return!0}class Xt{constructor(e,t="asc"){this.field=e,this.dir=t}}function Yt(e,t){return e.dir===t.dir&&e.field.isEqual(t.field)}class Zt{}class en extends Zt{constructor(e,t,n){super(),this.field=e,this.op=t,this.value=n}static create(e,t,n){return e.isKeyField()?"in"===t||"not-in"===t?this.createKeyFieldInFilter(e,t,n):new hn(e,t,n):"array-contains"===t?new pn(e,n):"in"===t?new mn(e,n):"not-in"===t?new yn(e,n):"array-contains-any"===t?new vn(e,n):new en(e,t,n)}static createKeyFieldInFilter(e,t,n){return"in"===t?new dn(e,n):new fn(e,n)}matches(e){const t=e.data.field(this.field);return"!="===this.op?null!==t&&this.matchesComparison(St(t,this.value)):null!==t&&It(this.value)===It(t)&&this.matchesComparison(St(t,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 v()}}isInequality(){return["<","<=",">",">=","!=","not-in"].indexOf(this.op)>=0}getFlattenedFilters(){return[this]}getFilters(){return[this]}}class tn extends Zt{constructor(e,t){super(),this.filters=e,this.op=t,this.ae=null}static create(e,t){return new tn(e,t)}matches(e){return nn(this)?void 0===this.filters.find((t=>!t.matches(e))):void 0!==this.filters.find((t=>t.matches(e)))}getFlattenedFilters(){return null!==this.ae||(this.ae=this.filters.reduce(((e,t)=>e.concat(t.getFlattenedFilters())),[])),this.ae}getFilters(){return Object.assign([],this.filters)}}function nn(e){return"and"===e.op}function rn(e){return"or"===e.op}function sn(e){return on(e)&&nn(e)}function on(e){for(const t of e.filters)if(t instanceof tn)return!1;return!0}function an(e){if(e instanceof en)return e.field.canonicalString()+e.op.toString()+Dt(e.value);if(sn(e))return e.filters.map((e=>an(e))).join(",");{const t=e.filters.map((e=>an(e))).join(",");return`${e.op}(${t})`}}function cn(e,t){return e instanceof en?function(e,t){return t instanceof en&&e.op===t.op&&e.field.isEqual(t.field)&&Et(e.value,t.value)}(e,t):e instanceof tn?function(e,t){return t instanceof tn&&e.op===t.op&&e.filters.length===t.filters.length&&e.filters.reduce(((e,n,r)=>e&&cn(n,t.filters[r])),!0)}(e,t):void v()}function un(e,t){const n=e.filters.concat(t);return tn.create(n,e.op)}function ln(e){return e instanceof en?function(e){return`${e.field.canonicalString()} ${e.op} ${Dt(e.value)}`}(e):e instanceof tn?function(e){return e.op.toString()+" {"+e.getFilters().map(ln).join(" ,")+"}"}(e):"Filter"}class hn extends en{constructor(e,t,n){super(e,t,n),this.key=$.fromName(n.referenceValue)}matches(e){const t=$.comparator(e.key,this.key);return this.matchesComparison(t)}}class dn extends en{constructor(e,t){super(e,"in",t),this.keys=gn(0,t)}matches(e){return this.keys.some((t=>t.isEqual(e.key)))}}class fn extends en{constructor(e,t){super(e,"not-in",t),this.keys=gn(0,t)}matches(e){return!this.keys.some((t=>t.isEqual(e.key)))}}function gn(e,t){var n;return((null===(n=t.arrayValue)||void 0===n?void 0:n.values)||[]).map((e=>$.fromName(e.referenceValue)))}class pn extends en{constructor(e,t){super(e,"array-contains",t)}matches(e){const t=e.data.field(this.field);return Ot(t)&&Tt(t.arrayValue,this.value)}}class mn extends en{constructor(e,t){super(e,"in",t)}matches(e){const t=e.data.field(this.field);return null!==t&&Tt(this.value.arrayValue,t)}}class yn extends en{constructor(e,t){super(e,"not-in",t)}matches(e){if(Tt(this.value.arrayValue,{nullValue:"NULL_VALUE"}))return!1;const t=e.data.field(this.field);return null!==t&&!Tt(this.value.arrayValue,t)}}class vn extends en{constructor(e,t){super(e,"array-contains-any",t)}matches(e){const t=e.data.field(this.field);return!(!Ot(t)||!t.arrayValue.values)&&t.arrayValue.values.some((e=>Tt(this.value.arrayValue,e)))}}class wn{constructor(e,t=null,n=[],r=[],i=null,s=null,o=null){this.path=e,this.collectionGroup=t,this.orderBy=n,this.filters=r,this.limit=i,this.startAt=s,this.endAt=o,this.ue=null}}function bn(e,t=null,n=[],r=[],i=null,s=null,o=null){return new wn(e,t,n,r,i,s,o)}function _n(e){const t=b(e);if(null===t.ue){let e=t.path.canonicalString();null!==t.collectionGroup&&(e+="|cg:"+t.collectionGroup),e+="|f:",e+=t.filters.map((e=>an(e))).join(","),e+="|ob:",e+=t.orderBy.map((e=>function(e){return e.field.canonicalString()+e.dir}(e))).join(","),ve(t.limit)||(e+="|l:",e+=t.limit),t.startAt&&(e+="|lb:",e+=t.startAt.inclusive?"b:":"a:",e+=t.startAt.position.map((e=>Dt(e))).join(",")),t.endAt&&(e+="|ub:",e+=t.endAt.inclusive?"a:":"b:",e+=t.endAt.position.map((e=>Dt(e))).join(",")),t.ue=e}return t.ue}function In(e,t){if(e.limit!==t.limit)return!1;if(e.orderBy.length!==t.orderBy.length)return!1;for(let n=0;n<e.orderBy.length;n++)if(!Yt(e.orderBy[n],t.orderBy[n]))return!1;if(e.filters.length!==t.filters.length)return!1;for(let n=0;n<e.filters.length;n++)if(!cn(e.filters[n],t.filters[n]))return!1;return e.collectionGroup===t.collectionGroup&&!!e.path.isEqual(t.path)&&!!Jt(e.startAt,t.startAt)&&Jt(e.endAt,t.endAt)}function En(e){return $.isDocumentKey(e.path)&&null===e.collectionGroup&&0===e.filters.length}function Tn(e,t){return e.filters.filter((e=>e instanceof en&&e.field.isEqual(t)))}function Sn(e,t,n){let r=_t,i=!0;for(const n of Tn(e,t)){let e=_t,t=!0;switch(n.op){case"<":case"<=":e=Ut(n.value);break;case"==":case"in":case">=":e=n.value;break;case">":e=n.value,t=!1;break;case"!=":case"not-in":e=_t}$t({value:r,inclusive:i},{value:e,inclusive:t})<0&&(r=e,i=t)}if(null!==n)for(let s=0;s<e.orderBy.length;++s)if(e.orderBy[s].field.isEqual(t)){const e=n.position[s];$t({value:r,inclusive:i},{value:e,inclusive:n.inclusive})<0&&(r=e,i=n.inclusive);break}return{value:r,inclusive:i}}function xn(e,t,n){let r=bt,i=!0;for(const n of Tn(e,t)){let e=bt,t=!0;switch(n.op){case">=":case">":e=jt(n.value),t=!1;break;case"==":case"in":case"<=":e=n.value;break;case"<":e=n.value,t=!1;break;case"!=":case"not-in":e=bt}zt({value:r,inclusive:i},{value:e,inclusive:t})>0&&(r=e,i=t)}if(null!==n)for(let s=0;s<e.orderBy.length;++s)if(e.orderBy[s].field.isEqual(t)){const e=n.position[s];zt({value:r,inclusive:i},{value:e,inclusive:n.inclusive})>0&&(r=e,i=n.inclusive);break}return{value:r,inclusive:i}}class Cn{constructor(e,t=null,n=[],r=[],i=null,s="F",o=null,a=null){this.path=e,this.collectionGroup=t,this.explicitOrderBy=n,this.filters=r,this.limit=i,this.limitType=s,this.startAt=o,this.endAt=a,this.ce=null,this.le=null,this.he=null,this.startAt,this.endAt}}function Dn(e,t,n,r,i,s,o,a){return new Cn(e,t,n,r,i,s,o,a)}function An(e){return new Cn(e)}function kn(e){return 0===e.filters.length&&null===e.limit&&null==e.startAt&&null==e.endAt&&(0===e.explicitOrderBy.length||1===e.explicitOrderBy.length&&e.explicitOrderBy[0].field.isKeyField())}function Nn(e){return null!==e.collectionGroup}function Ln(e){const t=b(e);if(null===t.ce){t.ce=[];const e=new Set;for(const n of t.explicitOrderBy)t.ce.push(n),e.add(n.field.canonicalString());const n=t.explicitOrderBy.length>0?t.explicitOrderBy[t.explicitOrderBy.length-1].dir:"asc",r=function(e){let t=new st(j.comparator);return e.filters.forEach((e=>{e.getFlattenedFilters().forEach((e=>{e.isInequality()&&(t=t.add(e.field))}))})),t}(t);r.forEach((r=>{e.has(r.canonicalString())||r.isKeyField()||t.ce.push(new Xt(r,n))})),e.has(j.keyField().canonicalString())||t.ce.push(new Xt(j.keyField(),n))}return t.ce}function On(e){const t=b(e);return t.le||(t.le=Rn(t,Ln(e))),t.le}function Mn(e){const t=b(e);return t.he||(t.he=Rn(t,e.explicitOrderBy)),t.he}function Rn(e,t){if("F"===e.limitType)return bn(e.path,e.collectionGroup,t,e.filters,e.limit,e.startAt,e.endAt);{t=t.map((e=>{const t="desc"===e.dir?"asc":"desc";return new Xt(e.field,t)}));const n=e.endAt?new Ht(e.endAt.position,e.endAt.inclusive):null,r=e.startAt?new Ht(e.startAt.position,e.startAt.inclusive):null;return bn(e.path,e.collectionGroup,t,e.filters,e.limit,n,r)}}function Pn(e,t){const n=e.filters.concat([t]);return new Cn(e.path,e.collectionGroup,e.explicitOrderBy.slice(),n,e.limit,e.limitType,e.startAt,e.endAt)}function Fn(e,t,n){return new Cn(e.path,e.collectionGroup,e.explicitOrderBy.slice(),e.filters.slice(),t,n,e.startAt,e.endAt)}function Vn(e,t){return In(On(e),On(t))&&e.limitType===t.limitType}function qn(e){return`${_n(On(e))}|lt:${e.limitType}`}function Bn(e){return`Query(target=${function(e){let t=e.path.canonicalString();return null!==e.collectionGroup&&(t+=" collectionGroup="+e.collectionGroup),e.filters.length>0&&(t+=`, filters: [${e.filters.map((e=>ln(e))).join(", ")}]`),ve(e.limit)||(t+=", limit: "+e.limit),e.orderBy.length>0&&(t+=`, orderBy: [${e.orderBy.map((e=>function(e){return`${e.field.canonicalString()} (${e.dir})`}(e))).join(", ")}]`),e.startAt&&(t+=", startAt: ",t+=e.startAt.inclusive?"b:":"a:",t+=e.startAt.position.map((e=>Dt(e))).join(",")),e.endAt&&(t+=", endAt: ",t+=e.endAt.inclusive?"a:":"b:",t+=e.endAt.position.map((e=>Dt(e))).join(",")),`Target(${t})`}(On(e))}; limitType=${e.limitType})`}function Un(e,t){return t.isFoundDocument()&&function(e,t){const n=t.key.path;return null!==e.collectionGroup?t.key.hasCollectionId(e.collectionGroup)&&e.path.isPrefixOf(n):$.isDocumentKey(e.path)?e.path.isEqual(n):e.path.isImmediateParentOf(n)}(e,t)&&function(e,t){for(const n of Ln(e))if(!n.field.isKeyField()&&null===t.data.field(n.field))return!1;return!0}(e,t)&&function(e,t){for(const n of e.filters)if(!n.matches(t))return!1;return!0}(e,t)&&function(e,t){return!(e.startAt&&!function(e,t,n){const r=Wt(e,t,n);return e.inclusive?r<=0:r<0}(e.startAt,Ln(e),t)||e.endAt&&!function(e,t,n){const r=Wt(e,t,n);return e.inclusive?r>=0:r>0}(e.endAt,Ln(e),t))}(e,t)}function jn(e){return e.collectionGroup||(e.path.length%2==1?e.path.lastSegment():e.path.get(e.path.length-2))}function $n(e){return(t,n)=>{let r=!1;for(const i of Ln(e)){const e=zn(i,t,n);if(0!==e)return e;r=r||i.field.isKeyField()}return 0}}function zn(e,t,n){const r=e.field.isKeyField()?$.comparator(t.key,n.key):function(e,t,n){const r=t.data.field(e),i=n.data.field(e);return null!==r&&null!==i?St(r,i):v()}(e.field,t,n);switch(e.dir){case"asc":return r;case"desc":return-1*r;default:return v()}}class Gn{constructor(e,t){this.mapKeyFn=e,this.equalsFn=t,this.inner={},this.innerSize=0}get(e){const t=this.mapKeyFn(e),n=this.inner[t];if(void 0!==n)for(const[t,r]of n)if(this.equalsFn(t,e))return r}has(e){return void 0!==this.get(e)}set(e,t){const n=this.mapKeyFn(e),r=this.inner[n];if(void 0===r)return this.inner[n]=[[e,t]],void this.innerSize++;for(let n=0;n<r.length;n++)if(this.equalsFn(r[n][0],e))return void(r[n]=[e,t]);r.push([e,t]),this.innerSize++}delete(e){const t=this.mapKeyFn(e),n=this.inner[t];if(void 0===n)return!1;for(let r=0;r<n.length;r++)if(this.equalsFn(n[r][0],e))return 1===n.length?delete this.inner[t]:n.splice(r,1),this.innerSize--,!0;return!1}forEach(e){Ze(this.inner,((t,n)=>{for(const[t,r]of n)e(t,r)}))}isEmpty(){return tt(this.inner)}size(){return this.innerSize}}const Kn=new nt($.comparator);function Qn(){return Kn}const Hn=new nt($.comparator);function Wn(...e){let t=Hn;for(const n of e)t=t.insert(n.key,n);return t}function Jn(e){let t=Hn;return e.forEach(((e,n)=>t=t.insert(e,n.overlayedDocument))),t}function Xn(){return Zn()}function Yn(){return Zn()}function Zn(){return new Gn((e=>e.toString()),((e,t)=>e.isEqual(t)))}const er=new nt($.comparator),tr=new st($.comparator);function nr(...e){let t=tr;for(const n of e)t=t.add(n);return t}const rr=new st(M);function ir(){return rr}function sr(e,t){if(e.useProto3Json){if(isNaN(t))return{doubleValue:"NaN"};if(t===1/0)return{doubleValue:"Infinity"};if(t===-1/0)return{doubleValue:"-Infinity"}}return{doubleValue:we(t)?"-0":t}}function or(e){return{integerValue:""+e}}function ar(e,t){return be(t)?or(t):sr(e,t)}class cr{constructor(){this._=void 0}}function ur(e,t,n){return e instanceof dr?function(e,t){const n={fields:{__type__:{stringValue:"server_timestamp"},__local_write_time__:{timestampValue:{seconds:e.seconds,nanos:e.nanoseconds}}}};return t&&pt(t)&&(t=mt(t)),t&&(n.fields.__previous_value__=t),{mapValue:n}}(n,t):e instanceof fr?gr(e,t):e instanceof pr?mr(e,t):function(e,t){const n=hr(e,t),r=vr(n)+vr(e.Pe);return Lt(n)&&Lt(e.Pe)?or(r):sr(e.serializer,r)}(e,t)}function lr(e,t,n){return e instanceof fr?gr(e,t):e instanceof pr?mr(e,t):n}function hr(e,t){return e instanceof yr?function(e){return Lt(e)||function(e){return!!e&&"doubleValue"in e}(e)}(t)?t:{integerValue:0}:null}class dr extends cr{}class fr extends cr{constructor(e){super(),this.elements=e}}function gr(e,t){const n=wr(t);for(const t of e.elements)n.some((e=>Et(e,t)))||n.push(t);return{arrayValue:{values:n}}}class pr extends cr{constructor(e){super(),this.elements=e}}function mr(e,t){let n=wr(t);for(const t of e.elements)n=n.filter((e=>!Et(e,t)));return{arrayValue:{values:n}}}class yr extends cr{constructor(e,t){super(),this.serializer=e,this.Pe=t}}function vr(e){return ft(e.integerValue||e.doubleValue)}function wr(e){return Ot(e)&&e.arrayValue.values?e.arrayValue.values.slice():[]}class br{constructor(e,t){this.field=e,this.transform=t}}class _r{constructor(e,t){this.version=e,this.transformResults=t}}class Ir{constructor(e,t){this.updateTime=e,this.exists=t}static none(){return new Ir}static exists(e){return new Ir(void 0,e)}static updateTime(e){return new Ir(e)}get isNone(){return void 0===this.updateTime&&void 0===this.exists}isEqual(e){return this.exists===e.exists&&(this.updateTime?!!e.updateTime&&this.updateTime.isEqual(e.updateTime):!e.updateTime)}}function Er(e,t){return void 0!==e.updateTime?t.isFoundDocument()&&t.version.isEqual(e.updateTime):void 0===e.exists||e.exists===t.isFoundDocument()}class Tr{}function Sr(e,t){if(!e.hasLocalMutations||t&&0===t.fields.length)return null;if(null===t)return e.isNoDocument()?new Rr(e.key,Ir.none()):new kr(e.key,e.data,Ir.none());{const n=e.data,r=Gt.empty();let i=new st(j.comparator);for(let e of t.fields)if(!i.has(e)){let t=n.field(e);null===t&&e.length>1&&(e=e.popLast(),t=n.field(e)),null===t?r.delete(e):r.set(e,t),i=i.add(e)}return new Nr(e.key,r,new ct(i.toArray()),Ir.none())}}function xr(e,t,n){e instanceof kr?function(e,t,n){const r=e.value.clone(),i=Or(e.fieldTransforms,t,n.transformResults);r.setAll(i),t.convertToFoundDocument(n.version,r).setHasCommittedMutations()}(e,t,n):e instanceof Nr?function(e,t,n){if(!Er(e.precondition,t))return void t.convertToUnknownDocument(n.version);const r=Or(e.fieldTransforms,t,n.transformResults),i=t.data;i.setAll(Lr(e)),i.setAll(r),t.convertToFoundDocument(n.version,i).setHasCommittedMutations()}(e,t,n):function(e,t,n){t.convertToNoDocument(n.version).setHasCommittedMutations()}(0,t,n)}function Cr(e,t,n,r){return e instanceof kr?function(e,t,n,r){if(!Er(e.precondition,t))return n;const i=e.value.clone(),s=Mr(e.fieldTransforms,r,t);return i.setAll(s),t.convertToFoundDocument(t.version,i).setHasLocalMutations(),null}(e,t,n,r):e instanceof Nr?function(e,t,n,r){if(!Er(e.precondition,t))return n;const i=Mr(e.fieldTransforms,r,t),s=t.data;return s.setAll(Lr(e)),s.setAll(i),t.convertToFoundDocument(t.version,s).setHasLocalMutations(),null===n?null:n.unionWith(e.fieldMask.fields).unionWith(e.fieldTransforms.map((e=>e.field)))}(e,t,n,r):function(e,t,n){return Er(e.precondition,t)?(t.convertToNoDocument(t.version).setHasLocalMutations(),null):n}(e,t,n)}function Dr(e,t){let n=null;for(const r of e.fieldTransforms){const e=t.data.field(r.field),i=hr(r.transform,e||null);null!=i&&(null===n&&(n=Gt.empty()),n.set(r.field,i))}return n||null}function Ar(e,t){return e.type===t.type&&!!e.key.isEqual(t.key)&&!!e.precondition.isEqual(t.precondition)&&!!function(e,t){return void 0===e&&void 0===t||!(!e||!t)&&R(e,t,((e,t)=>function(e,t){return e.field.isEqual(t.field)&&function(e,t){return e instanceof fr&&t instanceof fr||e instanceof pr&&t instanceof pr?R(e.elements,t.elements,Et):e instanceof yr&&t instanceof yr?Et(e.Pe,t.Pe):e instanceof dr&&t instanceof dr}(e.transform,t.transform)}(e,t)))}(e.fieldTransforms,t.fieldTransforms)&&(0===e.type?e.value.isEqual(t.value):1!==e.type||e.data.isEqual(t.data)&&e.fieldMask.isEqual(t.fieldMask))}class kr extends Tr{constructor(e,t,n,r=[]){super(),this.key=e,this.value=t,this.precondition=n,this.fieldTransforms=r,this.type=0}getFieldMask(){return null}}class Nr extends Tr{constructor(e,t,n,r,i=[]){super(),this.key=e,this.data=t,this.fieldMask=n,this.precondition=r,this.fieldTransforms=i,this.type=1}getFieldMask(){return this.fieldMask}}function Lr(e){const t=new Map;return e.fieldMask.fields.forEach((n=>{if(!n.isEmpty()){const r=e.data.field(n);t.set(n,r)}})),t}function Or(e,t,n){const r=new Map;w(e.length===n.length);for(let i=0;i<n.length;i++){const s=e[i],o=s.transform,a=t.data.field(s.field);r.set(s.field,lr(o,a,n[i]))}return r}function Mr(e,t,n){const r=new Map;for(const i of e){const e=i.transform,s=n.data.field(i.field);r.set(i.field,ur(e,s,t))}return r}class Rr extends Tr{constructor(e,t){super(),this.key=e,this.precondition=t,this.type=2,this.fieldTransforms=[]}getFieldMask(){return null}}class Pr extends Tr{constructor(e,t){super(),this.key=e,this.precondition=t,this.type=3,this.fieldTransforms=[]}getFieldMask(){return null}}class Fr{constructor(e,t,n,r){this.batchId=e,this.localWriteTime=t,this.baseMutations=n,this.mutations=r}applyToRemoteDocument(e,t){const n=t.mutationResults;for(let t=0;t<this.mutations.length;t++){const r=this.mutations[t];r.key.isEqual(e.key)&&xr(r,e,n[t])}}applyToLocalView(e,t){for(const n of this.baseMutations)n.key.isEqual(e.key)&&(t=Cr(n,e,t,this.localWriteTime));for(const n of this.mutations)n.key.isEqual(e.key)&&(t=Cr(n,e,t,this.localWriteTime));return t}applyToLocalDocumentSet(e,t){const n=Yn();return this.mutations.forEach((r=>{const i=e.get(r.key),s=i.overlayedDocument;let o=this.applyToLocalView(s,i.mutatedFields);o=t.has(r.key)?null:o;const a=Sr(s,o);null!==a&&n.set(r.key,a),s.isValidDocument()||s.convertToNoDocument(V.min())})),n}keys(){return this.mutations.reduce(((e,t)=>e.add(t.key)),nr())}isEqual(e){return this.batchId===e.batchId&&R(this.mutations,e.mutations,((e,t)=>Ar(e,t)))&&R(this.baseMutations,e.baseMutations,((e,t)=>Ar(e,t)))}}class Vr{constructor(e,t,n,r){this.batch=e,this.commitVersion=t,this.mutationResults=n,this.docVersions=r}static from(e,t,n){w(e.mutations.length===n.length);let r=er;const i=e.mutations;for(let e=0;e<i.length;e++)r=r.insert(i[e].key,n[e].version);return new Vr(e,t,n,r)}}class qr{constructor(e,t){this.largestBatchId=e,this.mutation=t}getKey(){return this.mutation.key}isEqual(e){return null!==e&&this.mutation===e.mutation}toString(){return`Overlay{\n largestBatchId: ${this.largestBatchId},\n mutation: ${this.mutation.toString()}\n }`}}class Br{constructor(e,t,n){this.alias=e,this.aggregateType=t,this.fieldPath=n}}class Ur{constructor(e,t){this.count=e,this.unchangedNames=t}}var jr,$r;function zr(e){switch(e){default:return v();case _.CANCELLED:case _.UNKNOWN:case _.DEADLINE_EXCEEDED:case _.RESOURCE_EXHAUSTED:case _.INTERNAL:case _.UNAVAILABLE:case _.UNAUTHENTICATED:return!1;case _.INVALID_ARGUMENT:case _.NOT_FOUND:case _.ALREADY_EXISTS:case _.PERMISSION_DENIED:case _.FAILED_PRECONDITION:case _.ABORTED:case _.OUT_OF_RANGE:case _.UNIMPLEMENTED:case _.DATA_LOSS:return!0}}function Gr(e){if(void 0===e)return p("GRPC error has no .code"),_.UNKNOWN;switch(e){case jr.OK:return _.OK;case jr.CANCELLED:return _.CANCELLED;case jr.UNKNOWN:return _.UNKNOWN;case jr.DEADLINE_EXCEEDED:return _.DEADLINE_EXCEEDED;case jr.RESOURCE_EXHAUSTED:return _.RESOURCE_EXHAUSTED;case jr.INTERNAL:return _.INTERNAL;case jr.UNAVAILABLE:return _.UNAVAILABLE;case jr.UNAUTHENTICATED:return _.UNAUTHENTICATED;case jr.INVALID_ARGUMENT:return _.INVALID_ARGUMENT;case jr.NOT_FOUND:return _.NOT_FOUND;case jr.ALREADY_EXISTS:return _.ALREADY_EXISTS;case jr.PERMISSION_DENIED:return _.PERMISSION_DENIED;case jr.FAILED_PRECONDITION:return _.FAILED_PRECONDITION;case jr.ABORTED:return _.ABORTED;case jr.OUT_OF_RANGE:return _.OUT_OF_RANGE;case jr.UNIMPLEMENTED:return _.UNIMPLEMENTED;case jr.DATA_LOSS:return _.DATA_LOSS;default:return v()}}($r=jr||(jr={}))[$r.OK=0]="OK",$r[$r.CANCELLED=1]="CANCELLED",$r[$r.UNKNOWN=2]="UNKNOWN",$r[$r.INVALID_ARGUMENT=3]="INVALID_ARGUMENT",$r[$r.DEADLINE_EXCEEDED=4]="DEADLINE_EXCEEDED",$r[$r.NOT_FOUND=5]="NOT_FOUND",$r[$r.ALREADY_EXISTS=6]="ALREADY_EXISTS",$r[$r.PERMISSION_DENIED=7]="PERMISSION_DENIED",$r[$r.UNAUTHENTICATED=16]="UNAUTHENTICATED",$r[$r.RESOURCE_EXHAUSTED=8]="RESOURCE_EXHAUSTED",$r[$r.FAILED_PRECONDITION=9]="FAILED_PRECONDITION",$r[$r.ABORTED=10]="ABORTED",$r[$r.OUT_OF_RANGE=11]="OUT_OF_RANGE",$r[$r.UNIMPLEMENTED=12]="UNIMPLEMENTED",$r[$r.INTERNAL=13]="INTERNAL",$r[$r.UNAVAILABLE=14]="UNAVAILABLE",$r[$r.DATA_LOSS=15]="DATA_LOSS";let Kr=null;function Qr(){return new TextEncoder}const Hr=new a.Integer([4294967295,4294967295],0);function Wr(e){const t=Qr().encode(e),n=new a.Md5;return n.update(t),new Uint8Array(n.digest())}function Jr(e){const t=new DataView(e.buffer),n=t.getUint32(0,!0),r=t.getUint32(4,!0),i=t.getUint32(8,!0),s=t.getUint32(12,!0);return[new a.Integer([n,r],0),new a.Integer([i,s],0)]}class Xr{constructor(e,t,n){if(this.bitmap=e,this.padding=t,this.hashCount=n,t<0||t>=8)throw new Yr(`Invalid padding: ${t}`);if(n<0)throw new Yr(`Invalid hash count: ${n}`);if(e.length>0&&0===this.hashCount)throw new Yr(`Invalid hash count: ${n}`);if(0===e.length&&0!==t)throw new Yr(`Invalid padding when bitmap length is 0: ${t}`);this.Te=8*e.length-t,this.Ie=a.Integer.fromNumber(this.Te)}Ee(e,t,n){let r=e.add(t.multiply(a.Integer.fromNumber(n)));return 1===r.compare(Hr)&&(r=new a.Integer([r.getBits(0),r.getBits(1)],0)),r.modulo(this.Ie).toNumber()}de(e){return!!(this.bitmap[Math.floor(e/8)]&1<<e%8)}mightContain(e){if(0===this.Te)return!1;const t=Wr(e),[n,r]=Jr(t);for(let e=0;e<this.hashCount;e++){const t=this.Ee(n,r,e);if(!this.de(t))return!1}return!0}static create(e,t,n){const r=e%8==0?0:8-e%8,i=new Uint8Array(Math.ceil(e/8)),s=new Xr(i,r,t);return n.forEach((e=>s.insert(e))),s}insert(e){if(0===this.Te)return;const t=Wr(e),[n,r]=Jr(t);for(let e=0;e<this.hashCount;e++){const t=this.Ee(n,r,e);this.Ae(t)}}Ae(e){const t=Math.floor(e/8),n=e%8;this.bitmap[t]|=1<<n}}class Yr extends Error{constructor(){super(...arguments),this.name="BloomFilterError"}}class Zr{constructor(e,t,n,r,i){this.snapshotVersion=e,this.targetChanges=t,this.targetMismatches=n,this.documentUpdates=r,this.resolvedLimboDocuments=i}static createSynthesizedRemoteEventForCurrentChange(e,t,n){const r=new Map;return r.set(e,ei.createSynthesizedTargetChangeForCurrentChange(e,t,n)),new Zr(V.min(),r,new nt(M),Qn(),nr())}}class ei{constructor(e,t,n,r,i){this.resumeToken=e,this.current=t,this.addedDocuments=n,this.modifiedDocuments=r,this.removedDocuments=i}static createSynthesizedTargetChangeForCurrentChange(e,t,n){return new ei(n,t,nr(),nr(),nr())}}class ti{constructor(e,t,n,r){this.Re=e,this.removedTargetIds=t,this.key=n,this.Ve=r}}class ni{constructor(e,t){this.targetId=e,this.me=t}}class ri{constructor(e,t,n=lt.EMPTY_BYTE_STRING,r=null){this.state=e,this.targetIds=t,this.resumeToken=n,this.cause=r}}class ii{constructor(){this.fe=0,this.ge=ai(),this.pe=lt.EMPTY_BYTE_STRING,this.ye=!1,this.we=!0}get current(){return this.ye}get resumeToken(){return this.pe}get Se(){return 0!==this.fe}get be(){return this.we}De(e){e.approximateByteSize()>0&&(this.we=!0,this.pe=e)}ve(){let e=nr(),t=nr(),n=nr();return this.ge.forEach(((r,i)=>{switch(i){case 0:e=e.add(r);break;case 2:t=t.add(r);break;case 1:n=n.add(r);break;default:v()}})),new ei(this.pe,this.ye,e,t,n)}Ce(){this.we=!1,this.ge=ai()}Fe(e,t){this.we=!0,this.ge=this.ge.insert(e,t)}Me(e){this.we=!0,this.ge=this.ge.remove(e)}xe(){this.fe+=1}Oe(){this.fe-=1,w(this.fe>=0)}Ne(){this.we=!0,this.ye=!0}}class si{constructor(e){this.Le=e,this.Be=new Map,this.ke=Qn(),this.qe=oi(),this.Qe=oi(),this.Ke=new nt(M)}$e(e){for(const t of e.Re)e.Ve&&e.Ve.isFoundDocument()?this.Ue(t,e.Ve):this.We(t,e.key,e.Ve);for(const t of e.removedTargetIds)this.We(t,e.key,e.Ve)}Ge(e){this.forEachTarget(e,(t=>{const n=this.ze(t);switch(e.state){case 0:this.je(t)&&n.De(e.resumeToken);break;case 1:n.Oe(),n.Se||n.Ce(),n.De(e.resumeToken);break;case 2:n.Oe(),n.Se||this.removeTarget(t);break;case 3:this.je(t)&&(n.Ne(),n.De(e.resumeToken));break;case 4:this.je(t)&&(this.He(t),n.De(e.resumeToken));break;default:v()}}))}forEachTarget(e,t){e.targetIds.length>0?e.targetIds.forEach(t):this.Be.forEach(((e,n)=>{this.je(n)&&t(n)}))}Je(e){const t=e.targetId,n=e.me.count,r=this.Ye(t);if(r){const i=r.target;if(En(i))if(0===n){const e=new $(i.path);this.We(t,e,Qt.newNoDocument(e,V.min()))}else w(1===n);else{const r=this.Ze(t);if(r!==n){const n=this.Xe(e),i=n?this.et(n,e,r):1;if(0!==i){this.He(t);const e=2===i?"TargetPurposeExistenceFilterMismatchBloom":"TargetPurposeExistenceFilterMismatch";this.Ke=this.Ke.insert(t,e)}null==Kr||Kr.tt(function(e,t,n,r,i){var s,o,a,c,u,l;const h={localCacheCount:e,existenceFilterCount:t.count,databaseId:n.database,projectId:n.projectId},d=t.unchangedNames;return d&&(h.bloomFilter={applied:0===i,hashCount:null!==(s=null==d?void 0:d.hashCount)&&void 0!==s?s:0,bitmapLength:null!==(c=null===(a=null===(o=null==d?void 0:d.bits)||void 0===o?void 0:o.bitmap)||void 0===a?void 0:a.length)&&void 0!==c?c:0,padding:null!==(l=null===(u=null==d?void 0:d.bits)||void 0===u?void 0:u.padding)&&void 0!==l?l:0,mightContain:e=>{var t;return null!==(t=null==r?void 0:r.mightContain(e))&&void 0!==t&&t}}),h}(r,e.me,this.Le.nt(),n,i))}}}}Xe(e){const t=e.me.unchangedNames;if(!t||!t.bits)return null;const{bits:{bitmap:n="",padding:r=0},hashCount:i=0}=t;let s,o;try{s=gt(n).toUint8Array()}catch(e){if(e instanceof ut)return m("Decoding the base64 bloom filter in existence filter failed ("+e.message+"); ignoring the bloom filter and falling back to full re-query."),null;throw e}try{o=new Xr(s,r,i)}catch(e){return m(e instanceof Yr?"BloomFilter error: ":"Applying bloom filter failed: ",e),null}return 0===o.Te?null:o}et(e,t,n){return t.me.count===n-this.rt(e,t.targetId)?0:2}rt(e,t){const n=this.Le.getRemoteKeysForTarget(t);let r=0;return n.forEach((n=>{const i=this.Le.nt(),s=`projects/${i.projectId}/databases/${i.database}/documents/${n.path.canonicalString()}`;e.mightContain(s)||(this.We(t,n,null),r++)})),r}it(e){const t=new Map;this.Be.forEach(((n,r)=>{const i=this.Ye(r);if(i){if(n.current&&En(i.target)){const t=new $(i.target.path);this.st(t).has(r)||this.ot(r,t)||this.We(r,t,Qt.newNoDocument(t,e))}n.be&&(t.set(r,n.ve()),n.Ce())}}));let n=nr();this.Qe.forEach(((e,t)=>{let r=!0;t.forEachWhile((e=>{const t=this.Ye(e);return!t||"TargetPurposeLimboResolution"===t.purpose||(r=!1,!1)})),r&&(n=n.add(e))})),this.ke.forEach(((t,n)=>n.setReadTime(e)));const r=new Zr(e,t,this.Ke,this.ke,n);return this.ke=Qn(),this.qe=oi(),this.Qe=oi(),this.Ke=new nt(M),r}Ue(e,t){if(!this.je(e))return;const n=this.ot(e,t.key)?2:0;this.ze(e).Fe(t.key,n),this.ke=this.ke.insert(t.key,t),this.qe=this.qe.insert(t.key,this.st(t.key).add(e)),this.Qe=this.Qe.insert(t.key,this._t(t.key).add(e))}We(e,t,n){if(!this.je(e))return;const r=this.ze(e);this.ot(e,t)?r.Fe(t,1):r.Me(t),this.Qe=this.Qe.insert(t,this._t(t).delete(e)),this.Qe=this.Qe.insert(t,this._t(t).add(e)),n&&(this.ke=this.ke.insert(t,n))}removeTarget(e){this.Be.delete(e)}Ze(e){const t=this.ze(e).ve();return this.Le.getRemoteKeysForTarget(e).size+t.addedDocuments.size-t.removedDocuments.size}xe(e){this.ze(e).xe()}ze(e){let t=this.Be.get(e);return t||(t=new ii,this.Be.set(e,t)),t}_t(e){let t=this.Qe.get(e);return t||(t=new st(M),this.Qe=this.Qe.insert(e,t)),t}st(e){let t=this.qe.get(e);return t||(t=new st(M),this.qe=this.qe.insert(e,t)),t}je(e){const t=null!==this.Ye(e);return t||g("WatchChangeAggregator","Detected inactive target",e),t}Ye(e){const t=this.Be.get(e);return t&&t.Se?null:this.Le.ut(e)}He(e){this.Be.set(e,new ii),this.Le.getRemoteKeysForTarget(e).forEach((t=>{this.We(e,t,null)}))}ot(e,t){return this.Le.getRemoteKeysForTarget(e).has(t)}}function oi(){return new nt($.comparator)}function ai(){return new nt($.comparator)}const ci={asc:"ASCENDING",desc:"DESCENDING"},ui={"<":"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"},li={and:"AND",or:"OR"};class hi{constructor(e,t){this.databaseId=e,this.useProto3Json=t}}function di(e,t){return e.useProto3Json||ve(t)?t:{value:t}}function fi(e,t){return e.useProto3Json?`${new Date(1e3*t.seconds).toISOString().replace(/\.\d*/,"").replace("Z","")}.${("000000000"+t.nanoseconds).slice(-9)}Z`:{seconds:""+t.seconds,nanos:t.nanoseconds}}function gi(e,t){return e.useProto3Json?t.toBase64():t.toUint8Array()}function pi(e,t){return fi(e,t.toTimestamp())}function mi(e){return w(!!e),V.fromTimestamp(function(e){const t=dt(e);return new F(t.seconds,t.nanos)}(e))}function yi(e,t){return vi(e,t).canonicalString()}function vi(e,t){const n=function(e){return new B(["projects",e.projectId,"databases",e.database])}(e).child("documents");return void 0===t?n:n.child(t)}function wi(e){const t=B.fromString(e);return w(ji(t)),t}function bi(e,t){return yi(e.databaseId,t.path)}function _i(e,t){const n=wi(t);if(n.get(1)!==e.databaseId.projectId)throw new I(_.INVALID_ARGUMENT,"Tried to deserialize key from different project: "+n.get(1)+" vs "+e.databaseId.projectId);if(n.get(3)!==e.databaseId.database)throw new I(_.INVALID_ARGUMENT,"Tried to deserialize key from different database: "+n.get(3)+" vs "+e.databaseId.database);return new $(Si(n))}function Ii(e,t){return yi(e.databaseId,t)}function Ei(e){const t=wi(e);return 4===t.length?B.emptyPath():Si(t)}function Ti(e){return new B(["projects",e.databaseId.projectId,"databases",e.databaseId.database]).canonicalString()}function Si(e){return w(e.length>4&&"documents"===e.get(4)),e.popFirst(5)}function xi(e,t,n){return{name:bi(e,t),fields:n.value.mapValue.fields}}function Ci(e,t,n){const r=_i(e,t.name),i=mi(t.updateTime),s=t.createTime?mi(t.createTime):V.min(),o=new Gt({mapValue:{fields:t.fields}}),a=Qt.newFoundDocument(r,i,s,o);return n&&a.setHasCommittedMutations(),n?a.setHasCommittedMutations():a}function Di(e,t){let n;if(t instanceof kr)n={update:xi(e,t.key,t.value)};else if(t instanceof Rr)n={delete:bi(e,t.key)};else if(t instanceof Nr)n={update:xi(e,t.key,t.data),updateMask:Ui(t.fieldMask)};else{if(!(t instanceof Pr))return v();n={verify:bi(e,t.key)}}return t.fieldTransforms.length>0&&(n.updateTransforms=t.fieldTransforms.map((e=>function(e,t){const n=t.transform;if(n instanceof dr)return{fieldPath:t.field.canonicalString(),setToServerValue:"REQUEST_TIME"};if(n instanceof fr)return{fieldPath:t.field.canonicalString(),appendMissingElements:{values:n.elements}};if(n instanceof pr)return{fieldPath:t.field.canonicalString(),removeAllFromArray:{values:n.elements}};if(n instanceof yr)return{fieldPath:t.field.canonicalString(),increment:n.Pe};throw v()}(0,e)))),t.precondition.isNone||(n.currentDocument=function(e,t){return void 0!==t.updateTime?{updateTime:pi(e,t.updateTime)}:void 0!==t.exists?{exists:t.exists}:v()}(e,t.precondition)),n}function Ai(e,t){const n=t.currentDocument?function(e){return void 0!==e.updateTime?Ir.updateTime(mi(e.updateTime)):void 0!==e.exists?Ir.exists(e.exists):Ir.none()}(t.currentDocument):Ir.none(),r=t.updateTransforms?t.updateTransforms.map((t=>function(e,t){let n=null;if("setToServerValue"in t)w("REQUEST_TIME"===t.setToServerValue),n=new dr;else if("appendMissingElements"in t){const e=t.appendMissingElements.values||[];n=new fr(e)}else if("removeAllFromArray"in t){const e=t.removeAllFromArray.values||[];n=new pr(e)}else"increment"in t?n=new yr(e,t.increment):v();const r=j.fromServerFormat(t.fieldPath);return new br(r,n)}(e,t))):[];if(t.update){t.update.name;const i=_i(e,t.update.name),s=new Gt({mapValue:{fields:t.update.fields}});if(t.updateMask){const e=function(e){const t=e.fieldPaths||[];return new ct(t.map((e=>j.fromServerFormat(e))))}(t.updateMask);return new Nr(i,s,e,n,r)}return new kr(i,s,n,r)}if(t.delete){const r=_i(e,t.delete);return new Rr(r,n)}if(t.verify){const r=_i(e,t.verify);return new Pr(r,n)}return v()}function ki(e,t){return{documents:[Ii(e,t.path)]}}function Ni(e,t){const n={structuredQuery:{}},r=t.path;let i;null!==t.collectionGroup?(i=r,n.structuredQuery.from=[{collectionId:t.collectionGroup,allDescendants:!0}]):(i=r.popLast(),n.structuredQuery.from=[{collectionId:r.lastSegment()}]),n.parent=Ii(e,i);const s=function(e){if(0!==e.length)return Bi(tn.create(e,"and"))}(t.filters);s&&(n.structuredQuery.where=s);const o=function(e){if(0!==e.length)return e.map((e=>function(e){return{field:Vi(e.field),direction:Ri(e.dir)}}(e)))}(t.orderBy);o&&(n.structuredQuery.orderBy=o);const a=di(e,t.limit);return null!==a&&(n.structuredQuery.limit=a),t.startAt&&(n.structuredQuery.startAt=function(e){return{before:e.inclusive,values:e.position}}(t.startAt)),t.endAt&&(n.structuredQuery.endAt=function(e){return{before:!e.inclusive,values:e.position}}(t.endAt)),{ct:n,parent:i}}function Li(e,t,n,r){const{ct:i,parent:s}=Ni(e,t),o={},a=[];let c=0;return n.forEach((e=>{const t=r?e.alias:"aggregate_"+c++;o[t]=e.alias,"count"===e.aggregateType?a.push({alias:t,count:{}}):"avg"===e.aggregateType?a.push({alias:t,avg:{field:Vi(e.fieldPath)}}):"sum"===e.aggregateType&&a.push({alias:t,sum:{field:Vi(e.fieldPath)}})})),{request:{structuredAggregationQuery:{aggregations:a,structuredQuery:i.structuredQuery},parent:i.parent},lt:o,parent:s}}function Oi(e){let t=Ei(e.parent);const n=e.structuredQuery,r=n.from?n.from.length:0;let i=null;if(r>0){w(1===r);const e=n.from[0];e.allDescendants?i=e.collectionId:t=t.child(e.collectionId)}let s=[];n.where&&(s=function(e){const t=Mi(e);return t instanceof tn&&sn(t)?t.getFilters():[t]}(n.where));let o=[];n.orderBy&&(o=function(e){return e.map((e=>function(e){return new Xt(qi(e.field),function(e){switch(e){case"ASCENDING":return"asc";case"DESCENDING":return"desc";default:return}}(e.direction))}(e)))}(n.orderBy));let a=null;n.limit&&(a=function(e){let t;return t="object"==typeof e?e.value:e,ve(t)?null:t}(n.limit));let c=null;n.startAt&&(c=function(e){const t=!!e.before,n=e.values||[];return new Ht(n,t)}(n.startAt));let u=null;return n.endAt&&(u=function(e){const t=!e.before,n=e.values||[];return new Ht(n,t)}(n.endAt)),Dn(t,i,o,s,a,"F",c,u)}function Mi(e){return void 0!==e.unaryFilter?function(e){switch(e.unaryFilter.op){case"IS_NAN":const t=qi(e.unaryFilter.field);return en.create(t,"==",{doubleValue:NaN});case"IS_NULL":const n=qi(e.unaryFilter.field);return en.create(n,"==",{nullValue:"NULL_VALUE"});case"IS_NOT_NAN":const r=qi(e.unaryFilter.field);return en.create(r,"!=",{doubleValue:NaN});case"IS_NOT_NULL":const i=qi(e.unaryFilter.field);return en.create(i,"!=",{nullValue:"NULL_VALUE"});default:return v()}}(e):void 0!==e.fieldFilter?function(e){return en.create(qi(e.fieldFilter.field),function(e){switch(e){case"EQUAL":return"==";case"NOT_EQUAL":return"!=";case"GREATER_THAN":return">";case"GREATER_THAN_OR_EQUAL":return">=";case"LESS_THAN":return"<";case"LESS_THAN_OR_EQUAL":return"<=";case"ARRAY_CONTAINS":return"array-contains";case"IN":return"in";case"NOT_IN":return"not-in";case"ARRAY_CONTAINS_ANY":return"array-contains-any";default:return v()}}(e.fieldFilter.op),e.fieldFilter.value)}(e):void 0!==e.compositeFilter?function(e){return tn.create(e.compositeFilter.filters.map((e=>Mi(e))),function(e){switch(e){case"AND":return"and";case"OR":return"or";default:return v()}}(e.compositeFilter.op))}(e):v()}function Ri(e){return ci[e]}function Pi(e){return ui[e]}function Fi(e){return li[e]}function Vi(e){return{fieldPath:e.canonicalString()}}function qi(e){return j.fromServerFormat(e.fieldPath)}function Bi(e){return e instanceof en?function(e){if("=="===e.op){if(Rt(e.value))return{unaryFilter:{field:Vi(e.field),op:"IS_NAN"}};if(Mt(e.value))return{unaryFilter:{field:Vi(e.field),op:"IS_NULL"}}}else if("!="===e.op){if(Rt(e.value))return{unaryFilter:{field:Vi(e.field),op:"IS_NOT_NAN"}};if(Mt(e.value))return{unaryFilter:{field:Vi(e.field),op:"IS_NOT_NULL"}}}return{fieldFilter:{field:Vi(e.field),op:Pi(e.op),value:e.value}}}(e):e instanceof tn?function(e){const t=e.getFilters().map((e=>Bi(e)));return 1===t.length?t[0]:{compositeFilter:{op:Fi(e.op),filters:t}}}(e):v()}function Ui(e){const t=[];return e.fields.forEach((e=>t.push(e.canonicalString()))),{fieldPaths:t}}function ji(e){return e.length>=4&&"projects"===e.get(0)&&"databases"===e.get(2)}class $i{constructor(e,t,n,r,i=V.min(),s=V.min(),o=lt.EMPTY_BYTE_STRING,a=null){this.target=e,this.targetId=t,this.purpose=n,this.sequenceNumber=r,this.snapshotVersion=i,this.lastLimboFreeSnapshotVersion=s,this.resumeToken=o,this.expectedCount=a}withSequenceNumber(e){return new $i(this.target,this.targetId,this.purpose,e,this.snapshotVersion,this.lastLimboFreeSnapshotVersion,this.resumeToken,this.expectedCount)}withResumeToken(e,t){return new $i(this.target,this.targetId,this.purpose,this.sequenceNumber,t,this.lastLimboFreeSnapshotVersion,e,null)}withExpectedCount(e){return new $i(this.target,this.targetId,this.purpose,this.sequenceNumber,this.snapshotVersion,this.lastLimboFreeSnapshotVersion,this.resumeToken,e)}withLastLimboFreeSnapshotVersion(e){return new $i(this.target,this.targetId,this.purpose,this.sequenceNumber,this.snapshotVersion,e,this.resumeToken,this.expectedCount)}}class zi{constructor(e){this.ht=e}}function Gi(e,t){const n=t.key,r={prefixPath:n.getCollectionPath().popLast().toArray(),collectionGroup:n.collectionGroup,documentId:n.path.lastSegment(),readTime:Ki(t.readTime),hasCommittedMutations:t.hasCommittedMutations};if(t.isFoundDocument())r.document=function(e,t){return{name:bi(e,t.key),fields:t.data.value.mapValue.fields,updateTime:fi(e,t.version.toTimestamp()),createTime:fi(e,t.createTime.toTimestamp())}}(e.ht,t);else if(t.isNoDocument())r.noDocument={path:n.path.toArray(),readTime:Qi(t.version)};else{if(!t.isUnknownDocument())return v();r.unknownDocument={path:n.path.toArray(),version:Qi(t.version)}}return r}function Ki(e){const t=e.toTimestamp();return[t.seconds,t.nanoseconds]}function Qi(e){const t=e.toTimestamp();return{seconds:t.seconds,nanoseconds:t.nanoseconds}}function Hi(e){const t=new F(e.seconds,e.nanoseconds);return V.fromTimestamp(t)}function Wi(e,t){const n=(t.baseMutations||[]).map((t=>Ai(e.ht,t)));for(let e=0;e<t.mutations.length-1;++e){const n=t.mutations[e];if(e+1<t.mutations.length&&void 0!==t.mutations[e+1].transform){const r=t.mutations[e+1];n.updateTransforms=r.transform.fieldTransforms,t.mutations.splice(e+1,1),++e}}const r=t.mutations.map((t=>Ai(e.ht,t))),i=F.fromMillis(t.localWriteTimeMs);return new Fr(t.batchId,i,n,r)}function Ji(e){const t=Hi(e.readTime),n=void 0!==e.lastLimboFreeSnapshotVersion?Hi(e.lastLimboFreeSnapshotVersion):V.min();let r;return r=function(e){return void 0!==e.documents}(e.query)?function(e){return w(1===e.documents.length),On(An(Ei(e.documents[0])))}(e.query):function(e){return On(Oi(e))}(e.query),new $i(r,e.targetId,"TargetPurposeListen",e.lastListenSequenceNumber,t,n,lt.fromBase64String(e.resumeToken))}function Xi(e,t){const n=Qi(t.snapshotVersion),r=Qi(t.lastLimboFreeSnapshotVersion);let i;i=En(t.target)?ki(e.ht,t.target):Ni(e.ht,t.target).ct;const s=t.resumeToken.toBase64();return{targetId:t.targetId,canonicalId:_n(t.target),readTime:n,resumeToken:s,lastListenSequenceNumber:t.sequenceNumber,lastLimboFreeSnapshotVersion:r,query:i}}function Yi(e){const t=Oi({parent:e.parent,structuredQuery:e.structuredQuery});return"LAST"===e.limitType?Fn(t,t.limit,"L"):t}function Zi(e,t){return new qr(t.largestBatchId,Ai(e.ht,t.overlayMutation))}function es(e,t){const n=t.path.lastSegment();return[e,_e(t.path.popLast()),n]}function ts(e,t,n,r){return{indexId:e,uid:t,sequenceNumber:n,readTime:Qi(r.readTime),documentKey:_e(r.documentKey.path),largestBatchId:r.largestBatchId}}class ns{getBundleMetadata(e,t){return rs(e).get(t).next((e=>{if(e)return function(e){return{id:e.bundleId,createTime:Hi(e.createTime),version:e.version}}(e)}))}saveBundleMetadata(e,t){return rs(e).put(function(e){return{bundleId:e.id,createTime:Qi(mi(e.createTime)),version:e.version}}(t))}getNamedQuery(e,t){return is(e).get(t).next((e=>{if(e)return function(e){return{name:e.name,query:Yi(e.bundledQuery),readTime:Hi(e.readTime)}}(e)}))}saveNamedQuery(e,t){return is(e).put(function(e){return{name:e.name,readTime:Qi(mi(e.readTime)),bundledQuery:e.bundledQuery}}(t))}}function rs(e){return Xe(e,"bundles")}function is(e){return Xe(e,"namedQueries")}class ss{constructor(e,t){this.serializer=e,this.userId=t}static Pt(e,t){const n=t.uid||"";return new ss(e,n)}getOverlay(e,t){return os(e).get(es(this.userId,t)).next((e=>e?Zi(this.serializer,e):null))}getOverlays(e,t){const n=Xn();return ie.forEach(t,(t=>this.getOverlay(e,t).next((e=>{null!==e&&n.set(t,e)})))).next((()=>n))}saveOverlays(e,t,n){const r=[];return n.forEach(((n,i)=>{const s=new qr(t,i);r.push(this.Tt(e,s))})),ie.waitFor(r)}removeOverlaysForBatchId(e,t,n){const r=new Set;t.forEach((e=>r.add(_e(e.getCollectionPath()))));const i=[];return r.forEach((t=>{const r=IDBKeyRange.bound([this.userId,t,n],[this.userId,t,n+1],!1,!0);i.push(os(e).j("collectionPathOverlayIndex",r))})),ie.waitFor(i)}getOverlaysForCollection(e,t,n){const r=Xn(),i=_e(t),s=IDBKeyRange.bound([this.userId,i,n],[this.userId,i,Number.POSITIVE_INFINITY],!0);return os(e).U("collectionPathOverlayIndex",s).next((e=>{for(const t of e){const e=Zi(this.serializer,t);r.set(e.getKey(),e)}return r}))}getOverlaysForCollectionGroup(e,t,n,r){const i=Xn();let s;const o=IDBKeyRange.bound([this.userId,t,n],[this.userId,t,Number.POSITIVE_INFINITY],!0);return os(e).J({index:"collectionGroupOverlayIndex",range:o},((e,t,n)=>{const o=Zi(this.serializer,t);i.size()<r||o.largestBatchId===s?(i.set(o.getKey(),o),s=o.largestBatchId):n.done()})).next((()=>i))}Tt(e,t){return os(e).put(function(e,t,n){const[r,i,s]=es(t,n.mutation.key);return{userId:t,collectionPath:i,documentId:s,collectionGroup:n.mutation.key.getCollectionGroup(),largestBatchId:n.largestBatchId,overlayMutation:Di(e.ht,n.mutation)}}(this.serializer,this.userId,t))}}function os(e){return Xe(e,"documentOverlays")}class as{It(e){return Xe(e,"globals")}getSessionToken(e){return this.It(e).get("sessionToken").next((e=>{const t=null==e?void 0:e.value;return t?lt.fromUint8Array(t):lt.EMPTY_BYTE_STRING}))}setSessionToken(e,t){return this.It(e).put({name:"sessionToken",value:t.toUint8Array()})}}class cs{constructor(){}Et(e,t){this.dt(e,t),t.At()}dt(e,t){if("nullValue"in e)this.Rt(t,5);else if("booleanValue"in e)this.Rt(t,10),t.Vt(e.booleanValue?1:0);else if("integerValue"in e)this.Rt(t,15),t.Vt(ft(e.integerValue));else if("doubleValue"in e){const n=ft(e.doubleValue);isNaN(n)?this.Rt(t,13):(this.Rt(t,15),we(n)?t.Vt(0):t.Vt(n))}else if("timestampValue"in e){let n=e.timestampValue;this.Rt(t,20),"string"==typeof n&&(n=dt(n)),t.ft(`${n.seconds||""}`),t.Vt(n.nanos||0)}else if("stringValue"in e)this.gt(e.stringValue,t),this.yt(t);else if("bytesValue"in e)this.Rt(t,30),t.wt(gt(e.bytesValue)),this.yt(t);else if("referenceValue"in e)this.St(e.referenceValue,t);else if("geoPointValue"in e){const n=e.geoPointValue;this.Rt(t,45),t.Vt(n.latitude||0),t.Vt(n.longitude||0)}else"mapValue"in e?qt(e)?this.Rt(t,Number.MAX_SAFE_INTEGER):Ft(e)?this.bt(e.mapValue,t):(this.Dt(e.mapValue,t),this.yt(t)):"arrayValue"in e?(this.vt(e.arrayValue,t),this.yt(t)):v()}gt(e,t){this.Rt(t,25),this.Ct(e,t)}Ct(e,t){t.ft(e)}Dt(e,t){const n=e.fields||{};this.Rt(t,55);for(const e of Object.keys(n))this.gt(e,t),this.dt(n[e],t)}bt(e,t){var n,r;const i=e.fields||{};this.Rt(t,53);const s="value",o=(null===(r=null===(n=i[s].arrayValue)||void 0===n?void 0:n.values)||void 0===r?void 0:r.length)||0;this.Rt(t,15),t.Vt(ft(o)),this.gt(s,t),this.dt(i[s],t)}vt(e,t){const n=e.values||[];this.Rt(t,50);for(const e of n)this.dt(e,t)}St(e,t){this.Rt(t,37),$.fromName(e).path.forEach((e=>{this.Rt(t,60),this.Ct(e,t)}))}Rt(e,t){e.Vt(t)}yt(e){e.Vt(2)}}function us(e){if(0===e)return 8;let t=0;return!(e>>4)&&(t+=4,e<<=4),!(e>>6)&&(t+=2,e<<=2),!(e>>7)&&(t+=1),t}function ls(e){const t=64-function(e){let t=0;for(let n=0;n<8;++n){const r=us(255&e[n]);if(t+=r,8!==r)break}return t}(e);return Math.ceil(t/8)}cs.Ft=new cs;class hs{constructor(){this.buffer=new Uint8Array(1024),this.position=0}Mt(e){const t=e[Symbol.iterator]();let n=t.next();for(;!n.done;)this.xt(n.value),n=t.next();this.Ot()}Nt(e){const t=e[Symbol.iterator]();let n=t.next();for(;!n.done;)this.Lt(n.value),n=t.next();this.Bt()}kt(e){for(const t of e){const e=t.charCodeAt(0);if(e<128)this.xt(e);else if(e<2048)this.xt(960|e>>>6),this.xt(128|63&e);else if(t<"\ud800"||"\udbff"<t)this.xt(480|e>>>12),this.xt(128|63&e>>>6),this.xt(128|63&e);else{const e=t.codePointAt(0);this.xt(240|e>>>18),this.xt(128|63&e>>>12),this.xt(128|63&e>>>6),this.xt(128|63&e)}}this.Ot()}qt(e){for(const t of e){const e=t.charCodeAt(0);if(e<128)this.Lt(e);else if(e<2048)this.Lt(960|e>>>6),this.Lt(128|63&e);else if(t<"\ud800"||"\udbff"<t)this.Lt(480|e>>>12),this.Lt(128|63&e>>>6),this.Lt(128|63&e);else{const e=t.codePointAt(0);this.Lt(240|e>>>18),this.Lt(128|63&e>>>12),this.Lt(128|63&e>>>6),this.Lt(128|63&e)}}this.Bt()}Qt(e){const t=this.Kt(e),n=ls(t);this.$t(1+n),this.buffer[this.position++]=255&n;for(let e=t.length-n;e<t.length;++e)this.buffer[this.position++]=255&t[e]}Ut(e){const t=this.Kt(e),n=ls(t);this.$t(1+n),this.buffer[this.position++]=~(255&n);for(let e=t.length-n;e<t.length;++e)this.buffer[this.position++]=~(255&t[e])}Wt(){this.Gt(255),this.Gt(255)}zt(){this.jt(255),this.jt(255)}reset(){this.position=0}seed(e){this.$t(e.length),this.buffer.set(e,this.position),this.position+=e.length}Ht(){return this.buffer.slice(0,this.position)}Kt(e){const t=function(e){const t=new DataView(new ArrayBuffer(8));return t.setFloat64(0,e,!1),new Uint8Array(t.buffer)}(e),n=!!(128&t[0]);t[0]^=n?255:128;for(let e=1;e<t.length;++e)t[e]^=n?255:0;return t}xt(e){const t=255&e;0===t?(this.Gt(0),this.Gt(255)):255===t?(this.Gt(255),this.Gt(0)):this.Gt(t)}Lt(e){const t=255&e;0===t?(this.jt(0),this.jt(255)):255===t?(this.jt(255),this.jt(0)):this.jt(e)}Ot(){this.Gt(0),this.Gt(1)}Bt(){this.jt(0),this.jt(1)}Gt(e){this.$t(1),this.buffer[this.position++]=e}jt(e){this.$t(1),this.buffer[this.position++]=~e}$t(e){const t=e+this.position;if(t<=this.buffer.length)return;let n=2*this.buffer.length;n<t&&(n=t);const r=new Uint8Array(n);r.set(this.buffer),this.buffer=r}}class ds{constructor(e){this.Jt=e}wt(e){this.Jt.Mt(e)}ft(e){this.Jt.kt(e)}Vt(e){this.Jt.Qt(e)}At(){this.Jt.Wt()}}class fs{constructor(e){this.Jt=e}wt(e){this.Jt.Nt(e)}ft(e){this.Jt.qt(e)}Vt(e){this.Jt.Ut(e)}At(){this.Jt.zt()}}class gs{constructor(){this.Jt=new hs,this.Yt=new ds(this.Jt),this.Zt=new fs(this.Jt)}seed(e){this.Jt.seed(e)}Xt(e){return 0===e?this.Yt:this.Zt}Ht(){return this.Jt.Ht()}reset(){this.Jt.reset()}}class ps{constructor(e,t,n,r){this.indexId=e,this.documentKey=t,this.arrayValue=n,this.directionalValue=r}en(){const e=this.directionalValue.length,t=0===e||255===this.directionalValue[e-1]?e+1:e,n=new Uint8Array(t);return n.set(this.directionalValue,0),t!==e?n.set([0],this.directionalValue.length):++n[n.length-1],new ps(this.indexId,this.documentKey,this.arrayValue,n)}}function ms(e,t){let n=e.indexId-t.indexId;return 0!==n?n:(n=ys(e.arrayValue,t.arrayValue),0!==n?n:(n=ys(e.directionalValue,t.directionalValue),0!==n?n:$.comparator(e.documentKey,t.documentKey)))}function ys(e,t){for(let n=0;n<e.length&&n<t.length;++n){const r=e[n]-t[n];if(0!==r)return r}return e.length-t.length}class vs{constructor(e){this.tn=new st(((e,t)=>j.comparator(e.field,t.field))),this.collectionId=null!=e.collectionGroup?e.collectionGroup:e.path.lastSegment(),this.nn=e.orderBy,this.rn=[];for(const t of e.filters){const e=t;e.isInequality()?this.tn=this.tn.add(e):this.rn.push(e)}}get sn(){return this.tn.size>1}on(e){if(w(e.collectionGroup===this.collectionId),this.sn)return!1;const t=G(e);if(void 0!==t&&!this._n(t))return!1;const n=K(e);let r=new Set,i=0,s=0;for(;i<n.length&&this._n(n[i]);++i)r=r.add(n[i].fieldPath.canonicalString());if(i===n.length)return!0;if(this.tn.size>0){const e=this.tn.getIterator().getNext();if(!r.has(e.field.canonicalString())){const t=n[i];if(!this.an(e,t)||!this.un(this.nn[s++],t))return!1}++i}for(;i<n.length;++i){const e=n[i];if(s>=this.nn.length||!this.un(this.nn[s++],e))return!1}return!0}cn(){if(this.sn)return null;let e=new st(j.comparator);const t=[];for(const n of this.rn)if(!n.field.isKeyField())if("array-contains"===n.op||"array-contains-any"===n.op)t.push(new H(n.field,2));else{if(e.has(n.field))continue;e=e.add(n.field),t.push(new H(n.field,0))}for(const n of this.nn)n.field.isKeyField()||e.has(n.field)||(e=e.add(n.field),t.push(new H(n.field,"asc"===n.dir?0:1)));return new z(z.UNKNOWN_ID,this.collectionId,t,J.empty())}_n(e){for(const t of this.rn)if(this.an(t,e))return!0;return!1}an(e,t){if(void 0===e||!e.field.isEqual(t.fieldPath))return!1;const n="array-contains"===e.op||"array-contains-any"===e.op;return 2===t.kind===n}un(e,t){return!!e.field.isEqual(t.fieldPath)&&(0===t.kind&&"asc"===e.dir||1===t.kind&&"desc"===e.dir)}}function ws(e){var t,n;if(w(e instanceof en||e instanceof tn),e instanceof en){if(e instanceof mn){const r=(null===(n=null===(t=e.value.arrayValue)||void 0===t?void 0:t.values)||void 0===n?void 0:n.map((t=>en.create(e.field,"==",t))))||[];return tn.create(r,"or")}return e}const r=e.filters.map((e=>ws(e)));return tn.create(r,e.op)}function bs(e){if(0===e.getFilters().length)return[];const t=Ts(ws(e));return w(Es(t)),_s(t)||Is(t)?[t]:t.getFilters()}function _s(e){return e instanceof en}function Is(e){return e instanceof tn&&sn(e)}function Es(e){return _s(e)||Is(e)||function(e){if(e instanceof tn&&rn(e)){for(const t of e.getFilters())if(!_s(t)&&!Is(t))return!1;return!0}return!1}(e)}function Ts(e){if(w(e instanceof en||e instanceof tn),e instanceof en)return e;if(1===e.filters.length)return Ts(e.filters[0]);const t=e.filters.map((e=>Ts(e)));let n=tn.create(t,e.op);return n=Cs(n),Es(n)?n:(w(n instanceof tn),w(nn(n)),w(n.filters.length>1),n.filters.reduce(((e,t)=>Ss(e,t))))}function Ss(e,t){let n;return w(e instanceof en||e instanceof tn),w(t instanceof en||t instanceof tn),n=e instanceof en?t instanceof en?function(e,t){return tn.create([e,t],"and")}(e,t):xs(e,t):t instanceof en?xs(t,e):function(e,t){if(w(e.filters.length>0&&t.filters.length>0),nn(e)&&nn(t))return un(e,t.getFilters());const n=rn(e)?e:t,r=rn(e)?t:e,i=n.filters.map((e=>Ss(e,r)));return tn.create(i,"or")}(e,t),Cs(n)}function xs(e,t){if(nn(t))return un(t,e.getFilters());{const n=t.filters.map((t=>Ss(e,t)));return tn.create(n,"or")}}function Cs(e){if(w(e instanceof en||e instanceof tn),e instanceof en)return e;const t=e.getFilters();if(1===t.length)return Cs(t[0]);if(on(e))return e;const n=t.map((e=>Cs(e))),r=[];return n.forEach((t=>{t instanceof en?r.push(t):t instanceof tn&&(t.op===e.op?r.push(...t.filters):r.push(t))})),1===r.length?r[0]:tn.create(r,e.op)}class Ds{constructor(){this.ln=new As}addToCollectionParentIndex(e,t){return this.ln.add(t),ie.resolve()}getCollectionParents(e,t){return ie.resolve(this.ln.getEntries(t))}addFieldIndex(e,t){return ie.resolve()}deleteFieldIndex(e,t){return ie.resolve()}deleteAllFieldIndexes(e){return ie.resolve()}createTargetIndexes(e,t){return ie.resolve()}getDocumentsMatchingTarget(e,t){return ie.resolve(null)}getIndexType(e,t){return ie.resolve(0)}getFieldIndexes(e,t){return ie.resolve([])}getNextCollectionGroupToUpdate(e){return ie.resolve(null)}getMinOffset(e,t){return ie.resolve(Z.min())}getMinOffsetFromCollectionGroup(e,t){return ie.resolve(Z.min())}updateCollectionGroup(e,t,n){return ie.resolve()}updateIndexEntries(e,t){return ie.resolve()}}class As{constructor(){this.index={}}add(e){const t=e.lastSegment(),n=e.popLast(),r=this.index[t]||new st(B.comparator),i=!r.has(n);return this.index[t]=r.add(n),i}has(e){const t=e.lastSegment(),n=e.popLast(),r=this.index[t];return r&&r.has(n)}getEntries(e){return(this.index[e]||new st(B.comparator)).toArray()}}const ks=new Uint8Array(0);class Ns{constructor(e,t){this.databaseId=t,this.hn=new As,this.Pn=new Gn((e=>_n(e)),((e,t)=>In(e,t))),this.uid=e.uid||""}addToCollectionParentIndex(e,t){if(!this.hn.has(t)){const n=t.lastSegment(),r=t.popLast();e.addOnCommittedListener((()=>{this.hn.add(t)}));const i={collectionId:n,parent:_e(r)};return Ls(e).put(i)}return ie.resolve()}getCollectionParents(e,t){const n=[],r=IDBKeyRange.bound([t,""],[P(t),""],!1,!0);return Ls(e).U(r).next((e=>{for(const r of e){if(r.collectionId!==t)break;n.push(Te(r.parent))}return n}))}addFieldIndex(e,t){const n=Ms(e),r=function(e){return{indexId:e.indexId,collectionGroup:e.collectionGroup,fields:e.fields.map((e=>[e.fieldPath.canonicalString(),e.kind]))}}(t);delete r.indexId;const i=n.add(r);if(t.indexState){const n=Rs(e);return i.next((e=>{n.put(ts(e,this.uid,t.indexState.sequenceNumber,t.indexState.offset))}))}return i.next()}deleteFieldIndex(e,t){const n=Ms(e),r=Rs(e),i=Os(e);return n.delete(t.indexId).next((()=>r.delete(IDBKeyRange.bound([t.indexId],[t.indexId+1],!1,!0)))).next((()=>i.delete(IDBKeyRange.bound([t.indexId],[t.indexId+1],!1,!0))))}deleteAllFieldIndexes(e){const t=Ms(e),n=Os(e),r=Rs(e);return t.j().next((()=>n.j())).next((()=>r.j()))}createTargetIndexes(e,t){return ie.forEach(this.Tn(t),(t=>this.getIndexType(e,t).next((n=>{if(0===n||1===n){const n=new vs(t).cn();if(null!=n)return this.addFieldIndex(e,n)}}))))}getDocumentsMatchingTarget(e,t){const n=Os(e);let r=!0;const i=new Map;return ie.forEach(this.Tn(t),(t=>this.In(e,t).next((e=>{r&&(r=!!e),i.set(t,e)})))).next((()=>{if(r){let e=nr();const r=[];return ie.forEach(i,((i,s)=>{g("IndexedDbIndexManager",`Using index ${function(e){return`id=${e.indexId}|cg=${e.collectionGroup}|f=${e.fields.map((e=>`${e.fieldPath}:${e.kind}`)).join(",")}`}(i)} to execute ${_n(t)}`);const o=function(e,t){const n=G(t);if(void 0===n)return null;for(const t of Tn(e,n.fieldPath))switch(t.op){case"array-contains-any":return t.value.arrayValue.values||[];case"array-contains":return[t.value]}return null}(s,i),a=function(e,t){const n=new Map;for(const r of K(t))for(const t of Tn(e,r.fieldPath))switch(t.op){case"==":case"in":n.set(r.fieldPath.canonicalString(),t.value);break;case"not-in":case"!=":return n.set(r.fieldPath.canonicalString(),t.value),Array.from(n.values())}return null}(s,i),c=function(e,t){const n=[];let r=!0;for(const i of K(t)){const t=0===i.kind?Sn(e,i.fieldPath,e.startAt):xn(e,i.fieldPath,e.startAt);n.push(t.value),r&&(r=t.inclusive)}return new Ht(n,r)}(s,i),u=function(e,t){const n=[];let r=!0;for(const i of K(t)){const t=0===i.kind?xn(e,i.fieldPath,e.endAt):Sn(e,i.fieldPath,e.endAt);n.push(t.value),r&&(r=t.inclusive)}return new Ht(n,r)}(s,i),l=this.En(i,s,c),h=this.En(i,s,u),d=this.dn(i,s,a),f=this.An(i.indexId,o,l,c.inclusive,h,u.inclusive,d);return ie.forEach(f,(i=>n.G(i,t.limit).next((t=>{t.forEach((t=>{const n=$.fromSegments(t.documentKey);e.has(n)||(e=e.add(n),r.push(n))}))}))))})).next((()=>r))}return ie.resolve(null)}))}Tn(e){let t=this.Pn.get(e);return t||(t=0===e.filters.length?[e]:bs(tn.create(e.filters,"and")).map((t=>bn(e.path,e.collectionGroup,e.orderBy,t.getFilters(),e.limit,e.startAt,e.endAt))),this.Pn.set(e,t),t)}An(e,t,n,r,i,s,o){const a=(null!=t?t.length:1)*Math.max(n.length,i.length),c=a/(null!=t?t.length:1),u=[];for(let l=0;l<a;++l){const a=t?this.Rn(t[l/c]):ks,h=this.Vn(e,a,n[l%c],r),d=this.mn(e,a,i[l%c],s),f=o.map((t=>this.Vn(e,a,t,!0)));u.push(...this.createRange(h,d,f))}return u}Vn(e,t,n,r){const i=new ps(e,$.empty(),t,n);return r?i:i.en()}mn(e,t,n,r){const i=new ps(e,$.empty(),t,n);return r?i.en():i}In(e,t){const n=new vs(t),r=null!=t.collectionGroup?t.collectionGroup:t.path.lastSegment();return this.getFieldIndexes(e,r).next((e=>{let t=null;for(const r of e)n.on(r)&&(!t||r.fields.length>t.fields.length)&&(t=r);return t}))}getIndexType(e,t){let n=2;const r=this.Tn(t);return ie.forEach(r,(t=>this.In(e,t).next((e=>{e?0!==n&&e.fields.length<function(e){let t=new st(j.comparator),n=!1;for(const r of e.filters)for(const e of r.getFlattenedFilters())e.field.isKeyField()||("array-contains"===e.op||"array-contains-any"===e.op?n=!0:t=t.add(e.field));for(const n of e.orderBy)n.field.isKeyField()||(t=t.add(n.field));return t.size+(n?1:0)}(t)&&(n=1):n=0})))).next((()=>function(e){return null!==e.limit}(t)&&r.length>1&&2===n?1:n))}fn(e,t){const n=new gs;for(const r of K(e)){const e=t.data.field(r.fieldPath);if(null==e)return null;const i=n.Xt(r.kind);cs.Ft.Et(e,i)}return n.Ht()}Rn(e){const t=new gs;return cs.Ft.Et(e,t.Xt(0)),t.Ht()}gn(e,t){const n=new gs;return cs.Ft.Et(Nt(this.databaseId,t),n.Xt(function(e){const t=K(e);return 0===t.length?0:t[t.length-1].kind}(e))),n.Ht()}dn(e,t,n){if(null===n)return[];let r=[];r.push(new gs);let i=0;for(const s of K(e)){const e=n[i++];for(const n of r)if(this.pn(t,s.fieldPath)&&Ot(e))r=this.yn(r,s,e);else{const t=n.Xt(s.kind);cs.Ft.Et(e,t)}}return this.wn(r)}En(e,t,n){return this.dn(e,t,n.position)}wn(e){const t=[];for(let n=0;n<e.length;++n)t[n]=e[n].Ht();return t}yn(e,t,n){const r=[...e],i=[];for(const e of n.arrayValue.values||[])for(const n of r){const r=new gs;r.seed(n.Ht()),cs.Ft.Et(e,r.Xt(t.kind)),i.push(r)}return i}pn(e,t){return!!e.filters.find((e=>e instanceof en&&e.field.isEqual(t)&&("in"===e.op||"not-in"===e.op)))}getFieldIndexes(e,t){const n=Ms(e),r=Rs(e);return(t?n.U("collectionGroupIndex",IDBKeyRange.bound(t,t)):n.U()).next((e=>{const t=[];return ie.forEach(e,(e=>r.get([e.indexId,this.uid]).next((n=>{t.push(function(e,t){const n=t?new J(t.sequenceNumber,new Z(Hi(t.readTime),new $(Te(t.documentKey)),t.largestBatchId)):J.empty(),r=e.fields.map((([e,t])=>new H(j.fromServerFormat(e),t)));return new z(e.indexId,e.collectionGroup,r,n)}(e,n))})))).next((()=>t))}))}getNextCollectionGroupToUpdate(e){return this.getFieldIndexes(e).next((e=>0===e.length?null:(e.sort(((e,t)=>{const n=e.indexState.sequenceNumber-t.indexState.sequenceNumber;return 0!==n?n:M(e.collectionGroup,t.collectionGroup)})),e[0].collectionGroup)))}updateCollectionGroup(e,t,n){const r=Ms(e),i=Rs(e);return this.Sn(e).next((e=>r.U("collectionGroupIndex",IDBKeyRange.bound(t,t)).next((t=>ie.forEach(t,(t=>i.put(ts(t.indexId,this.uid,e,n))))))))}updateIndexEntries(e,t){const n=new Map;return ie.forEach(t,((t,r)=>{const i=n.get(t.collectionGroup);return(i?ie.resolve(i):this.getFieldIndexes(e,t.collectionGroup)).next((i=>(n.set(t.collectionGroup,i),ie.forEach(i,(n=>this.bn(e,t,n).next((t=>{const i=this.Dn(r,n);return t.isEqual(i)?ie.resolve():this.vn(e,r,n,t,i)})))))))}))}Cn(e,t,n,r){return Os(e).put({indexId:r.indexId,uid:this.uid,arrayValue:r.arrayValue,directionalValue:r.directionalValue,orderedDocumentKey:this.gn(n,t.key),documentKey:t.key.path.toArray()})}Fn(e,t,n,r){return Os(e).delete([r.indexId,this.uid,r.arrayValue,r.directionalValue,this.gn(n,t.key),t.key.path.toArray()])}bn(e,t,n){const r=Os(e);let i=new st(ms);return r.J({index:"documentKeyIndex",range:IDBKeyRange.only([n.indexId,this.uid,this.gn(n,t)])},((e,r)=>{i=i.add(new ps(n.indexId,t,r.arrayValue,r.directionalValue))})).next((()=>i))}Dn(e,t){let n=new st(ms);const r=this.fn(t,e);if(null==r)return n;const i=G(t);if(null!=i){const s=e.data.field(i.fieldPath);if(Ot(s))for(const i of s.arrayValue.values||[])n=n.add(new ps(t.indexId,e.key,this.Rn(i),r))}else n=n.add(new ps(t.indexId,e.key,ks,r));return n}vn(e,t,n,r,i){g("IndexedDbIndexManager","Updating index entries for document '%s'",t.key);const s=[];return function(e,t,n,r,i){const s=e.getIterator(),o=t.getIterator();let a=at(s),c=at(o);for(;a||c;){let e=!1,t=!1;if(a&&c){const r=n(a,c);r<0?t=!0:r>0&&(e=!0)}else null!=a?t=!0:e=!0;e?(r(c),c=at(o)):t?(i(a),a=at(s)):(a=at(s),c=at(o))}}(r,i,ms,(r=>{s.push(this.Cn(e,t,n,r))}),(r=>{s.push(this.Fn(e,t,n,r))})),ie.waitFor(s)}Sn(e){let t=1;return Rs(e).J({index:"sequenceNumberIndex",reverse:!0,range:IDBKeyRange.upperBound([this.uid,Number.MAX_SAFE_INTEGER])},((e,n,r)=>{r.done(),t=n.sequenceNumber+1})).next((()=>t))}createRange(e,t,n){n=n.sort(((e,t)=>ms(e,t))).filter(((e,t,n)=>!t||0!==ms(e,n[t-1])));const r=[];r.push(e);for(const i of n){const n=ms(i,e),s=ms(i,t);if(0===n)r[0]=e.en();else if(n>0&&s<0)r.push(i),r.push(i.en());else if(s>0)break}r.push(t);const i=[];for(let e=0;e<r.length;e+=2){if(this.Mn(r[e],r[e+1]))return[];const t=[r[e].indexId,this.uid,r[e].arrayValue,r[e].directionalValue,ks,[]],n=[r[e+1].indexId,this.uid,r[e+1].arrayValue,r[e+1].directionalValue,ks,[]];i.push(IDBKeyRange.bound(t,n))}return i}Mn(e,t){return ms(e,t)>0}getMinOffsetFromCollectionGroup(e,t){return this.getFieldIndexes(e,t).next(Ps)}getMinOffset(e,t){return ie.mapArray(this.Tn(t),(t=>this.In(e,t).next((e=>e||v())))).next(Ps)}}function Ls(e){return Xe(e,"collectionParents")}function Os(e){return Xe(e,"indexEntries")}function Ms(e){return Xe(e,"indexConfiguration")}function Rs(e){return Xe(e,"indexState")}function Ps(e){w(0!==e.length);let t=e[0].indexState.offset,n=t.largestBatchId;for(let r=1;r<e.length;r++){const i=e[r].indexState.offset;ee(i,t)<0&&(t=i),n<i.largestBatchId&&(n=i.largestBatchId)}return new Z(t.readTime,t.documentKey,n)}const Fs={didRun:!1,sequenceNumbersCollected:0,targetsRemoved:0,documentsRemoved:0};class Vs{static withCacheSize(e){return new Vs(e,Vs.DEFAULT_COLLECTION_PERCENTILE,Vs.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT)}constructor(e,t,n){this.cacheSizeCollectionThreshold=e,this.percentileToCollect=t,this.maximumSequenceNumbersToCollect=n}}function qs(e,t,n){const r=e.store("mutations"),i=e.store("documentMutations"),s=[],o=IDBKeyRange.only(n.batchId);let a=0;const c=r.J({range:o},((e,t,n)=>(a++,n.delete())));s.push(c.next((()=>{w(1===a)})));const u=[];for(const e of n.mutations){const r=Ce(t,e.key.path,n.batchId);s.push(i.delete(r)),u.push(e.key)}return ie.waitFor(s).next((()=>u))}function Bs(e){if(!e)return 0;let t;if(e.document)t=e.document;else if(e.unknownDocument)t=e.unknownDocument;else{if(!e.noDocument)throw v();t=e.noDocument}return JSON.stringify(t).length}Vs.DEFAULT_COLLECTION_PERCENTILE=10,Vs.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT=1e3,Vs.DEFAULT=new Vs(41943040,Vs.DEFAULT_COLLECTION_PERCENTILE,Vs.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT),Vs.DISABLED=new Vs(-1,0,0);class Us{constructor(e,t,n,r){this.userId=e,this.serializer=t,this.indexManager=n,this.referenceDelegate=r,this.xn={}}static Pt(e,t,n,r){w(""!==e.uid);const i=e.isAuthenticated()?e.uid:"";return new Us(i,t,n,r)}checkEmpty(e){let t=!0;const n=IDBKeyRange.bound([this.userId,Number.NEGATIVE_INFINITY],[this.userId,Number.POSITIVE_INFINITY]);return $s(e).J({index:"userMutationsIndex",range:n},((e,n,r)=>{t=!1,r.done()})).next((()=>t))}addMutationBatch(e,t,n,r){const i=zs(e),s=$s(e);return s.add({}).next((o=>{w("number"==typeof o);const a=new Fr(o,t,n,r),c=function(e,t,n){const r=n.baseMutations.map((t=>Di(e.ht,t))),i=n.mutations.map((t=>Di(e.ht,t)));return{userId:t,batchId:n.batchId,localWriteTimeMs:n.localWriteTime.toMillis(),baseMutations:r,mutations:i}}(this.serializer,this.userId,a),u=[];let l=new st(((e,t)=>M(e.canonicalString(),t.canonicalString())));for(const e of r){const t=Ce(this.userId,e.key.path,o);l=l.add(e.key.path.popLast()),u.push(s.put(c)),u.push(i.put(t,De))}return l.forEach((t=>{u.push(this.indexManager.addToCollectionParentIndex(e,t))})),e.addOnCommittedListener((()=>{this.xn[o]=a.keys()})),ie.waitFor(u).next((()=>a))}))}lookupMutationBatch(e,t){return $s(e).get(t).next((e=>e?(w(e.userId===this.userId),Wi(this.serializer,e)):null))}On(e,t){return this.xn[t]?ie.resolve(this.xn[t]):this.lookupMutationBatch(e,t).next((e=>{if(e){const n=e.keys();return this.xn[t]=n,n}return null}))}getNextMutationBatchAfterBatchId(e,t){const n=t+1,r=IDBKeyRange.lowerBound([this.userId,n]);let i=null;return $s(e).J({index:"userMutationsIndex",range:r},((e,t,r)=>{t.userId===this.userId&&(w(t.batchId>=n),i=Wi(this.serializer,t)),r.done()})).next((()=>i))}getHighestUnacknowledgedBatchId(e){const t=IDBKeyRange.upperBound([this.userId,Number.POSITIVE_INFINITY]);let n=-1;return $s(e).J({index:"userMutationsIndex",range:t,reverse:!0},((e,t,r)=>{n=t.batchId,r.done()})).next((()=>n))}getAllMutationBatches(e){const t=IDBKeyRange.bound([this.userId,-1],[this.userId,Number.POSITIVE_INFINITY]);return $s(e).U("userMutationsIndex",t).next((e=>e.map((e=>Wi(this.serializer,e)))))}getAllMutationBatchesAffectingDocumentKey(e,t){const n=xe(this.userId,t.path),r=IDBKeyRange.lowerBound(n),i=[];return zs(e).J({range:r},((n,r,s)=>{const[o,a,c]=n,u=Te(a);if(o===this.userId&&t.path.isEqual(u))return $s(e).get(c).next((e=>{if(!e)throw v();w(e.userId===this.userId),i.push(Wi(this.serializer,e))}));s.done()})).next((()=>i))}getAllMutationBatchesAffectingDocumentKeys(e,t){let n=new st(M);const r=[];return t.forEach((t=>{const i=xe(this.userId,t.path),s=IDBKeyRange.lowerBound(i),o=zs(e).J({range:s},((e,r,i)=>{const[s,o,a]=e,c=Te(o);s===this.userId&&t.path.isEqual(c)?n=n.add(a):i.done()}));r.push(o)})),ie.waitFor(r).next((()=>this.Nn(e,n)))}getAllMutationBatchesAffectingQuery(e,t){const n=t.path,r=n.length+1,i=xe(this.userId,n),s=IDBKeyRange.lowerBound(i);let o=new st(M);return zs(e).J({range:s},((e,t,i)=>{const[s,a,c]=e,u=Te(a);s===this.userId&&n.isPrefixOf(u)?u.length===r&&(o=o.add(c)):i.done()})).next((()=>this.Nn(e,o)))}Nn(e,t){const n=[],r=[];return t.forEach((t=>{r.push($s(e).get(t).next((e=>{if(null===e)throw v();w(e.userId===this.userId),n.push(Wi(this.serializer,e))})))})),ie.waitFor(r).next((()=>n))}removeMutationBatch(e,t){return qs(e._e,this.userId,t).next((n=>(e.addOnCommittedListener((()=>{this.Ln(t.batchId)})),ie.forEach(n,(t=>this.referenceDelegate.markPotentiallyOrphaned(e,t))))))}Ln(e){delete this.xn[e]}performConsistencyCheck(e){return this.checkEmpty(e).next((t=>{if(!t)return ie.resolve();const n=IDBKeyRange.lowerBound(function(e){return[e]}(this.userId)),r=[];return zs(e).J({range:n},((e,t,n)=>{if(e[0]===this.userId){const t=Te(e[1]);r.push(t)}else n.done()})).next((()=>{w(0===r.length)}))}))}containsKey(e,t){return js(e,this.userId,t)}Bn(e){return Gs(e).get(this.userId).next((e=>e||{userId:this.userId,lastAcknowledgedBatchId:-1,lastStreamToken:""}))}}function js(e,t,n){const r=xe(t,n.path),i=r[1],s=IDBKeyRange.lowerBound(r);let o=!1;return zs(e).J({range:s,H:!0},((e,n,r)=>{const[s,a,c]=e;s===t&&a===i&&(o=!0),r.done()})).next((()=>o))}function $s(e){return Xe(e,"mutations")}function zs(e){return Xe(e,"documentMutations")}function Gs(e){return Xe(e,"mutationQueues")}class Ks{constructor(e){this.kn=e}next(){return this.kn+=2,this.kn}static qn(){return new Ks(0)}static Qn(){return new Ks(-1)}}class Qs{constructor(e,t){this.referenceDelegate=e,this.serializer=t}allocateTargetId(e){return this.Kn(e).next((t=>{const n=new Ks(t.highestTargetId);return t.highestTargetId=n.next(),this.$n(e,t).next((()=>t.highestTargetId))}))}getLastRemoteSnapshotVersion(e){return this.Kn(e).next((e=>V.fromTimestamp(new F(e.lastRemoteSnapshotVersion.seconds,e.lastRemoteSnapshotVersion.nanoseconds))))}getHighestSequenceNumber(e){return this.Kn(e).next((e=>e.highestListenSequenceNumber))}setTargetsMetadata(e,t,n){return this.Kn(e).next((r=>(r.highestListenSequenceNumber=t,n&&(r.lastRemoteSnapshotVersion=n.toTimestamp()),t>r.highestListenSequenceNumber&&(r.highestListenSequenceNumber=t),this.$n(e,r))))}addTargetData(e,t){return this.Un(e,t).next((()=>this.Kn(e).next((n=>(n.targetCount+=1,this.Wn(t,n),this.$n(e,n))))))}updateTargetData(e,t){return this.Un(e,t)}removeTargetData(e,t){return this.removeMatchingKeysForTargetId(e,t.targetId).next((()=>Hs(e).delete(t.targetId))).next((()=>this.Kn(e))).next((t=>(w(t.targetCount>0),t.targetCount-=1,this.$n(e,t))))}removeTargets(e,t,n){let r=0;const i=[];return Hs(e).J(((s,o)=>{const a=Ji(o);a.sequenceNumber<=t&&null===n.get(a.targetId)&&(r++,i.push(this.removeTargetData(e,a)))})).next((()=>ie.waitFor(i))).next((()=>r))}forEachTarget(e,t){return Hs(e).J(((e,n)=>{const r=Ji(n);t(r)}))}Kn(e){return Ws(e).get("targetGlobalKey").next((e=>(w(null!==e),e)))}$n(e,t){return Ws(e).put("targetGlobalKey",t)}Un(e,t){return Hs(e).put(Xi(this.serializer,t))}Wn(e,t){let n=!1;return e.targetId>t.highestTargetId&&(t.highestTargetId=e.targetId,n=!0),e.sequenceNumber>t.highestListenSequenceNumber&&(t.highestListenSequenceNumber=e.sequenceNumber,n=!0),n}getTargetCount(e){return this.Kn(e).next((e=>e.targetCount))}getTargetData(e,t){const n=_n(t),r=IDBKeyRange.bound([n,Number.NEGATIVE_INFINITY],[n,Number.POSITIVE_INFINITY]);let i=null;return Hs(e).J({range:r,index:"queryTargetsIndex"},((e,n,r)=>{const s=Ji(n);In(t,s.target)&&(i=s,r.done())})).next((()=>i))}addMatchingKeys(e,t,n){const r=[],i=Js(e);return t.forEach((t=>{const s=_e(t.path);r.push(i.put({targetId:n,path:s})),r.push(this.referenceDelegate.addReference(e,n,t))})),ie.waitFor(r)}removeMatchingKeys(e,t,n){const r=Js(e);return ie.forEach(t,(t=>{const i=_e(t.path);return ie.waitFor([r.delete([n,i]),this.referenceDelegate.removeReference(e,n,t)])}))}removeMatchingKeysForTargetId(e,t){const n=Js(e),r=IDBKeyRange.bound([t],[t+1],!1,!0);return n.delete(r)}getMatchingKeysForTargetId(e,t){const n=IDBKeyRange.bound([t],[t+1],!1,!0),r=Js(e);let i=nr();return r.J({range:n,H:!0},((e,t,n)=>{const r=Te(e[1]),s=new $(r);i=i.add(s)})).next((()=>i))}containsKey(e,t){const n=_e(t.path),r=IDBKeyRange.bound([n],[P(n)],!1,!0);let i=0;return Js(e).J({index:"documentTargetsIndex",H:!0,range:r},(([e,t],n,r)=>{0!==e&&(i++,r.done())})).next((()=>i>0))}ut(e,t){return Hs(e).get(t).next((e=>e?Ji(e):null))}}function Hs(e){return Xe(e,"targets")}function Ws(e){return Xe(e,"targetGlobal")}function Js(e){return Xe(e,"targetDocuments")}function Xs([e,t],[n,r]){const i=M(e,n);return 0===i?M(t,r):i}class Ys{constructor(e){this.Gn=e,this.buffer=new st(Xs),this.zn=0}jn(){return++this.zn}Hn(e){const t=[e,this.jn()];if(this.buffer.size<this.Gn)this.buffer=this.buffer.add(t);else{const e=this.buffer.last();Xs(t,e)<0&&(this.buffer=this.buffer.delete(e).add(t))}}get maxValue(){return this.buffer.last()[0]}}class Zs{constructor(e,t,n){this.garbageCollector=e,this.asyncQueue=t,this.localStore=n,this.Jn=null}start(){-1!==this.garbageCollector.params.cacheSizeCollectionThreshold&&this.Yn(6e4)}stop(){this.Jn&&(this.Jn.cancel(),this.Jn=null)}get started(){return null!==this.Jn}Yn(e){g("LruGarbageCollector",`Garbage collection scheduled in ${e}ms`),this.Jn=this.asyncQueue.enqueueAfterDelay("lru_garbage_collection",e,(async()=>{this.Jn=null;try{await this.localStore.collectGarbage(this.garbageCollector)}catch(e){le(e)?g("LruGarbageCollector","Ignoring IndexedDB error during garbage collection: ",e):await re(e)}await this.Yn(3e5)}))}}class eo{constructor(e,t){this.Zn=e,this.params=t}calculateTargetCount(e,t){return this.Zn.Xn(e).next((e=>Math.floor(t/100*e)))}nthSequenceNumber(e,t){if(0===t)return ie.resolve(ye.oe);const n=new Ys(t);return this.Zn.forEachTarget(e,(e=>n.Hn(e.sequenceNumber))).next((()=>this.Zn.er(e,(e=>n.Hn(e))))).next((()=>n.maxValue))}removeTargets(e,t,n){return this.Zn.removeTargets(e,t,n)}removeOrphanedDocuments(e,t){return this.Zn.removeOrphanedDocuments(e,t)}collect(e,t){return-1===this.params.cacheSizeCollectionThreshold?(g("LruGarbageCollector","Garbage collection skipped; disabled"),ie.resolve(Fs)):this.getCacheSize(e).next((n=>n<this.params.cacheSizeCollectionThreshold?(g("LruGarbageCollector",`Garbage collection skipped; Cache size ${n} is lower than threshold ${this.params.cacheSizeCollectionThreshold}`),Fs):this.tr(e,t)))}getCacheSize(e){return this.Zn.getCacheSize(e)}tr(e,t){let n,r,i,o,a,c,u;const l=Date.now();return this.calculateTargetCount(e,this.params.percentileToCollect).next((t=>(t>this.params.maximumSequenceNumbersToCollect?(g("LruGarbageCollector",`Capping sequence numbers to collect down to the maximum of ${this.params.maximumSequenceNumbersToCollect} from ${t}`),r=this.params.maximumSequenceNumbersToCollect):r=t,o=Date.now(),this.nthSequenceNumber(e,r)))).next((r=>(n=r,a=Date.now(),this.removeTargets(e,n,t)))).next((t=>(i=t,c=Date.now(),this.removeOrphanedDocuments(e,n)))).next((e=>(u=Date.now(),f()<=s.LogLevel.DEBUG&&g("LruGarbageCollector",`LRU Garbage Collection\n\tCounted targets in ${o-l}ms\n\tDetermined least recently used ${r} in `+(a-o)+"ms\n"+`\tRemoved ${i} targets in `+(c-a)+"ms\n"+`\tRemoved ${e} documents in `+(u-c)+"ms\n"+`Total Duration: ${u-l}ms`),ie.resolve({didRun:!0,sequenceNumbersCollected:r,targetsRemoved:i,documentsRemoved:e}))))}}function to(e,t){return new eo(e,t)}class no{constructor(e,t){this.db=e,this.garbageCollector=to(this,t)}Xn(e){const t=this.nr(e);return this.db.getTargetCache().getTargetCount(e).next((e=>t.next((t=>e+t))))}nr(e){let t=0;return this.er(e,(e=>{t++})).next((()=>t))}forEachTarget(e,t){return this.db.getTargetCache().forEachTarget(e,t)}er(e,t){return this.rr(e,((e,n)=>t(n)))}addReference(e,t,n){return ro(e,n)}removeReference(e,t,n){return ro(e,n)}removeTargets(e,t,n){return this.db.getTargetCache().removeTargets(e,t,n)}markPotentiallyOrphaned(e,t){return ro(e,t)}ir(e,t){return function(e,t){let n=!1;return Gs(e).Y((r=>js(e,r,t).next((e=>(e&&(n=!0),ie.resolve(!e)))))).next((()=>n))}(e,t)}removeOrphanedDocuments(e,t){const n=this.db.getRemoteDocumentCache().newChangeBuffer(),r=[];let i=0;return this.rr(e,((s,o)=>{if(o<=t){const t=this.ir(e,s).next((t=>{if(!t)return i++,n.getEntry(e,s).next((()=>(n.removeEntry(s,V.min()),Js(e).delete(function(e){return[0,_e(e.path)]}(s)))))}));r.push(t)}})).next((()=>ie.waitFor(r))).next((()=>n.apply(e))).next((()=>i))}removeTarget(e,t){const n=t.withSequenceNumber(e.currentSequenceNumber);return this.db.getTargetCache().updateTargetData(e,n)}updateLimboDocument(e,t){return ro(e,t)}rr(e,t){const n=Js(e);let r,i=ye.oe;return n.J({index:"documentTargetsIndex"},(([e,n],{path:s,sequenceNumber:o})=>{0===e?(i!==ye.oe&&t(new $(Te(r)),i),i=o,r=s):i=ye.oe})).next((()=>{i!==ye.oe&&t(new $(Te(r)),i)}))}getCacheSize(e){return this.db.getRemoteDocumentCache().getSize(e)}}function ro(e,t){return Js(e).put(function(e,t){return{targetId:0,path:_e(e.path),sequenceNumber:t}}(t,e.currentSequenceNumber))}class io{constructor(){this.changes=new Gn((e=>e.toString()),((e,t)=>e.isEqual(t))),this.changesApplied=!1}addEntry(e){this.assertNotApplied(),this.changes.set(e.key,e)}removeEntry(e,t){this.assertNotApplied(),this.changes.set(e,Qt.newInvalidDocument(e).setReadTime(t))}getEntry(e,t){this.assertNotApplied();const n=this.changes.get(t);return void 0!==n?ie.resolve(n):this.getFromCache(e,t)}getEntries(e,t){return this.getAllFromCache(e,t)}apply(e){return this.assertNotApplied(),this.changesApplied=!0,this.applyChanges(e)}assertNotApplied(){}}class so{constructor(e){this.serializer=e}setIndexManager(e){this.indexManager=e}addEntry(e,t,n){return uo(e).put(n)}removeEntry(e,t,n){return uo(e).delete(function(e,t){const n=e.path.toArray();return[n.slice(0,n.length-2),n[n.length-2],Ki(t),n[n.length-1]]}(t,n))}updateMetadata(e,t){return this.getMetadata(e).next((n=>(n.byteSize+=t,this.sr(e,n))))}getEntry(e,t){let n=Qt.newInvalidDocument(t);return uo(e).J({index:"documentKeyIndex",range:IDBKeyRange.only(lo(t))},((e,r)=>{n=this._r(t,r)})).next((()=>n))}ar(e,t){let n={size:0,document:Qt.newInvalidDocument(t)};return uo(e).J({index:"documentKeyIndex",range:IDBKeyRange.only(lo(t))},((e,r)=>{n={document:this._r(t,r),size:Bs(r)}})).next((()=>n))}getEntries(e,t){let n=Qn();return this.ur(e,t,((e,t)=>{const r=this._r(e,t);n=n.insert(e,r)})).next((()=>n))}cr(e,t){let n=Qn(),r=new nt($.comparator);return this.ur(e,t,((e,t)=>{const i=this._r(e,t);n=n.insert(e,i),r=r.insert(e,Bs(t))})).next((()=>({documents:n,lr:r})))}ur(e,t,n){if(t.isEmpty())return ie.resolve();let r=new st(fo);t.forEach((e=>r=r.add(e)));const i=IDBKeyRange.bound(lo(r.first()),lo(r.last())),s=r.getIterator();let o=s.getNext();return uo(e).J({index:"documentKeyIndex",range:i},((e,t,r)=>{const i=$.fromSegments([...t.prefixPath,t.collectionGroup,t.documentId]);for(;o&&fo(o,i)<0;)n(o,null),o=s.getNext();o&&o.isEqual(i)&&(n(o,t),o=s.hasNext()?s.getNext():null),o?r.$(lo(o)):r.done()})).next((()=>{for(;o;)n(o,null),o=s.hasNext()?s.getNext():null}))}getDocumentsMatchingQuery(e,t,n,r,i){const s=t.path,o=[s.popLast().toArray(),s.lastSegment(),Ki(n.readTime),n.documentKey.path.isEmpty()?"":n.documentKey.path.lastSegment()],a=[s.popLast().toArray(),s.lastSegment(),[Number.MAX_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],""];return uo(e).U(IDBKeyRange.bound(o,a,!0)).next((e=>{null==i||i.incrementDocumentReadCount(e.length);let n=Qn();for(const i of e){const e=this._r($.fromSegments(i.prefixPath.concat(i.collectionGroup,i.documentId)),i);e.isFoundDocument()&&(Un(t,e)||r.has(e.key))&&(n=n.insert(e.key,e))}return n}))}getAllFromCollectionGroup(e,t,n,r){let i=Qn();const s=ho(t,n),o=ho(t,Z.max());return uo(e).J({index:"collectionGroupIndex",range:IDBKeyRange.bound(s,o,!0)},((e,t,n)=>{const s=this._r($.fromSegments(t.prefixPath.concat(t.collectionGroup,t.documentId)),t);i=i.insert(s.key,s),i.size===r&&n.done()})).next((()=>i))}newChangeBuffer(e){return new ao(this,!!e&&e.trackRemovals)}getSize(e){return this.getMetadata(e).next((e=>e.byteSize))}getMetadata(e){return co(e).get("remoteDocumentGlobalKey").next((e=>(w(!!e),e)))}sr(e,t){return co(e).put("remoteDocumentGlobalKey",t)}_r(e,t){if(t){const e=function(e,t){let n;if(t.document)n=Ci(e.ht,t.document,!!t.hasCommittedMutations);else if(t.noDocument){const e=$.fromSegments(t.noDocument.path),r=Hi(t.noDocument.readTime);n=Qt.newNoDocument(e,r),t.hasCommittedMutations&&n.setHasCommittedMutations()}else{if(!t.unknownDocument)return v();{const e=$.fromSegments(t.unknownDocument.path),r=Hi(t.unknownDocument.version);n=Qt.newUnknownDocument(e,r)}}return t.readTime&&n.setReadTime(function(e){const t=new F(e[0],e[1]);return V.fromTimestamp(t)}(t.readTime)),n}(this.serializer,t);if(!e.isNoDocument()||!e.version.isEqual(V.min()))return e}return Qt.newInvalidDocument(e)}}function oo(e){return new so(e)}class ao extends io{constructor(e,t){super(),this.hr=e,this.trackRemovals=t,this.Pr=new Gn((e=>e.toString()),((e,t)=>e.isEqual(t)))}applyChanges(e){const t=[];let n=0,r=new st(((e,t)=>M(e.canonicalString(),t.canonicalString())));return this.changes.forEach(((i,s)=>{const o=this.Pr.get(i);if(t.push(this.hr.removeEntry(e,i,o.readTime)),s.isValidDocument()){const a=Gi(this.hr.serializer,s);r=r.add(i.path.popLast());const c=Bs(a);n+=c-o.size,t.push(this.hr.addEntry(e,i,a))}else if(n-=o.size,this.trackRemovals){const n=Gi(this.hr.serializer,s.convertToNoDocument(V.min()));t.push(this.hr.addEntry(e,i,n))}})),r.forEach((n=>{t.push(this.hr.indexManager.addToCollectionParentIndex(e,n))})),t.push(this.hr.updateMetadata(e,n)),ie.waitFor(t)}getFromCache(e,t){return this.hr.ar(e,t).next((e=>(this.Pr.set(t,{size:e.size,readTime:e.document.readTime}),e.document)))}getAllFromCache(e,t){return this.hr.cr(e,t).next((({documents:e,lr:t})=>(t.forEach(((t,n)=>{this.Pr.set(t,{size:n,readTime:e.get(t).readTime})})),e)))}}function co(e){return Xe(e,"remoteDocumentGlobal")}function uo(e){return Xe(e,"remoteDocumentsV14")}function lo(e){const t=e.path.toArray();return[t.slice(0,t.length-2),t[t.length-2],t[t.length-1]]}function ho(e,t){const n=t.documentKey.path.toArray();return[e,Ki(t.readTime),n.slice(0,n.length-2),n.length>0?n[n.length-1]:""]}function fo(e,t){const n=e.path.toArray(),r=t.path.toArray();let i=0;for(let e=0;e<n.length-2&&e<r.length-2;++e)if(i=M(n[e],r[e]),i)return i;return i=M(n.length,r.length),i||(i=M(n[n.length-2],r[r.length-2]),i||M(n[n.length-1],r[r.length-1]))}class go{constructor(e,t){this.overlayedDocument=e,this.mutatedFields=t}}class po{constructor(e,t,n,r){this.remoteDocumentCache=e,this.mutationQueue=t,this.documentOverlayCache=n,this.indexManager=r}getDocument(e,t){let n=null;return this.documentOverlayCache.getOverlay(e,t).next((r=>(n=r,this.remoteDocumentCache.getEntry(e,t)))).next((e=>(null!==n&&Cr(n.mutation,e,ct.empty(),F.now()),e)))}getDocuments(e,t){return this.remoteDocumentCache.getEntries(e,t).next((t=>this.getLocalViewOfDocuments(e,t,nr()).next((()=>t))))}getLocalViewOfDocuments(e,t,n=nr()){const r=Xn();return this.populateOverlays(e,r,t).next((()=>this.computeViews(e,t,r,n).next((e=>{let t=Wn();return e.forEach(((e,n)=>{t=t.insert(e,n.overlayedDocument)})),t}))))}getOverlayedDocuments(e,t){const n=Xn();return this.populateOverlays(e,n,t).next((()=>this.computeViews(e,t,n,nr())))}populateOverlays(e,t,n){const r=[];return n.forEach((e=>{t.has(e)||r.push(e)})),this.documentOverlayCache.getOverlays(e,r).next((e=>{e.forEach(((e,n)=>{t.set(e,n)}))}))}computeViews(e,t,n,r){let i=Qn();const s=Zn(),o=Zn();return t.forEach(((e,t)=>{const o=n.get(t.key);r.has(t.key)&&(void 0===o||o.mutation instanceof Nr)?i=i.insert(t.key,t):void 0!==o?(s.set(t.key,o.mutation.getFieldMask()),Cr(o.mutation,t,o.mutation.getFieldMask(),F.now())):s.set(t.key,ct.empty())})),this.recalculateAndSaveOverlays(e,i).next((e=>(e.forEach(((e,t)=>s.set(e,t))),t.forEach(((e,t)=>{var n;return o.set(e,new go(t,null!==(n=s.get(e))&&void 0!==n?n:null))})),o)))}recalculateAndSaveOverlays(e,t){const n=Zn();let r=new nt(((e,t)=>e-t)),i=nr();return this.mutationQueue.getAllMutationBatchesAffectingDocumentKeys(e,t).next((e=>{for(const i of e)i.keys().forEach((e=>{const s=t.get(e);if(null===s)return;let o=n.get(e)||ct.empty();o=i.applyToLocalView(s,o),n.set(e,o);const a=(r.get(i.batchId)||nr()).add(e);r=r.insert(i.batchId,a)}))})).next((()=>{const s=[],o=r.getReverseIterator();for(;o.hasNext();){const r=o.getNext(),a=r.key,c=r.value,u=Yn();c.forEach((e=>{if(!i.has(e)){const r=Sr(t.get(e),n.get(e));null!==r&&u.set(e,r),i=i.add(e)}})),s.push(this.documentOverlayCache.saveOverlays(e,a,u))}return ie.waitFor(s)})).next((()=>n))}recalculateAndSaveOverlaysForDocumentKeys(e,t){return this.remoteDocumentCache.getEntries(e,t).next((t=>this.recalculateAndSaveOverlays(e,t)))}getDocumentsMatchingQuery(e,t,n,r){return function(e){return $.isDocumentKey(e.path)&&null===e.collectionGroup&&0===e.filters.length}(t)?this.getDocumentsMatchingDocumentQuery(e,t.path):Nn(t)?this.getDocumentsMatchingCollectionGroupQuery(e,t,n,r):this.getDocumentsMatchingCollectionQuery(e,t,n,r)}getNextDocuments(e,t,n,r){return this.remoteDocumentCache.getAllFromCollectionGroup(e,t,n,r).next((i=>{const s=r-i.size>0?this.documentOverlayCache.getOverlaysForCollectionGroup(e,t,n.largestBatchId,r-i.size):ie.resolve(Xn());let o=-1,a=i;return s.next((t=>ie.forEach(t,((t,n)=>(o<n.largestBatchId&&(o=n.largestBatchId),i.get(t)?ie.resolve():this.remoteDocumentCache.getEntry(e,t).next((e=>{a=a.insert(t,e)}))))).next((()=>this.populateOverlays(e,t,i))).next((()=>this.computeViews(e,a,t,nr()))).next((e=>({batchId:o,changes:Jn(e)})))))}))}getDocumentsMatchingDocumentQuery(e,t){return this.getDocument(e,new $(t)).next((e=>{let t=Wn();return e.isFoundDocument()&&(t=t.insert(e.key,e)),t}))}getDocumentsMatchingCollectionGroupQuery(e,t,n,r){const i=t.collectionGroup;let s=Wn();return this.indexManager.getCollectionParents(e,i).next((o=>ie.forEach(o,(o=>{const a=function(e,t){return new Cn(t,null,e.explicitOrderBy.slice(),e.filters.slice(),e.limit,e.limitType,e.startAt,e.endAt)}(t,o.child(i));return this.getDocumentsMatchingCollectionQuery(e,a,n,r).next((e=>{e.forEach(((e,t)=>{s=s.insert(e,t)}))}))})).next((()=>s))))}getDocumentsMatchingCollectionQuery(e,t,n,r){let i;return this.documentOverlayCache.getOverlaysForCollection(e,t.path,n.largestBatchId).next((s=>(i=s,this.remoteDocumentCache.getDocumentsMatchingQuery(e,t,n,i,r)))).next((e=>{i.forEach(((t,n)=>{const r=n.getKey();null===e.get(r)&&(e=e.insert(r,Qt.newInvalidDocument(r)))}));let n=Wn();return e.forEach(((e,r)=>{const s=i.get(e);void 0!==s&&Cr(s.mutation,r,ct.empty(),F.now()),Un(t,r)&&(n=n.insert(e,r))})),n}))}}class mo{constructor(e){this.serializer=e,this.Tr=new Map,this.Ir=new Map}getBundleMetadata(e,t){return ie.resolve(this.Tr.get(t))}saveBundleMetadata(e,t){return this.Tr.set(t.id,function(e){return{id:e.id,version:e.version,createTime:mi(e.createTime)}}(t)),ie.resolve()}getNamedQuery(e,t){return ie.resolve(this.Ir.get(t))}saveNamedQuery(e,t){return this.Ir.set(t.name,function(e){return{name:e.name,query:Yi(e.bundledQuery),readTime:mi(e.readTime)}}(t)),ie.resolve()}}class yo{constructor(){this.overlays=new nt($.comparator),this.Er=new Map}getOverlay(e,t){return ie.resolve(this.overlays.get(t))}getOverlays(e,t){const n=Xn();return ie.forEach(t,(t=>this.getOverlay(e,t).next((e=>{null!==e&&n.set(t,e)})))).next((()=>n))}saveOverlays(e,t,n){return n.forEach(((n,r)=>{this.Tt(e,t,r)})),ie.resolve()}removeOverlaysForBatchId(e,t,n){const r=this.Er.get(n);return void 0!==r&&(r.forEach((e=>this.overlays=this.overlays.remove(e))),this.Er.delete(n)),ie.resolve()}getOverlaysForCollection(e,t,n){const r=Xn(),i=t.length+1,s=new $(t.child("")),o=this.overlays.getIteratorFrom(s);for(;o.hasNext();){const e=o.getNext().value,s=e.getKey();if(!t.isPrefixOf(s.path))break;s.path.length===i&&e.largestBatchId>n&&r.set(e.getKey(),e)}return ie.resolve(r)}getOverlaysForCollectionGroup(e,t,n,r){let i=new nt(((e,t)=>e-t));const s=this.overlays.getIterator();for(;s.hasNext();){const e=s.getNext().value;if(e.getKey().getCollectionGroup()===t&&e.largestBatchId>n){let t=i.get(e.largestBatchId);null===t&&(t=Xn(),i=i.insert(e.largestBatchId,t)),t.set(e.getKey(),e)}}const o=Xn(),a=i.getIterator();for(;a.hasNext()&&(a.getNext().value.forEach(((e,t)=>o.set(e,t))),!(o.size()>=r)););return ie.resolve(o)}Tt(e,t,n){const r=this.overlays.get(n.key);if(null!==r){const e=this.Er.get(r.largestBatchId).delete(n.key);this.Er.set(r.largestBatchId,e)}this.overlays=this.overlays.insert(n.key,new qr(t,n));let i=this.Er.get(t);void 0===i&&(i=nr(),this.Er.set(t,i)),this.Er.set(t,i.add(n.key))}}class vo{constructor(){this.sessionToken=lt.EMPTY_BYTE_STRING}getSessionToken(e){return ie.resolve(this.sessionToken)}setSessionToken(e,t){return this.sessionToken=t,ie.resolve()}}class wo{constructor(){this.dr=new st(bo.Ar),this.Rr=new st(bo.Vr)}isEmpty(){return this.dr.isEmpty()}addReference(e,t){const n=new bo(e,t);this.dr=this.dr.add(n),this.Rr=this.Rr.add(n)}mr(e,t){e.forEach((e=>this.addReference(e,t)))}removeReference(e,t){this.gr(new bo(e,t))}pr(e,t){e.forEach((e=>this.removeReference(e,t)))}yr(e){const t=new $(new B([])),n=new bo(t,e),r=new bo(t,e+1),i=[];return this.Rr.forEachInRange([n,r],(e=>{this.gr(e),i.push(e.key)})),i}wr(){this.dr.forEach((e=>this.gr(e)))}gr(e){this.dr=this.dr.delete(e),this.Rr=this.Rr.delete(e)}Sr(e){const t=new $(new B([])),n=new bo(t,e),r=new bo(t,e+1);let i=nr();return this.Rr.forEachInRange([n,r],(e=>{i=i.add(e.key)})),i}containsKey(e){const t=new bo(e,0),n=this.dr.firstAfterOrEqual(t);return null!==n&&e.isEqual(n.key)}}class bo{constructor(e,t){this.key=e,this.br=t}static Ar(e,t){return $.comparator(e.key,t.key)||M(e.br,t.br)}static Vr(e,t){return M(e.br,t.br)||$.comparator(e.key,t.key)}}class _o{constructor(e,t){this.indexManager=e,this.referenceDelegate=t,this.mutationQueue=[],this.Dr=1,this.vr=new st(bo.Ar)}checkEmpty(e){return ie.resolve(0===this.mutationQueue.length)}addMutationBatch(e,t,n,r){const i=this.Dr;this.Dr++,this.mutationQueue.length>0&&this.mutationQueue[this.mutationQueue.length-1];const s=new Fr(i,t,n,r);this.mutationQueue.push(s);for(const t of r)this.vr=this.vr.add(new bo(t.key,i)),this.indexManager.addToCollectionParentIndex(e,t.key.path.popLast());return ie.resolve(s)}lookupMutationBatch(e,t){return ie.resolve(this.Cr(t))}getNextMutationBatchAfterBatchId(e,t){const n=t+1,r=this.Fr(n),i=r<0?0:r;return ie.resolve(this.mutationQueue.length>i?this.mutationQueue[i]:null)}getHighestUnacknowledgedBatchId(){return ie.resolve(0===this.mutationQueue.length?-1:this.Dr-1)}getAllMutationBatches(e){return ie.resolve(this.mutationQueue.slice())}getAllMutationBatchesAffectingDocumentKey(e,t){const n=new bo(t,0),r=new bo(t,Number.POSITIVE_INFINITY),i=[];return this.vr.forEachInRange([n,r],(e=>{const t=this.Cr(e.br);i.push(t)})),ie.resolve(i)}getAllMutationBatchesAffectingDocumentKeys(e,t){let n=new st(M);return t.forEach((e=>{const t=new bo(e,0),r=new bo(e,Number.POSITIVE_INFINITY);this.vr.forEachInRange([t,r],(e=>{n=n.add(e.br)}))})),ie.resolve(this.Mr(n))}getAllMutationBatchesAffectingQuery(e,t){const n=t.path,r=n.length+1;let i=n;$.isDocumentKey(i)||(i=i.child(""));const s=new bo(new $(i),0);let o=new st(M);return this.vr.forEachWhile((e=>{const t=e.key.path;return!!n.isPrefixOf(t)&&(t.length===r&&(o=o.add(e.br)),!0)}),s),ie.resolve(this.Mr(o))}Mr(e){const t=[];return e.forEach((e=>{const n=this.Cr(e);null!==n&&t.push(n)})),t}removeMutationBatch(e,t){w(0===this.Or(t.batchId,"removed")),this.mutationQueue.shift();let n=this.vr;return ie.forEach(t.mutations,(r=>{const i=new bo(r.key,t.batchId);return n=n.delete(i),this.referenceDelegate.markPotentiallyOrphaned(e,r.key)})).next((()=>{this.vr=n}))}Ln(e){}containsKey(e,t){const n=new bo(t,0),r=this.vr.firstAfterOrEqual(n);return ie.resolve(t.isEqual(r&&r.key))}performConsistencyCheck(e){return this.mutationQueue.length,ie.resolve()}Or(e,t){return this.Fr(e)}Fr(e){return 0===this.mutationQueue.length?0:e-this.mutationQueue[0].batchId}Cr(e){const t=this.Fr(e);return t<0||t>=this.mutationQueue.length?null:this.mutationQueue[t]}}class Io{constructor(e){this.Nr=e,this.docs=new nt($.comparator),this.size=0}setIndexManager(e){this.indexManager=e}addEntry(e,t){const n=t.key,r=this.docs.get(n),i=r?r.size:0,s=this.Nr(t);return this.docs=this.docs.insert(n,{document:t.mutableCopy(),size:s}),this.size+=s-i,this.indexManager.addToCollectionParentIndex(e,n.path.popLast())}removeEntry(e){const t=this.docs.get(e);t&&(this.docs=this.docs.remove(e),this.size-=t.size)}getEntry(e,t){const n=this.docs.get(t);return ie.resolve(n?n.document.mutableCopy():Qt.newInvalidDocument(t))}getEntries(e,t){let n=Qn();return t.forEach((e=>{const t=this.docs.get(e);n=n.insert(e,t?t.document.mutableCopy():Qt.newInvalidDocument(e))})),ie.resolve(n)}getDocumentsMatchingQuery(e,t,n,r){let i=Qn();const s=t.path,o=new $(s.child("")),a=this.docs.getIteratorFrom(o);for(;a.hasNext();){const{key:e,value:{document:o}}=a.getNext();if(!s.isPrefixOf(e.path))break;e.path.length>s.length+1||ee(Y(o),n)<=0||(r.has(o.key)||Un(t,o))&&(i=i.insert(o.key,o.mutableCopy()))}return ie.resolve(i)}getAllFromCollectionGroup(e,t,n,r){v()}Lr(e,t){return ie.forEach(this.docs,(e=>t(e)))}newChangeBuffer(e){return new Eo(this)}getSize(e){return ie.resolve(this.size)}}class Eo extends io{constructor(e){super(),this.hr=e}applyChanges(e){const t=[];return this.changes.forEach(((n,r)=>{r.isValidDocument()?t.push(this.hr.addEntry(e,r)):this.hr.removeEntry(n)})),ie.waitFor(t)}getFromCache(e,t){return this.hr.getEntry(e,t)}getAllFromCache(e,t){return this.hr.getEntries(e,t)}}class To{constructor(e){this.persistence=e,this.Br=new Gn((e=>_n(e)),In),this.lastRemoteSnapshotVersion=V.min(),this.highestTargetId=0,this.kr=0,this.qr=new wo,this.targetCount=0,this.Qr=Ks.qn()}forEachTarget(e,t){return this.Br.forEach(((e,n)=>t(n))),ie.resolve()}getLastRemoteSnapshotVersion(e){return ie.resolve(this.lastRemoteSnapshotVersion)}getHighestSequenceNumber(e){return ie.resolve(this.kr)}allocateTargetId(e){return this.highestTargetId=this.Qr.next(),ie.resolve(this.highestTargetId)}setTargetsMetadata(e,t,n){return n&&(this.lastRemoteSnapshotVersion=n),t>this.kr&&(this.kr=t),ie.resolve()}Un(e){this.Br.set(e.target,e);const t=e.targetId;t>this.highestTargetId&&(this.Qr=new Ks(t),this.highestTargetId=t),e.sequenceNumber>this.kr&&(this.kr=e.sequenceNumber)}addTargetData(e,t){return this.Un(t),this.targetCount+=1,ie.resolve()}updateTargetData(e,t){return this.Un(t),ie.resolve()}removeTargetData(e,t){return this.Br.delete(t.target),this.qr.yr(t.targetId),this.targetCount-=1,ie.resolve()}removeTargets(e,t,n){let r=0;const i=[];return this.Br.forEach(((s,o)=>{o.sequenceNumber<=t&&null===n.get(o.targetId)&&(this.Br.delete(s),i.push(this.removeMatchingKeysForTargetId(e,o.targetId)),r++)})),ie.waitFor(i).next((()=>r))}getTargetCount(e){return ie.resolve(this.targetCount)}getTargetData(e,t){const n=this.Br.get(t)||null;return ie.resolve(n)}addMatchingKeys(e,t,n){return this.qr.mr(t,n),ie.resolve()}removeMatchingKeys(e,t,n){this.qr.pr(t,n);const r=this.persistence.referenceDelegate,i=[];return r&&t.forEach((t=>{i.push(r.markPotentiallyOrphaned(e,t))})),ie.waitFor(i)}removeMatchingKeysForTargetId(e,t){return this.qr.yr(t),ie.resolve()}getMatchingKeysForTargetId(e,t){const n=this.qr.Sr(t);return ie.resolve(n)}containsKey(e,t){return ie.resolve(this.qr.containsKey(t))}}class So{constructor(e,t){this.Kr={},this.overlays={},this.$r=new ye(0),this.Ur=!1,this.Ur=!0,this.Wr=new vo,this.referenceDelegate=e(this),this.Gr=new To(this),this.indexManager=new Ds,this.remoteDocumentCache=function(e){return new Io(e)}((e=>this.referenceDelegate.zr(e))),this.serializer=new zi(t),this.jr=new mo(this.serializer)}start(){return Promise.resolve()}shutdown(){return this.Ur=!1,Promise.resolve()}get started(){return this.Ur}setDatabaseDeletedListener(){}setNetworkEnabled(){}getIndexManager(e){return this.indexManager}getDocumentOverlayCache(e){let t=this.overlays[e.toKey()];return t||(t=new yo,this.overlays[e.toKey()]=t),t}getMutationQueue(e,t){let n=this.Kr[e.toKey()];return n||(n=new _o(t,this.referenceDelegate),this.Kr[e.toKey()]=n),n}getGlobalsCache(){return this.Wr}getTargetCache(){return this.Gr}getRemoteDocumentCache(){return this.remoteDocumentCache}getBundleCache(){return this.jr}runTransaction(e,t,n){g("MemoryPersistence","Starting transaction:",e);const r=new xo(this.$r.next());return this.referenceDelegate.Hr(),n(r).next((e=>this.referenceDelegate.Jr(r).next((()=>e)))).toPromise().then((e=>(r.raiseOnCommittedEvent(),e)))}Yr(e,t){return ie.or(Object.values(this.Kr).map((n=>()=>n.containsKey(e,t))))}}class xo extends ne{constructor(e){super(),this.currentSequenceNumber=e}}class Co{constructor(e){this.persistence=e,this.Zr=new wo,this.Xr=null}static ei(e){return new Co(e)}get ti(){if(this.Xr)return this.Xr;throw v()}addReference(e,t,n){return this.Zr.addReference(n,t),this.ti.delete(n.toString()),ie.resolve()}removeReference(e,t,n){return this.Zr.removeReference(n,t),this.ti.add(n.toString()),ie.resolve()}markPotentiallyOrphaned(e,t){return this.ti.add(t.toString()),ie.resolve()}removeTarget(e,t){this.Zr.yr(t.targetId).forEach((e=>this.ti.add(e.toString())));const n=this.persistence.getTargetCache();return n.getMatchingKeysForTargetId(e,t.targetId).next((e=>{e.forEach((e=>this.ti.add(e.toString())))})).next((()=>n.removeTargetData(e,t)))}Hr(){this.Xr=new Set}Jr(e){const t=this.persistence.getRemoteDocumentCache().newChangeBuffer();return ie.forEach(this.ti,(n=>{const r=$.fromPath(n);return this.ni(e,r).next((e=>{e||t.removeEntry(r,V.min())}))})).next((()=>(this.Xr=null,t.apply(e))))}updateLimboDocument(e,t){return this.ni(e,t).next((e=>{e?this.ti.delete(t.toString()):this.ti.add(t.toString())}))}zr(e){return 0}ni(e,t){return ie.or([()=>ie.resolve(this.Zr.containsKey(t)),()=>this.persistence.getTargetCache().containsKey(e,t),()=>this.persistence.Yr(e,t)])}}class Do{constructor(e,t){this.persistence=e,this.ri=new Gn((e=>_e(e.path)),((e,t)=>e.isEqual(t))),this.garbageCollector=to(this,t)}static ei(e,t){return new Do(e,t)}Hr(){}Jr(e){return ie.resolve()}forEachTarget(e,t){return this.persistence.getTargetCache().forEachTarget(e,t)}Xn(e){const t=this.nr(e);return this.persistence.getTargetCache().getTargetCount(e).next((e=>t.next((t=>e+t))))}nr(e){let t=0;return this.er(e,(e=>{t++})).next((()=>t))}er(e,t){return ie.forEach(this.ri,((n,r)=>this.ir(e,n,r).next((e=>e?ie.resolve():t(r)))))}removeTargets(e,t,n){return this.persistence.getTargetCache().removeTargets(e,t,n)}removeOrphanedDocuments(e,t){let n=0;const r=this.persistence.getRemoteDocumentCache(),i=r.newChangeBuffer();return r.Lr(e,(r=>this.ir(e,r,t).next((e=>{e||(n++,i.removeEntry(r,V.min()))})))).next((()=>i.apply(e))).next((()=>n))}markPotentiallyOrphaned(e,t){return this.ri.set(t,e.currentSequenceNumber),ie.resolve()}removeTarget(e,t){const n=t.withSequenceNumber(e.currentSequenceNumber);return this.persistence.getTargetCache().updateTargetData(e,n)}addReference(e,t,n){return this.ri.set(n,e.currentSequenceNumber),ie.resolve()}removeReference(e,t,n){return this.ri.set(n,e.currentSequenceNumber),ie.resolve()}updateLimboDocument(e,t){return this.ri.set(t,e.currentSequenceNumber),ie.resolve()}zr(e){let t=e.key.toString().length;return e.isFoundDocument()&&(t+=kt(e.data.value)),t}ir(e,t,n){return ie.or([()=>this.persistence.Yr(e,t),()=>this.persistence.getTargetCache().containsKey(e,t),()=>{const e=this.ri.get(t);return ie.resolve(void 0!==e&&e>n)}])}getCacheSize(e){return this.persistence.getRemoteDocumentCache().getSize(e)}}class Ao{constructor(e){this.serializer=e}O(e,t,n,r){const i=new se("createOrUpgrade",t);n<1&&r>=1&&(function(e){e.createObjectStore("owner")}(e),function(e){e.createObjectStore("mutationQueues",{keyPath:"userId"}),e.createObjectStore("mutations",{keyPath:"batchId",autoIncrement:!0}).createIndex("userMutationsIndex",Se,{unique:!0}),e.createObjectStore("documentMutations")}(e),ko(e),function(e){e.createObjectStore("remoteDocuments")}(e));let s=ie.resolve();return n<3&&r>=3&&(0!==n&&(function(e){e.deleteObjectStore("targetDocuments"),e.deleteObjectStore("targets"),e.deleteObjectStore("targetGlobal")}(e),ko(e)),s=s.next((()=>function(e){const t=e.store("targetGlobal"),n={highestTargetId:0,highestListenSequenceNumber:0,lastRemoteSnapshotVersion:V.min().toTimestamp(),targetCount:0};return t.put("targetGlobalKey",n)}(i)))),n<4&&r>=4&&(0!==n&&(s=s.next((()=>function(e,t){return t.store("mutations").U().next((n=>{e.deleteObjectStore("mutations"),e.createObjectStore("mutations",{keyPath:"batchId",autoIncrement:!0}).createIndex("userMutationsIndex",Se,{unique:!0});const r=t.store("mutations"),i=n.map((e=>r.put(e)));return ie.waitFor(i)}))}(e,i)))),s=s.next((()=>{!function(e){e.createObjectStore("clientMetadata",{keyPath:"clientId"})}(e)}))),n<5&&r>=5&&(s=s.next((()=>this.ii(i)))),n<6&&r>=6&&(s=s.next((()=>(function(e){e.createObjectStore("remoteDocumentGlobal")}(e),this.si(i))))),n<7&&r>=7&&(s=s.next((()=>this.oi(i)))),n<8&&r>=8&&(s=s.next((()=>this._i(e,i)))),n<9&&r>=9&&(s=s.next((()=>{!function(e){e.objectStoreNames.contains("remoteDocumentChanges")&&e.deleteObjectStore("remoteDocumentChanges")}(e)}))),n<10&&r>=10&&(s=s.next((()=>this.ai(i)))),n<11&&r>=11&&(s=s.next((()=>{!function(e){e.createObjectStore("bundles",{keyPath:"bundleId"})}(e),function(e){e.createObjectStore("namedQueries",{keyPath:"name"})}(e)}))),n<12&&r>=12&&(s=s.next((()=>{!function(e){const t=e.createObjectStore("documentOverlays",{keyPath:Be});t.createIndex("collectionPathOverlayIndex",Ue,{unique:!1}),t.createIndex("collectionGroupOverlayIndex",je,{unique:!1})}(e)}))),n<13&&r>=13&&(s=s.next((()=>function(e){const t=e.createObjectStore("remoteDocumentsV14",{keyPath:Ae});t.createIndex("documentKeyIndex",ke),t.createIndex("collectionGroupIndex",Ne)}(e))).next((()=>this.ui(e,i))).next((()=>e.deleteObjectStore("remoteDocuments")))),n<14&&r>=14&&(s=s.next((()=>this.ci(e,i)))),n<15&&r>=15&&(s=s.next((()=>function(e){e.createObjectStore("indexConfiguration",{keyPath:"indexId",autoIncrement:!0}).createIndex("collectionGroupIndex","collectionGroup",{unique:!1}),e.createObjectStore("indexState",{keyPath:Pe}).createIndex("sequenceNumberIndex",Fe,{unique:!1}),e.createObjectStore("indexEntries",{keyPath:Ve}).createIndex("documentKeyIndex",qe,{unique:!1})}(e)))),n<16&&r>=16&&(s=s.next((()=>{t.objectStore("indexState").clear()})).next((()=>{t.objectStore("indexEntries").clear()}))),n<17&&r>=17&&(s=s.next((()=>{!function(e){e.createObjectStore("globals",{keyPath:"name"})}(e)}))),s}si(e){let t=0;return e.store("remoteDocuments").J(((e,n)=>{t+=Bs(n)})).next((()=>{const n={byteSize:t};return e.store("remoteDocumentGlobal").put("remoteDocumentGlobalKey",n)}))}ii(e){const t=e.store("mutationQueues"),n=e.store("mutations");return t.U().next((t=>ie.forEach(t,(t=>{const r=IDBKeyRange.bound([t.userId,-1],[t.userId,t.lastAcknowledgedBatchId]);return n.U("userMutationsIndex",r).next((n=>ie.forEach(n,(n=>{w(n.userId===t.userId);const r=Wi(this.serializer,n);return qs(e,t.userId,r).next((()=>{}))}))))}))))}oi(e){const t=e.store("targetDocuments"),n=e.store("remoteDocuments");return e.store("targetGlobal").get("targetGlobalKey").next((e=>{const r=[];return n.J(((n,i)=>{const s=new B(n),o=function(e){return[0,_e(e)]}(s);r.push(t.get(o).next((n=>n?ie.resolve():(n=>t.put({targetId:0,path:_e(n),sequenceNumber:e.highestListenSequenceNumber}))(s))))})).next((()=>ie.waitFor(r)))}))}_i(e,t){e.createObjectStore("collectionParents",{keyPath:Re});const n=t.store("collectionParents"),r=new As,i=e=>{if(r.add(e)){const t=e.lastSegment(),r=e.popLast();return n.put({collectionId:t,parent:_e(r)})}};return t.store("remoteDocuments").J({H:!0},((e,t)=>{const n=new B(e);return i(n.popLast())})).next((()=>t.store("documentMutations").J({H:!0},(([e,t,n],r)=>{const s=Te(t);return i(s.popLast())}))))}ai(e){const t=e.store("targets");return t.J(((e,n)=>{const r=Ji(n),i=Xi(this.serializer,r);return t.put(i)}))}ui(e,t){const n=t.store("remoteDocuments"),r=[];return n.J(((e,n)=>{const i=t.store("remoteDocumentsV14"),s=function(e){return e.document?new $(B.fromString(e.document.name).popFirst(5)):e.noDocument?$.fromSegments(e.noDocument.path):e.unknownDocument?$.fromSegments(e.unknownDocument.path):v()}(n).path.toArray(),o={prefixPath:s.slice(0,s.length-2),collectionGroup:s[s.length-2],documentId:s[s.length-1],readTime:n.readTime||[0,0],unknownDocument:n.unknownDocument,noDocument:n.noDocument,document:n.document,hasCommittedMutations:!!n.hasCommittedMutations};r.push(i.put(o))})).next((()=>ie.waitFor(r)))}ci(e,t){const n=t.store("mutations"),r=oo(this.serializer),i=new So(Co.ei,this.serializer.ht);return n.U().next((e=>{const n=new Map;return e.forEach((e=>{var t;let r=null!==(t=n.get(e.userId))&&void 0!==t?t:nr();Wi(this.serializer,e).keys().forEach((e=>r=r.add(e))),n.set(e.userId,r)})),ie.forEach(n,((e,n)=>{const s=new l(n),o=ss.Pt(this.serializer,s),a=i.getIndexManager(s),c=Us.Pt(s,this.serializer,a,i.referenceDelegate);return new po(r,c,o,a).recalculateAndSaveOverlaysForDocumentKeys(new Je(t,ye.oe),e).next()}))}))}}function ko(e){e.createObjectStore("targetDocuments",{keyPath:Oe}).createIndex("documentTargetsIndex",Me,{unique:!0}),e.createObjectStore("targets",{keyPath:"targetId"}).createIndex("queryTargetsIndex",Le,{unique:!0}),e.createObjectStore("targetGlobal")}const No="Failed to obtain exclusive access to the persistence layer. To allow shared access, multi-tab synchronization has to be enabled in all tabs. If you are using `experimentalForceOwningTab:true`, make sure that only one tab has persistence enabled at any given time.";class Lo{constructor(e,t,n,r,i,s,o,a,c,u,l=17){if(this.allowTabSynchronization=e,this.persistenceKey=t,this.clientId=n,this.li=i,this.window=s,this.document=o,this.hi=c,this.Pi=u,this.Ti=l,this.$r=null,this.Ur=!1,this.isPrimary=!1,this.networkEnabled=!0,this.Ii=null,this.inForeground=!1,this.Ei=null,this.di=null,this.Ai=Number.NEGATIVE_INFINITY,this.Ri=e=>Promise.resolve(),!Lo.p())throw new I(_.UNIMPLEMENTED,"This platform is either missing IndexedDB or is known to have an incomplete implementation. Offline persistence has been disabled.");this.referenceDelegate=new no(this,r),this.Vi=t+"main",this.serializer=new zi(a),this.mi=new oe(this.Vi,this.Ti,new Ao(this.serializer)),this.Wr=new as,this.Gr=new Qs(this.referenceDelegate,this.serializer),this.remoteDocumentCache=oo(this.serializer),this.jr=new ns,this.window&&this.window.localStorage?this.fi=this.window.localStorage:(this.fi=null,!1===u&&p("IndexedDbPersistence","LocalStorage is unavailable. As a result, persistence may not work reliably. In particular enablePersistence() could fail immediately after refreshing the page."))}start(){return this.gi().then((()=>{if(!this.isPrimary&&!this.allowTabSynchronization)throw new I(_.FAILED_PRECONDITION,No);return this.pi(),this.yi(),this.wi(),this.runTransaction("getHighestListenSequenceNumber","readonly",(e=>this.Gr.getHighestSequenceNumber(e)))})).then((e=>{this.$r=new ye(e,this.hi)})).then((()=>{this.Ur=!0})).catch((e=>(this.mi&&this.mi.close(),Promise.reject(e))))}Si(e){return this.Ri=async t=>{if(this.started)return e(t)},e(this.isPrimary)}setDatabaseDeletedListener(e){this.mi.L((async t=>{null===t.newVersion&&await e()}))}setNetworkEnabled(e){this.networkEnabled!==e&&(this.networkEnabled=e,this.li.enqueueAndForget((async()=>{this.started&&await this.gi()})))}gi(){return this.runTransaction("updateClientMetadataAndTryBecomePrimary","readwrite",(e=>Mo(e).put({clientId:this.clientId,updateTimeMs:Date.now(),networkEnabled:this.networkEnabled,inForeground:this.inForeground}).next((()=>{if(this.isPrimary)return this.bi(e).next((e=>{e||(this.isPrimary=!1,this.li.enqueueRetryable((()=>this.Ri(!1))))}))})).next((()=>this.Di(e))).next((t=>this.isPrimary&&!t?this.vi(e).next((()=>!1)):!!t&&this.Ci(e).next((()=>!0)))))).catch((e=>{if(le(e))return g("IndexedDbPersistence","Failed to extend owner lease: ",e),this.isPrimary;if(!this.allowTabSynchronization)throw e;return g("IndexedDbPersistence","Releasing owner lease after error during lease refresh",e),!1})).then((e=>{this.isPrimary!==e&&this.li.enqueueRetryable((()=>this.Ri(e))),this.isPrimary=e}))}bi(e){return Oo(e).get("owner").next((e=>ie.resolve(this.Fi(e))))}Mi(e){return Mo(e).delete(this.clientId)}async xi(){if(this.isPrimary&&!this.Oi(this.Ai,18e5)){this.Ai=Date.now();const e=await this.runTransaction("maybeGarbageCollectMultiClientState","readwrite-primary",(e=>{const t=Xe(e,"clientMetadata");return t.U().next((e=>{const n=this.Ni(e,18e5),r=e.filter((e=>-1===n.indexOf(e)));return ie.forEach(r,(e=>t.delete(e.clientId))).next((()=>r))}))})).catch((()=>[]));if(this.fi)for(const t of e)this.fi.removeItem(this.Li(t.clientId))}}wi(){this.di=this.li.enqueueAfterDelay("client_metadata_refresh",4e3,(()=>this.gi().then((()=>this.xi())).then((()=>this.wi()))))}Fi(e){return!!e&&e.ownerId===this.clientId}Di(e){return this.Pi?ie.resolve(!0):Oo(e).get("owner").next((t=>{if(null!==t&&this.Oi(t.leaseTimestampMs,5e3)&&!this.Bi(t.ownerId)){if(this.Fi(t)&&this.networkEnabled)return!0;if(!this.Fi(t)){if(!t.allowTabSynchronization)throw new I(_.FAILED_PRECONDITION,No);return!1}}return!(!this.networkEnabled||!this.inForeground)||Mo(e).U().next((e=>void 0===this.Ni(e,5e3).find((e=>{if(this.clientId!==e.clientId){const t=!this.networkEnabled&&e.networkEnabled,n=!this.inForeground&&e.inForeground,r=this.networkEnabled===e.networkEnabled;if(t||n&&r)return!0}return!1}))))})).next((e=>(this.isPrimary!==e&&g("IndexedDbPersistence",`Client ${e?"is":"is not"} eligible for a primary lease.`),e)))}async shutdown(){this.Ur=!1,this.ki(),this.di&&(this.di.cancel(),this.di=null),this.qi(),this.Qi(),await this.mi.runTransaction("shutdown","readwrite",["owner","clientMetadata"],(e=>{const t=new Je(e,ye.oe);return this.vi(t).next((()=>this.Mi(t)))})),this.mi.close(),this.Ki()}Ni(e,t){return e.filter((e=>this.Oi(e.updateTimeMs,t)&&!this.Bi(e.clientId)))}$i(){return this.runTransaction("getActiveClients","readonly",(e=>Mo(e).U().next((e=>this.Ni(e,18e5).map((e=>e.clientId))))))}get started(){return this.Ur}getGlobalsCache(){return this.Wr}getMutationQueue(e,t){return Us.Pt(e,this.serializer,t,this.referenceDelegate)}getTargetCache(){return this.Gr}getRemoteDocumentCache(){return this.remoteDocumentCache}getIndexManager(e){return new Ns(e,this.serializer.ht.databaseId)}getDocumentOverlayCache(e){return ss.Pt(this.serializer,e)}getBundleCache(){return this.jr}runTransaction(e,t,n){g("IndexedDbPersistence","Starting transaction:",e);const r="readonly"===t?"readonly":"readwrite",i=function(e){return 17===e?We:16===e?He:15===e?Qe:14===e?Ke:13===e?Ge:12===e?ze:11===e?$e:void v()}(this.Ti);let s;return this.mi.runTransaction(e,r,i,(r=>(s=new Je(r,this.$r?this.$r.next():ye.oe),"readwrite-primary"===t?this.bi(s).next((e=>!!e||this.Di(s))).next((t=>{if(!t)throw p(`Failed to obtain primary lease for action '${e}'.`),this.isPrimary=!1,this.li.enqueueRetryable((()=>this.Ri(!1))),new I(_.FAILED_PRECONDITION,te);return n(s)})).next((e=>this.Ci(s).next((()=>e)))):this.Ui(s).next((()=>n(s)))))).then((e=>(s.raiseOnCommittedEvent(),e)))}Ui(e){return Oo(e).get("owner").next((e=>{if(null!==e&&this.Oi(e.leaseTimestampMs,5e3)&&!this.Bi(e.ownerId)&&!this.Fi(e)&&!(this.Pi||this.allowTabSynchronization&&e.allowTabSynchronization))throw new I(_.FAILED_PRECONDITION,No)}))}Ci(e){const t={ownerId:this.clientId,allowTabSynchronization:this.allowTabSynchronization,leaseTimestampMs:Date.now()};return Oo(e).put("owner",t)}static p(){return oe.p()}vi(e){const t=Oo(e);return t.get("owner").next((e=>this.Fi(e)?(g("IndexedDbPersistence","Releasing primary lease."),t.delete("owner")):ie.resolve()))}Oi(e,t){const n=Date.now();return!(e<n-t||e>n&&(p(`Detected an update time that is in the future: ${e} > ${n}`),1))}pi(){null!==this.document&&"function"==typeof this.document.addEventListener&&(this.Ei=()=>{this.li.enqueueAndForget((()=>(this.inForeground="visible"===this.document.visibilityState,this.gi())))},this.document.addEventListener("visibilitychange",this.Ei),this.inForeground="visible"===this.document.visibilityState)}qi(){this.Ei&&(this.document.removeEventListener("visibilitychange",this.Ei),this.Ei=null)}yi(){var e;"function"==typeof(null===(e=this.window)||void 0===e?void 0:e.addEventListener)&&(this.Ii=()=>{this.ki();const e=/(?:Version|Mobile)\/1[456]/;o.isSafari()&&(navigator.appVersion.match(e)||navigator.userAgent.match(e))&&this.li.enterRestrictedMode(!0),this.li.enqueueAndForget((()=>this.shutdown()))},this.window.addEventListener("pagehide",this.Ii))}Qi(){this.Ii&&(this.window.removeEventListener("pagehide",this.Ii),this.Ii=null)}Bi(e){var t;try{const n=null!==(null===(t=this.fi)||void 0===t?void 0:t.getItem(this.Li(e)));return g("IndexedDbPersistence",`Client '${e}' ${n?"is":"is not"} zombied in LocalStorage`),n}catch(e){return p("IndexedDbPersistence","Failed to get zombied client id.",e),!1}}ki(){if(this.fi)try{this.fi.setItem(this.Li(this.clientId),String(Date.now()))}catch(e){p("Failed to set zombie client id.",e)}}Ki(){if(this.fi)try{this.fi.removeItem(this.Li(this.clientId))}catch(e){}}Li(e){return`firestore_zombie_${this.persistenceKey}_${e}`}}function Oo(e){return Xe(e,"owner")}function Mo(e){return Xe(e,"clientMetadata")}function Ro(e,t){let n=e.projectId;return e.isDefaultDatabase||(n+="."+e.database),"firestore/"+t+"/"+n+"/"}class Po{constructor(e,t,n,r){this.targetId=e,this.fromCache=t,this.Wi=n,this.Gi=r}static zi(e,t){let n=nr(),r=nr();for(const e of t.docChanges)switch(e.type){case 0:n=n.add(e.doc.key);break;case 1:r=r.add(e.doc.key)}return new Po(e,t.fromCache,n,r)}}class Fo{constructor(){this._documentReadCount=0}get documentReadCount(){return this._documentReadCount}incrementDocumentReadCount(e){this._documentReadCount+=e}}class Vo{constructor(){this.ji=!1,this.Hi=!1,this.Ji=100,this.Yi=o.isSafari()?8:ae(o.getUA())>0?6:4}initialize(e,t){this.Zi=e,this.indexManager=t,this.ji=!0}getDocumentsMatchingQuery(e,t,n,r){const i={result:null};return this.Xi(e,t).next((e=>{i.result=e})).next((()=>{if(!i.result)return this.es(e,t,r,n).next((e=>{i.result=e}))})).next((()=>{if(i.result)return;const n=new Fo;return this.ts(e,t,n).next((r=>{if(i.result=r,this.Hi)return this.ns(e,t,n,r.size)}))})).next((()=>i.result))}ns(e,t,n,r){return n.documentReadCount<this.Ji?(f()<=s.LogLevel.DEBUG&&g("QueryEngine","SDK will not create cache indexes for query:",Bn(t),"since it only creates cache indexes for collection contains","more than or equal to",this.Ji,"documents"),ie.resolve()):(f()<=s.LogLevel.DEBUG&&g("QueryEngine","Query:",Bn(t),"scans",n.documentReadCount,"local documents and returns",r,"documents as results."),n.documentReadCount>this.Yi*r?(f()<=s.LogLevel.DEBUG&&g("QueryEngine","The SDK decides to create cache indexes for query:",Bn(t),"as using cache indexes may help improve performance."),this.indexManager.createTargetIndexes(e,On(t))):ie.resolve())}Xi(e,t){if(kn(t))return ie.resolve(null);let n=On(t);return this.indexManager.getIndexType(e,n).next((r=>0===r?null:(null!==t.limit&&1===r&&(t=Fn(t,null,"F"),n=On(t)),this.indexManager.getDocumentsMatchingTarget(e,n).next((r=>{const i=nr(...r);return this.Zi.getDocuments(e,i).next((r=>this.indexManager.getMinOffset(e,n).next((n=>{const s=this.rs(t,r);return this.ss(t,s,i,n.readTime)?this.Xi(e,Fn(t,null,"F")):this.os(e,s,t,n)}))))})))))}es(e,t,n,r){return kn(t)||r.isEqual(V.min())?ie.resolve(null):this.Zi.getDocuments(e,n).next((i=>{const o=this.rs(t,i);return this.ss(t,o,n,r)?ie.resolve(null):(f()<=s.LogLevel.DEBUG&&g("QueryEngine","Re-using previous result from %s to execute query: %s",r.toString(),Bn(t)),this.os(e,o,t,X(r,-1)).next((e=>e)))}))}rs(e,t){let n=new st($n(e));return t.forEach(((t,r)=>{Un(e,r)&&(n=n.add(r))})),n}ss(e,t,n,r){if(null===e.limit)return!1;if(n.size!==t.size)return!0;const i="F"===e.limitType?t.last():t.first();return!!i&&(i.hasPendingWrites||i.version.compareTo(r)>0)}ts(e,t,n){return f()<=s.LogLevel.DEBUG&&g("QueryEngine","Using full collection scan to execute query:",Bn(t)),this.Zi.getDocumentsMatchingQuery(e,t,Z.min(),n)}os(e,t,n,r){return this.Zi.getDocumentsMatchingQuery(e,n,r).next((e=>(t.forEach((t=>{e=e.insert(t.key,t)})),e)))}}class qo{constructor(e,t,n,r){this.persistence=e,this._s=t,this.serializer=r,this.us=new nt(M),this.cs=new Gn((e=>_n(e)),In),this.ls=new Map,this.hs=e.getRemoteDocumentCache(),this.Gr=e.getTargetCache(),this.jr=e.getBundleCache(),this.Ps(n)}Ps(e){this.documentOverlayCache=this.persistence.getDocumentOverlayCache(e),this.indexManager=this.persistence.getIndexManager(e),this.mutationQueue=this.persistence.getMutationQueue(e,this.indexManager),this.localDocuments=new po(this.hs,this.mutationQueue,this.documentOverlayCache,this.indexManager),this.hs.setIndexManager(this.indexManager),this._s.initialize(this.localDocuments,this.indexManager)}collectGarbage(e){return this.persistence.runTransaction("Collect garbage","readwrite-primary",(t=>e.collect(t,this.us)))}}function Bo(e,t,n,r){return new qo(e,t,n,r)}async function Uo(e,t){const n=b(e);return await n.persistence.runTransaction("Handle user change","readonly",(e=>{let r;return n.mutationQueue.getAllMutationBatches(e).next((i=>(r=i,n.Ps(t),n.mutationQueue.getAllMutationBatches(e)))).next((t=>{const i=[],s=[];let o=nr();for(const e of r){i.push(e.batchId);for(const t of e.mutations)o=o.add(t.key)}for(const e of t){s.push(e.batchId);for(const t of e.mutations)o=o.add(t.key)}return n.localDocuments.getDocuments(e,o).next((e=>({Ts:e,removedBatchIds:i,addedBatchIds:s})))}))}))}function jo(e){const t=b(e);return t.persistence.runTransaction("Get last remote snapshot version","readonly",(e=>t.Gr.getLastRemoteSnapshotVersion(e)))}function $o(e,t,n){let r=nr(),i=nr();return n.forEach((e=>r=r.add(e))),t.getEntries(e,r).next((e=>{let r=Qn();return n.forEach(((n,s)=>{const o=e.get(n);s.isFoundDocument()!==o.isFoundDocument()&&(i=i.add(n)),s.isNoDocument()&&s.version.isEqual(V.min())?(t.removeEntry(n,s.readTime),r=r.insert(n,s)):!o.isValidDocument()||s.version.compareTo(o.version)>0||0===s.version.compareTo(o.version)&&o.hasPendingWrites?(t.addEntry(s),r=r.insert(n,s)):g("LocalStore","Ignoring outdated watch update for ",n,". Current version:",o.version," Watch version:",s.version)})),{Is:r,Es:i}}))}function zo(e,t){const n=b(e);return n.persistence.runTransaction("Get next mutation batch","readonly",(e=>(void 0===t&&(t=-1),n.mutationQueue.getNextMutationBatchAfterBatchId(e,t))))}function Go(e,t){const n=b(e);return n.persistence.runTransaction("Allocate target","readwrite",(e=>{let r;return n.Gr.getTargetData(e,t).next((i=>i?(r=i,ie.resolve(r)):n.Gr.allocateTargetId(e).next((i=>(r=new $i(t,i,"TargetPurposeListen",e.currentSequenceNumber),n.Gr.addTargetData(e,r).next((()=>r)))))))})).then((e=>{const r=n.us.get(e.targetId);return(null===r||e.snapshotVersion.compareTo(r.snapshotVersion)>0)&&(n.us=n.us.insert(e.targetId,e),n.cs.set(t,e.targetId)),e}))}async function Ko(e,t,n){const r=b(e),i=r.us.get(t),s=n?"readwrite":"readwrite-primary";try{n||await r.persistence.runTransaction("Release target",s,(e=>r.persistence.referenceDelegate.removeTarget(e,i)))}catch(e){if(!le(e))throw e;g("LocalStore",`Failed to update sequence numbers for target ${t}: ${e}`)}r.us=r.us.remove(t),r.cs.delete(i.target)}function Qo(e,t,n){const r=b(e);let i=V.min(),s=nr();return r.persistence.runTransaction("Execute query","readwrite",(e=>function(e,t,n){const r=b(e),i=r.cs.get(n);return void 0!==i?ie.resolve(r.us.get(i)):r.Gr.getTargetData(t,n)}(r,e,On(t)).next((t=>{if(t)return i=t.lastLimboFreeSnapshotVersion,r.Gr.getMatchingKeysForTargetId(e,t.targetId).next((e=>{s=e}))})).next((()=>r._s.getDocumentsMatchingQuery(e,t,n?i:V.min(),n?s:nr()))).next((e=>(Jo(r,jn(t),e),{documents:e,ds:s})))))}function Ho(e,t){const n=b(e),r=b(n.Gr),i=n.us.get(t);return i?Promise.resolve(i.target):n.persistence.runTransaction("Get target data","readonly",(e=>r.ut(e,t).next((e=>e?e.target:null))))}function Wo(e,t){const n=b(e),r=n.ls.get(t)||V.min();return n.persistence.runTransaction("Get new document changes","readonly",(e=>n.hs.getAllFromCollectionGroup(e,t,X(r,-1),Number.MAX_SAFE_INTEGER))).then((e=>(Jo(n,t,e),e)))}function Jo(e,t,n){let r=e.ls.get(t)||V.min();n.forEach(((e,t)=>{t.readTime.compareTo(r)>0&&(r=t.readTime)})),e.ls.set(t,r)}async function Xo(e,t,n=nr()){const r=await Go(e,On(Yi(t.bundledQuery))),i=b(e);return i.persistence.runTransaction("Save named query","readwrite",(e=>{const s=mi(t.readTime);if(r.snapshotVersion.compareTo(s)>=0)return i.jr.saveNamedQuery(e,t);const o=r.withResumeToken(lt.EMPTY_BYTE_STRING,s);return i.us=i.us.insert(o.targetId,o),i.Gr.updateTargetData(e,o).next((()=>i.Gr.removeMatchingKeysForTargetId(e,r.targetId))).next((()=>i.Gr.addMatchingKeys(e,n,r.targetId))).next((()=>i.jr.saveNamedQuery(e,t)))}))}function Yo(e,t){return`firestore_clients_${e}_${t}`}function Zo(e,t,n){let r=`firestore_mutations_${e}_${n}`;return t.isAuthenticated()&&(r+=`_${t.uid}`),r}function ea(e,t){return`firestore_targets_${e}_${t}`}class ta{constructor(e,t,n,r){this.user=e,this.batchId=t,this.state=n,this.error=r}static fs(e,t,n){const r=JSON.parse(n);let i,s="object"==typeof r&&-1!==["pending","acknowledged","rejected"].indexOf(r.state)&&(void 0===r.error||"object"==typeof r.error);return s&&r.error&&(s="string"==typeof r.error.message&&"string"==typeof r.error.code,s&&(i=new I(r.error.code,r.error.message))),s?new ta(e,t,r.state,i):(p("SharedClientState",`Failed to parse mutation state for ID '${t}': ${n}`),null)}gs(){const e={state:this.state,updateTimeMs:Date.now()};return this.error&&(e.error={code:this.error.code,message:this.error.message}),JSON.stringify(e)}}class na{constructor(e,t,n){this.targetId=e,this.state=t,this.error=n}static fs(e,t){const n=JSON.parse(t);let r,i="object"==typeof n&&-1!==["not-current","current","rejected"].indexOf(n.state)&&(void 0===n.error||"object"==typeof n.error);return i&&n.error&&(i="string"==typeof n.error.message&&"string"==typeof n.error.code,i&&(r=new I(n.error.code,n.error.message))),i?new na(e,n.state,r):(p("SharedClientState",`Failed to parse target state for ID '${e}': ${t}`),null)}gs(){const e={state:this.state,updateTimeMs:Date.now()};return this.error&&(e.error={code:this.error.code,message:this.error.message}),JSON.stringify(e)}}class ra{constructor(e,t){this.clientId=e,this.activeTargetIds=t}static fs(e,t){const n=JSON.parse(t);let r="object"==typeof n&&n.activeTargetIds instanceof Array,i=ir();for(let e=0;r&&e<n.activeTargetIds.length;++e)r=be(n.activeTargetIds[e]),i=i.add(n.activeTargetIds[e]);return r?new ra(e,i):(p("SharedClientState",`Failed to parse client data for instance '${e}': ${t}`),null)}}class ia{constructor(e,t){this.clientId=e,this.onlineState=t}static fs(e){const t=JSON.parse(e);return"object"==typeof t&&-1!==["Unknown","Online","Offline"].indexOf(t.onlineState)&&"string"==typeof t.clientId?new ia(t.clientId,t.onlineState):(p("SharedClientState",`Failed to parse online state: ${e}`),null)}}class sa{constructor(){this.activeTargetIds=ir()}ps(e){this.activeTargetIds=this.activeTargetIds.add(e)}ys(e){this.activeTargetIds=this.activeTargetIds.delete(e)}gs(){const e={activeTargetIds:this.activeTargetIds.toArray(),updateTimeMs:Date.now()};return JSON.stringify(e)}}class oa{constructor(e,t,n,r,i){this.window=e,this.li=t,this.persistenceKey=n,this.ws=r,this.syncEngine=null,this.onlineStateHandler=null,this.sequenceNumberHandler=null,this.Ss=this.bs.bind(this),this.Ds=new nt(M),this.started=!1,this.vs=[];const s=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");this.storage=this.window.localStorage,this.currentUser=i,this.Cs=Yo(this.persistenceKey,this.ws),this.Fs=function(e){return`firestore_sequence_number_${e}`}(this.persistenceKey),this.Ds=this.Ds.insert(this.ws,new sa),this.Ms=new RegExp(`^firestore_clients_${s}_([^_]*)$`),this.xs=new RegExp(`^firestore_mutations_${s}_(\\d+)(?:_(.*))?$`),this.Os=new RegExp(`^firestore_targets_${s}_(\\d+)$`),this.Ns=function(e){return`firestore_online_state_${e}`}(this.persistenceKey),this.Ls=function(e){return`firestore_bundle_loaded_v2_${e}`}(this.persistenceKey),this.window.addEventListener("storage",this.Ss)}static p(e){return!(!e||!e.localStorage)}async start(){const e=await this.syncEngine.$i();for(const t of e){if(t===this.ws)continue;const e=this.getItem(Yo(this.persistenceKey,t));if(e){const n=ra.fs(t,e);n&&(this.Ds=this.Ds.insert(n.clientId,n))}}this.Bs();const t=this.storage.getItem(this.Ns);if(t){const e=this.ks(t);e&&this.qs(e)}for(const e of this.vs)this.bs(e);this.vs=[],this.window.addEventListener("pagehide",(()=>this.shutdown())),this.started=!0}writeSequenceNumber(e){this.setItem(this.Fs,JSON.stringify(e))}getAllActiveQueryTargets(){return this.Qs(this.Ds)}isActiveQueryTarget(e){let t=!1;return this.Ds.forEach(((n,r)=>{r.activeTargetIds.has(e)&&(t=!0)})),t}addPendingMutation(e){this.Ks(e,"pending")}updateMutationState(e,t,n){this.Ks(e,t,n),this.$s(e)}addLocalQueryTarget(e,t=!0){let n="not-current";if(this.isActiveQueryTarget(e)){const t=this.storage.getItem(ea(this.persistenceKey,e));if(t){const r=na.fs(e,t);r&&(n=r.state)}}return t&&this.Us.ps(e),this.Bs(),n}removeLocalQueryTarget(e){this.Us.ys(e),this.Bs()}isLocalQueryTarget(e){return this.Us.activeTargetIds.has(e)}clearQueryState(e){this.removeItem(ea(this.persistenceKey,e))}updateQueryState(e,t,n){this.Ws(e,t,n)}handleUserChange(e,t,n){t.forEach((e=>{this.$s(e)})),this.currentUser=e,n.forEach((e=>{this.addPendingMutation(e)}))}setOnlineState(e){this.Gs(e)}notifyBundleLoaded(e){this.zs(e)}shutdown(){this.started&&(this.window.removeEventListener("storage",this.Ss),this.removeItem(this.Cs),this.started=!1)}getItem(e){const t=this.storage.getItem(e);return g("SharedClientState","READ",e,t),t}setItem(e,t){g("SharedClientState","SET",e,t),this.storage.setItem(e,t)}removeItem(e){g("SharedClientState","REMOVE",e),this.storage.removeItem(e)}bs(e){const t=e;if(t.storageArea===this.storage){if(g("SharedClientState","EVENT",t.key,t.newValue),t.key===this.Cs)return void p("Received WebStorage notification for local change. Another client might have garbage-collected our state");this.li.enqueueRetryable((async()=>{if(this.started){if(null!==t.key)if(this.Ms.test(t.key)){if(null==t.newValue){const e=this.js(t.key);return this.Hs(e,null)}{const e=this.Js(t.key,t.newValue);if(e)return this.Hs(e.clientId,e)}}else if(this.xs.test(t.key)){if(null!==t.newValue){const e=this.Ys(t.key,t.newValue);if(e)return this.Zs(e)}}else if(this.Os.test(t.key)){if(null!==t.newValue){const e=this.Xs(t.key,t.newValue);if(e)return this.eo(e)}}else if(t.key===this.Ns){if(null!==t.newValue){const e=this.ks(t.newValue);if(e)return this.qs(e)}}else if(t.key===this.Fs){const e=function(e){let t=ye.oe;if(null!=e)try{const n=JSON.parse(e);w("number"==typeof n),t=n}catch(e){p("SharedClientState","Failed to read sequence number from WebStorage",e)}return t}(t.newValue);e!==ye.oe&&this.sequenceNumberHandler(e)}else if(t.key===this.Ls){const e=this.no(t.newValue);await Promise.all(e.map((e=>this.syncEngine.ro(e))))}}else this.vs.push(t)}))}}get Us(){return this.Ds.get(this.ws)}Bs(){this.setItem(this.Cs,this.Us.gs())}Ks(e,t,n){const r=new ta(this.currentUser,e,t,n),i=Zo(this.persistenceKey,this.currentUser,e);this.setItem(i,r.gs())}$s(e){const t=Zo(this.persistenceKey,this.currentUser,e);this.removeItem(t)}Gs(e){const t={clientId:this.ws,onlineState:e};this.storage.setItem(this.Ns,JSON.stringify(t))}Ws(e,t,n){const r=ea(this.persistenceKey,e),i=new na(e,t,n);this.setItem(r,i.gs())}zs(e){const t=JSON.stringify(Array.from(e));this.setItem(this.Ls,t)}js(e){const t=this.Ms.exec(e);return t?t[1]:null}Js(e,t){const n=this.js(e);return ra.fs(n,t)}Ys(e,t){const n=this.xs.exec(e),r=Number(n[1]),i=void 0!==n[2]?n[2]:null;return ta.fs(new l(i),r,t)}Xs(e,t){const n=this.Os.exec(e),r=Number(n[1]);return na.fs(r,t)}ks(e){return ia.fs(e)}no(e){return JSON.parse(e)}async Zs(e){if(e.user.uid===this.currentUser.uid)return this.syncEngine.io(e.batchId,e.state,e.error);g("SharedClientState",`Ignoring mutation for non-active user ${e.user.uid}`)}eo(e){return this.syncEngine.so(e.targetId,e.state,e.error)}Hs(e,t){const n=t?this.Ds.insert(e,t):this.Ds.remove(e),r=this.Qs(this.Ds),i=this.Qs(n),s=[],o=[];return i.forEach((e=>{r.has(e)||s.push(e)})),r.forEach((e=>{i.has(e)||o.push(e)})),this.syncEngine.oo(s,o).then((()=>{this.Ds=n}))}qs(e){this.Ds.get(e.clientId)&&this.onlineStateHandler(e.onlineState)}Qs(e){let t=ir();return e.forEach(((e,n)=>{t=t.unionWith(n.activeTargetIds)})),t}}class aa{constructor(){this._o=new sa,this.ao={},this.onlineStateHandler=null,this.sequenceNumberHandler=null}addPendingMutation(e){}updateMutationState(e,t,n){}addLocalQueryTarget(e,t=!0){return t&&this._o.ps(e),this.ao[e]||"not-current"}updateQueryState(e,t,n){this.ao[e]=t}removeLocalQueryTarget(e){this._o.ys(e)}isLocalQueryTarget(e){return this._o.activeTargetIds.has(e)}clearQueryState(e){delete this.ao[e]}getAllActiveQueryTargets(){return this._o.activeTargetIds}isActiveQueryTarget(e){return this._o.activeTargetIds.has(e)}start(){return this._o=new sa,Promise.resolve()}handleUserChange(e,t,n){}setOnlineState(e){}shutdown(){}writeSequenceNumber(e){}notifyBundleLoaded(e){}}class ca{uo(e){}shutdown(){}}class ua{constructor(){this.co=()=>this.lo(),this.ho=()=>this.Po(),this.To=[],this.Io()}uo(e){this.To.push(e)}shutdown(){window.removeEventListener("online",this.co),window.removeEventListener("offline",this.ho)}Io(){window.addEventListener("online",this.co),window.addEventListener("offline",this.ho)}lo(){g("ConnectivityMonitor","Network connectivity changed: AVAILABLE");for(const e of this.To)e(0)}Po(){g("ConnectivityMonitor","Network connectivity changed: UNAVAILABLE");for(const e of this.To)e(1)}static p(){return"undefined"!=typeof window&&void 0!==window.addEventListener&&void 0!==window.removeEventListener}}let la=null;function ha(){return null===la?la=268435456+Math.round(2147483648*Math.random()):la++,"0x"+la.toString(16)}const da={BatchGetDocuments:"batchGet",Commit:"commit",RunQuery:"runQuery",RunAggregationQuery:"runAggregationQuery"};class fa{constructor(e){this.Eo=e.Eo,this.Ao=e.Ao}Ro(e){this.Vo=e}mo(e){this.fo=e}po(e){this.yo=e}onMessage(e){this.wo=e}close(){this.Ao()}send(e){this.Eo(e)}So(){this.Vo()}bo(){this.fo()}Do(e){this.yo(e)}vo(e){this.wo(e)}}const ga="WebChannelConnection";class pa extends class{get Co(){return!1}constructor(e){this.databaseInfo=e,this.databaseId=e.databaseId;const t=e.ssl?"https":"http",n=encodeURIComponent(this.databaseId.projectId),r=encodeURIComponent(this.databaseId.database);this.Fo=t+"://"+e.host,this.Mo=`projects/${n}/databases/${r}`,this.xo="(default)"===this.databaseId.database?`project_id=${n}`:`project_id=${n}&database_id=${r}`}Oo(e,t,n,r,i){const s=ha(),o=this.No(e,t.toUriEncodedString());g("RestConnection",`Sending RPC '${e}' ${s}:`,o,n);const a={"google-cloud-resource-prefix":this.Mo,"x-goog-request-params":this.xo};return this.Lo(a,r,i),this.Bo(e,o,a,n).then((t=>(g("RestConnection",`Received RPC '${e}' ${s}: `,t),t)),(t=>{throw m("RestConnection",`RPC '${e}' ${s} failed with error: `,t,"url: ",o,"request:",n),t}))}ko(e,t,n,r,i,s){return this.Oo(e,t,n,r,i)}Lo(e,t,n){e["X-Goog-Api-Client"]="gl-js/ fire/"+h,e["Content-Type"]="text/plain",this.databaseInfo.appId&&(e["X-Firebase-GMPID"]=this.databaseInfo.appId),t&&t.headers.forEach(((t,n)=>e[n]=t)),n&&n.headers.forEach(((t,n)=>e[n]=t))}No(e,t){const n=da[e];return`${this.Fo}/v1/${t}:${n}`}terminate(){}}{constructor(e){super(e),this.forceLongPolling=e.forceLongPolling,this.autoDetectLongPolling=e.autoDetectLongPolling,this.useFetchStreams=e.useFetchStreams,this.longPollingOptions=e.longPollingOptions}Bo(e,t,n,r){const i=ha();return new Promise(((s,o)=>{const a=new c.XhrIo;a.setWithCredentials(!0),a.listenOnce(c.EventType.COMPLETE,(()=>{try{switch(a.getLastErrorCode()){case c.ErrorCode.NO_ERROR:const t=a.getResponseJson();g(ga,`XHR for RPC '${e}' ${i} received:`,JSON.stringify(t)),s(t);break;case c.ErrorCode.TIMEOUT:g(ga,`RPC '${e}' ${i} timed out`),o(new I(_.DEADLINE_EXCEEDED,"Request time out"));break;case c.ErrorCode.HTTP_ERROR:const n=a.getStatus();if(g(ga,`RPC '${e}' ${i} failed with status:`,n,"response text:",a.getResponseText()),n>0){let e=a.getResponseJson();Array.isArray(e)&&(e=e[0]);const t=null==e?void 0:e.error;if(t&&t.status&&t.message){const e=function(e){const t=e.toLowerCase().replace(/_/g,"-");return Object.values(_).indexOf(t)>=0?t:_.UNKNOWN}(t.status);o(new I(e,t.message))}else o(new I(_.UNKNOWN,"Server responded with status "+a.getStatus()))}else o(new I(_.UNAVAILABLE,"Connection failed."));break;default:v()}}finally{g(ga,`RPC '${e}' ${i} completed.`)}}));const u=JSON.stringify(r);g(ga,`RPC '${e}' ${i} sending request:`,r),a.send(t,"POST",u,n,15)}))}qo(e,t,n){const r=ha(),i=[this.Fo,"/","google.firestore.v1.Firestore","/",e,"/channel"],s=c.createWebChannelTransport(),o=c.getStatEventTarget(),a={httpSessionIdParam:"gsessionid",initMessageHeaders:{},messageUrlParams:{database:`projects/${this.databaseId.projectId}/databases/${this.databaseId.database}`},sendRawJson:!0,supportsCrossDomainXhr:!0,internalChannelParams:{forwardChannelRequestTimeoutMs:6e5},forceLongPolling:this.forceLongPolling,detectBufferingProxy:this.autoDetectLongPolling},u=this.longPollingOptions.timeoutSeconds;void 0!==u&&(a.longPollingTimeout=Math.round(1e3*u)),this.useFetchStreams&&(a.useFetchStreams=!0),this.Lo(a.initMessageHeaders,t,n),a.encodeInitMessageHeaders=!0;const l=i.join("");g(ga,`Creating RPC '${e}' stream ${r}: ${l}`,a);const h=s.createWebChannel(l,a);let d=!1,f=!1;const p=new fa({Eo:t=>{f?g(ga,`Not sending because RPC '${e}' stream ${r} is closed:`,t):(d||(g(ga,`Opening RPC '${e}' stream ${r} transport.`),h.open(),d=!0),g(ga,`RPC '${e}' stream ${r} sending:`,t),h.send(t))},Ao:()=>h.close()}),y=(e,t,n)=>{e.listen(t,(e=>{try{n(e)}catch(e){setTimeout((()=>{throw e}),0)}}))};return y(h,c.WebChannel.EventType.OPEN,(()=>{f||(g(ga,`RPC '${e}' stream ${r} transport opened.`),p.So())})),y(h,c.WebChannel.EventType.CLOSE,(()=>{f||(f=!0,g(ga,`RPC '${e}' stream ${r} transport closed`),p.Do())})),y(h,c.WebChannel.EventType.ERROR,(t=>{f||(f=!0,m(ga,`RPC '${e}' stream ${r} transport errored:`,t),p.Do(new I(_.UNAVAILABLE,"The operation could not be completed")))})),y(h,c.WebChannel.EventType.MESSAGE,(t=>{var n;if(!f){const i=t.data[0];w(!!i);const s=i,o=(null==s?void 0:s.error)||(null===(n=s[0])||void 0===n?void 0:n.error);if(o){g(ga,`RPC '${e}' stream ${r} received error:`,o);const t=o.status;let n=function(e){const t=jr[e];if(void 0!==t)return Gr(t)}(t),i=o.message;void 0===n&&(n=_.INTERNAL,i="Unknown error status: "+t+" with message "+o.message),f=!0,p.Do(new I(n,i)),h.close()}else g(ga,`RPC '${e}' stream ${r} received:`,i),p.vo(i)}})),y(o,c.Event.STAT_EVENT,(t=>{t.stat===c.Stat.PROXY?g(ga,`RPC '${e}' stream ${r} detected buffering proxy`):t.stat===c.Stat.NOPROXY&&g(ga,`RPC '${e}' stream ${r} detected no buffering proxy`)})),setTimeout((()=>{p.bo()}),0),p}}function ma(){return"undefined"!=typeof window?window:null}function ya(){return"undefined"!=typeof document?document:null}function va(e){return new hi(e,!0)}class wa{constructor(e,t,n=1e3,r=1.5,i=6e4){this.li=e,this.timerId=t,this.Qo=n,this.Ko=r,this.$o=i,this.Uo=0,this.Wo=null,this.Go=Date.now(),this.reset()}reset(){this.Uo=0}zo(){this.Uo=this.$o}jo(e){this.cancel();const t=Math.floor(this.Uo+this.Ho()),n=Math.max(0,Date.now()-this.Go),r=Math.max(0,t-n);r>0&&g("ExponentialBackoff",`Backing off for ${r} ms (base delay: ${this.Uo} ms, delay with jitter: ${t} ms, last attempt: ${n} ms ago)`),this.Wo=this.li.enqueueAfterDelay(this.timerId,r,(()=>(this.Go=Date.now(),e()))),this.Uo*=this.Ko,this.Uo<this.Qo&&(this.Uo=this.Qo),this.Uo>this.$o&&(this.Uo=this.$o)}Jo(){null!==this.Wo&&(this.Wo.skipDelay(),this.Wo=null)}cancel(){null!==this.Wo&&(this.Wo.cancel(),this.Wo=null)}Ho(){return(Math.random()-.5)*this.Uo}}class ba{constructor(e,t,n,r,i,s,o,a){this.li=e,this.Yo=n,this.Zo=r,this.connection=i,this.authCredentialsProvider=s,this.appCheckCredentialsProvider=o,this.listener=a,this.state=0,this.Xo=0,this.e_=null,this.t_=null,this.stream=null,this.n_=0,this.r_=new wa(e,t)}i_(){return 1===this.state||5===this.state||this.s_()}s_(){return 2===this.state||3===this.state}start(){this.n_=0,4!==this.state?this.auth():this.o_()}async stop(){this.i_()&&await this.close(0)}__(){this.state=0,this.r_.reset()}a_(){this.s_()&&null===this.e_&&(this.e_=this.li.enqueueAfterDelay(this.Yo,6e4,(()=>this.u_())))}c_(e){this.l_(),this.stream.send(e)}async u_(){if(this.s_())return this.close(0)}l_(){this.e_&&(this.e_.cancel(),this.e_=null)}h_(){this.t_&&(this.t_.cancel(),this.t_=null)}async close(e,t){this.l_(),this.h_(),this.r_.cancel(),this.Xo++,4!==e?this.r_.reset():t&&t.code===_.RESOURCE_EXHAUSTED?(p(t.toString()),p("Using maximum backoff delay to prevent overloading the backend."),this.r_.zo()):t&&t.code===_.UNAUTHENTICATED&&3!==this.state&&(this.authCredentialsProvider.invalidateToken(),this.appCheckCredentialsProvider.invalidateToken()),null!==this.stream&&(this.P_(),this.stream.close(),this.stream=null),this.state=e,await this.listener.po(t)}P_(){}auth(){this.state=1;const e=this.T_(this.Xo),t=this.Xo;Promise.all([this.authCredentialsProvider.getToken(),this.appCheckCredentialsProvider.getToken()]).then((([e,n])=>{this.Xo===t&&this.I_(e,n)}),(t=>{e((()=>{const e=new I(_.UNKNOWN,"Fetching auth token failed: "+t.message);return this.E_(e)}))}))}I_(e,t){const n=this.T_(this.Xo);this.stream=this.d_(e,t),this.stream.Ro((()=>{n((()=>this.listener.Ro()))})),this.stream.mo((()=>{n((()=>(this.state=2,this.t_=this.li.enqueueAfterDelay(this.Zo,1e4,(()=>(this.s_()&&(this.state=3),Promise.resolve()))),this.listener.mo())))})),this.stream.po((e=>{n((()=>this.E_(e)))})),this.stream.onMessage((e=>{n((()=>1==++this.n_?this.A_(e):this.onNext(e)))}))}o_(){this.state=5,this.r_.jo((async()=>{this.state=0,this.start()}))}E_(e){return g("PersistentStream",`close with error: ${e}`),this.stream=null,this.close(4,e)}T_(e){return t=>{this.li.enqueueAndForget((()=>this.Xo===e?t():(g("PersistentStream","stream callback skipped by getCloseGuardedDispatcher."),Promise.resolve())))}}}class _a extends ba{constructor(e,t,n,r,i,s){super(e,"listen_stream_connection_backoff","listen_stream_idle","health_check_timeout",t,n,r,s),this.serializer=i}d_(e,t){return this.connection.qo("Listen",e,t)}A_(e){return this.onNext(e)}onNext(e){this.r_.reset();const t=function(e,t){let n;if("targetChange"in t){t.targetChange;const r=function(e){return"NO_CHANGE"===e?0:"ADD"===e?1:"REMOVE"===e?2:"CURRENT"===e?3:"RESET"===e?4:v()}(t.targetChange.targetChangeType||"NO_CHANGE"),i=t.targetChange.targetIds||[],s=function(e,t){return e.useProto3Json?(w(void 0===t||"string"==typeof t),lt.fromBase64String(t||"")):(w(void 0===t||t instanceof Buffer||t instanceof Uint8Array),lt.fromUint8Array(t||new Uint8Array))}(e,t.targetChange.resumeToken),o=t.targetChange.cause,a=o&&function(e){const t=void 0===e.code?_.UNKNOWN:Gr(e.code);return new I(t,e.message||"")}(o);n=new ri(r,i,s,a||null)}else if("documentChange"in t){t.documentChange;const r=t.documentChange;r.document,r.document.name,r.document.updateTime;const i=_i(e,r.document.name),s=mi(r.document.updateTime),o=r.document.createTime?mi(r.document.createTime):V.min(),a=new Gt({mapValue:{fields:r.document.fields}}),c=Qt.newFoundDocument(i,s,o,a),u=r.targetIds||[],l=r.removedTargetIds||[];n=new ti(u,l,c.key,c)}else if("documentDelete"in t){t.documentDelete;const r=t.documentDelete;r.document;const i=_i(e,r.document),s=r.readTime?mi(r.readTime):V.min(),o=Qt.newNoDocument(i,s),a=r.removedTargetIds||[];n=new ti([],a,o.key,o)}else if("documentRemove"in t){t.documentRemove;const r=t.documentRemove;r.document;const i=_i(e,r.document),s=r.removedTargetIds||[];n=new ti([],s,i,null)}else{if(!("filter"in t))return v();{t.filter;const e=t.filter;e.targetId;const{count:r=0,unchangedNames:i}=e,s=new Ur(r,i),o=e.targetId;n=new ni(o,s)}}return n}(this.serializer,e),n=function(e){if(!("targetChange"in e))return V.min();const t=e.targetChange;return t.targetIds&&t.targetIds.length?V.min():t.readTime?mi(t.readTime):V.min()}(e);return this.listener.R_(t,n)}V_(e){const t={};t.database=Ti(this.serializer),t.addTarget=function(e,t){let n;const r=t.target;if(n=En(r)?{documents:ki(e,r)}:{query:Ni(e,r).ct},n.targetId=t.targetId,t.resumeToken.approximateByteSize()>0){n.resumeToken=gi(e,t.resumeToken);const r=di(e,t.expectedCount);null!==r&&(n.expectedCount=r)}else if(t.snapshotVersion.compareTo(V.min())>0){n.readTime=fi(e,t.snapshotVersion.toTimestamp());const r=di(e,t.expectedCount);null!==r&&(n.expectedCount=r)}return n}(this.serializer,e);const n=function(e,t){const n=function(e){switch(e){case"TargetPurposeListen":return null;case"TargetPurposeExistenceFilterMismatch":return"existence-filter-mismatch";case"TargetPurposeExistenceFilterMismatchBloom":return"existence-filter-mismatch-bloom";case"TargetPurposeLimboResolution":return"limbo-document";default:return v()}}(t.purpose);return null==n?null:{"goog-listen-tags":n}}(this.serializer,e);n&&(t.labels=n),this.c_(t)}m_(e){const t={};t.database=Ti(this.serializer),t.removeTarget=e,this.c_(t)}}class Ia extends ba{constructor(e,t,n,r,i,s){super(e,"write_stream_connection_backoff","write_stream_idle","health_check_timeout",t,n,r,s),this.serializer=i}get f_(){return this.n_>0}start(){this.lastStreamToken=void 0,super.start()}P_(){this.f_&&this.g_([])}d_(e,t){return this.connection.qo("Write",e,t)}A_(e){return w(!!e.streamToken),this.lastStreamToken=e.streamToken,w(!e.writeResults||0===e.writeResults.length),this.listener.p_()}onNext(e){w(!!e.streamToken),this.lastStreamToken=e.streamToken,this.r_.reset();const t=function(e,t){return e&&e.length>0?(w(void 0!==t),e.map((e=>function(e,t){let n=e.updateTime?mi(e.updateTime):mi(t);return n.isEqual(V.min())&&(n=mi(t)),new _r(n,e.transformResults||[])}(e,t)))):[]}(e.writeResults,e.commitTime),n=mi(e.commitTime);return this.listener.y_(n,t)}w_(){const e={};e.database=Ti(this.serializer),this.c_(e)}g_(e){const t={streamToken:this.lastStreamToken,writes:e.map((e=>Di(this.serializer,e)))};this.c_(t)}}class Ea extends class{}{constructor(e,t,n,r){super(),this.authCredentials=e,this.appCheckCredentials=t,this.connection=n,this.serializer=r,this.S_=!1}b_(){if(this.S_)throw new I(_.FAILED_PRECONDITION,"The client has already been terminated.")}Oo(e,t,n,r){return this.b_(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then((([i,s])=>this.connection.Oo(e,vi(t,n),r,i,s))).catch((e=>{throw"FirebaseError"===e.name?(e.code===_.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),e):new I(_.UNKNOWN,e.toString())}))}ko(e,t,n,r,i){return this.b_(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then((([s,o])=>this.connection.ko(e,vi(t,n),r,s,o,i))).catch((e=>{throw"FirebaseError"===e.name?(e.code===_.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),e):new I(_.UNKNOWN,e.toString())}))}terminate(){this.S_=!0,this.connection.terminate()}}class Ta{constructor(e,t){this.asyncQueue=e,this.onlineStateHandler=t,this.state="Unknown",this.D_=0,this.v_=null,this.C_=!0}F_(){0===this.D_&&(this.M_("Unknown"),this.v_=this.asyncQueue.enqueueAfterDelay("online_state_timeout",1e4,(()=>(this.v_=null,this.x_("Backend didn't respond within 10 seconds."),this.M_("Offline"),Promise.resolve()))))}O_(e){"Online"===this.state?this.M_("Unknown"):(this.D_++,this.D_>=1&&(this.N_(),this.x_(`Connection failed 1 times. Most recent error: ${e.toString()}`),this.M_("Offline")))}set(e){this.N_(),this.D_=0,"Online"===e&&(this.C_=!1),this.M_(e)}M_(e){e!==this.state&&(this.state=e,this.onlineStateHandler(e))}x_(e){const t=`Could not reach Cloud Firestore backend. ${e}\nThis typically indicates that your device does not have a healthy Internet connection at the moment. The client will operate in offline mode until it is able to successfully connect to the backend.`;this.C_?(p(t),this.C_=!1):g("OnlineStateTracker",t)}N_(){null!==this.v_&&(this.v_.cancel(),this.v_=null)}}class Sa{constructor(e,t,n,r,i){this.localStore=e,this.datastore=t,this.asyncQueue=n,this.remoteSyncer={},this.L_=[],this.B_=new Map,this.k_=new Set,this.q_=[],this.Q_=i,this.Q_.uo((e=>{n.enqueueAndForget((async()=>{Ma(this)&&(g("RemoteStore","Restarting streams for network reachability change."),await async function(e){const t=b(e);t.k_.add(4),await Ca(t),t.K_.set("Unknown"),t.k_.delete(4),await xa(t)}(this))}))})),this.K_=new Ta(n,r)}}async function xa(e){if(Ma(e))for(const t of e.q_)await t(!0)}async function Ca(e){for(const t of e.q_)await t(!1)}function Da(e,t){const n=b(e);n.B_.has(t.targetId)||(n.B_.set(t.targetId,t),Oa(n)?La(n):Za(n).s_()&&ka(n,t))}function Aa(e,t){const n=b(e),r=Za(n);n.B_.delete(t),r.s_()&&Na(n,t),0===n.B_.size&&(r.s_()?r.a_():Ma(n)&&n.K_.set("Unknown"))}function ka(e,t){if(e.U_.xe(t.targetId),t.resumeToken.approximateByteSize()>0||t.snapshotVersion.compareTo(V.min())>0){const n=e.remoteSyncer.getRemoteKeysForTarget(t.targetId).size;t=t.withExpectedCount(n)}Za(e).V_(t)}function Na(e,t){e.U_.xe(t),Za(e).m_(t)}function La(e){e.U_=new si({getRemoteKeysForTarget:t=>e.remoteSyncer.getRemoteKeysForTarget(t),ut:t=>e.B_.get(t)||null,nt:()=>e.datastore.serializer.databaseId}),Za(e).start(),e.K_.F_()}function Oa(e){return Ma(e)&&!Za(e).i_()&&e.B_.size>0}function Ma(e){return 0===b(e).k_.size}function Ra(e){e.U_=void 0}async function Pa(e){e.K_.set("Online")}async function Fa(e){e.B_.forEach(((t,n)=>{ka(e,t)}))}async function Va(e,t){Ra(e),Oa(e)?(e.K_.O_(t),La(e)):e.K_.set("Unknown")}async function qa(e,t,n){if(e.K_.set("Online"),t instanceof ri&&2===t.state&&t.cause)try{await async function(e,t){const n=t.cause;for(const r of t.targetIds)e.B_.has(r)&&(await e.remoteSyncer.rejectListen(r,n),e.B_.delete(r),e.U_.removeTarget(r))}(e,t)}catch(n){g("RemoteStore","Failed to remove targets %s: %s ",t.targetIds.join(","),n),await Ba(e,n)}else if(t instanceof ti?e.U_.$e(t):t instanceof ni?e.U_.Je(t):e.U_.Ge(t),!n.isEqual(V.min()))try{const t=await jo(e.localStore);n.compareTo(t)>=0&&await function(e,t){const n=e.U_.it(t);return n.targetChanges.forEach(((n,r)=>{if(n.resumeToken.approximateByteSize()>0){const i=e.B_.get(r);i&&e.B_.set(r,i.withResumeToken(n.resumeToken,t))}})),n.targetMismatches.forEach(((t,n)=>{const r=e.B_.get(t);if(!r)return;e.B_.set(t,r.withResumeToken(lt.EMPTY_BYTE_STRING,r.snapshotVersion)),Na(e,t);const i=new $i(r.target,t,n,r.sequenceNumber);ka(e,i)})),e.remoteSyncer.applyRemoteEvent(n)}(e,n)}catch(t){g("RemoteStore","Failed to raise snapshot:",t),await Ba(e,t)}}async function Ba(e,t,n){if(!le(t))throw t;e.k_.add(1),await Ca(e),e.K_.set("Offline"),n||(n=()=>jo(e.localStore)),e.asyncQueue.enqueueRetryable((async()=>{g("RemoteStore","Retrying IndexedDB access"),await n(),e.k_.delete(1),await xa(e)}))}function Ua(e,t){return t().catch((n=>Ba(e,n,t)))}async function ja(e){const t=b(e),n=ec(t);let r=t.L_.length>0?t.L_[t.L_.length-1].batchId:-1;for(;$a(t);)try{const e=await zo(t.localStore,r);if(null===e){0===t.L_.length&&n.a_();break}r=e.batchId,za(t,e)}catch(e){await Ba(t,e)}Ga(t)&&Ka(t)}function $a(e){return Ma(e)&&e.L_.length<10}function za(e,t){e.L_.push(t);const n=ec(e);n.s_()&&n.f_&&n.g_(t.mutations)}function Ga(e){return Ma(e)&&!ec(e).i_()&&e.L_.length>0}function Ka(e){ec(e).start()}async function Qa(e){ec(e).w_()}async function Ha(e){const t=ec(e);for(const n of e.L_)t.g_(n.mutations)}async function Wa(e,t,n){const r=e.L_.shift(),i=Vr.from(r,t,n);await Ua(e,(()=>e.remoteSyncer.applySuccessfulWrite(i))),await ja(e)}async function Ja(e,t){t&&ec(e).f_&&await async function(e,t){if(function(e){return zr(e)&&e!==_.ABORTED}(t.code)){const n=e.L_.shift();ec(e).__(),await Ua(e,(()=>e.remoteSyncer.rejectFailedWrite(n.batchId,t))),await ja(e)}}(e,t),Ga(e)&&Ka(e)}async function Xa(e,t){const n=b(e);n.asyncQueue.verifyOperationInProgress(),g("RemoteStore","RemoteStore received new credentials");const r=Ma(n);n.k_.add(3),await Ca(n),r&&n.K_.set("Unknown"),await n.remoteSyncer.handleCredentialChange(t),n.k_.delete(3),await xa(n)}async function Ya(e,t){const n=b(e);t?(n.k_.delete(2),await xa(n)):t||(n.k_.add(2),await Ca(n),n.K_.set("Unknown"))}function Za(e){return e.W_||(e.W_=function(e,t,n){const r=b(e);return r.b_(),new _a(t,r.connection,r.authCredentials,r.appCheckCredentials,r.serializer,n)}(e.datastore,e.asyncQueue,{Ro:Pa.bind(null,e),mo:Fa.bind(null,e),po:Va.bind(null,e),R_:qa.bind(null,e)}),e.q_.push((async t=>{t?(e.W_.__(),Oa(e)?La(e):e.K_.set("Unknown")):(await e.W_.stop(),Ra(e))}))),e.W_}function ec(e){return e.G_||(e.G_=function(e,t,n){const r=b(e);return r.b_(),new Ia(t,r.connection,r.authCredentials,r.appCheckCredentials,r.serializer,n)}(e.datastore,e.asyncQueue,{Ro:()=>Promise.resolve(),mo:Qa.bind(null,e),po:Ja.bind(null,e),p_:Ha.bind(null,e),y_:Wa.bind(null,e)}),e.q_.push((async t=>{t?(e.G_.__(),await ja(e)):(await e.G_.stop(),e.L_.length>0&&(g("RemoteStore",`Stopping write stream with ${e.L_.length} pending writes`),e.L_=[]))}))),e.G_}class tc{constructor(e,t,n,r,i){this.asyncQueue=e,this.timerId=t,this.targetTimeMs=n,this.op=r,this.removalCallback=i,this.deferred=new E,this.then=this.deferred.promise.then.bind(this.deferred.promise),this.deferred.promise.catch((e=>{}))}get promise(){return this.deferred.promise}static createAndSchedule(e,t,n,r,i){const s=Date.now()+n,o=new tc(e,t,s,r,i);return o.start(n),o}start(e){this.timerHandle=setTimeout((()=>this.handleDelayElapsed()),e)}skipDelay(){return this.handleDelayElapsed()}cancel(e){null!==this.timerHandle&&(this.clearTimeout(),this.deferred.reject(new I(_.CANCELLED,"Operation cancelled"+(e?": "+e:""))))}handleDelayElapsed(){this.asyncQueue.enqueueAndForget((()=>null!==this.timerHandle?(this.clearTimeout(),this.op().then((e=>this.deferred.resolve(e)))):Promise.resolve()))}clearTimeout(){null!==this.timerHandle&&(this.removalCallback(this),clearTimeout(this.timerHandle),this.timerHandle=null)}}function nc(e,t){if(p("AsyncQueue",`${t}: ${e}`),le(e))return new I(_.UNAVAILABLE,`${t}: ${e}`);throw e}class rc{static emptySet(e){return new rc(e.comparator)}constructor(e){this.comparator=e?(t,n)=>e(t,n)||$.comparator(t.key,n.key):(e,t)=>$.comparator(e.key,t.key),this.keyedMap=Wn(),this.sortedSet=new nt(this.comparator)}has(e){return null!=this.keyedMap.get(e)}get(e){return this.keyedMap.get(e)}first(){return this.sortedSet.minKey()}last(){return this.sortedSet.maxKey()}isEmpty(){return this.sortedSet.isEmpty()}indexOf(e){const t=this.keyedMap.get(e);return t?this.sortedSet.indexOf(t):-1}get size(){return this.sortedSet.size}forEach(e){this.sortedSet.inorderTraversal(((t,n)=>(e(t),!1)))}add(e){const t=this.delete(e.key);return t.copy(t.keyedMap.insert(e.key,e),t.sortedSet.insert(e,null))}delete(e){const t=this.get(e);return t?this.copy(this.keyedMap.remove(e),this.sortedSet.remove(t)):this}isEqual(e){if(!(e instanceof rc))return!1;if(this.size!==e.size)return!1;const t=this.sortedSet.getIterator(),n=e.sortedSet.getIterator();for(;t.hasNext();){const e=t.getNext().key,r=n.getNext().key;if(!e.isEqual(r))return!1}return!0}toString(){const e=[];return this.forEach((t=>{e.push(t.toString())})),0===e.length?"DocumentSet ()":"DocumentSet (\n "+e.join(" \n")+"\n)"}copy(e,t){const n=new rc;return n.comparator=this.comparator,n.keyedMap=e,n.sortedSet=t,n}}class ic{constructor(){this.z_=new nt($.comparator)}track(e){const t=e.doc.key,n=this.z_.get(t);n?0!==e.type&&3===n.type?this.z_=this.z_.insert(t,e):3===e.type&&1!==n.type?this.z_=this.z_.insert(t,{type:n.type,doc:e.doc}):2===e.type&&2===n.type?this.z_=this.z_.insert(t,{type:2,doc:e.doc}):2===e.type&&0===n.type?this.z_=this.z_.insert(t,{type:0,doc:e.doc}):1===e.type&&0===n.type?this.z_=this.z_.remove(t):1===e.type&&2===n.type?this.z_=this.z_.insert(t,{type:1,doc:n.doc}):0===e.type&&1===n.type?this.z_=this.z_.insert(t,{type:2,doc:e.doc}):v():this.z_=this.z_.insert(t,e)}j_(){const e=[];return this.z_.inorderTraversal(((t,n)=>{e.push(n)})),e}}class sc{constructor(e,t,n,r,i,s,o,a,c){this.query=e,this.docs=t,this.oldDocs=n,this.docChanges=r,this.mutatedKeys=i,this.fromCache=s,this.syncStateChanged=o,this.excludesMetadataChanges=a,this.hasCachedResults=c}static fromInitialDocuments(e,t,n,r,i){const s=[];return t.forEach((e=>{s.push({type:0,doc:e})})),new sc(e,t,rc.emptySet(t),s,n,r,!0,!1,i)}get hasPendingWrites(){return!this.mutatedKeys.isEmpty()}isEqual(e){if(!(this.fromCache===e.fromCache&&this.hasCachedResults===e.hasCachedResults&&this.syncStateChanged===e.syncStateChanged&&this.mutatedKeys.isEqual(e.mutatedKeys)&&Vn(this.query,e.query)&&this.docs.isEqual(e.docs)&&this.oldDocs.isEqual(e.oldDocs)))return!1;const t=this.docChanges,n=e.docChanges;if(t.length!==n.length)return!1;for(let e=0;e<t.length;e++)if(t[e].type!==n[e].type||!t[e].doc.isEqual(n[e].doc))return!1;return!0}}class oc{constructor(){this.H_=void 0,this.J_=[]}Y_(){return this.J_.some((e=>e.Z_()))}}class ac{constructor(){this.queries=cc(),this.onlineState="Unknown",this.X_=new Set}terminate(){!function(e,t){const n=b(e),r=n.queries;n.queries=cc(),r.forEach(((e,n)=>{for(const e of n.J_)e.onError(t)}))}(this,new I(_.ABORTED,"Firestore shutting down"))}}function cc(){return new Gn((e=>qn(e)),Vn)}async function uc(e,t){const n=b(e);let r=3;const i=t.query;let s=n.queries.get(i);s?!s.Y_()&&t.Z_()&&(r=2):(s=new oc,r=t.Z_()?0:1);try{switch(r){case 0:s.H_=await n.onListen(i,!0);break;case 1:s.H_=await n.onListen(i,!1);break;case 2:await n.onFirstRemoteStoreListen(i)}}catch(e){const n=nc(e,`Initialization of query '${Bn(t.query)}' failed`);return void t.onError(n)}n.queries.set(i,s),s.J_.push(t),t.ea(n.onlineState),s.H_&&t.ta(s.H_)&&fc(n)}async function lc(e,t){const n=b(e),r=t.query;let i=3;const s=n.queries.get(r);if(s){const e=s.J_.indexOf(t);e>=0&&(s.J_.splice(e,1),0===s.J_.length?i=t.Z_()?0:1:!s.Y_()&&t.Z_()&&(i=2))}switch(i){case 0:return n.queries.delete(r),n.onUnlisten(r,!0);case 1:return n.queries.delete(r),n.onUnlisten(r,!1);case 2:return n.onLastRemoteStoreUnlisten(r);default:return}}function hc(e,t){const n=b(e);let r=!1;for(const e of t){const t=e.query,i=n.queries.get(t);if(i){for(const t of i.J_)t.ta(e)&&(r=!0);i.H_=e}}r&&fc(n)}function dc(e,t,n){const r=b(e),i=r.queries.get(t);if(i)for(const e of i.J_)e.onError(n);r.queries.delete(t)}function fc(e){e.X_.forEach((e=>{e.next()}))}var gc,pc;(pc=gc||(gc={})).na="default",pc.Cache="cache";class mc{constructor(e,t,n){this.query=e,this.ra=t,this.ia=!1,this.sa=null,this.onlineState="Unknown",this.options=n||{}}ta(e){if(!this.options.includeMetadataChanges){const t=[];for(const n of e.docChanges)3!==n.type&&t.push(n);e=new sc(e.query,e.docs,e.oldDocs,t,e.mutatedKeys,e.fromCache,e.syncStateChanged,!0,e.hasCachedResults)}let t=!1;return this.ia?this.oa(e)&&(this.ra.next(e),t=!0):this._a(e,this.onlineState)&&(this.aa(e),t=!0),this.sa=e,t}onError(e){this.ra.error(e)}ea(e){this.onlineState=e;let t=!1;return this.sa&&!this.ia&&this._a(this.sa,e)&&(this.aa(this.sa),t=!0),t}_a(e,t){if(!e.fromCache)return!0;if(!this.Z_())return!0;const n="Offline"!==t;return(!this.options.ua||!n)&&(!e.docs.isEmpty()||e.hasCachedResults||"Offline"===t)}oa(e){if(e.docChanges.length>0)return!0;const t=this.sa&&this.sa.hasPendingWrites!==e.hasPendingWrites;return!(!e.syncStateChanged&&!t)&&!0===this.options.includeMetadataChanges}aa(e){e=sc.fromInitialDocuments(e.query,e.docs,e.mutatedKeys,e.fromCache,e.hasCachedResults),this.ia=!0,this.ra.next(e)}Z_(){return this.options.source!==gc.Cache}}class yc{constructor(e,t){this.ca=e,this.byteLength=t}la(){return"metadata"in this.ca}}class vc{constructor(e){this.serializer=e}As(e){return _i(this.serializer,e)}Rs(e){return e.metadata.exists?Ci(this.serializer,e.document,!1):Qt.newNoDocument(this.As(e.metadata.name),this.Vs(e.metadata.readTime))}Vs(e){return mi(e)}}class wc{constructor(e,t,n){this.ha=e,this.localStore=t,this.serializer=n,this.queries=[],this.documents=[],this.collectionGroups=new Set,this.progress=bc(e)}Pa(e){this.progress.bytesLoaded+=e.byteLength;let t=this.progress.documentsLoaded;if(e.ca.namedQuery)this.queries.push(e.ca.namedQuery);else if(e.ca.documentMetadata){this.documents.push({metadata:e.ca.documentMetadata}),e.ca.documentMetadata.exists||++t;const n=B.fromString(e.ca.documentMetadata.name);this.collectionGroups.add(n.get(n.length-2))}else e.ca.document&&(this.documents[this.documents.length-1].document=e.ca.document,++t);return t!==this.progress.documentsLoaded?(this.progress.documentsLoaded=t,Object.assign({},this.progress)):null}Ta(e){const t=new Map,n=new vc(this.serializer);for(const r of e)if(r.metadata.queries){const e=n.As(r.metadata.name);for(const n of r.metadata.queries){const r=(t.get(n)||nr()).add(e);t.set(n,r)}}return t}async complete(){const e=await async function(e,t,n,r){const i=b(e);let s=nr(),o=Qn();for(const e of n){const n=t.As(e.metadata.name);e.document&&(s=s.add(n));const r=t.Rs(e);r.setReadTime(t.Vs(e.metadata.readTime)),o=o.insert(n,r)}const a=i.hs.newChangeBuffer({trackRemovals:!0}),c=await Go(i,function(e){return On(An(B.fromString(`__bundle__/docs/${e}`)))}(r));return i.persistence.runTransaction("Apply bundle documents","readwrite",(e=>$o(e,a,o).next((t=>(a.apply(e),t))).next((t=>i.Gr.removeMatchingKeysForTargetId(e,c.targetId).next((()=>i.Gr.addMatchingKeys(e,s,c.targetId))).next((()=>i.localDocuments.getLocalViewOfDocuments(e,t.Is,t.Es))).next((()=>t.Is))))))}(this.localStore,new vc(this.serializer),this.documents,this.ha.id),t=this.Ta(this.documents);for(const e of this.queries)await Xo(this.localStore,e,t.get(e.name));return this.progress.taskState="Success",{progress:this.progress,Ia:this.collectionGroups,Ea:e}}}function bc(e){return{taskState:"Running",documentsLoaded:0,bytesLoaded:0,totalDocuments:e.totalDocuments,totalBytes:e.totalBytes}}class _c{constructor(e){this.key=e}}class Ic{constructor(e){this.key=e}}class Ec{constructor(e,t){this.query=e,this.da=t,this.Aa=null,this.hasCachedResults=!1,this.current=!1,this.Ra=nr(),this.mutatedKeys=nr(),this.Va=$n(e),this.ma=new rc(this.Va)}get fa(){return this.da}ga(e,t){const n=t?t.pa:new ic,r=t?t.ma:this.ma;let i=t?t.mutatedKeys:this.mutatedKeys,s=r,o=!1;const a="F"===this.query.limitType&&r.size===this.query.limit?r.last():null,c="L"===this.query.limitType&&r.size===this.query.limit?r.first():null;if(e.inorderTraversal(((e,t)=>{const u=r.get(e),l=Un(this.query,t)?t:null,h=!!u&&this.mutatedKeys.has(u.key),d=!!l&&(l.hasLocalMutations||this.mutatedKeys.has(l.key)&&l.hasCommittedMutations);let f=!1;u&&l?u.data.isEqual(l.data)?h!==d&&(n.track({type:3,doc:l}),f=!0):this.ya(u,l)||(n.track({type:2,doc:l}),f=!0,(a&&this.Va(l,a)>0||c&&this.Va(l,c)<0)&&(o=!0)):!u&&l?(n.track({type:0,doc:l}),f=!0):u&&!l&&(n.track({type:1,doc:u}),f=!0,(a||c)&&(o=!0)),f&&(l?(s=s.add(l),i=d?i.add(e):i.delete(e)):(s=s.delete(e),i=i.delete(e)))})),null!==this.query.limit)for(;s.size>this.query.limit;){const e="F"===this.query.limitType?s.last():s.first();s=s.delete(e.key),i=i.delete(e.key),n.track({type:1,doc:e})}return{ma:s,pa:n,ss:o,mutatedKeys:i}}ya(e,t){return e.hasLocalMutations&&t.hasCommittedMutations&&!t.hasLocalMutations}applyChanges(e,t,n,r){const i=this.ma;this.ma=e.ma,this.mutatedKeys=e.mutatedKeys;const s=e.pa.j_();s.sort(((e,t)=>function(e,t){const n=e=>{switch(e){case 0:return 1;case 2:case 3:return 2;case 1:return 0;default:return v()}};return n(e)-n(t)}(e.type,t.type)||this.Va(e.doc,t.doc))),this.wa(n),r=null!=r&&r;const o=t&&!r?this.Sa():[],a=0===this.Ra.size&&this.current&&!r?1:0,c=a!==this.Aa;return this.Aa=a,0!==s.length||c?{snapshot:new sc(this.query,e.ma,i,s,e.mutatedKeys,0===a,c,!1,!!n&&n.resumeToken.approximateByteSize()>0),ba:o}:{ba:o}}ea(e){return this.current&&"Offline"===e?(this.current=!1,this.applyChanges({ma:this.ma,pa:new ic,mutatedKeys:this.mutatedKeys,ss:!1},!1)):{ba:[]}}Da(e){return!this.da.has(e)&&!!this.ma.has(e)&&!this.ma.get(e).hasLocalMutations}wa(e){e&&(e.addedDocuments.forEach((e=>this.da=this.da.add(e))),e.modifiedDocuments.forEach((e=>{})),e.removedDocuments.forEach((e=>this.da=this.da.delete(e))),this.current=e.current)}Sa(){if(!this.current)return[];const e=this.Ra;this.Ra=nr(),this.ma.forEach((e=>{this.Da(e.key)&&(this.Ra=this.Ra.add(e.key))}));const t=[];return e.forEach((e=>{this.Ra.has(e)||t.push(new Ic(e))})),this.Ra.forEach((n=>{e.has(n)||t.push(new _c(n))})),t}va(e){this.da=e.ds,this.Ra=nr();const t=this.ga(e.documents);return this.applyChanges(t,!0)}Ca(){return sc.fromInitialDocuments(this.query,this.ma,this.mutatedKeys,0===this.Aa,this.hasCachedResults)}}class Tc{constructor(e,t,n){this.query=e,this.targetId=t,this.view=n}}class Sc{constructor(e){this.key=e,this.Fa=!1}}class xc{constructor(e,t,n,r,i,s){this.localStore=e,this.remoteStore=t,this.eventManager=n,this.sharedClientState=r,this.currentUser=i,this.maxConcurrentLimboResolutions=s,this.Ma={},this.xa=new Gn((e=>qn(e)),Vn),this.Oa=new Map,this.Na=new Set,this.La=new nt($.comparator),this.Ba=new Map,this.ka=new wo,this.qa={},this.Qa=new Map,this.Ka=Ks.Qn(),this.onlineState="Unknown",this.$a=void 0}get isPrimaryClient(){return!0===this.$a}}async function Cc(e,t,n=!0){const r=nu(e);let i;const s=r.xa.get(t);return s?(r.sharedClientState.addLocalQueryTarget(s.targetId),i=s.view.Ca()):i=await Ac(r,t,n,!0),i}async function Dc(e,t){const n=nu(e);await Ac(n,t,!0,!1)}async function Ac(e,t,n,r){const i=await Go(e.localStore,On(t)),s=i.targetId,o=e.sharedClientState.addLocalQueryTarget(s,n);let a;return r&&(a=await kc(e,t,s,"current"===o,i.resumeToken)),e.isPrimaryClient&&n&&Da(e.remoteStore,i),a}async function kc(e,t,n,r,i){e.Ua=(t,n,r)=>async function(e,t,n,r){let i=t.view.ga(n);i.ss&&(i=await Qo(e.localStore,t.query,!1).then((({documents:e})=>t.view.ga(e,i))));const s=r&&r.targetChanges.get(t.targetId),o=r&&null!=r.targetMismatches.get(t.targetId),a=t.view.applyChanges(i,e.isPrimaryClient,s,o);return jc(e,t.targetId,a.ba),a.snapshot}(e,t,n,r);const s=await Qo(e.localStore,t,!0),o=new Ec(t,s.ds),a=o.ga(s.documents),c=ei.createSynthesizedTargetChangeForCurrentChange(n,r&&"Offline"!==e.onlineState,i),u=o.applyChanges(a,e.isPrimaryClient,c);jc(e,n,u.ba);const l=new Tc(t,n,o);return e.xa.set(t,l),e.Oa.has(n)?e.Oa.get(n).push(t):e.Oa.set(n,[t]),u.snapshot}async function Nc(e,t,n){const r=b(e),i=r.xa.get(t),s=r.Oa.get(i.targetId);if(s.length>1)return r.Oa.set(i.targetId,s.filter((e=>!Vn(e,t)))),void r.xa.delete(t);r.isPrimaryClient?(r.sharedClientState.removeLocalQueryTarget(i.targetId),r.sharedClientState.isActiveQueryTarget(i.targetId)||await Ko(r.localStore,i.targetId,!1).then((()=>{r.sharedClientState.clearQueryState(i.targetId),n&&Aa(r.remoteStore,i.targetId),Bc(r,i.targetId)})).catch(re)):(Bc(r,i.targetId),await Ko(r.localStore,i.targetId,!0))}async function Lc(e,t){const n=b(e),r=n.xa.get(t),i=n.Oa.get(r.targetId);n.isPrimaryClient&&1===i.length&&(n.sharedClientState.removeLocalQueryTarget(r.targetId),Aa(n.remoteStore,r.targetId))}async function Oc(e,t){const n=b(e);try{const e=await function(e,t){const n=b(e),r=t.snapshotVersion;let i=n.us;return n.persistence.runTransaction("Apply remote event","readwrite-primary",(e=>{const s=n.hs.newChangeBuffer({trackRemovals:!0});i=n.us;const o=[];t.targetChanges.forEach(((s,a)=>{const c=i.get(a);if(!c)return;o.push(n.Gr.removeMatchingKeys(e,s.removedDocuments,a).next((()=>n.Gr.addMatchingKeys(e,s.addedDocuments,a))));let u=c.withSequenceNumber(e.currentSequenceNumber);null!==t.targetMismatches.get(a)?u=u.withResumeToken(lt.EMPTY_BYTE_STRING,V.min()).withLastLimboFreeSnapshotVersion(V.min()):s.resumeToken.approximateByteSize()>0&&(u=u.withResumeToken(s.resumeToken,r)),i=i.insert(a,u),function(e,t,n){return 0===e.resumeToken.approximateByteSize()||t.snapshotVersion.toMicroseconds()-e.snapshotVersion.toMicroseconds()>=3e8||n.addedDocuments.size+n.modifiedDocuments.size+n.removedDocuments.size>0}(c,u,s)&&o.push(n.Gr.updateTargetData(e,u))}));let a=Qn(),c=nr();if(t.documentUpdates.forEach((r=>{t.resolvedLimboDocuments.has(r)&&o.push(n.persistence.referenceDelegate.updateLimboDocument(e,r))})),o.push($o(e,s,t.documentUpdates).next((e=>{a=e.Is,c=e.Es}))),!r.isEqual(V.min())){const t=n.Gr.getLastRemoteSnapshotVersion(e).next((t=>n.Gr.setTargetsMetadata(e,e.currentSequenceNumber,r)));o.push(t)}return ie.waitFor(o).next((()=>s.apply(e))).next((()=>n.localDocuments.getLocalViewOfDocuments(e,a,c))).next((()=>a))})).then((e=>(n.us=i,e)))}(n.localStore,t);t.targetChanges.forEach(((e,t)=>{const r=n.Ba.get(t);r&&(w(e.addedDocuments.size+e.modifiedDocuments.size+e.removedDocuments.size<=1),e.addedDocuments.size>0?r.Fa=!0:e.modifiedDocuments.size>0?w(r.Fa):e.removedDocuments.size>0&&(w(r.Fa),r.Fa=!1))})),await Gc(n,e,t)}catch(e){await re(e)}}function Mc(e,t,n){const r=b(e);if(r.isPrimaryClient&&0===n||!r.isPrimaryClient&&1===n){const e=[];r.xa.forEach(((n,r)=>{const i=r.view.ea(t);i.snapshot&&e.push(i.snapshot)})),function(e,t){const n=b(e);n.onlineState=t;let r=!1;n.queries.forEach(((e,n)=>{for(const e of n.J_)e.ea(t)&&(r=!0)})),r&&fc(n)}(r.eventManager,t),e.length&&r.Ma.R_(e),r.onlineState=t,r.isPrimaryClient&&r.sharedClientState.setOnlineState(t)}}async function Rc(e,t,n){const r=b(e);r.sharedClientState.updateQueryState(t,"rejected",n);const i=r.Ba.get(t),s=i&&i.key;if(s){let e=new nt($.comparator);e=e.insert(s,Qt.newNoDocument(s,V.min()));const n=nr().add(s),i=new Zr(V.min(),new Map,new nt(M),e,n);await Oc(r,i),r.La=r.La.remove(s),r.Ba.delete(t),zc(r)}else await Ko(r.localStore,t,!1).then((()=>Bc(r,t,n))).catch(re)}async function Pc(e,t){const n=b(e),r=t.batch.batchId;try{const e=await function(e,t){const n=b(e);return n.persistence.runTransaction("Acknowledge batch","readwrite-primary",(e=>{const r=t.batch.keys(),i=n.hs.newChangeBuffer({trackRemovals:!0});return function(e,t,n,r){const i=n.batch,s=i.keys();let o=ie.resolve();return s.forEach((e=>{o=o.next((()=>r.getEntry(t,e))).next((t=>{const s=n.docVersions.get(e);w(null!==s),t.version.compareTo(s)<0&&(i.applyToRemoteDocument(t,n),t.isValidDocument()&&(t.setReadTime(n.commitVersion),r.addEntry(t)))}))})),o.next((()=>e.mutationQueue.removeMutationBatch(t,i)))}(n,e,t,i).next((()=>i.apply(e))).next((()=>n.mutationQueue.performConsistencyCheck(e))).next((()=>n.documentOverlayCache.removeOverlaysForBatchId(e,r,t.batch.batchId))).next((()=>n.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(e,function(e){let t=nr();for(let n=0;n<e.mutationResults.length;++n)e.mutationResults[n].transformResults.length>0&&(t=t.add(e.batch.mutations[n].key));return t}(t)))).next((()=>n.localDocuments.getDocuments(e,r)))}))}(n.localStore,t);qc(n,r,null),Vc(n,r),n.sharedClientState.updateMutationState(r,"acknowledged"),await Gc(n,e)}catch(e){await re(e)}}async function Fc(e,t,n){const r=b(e);try{const e=await function(e,t){const n=b(e);return n.persistence.runTransaction("Reject batch","readwrite-primary",(e=>{let r;return n.mutationQueue.lookupMutationBatch(e,t).next((t=>(w(null!==t),r=t.keys(),n.mutationQueue.removeMutationBatch(e,t)))).next((()=>n.mutationQueue.performConsistencyCheck(e))).next((()=>n.documentOverlayCache.removeOverlaysForBatchId(e,r,t))).next((()=>n.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(e,r))).next((()=>n.localDocuments.getDocuments(e,r)))}))}(r.localStore,t);qc(r,t,n),Vc(r,t),r.sharedClientState.updateMutationState(t,"rejected",n),await Gc(r,e)}catch(n){await re(n)}}function Vc(e,t){(e.Qa.get(t)||[]).forEach((e=>{e.resolve()})),e.Qa.delete(t)}function qc(e,t,n){const r=b(e);let i=r.qa[r.currentUser.toKey()];if(i){const e=i.get(t);e&&(n?e.reject(n):e.resolve(),i=i.remove(t)),r.qa[r.currentUser.toKey()]=i}}function Bc(e,t,n=null){e.sharedClientState.removeLocalQueryTarget(t);for(const r of e.Oa.get(t))e.xa.delete(r),n&&e.Ma.Wa(r,n);e.Oa.delete(t),e.isPrimaryClient&&e.ka.yr(t).forEach((t=>{e.ka.containsKey(t)||Uc(e,t)}))}function Uc(e,t){e.Na.delete(t.path.canonicalString());const n=e.La.get(t);null!==n&&(Aa(e.remoteStore,n),e.La=e.La.remove(t),e.Ba.delete(n),zc(e))}function jc(e,t,n){for(const r of n)r instanceof _c?(e.ka.addReference(r.key,t),$c(e,r)):r instanceof Ic?(g("SyncEngine","Document no longer in limbo: "+r.key),e.ka.removeReference(r.key,t),e.ka.containsKey(r.key)||Uc(e,r.key)):v()}function $c(e,t){const n=t.key,r=n.path.canonicalString();e.La.get(n)||e.Na.has(r)||(g("SyncEngine","New document in limbo: "+n),e.Na.add(r),zc(e))}function zc(e){for(;e.Na.size>0&&e.La.size<e.maxConcurrentLimboResolutions;){const t=e.Na.values().next().value;e.Na.delete(t);const n=new $(B.fromString(t)),r=e.Ka.next();e.Ba.set(r,new Sc(n)),e.La=e.La.insert(n,r),Da(e.remoteStore,new $i(On(An(n.path)),r,"TargetPurposeLimboResolution",ye.oe))}}async function Gc(e,t,n){const r=b(e),i=[],s=[],o=[];r.xa.isEmpty()||(r.xa.forEach(((e,a)=>{o.push(r.Ua(a,t,n).then((e=>{var t;if((e||n)&&r.isPrimaryClient){const i=e?!e.fromCache:null===(t=null==n?void 0:n.targetChanges.get(a.targetId))||void 0===t?void 0:t.current;r.sharedClientState.updateQueryState(a.targetId,i?"current":"not-current")}if(e){i.push(e);const t=Po.zi(a.targetId,e);s.push(t)}})))})),await Promise.all(o),r.Ma.R_(i),await async function(e,t){const n=b(e);try{await n.persistence.runTransaction("notifyLocalViewChanges","readwrite",(e=>ie.forEach(t,(t=>ie.forEach(t.Wi,(r=>n.persistence.referenceDelegate.addReference(e,t.targetId,r))).next((()=>ie.forEach(t.Gi,(r=>n.persistence.referenceDelegate.removeReference(e,t.targetId,r)))))))))}catch(e){if(!le(e))throw e;g("LocalStore","Failed to update sequence numbers: "+e)}for(const e of t){const t=e.targetId;if(!e.fromCache){const e=n.us.get(t),r=e.snapshotVersion,i=e.withLastLimboFreeSnapshotVersion(r);n.us=n.us.insert(t,i)}}}(r.localStore,s))}async function Kc(e,t){const n=b(e);if(!n.currentUser.isEqual(t)){g("SyncEngine","User change. New user:",t.toKey());const e=await Uo(n.localStore,t);n.currentUser=t,function(e){e.Qa.forEach((e=>{e.forEach((e=>{e.reject(new I(_.CANCELLED,"'waitForPendingWrites' promise is rejected due to a user change."))}))})),e.Qa.clear()}(n),n.sharedClientState.handleUserChange(t,e.removedBatchIds,e.addedBatchIds),await Gc(n,e.Ts)}}function Qc(e,t){const n=b(e),r=n.Ba.get(t);if(r&&r.Fa)return nr().add(r.key);{let e=nr();const r=n.Oa.get(t);if(!r)return e;for(const t of r){const r=n.xa.get(t);e=e.unionWith(r.view.fa)}return e}}async function Hc(e,t){const n=b(e),r=await Qo(n.localStore,t.query,!0),i=t.view.va(r);return n.isPrimaryClient&&jc(n,t.targetId,i.ba),i}async function Wc(e,t){const n=b(e);return Wo(n.localStore,t).then((e=>Gc(n,e)))}async function Jc(e,t,n,r){const i=b(e),s=await function(e,t){const n=b(e),r=b(n.mutationQueue);return n.persistence.runTransaction("Lookup mutation documents","readonly",(e=>r.On(e,t).next((t=>t?n.localDocuments.getDocuments(e,t):ie.resolve(null)))))}(i.localStore,t);null!==s?("pending"===n?await ja(i.remoteStore):"acknowledged"===n||"rejected"===n?(qc(i,t,r||null),Vc(i,t),function(e,t){b(b(e).mutationQueue).Ln(t)}(i.localStore,t)):v(),await Gc(i,s)):g("SyncEngine","Cannot apply mutation batch with id: "+t)}async function Xc(e,t,n){const r=b(e),i=[],s=[];for(const e of t){let t;const n=r.Oa.get(e);if(n&&0!==n.length){t=await Go(r.localStore,On(n[0]));for(const e of n){const t=r.xa.get(e),n=await Hc(r,t);n.snapshot&&s.push(n.snapshot)}}else{const n=await Ho(r.localStore,e);t=await Go(r.localStore,n),await kc(r,Yc(n),e,!1,t.resumeToken)}i.push(t)}return r.Ma.R_(s),i}function Yc(e){return Dn(e.path,e.collectionGroup,e.orderBy,e.filters,e.limit,"F",e.startAt,e.endAt)}function Zc(e){return function(e){return b(b(e).persistence).$i()}(b(e).localStore)}async function eu(e,t,n,r){const i=b(e);if(i.$a)return void g("SyncEngine","Ignoring unexpected query state notification.");const s=i.Oa.get(t);if(s&&s.length>0)switch(n){case"current":case"not-current":{const e=await Wo(i.localStore,jn(s[0])),r=Zr.createSynthesizedRemoteEventForCurrentChange(t,"current"===n,lt.EMPTY_BYTE_STRING);await Gc(i,e,r);break}case"rejected":await Ko(i.localStore,t,!0),Bc(i,t,r);break;default:v()}}async function tu(e,t,n){const r=nu(e);if(r.$a){for(const e of t){if(r.Oa.has(e)&&r.sharedClientState.isActiveQueryTarget(e)){g("SyncEngine","Adding an already active target "+e);continue}const t=await Ho(r.localStore,e),n=await Go(r.localStore,t);await kc(r,Yc(t),n.targetId,!1,n.resumeToken),Da(r.remoteStore,n)}for(const e of n)r.Oa.has(e)&&await Ko(r.localStore,e,!1).then((()=>{Aa(r.remoteStore,e),Bc(r,e)})).catch(re)}}function nu(e){const t=b(e);return t.remoteStore.remoteSyncer.applyRemoteEvent=Oc.bind(null,t),t.remoteStore.remoteSyncer.getRemoteKeysForTarget=Qc.bind(null,t),t.remoteStore.remoteSyncer.rejectListen=Rc.bind(null,t),t.Ma.R_=hc.bind(null,t.eventManager),t.Ma.Wa=dc.bind(null,t.eventManager),t}function ru(e){const t=b(e);return t.remoteStore.remoteSyncer.applySuccessfulWrite=Pc.bind(null,t),t.remoteStore.remoteSyncer.rejectFailedWrite=Fc.bind(null,t),t}class iu{constructor(){this.kind="memory",this.synchronizeTabs=!1}async initialize(e){this.serializer=va(e.databaseInfo.databaseId),this.sharedClientState=this.za(e),this.persistence=this.ja(e),await this.persistence.start(),this.localStore=this.Ha(e),this.gcScheduler=this.Ja(e,this.localStore),this.indexBackfillerScheduler=this.Ya(e,this.localStore)}Ja(e,t){return null}Ya(e,t){return null}Ha(e){return Bo(this.persistence,new Vo,e.initialUser,this.serializer)}ja(e){return new So(Co.ei,this.serializer)}za(e){return new aa}async terminate(){var e,t;null===(e=this.gcScheduler)||void 0===e||e.stop(),null===(t=this.indexBackfillerScheduler)||void 0===t||t.stop(),this.sharedClientState.shutdown(),await this.persistence.shutdown()}}iu.provider={build:()=>new iu};class su extends iu{constructor(e){super(),this.cacheSizeBytes=e}Ja(e,t){w(this.persistence.referenceDelegate instanceof Do);const n=this.persistence.referenceDelegate.garbageCollector;return new Zs(n,e.asyncQueue,t)}ja(e){const t=void 0!==this.cacheSizeBytes?Vs.withCacheSize(this.cacheSizeBytes):Vs.DEFAULT;return new So((e=>Do.ei(e,t)),this.serializer)}}class ou extends iu{constructor(e,t,n){super(),this.Za=e,this.cacheSizeBytes=t,this.forceOwnership=n,this.kind="persistent",this.synchronizeTabs=!1}async initialize(e){await super.initialize(e),await this.Za.initialize(this,e),await ru(this.Za.syncEngine),await ja(this.Za.remoteStore),await this.persistence.Si((()=>(this.gcScheduler&&!this.gcScheduler.started&&this.gcScheduler.start(),this.indexBackfillerScheduler&&!this.indexBackfillerScheduler.started&&this.indexBackfillerScheduler.start(),Promise.resolve())))}Ha(e){return Bo(this.persistence,new Vo,e.initialUser,this.serializer)}Ja(e,t){const n=this.persistence.referenceDelegate.garbageCollector;return new Zs(n,e.asyncQueue,t)}Ya(e,t){const n=new me(t,this.persistence);return new pe(e.asyncQueue,n)}ja(e){const t=Ro(e.databaseInfo.databaseId,e.databaseInfo.persistenceKey),n=void 0!==this.cacheSizeBytes?Vs.withCacheSize(this.cacheSizeBytes):Vs.DEFAULT;return new Lo(this.synchronizeTabs,t,e.clientId,n,e.asyncQueue,ma(),ya(),this.serializer,this.sharedClientState,!!this.forceOwnership)}za(e){return new aa}}class au extends ou{constructor(e,t){super(e,t,!1),this.Za=e,this.cacheSizeBytes=t,this.synchronizeTabs=!0}async initialize(e){await super.initialize(e);const t=this.Za.syncEngine;this.sharedClientState instanceof oa&&(this.sharedClientState.syncEngine={io:Jc.bind(null,t),so:eu.bind(null,t),oo:tu.bind(null,t),$i:Zc.bind(null,t),ro:Wc.bind(null,t)},await this.sharedClientState.start()),await this.persistence.Si((async e=>{await async function(e,t){const n=b(e);if(nu(n),ru(n),!0===t&&!0!==n.$a){const e=n.sharedClientState.getAllActiveQueryTargets(),t=await Xc(n,e.toArray());n.$a=!0,await Ya(n.remoteStore,!0);for(const e of t)Da(n.remoteStore,e)}else if(!1===t&&!1!==n.$a){const e=[];let t=Promise.resolve();n.Oa.forEach(((r,i)=>{n.sharedClientState.isLocalQueryTarget(i)?e.push(i):t=t.then((()=>(Bc(n,i),Ko(n.localStore,i,!0)))),Aa(n.remoteStore,i)})),await t,await Xc(n,e),function(e){const t=b(e);t.Ba.forEach(((e,n)=>{Aa(t.remoteStore,n)})),t.ka.wr(),t.Ba=new Map,t.La=new nt($.comparator)}(n),n.$a=!1,await Ya(n.remoteStore,!1)}}(this.Za.syncEngine,e),this.gcScheduler&&(e&&!this.gcScheduler.started?this.gcScheduler.start():e||this.gcScheduler.stop()),this.indexBackfillerScheduler&&(e&&!this.indexBackfillerScheduler.started?this.indexBackfillerScheduler.start():e||this.indexBackfillerScheduler.stop())}))}za(e){const t=ma();if(!oa.p(t))throw new I(_.UNIMPLEMENTED,"IndexedDB persistence is only available on platforms that support LocalStorage.");const n=Ro(e.databaseInfo.databaseId,e.databaseInfo.persistenceKey);return new oa(t,e.asyncQueue,n,e.clientId,e.initialUser)}}class cu{async initialize(e,t){this.localStore||(this.localStore=e.localStore,this.sharedClientState=e.sharedClientState,this.datastore=this.createDatastore(t),this.remoteStore=this.createRemoteStore(t),this.eventManager=this.createEventManager(t),this.syncEngine=this.createSyncEngine(t,!e.synchronizeTabs),this.sharedClientState.onlineStateHandler=e=>Mc(this.syncEngine,e,1),this.remoteStore.remoteSyncer.handleCredentialChange=Kc.bind(null,this.syncEngine),await Ya(this.remoteStore,this.syncEngine.isPrimaryClient))}createEventManager(e){return new ac}createDatastore(e){const t=va(e.databaseInfo.databaseId),n=function(e){return new pa(e)}(e.databaseInfo);return function(e,t,n,r){return new Ea(e,t,n,r)}(e.authCredentials,e.appCheckCredentials,n,t)}createRemoteStore(e){return function(e,t,n,r,i){return new Sa(e,t,n,r,i)}(this.localStore,this.datastore,e.asyncQueue,(e=>Mc(this.syncEngine,e,0)),ua.p()?new ua:new ca)}createSyncEngine(e,t){return function(e,t,n,r,i,s,o){const a=new xc(e,t,n,r,i,s);return o&&(a.$a=!0),a}(this.localStore,this.remoteStore,this.eventManager,this.sharedClientState,e.initialUser,e.maxConcurrentLimboResolutions,t)}async terminate(){var e,t;await async function(e){const t=b(e);g("RemoteStore","RemoteStore shutting down."),t.k_.add(5),await Ca(t),t.Q_.shutdown(),t.K_.set("Unknown")}(this.remoteStore),null===(e=this.datastore)||void 0===e||e.terminate(),null===(t=this.eventManager)||void 0===t||t.terminate()}}function uu(e,t=10240){let n=0;return{async read(){if(n<e.byteLength){const r={value:e.slice(n,n+t),done:!1};return n+=t,r}return{done:!0}},async cancel(){},releaseLock(){},closed:Promise.resolve()}}cu.provider={build:()=>new cu};class lu{constructor(e){this.observer=e,this.muted=!1}next(e){this.muted||this.observer.next&&this.Xa(this.observer.next,e)}error(e){this.muted||(this.observer.error?this.Xa(this.observer.error,e):p("Uncaught Error in snapshot listener:",e.toString()))}eu(){this.muted=!0}Xa(e,t){setTimeout((()=>{this.muted||e(t)}),0)}}class hu{constructor(e,t){this.tu=e,this.serializer=t,this.metadata=new E,this.buffer=new Uint8Array,this.nu=new TextDecoder("utf-8"),this.ru().then((e=>{e&&e.la()?this.metadata.resolve(e.ca.metadata):this.metadata.reject(new Error(`The first element of the bundle is not a metadata, it is\n ${JSON.stringify(null==e?void 0:e.ca)}`))}),(e=>this.metadata.reject(e)))}close(){return this.tu.cancel()}async getMetadata(){return this.metadata.promise}async Ga(){return await this.getMetadata(),this.ru()}async ru(){const e=await this.iu();if(null===e)return null;const t=this.nu.decode(e),n=Number(t);isNaN(n)&&this.su(`length string (${t}) is not valid number`);const r=await this.ou(n);return new yc(JSON.parse(r),e.length+n)}_u(){return this.buffer.findIndex((e=>e==="{".charCodeAt(0)))}async iu(){for(;this._u()<0&&!await this.au(););if(0===this.buffer.length)return null;const e=this._u();e<0&&this.su("Reached the end of bundle when a length string is expected.");const t=this.buffer.slice(0,e);return this.buffer=this.buffer.slice(e),t}async ou(e){for(;this.buffer.length<e;)await this.au()&&this.su("Reached the end of bundle when more is expected.");const t=this.nu.decode(this.buffer.slice(0,e));return this.buffer=this.buffer.slice(e),t}su(e){throw this.tu.cancel(),new Error(`Invalid bundle format: ${e}`)}async au(){const e=await this.tu.read();if(!e.done){const t=new Uint8Array(this.buffer.length+e.value.length);t.set(this.buffer),t.set(e.value,this.buffer.length),this.buffer=t}return e.done}}class du{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 I(_.INVALID_ARGUMENT,"Firestore transactions require all reads to be executed before all writes."),this.lastTransactionError;const t=await async function(e,t){const n=b(e),r={documents:t.map((e=>bi(n.serializer,e)))},i=await n.ko("BatchGetDocuments",n.serializer.databaseId,B.emptyPath(),r,t.length),s=new Map;i.forEach((e=>{const t=function(e,t){return"found"in t?function(e,t){w(!!t.found),t.found.name,t.found.updateTime;const n=_i(e,t.found.name),r=mi(t.found.updateTime),i=t.found.createTime?mi(t.found.createTime):V.min(),s=new Gt({mapValue:{fields:t.found.fields}});return Qt.newFoundDocument(n,r,i,s)}(e,t):"missing"in t?function(e,t){w(!!t.missing),w(!!t.readTime);const n=_i(e,t.missing),r=mi(t.readTime);return Qt.newNoDocument(n,r)}(e,t):v()}(n.serializer,e);s.set(t.key.toString(),t)}));const o=[];return t.forEach((e=>{const t=s.get(e.toString());w(!!t),o.push(t)})),o}(this.datastore,e);return t.forEach((e=>this.recordVersion(e))),t}set(e,t){this.write(t.toMutation(e,this.precondition(e))),this.writtenDocs.add(e.toString())}update(e,t){try{this.write(t.toMutation(e,this.preconditionForUpdate(e)))}catch(e){this.lastTransactionError=e}this.writtenDocs.add(e.toString())}delete(e){this.write(new Rr(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((t=>{e.delete(t.key.toString())})),e.forEach(((e,t)=>{const n=$.fromPath(t);this.mutations.push(new Pr(n,this.precondition(n)))})),await async function(e,t){const n=b(e),r={writes:t.map((e=>Di(n.serializer,e)))};await n.Oo("Commit",n.serializer.databaseId,B.emptyPath(),r)}(this.datastore,this.mutations),this.committed=!0}recordVersion(e){let t;if(e.isFoundDocument())t=e.version;else{if(!e.isNoDocument())throw v();t=V.min()}const n=this.readVersions.get(e.key.toString());if(n){if(!t.isEqual(n))throw new I(_.ABORTED,"Document version changed between two reads.")}else this.readVersions.set(e.key.toString(),t)}precondition(e){const t=this.readVersions.get(e.toString());return!this.writtenDocs.has(e.toString())&&t?t.isEqual(V.min())?Ir.exists(!1):Ir.updateTime(t):Ir.none()}preconditionForUpdate(e){const t=this.readVersions.get(e.toString());if(!this.writtenDocs.has(e.toString())&&t){if(t.isEqual(V.min()))throw new I(_.INVALID_ARGUMENT,"Can't update a document that doesn't exist.");return Ir.updateTime(t)}return Ir.exists(!0)}write(e){this.ensureCommitNotCalled(),this.mutations.push(e)}ensureCommitNotCalled(){}}class fu{constructor(e,t,n,r,i){this.asyncQueue=e,this.datastore=t,this.options=n,this.updateFunction=r,this.deferred=i,this.uu=n.maxAttempts,this.r_=new wa(this.asyncQueue,"transaction_retry")}cu(){this.uu-=1,this.lu()}lu(){this.r_.jo((async()=>{const e=new du(this.datastore),t=this.hu(e);t&&t.then((t=>{this.asyncQueue.enqueueAndForget((()=>e.commit().then((()=>{this.deferred.resolve(t)})).catch((e=>{this.Pu(e)}))))})).catch((e=>{this.Pu(e)}))}))}hu(e){try{const t=this.updateFunction(e);return!ve(t)&&t.catch&&t.then?t:(this.deferred.reject(Error("Transaction callback must return a Promise")),null)}catch(e){return this.deferred.reject(e),null}}Pu(e){this.uu>0&&this.Tu(e)?(this.uu-=1,this.asyncQueue.enqueueAndForget((()=>(this.lu(),Promise.resolve())))):this.deferred.reject(e)}Tu(e){if("FirebaseError"===e.name){const t=e.code;return"aborted"===t||"failed-precondition"===t||"already-exists"===t||!zr(t)}return!1}}class gu{constructor(e,t,n,r,i){this.authCredentials=e,this.appCheckCredentials=t,this.asyncQueue=n,this.databaseInfo=r,this.user=l.UNAUTHENTICATED,this.clientId=O.newId(),this.authCredentialListener=()=>Promise.resolve(),this.appCheckCredentialListener=()=>Promise.resolve(),this._uninitializedComponentsProvider=i,this.authCredentials.start(n,(async e=>{g("FirestoreClient","Received user=",e.uid),await this.authCredentialListener(e),this.user=e})),this.appCheckCredentials.start(n,(e=>(g("FirestoreClient","Received new app check token=",e),this.appCheckCredentialListener(e,this.user))))}get configuration(){return{asyncQueue:this.asyncQueue,databaseInfo:this.databaseInfo,clientId:this.clientId,authCredentials:this.authCredentials,appCheckCredentials:this.appCheckCredentials,initialUser:this.user,maxConcurrentLimboResolutions:100}}setCredentialChangeListener(e){this.authCredentialListener=e}setAppCheckTokenChangeListener(e){this.appCheckCredentialListener=e}terminate(){this.asyncQueue.enterRestrictedMode();const e=new E;return this.asyncQueue.enqueueAndForgetEvenWhileRestricted((async()=>{try{this._onlineComponents&&await this._onlineComponents.terminate(),this._offlineComponents&&await this._offlineComponents.terminate(),this.authCredentials.shutdown(),this.appCheckCredentials.shutdown(),e.resolve()}catch(t){const n=nc(t,"Failed to shutdown persistence");e.reject(n)}})),e.promise}}async function pu(e,t){e.asyncQueue.verifyOperationInProgress(),g("FirestoreClient","Initializing OfflineComponentProvider");const n=e.configuration;await t.initialize(n);let r=n.initialUser;e.setCredentialChangeListener((async e=>{r.isEqual(e)||(await Uo(t.localStore,e),r=e)})),t.persistence.setDatabaseDeletedListener((()=>e.terminate())),e._offlineComponents=t}async function mu(e,t){e.asyncQueue.verifyOperationInProgress();const n=await yu(e);g("FirestoreClient","Initializing OnlineComponentProvider"),await t.initialize(n,e.configuration),e.setCredentialChangeListener((e=>Xa(t.remoteStore,e))),e.setAppCheckTokenChangeListener(((e,n)=>Xa(t.remoteStore,n))),e._onlineComponents=t}async function yu(e){if(!e._offlineComponents)if(e._uninitializedComponentsProvider){g("FirestoreClient","Using user provided OfflineComponentProvider");try{await pu(e,e._uninitializedComponentsProvider._offline)}catch(t){const n=t;if(!function(e){return"FirebaseError"===e.name?e.code===_.FAILED_PRECONDITION||e.code===_.UNIMPLEMENTED:!("undefined"!=typeof DOMException&&e instanceof DOMException)||22===e.code||20===e.code||11===e.code}(n))throw n;m("Error using user provided cache. Falling back to memory cache: "+n),await pu(e,new iu)}}else g("FirestoreClient","Using default OfflineComponentProvider"),await pu(e,new su(void 0));return e._offlineComponents}async function vu(e){return e._onlineComponents||(e._uninitializedComponentsProvider?(g("FirestoreClient","Using user provided OnlineComponentProvider"),await mu(e,e._uninitializedComponentsProvider._online)):(g("FirestoreClient","Using default OnlineComponentProvider"),await mu(e,new cu))),e._onlineComponents}function wu(e){return yu(e).then((e=>e.persistence))}function bu(e){return yu(e).then((e=>e.localStore))}function _u(e){return vu(e).then((e=>e.remoteStore))}function Iu(e){return vu(e).then((e=>e.syncEngine))}function Eu(e){return vu(e).then((e=>e.datastore))}async function Tu(e){const t=await vu(e),n=t.eventManager;return n.onListen=Cc.bind(null,t.syncEngine),n.onUnlisten=Nc.bind(null,t.syncEngine),n.onFirstRemoteStoreListen=Dc.bind(null,t.syncEngine),n.onLastRemoteStoreUnlisten=Lc.bind(null,t.syncEngine),n}function Su(e,t,n={}){const r=new E;return e.asyncQueue.enqueueAndForget((async()=>function(e,t,n,r,i){const s=new lu({next:a=>{s.eu(),t.enqueueAndForget((()=>lc(e,o)));const c=a.docs.has(n);!c&&a.fromCache?i.reject(new I(_.UNAVAILABLE,"Failed to get document because the client is offline.")):c&&a.fromCache&&r&&"server"===r.source?i.reject(new I(_.UNAVAILABLE,'Failed to get document from server. (However, this document does exist in the local cache. Run again without setting source to "server" to retrieve the cached document.)')):i.resolve(a)},error:e=>i.reject(e)}),o=new mc(An(n.path),s,{includeMetadataChanges:!0,ua:!0});return uc(e,o)}(await Tu(e),e.asyncQueue,t,n,r))),r.promise}function xu(e,t,n={}){const r=new E;return e.asyncQueue.enqueueAndForget((async()=>function(e,t,n,r,i){const s=new lu({next:n=>{s.eu(),t.enqueueAndForget((()=>lc(e,o))),n.fromCache&&"server"===r.source?i.reject(new I(_.UNAVAILABLE,'Failed to get documents from server. (However, these documents may exist in the local cache. Run again without setting source to "server" to retrieve the cached documents.)')):i.resolve(n)},error:e=>i.reject(e)}),o=new mc(n,s,{includeMetadataChanges:!0,ua:!0});return uc(e,o)}(await Tu(e),e.asyncQueue,t,n,r))),r.promise}function Cu(e){const t={};return void 0!==e.timeoutSeconds&&(t.timeoutSeconds=e.timeoutSeconds),t}const Du=new Map;function Au(e,t,n){if(!n)throw new I(_.INVALID_ARGUMENT,`Function ${e}() cannot be called with an empty ${t}.`)}function ku(e,t,n,r){if(!0===t&&!0===r)throw new I(_.INVALID_ARGUMENT,`${e} and ${n} cannot be used together.`)}function Nu(e){if(!$.isDocumentKey(e))throw new I(_.INVALID_ARGUMENT,`Invalid document reference. Document references must have an even number of segments, but ${e} has ${e.length}.`)}function Lu(e){if($.isDocumentKey(e))throw new I(_.INVALID_ARGUMENT,`Invalid collection reference. Collection references must have an odd number of segments, but ${e} has ${e.length}.`)}function Ou(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 t=function(e){return e.constructor?e.constructor.name:null}(e);return t?`a custom ${t} object`:"an object"}}return"function"==typeof e?"a function":v()}function Mu(e,t){if("_delegate"in e&&(e=e._delegate),!(e instanceof t)){if(t.name===e.constructor.name)throw new I(_.INVALID_ARGUMENT,"Type does not match the expected instance. Did you pass a reference from a different Firestore SDK?");{const n=Ou(e);throw new I(_.INVALID_ARGUMENT,`Expected type '${t.name}', but it was: ${n}`)}}return e}function Ru(e,t){if(t<=0)throw new I(_.INVALID_ARGUMENT,`Function ${e}() requires a positive number, but it was: ${t}.`)}class Pu{constructor(e){var t,n;if(void 0===e.host){if(void 0!==e.ssl)throw new I(_.INVALID_ARGUMENT,"Can't provide ssl option if host option is not set");this.host="firestore.googleapis.com",this.ssl=!0}else this.host=e.host,this.ssl=null===(t=e.ssl)||void 0===t||t;if(this.credentials=e.credentials,this.ignoreUndefinedProperties=!!e.ignoreUndefinedProperties,this.localCache=e.localCache,void 0===e.cacheSizeBytes)this.cacheSizeBytes=41943040;else{if(-1!==e.cacheSizeBytes&&e.cacheSizeBytes<1048576)throw new I(_.INVALID_ARGUMENT,"cacheSizeBytes must be at least 1048576");this.cacheSizeBytes=e.cacheSizeBytes}ku("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=Cu(null!==(n=e.experimentalLongPollingOptions)&&void 0!==n?n:{}),function(e){if(void 0!==e.timeoutSeconds){if(isNaN(e.timeoutSeconds))throw new I(_.INVALID_ARGUMENT,`invalid long polling timeout: ${e.timeoutSeconds} (must not be NaN)`);if(e.timeoutSeconds<5)throw new I(_.INVALID_ARGUMENT,`invalid long polling timeout: ${e.timeoutSeconds} (minimum allowed value is 5)`);if(e.timeoutSeconds>30)throw new I(_.INVALID_ARGUMENT,`invalid long polling timeout: ${e.timeoutSeconds} (maximum allowed value is 30)`)}}(this.experimentalLongPollingOptions),this.useFetchStreams=!!e.useFetchStreams}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(e,t){return e.timeoutSeconds===t.timeoutSeconds}(this.experimentalLongPollingOptions,e.experimentalLongPollingOptions)&&this.ignoreUndefinedProperties===e.ignoreUndefinedProperties&&this.useFetchStreams===e.useFetchStreams}}class Fu{constructor(e,t,n,r){this._authCredentials=e,this._appCheckCredentials=t,this._databaseId=n,this._app=r,this.type="firestore-lite",this._persistenceKey="(lite)",this._settings=new Pu({}),this._settingsFrozen=!1,this._terminateTask="notTerminated"}get app(){if(!this._app)throw new I(_.FAILED_PRECONDITION,"Firestore was not initialized using the Firebase SDK. 'app' is not available");return this._app}get _initialized(){return this._settingsFrozen}get _terminated(){return"notTerminated"!==this._terminateTask}_setSettings(e){if(this._settingsFrozen)throw new I(_.FAILED_PRECONDITION,"Firestore has already been started and its settings can no longer be changed. You can only modify settings before calling any other methods on a Firestore object.");this._settings=new Pu(e),void 0!==e.credentials&&(this._authCredentials=function(e){if(!e)return new S;switch(e.type){case"firstParty":return new A(e.sessionIndex||"0",e.iamToken||null,e.authTokenFactory||null);case"provider":return e.client;default:throw new I(_.INVALID_ARGUMENT,"makeAuthCredentialsProvider failed due to invalid credential type")}}(e.credentials))}_getSettings(){return this._settings}_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(e){const t=Du.get(e);t&&(g("ComponentProvider","Removing Datastore"),Du.delete(e),t.terminate())}(this),Promise.resolve()}}function Vu(e,t,n,r={}){var i;const s=(e=Mu(e,Fu))._getSettings(),a=`${t}:${n}`;if("firestore.googleapis.com"!==s.host&&s.host!==a&&m("Host has been set in both settings() and connectFirestoreEmulator(), emulator host will be used."),e._setSettings(Object.assign(Object.assign({},s),{host:a,ssl:!1})),r.mockUserToken){let t,n;if("string"==typeof r.mockUserToken)t=r.mockUserToken,n=l.MOCK_USER;else{t=o.createMockUserToken(r.mockUserToken,null===(i=e._app)||void 0===i?void 0:i.options.projectId);const s=r.mockUserToken.sub||r.mockUserToken.user_id;if(!s)throw new I(_.INVALID_ARGUMENT,"mockUserToken must contain 'sub' or 'user_id' field!");n=new l(s)}e._authCredentials=new x(new T(t,n))}}class qu{constructor(e,t,n){this.converter=t,this._query=n,this.type="query",this.firestore=e}withConverter(e){return new qu(this.firestore,e,this._query)}}class Bu{constructor(e,t,n){this.converter=t,this._key=n,this.type="document",this.firestore=e}get _path(){return this._key.path}get id(){return this._key.path.lastSegment()}get path(){return this._key.path.canonicalString()}get parent(){return new Uu(this.firestore,this.converter,this._key.path.popLast())}withConverter(e){return new Bu(this.firestore,e,this._key)}}class Uu extends qu{constructor(e,t,n){super(e,t,An(n)),this._path=n,this.type="collection"}get id(){return this._query.path.lastSegment()}get path(){return this._query.path.canonicalString()}get parent(){const e=this._path.popLast();return e.isEmpty()?null:new Bu(this.firestore,null,new $(e))}withConverter(e){return new Uu(this.firestore,e,this._path)}}function ju(e,t,...n){if(e=o.getModularInstance(e),1===arguments.length&&(t=O.newId()),Au("doc","path",t),e instanceof Fu){const r=B.fromString(t,...n);return Nu(r),new Bu(e,null,new $(r))}{if(!(e instanceof Bu||e instanceof Uu))throw new I(_.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");const r=e._path.child(B.fromString(t,...n));return Nu(r),new Bu(e.firestore,e instanceof Uu?e.converter:null,new $(r))}}function $u(e,t){return e=o.getModularInstance(e),t=o.getModularInstance(t),e instanceof qu&&t instanceof qu&&e.firestore===t.firestore&&Vn(e._query,t._query)&&e.converter===t.converter}class zu{constructor(e=Promise.resolve()){this.Iu=[],this.Eu=!1,this.du=[],this.Au=null,this.Ru=!1,this.Vu=!1,this.mu=[],this.r_=new wa(this,"async_queue_retry"),this.fu=()=>{const e=ya();e&&g("AsyncQueue","Visibility state changed to "+e.visibilityState),this.r_.Jo()},this.gu=e;const t=ya();t&&"function"==typeof t.addEventListener&&t.addEventListener("visibilitychange",this.fu)}get isShuttingDown(){return this.Eu}enqueueAndForget(e){this.enqueue(e)}enqueueAndForgetEvenWhileRestricted(e){this.pu(),this.yu(e)}enterRestrictedMode(e){if(!this.Eu){this.Eu=!0,this.Vu=e||!1;const t=ya();t&&"function"==typeof t.removeEventListener&&t.removeEventListener("visibilitychange",this.fu)}}enqueue(e){if(this.pu(),this.Eu)return new Promise((()=>{}));const t=new E;return this.yu((()=>this.Eu&&this.Vu?Promise.resolve():(e().then(t.resolve,t.reject),t.promise))).then((()=>t.promise))}enqueueRetryable(e){this.enqueueAndForget((()=>(this.Iu.push(e),this.wu())))}async wu(){if(0!==this.Iu.length){try{await this.Iu[0](),this.Iu.shift(),this.r_.reset()}catch(e){if(!le(e))throw e;g("AsyncQueue","Operation failed with retryable error: "+e)}this.Iu.length>0&&this.r_.jo((()=>this.wu()))}}yu(e){const t=this.gu.then((()=>(this.Ru=!0,e().catch((e=>{this.Au=e,this.Ru=!1;const t=function(e){let t=e.message||"";return e.stack&&(t=e.stack.includes(e.message)?e.stack:e.message+"\n"+e.stack),t}(e);throw p("INTERNAL UNHANDLED ERROR: ",t),e})).then((e=>(this.Ru=!1,e))))));return this.gu=t,t}enqueueAfterDelay(e,t,n){this.pu(),this.mu.indexOf(e)>-1&&(t=0);const r=tc.createAndSchedule(this,e,t,n,(e=>this.Su(e)));return this.du.push(r),r}pu(){this.Au&&v()}verifyOperationInProgress(){}async bu(){let e;do{e=this.gu,await e}while(e!==this.gu)}Du(e){for(const t of this.du)if(t.timerId===e)return!0;return!1}vu(e){return this.bu().then((()=>{this.du.sort(((e,t)=>e.targetTimeMs-t.targetTimeMs));for(const t of this.du)if(t.skipDelay(),"all"!==e&&t.timerId===e)break;return this.bu()}))}Cu(e){this.mu.push(e)}Su(e){const t=this.du.indexOf(e);this.du.splice(t,1)}}function Gu(e){return function(e){if("object"!=typeof e||null===e)return!1;const t=e;for(const e of["next","error","complete"])if(e in t&&"function"==typeof t[e])return!0;return!1}(e)}class Ku{constructor(){this._progressObserver={},this._taskCompletionResolver=new E,this._lastProgress={taskState:"Running",totalBytes:0,totalDocuments:0,bytesLoaded:0,documentsLoaded:0}}onProgress(e,t,n){this._progressObserver={next:e,error:t,complete:n}}catch(e){return this._taskCompletionResolver.promise.catch(e)}then(e,t){return this._taskCompletionResolver.promise.then(e,t)}_completeWith(e){this._updateProgress(e),this._progressObserver.complete&&this._progressObserver.complete(),this._taskCompletionResolver.resolve(e)}_failWith(e){this._lastProgress.taskState="Error",this._progressObserver.next&&this._progressObserver.next(this._lastProgress),this._progressObserver.error&&this._progressObserver.error(e),this._taskCompletionResolver.reject(e)}_updateProgress(e){this._lastProgress=e,this._progressObserver.next&&this._progressObserver.next(e)}}class Qu extends Fu{constructor(e,t,n,r){super(e,t,n,r),this.type="firestore",this._queue=new zu,this._persistenceKey=(null==r?void 0:r.name)||"[DEFAULT]"}async _terminate(){if(this._firestoreClient){const e=this._firestoreClient.terminate();this._queue=new zu(e),this._firestoreClient=void 0,await e}}}function Hu(e){if(e._terminated)throw new I(_.FAILED_PRECONDITION,"The client has already been terminated.");return e._firestoreClient||Wu(e),e._firestoreClient}function Wu(e){var t,n,r;const i=e._freezeSettings(),s=function(e,t,n,r){return new vt(e,t,n,r.host,r.ssl,r.experimentalForceLongPolling,r.experimentalAutoDetectLongPolling,Cu(r.experimentalLongPollingOptions),r.useFetchStreams)}(e._databaseId,(null===(t=e._app)||void 0===t?void 0:t.options.appId)||"",e._persistenceKey,i);e._componentsProvider||(null===(n=i.localCache)||void 0===n?void 0:n._offlineComponentProvider)&&(null===(r=i.localCache)||void 0===r?void 0:r._onlineComponentProvider)&&(e._componentsProvider={_offline:i.localCache._offlineComponentProvider,_online:i.localCache._onlineComponentProvider}),e._firestoreClient=new gu(e._authCredentials,e._appCheckCredentials,e._queue,s,e._componentsProvider&&function(e){const t=null==e?void 0:e._online.build();return{_offline:null==e?void 0:e._offline.build(t),_online:t}}(e._componentsProvider))}function Ju(e,t,n){if((e=Mu(e,Qu))._firestoreClient||e._terminated)throw new I(_.FAILED_PRECONDITION,"Firestore has already been started and persistence can no longer be enabled. You can only enable persistence before calling any other methods on a Firestore object.");if(e._componentsProvider||e._getSettings().localCache)throw new I(_.FAILED_PRECONDITION,"SDK cache is already specified.");e._componentsProvider={_online:t,_offline:n},Wu(e)}class Xu{constructor(e="count",t){this._internalFieldPath=t,this.type="AggregateField",this.aggregateType=e}}class Yu{constructor(e,t,n){this._userDataWriter=t,this._data=n,this.type="AggregateQuerySnapshot",this.query=e}data(){return this._userDataWriter.convertObjectMap(this._data)}}class Zu{constructor(e){this._byteString=e}static fromBase64String(e){try{return new Zu(lt.fromBase64String(e))}catch(e){throw new I(_.INVALID_ARGUMENT,"Failed to construct data from Base64 string: "+e)}}static fromUint8Array(e){return new Zu(lt.fromUint8Array(e))}toBase64(){return this._byteString.toBase64()}toUint8Array(){return this._byteString.toUint8Array()}toString(){return"Bytes(base64: "+this.toBase64()+")"}isEqual(e){return this._byteString.isEqual(e._byteString)}}class el{constructor(...e){for(let t=0;t<e.length;++t)if(0===e[t].length)throw new I(_.INVALID_ARGUMENT,"Invalid field name at argument $(i + 1). Field names must not be empty.");this._internalPath=new j(e)}isEqual(e){return this._internalPath.isEqual(e._internalPath)}}class tl{constructor(e){this._methodName=e}}class nl{constructor(e,t){if(!isFinite(e)||e<-90||e>90)throw new I(_.INVALID_ARGUMENT,"Latitude must be a number between -90 and 90, but was: "+e);if(!isFinite(t)||t<-180||t>180)throw new I(_.INVALID_ARGUMENT,"Longitude must be a number between -180 and 180, but was: "+t);this._lat=e,this._long=t}get latitude(){return this._lat}get longitude(){return this._long}isEqual(e){return this._lat===e._lat&&this._long===e._long}toJSON(){return{latitude:this._lat,longitude:this._long}}_compareTo(e){return M(this._lat,e._lat)||M(this._long,e._long)}}class rl{constructor(e){this._values=(e||[]).map((e=>e))}toArray(){return this._values.map((e=>e))}isEqual(e){return function(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;++n)if(e[n]!==t[n])return!1;return!0}(this._values,e._values)}}const il=/^__.*__$/;class sl{constructor(e,t,n){this.data=e,this.fieldMask=t,this.fieldTransforms=n}toMutation(e,t){return null!==this.fieldMask?new Nr(e,this.data,this.fieldMask,t,this.fieldTransforms):new kr(e,this.data,t,this.fieldTransforms)}}class ol{constructor(e,t,n){this.data=e,this.fieldMask=t,this.fieldTransforms=n}toMutation(e,t){return new Nr(e,this.data,this.fieldMask,t,this.fieldTransforms)}}function al(e){switch(e){case 0:case 2:case 1:return!0;case 3:case 4:return!1;default:throw v()}}class cl{constructor(e,t,n,r,i,s){this.settings=e,this.databaseId=t,this.serializer=n,this.ignoreUndefinedProperties=r,void 0===i&&this.Fu(),this.fieldTransforms=i||[],this.fieldMask=s||[]}get path(){return this.settings.path}get Mu(){return this.settings.Mu}xu(e){return new cl(Object.assign(Object.assign({},this.settings),e),this.databaseId,this.serializer,this.ignoreUndefinedProperties,this.fieldTransforms,this.fieldMask)}Ou(e){var t;const n=null===(t=this.path)||void 0===t?void 0:t.child(e),r=this.xu({path:n,Nu:!1});return r.Lu(e),r}Bu(e){var t;const n=null===(t=this.path)||void 0===t?void 0:t.child(e),r=this.xu({path:n,Nu:!1});return r.Fu(),r}ku(e){return this.xu({path:void 0,Nu:!0})}qu(e){return Dl(e,this.settings.methodName,this.settings.Qu||!1,this.path,this.settings.Ku)}contains(e){return void 0!==this.fieldMask.find((t=>e.isPrefixOf(t)))||void 0!==this.fieldTransforms.find((t=>e.isPrefixOf(t.field)))}Fu(){if(this.path)for(let e=0;e<this.path.length;e++)this.Lu(this.path.get(e))}Lu(e){if(0===e.length)throw this.qu("Document fields must not be empty");if(al(this.Mu)&&il.test(e))throw this.qu('Document fields cannot begin and end with "__"')}}class ul{constructor(e,t,n){this.databaseId=e,this.ignoreUndefinedProperties=t,this.serializer=n||va(e)}$u(e,t,n,r=!1){return new cl({Mu:e,methodName:t,Ku:n,path:j.emptyPath(),Nu:!1,Qu:r},this.databaseId,this.serializer,this.ignoreUndefinedProperties)}}function ll(e){const t=e._freezeSettings(),n=va(e._databaseId);return new ul(e._databaseId,!!t.ignoreUndefinedProperties,n)}function hl(e,t,n,r,i,s={}){const o=e.$u(s.merge||s.mergeFields?2:0,t,n,i);Tl("Data must be an object, but it was:",o,r);const a=Il(r,o);let c,u;if(s.merge)c=new ct(o.fieldMask),u=o.fieldTransforms;else if(s.mergeFields){const e=[];for(const r of s.mergeFields){const i=Sl(t,r,n);if(!o.contains(i))throw new I(_.INVALID_ARGUMENT,`Field '${i}' is specified in your field mask but missing from your input data.`);Al(e,i)||e.push(i)}c=new ct(e),u=o.fieldTransforms.filter((e=>c.covers(e.field)))}else c=null,u=o.fieldTransforms;return new sl(new Gt(a),c,u)}class dl extends tl{_toFieldTransform(e){if(2!==e.Mu)throw 1===e.Mu?e.qu(`${this._methodName}() can only appear at the top level of your update data`):e.qu(`${this._methodName}() cannot be used with set() unless you pass {merge:true}`);return e.fieldMask.push(e.path),null}isEqual(e){return e instanceof dl}}function fl(e,t,n){return new cl({Mu:3,Ku:t.settings.Ku,methodName:e._methodName,Nu:n},t.databaseId,t.serializer,t.ignoreUndefinedProperties)}class gl extends tl{_toFieldTransform(e){return new br(e.path,new dr)}isEqual(e){return e instanceof gl}}class pl extends tl{constructor(e,t){super(e),this.Uu=t}_toFieldTransform(e){const t=fl(this,e,!0),n=this.Uu.map((e=>_l(e,t))),r=new fr(n);return new br(e.path,r)}isEqual(e){return e instanceof pl&&o.deepEqual(this.Uu,e.Uu)}}class ml extends tl{constructor(e,t){super(e),this.Uu=t}_toFieldTransform(e){const t=fl(this,e,!0),n=this.Uu.map((e=>_l(e,t))),r=new pr(n);return new br(e.path,r)}isEqual(e){return e instanceof ml&&o.deepEqual(this.Uu,e.Uu)}}class yl extends tl{constructor(e,t){super(e),this.Wu=t}_toFieldTransform(e){const t=new yr(e.serializer,ar(e.serializer,this.Wu));return new br(e.path,t)}isEqual(e){return e instanceof yl&&this.Wu===e.Wu}}function vl(e,t,n,r){const i=e.$u(1,t,n);Tl("Data must be an object, but it was:",i,r);const s=[],a=Gt.empty();Ze(r,((e,r)=>{const c=Cl(t,e,n);r=o.getModularInstance(r);const u=i.Bu(c);if(r instanceof dl)s.push(c);else{const e=_l(r,u);null!=e&&(s.push(c),a.set(c,e))}}));const c=new ct(s);return new ol(a,c,i.fieldTransforms)}function wl(e,t,n,r,i,s){const a=e.$u(1,t,n),c=[Sl(t,r,n)],u=[i];if(s.length%2!=0)throw new I(_.INVALID_ARGUMENT,`Function ${t}() needs to be called with an even number of arguments that alternate between field names and values.`);for(let e=0;e<s.length;e+=2)c.push(Sl(t,s[e])),u.push(s[e+1]);const l=[],h=Gt.empty();for(let e=c.length-1;e>=0;--e)if(!Al(l,c[e])){const t=c[e];let n=u[e];n=o.getModularInstance(n);const r=a.Bu(t);if(n instanceof dl)l.push(t);else{const e=_l(n,r);null!=e&&(l.push(t),h.set(t,e))}}const d=new ct(l);return new ol(h,d,a.fieldTransforms)}function bl(e,t,n,r=!1){return _l(n,e.$u(r?4:3,t))}function _l(e,t){if(El(e=o.getModularInstance(e)))return Tl("Unsupported field value:",t,e),Il(e,t);if(e instanceof tl)return function(e,t){if(!al(t.Mu))throw t.qu(`${e._methodName}() can only be used with update() and set()`);if(!t.path)throw t.qu(`${e._methodName}() is not currently supported inside arrays`);const n=e._toFieldTransform(t);n&&t.fieldTransforms.push(n)}(e,t),null;if(void 0===e&&t.ignoreUndefinedProperties)return null;if(t.path&&t.fieldMask.push(t.path),e instanceof Array){if(t.settings.Nu&&4!==t.Mu)throw t.qu("Nested arrays are not supported");return function(e,t){const n=[];let r=0;for(const i of e){let e=_l(i,t.ku(r));null==e&&(e={nullValue:"NULL_VALUE"}),n.push(e),r++}return{arrayValue:{values:n}}}(e,t)}return function(e,t){if(null===(e=o.getModularInstance(e)))return{nullValue:"NULL_VALUE"};if("number"==typeof e)return ar(t.serializer,e);if("boolean"==typeof e)return{booleanValue:e};if("string"==typeof e)return{stringValue:e};if(e instanceof Date){const n=F.fromDate(e);return{timestampValue:fi(t.serializer,n)}}if(e instanceof F){const n=new F(e.seconds,1e3*Math.floor(e.nanoseconds/1e3));return{timestampValue:fi(t.serializer,n)}}if(e instanceof nl)return{geoPointValue:{latitude:e.latitude,longitude:e.longitude}};if(e instanceof Zu)return{bytesValue:gi(t.serializer,e._byteString)};if(e instanceof Bu){const n=t.databaseId,r=e.firestore._databaseId;if(!r.isEqual(n))throw t.qu(`Document reference is for database ${r.projectId}/${r.database} but should be for database ${n.projectId}/${n.database}`);return{referenceValue:yi(e.firestore._databaseId||t.databaseId,e._key.path)}}if(e instanceof rl)return function(e,t){return{mapValue:{fields:{__type__:{stringValue:"__vector__"},value:{arrayValue:{values:e.toArray().map((e=>{if("number"!=typeof e)throw t.qu("VectorValues must only contain numeric values.");return sr(t.serializer,e)}))}}}}}}(e,t);throw t.qu(`Unsupported field value: ${Ou(e)}`)}(e,t)}function Il(e,t){const n={};return tt(e)?t.path&&t.path.length>0&&t.fieldMask.push(t.path):Ze(e,((e,r)=>{const i=_l(r,t.Ou(e));null!=i&&(n[e]=i)})),{mapValue:{fields:n}}}function El(e){return!("object"!=typeof e||null===e||e instanceof Array||e instanceof Date||e instanceof F||e instanceof nl||e instanceof Zu||e instanceof Bu||e instanceof tl||e instanceof rl)}function Tl(e,t,n){if(!El(n)||!function(e){return"object"==typeof e&&null!==e&&(Object.getPrototypeOf(e)===Object.prototype||null===Object.getPrototypeOf(e))}(n)){const r=Ou(n);throw"an object"===r?t.qu(e+" a custom object"):t.qu(e+" "+r)}}function Sl(e,t,n){if((t=o.getModularInstance(t))instanceof el)return t._internalPath;if("string"==typeof t)return Cl(e,t);throw Dl("Field path arguments must be of type string or ",e,!1,void 0,n)}const xl=new RegExp("[~\\*/\\[\\]]");function Cl(e,t,n){if(t.search(xl)>=0)throw Dl(`Invalid field path (${t}). Paths must not contain '~', '*', '/', '[', or ']'`,e,!1,void 0,n);try{return new el(...t.split("."))._internalPath}catch(r){throw Dl(`Invalid field path (${t}). Paths must not be empty, begin with '.', end with '.', or contain '..'`,e,!1,void 0,n)}}function Dl(e,t,n,r,i){const s=r&&!r.isEmpty(),o=void 0!==i;let a=`Function ${t}() called with invalid data`;n&&(a+=" (via `toFirestore()`)"),a+=". ";let c="";return(s||o)&&(c+=" (found",s&&(c+=` in field ${r}`),o&&(c+=` in document ${i}`),c+=")"),new I(_.INVALID_ARGUMENT,a+e+c)}function Al(e,t){return e.some((e=>e.isEqual(t)))}class kl{constructor(e,t,n,r,i){this._firestore=e,this._userDataWriter=t,this._key=n,this._document=r,this._converter=i}get id(){return this._key.path.lastSegment()}get ref(){return new Bu(this._firestore,this._converter,this._key)}exists(){return null!==this._document}data(){if(this._document){if(this._converter){const e=new Nl(this._firestore,this._userDataWriter,this._key,this._document,null);return this._converter.fromFirestore(e)}return this._userDataWriter.convertValue(this._document.data.value)}}get(e){if(this._document){const t=this._document.data.field(Ll("DocumentSnapshot.get",e));if(null!==t)return this._userDataWriter.convertValue(t)}}}class Nl extends kl{data(){return super.data()}}function Ll(e,t){return"string"==typeof t?Cl(e,t):t instanceof el?t._internalPath:t._delegate._internalPath}function Ol(e){if("L"===e.limitType&&0===e.explicitOrderBy.length)throw new I(_.UNIMPLEMENTED,"limitToLast() queries require specifying at least one orderBy() clause")}class Ml{}class Rl extends Ml{}class Pl extends Rl{constructor(e,t,n){super(),this._field=e,this._op=t,this._value=n,this.type="where"}static _create(e,t,n){return new Pl(e,t,n)}_apply(e){const t=this._parse(e);return Gl(e._query,t),new qu(e.firestore,e.converter,Pn(e._query,t))}_parse(e){const t=ll(e.firestore),n=function(e,t,n,r,i,s,o){let a;if(i.isKeyField()){if("array-contains"===s||"array-contains-any"===s)throw new I(_.INVALID_ARGUMENT,`Invalid Query. You can't perform '${s}' queries on documentId().`);if("in"===s||"not-in"===s){zl(o,s);const t=[];for(const n of o)t.push($l(r,e,n));a={arrayValue:{values:t}}}else a=$l(r,e,o)}else"in"!==s&&"not-in"!==s&&"array-contains-any"!==s||zl(o,s),a=bl(n,"where",o,"in"===s||"not-in"===s);return en.create(i,s,a)}(e._query,0,t,e.firestore._databaseId,this._field,this._op,this._value);return n}}class Fl extends Ml{constructor(e,t){super(),this.type=e,this._queryConstraints=t}static _create(e,t){return new Fl(e,t)}_parse(e){const t=this._queryConstraints.map((t=>t._parse(e))).filter((e=>e.getFilters().length>0));return 1===t.length?t[0]:tn.create(t,this._getOperator())}_apply(e){const t=this._parse(e);return 0===t.getFilters().length?e:(function(e,t){let n=e;const r=t.getFlattenedFilters();for(const e of r)Gl(n,e),n=Pn(n,e)}(e._query,t),new qu(e.firestore,e.converter,Pn(e._query,t)))}_getQueryConstraints(){return this._queryConstraints}_getOperator(){return"and"===this.type?"and":"or"}}class Vl extends Rl{constructor(e,t){super(),this._field=e,this._direction=t,this.type="orderBy"}static _create(e,t){return new Vl(e,t)}_apply(e){const t=function(e,t,n){if(null!==e.startAt)throw new I(_.INVALID_ARGUMENT,"Invalid query. You must not call startAt() or startAfter() before calling orderBy().");if(null!==e.endAt)throw new I(_.INVALID_ARGUMENT,"Invalid query. You must not call endAt() or endBefore() before calling orderBy().");return new Xt(t,n)}(e._query,this._field,this._direction);return new qu(e.firestore,e.converter,function(e,t){const n=e.explicitOrderBy.concat([t]);return new Cn(e.path,e.collectionGroup,n,e.filters.slice(),e.limit,e.limitType,e.startAt,e.endAt)}(e._query,t))}}class ql extends Rl{constructor(e,t,n){super(),this.type=e,this._limit=t,this._limitType=n}static _create(e,t,n){return new ql(e,t,n)}_apply(e){return new qu(e.firestore,e.converter,Fn(e._query,this._limit,this._limitType))}}class Bl extends Rl{constructor(e,t,n){super(),this.type=e,this._docOrFields=t,this._inclusive=n}static _create(e,t,n){return new Bl(e,t,n)}_apply(e){const t=jl(e,this.type,this._docOrFields,this._inclusive);return new qu(e.firestore,e.converter,function(e,t){return new Cn(e.path,e.collectionGroup,e.explicitOrderBy.slice(),e.filters.slice(),e.limit,e.limitType,t,e.endAt)}(e._query,t))}}class Ul extends Rl{constructor(e,t,n){super(),this.type=e,this._docOrFields=t,this._inclusive=n}static _create(e,t,n){return new Ul(e,t,n)}_apply(e){const t=jl(e,this.type,this._docOrFields,this._inclusive);return new qu(e.firestore,e.converter,function(e,t){return new Cn(e.path,e.collectionGroup,e.explicitOrderBy.slice(),e.filters.slice(),e.limit,e.limitType,e.startAt,t)}(e._query,t))}}function jl(e,t,n,r){if(n[0]=o.getModularInstance(n[0]),n[0]instanceof kl)return function(e,t,n,r,i){if(!r)throw new I(_.NOT_FOUND,`Can't use a DocumentSnapshot that doesn't exist for ${n}().`);const s=[];for(const n of Ln(e))if(n.field.isKeyField())s.push(Nt(t,r.key));else{const e=r.data.field(n.field);if(pt(e))throw new I(_.INVALID_ARGUMENT,'Invalid query. You are trying to start or end a query using a document for which the field "'+n.field+'" is an uncommitted server timestamp. (Since the value of this field is unknown, you cannot start/end a query with it.)');if(null===e){const e=n.field.canonicalString();throw new I(_.INVALID_ARGUMENT,`Invalid query. You are trying to start or end a query using a document for which the field '${e}' (used as the orderBy) does not exist.`)}s.push(e)}return new Ht(s,i)}(e._query,e.firestore._databaseId,t,n[0]._document,r);{const i=ll(e.firestore);return function(e,t,n,r,i,s){const o=e.explicitOrderBy;if(i.length>o.length)throw new I(_.INVALID_ARGUMENT,`Too many arguments provided to ${r}(). The number of arguments must be less than or equal to the number of orderBy() clauses`);const a=[];for(let s=0;s<i.length;s++){const c=i[s];if(o[s].field.isKeyField()){if("string"!=typeof c)throw new I(_.INVALID_ARGUMENT,`Invalid query. Expected a string for document ID in ${r}(), but got a ${typeof c}`);if(!Nn(e)&&-1!==c.indexOf("/"))throw new I(_.INVALID_ARGUMENT,`Invalid query. When querying a collection and ordering by documentId(), the value passed to ${r}() must be a plain document ID, but '${c}' contains a slash.`);const n=e.path.child(B.fromString(c));if(!$.isDocumentKey(n))throw new I(_.INVALID_ARGUMENT,`Invalid query. When querying a collection group and ordering by documentId(), the value passed to ${r}() must result in a valid document path, but '${n}' is not because it contains an odd number of segments.`);const i=new $(n);a.push(Nt(t,i))}else{const e=bl(n,r,c);a.push(e)}}return new Ht(a,s)}(e._query,e.firestore._databaseId,i,t,n,r)}}function $l(e,t,n){if("string"==typeof(n=o.getModularInstance(n))){if(""===n)throw new I(_.INVALID_ARGUMENT,"Invalid query. When querying with documentId(), you must provide a valid document ID, but it was an empty string.");if(!Nn(t)&&-1!==n.indexOf("/"))throw new I(_.INVALID_ARGUMENT,`Invalid query. When querying a collection by documentId(), you must provide a plain document ID, but '${n}' contains a '/' character.`);const r=t.path.child(B.fromString(n));if(!$.isDocumentKey(r))throw new I(_.INVALID_ARGUMENT,`Invalid query. When querying a collection group by documentId(), the value provided must result in a valid document path, but '${r}' is not because it has an odd number of segments (${r.length}).`);return Nt(e,new $(r))}if(n instanceof Bu)return Nt(e,n._key);throw new I(_.INVALID_ARGUMENT,`Invalid query. When querying with documentId(), you must provide a valid string or a DocumentReference, but it was: ${Ou(n)}.`)}function zl(e,t){if(!Array.isArray(e)||0===e.length)throw new I(_.INVALID_ARGUMENT,`Invalid Query. A non-empty array is required for '${t.toString()}' filters.`)}function Gl(e,t){const n=function(e,t){for(const n of e)for(const e of n.getFlattenedFilters())if(t.indexOf(e.op)>=0)return e.op;return null}(e.filters,function(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[]}}(t.op));if(null!==n)throw n===t.op?new I(_.INVALID_ARGUMENT,`Invalid query. You cannot use more than one '${t.op.toString()}' filter.`):new I(_.INVALID_ARGUMENT,`Invalid query. You cannot use '${t.op.toString()}' filters with '${n.toString()}' filters.`)}function Kl(e,t){if(!(t instanceof Pl||t instanceof Fl))throw new I(_.INVALID_ARGUMENT,`Function ${e}() requires AppliableConstraints created with a call to 'where(...)', 'or(...)', or 'and(...)'.`)}class Ql{convertValue(e,t="none"){switch(It(e)){case 0:return null;case 1:return e.booleanValue;case 2:return ft(e.integerValue||e.doubleValue);case 3:return this.convertTimestamp(e.timestampValue);case 4:return this.convertServerTimestamp(e,t);case 5:return e.stringValue;case 6:return this.convertBytes(gt(e.bytesValue));case 7:return this.convertReference(e.referenceValue);case 8:return this.convertGeoPoint(e.geoPointValue);case 9:return this.convertArray(e.arrayValue,t);case 11:return this.convertObject(e.mapValue,t);case 10:return this.convertVectorValue(e.mapValue);default:throw v()}}convertObject(e,t){return this.convertObjectMap(e.fields,t)}convertObjectMap(e,t="none"){const n={};return Ze(e,((e,r)=>{n[e]=this.convertValue(r,t)})),n}convertVectorValue(e){var t,n,r;const i=null===(r=null===(n=null===(t=e.fields)||void 0===t?void 0:t.value.arrayValue)||void 0===n?void 0:n.values)||void 0===r?void 0:r.map((e=>ft(e.doubleValue)));return new rl(i)}convertGeoPoint(e){return new nl(ft(e.latitude),ft(e.longitude))}convertArray(e,t){return(e.values||[]).map((e=>this.convertValue(e,t)))}convertServerTimestamp(e,t){switch(t){case"previous":const n=mt(e);return null==n?null:this.convertValue(n,t);case"estimate":return this.convertTimestamp(yt(e));default:return null}}convertTimestamp(e){const t=dt(e);return new F(t.seconds,t.nanos)}convertDocumentKey(e,t){const n=B.fromString(e);w(ji(n));const r=new wt(n.get(1),n.get(3)),i=new $(n.popFirst(5));return r.isEqual(t)||p(`Document ${i} contains a document reference within a different database (${r.projectId}/${r.database}) which is not supported. It will be treated as a reference in the current database (${t.projectId}/${t.database}) instead.`),i}}function Hl(e,t,n){let r;return r=e?n&&(n.merge||n.mergeFields)?e.toFirestore(t,n):e.toFirestore(t):t,r}class Wl extends Ql{constructor(e){super(),this.firestore=e}convertBytes(e){return new Zu(e)}convertReference(e){const t=this.convertDocumentKey(e,this.firestore._databaseId);return new Bu(this.firestore,null,t)}}function Jl(){return new Xu("count")}class Xl{constructor(e,t){this.hasPendingWrites=e,this.fromCache=t}isEqual(e){return this.hasPendingWrites===e.hasPendingWrites&&this.fromCache===e.fromCache}}class Yl extends kl{constructor(e,t,n,r,i,s){super(e,t,n,r,s),this._firestore=e,this._firestoreImpl=e,this.metadata=i}exists(){return super.exists()}data(e={}){if(this._document){if(this._converter){const t=new Zl(this._firestore,this._userDataWriter,this._key,this._document,this.metadata,null);return this._converter.fromFirestore(t,e)}return this._userDataWriter.convertValue(this._document.data.value,e.serverTimestamps)}}get(e,t={}){if(this._document){const n=this._document.data.field(Ll("DocumentSnapshot.get",e));if(null!==n)return this._userDataWriter.convertValue(n,t.serverTimestamps)}}}class Zl extends Yl{data(e={}){return super.data(e)}}class eh{constructor(e,t,n,r){this._firestore=e,this._userDataWriter=t,this._snapshot=r,this.metadata=new Xl(r.hasPendingWrites,r.fromCache),this.query=n}get docs(){const e=[];return this.forEach((t=>e.push(t))),e}get size(){return this._snapshot.docs.size}get empty(){return 0===this.size}forEach(e,t){this._snapshot.docs.forEach((n=>{e.call(t,new Zl(this._firestore,this._userDataWriter,n.key,n,new Xl(this._snapshot.mutatedKeys.has(n.key),this._snapshot.fromCache),this.query.converter))}))}docChanges(e={}){const t=!!e.includeMetadataChanges;if(t&&this._snapshot.excludesMetadataChanges)throw new I(_.INVALID_ARGUMENT,"To include metadata changes with your document changes, you must also pass { includeMetadataChanges:true } to onSnapshot().");return this._cachedChanges&&this._cachedChangesIncludeMetadataChanges===t||(this._cachedChanges=function(e,t){if(e._snapshot.oldDocs.isEmpty()){let t=0;return e._snapshot.docChanges.map((n=>{const r=new Zl(e._firestore,e._userDataWriter,n.doc.key,n.doc,new Xl(e._snapshot.mutatedKeys.has(n.doc.key),e._snapshot.fromCache),e.query.converter);return n.doc,{type:"added",doc:r,oldIndex:-1,newIndex:t++}}))}{let n=e._snapshot.oldDocs;return e._snapshot.docChanges.filter((e=>t||3!==e.type)).map((t=>{const r=new Zl(e._firestore,e._userDataWriter,t.doc.key,t.doc,new Xl(e._snapshot.mutatedKeys.has(t.doc.key),e._snapshot.fromCache),e.query.converter);let i=-1,s=-1;return 0!==t.type&&(i=n.indexOf(t.doc.key),n=n.delete(t.doc.key)),1!==t.type&&(n=n.add(t.doc),s=n.indexOf(t.doc.key)),{type:th(t.type),doc:r,oldIndex:i,newIndex:s}}))}}(this,t),this._cachedChangesIncludeMetadataChanges=t),this._cachedChanges}}function th(e){switch(e){case 0:return"added";case 2:case 3:return"modified";case 1:return"removed";default:return v()}}class nh extends Ql{constructor(e){super(),this.firestore=e}convertBytes(e){return new Zu(e)}convertReference(e){const t=this.convertDocumentKey(e,this.firestore._databaseId);return new Bu(this.firestore,null,t)}}function rh(e,t){return function(e,t){const n=new E;return e.asyncQueue.enqueueAndForget((async()=>async function(e,t,n){const r=ru(e);try{const e=await function(e,t){const n=b(e),r=F.now(),i=t.reduce(((e,t)=>e.add(t.key)),nr());let s,o;return n.persistence.runTransaction("Locally write mutations","readwrite",(e=>{let a=Qn(),c=nr();return n.hs.getEntries(e,i).next((e=>{a=e,a.forEach(((e,t)=>{t.isValidDocument()||(c=c.add(e))}))})).next((()=>n.localDocuments.getOverlayedDocuments(e,a))).next((i=>{s=i;const o=[];for(const e of t){const t=Dr(e,s.get(e.key).overlayedDocument);null!=t&&o.push(new Nr(e.key,t,Kt(t.value.mapValue),Ir.exists(!0)))}return n.mutationQueue.addMutationBatch(e,r,o,t)})).next((t=>{o=t;const r=t.applyToLocalDocumentSet(s,c);return n.documentOverlayCache.saveOverlays(e,t.batchId,r)}))})).then((()=>({batchId:o.batchId,changes:Jn(s)})))}(r.localStore,t);r.sharedClientState.addPendingMutation(e.batchId),function(e,t,n){let r=e.qa[e.currentUser.toKey()];r||(r=new nt(M)),r=r.insert(t,n),e.qa[e.currentUser.toKey()]=r}(r,e.batchId,n),await Gc(r,e.changes),await ja(r.remoteStore)}catch(e){const t=nc(e,"Failed to persist write");n.reject(t)}}(await Iu(e),t,n))),n.promise}(Hu(e),t)}function ih(e,t,n){const r=n.docs.get(t._key),i=new nh(e);return new Yl(e,i,t._key,r,new Xl(n.hasPendingWrites,n.fromCache),t.converter)}function sh(e,t){const n=Mu(e.firestore,Qu),r=Hu(n),i=et(t,((e,t)=>new Br(t,e.aggregateType,e._internalFieldPath)));return function(e,t,n){const r=new E;return e.asyncQueue.enqueueAndForget((async()=>{try{const i=await Eu(e);r.resolve(async function(e,t,n){var r;const i=b(e),{request:s,lt:o,parent:a}=Li(i.serializer,Mn(t),n);i.connection.Co||delete s.parent;const c=(await i.ko("RunAggregationQuery",i.serializer.databaseId,a,s,1)).filter((e=>!!e.result));w(1===c.length);const u=null===(r=c[0].result)||void 0===r?void 0:r.aggregateFields;return Object.keys(u).reduce(((e,t)=>(e[o[t]]=u[t],e)),{})}(i,t,n))}catch(e){r.reject(e)}})),r.promise}(r,e._query,i).then((t=>function(e,t,n){const r=new nh(e);return new Yu(t,r,n)}(n,e,t)))}class oh{constructor(e){this.kind="memory",this._onlineComponentProvider=cu.provider,(null==e?void 0:e.garbageCollector)?this._offlineComponentProvider=e.garbageCollector._offlineComponentProvider:this._offlineComponentProvider={build:()=>new su(void 0)}}toJSON(){return{kind:this.kind}}}class ah{constructor(e){let t;this.kind="persistent",(null==e?void 0:e.tabManager)?(e.tabManager._initialize(e),t=e.tabManager):(t=dh(void 0),t._initialize(e)),this._onlineComponentProvider=t._onlineComponentProvider,this._offlineComponentProvider=t._offlineComponentProvider}toJSON(){return{kind:this.kind}}}class ch{constructor(){this.kind="memoryEager",this._offlineComponentProvider=iu.provider}toJSON(){return{kind:this.kind}}}class uh{constructor(e){this.kind="memoryLru",this._offlineComponentProvider={build:()=>new su(e)}}toJSON(){return{kind:this.kind}}}class lh{constructor(e){this.forceOwnership=e,this.kind="persistentSingleTab"}toJSON(){return{kind:this.kind}}_initialize(e){this._onlineComponentProvider=cu.provider,this._offlineComponentProvider={build:t=>new ou(t,null==e?void 0:e.cacheSizeBytes,this.forceOwnership)}}}class hh{constructor(){this.kind="PersistentMultipleTab"}toJSON(){return{kind:this.kind}}_initialize(e){this._onlineComponentProvider=cu.provider,this._offlineComponentProvider={build:t=>new au(t,null==e?void 0:e.cacheSizeBytes)}}}function dh(e){return new lh(null==e?void 0:e.forceOwnership)}const fh={maxAttempts:5};class gh{constructor(e,t){this._firestore=e,this._commitHandler=t,this._mutations=[],this._committed=!1,this._dataReader=ll(e)}set(e,t,n){this._verifyNotCommitted();const r=ph(e,this._firestore),i=Hl(r.converter,t,n),s=hl(this._dataReader,"WriteBatch.set",r._key,i,null!==r.converter,n);return this._mutations.push(s.toMutation(r._key,Ir.none())),this}update(e,t,n,...r){this._verifyNotCommitted();const i=ph(e,this._firestore);let s;return s="string"==typeof(t=o.getModularInstance(t))||t instanceof el?wl(this._dataReader,"WriteBatch.update",i._key,t,n,r):vl(this._dataReader,"WriteBatch.update",i._key,t),this._mutations.push(s.toMutation(i._key,Ir.exists(!0))),this}delete(e){this._verifyNotCommitted();const t=ph(e,this._firestore);return this._mutations=this._mutations.concat(new Rr(t._key,Ir.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 I(_.FAILED_PRECONDITION,"A write batch can no longer be used after commit() has been called.")}}function ph(e,t){if((e=o.getModularInstance(e)).firestore!==t)throw new I(_.INVALID_ARGUMENT,"Provided document reference is from a different Firestore instance.");return e}class mh extends class{constructor(e,t){this._firestore=e,this._transaction=t,this._dataReader=ll(e)}get(e){const t=ph(e,this._firestore),n=new Wl(this._firestore);return this._transaction.lookup([t._key]).then((e=>{if(!e||1!==e.length)return v();const r=e[0];if(r.isFoundDocument())return new kl(this._firestore,n,r.key,r,t.converter);if(r.isNoDocument())return new kl(this._firestore,n,t._key,null,t.converter);throw v()}))}set(e,t,n){const r=ph(e,this._firestore),i=Hl(r.converter,t,n),s=hl(this._dataReader,"Transaction.set",r._key,i,null!==r.converter,n);return this._transaction.set(r._key,s),this}update(e,t,n,...r){const i=ph(e,this._firestore);let s;return s="string"==typeof(t=o.getModularInstance(t))||t instanceof el?wl(this._dataReader,"Transaction.update",i._key,t,n,r):vl(this._dataReader,"Transaction.update",i._key,t),this._transaction.update(i._key,s),this}delete(e){const t=ph(e,this._firestore);return this._transaction.delete(t._key),this}}{constructor(e,t){super(e,t),this._firestore=e}get(e){const t=ph(e,this._firestore),n=new nh(this._firestore);return super.get(e).then((e=>new Yl(this._firestore,n,t._key,e._document,new Xl(!1,!1),t.converter)))}}function yh(e,t){if("string"!=typeof e[t])throw new I(_.INVALID_ARGUMENT,"Missing string value for: "+t);return e[t]}class vh{constructor(e){this._firestore=e,this.type="PersistentCacheIndexManager"}}function wh(e,t){(function(e,t){return e.asyncQueue.enqueue((async()=>function(e,t){b(e)._s.Hi=t}(await bu(e),t)))})(Hu(e._firestore),t).then((e=>g(`setting persistent cache index auto creation isEnabled=${t} succeeded`))).catch((e=>m(`setting persistent cache index auto creation isEnabled=${t} failed`,e)))}const bh=new WeakMap;class _h{constructor(){this.Gu=new Map}static get instance(){return Ih||(Ih=new _h,function(e){if(Kr)throw new Error("a TestingHooksSpi instance is already set");Kr=e}(Ih)),Ih}tt(e){this.Gu.forEach((t=>t(e)))}onExistenceFilterMismatch(e){const t=Symbol(),n=this.Gu;return n.set(t,e),()=>n.delete(t)}}let Ih=null;!function(e,t=!0){!function(e){h=e}(r.SDK_VERSION),r._registerComponent(new i.Component("firestore",((e,{instanceIdentifier:n,options:r})=>{const i=e.getProvider("app").getImmediate(),s=new Qu(new C(e.getProvider("auth-internal")),new N(e.getProvider("app-check-internal")),function(e,t){if(!Object.prototype.hasOwnProperty.apply(e.options,["projectId"]))throw new I(_.INVALID_ARGUMENT,'"projectId" not provided in firebase.initializeApp.');return new wt(e.options.projectId,t)}(i,n),i);return r=Object.assign({useFetchStreams:t},r),s._setSettings(r),s}),"PUBLIC").setMultipleInstances(!0)),r.registerVersion(u,"4.7.5",e),r.registerVersion(u,"4.7.5","cjs2017")}(),t.AbstractUserDataWriter=Ql,t.AggregateField=Xu,t.AggregateQuerySnapshot=Yu,t.Bytes=Zu,t.CACHE_SIZE_UNLIMITED=-1,t.CollectionReference=Uu,t.DocumentReference=Bu,t.DocumentSnapshot=Yl,t.FieldPath=el,t.FieldValue=tl,t.Firestore=Qu,t.FirestoreError=I,t.GeoPoint=nl,t.LoadBundleTask=Ku,t.PersistentCacheIndexManager=vh,t.Query=qu,t.QueryCompositeFilterConstraint=Fl,t.QueryConstraint=Rl,t.QueryDocumentSnapshot=Zl,t.QueryEndAtConstraint=Ul,t.QueryFieldFilterConstraint=Pl,t.QueryLimitConstraint=ql,t.QueryOrderByConstraint=Vl,t.QuerySnapshot=eh,t.QueryStartAtConstraint=Bl,t.SnapshotMetadata=Xl,t.Timestamp=F,t.Transaction=mh,t.VectorValue=rl,t.WriteBatch=gh,t._AutoId=O,t._ByteString=lt,t._DatabaseId=wt,t._DocumentKey=$,t._EmptyAppCheckTokenProvider=class{getToken(){return Promise.resolve(new k(""))}invalidateToken(){}start(e,t){}shutdown(){}},t._EmptyAuthCredentialsProvider=S,t._FieldPath=j,t._TestingHooks=class{constructor(){throw new Error("instances of this class should not be created")}static onExistenceFilterMismatch(e){return _h.instance.onExistenceFilterMismatch(e)}},t._cast=Mu,t._debugAssert=function(e,t){e||v()},t._internalAggregationQueryToProtoRunAggregationQueryRequest=function(e,t){var n;const r=et(t,((e,t)=>new Br(t,e.aggregateType,e._internalFieldPath))),i=null===(n=Hu(Mu(e.firestore,Qu))._onlineComponents)||void 0===n?void 0:n.datastore.serializer;return void 0===i?null:Li(i,Mn(e._query),r,!0).request},t._internalQueryToProtoQueryTarget=function(e){var t;const n=null===(t=Hu(Mu(e.firestore,Qu))._onlineComponents)||void 0===t?void 0:t.datastore.serializer;return void 0===n?null:Ni(n,On(e._query)).ct},t._isBase64Available=function(){return"undefined"!=typeof atob},t._logWarn=m,t._validateIsNotUsedTogether=ku,t.addDoc=function(e,t){const n=Mu(e.firestore,Qu),r=ju(e),i=Hl(e.converter,t);return rh(n,[hl(ll(e.firestore),"addDoc",r._key,i,null!==e.converter,{}).toMutation(r._key,Ir.exists(!1))]).then((()=>r))},t.aggregateFieldEqual=function(e,t){var n,r;return e instanceof Xu&&t instanceof Xu&&e.aggregateType===t.aggregateType&&(null===(n=e._internalFieldPath)||void 0===n?void 0:n.canonicalString())===(null===(r=t._internalFieldPath)||void 0===r?void 0:r.canonicalString())},t.aggregateQuerySnapshotEqual=function(e,t){return $u(e.query,t.query)&&o.deepEqual(e.data(),t.data())},t.and=function(...e){return e.forEach((e=>Kl("and",e))),Fl._create("and",e)},t.arrayRemove=function(...e){return new ml("arrayRemove",e)},t.arrayUnion=function(...e){return new pl("arrayUnion",e)},t.average=function(e){return new Xu("avg",Sl("average",e))},t.clearIndexedDbPersistence=function(e){if(e._initialized&&!e._terminated)throw new I(_.FAILED_PRECONDITION,"Persistence can only be cleared before a Firestore instance is initialized or after it is terminated.");const t=new E;return e._queue.enqueueAndForgetEvenWhileRestricted((async()=>{try{await async function(e){if(!oe.p())return Promise.resolve();const t=e+"main";await oe.delete(t)}(Ro(e._databaseId,e._persistenceKey)),t.resolve()}catch(e){t.reject(e)}})),t.promise},t.collection=function(e,t,...n){if(e=o.getModularInstance(e),Au("collection","path",t),e instanceof Fu){const r=B.fromString(t,...n);return Lu(r),new Uu(e,null,r)}{if(!(e instanceof Bu||e instanceof Uu))throw new I(_.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");const r=e._path.child(B.fromString(t,...n));return Lu(r),new Uu(e.firestore,null,r)}},t.collectionGroup=function(e,t){if(e=Mu(e,Fu),Au("collectionGroup","collection id",t),t.indexOf("/")>=0)throw new I(_.INVALID_ARGUMENT,`Invalid collection ID '${t}' passed to function collectionGroup(). Collection IDs must not contain '/'.`);return new qu(e,null,function(e){return new Cn(B.emptyPath(),e)}(t))},t.connectFirestoreEmulator=Vu,t.count=Jl,t.deleteAllPersistentCacheIndexes=function(e){(function(e){return e.asyncQueue.enqueue((async()=>function(e){const t=b(e),n=t.indexManager;return t.persistence.runTransaction("Delete All Indexes","readwrite",(e=>n.deleteAllFieldIndexes(e)))}(await bu(e))))})(Hu(e._firestore)).then((e=>g("deleting all persistent cache indexes succeeded"))).catch((e=>m("deleting all persistent cache indexes failed",e)))},t.deleteDoc=function(e){return rh(Mu(e.firestore,Qu),[new Rr(e._key,Ir.none())])},t.deleteField=function(){return new dl("deleteField")},t.disableNetwork=function(e){return function(e){return e.asyncQueue.enqueue((async()=>{const t=await wu(e),n=await _u(e);return t.setNetworkEnabled(!1),async function(e){const t=b(e);t.k_.add(0),await Ca(t),t.K_.set("Offline")}(n)}))}(Hu(e=Mu(e,Qu)))},t.disablePersistentCacheIndexAutoCreation=function(e){wh(e,!1)},t.doc=ju,t.documentId=function(){return new el("__name__")},t.enableIndexedDbPersistence=function(e,t){m("enableIndexedDbPersistence() will be deprecated in the future, you can use `FirestoreSettings.cache` instead.");const n=e._freezeSettings();return Ju(e,cu.provider,{build:e=>new ou(e,n.cacheSizeBytes,null==t?void 0:t.forceOwnership)}),Promise.resolve()},t.enableMultiTabIndexedDbPersistence=async function(e){m("enableMultiTabIndexedDbPersistence() will be deprecated in the future, you can use `FirestoreSettings.cache` instead.");const t=e._freezeSettings();Ju(e,cu.provider,{build:e=>new au(e,t.cacheSizeBytes)})},t.enableNetwork=function(e){return function(e){return e.asyncQueue.enqueue((async()=>{const t=await wu(e),n=await _u(e);return t.setNetworkEnabled(!0),function(e){const t=b(e);return t.k_.delete(0),xa(t)}(n)}))}(Hu(e=Mu(e,Qu)))},t.enablePersistentCacheIndexAutoCreation=function(e){wh(e,!0)},t.endAt=function(...e){return Ul._create("endAt",e,!0)},t.endBefore=function(...e){return Ul._create("endBefore",e,!1)},t.ensureFirestoreConfigured=Hu,t.executeWrite=rh,t.getAggregateFromServer=sh,t.getCountFromServer=function(e){return sh(e,{count:Jl()})},t.getDoc=function(e){e=Mu(e,Bu);const t=Mu(e.firestore,Qu);return Su(Hu(t),e._key).then((n=>ih(t,e,n)))},t.getDocFromCache=function(e){e=Mu(e,Bu);const t=Mu(e.firestore,Qu),n=Hu(t),r=new nh(t);return function(e,t){const n=new E;return e.asyncQueue.enqueueAndForget((async()=>async function(e,t,n){try{const r=await function(e,t){const n=b(e);return n.persistence.runTransaction("read document","readonly",(e=>n.localDocuments.getDocument(e,t)))}(e,t);r.isFoundDocument()?n.resolve(r):r.isNoDocument()?n.resolve(null):n.reject(new I(_.UNAVAILABLE,"Failed to get document from cache. (However, this document may exist on the server. Run again without setting 'source' in the GetOptions to attempt to retrieve the document from the server.)"))}catch(e){const r=nc(e,`Failed to get document '${t} from cache`);n.reject(r)}}(await bu(e),t,n))),n.promise}(n,e._key).then((n=>new Yl(t,r,e._key,n,new Xl(null!==n&&n.hasLocalMutations,!0),e.converter)))},t.getDocFromServer=function(e){e=Mu(e,Bu);const t=Mu(e.firestore,Qu);return Su(Hu(t),e._key,{source:"server"}).then((n=>ih(t,e,n)))},t.getDocs=function(e){e=Mu(e,qu);const t=Mu(e.firestore,Qu),n=Hu(t),r=new nh(t);return Ol(e._query),xu(n,e._query).then((n=>new eh(t,r,e,n)))},t.getDocsFromCache=function(e){e=Mu(e,qu);const t=Mu(e.firestore,Qu),n=Hu(t),r=new nh(t);return function(e,t){const n=new E;return e.asyncQueue.enqueueAndForget((async()=>async function(e,t,n){try{const r=await Qo(e,t,!0),i=new Ec(t,r.ds),s=i.ga(r.documents),o=i.applyChanges(s,!1);n.resolve(o.snapshot)}catch(e){const r=nc(e,`Failed to execute query '${t} against cache`);n.reject(r)}}(await bu(e),t,n))),n.promise}(n,e._query).then((n=>new eh(t,r,e,n)))},t.getDocsFromServer=function(e){e=Mu(e,qu);const t=Mu(e.firestore,Qu),n=Hu(t),r=new nh(t);return xu(n,e._query,{source:"server"}).then((n=>new eh(t,r,e,n)))},t.getFirestore=function(e,t){const n="object"==typeof e?e:r.getApp(),i="string"==typeof e?e:t||"(default)",s=r._getProvider(n,"firestore").getImmediate({identifier:i});if(!s._initialized){const e=o.getDefaultEmulatorHostnameAndPort("firestore");e&&Vu(s,...e)}return s},t.getPersistentCacheIndexManager=function(e){var t;e=Mu(e,Qu);const n=bh.get(e);if(n)return n;if("persistent"!==(null===(t=Hu(e)._uninitializedComponentsProvider)||void 0===t?void 0:t._offline.kind))return null;const r=new vh(e);return bh.set(e,r),r},t.increment=function(e){return new yl("increment",e)},t.initializeFirestore=function(e,t,n){n||(n="(default)");const i=r._getProvider(e,"firestore");if(i.isInitialized(n)){const e=i.getImmediate({identifier:n}),r=i.getOptions(n);if(o.deepEqual(r,t))return e;throw new I(_.FAILED_PRECONDITION,"initializeFirestore() has already been called with different options. To avoid this error, call initializeFirestore() with the same options as when it was originally called, or call getFirestore() to return the already initialized instance.")}if(void 0!==t.cacheSizeBytes&&void 0!==t.localCache)throw new I(_.INVALID_ARGUMENT,"cache and cacheSizeBytes cannot be specified at the same time as cacheSizeBytes willbe deprecated. Instead, specify the cache size in the cache object");if(void 0!==t.cacheSizeBytes&&-1!==t.cacheSizeBytes&&t.cacheSizeBytes<1048576)throw new I(_.INVALID_ARGUMENT,"cacheSizeBytes must be at least 1048576");return i.initialize({options:t,instanceIdentifier:n})},t.limit=function(e){return Ru("limit",e),ql._create("limit",e,"F")},t.limitToLast=function(e){return Ru("limitToLast",e),ql._create("limitToLast",e,"L")},t.loadBundle=function(e,t){const n=Hu(e=Mu(e,Qu)),r=new Ku;return function(e,t,n,r){const i=function(e,t){let n;return n="string"==typeof e?Qr().encode(e):e,function(e,t){return new hu(e,t)}(function(e,t){if(e instanceof Uint8Array)return uu(e,t);if(e instanceof ArrayBuffer)return uu(new Uint8Array(e),t);if(e instanceof ReadableStream)return e.getReader();throw new Error("Source of `toByteStreamReader` has to be a ArrayBuffer or ReadableStream")}(n),t)}(n,va(t));e.asyncQueue.enqueueAndForget((async()=>{!function(e,t,n){const r=b(e);(async function(e,t,n){try{const r=await t.getMetadata();if(await function(e,t){const n=b(e),r=mi(t.createTime);return n.persistence.runTransaction("hasNewerBundle","readonly",(e=>n.jr.getBundleMetadata(e,t.id))).then((e=>!!e&&e.createTime.compareTo(r)>=0))}(e.localStore,r))return await t.close(),n._completeWith(function(e){return{taskState:"Success",documentsLoaded:e.totalDocuments,bytesLoaded:e.totalBytes,totalDocuments:e.totalDocuments,totalBytes:e.totalBytes}}(r)),Promise.resolve(new Set);n._updateProgress(bc(r));const i=new wc(r,e.localStore,t.serializer);let s=await t.Ga();for(;s;){const e=await i.Pa(s);e&&n._updateProgress(e),s=await t.Ga()}const o=await i.complete();return await Gc(e,o.Ea,void 0),await function(e,t){const n=b(e);return n.persistence.runTransaction("Save bundle","readwrite",(e=>n.jr.saveBundleMetadata(e,t)))}(e.localStore,r),n._completeWith(o.progress),Promise.resolve(o.Ia)}catch(e){return m("SyncEngine",`Loading bundle failed with ${e}`),n._failWith(e),Promise.resolve(new Set)}})(r,t,n).then((e=>{r.sharedClientState.notifyBundleLoaded(e)}))}(await Iu(e),i,r)}))}(n,e._databaseId,t,r),r},t.memoryEagerGarbageCollector=function(){return new ch},t.memoryLocalCache=function(e){return new oh(e)},t.memoryLruGarbageCollector=function(e){return new uh(null==e?void 0:e.cacheSizeBytes)},t.namedQuery=function(e,t){return function(e,t){return e.asyncQueue.enqueue((async()=>function(e,t){const n=b(e);return n.persistence.runTransaction("Get named query","readonly",(e=>n.jr.getNamedQuery(e,t)))}(await bu(e),t)))}(Hu(e=Mu(e,Qu)),t).then((t=>t?new qu(e,null,t.query):null))},t.onSnapshot=function(e,...t){var n,r,i;e=o.getModularInstance(e);let s={includeMetadataChanges:!1,source:"default"},a=0;"object"!=typeof t[a]||Gu(t[a])||(s=t[a],a++);const c={includeMetadataChanges:s.includeMetadataChanges,source:s.source};if(Gu(t[a])){const e=t[a];t[a]=null===(n=e.next)||void 0===n?void 0:n.bind(e),t[a+1]=null===(r=e.error)||void 0===r?void 0:r.bind(e),t[a+2]=null===(i=e.complete)||void 0===i?void 0:i.bind(e)}let u,l,h;if(e instanceof Bu)l=Mu(e.firestore,Qu),h=An(e._key.path),u={next:n=>{t[a]&&t[a](ih(l,e,n))},error:t[a+1],complete:t[a+2]};else{const n=Mu(e,qu);l=Mu(n.firestore,Qu),h=n._query;const r=new nh(l);u={next:e=>{t[a]&&t[a](new eh(l,r,n,e))},error:t[a+1],complete:t[a+2]},Ol(e._query)}return function(e,t,n,r){const i=new lu(r),s=new mc(t,i,n);return e.asyncQueue.enqueueAndForget((async()=>uc(await Tu(e),s))),()=>{i.eu(),e.asyncQueue.enqueueAndForget((async()=>lc(await Tu(e),s)))}}(Hu(l),h,c,u)},t.onSnapshotsInSync=function(e,t){return function(e,t){const n=new lu(t);return e.asyncQueue.enqueueAndForget((async()=>function(e,t){b(e).X_.add(t),t.next()}(await Tu(e),n))),()=>{n.eu(),e.asyncQueue.enqueueAndForget((async()=>function(e,t){b(e).X_.delete(t)}(await Tu(e),n)))}}(Hu(e=Mu(e,Qu)),Gu(t)?t:{next:t})},t.or=function(...e){return e.forEach((e=>Kl("or",e))),Fl._create("or",e)},t.orderBy=function(e,t="asc"){const n=t,r=Ll("orderBy",e);return Vl._create(r,n)},t.persistentLocalCache=function(e){return new ah(e)},t.persistentMultipleTabManager=function(){return new hh},t.persistentSingleTabManager=dh,t.query=function(e,t,...n){let r=[];t instanceof Ml&&r.push(t),r=r.concat(n),function(e){const t=e.filter((e=>e instanceof Fl)).length,n=e.filter((e=>e instanceof Pl)).length;if(t>1||t>0&&n>0)throw new I(_.INVALID_ARGUMENT,"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(...)))`.")}(r);for(const t of r)e=t._apply(e);return e},t.queryEqual=$u,t.refEqual=function(e,t){return e=o.getModularInstance(e),t=o.getModularInstance(t),(e instanceof Bu||e instanceof Uu)&&(t instanceof Bu||t instanceof Uu)&&e.firestore===t.firestore&&e.path===t.path&&e.converter===t.converter},t.runTransaction=function(e,t,n){e=Mu(e,Qu);const r=Object.assign(Object.assign({},fh),n);return function(e){if(e.maxAttempts<1)throw new I(_.INVALID_ARGUMENT,"Max attempts must be at least 1")}(r),function(e,t,n){const r=new E;return e.asyncQueue.enqueueAndForget((async()=>{const i=await Eu(e);new fu(e.asyncQueue,i,n,t,r).cu()})),r.promise}(Hu(e),(n=>t(new mh(e,n))),r)},t.serverTimestamp=function(){return new gl("serverTimestamp")},t.setDoc=function(e,t,n){e=Mu(e,Bu);const r=Mu(e.firestore,Qu),i=Hl(e.converter,t,n);return rh(r,[hl(ll(r),"setDoc",e._key,i,null!==e.converter,n).toMutation(e._key,Ir.none())])},t.setIndexConfiguration=function(e,t){const n=Hu(e=Mu(e,Qu));if(!n._uninitializedComponentsProvider||"memory"===n._uninitializedComponentsProvider._offline.kind)return m("Cannot enable indexes when persistence is disabled"),Promise.resolve();const r=function(e){const t="string"==typeof e?function(e){try{return JSON.parse(e)}catch(e){throw new I(_.INVALID_ARGUMENT,"Failed to parse JSON: "+(null==e?void 0:e.message))}}(e):e,n=[];if(Array.isArray(t.indexes))for(const e of t.indexes){const t=yh(e,"collectionGroup"),r=[];if(Array.isArray(e.fields))for(const t of e.fields){const e=Cl("setIndexConfiguration",yh(t,"fieldPath"));"CONTAINS"===t.arrayConfig?r.push(new H(e,2)):"ASCENDING"===t.order?r.push(new H(e,0)):"DESCENDING"===t.order&&r.push(new H(e,1))}n.push(new z(z.UNKNOWN_ID,t,r,J.empty()))}return n}(t);return function(e,t){return e.asyncQueue.enqueue((async()=>async function(e,t){const n=b(e),r=n.indexManager,i=[];return n.persistence.runTransaction("Configure indexes","readwrite",(e=>r.getFieldIndexes(e).next((n=>function(e,t,n,r,i){e=[...e],t=[...t],e.sort(n),t.sort(n);const s=e.length,o=t.length;let a=0,c=0;for(;a<o&&c<s;){const s=n(e[c],t[a]);s<0?i(e[c++]):s>0?r(t[a++]):(a++,c++)}for(;a<o;)r(t[a++]);for(;c<s;)i(e[c++])}(n,t,Q,(t=>{i.push(r.addFieldIndex(e,t))}),(t=>{i.push(r.deleteFieldIndex(e,t))})))).next((()=>ie.waitFor(i)))))}(await bu(e),t)))}(n,r)},t.setLogLevel=function(e){d.setLogLevel(e)},t.snapshotEqual=function(e,t){return e instanceof Yl&&t instanceof Yl?e._firestore===t._firestore&&e._key.isEqual(t._key)&&(null===e._document?null===t._document:e._document.isEqual(t._document))&&e._converter===t._converter:e instanceof eh&&t instanceof eh&&e._firestore===t._firestore&&$u(e.query,t.query)&&e.metadata.isEqual(t.metadata)&&e._snapshot.isEqual(t._snapshot)},t.startAfter=function(...e){return Bl._create("startAfter",e,!1)},t.startAt=function(...e){return Bl._create("startAt",e,!0)},t.sum=function(e){return new Xu("sum",Sl("sum",e))},t.terminate=function(e){return r._removeServiceInstance(e.app,"firestore",e._databaseId.database),e._delete()},t.updateDoc=function(e,t,n,...r){e=Mu(e,Bu);const i=Mu(e.firestore,Qu),s=ll(i);let a;return a="string"==typeof(t=o.getModularInstance(t))||t instanceof el?wl(s,"updateDoc",e._key,t,n,r):vl(s,"updateDoc",e._key,t),rh(i,[a.toMutation(e._key,Ir.exists(!0))])},t.vector=function(e){return new rl(e)},t.waitForPendingWrites=function(e){return function(e){const t=new E;return e.asyncQueue.enqueueAndForget((async()=>async function(e,t){const n=b(e);Ma(n.remoteStore)||g("SyncEngine","The network is disabled. The task returned by 'awaitPendingWrites()' will not complete until the network is enabled.");try{const e=await function(e){const t=b(e);return t.persistence.runTransaction("Get highest unacknowledged batch id","readonly",(e=>t.mutationQueue.getHighestUnacknowledgedBatchId(e)))}(n.localStore);if(-1===e)return void t.resolve();const r=n.Qa.get(e)||[];r.push(t),n.Qa.set(e,r)}catch(e){const n=nc(e,"Initialization of waitForPendingWrites() operation failed");t.reject(n)}}(await Iu(e),t))),t.promise}(Hu(e=Mu(e,Qu)))},t.where=function(e,t,n){const r=t,i=Ll("where",e);return Pl._create(i,r,n)},t.writeBatch=function(e){return Hu(e=Mu(e,Qu)),new gh(e,(t=>rh(e,t)))}},249:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(199),i=n(336),s=n(319);function o(e,t){const n={};for(const r in e)e.hasOwnProperty(r)&&(n[r]=t(e[r]));return n}function a(e){if(null==e)return null;if(e instanceof Number&&(e=e.valueOf()),"number"==typeof e&&isFinite(e))return e;if(!0===e||!1===e)return e;if("[object String]"===Object.prototype.toString.call(e))return e;if(e instanceof Date)return e.toISOString();if(Array.isArray(e))return e.map((e=>a(e)));if("function"==typeof e||"object"==typeof e)return o(e,(e=>a(e)));throw new Error("Data cannot be encoded in JSON: "+e)}function c(e){if(null==e)return e;if(e["@type"])switch(e["@type"]){case"type.googleapis.com/google.protobuf.Int64Value":case"type.googleapis.com/google.protobuf.UInt64Value":{const t=Number(e.value);if(isNaN(t))throw new Error("Data cannot be decoded from JSON: "+e);return t}default:throw new Error("Data cannot be decoded from JSON: "+e)}return Array.isArray(e)?e.map((e=>c(e))):"function"==typeof e||"object"==typeof e?o(e,(e=>c(e))):e}const u="functions",l={OK:"ok",CANCELLED:"cancelled",UNKNOWN:"unknown",INVALID_ARGUMENT:"invalid-argument",DEADLINE_EXCEEDED:"deadline-exceeded",NOT_FOUND:"not-found",ALREADY_EXISTS:"already-exists",PERMISSION_DENIED:"permission-denied",UNAUTHENTICATED:"unauthenticated",RESOURCE_EXHAUSTED:"resource-exhausted",FAILED_PRECONDITION:"failed-precondition",ABORTED:"aborted",OUT_OF_RANGE:"out-of-range",UNIMPLEMENTED:"unimplemented",INTERNAL:"internal",UNAVAILABLE:"unavailable",DATA_LOSS:"data-loss"};class h extends i.FirebaseError{constructor(e,t,n){super(`${u}/${e}`,t||""),this.details=n,Object.setPrototypeOf(this,h.prototype)}}function d(e,t){let n,r=function(e){if(e>=200&&e<300)return"ok";switch(e){case 0:case 500:return"internal";case 400:return"invalid-argument";case 401:return"unauthenticated";case 403:return"permission-denied";case 404:return"not-found";case 409:return"aborted";case 429:return"resource-exhausted";case 499:return"cancelled";case 501:return"unimplemented";case 503:return"unavailable";case 504:return"deadline-exceeded"}return"unknown"}(e),i=r;try{const e=t&&t.error;if(e){const t=e.status;if("string"==typeof t){if(!l[t])return new h("internal","internal");r=l[t],i=t}const s=e.message;"string"==typeof s&&(i=s),n=e.details,void 0!==n&&(n=c(n))}}catch(e){}return"ok"===r?null:new h(r,i,n)}class f{constructor(e,t,n){this.auth=null,this.messaging=null,this.appCheck=null,this.auth=e.getImmediate({optional:!0}),this.messaging=t.getImmediate({optional:!0}),this.auth||e.get().then((e=>this.auth=e),(()=>{})),this.messaging||t.get().then((e=>this.messaging=e),(()=>{})),this.appCheck||n.get().then((e=>this.appCheck=e),(()=>{}))}async getAuthToken(){if(this.auth)try{const e=await this.auth.getToken();return null==e?void 0:e.accessToken}catch(e){return}}async getMessagingToken(){if(this.messaging&&"Notification"in self&&"granted"===Notification.permission)try{return await this.messaging.getToken()}catch(e){return}}async getAppCheckToken(e){if(this.appCheck){const t=e?await this.appCheck.getLimitedUseToken():await this.appCheck.getToken();return t.error?null:t.token}return null}async getContext(e){return{authToken:await this.getAuthToken(),messagingToken:await this.getMessagingToken(),appCheckToken:await this.getAppCheckToken(e)}}}const g="us-central1",p=/^data: (.*?)(?:\n|$)/;class m{constructor(e,t,n,r,i=g,s=(...e)=>fetch(...e)){this.app=e,this.fetchImpl=s,this.emulatorOrigin=null,this.contextProvider=new f(t,n,r),this.cancelAllRequests=new Promise((e=>{this.deleteService=()=>Promise.resolve(e())}));try{const e=new URL(i);this.customDomain=e.origin+("/"===e.pathname?"":e.pathname),this.region=g}catch(e){this.customDomain=null,this.region=i}}_delete(){return this.deleteService()}_url(e){const t=this.app.options.projectId;return null!==this.emulatorOrigin?`${this.emulatorOrigin}/${t}/${this.region}/${e}`:null!==this.customDomain?`${this.customDomain}/${e}`:`https://${this.region}-${t}.cloudfunctions.net/${e}`}}async function y(e,t,n,r){let i;n["Content-Type"]="application/json";try{i=await r(e,{method:"POST",body:JSON.stringify(t),headers:n})}catch(e){return{status:0,json:null}}let s=null;try{s=await i.json()}catch(e){}return{status:i.status,json:s}}async function v(e,t){const n={},r=await e.contextProvider.getContext(t.limitedUseAppCheckTokens);return r.authToken&&(n.Authorization="Bearer "+r.authToken),r.messagingToken&&(n["Firebase-Instance-ID-Token"]=r.messagingToken),null!==r.appCheckToken&&(n["X-Firebase-AppCheck"]=r.appCheckToken),n}async function w(e,t,n,r){const i={data:n=a(n)},s=await v(e,r),o=function(e){let t=null;return{promise:new Promise(((n,r)=>{t=setTimeout((()=>{r(new h("deadline-exceeded","deadline-exceeded"))}),e)})),cancel:()=>{t&&clearTimeout(t)}}}(r.timeout||7e4),u=await Promise.race([y(t,i,s,e.fetchImpl),o.promise,e.cancelAllRequests]);if(o.cancel(),!u)throw new h("cancelled","Firebase Functions instance was deleted.");const l=d(u.status,u.json);if(l)throw l;if(!u.json)throw new h("internal","Response is not valid JSON object.");let f=u.json.data;if(void 0===f&&(f=u.json.result),void 0===f)throw new h("internal","Response is missing data field.");return{data:c(f)}}async function b(e,t,n,r){var i;const s={data:n=a(n)},o=await v(e,r);let u,l,f;o["Content-Type"]="application/json",o.Accept="text/event-stream";try{u=await e.fetchImpl(t,{method:"POST",body:JSON.stringify(s),headers:o,signal:null==r?void 0:r.signal})}catch(e){if(e instanceof Error&&"AbortError"===e.name){const e=new h("cancelled","Request was cancelled.");return{data:Promise.reject(e),stream:{[Symbol.asyncIterator]:()=>({next:()=>Promise.reject(e)})}}}const t=d(0,null);return{data:Promise.reject(t),stream:{[Symbol.asyncIterator]:()=>({next:()=>Promise.reject(t)})}}}const g=new Promise(((e,t)=>{l=e,f=t}));null===(i=null==r?void 0:r.signal)||void 0===i||i.addEventListener("abort",(()=>{const e=new h("cancelled","Request was cancelled.");f(e)}));const m=function(e,t,n,r){const i=(e,r)=>{const i=e.match(p);if(!i)return;const s=i[1];try{const e=JSON.parse(s);if("result"in e)return void t(c(e.result));if("message"in e)return void r.enqueue(c(e.message));if("error"in e){const t=d(0,e);return r.error(t),void n(t)}}catch(e){if(e instanceof h)return r.error(e),void n(e)}},s=new TextDecoder;return new ReadableStream({start(t){let o="";return async function a(){if(null==r?void 0:r.aborted){const e=new h("cancelled","Request was cancelled");return t.error(e),n(e),Promise.resolve()}try{const{value:c,done:u}=await e.read();if(u)return o.trim()&&i(o.trim(),t),void t.close();if(null==r?void 0:r.aborted){const r=new h("cancelled","Request was cancelled");return t.error(r),n(r),void await e.cancel()}o+=s.decode(c,{stream:!0});const l=o.split("\n");o=l.pop()||"";for(const e of l)e.trim()&&i(e.trim(),t);return a()}catch(e){const r=e instanceof h?e:d(0,null);t.error(r),n(r)}}()},cancel:()=>e.cancel()})}(u.body.getReader(),l,f,null==r?void 0:r.signal);return{stream:{[Symbol.asyncIterator](){const e=m.getReader();return{async next(){const{value:t,done:n}=await e.read();return{value:t,done:n}},return:async()=>(await e.cancel(),{done:!0,value:void 0})}}},data:g}}const _="@firebase/functions",I="0.12.0";function E(e,t,n){!function(e,t,n){e.emulatorOrigin=`http://${t}:${n}`}(i.getModularInstance(e),t,n)}r._registerComponent(new s.Component(u,((e,{instanceIdentifier:t})=>{const n=e.getProvider("app").getImmediate(),r=e.getProvider("auth-internal"),i=e.getProvider("messaging-internal"),s=e.getProvider("app-check-internal");return new m(n,r,i,s,t)}),"PUBLIC").setMultipleInstances(!0)),r.registerVersion(_,I,undefined),r.registerVersion(_,I,"cjs2017"),t.FunctionsError=h,t.connectFunctionsEmulator=E,t.getFunctions=function(e=r.getApp(),t=g){const n=r._getProvider(i.getModularInstance(e),u).getImmediate({identifier:t}),s=i.getDefaultEmulatorHostnameAndPort("functions");return s&&E(n,...s),n},t.httpsCallable=function(e,t,n){return function(e,t,n){const r=r=>function(e,t,n,r){const i=e._url(t);return w(e,i,n,r)}(e,t,r,n||{});return r.stream=(n,r)=>function(e,t,n,r){const i=e._url(t);return b(e,i,n,r||{})}(e,t,n,r),r}(i.getModularInstance(e),t,n)},t.httpsCallableFromURL=function(e,t,n){return function(e,t,n){const r=r=>w(e,t,r,n||{});return r.stream=(n,r)=>b(e,t,n,r||{}),r}(i.getModularInstance(e),t,n)}},844:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=[];var r;t.LogLevel=void 0,(r=t.LogLevel||(t.LogLevel={}))[r.DEBUG=0]="DEBUG",r[r.VERBOSE=1]="VERBOSE",r[r.INFO=2]="INFO",r[r.WARN=3]="WARN",r[r.ERROR=4]="ERROR",r[r.SILENT=5]="SILENT";const i={debug:t.LogLevel.DEBUG,verbose:t.LogLevel.VERBOSE,info:t.LogLevel.INFO,warn:t.LogLevel.WARN,error:t.LogLevel.ERROR,silent:t.LogLevel.SILENT},s=t.LogLevel.INFO,o={[t.LogLevel.DEBUG]:"log",[t.LogLevel.VERBOSE]:"log",[t.LogLevel.INFO]:"info",[t.LogLevel.WARN]:"warn",[t.LogLevel.ERROR]:"error"},a=(e,t,...n)=>{if(t<e.logLevel)return;const r=(new Date).toISOString(),i=o[t];if(!i)throw new Error(`Attempted to log a message with an invalid logType (value: ${t})`);console[i](`[${r}] ${e.name}:`,...n)};t.Logger=class{constructor(e){this.name=e,this._logLevel=s,this._logHandler=a,this._userLogHandler=null,n.push(this)}get logLevel(){return this._logLevel}set logLevel(e){if(!(e in t.LogLevel))throw new TypeError(`Invalid value "${e}" assigned to \`logLevel\``);this._logLevel=e}setLogLevel(e){this._logLevel="string"==typeof e?i[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,t.LogLevel.DEBUG,...e),this._logHandler(this,t.LogLevel.DEBUG,...e)}log(...e){this._userLogHandler&&this._userLogHandler(this,t.LogLevel.VERBOSE,...e),this._logHandler(this,t.LogLevel.VERBOSE,...e)}info(...e){this._userLogHandler&&this._userLogHandler(this,t.LogLevel.INFO,...e),this._logHandler(this,t.LogLevel.INFO,...e)}warn(...e){this._userLogHandler&&this._userLogHandler(this,t.LogLevel.WARN,...e),this._logHandler(this,t.LogLevel.WARN,...e)}error(...e){this._userLogHandler&&this._userLogHandler(this,t.LogLevel.ERROR,...e),this._logHandler(this,t.LogLevel.ERROR,...e)}},t.setLogLevel=function(e){n.forEach((t=>{t.setLogLevel(e)}))},t.setUserLogHandler=function(e,r){for(const s of n){let n=null;r&&r.level&&(n=i[r.level]),s.userLogHandler=null===e?null:(r,i,...s)=>{const o=s.map((e=>{if(null==e)return null;if("string"==typeof e)return e;if("number"==typeof e||"boolean"==typeof e)return e.toString();if(e instanceof Error)return e.message;try{return JSON.stringify(e)}catch(e){return null}})).filter((e=>e)).join(" ");i>=(null!=n?n:r.logLevel)&&e({level:t.LogLevel[i].toLowerCase(),message:o,args:s,type:r.name})}}}},336:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const r={NODE_CLIENT:!1,NODE_ADMIN:!1,SDK_VERSION:"${JSCORE_VERSION}"},i=function(e,t){if(!e)throw s(t)},s=function(e){return new Error("Firebase Database ("+r.SDK_VERSION+") INTERNAL ASSERT FAILED: "+e)},o=function(e){const t=[];let n=0;for(let r=0;r<e.length;r++){let i=e.charCodeAt(r);i<128?t[n++]=i:i<2048?(t[n++]=i>>6|192,t[n++]=63&i|128):55296==(64512&i)&&r+1<e.length&&56320==(64512&e.charCodeAt(r+1))?(i=65536+((1023&i)<<10)+(1023&e.charCodeAt(++r)),t[n++]=i>>18|240,t[n++]=i>>12&63|128,t[n++]=i>>6&63|128,t[n++]=63&i|128):(t[n++]=i>>12|224,t[n++]=i>>6&63|128,t[n++]=63&i|128)}return t},a={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,t){if(!Array.isArray(e))throw Error("encodeByteArray takes an array as a parameter");this.init_();const n=t?this.byteToCharMapWebSafe_:this.byteToCharMap_,r=[];for(let t=0;t<e.length;t+=3){const i=e[t],s=t+1<e.length,o=s?e[t+1]:0,a=t+2<e.length,c=a?e[t+2]:0,u=i>>2,l=(3&i)<<4|o>>4;let h=(15&o)<<2|c>>6,d=63&c;a||(d=64,s||(h=64)),r.push(n[u],n[l],n[h],n[d])}return r.join("")},encodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?btoa(e):this.encodeByteArray(o(e),t)},decodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?atob(e):function(e){const t=[];let n=0,r=0;for(;n<e.length;){const i=e[n++];if(i<128)t[r++]=String.fromCharCode(i);else if(i>191&&i<224){const s=e[n++];t[r++]=String.fromCharCode((31&i)<<6|63&s)}else if(i>239&&i<365){const s=((7&i)<<18|(63&e[n++])<<12|(63&e[n++])<<6|63&e[n++])-65536;t[r++]=String.fromCharCode(55296+(s>>10)),t[r++]=String.fromCharCode(56320+(1023&s))}else{const s=e[n++],o=e[n++];t[r++]=String.fromCharCode((15&i)<<12|(63&s)<<6|63&o)}}return t.join("")}(this.decodeStringToByteArray(e,t))},decodeStringToByteArray(e,t){this.init_();const n=t?this.charToByteMapWebSafe_:this.charToByteMap_,r=[];for(let t=0;t<e.length;){const i=n[e.charAt(t++)],s=t<e.length?n[e.charAt(t)]:0;++t;const o=t<e.length?n[e.charAt(t)]:64;++t;const a=t<e.length?n[e.charAt(t)]:64;if(++t,null==i||null==s||null==o||null==a)throw new c;const u=i<<2|s>>4;if(r.push(u),64!==o){const e=s<<4&240|o>>2;if(r.push(e),64!==a){const e=o<<6&192|a;r.push(e)}}}return r},init_(){if(!this.byteToCharMap_){this.byteToCharMap_={},this.charToByteMap_={},this.byteToCharMapWebSafe_={},this.charToByteMapWebSafe_={};for(let e=0;e<this.ENCODED_VALS.length;e++)this.byteToCharMap_[e]=this.ENCODED_VALS.charAt(e),this.charToByteMap_[this.byteToCharMap_[e]]=e,this.byteToCharMapWebSafe_[e]=this.ENCODED_VALS_WEBSAFE.charAt(e),this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[e]]=e,e>=this.ENCODED_VALS_BASE.length&&(this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(e)]=e,this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(e)]=e)}}};class c extends Error{constructor(){super(...arguments),this.name="DecodeBase64StringError"}}const u=function(e){const t=o(e);return a.encodeByteArray(t,!0)},l=function(e){return u(e).replace(/\./g,"")},h=function(e){try{return a.decodeString(e,!0)}catch(e){console.error("base64Decode failed: ",e)}return null};function d(e,t){if(!(t instanceof Object))return t;switch(t.constructor){case Date:return new Date(t.getTime());case Object:void 0===e&&(e={});break;case Array:e=[];break;default:return t}for(const n in t)t.hasOwnProperty(n)&&"__proto__"!==n&&(e[n]=d(e[n],t[n]));return e}function f(){if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if(void 0!==n.g)return n.g;throw new Error("Unable to locate global object.")}const g=()=>{try{return f().__FIREBASE_DEFAULTS__||(()=>{if("undefined"==typeof process||void 0===process.env)return;const e=process.env.__FIREBASE_DEFAULTS__;return e?JSON.parse(e):void 0})()||(()=>{if("undefined"==typeof document)return;let e;try{e=document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/)}catch(e){return}const t=e&&h(e[1]);return t&&JSON.parse(t)})()}catch(e){return void console.info(`Unable to get __FIREBASE_DEFAULTS__ due to: ${e}`)}},p=e=>{var t,n;return null===(n=null===(t=g())||void 0===t?void 0:t.emulatorHosts)||void 0===n?void 0:n[e]};class m{constructor(){this.reject=()=>{},this.resolve=()=>{},this.promise=new Promise(((e,t)=>{this.resolve=e,this.reject=t}))}wrapCallback(e){return(t,n)=>{t?this.reject(t):this.resolve(n),"function"==typeof e&&(this.promise.catch((()=>{})),1===e.length?e(t):e(t,n))}}}function y(){return"undefined"!=typeof navigator&&"string"==typeof navigator.userAgent?navigator.userAgent:""}function v(){var e;const t=null===(e=g())||void 0===e?void 0:e.forceEnvironment;if("node"===t)return!0;if("browser"===t)return!1;try{return"[object process]"===Object.prototype.toString.call(n.g.process)}catch(e){return!1}}function w(){return"undefined"!=typeof WorkerGlobalScope&&"undefined"!=typeof self&&self instanceof WorkerGlobalScope}class b extends Error{constructor(e,t,n){super(t),this.code=e,this.customData=n,this.name="FirebaseError",Object.setPrototypeOf(this,b.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,_.prototype.create)}}class _{constructor(e,t,n){this.service=e,this.serviceName=t,this.errors=n}create(e,...t){const n=t[0]||{},r=`${this.service}/${e}`,i=this.errors[e],s=i?function(e,t){return e.replace(I,((e,n)=>{const r=t[n];return null!=r?String(r):`<${n}?>`}))}(i,n):"Error",o=`${this.serviceName}: ${s} (${r}).`;return new b(r,o,n)}}const I=/\{\$([^}]+)}/g;function E(e){return JSON.parse(e)}const T=function(e){let t={},n={},r={},i="";try{const s=e.split(".");t=E(h(s[0])||""),n=E(h(s[1])||""),i=s[2],r=n.d||{},delete n.d}catch(e){}return{header:t,claims:n,data:r,signature:i}};function S(e){return null!==e&&"object"==typeof e}class x{constructor(e,t){this.observers=[],this.unsubscribes=[],this.observerCount=0,this.task=Promise.resolve(),this.finalized=!1,this.onNoObservers=t,this.task.then((()=>{e(this)})).catch((e=>{this.error(e)}))}next(e){this.forEachObserver((t=>{t.next(e)}))}error(e){this.forEachObserver((t=>{t.error(e)})),this.close(e)}complete(){this.forEachObserver((e=>{e.complete()})),this.close()}subscribe(e,t,n){let r;if(void 0===e&&void 0===t&&void 0===n)throw new Error("Missing Observer.");r=function(e){if("object"!=typeof e||null===e)return!1;for(const t of["next","error","complete"])if(t in e&&"function"==typeof e[t])return!0;return!1}(e)?e:{next:e,error:t,complete:n},void 0===r.next&&(r.next=C),void 0===r.error&&(r.error=C),void 0===r.complete&&(r.complete=C);const i=this.unsubscribeOne.bind(this,this.observers.length);return this.finalized&&this.task.then((()=>{try{this.finalError?r.error(this.finalError):r.complete()}catch(e){}})),this.observers.push(r),i}unsubscribeOne(e){void 0!==this.observers&&void 0!==this.observers[e]&&(delete this.observers[e],this.observerCount-=1,0===this.observerCount&&void 0!==this.onNoObservers&&this.onNoObservers(this))}forEachObserver(e){if(!this.finalized)for(let t=0;t<this.observers.length;t++)this.sendOne(t,e)}sendOne(e,t){this.task.then((()=>{if(void 0!==this.observers&&void 0!==this.observers[e])try{t(this.observers[e])}catch(e){"undefined"!=typeof console&&console.error&&console.error(e)}}))}close(e){this.finalized||(this.finalized=!0,void 0!==e&&(this.finalError=e),this.task.then((()=>{this.observers=void 0,this.onNoObservers=void 0})))}}function C(){}function D(e,t){return`${e} failed: ${t} argument `}const A=144e5;t.CONSTANTS=r,t.DecodeBase64StringError=c,t.Deferred=m,t.ErrorFactory=_,t.FirebaseError=b,t.MAX_VALUE_MILLIS=A,t.RANDOM_FACTOR=.5,t.Sha1=class{constructor(){this.chain_=[],this.buf_=[],this.W_=[],this.pad_=[],this.inbuf_=0,this.total_=0,this.blockSize=64,this.pad_[0]=128;for(let e=1;e<this.blockSize;++e)this.pad_[e]=0;this.reset()}reset(){this.chain_[0]=1732584193,this.chain_[1]=4023233417,this.chain_[2]=2562383102,this.chain_[3]=271733878,this.chain_[4]=3285377520,this.inbuf_=0,this.total_=0}compress_(e,t){t||(t=0);const n=this.W_;if("string"==typeof e)for(let r=0;r<16;r++)n[r]=e.charCodeAt(t)<<24|e.charCodeAt(t+1)<<16|e.charCodeAt(t+2)<<8|e.charCodeAt(t+3),t+=4;else for(let r=0;r<16;r++)n[r]=e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3],t+=4;for(let e=16;e<80;e++){const t=n[e-3]^n[e-8]^n[e-14]^n[e-16];n[e]=4294967295&(t<<1|t>>>31)}let r,i,s=this.chain_[0],o=this.chain_[1],a=this.chain_[2],c=this.chain_[3],u=this.chain_[4];for(let e=0;e<80;e++){e<40?e<20?(r=c^o&(a^c),i=1518500249):(r=o^a^c,i=1859775393):e<60?(r=o&a|c&(o|a),i=2400959708):(r=o^a^c,i=3395469782);const t=(s<<5|s>>>27)+r+u+i+n[e]&4294967295;u=c,c=a,a=4294967295&(o<<30|o>>>2),o=s,s=t}this.chain_[0]=this.chain_[0]+s&4294967295,this.chain_[1]=this.chain_[1]+o&4294967295,this.chain_[2]=this.chain_[2]+a&4294967295,this.chain_[3]=this.chain_[3]+c&4294967295,this.chain_[4]=this.chain_[4]+u&4294967295}update(e,t){if(null==e)return;void 0===t&&(t=e.length);const n=t-this.blockSize;let r=0;const i=this.buf_;let s=this.inbuf_;for(;r<t;){if(0===s)for(;r<=n;)this.compress_(e,r),r+=this.blockSize;if("string"==typeof e){for(;r<t;)if(i[s]=e.charCodeAt(r),++s,++r,s===this.blockSize){this.compress_(i),s=0;break}}else for(;r<t;)if(i[s]=e[r],++s,++r,s===this.blockSize){this.compress_(i),s=0;break}}this.inbuf_=s,this.total_+=t}digest(){const e=[];let t=8*this.total_;this.inbuf_<56?this.update(this.pad_,56-this.inbuf_):this.update(this.pad_,this.blockSize-(this.inbuf_-56));for(let e=this.blockSize-1;e>=56;e--)this.buf_[e]=255&t,t/=256;this.compress_(this.buf_);let n=0;for(let t=0;t<5;t++)for(let r=24;r>=0;r-=8)e[n]=this.chain_[t]>>r&255,++n;return e}},t.areCookiesEnabled=function(){return!("undefined"==typeof navigator||!navigator.cookieEnabled)},t.assert=i,t.assertionError=s,t.async=function(e,t){return(...n)=>{Promise.resolve(!0).then((()=>{e(...n)})).catch((e=>{t&&t(e)}))}},t.base64=a,t.base64Decode=h,t.base64Encode=u,t.base64urlEncodeWithoutPadding=l,t.calculateBackoffMillis=function(e,t=1e3,n=2){const r=t*Math.pow(n,e),i=Math.round(.5*r*(Math.random()-.5)*2);return Math.min(A,r+i)},t.contains=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},t.createMockUserToken=function(e,t){if(e.uid)throw new Error('The "uid" field is no longer supported by mockUserToken. Please use "sub" instead for Firebase Auth User ID.');const n=t||"demo-project",r=e.iat||0,i=e.sub||e.user_id;if(!i)throw new Error("mockUserToken must contain 'sub' or 'user_id' field!");const s=Object.assign({iss:`https://securetoken.google.com/${n}`,aud:n,iat:r,exp:r+3600,auth_time:r,sub:i,user_id:i,firebase:{sign_in_provider:"custom",identities:{}}},e);return[l(JSON.stringify({alg:"none",type:"JWT"})),l(JSON.stringify(s)),""].join(".")},t.createSubscribe=function(e,t){const n=new x(e,t);return n.subscribe.bind(n)},t.decode=T,t.deepCopy=function(e){return d(void 0,e)},t.deepEqual=function e(t,n){if(t===n)return!0;const r=Object.keys(t),i=Object.keys(n);for(const s of r){if(!i.includes(s))return!1;const r=t[s],o=n[s];if(S(r)&&S(o)){if(!e(r,o))return!1}else if(r!==o)return!1}for(const e of i)if(!r.includes(e))return!1;return!0},t.deepExtend=d,t.errorPrefix=D,t.extractQuerystring=function(e){const t=e.indexOf("?");if(!t)return"";const n=e.indexOf("#",t);return e.substring(t,n>0?n:void 0)},t.getDefaultAppConfig=()=>{var e;return null===(e=g())||void 0===e?void 0:e.config},t.getDefaultEmulatorHost=p,t.getDefaultEmulatorHostnameAndPort=e=>{const t=p(e);if(!t)return;const n=t.lastIndexOf(":");if(n<=0||n+1===t.length)throw new Error(`Invalid host ${t} with no separate hostname and port!`);const r=parseInt(t.substring(n+1),10);return"["===t[0]?[t.substring(1,n-1),r]:[t.substring(0,n),r]},t.getDefaults=g,t.getExperimentalSetting=e=>{var t;return null===(t=g())||void 0===t?void 0:t[`_${e}`]},t.getGlobal=f,t.getModularInstance=function(e){return e&&e._delegate?e._delegate:e},t.getUA=y,t.isAdmin=function(e){const t=T(e).claims;return"object"==typeof t&&!0===t.admin},t.isBrowser=function(){return"undefined"!=typeof window||w()},t.isBrowserExtension=function(){const e="object"==typeof chrome?chrome.runtime:"object"==typeof browser?browser.runtime:void 0;return"object"==typeof e&&void 0!==e.id},t.isCloudflareWorker=function(){return"undefined"!=typeof navigator&&"Cloudflare-Workers"===navigator.userAgent},t.isElectron=function(){return y().indexOf("Electron/")>=0},t.isEmpty=function(e){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0},t.isIE=function(){const e=y();return e.indexOf("MSIE ")>=0||e.indexOf("Trident/")>=0},t.isIndexedDBAvailable=function(){try{return"object"==typeof indexedDB}catch(e){return!1}},t.isMobileCordova=function(){return"undefined"!=typeof window&&!!(window.cordova||window.phonegap||window.PhoneGap)&&/ios|iphone|ipod|ipad|android|blackberry|iemobile/i.test(y())},t.isNode=v,t.isNodeSdk=function(){return!0===r.NODE_CLIENT||!0===r.NODE_ADMIN},t.isReactNative=function(){return"object"==typeof navigator&&"ReactNative"===navigator.product},t.isSafari=function(){return!v()&&!!navigator.userAgent&&navigator.userAgent.includes("Safari")&&!navigator.userAgent.includes("Chrome")},t.isUWP=function(){return y().indexOf("MSAppHost/")>=0},t.isValidFormat=function(e){const t=T(e).claims;return!!t&&"object"==typeof t&&t.hasOwnProperty("iat")},t.isValidTimestamp=function(e){const t=T(e).claims,n=Math.floor((new Date).getTime()/1e3);let r=0,i=0;return"object"==typeof t&&(t.hasOwnProperty("nbf")?r=t.nbf:t.hasOwnProperty("iat")&&(r=t.iat),i=t.hasOwnProperty("exp")?t.exp:r+86400),!!n&&!!r&&!!i&&n>=r&&n<=i},t.isWebWorker=w,t.issuedAtTime=function(e){const t=T(e).claims;return"object"==typeof t&&t.hasOwnProperty("iat")?t.iat:null},t.jsonEval=E,t.map=function(e,t,n){const r={};for(const i in e)Object.prototype.hasOwnProperty.call(e,i)&&(r[i]=t.call(n,e[i],i,e));return r},t.ordinal=function(e){return Number.isFinite(e)?e+function(e){const t=(e=Math.abs(e))%100;if(t>=10&&t<=20)return"th";const n=e%10;return 1===n?"st":2===n?"nd":3===n?"rd":"th"}(e):`${e}`},t.promiseWithTimeout=function(e,t=2e3){const n=new m;return setTimeout((()=>n.reject("timeout!")),t),e.then(n.resolve,n.reject),n.promise},t.querystring=function(e){const t=[];for(const[n,r]of Object.entries(e))Array.isArray(r)?r.forEach((e=>{t.push(encodeURIComponent(n)+"="+encodeURIComponent(e))})):t.push(encodeURIComponent(n)+"="+encodeURIComponent(r));return t.length?"&"+t.join("&"):""},t.querystringDecode=function(e){const t={};return e.replace(/^\?/,"").split("&").forEach((e=>{if(e){const[n,r]=e.split("=");t[decodeURIComponent(n)]=decodeURIComponent(r)}})),t},t.safeGet=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0},t.stringLength=function(e){let t=0;for(let n=0;n<e.length;n++){const r=e.charCodeAt(n);r<128?t++:r<2048?t+=2:r>=55296&&r<=56319?(t+=4,n++):t+=3}return t},t.stringToByteArray=function(e){const t=[];let n=0;for(let r=0;r<e.length;r++){let s=e.charCodeAt(r);if(s>=55296&&s<=56319){const t=s-55296;r++,i(r<e.length,"Surrogate pair missing trail surrogate."),s=65536+(t<<10)+(e.charCodeAt(r)-56320)}s<128?t[n++]=s:s<2048?(t[n++]=s>>6|192,t[n++]=63&s|128):s<65536?(t[n++]=s>>12|224,t[n++]=s>>6&63|128,t[n++]=63&s|128):(t[n++]=s>>18|240,t[n++]=s>>12&63|128,t[n++]=s>>6&63|128,t[n++]=63&s|128)}return t},t.stringify=function(e){return JSON.stringify(e)},t.uuidv4=function(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)}))},t.validateArgCount=function(e,t,n,r){let i;if(r<t?i="at least "+t:r>n&&(i=0===n?"none":"no more than "+n),i)throw new Error(e+" failed: Was called with "+r+(1===r?" argument.":" arguments.")+" Expects "+i+".")},t.validateCallback=function(e,t,n,r){if((!r||n)&&"function"!=typeof n)throw new Error(D(e,t)+"must be a valid function.")},t.validateContextObject=function(e,t,n,r){if((!r||n)&&("object"!=typeof n||null===n))throw new Error(D(e,t)+"must be a valid context object.")},t.validateIndexedDBOpenable=function(){return new Promise(((e,t)=>{try{let n=!0;const r="validate-browser-context-for-indexeddb-analytics-module",i=self.indexedDB.open(r);i.onsuccess=()=>{i.result.close(),n||self.indexedDB.deleteDatabase(r),e(!0)},i.onupgradeneeded=()=>{n=!1},i.onerror=()=>{var e;t((null===(e=i.error)||void 0===e?void 0:e.message)||"")}}catch(e){t(e)}}))},t.validateNamespace=function(e,t,n){if((!n||t)&&"string"!=typeof t)throw new Error(D(e,"namespace")+"must be a valid firebase namespace.")}},860:(e,t,n)=>{(function(){"use strict";var t;function n(){this.blockSize=-1,this.blockSize=64,this.g=Array(4),this.B=Array(this.blockSize),this.o=this.h=0,this.s()}function r(e,t,n){n||(n=0);var r=Array(16);if("string"==typeof t)for(var i=0;16>i;++i)r[i]=t.charCodeAt(n++)|t.charCodeAt(n++)<<8|t.charCodeAt(n++)<<16|t.charCodeAt(n++)<<24;else for(i=0;16>i;++i)r[i]=t[n++]|t[n++]<<8|t[n++]<<16|t[n++]<<24;t=e.g[0],n=e.g[1],i=e.g[2];var s=e.g[3],o=t+(s^n&(i^s))+r[0]+3614090360&4294967295;o=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=n+(o<<7&4294967295|o>>>25))+((o=s+(i^t&(n^i))+r[1]+3905402710&4294967295)<<12&4294967295|o>>>20))+((o=i+(n^s&(t^n))+r[2]+606105819&4294967295)<<17&4294967295|o>>>15))+((o=n+(t^i&(s^t))+r[3]+3250441966&4294967295)<<22&4294967295|o>>>10))+((o=t+(s^n&(i^s))+r[4]+4118548399&4294967295)<<7&4294967295|o>>>25))+((o=s+(i^t&(n^i))+r[5]+1200080426&4294967295)<<12&4294967295|o>>>20))+((o=i+(n^s&(t^n))+r[6]+2821735955&4294967295)<<17&4294967295|o>>>15))+((o=n+(t^i&(s^t))+r[7]+4249261313&4294967295)<<22&4294967295|o>>>10))+((o=t+(s^n&(i^s))+r[8]+1770035416&4294967295)<<7&4294967295|o>>>25))+((o=s+(i^t&(n^i))+r[9]+2336552879&4294967295)<<12&4294967295|o>>>20))+((o=i+(n^s&(t^n))+r[10]+4294925233&4294967295)<<17&4294967295|o>>>15))+((o=n+(t^i&(s^t))+r[11]+2304563134&4294967295)<<22&4294967295|o>>>10))+((o=t+(s^n&(i^s))+r[12]+1804603682&4294967295)<<7&4294967295|o>>>25))+((o=s+(i^t&(n^i))+r[13]+4254626195&4294967295)<<12&4294967295|o>>>20))+((o=i+(n^s&(t^n))+r[14]+2792965006&4294967295)<<17&4294967295|o>>>15))+((o=n+(t^i&(s^t))+r[15]+1236535329&4294967295)<<22&4294967295|o>>>10))+((o=t+(i^s&(n^i))+r[1]+4129170786&4294967295)<<5&4294967295|o>>>27))+((o=s+(n^i&(t^n))+r[6]+3225465664&4294967295)<<9&4294967295|o>>>23))+((o=i+(t^n&(s^t))+r[11]+643717713&4294967295)<<14&4294967295|o>>>18))+((o=n+(s^t&(i^s))+r[0]+3921069994&4294967295)<<20&4294967295|o>>>12))+((o=t+(i^s&(n^i))+r[5]+3593408605&4294967295)<<5&4294967295|o>>>27))+((o=s+(n^i&(t^n))+r[10]+38016083&4294967295)<<9&4294967295|o>>>23))+((o=i+(t^n&(s^t))+r[15]+3634488961&4294967295)<<14&4294967295|o>>>18))+((o=n+(s^t&(i^s))+r[4]+3889429448&4294967295)<<20&4294967295|o>>>12))+((o=t+(i^s&(n^i))+r[9]+568446438&4294967295)<<5&4294967295|o>>>27))+((o=s+(n^i&(t^n))+r[14]+3275163606&4294967295)<<9&4294967295|o>>>23))+((o=i+(t^n&(s^t))+r[3]+4107603335&4294967295)<<14&4294967295|o>>>18))+((o=n+(s^t&(i^s))+r[8]+1163531501&4294967295)<<20&4294967295|o>>>12))+((o=t+(i^s&(n^i))+r[13]+2850285829&4294967295)<<5&4294967295|o>>>27))+((o=s+(n^i&(t^n))+r[2]+4243563512&4294967295)<<9&4294967295|o>>>23))+((o=i+(t^n&(s^t))+r[7]+1735328473&4294967295)<<14&4294967295|o>>>18))+((o=n+(s^t&(i^s))+r[12]+2368359562&4294967295)<<20&4294967295|o>>>12))+((o=t+(n^i^s)+r[5]+4294588738&4294967295)<<4&4294967295|o>>>28))+((o=s+(t^n^i)+r[8]+2272392833&4294967295)<<11&4294967295|o>>>21))+((o=i+(s^t^n)+r[11]+1839030562&4294967295)<<16&4294967295|o>>>16))+((o=n+(i^s^t)+r[14]+4259657740&4294967295)<<23&4294967295|o>>>9))+((o=t+(n^i^s)+r[1]+2763975236&4294967295)<<4&4294967295|o>>>28))+((o=s+(t^n^i)+r[4]+1272893353&4294967295)<<11&4294967295|o>>>21))+((o=i+(s^t^n)+r[7]+4139469664&4294967295)<<16&4294967295|o>>>16))+((o=n+(i^s^t)+r[10]+3200236656&4294967295)<<23&4294967295|o>>>9))+((o=t+(n^i^s)+r[13]+681279174&4294967295)<<4&4294967295|o>>>28))+((o=s+(t^n^i)+r[0]+3936430074&4294967295)<<11&4294967295|o>>>21))+((o=i+(s^t^n)+r[3]+3572445317&4294967295)<<16&4294967295|o>>>16))+((o=n+(i^s^t)+r[6]+76029189&4294967295)<<23&4294967295|o>>>9))+((o=t+(n^i^s)+r[9]+3654602809&4294967295)<<4&4294967295|o>>>28))+((o=s+(t^n^i)+r[12]+3873151461&4294967295)<<11&4294967295|o>>>21))+((o=i+(s^t^n)+r[15]+530742520&4294967295)<<16&4294967295|o>>>16))+((o=n+(i^s^t)+r[2]+3299628645&4294967295)<<23&4294967295|o>>>9))+((o=t+(i^(n|~s))+r[0]+4096336452&4294967295)<<6&4294967295|o>>>26))+((o=s+(n^(t|~i))+r[7]+1126891415&4294967295)<<10&4294967295|o>>>22))+((o=i+(t^(s|~n))+r[14]+2878612391&4294967295)<<15&4294967295|o>>>17))+((o=n+(s^(i|~t))+r[5]+4237533241&4294967295)<<21&4294967295|o>>>11))+((o=t+(i^(n|~s))+r[12]+1700485571&4294967295)<<6&4294967295|o>>>26))+((o=s+(n^(t|~i))+r[3]+2399980690&4294967295)<<10&4294967295|o>>>22))+((o=i+(t^(s|~n))+r[10]+4293915773&4294967295)<<15&4294967295|o>>>17))+((o=n+(s^(i|~t))+r[1]+2240044497&4294967295)<<21&4294967295|o>>>11))+((o=t+(i^(n|~s))+r[8]+1873313359&4294967295)<<6&4294967295|o>>>26))+((o=s+(n^(t|~i))+r[15]+4264355552&4294967295)<<10&4294967295|o>>>22))+((o=i+(t^(s|~n))+r[6]+2734768916&4294967295)<<15&4294967295|o>>>17))+((o=n+(s^(i|~t))+r[13]+1309151649&4294967295)<<21&4294967295|o>>>11))+((s=(t=n+((o=t+(i^(n|~s))+r[4]+4149444226&4294967295)<<6&4294967295|o>>>26))+((o=s+(n^(t|~i))+r[11]+3174756917&4294967295)<<10&4294967295|o>>>22))^((i=s+((o=i+(t^(s|~n))+r[2]+718787259&4294967295)<<15&4294967295|o>>>17))|~t))+r[9]+3951481745&4294967295,e.g[0]=e.g[0]+t&4294967295,e.g[1]=e.g[1]+(i+(o<<21&4294967295|o>>>11))&4294967295,e.g[2]=e.g[2]+i&4294967295,e.g[3]=e.g[3]+s&4294967295}function i(e,t){this.h=t;for(var n=[],r=!0,i=e.length-1;0<=i;i--){var s=0|e[i];r&&s==t||(n[i]=s,r=!1)}this.g=n}!function(e,t){function n(){}n.prototype=t.prototype,e.D=t.prototype,e.prototype=new n,e.prototype.constructor=e,e.C=function(e,n,r){for(var i=Array(arguments.length-2),s=2;s<arguments.length;s++)i[s-2]=arguments[s];return t.prototype[n].apply(e,i)}}(n,(function(){this.blockSize=-1})),n.prototype.s=function(){this.g[0]=1732584193,this.g[1]=4023233417,this.g[2]=2562383102,this.g[3]=271733878,this.o=this.h=0},n.prototype.u=function(e,t){void 0===t&&(t=e.length);for(var n=t-this.blockSize,i=this.B,s=this.h,o=0;o<t;){if(0==s)for(;o<=n;)r(this,e,o),o+=this.blockSize;if("string"==typeof e){for(;o<t;)if(i[s++]=e.charCodeAt(o++),s==this.blockSize){r(this,i),s=0;break}}else for(;o<t;)if(i[s++]=e[o++],s==this.blockSize){r(this,i),s=0;break}}this.h=s,this.o+=t},n.prototype.v=function(){var e=Array((56>this.h?this.blockSize:2*this.blockSize)-this.h);e[0]=128;for(var t=1;t<e.length-8;++t)e[t]=0;var n=8*this.o;for(t=e.length-8;t<e.length;++t)e[t]=255&n,n/=256;for(this.u(e),e=Array(16),t=n=0;4>t;++t)for(var r=0;32>r;r+=8)e[n++]=this.g[t]>>>r&255;return e};var s={};function o(e){return-128<=e&&128>e?function(e){var t=s;return Object.prototype.hasOwnProperty.call(t,e)?t[e]:t[e]=function(e){return new i([0|e],0>e?-1:0)}(e)}(e):new i([0|e],0>e?-1:0)}function a(e){if(isNaN(e)||!isFinite(e))return c;if(0>e)return f(a(-e));for(var t=[],n=1,r=0;e>=n;r++)t[r]=e/n|0,n*=4294967296;return new i(t,0)}var c=o(0),u=o(1),l=o(16777216);function h(e){if(0!=e.h)return!1;for(var t=0;t<e.g.length;t++)if(0!=e.g[t])return!1;return!0}function d(e){return-1==e.h}function f(e){for(var t=e.g.length,n=[],r=0;r<t;r++)n[r]=~e.g[r];return new i(n,~e.h).add(u)}function g(e,t){return e.add(f(t))}function p(e,t){for(;(65535&e[t])!=e[t];)e[t+1]+=e[t]>>>16,e[t]&=65535,t++}function m(e,t){this.g=e,this.h=t}function y(e,t){if(h(t))throw Error("division by zero");if(h(e))return new m(c,c);if(d(e))return t=y(f(e),t),new m(f(t.g),f(t.h));if(d(t))return t=y(e,f(t)),new m(f(t.g),t.h);if(30<e.g.length){if(d(e)||d(t))throw Error("slowDivide_ only works with positive integers.");for(var n=u,r=t;0>=r.l(e);)n=v(n),r=v(r);var i=w(n,1),s=w(r,1);for(r=w(r,2),n=w(n,2);!h(r);){var o=s.add(r);0>=o.l(e)&&(i=i.add(n),s=o),r=w(r,1),n=w(n,1)}return t=g(e,i.j(t)),new m(i,t)}for(i=c;0<=e.l(t);){for(n=Math.max(1,Math.floor(e.m()/t.m())),r=48>=(r=Math.ceil(Math.log(n)/Math.LN2))?1:Math.pow(2,r-48),o=(s=a(n)).j(t);d(o)||0<o.l(e);)o=(s=a(n-=r)).j(t);h(s)&&(s=u),i=i.add(s),e=g(e,o)}return new m(i,e)}function v(e){for(var t=e.g.length+1,n=[],r=0;r<t;r++)n[r]=e.i(r)<<1|e.i(r-1)>>>31;return new i(n,e.h)}function w(e,t){var n=t>>5;t%=32;for(var r=e.g.length-n,s=[],o=0;o<r;o++)s[o]=0<t?e.i(o+n)>>>t|e.i(o+n+1)<<32-t:e.i(o+n);return new i(s,e.h)}(t=i.prototype).m=function(){if(d(this))return-f(this).m();for(var e=0,t=1,n=0;n<this.g.length;n++){var r=this.i(n);e+=(0<=r?r:4294967296+r)*t,t*=4294967296}return e},t.toString=function(e){if(2>(e=e||10)||36<e)throw Error("radix out of range: "+e);if(h(this))return"0";if(d(this))return"-"+f(this).toString(e);for(var t=a(Math.pow(e,6)),n=this,r="";;){var i=y(n,t).g,s=((0<(n=g(n,i.j(t))).g.length?n.g[0]:n.h)>>>0).toString(e);if(h(n=i))return s+r;for(;6>s.length;)s="0"+s;r=s+r}},t.i=function(e){return 0>e?0:e<this.g.length?this.g[e]:this.h},t.l=function(e){return d(e=g(this,e))?-1:h(e)?0:1},t.abs=function(){return d(this)?f(this):this},t.add=function(e){for(var t=Math.max(this.g.length,e.g.length),n=[],r=0,s=0;s<=t;s++){var o=r+(65535&this.i(s))+(65535&e.i(s)),a=(o>>>16)+(this.i(s)>>>16)+(e.i(s)>>>16);r=a>>>16,o&=65535,a&=65535,n[s]=a<<16|o}return new i(n,-2147483648&n[n.length-1]?-1:0)},t.j=function(e){if(h(this)||h(e))return c;if(d(this))return d(e)?f(this).j(f(e)):f(f(this).j(e));if(d(e))return f(this.j(f(e)));if(0>this.l(l)&&0>e.l(l))return a(this.m()*e.m());for(var t=this.g.length+e.g.length,n=[],r=0;r<2*t;r++)n[r]=0;for(r=0;r<this.g.length;r++)for(var s=0;s<e.g.length;s++){var o=this.i(r)>>>16,u=65535&this.i(r),g=e.i(s)>>>16,m=65535&e.i(s);n[2*r+2*s]+=u*m,p(n,2*r+2*s),n[2*r+2*s+1]+=o*m,p(n,2*r+2*s+1),n[2*r+2*s+1]+=u*g,p(n,2*r+2*s+1),n[2*r+2*s+2]+=o*g,p(n,2*r+2*s+2)}for(r=0;r<t;r++)n[r]=n[2*r+1]<<16|n[2*r];for(r=t;r<2*t;r++)n[r]=0;return new i(n,0)},t.A=function(e){return y(this,e).h},t.and=function(e){for(var t=Math.max(this.g.length,e.g.length),n=[],r=0;r<t;r++)n[r]=this.i(r)&e.i(r);return new i(n,this.h&e.h)},t.or=function(e){for(var t=Math.max(this.g.length,e.g.length),n=[],r=0;r<t;r++)n[r]=this.i(r)|e.i(r);return new i(n,this.h|e.h)},t.xor=function(e){for(var t=Math.max(this.g.length,e.g.length),n=[],r=0;r<t;r++)n[r]=this.i(r)^e.i(r);return new i(n,this.h^e.h)},n.prototype.digest=n.prototype.v,n.prototype.reset=n.prototype.s,n.prototype.update=n.prototype.u,e.exports.Md5=n,i.prototype.add=i.prototype.add,i.prototype.multiply=i.prototype.j,i.prototype.modulo=i.prototype.A,i.prototype.compare=i.prototype.l,i.prototype.toNumber=i.prototype.m,i.prototype.toString=i.prototype.toString,i.prototype.getBits=i.prototype.i,i.fromNumber=a,i.fromString=function e(t,n){if(0==t.length)throw Error("number format error: empty string");if(2>(n=n||10)||36<n)throw Error("radix out of range: "+n);if("-"==t.charAt(0))return f(e(t.substring(1),n));if(0<=t.indexOf("-"))throw Error('number format error: interior "-" character');for(var r=a(Math.pow(n,8)),i=c,s=0;s<t.length;s+=8){var o=Math.min(8,t.length-s),u=parseInt(t.substring(s,s+o),n);8>o?(o=a(Math.pow(n,o)),i=i.j(o).add(a(u))):i=(i=i.j(r)).add(a(u))}return i},e.exports.Integer=i}).apply(void 0!==n.g?n.g:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},832:(e,t,n)=>{(function(){"use strict";var t,r="function"==typeof Object.defineProperties?Object.defineProperty:function(e,t,n){return e==Array.prototype||e==Object.prototype||(e[t]=n.value),e},i=function(e){e=["object"==typeof globalThis&&globalThis,e,"object"==typeof window&&window,"object"==typeof self&&self,"object"==typeof n.g&&n.g];for(var t=0;t<e.length;++t){var r=e[t];if(r&&r.Math==Math)return r}throw Error("Cannot find global object")}(this);!function(e,t){if(t)e:{var n=i;e=e.split(".");for(var s=0;s<e.length-1;s++){var o=e[s];if(!(o in n))break e;n=n[o]}(t=t(s=n[e=e[e.length-1]]))!=s&&null!=t&&r(n,e,{configurable:!0,writable:!0,value:t})}}("Array.prototype.values",(function(e){return e||function(){return function(e,t){e instanceof String&&(e+="");var n=0,r=!1,i={next:function(){if(!r&&n<e.length){var i=n++;return{value:t(0,e[i]),done:!1}}return r=!0,{done:!0,value:void 0}}};return i[Symbol.iterator]=function(){return i},i}(this,(function(e,t){return t}))}}));var s=s||{},o=this||self;function a(e){var t=typeof e;return"array"==(t="object"!=t?t:e?Array.isArray(e)?"array":t:"null")||"object"==t&&"number"==typeof e.length}function c(e){var t=typeof e;return"object"==t&&null!=e||"function"==t}function u(e,t,n){return e.call.apply(e.bind,arguments)}function l(e,t,n){if(!e)throw Error();if(2<arguments.length){var r=Array.prototype.slice.call(arguments,2);return function(){var n=Array.prototype.slice.call(arguments);return Array.prototype.unshift.apply(n,r),e.apply(t,n)}}return function(){return e.apply(t,arguments)}}function h(e,t,n){return(h=Function.prototype.bind&&-1!=Function.prototype.bind.toString().indexOf("native code")?u:l).apply(null,arguments)}function d(e,t){var n=Array.prototype.slice.call(arguments,1);return function(){var t=n.slice();return t.push.apply(t,arguments),e.apply(this,t)}}function f(e,t){function n(){}n.prototype=t.prototype,e.aa=t.prototype,e.prototype=new n,e.prototype.constructor=e,e.Qb=function(e,n,r){for(var i=Array(arguments.length-2),s=2;s<arguments.length;s++)i[s-2]=arguments[s];return t.prototype[n].apply(e,i)}}function g(e){const t=e.length;if(0<t){const n=Array(t);for(let r=0;r<t;r++)n[r]=e[r];return n}return[]}function p(e,t){for(let t=1;t<arguments.length;t++){const n=arguments[t];if(a(n)){const t=e.length||0,r=n.length||0;e.length=t+r;for(let i=0;i<r;i++)e[t+i]=n[i]}else e.push(n)}}function m(e){return/^[\s\xa0]*$/.test(e)}function y(){var e=o.navigator;return e&&(e=e.userAgent)?e:""}function v(e){return v[" "](e),e}v[" "]=function(){};var w=!(-1==y().indexOf("Gecko")||-1!=y().toLowerCase().indexOf("webkit")&&-1==y().indexOf("Edge")||-1!=y().indexOf("Trident")||-1!=y().indexOf("MSIE")||-1!=y().indexOf("Edge"));function b(e,t,n){for(const r in e)t.call(n,e[r],r,e)}function _(e){const t={};for(const n in e)t[n]=e[n];return t}const I="constructor hasOwnProperty isPrototypeOf propertyIsEnumerable toLocaleString toString valueOf".split(" ");function E(e,t){let n,r;for(let t=1;t<arguments.length;t++){for(n in r=arguments[t],r)e[n]=r[n];for(let t=0;t<I.length;t++)n=I[t],Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}}function T(e){var t=1;e=e.split(":");const n=[];for(;0<t&&e.length;)n.push(e.shift()),t--;return e.length&&n.push(e.join(":")),n}function S(e){o.setTimeout((()=>{throw e}),0)}function x(){var e=N;let t=null;return e.g&&(t=e.g,e.g=e.g.next,e.g||(e.h=null),t.next=null),t}var C=new class{constructor(e,t){this.i=e,this.j=t,this.h=0,this.g=null}get(){let e;return 0<this.h?(this.h--,e=this.g,this.g=e.next,e.next=null):e=this.i(),e}}((()=>new D),(e=>e.reset()));class D{constructor(){this.next=this.g=this.h=null}set(e,t){this.h=e,this.g=t,this.next=null}reset(){this.next=this.g=this.h=null}}let A,k=!1,N=new class{constructor(){this.h=this.g=null}add(e,t){const n=C.get();n.set(e,t),this.h?this.h.next=n:this.g=n,this.h=n}},L=()=>{const e=o.Promise.resolve(void 0);A=()=>{e.then(O)}};var O=()=>{for(var e;e=x();){try{e.h.call(e.g)}catch(e){S(e)}var t=C;t.j(e),100>t.h&&(t.h++,e.next=t.g,t.g=e)}k=!1};function M(){this.s=this.s,this.C=this.C}function R(e,t){this.type=e,this.g=this.target=t,this.defaultPrevented=!1}M.prototype.s=!1,M.prototype.ma=function(){this.s||(this.s=!0,this.N())},M.prototype.N=function(){if(this.C)for(;this.C.length;)this.C.shift()()},R.prototype.h=function(){this.defaultPrevented=!0};var P=function(){if(!o.addEventListener||!Object.defineProperty)return!1;var e=!1,t=Object.defineProperty({},"passive",{get:function(){e=!0}});try{const e=()=>{};o.addEventListener("test",e,t),o.removeEventListener("test",e,t)}catch(e){}return e}();function F(e,t){if(R.call(this,e?e.type:""),this.relatedTarget=this.g=this.target=null,this.button=this.screenY=this.screenX=this.clientY=this.clientX=0,this.key="",this.metaKey=this.shiftKey=this.altKey=this.ctrlKey=!1,this.state=null,this.pointerId=0,this.pointerType="",this.i=null,e){var n=this.type=e.type,r=e.changedTouches&&e.changedTouches.length?e.changedTouches[0]:null;if(this.target=e.target||e.srcElement,this.g=t,t=e.relatedTarget){if(w){e:{try{v(t.nodeName);var i=!0;break e}catch(e){}i=!1}i||(t=null)}}else"mouseover"==n?t=e.fromElement:"mouseout"==n&&(t=e.toElement);this.relatedTarget=t,r?(this.clientX=void 0!==r.clientX?r.clientX:r.pageX,this.clientY=void 0!==r.clientY?r.clientY:r.pageY,this.screenX=r.screenX||0,this.screenY=r.screenY||0):(this.clientX=void 0!==e.clientX?e.clientX:e.pageX,this.clientY=void 0!==e.clientY?e.clientY:e.pageY,this.screenX=e.screenX||0,this.screenY=e.screenY||0),this.button=e.button,this.key=e.key||"",this.ctrlKey=e.ctrlKey,this.altKey=e.altKey,this.shiftKey=e.shiftKey,this.metaKey=e.metaKey,this.pointerId=e.pointerId||0,this.pointerType="string"==typeof e.pointerType?e.pointerType:V[e.pointerType]||"",this.state=e.state,this.i=e,e.defaultPrevented&&F.aa.h.call(this)}}f(F,R);var V={2:"touch",3:"pen",4:"mouse"};F.prototype.h=function(){F.aa.h.call(this);var e=this.i;e.preventDefault?e.preventDefault():e.returnValue=!1};var q="closure_listenable_"+(1e6*Math.random()|0),B=0;function U(e,t,n,r,i){this.listener=e,this.proxy=null,this.src=t,this.type=n,this.capture=!!r,this.ha=i,this.key=++B,this.da=this.fa=!1}function j(e){e.da=!0,e.listener=null,e.proxy=null,e.src=null,e.ha=null}function $(e){this.src=e,this.g={},this.h=0}function z(e,t){var n=t.type;if(n in e.g){var r,i=e.g[n],s=Array.prototype.indexOf.call(i,t,void 0);(r=0<=s)&&Array.prototype.splice.call(i,s,1),r&&(j(t),0==e.g[n].length&&(delete e.g[n],e.h--))}}function G(e,t,n,r){for(var i=0;i<e.length;++i){var s=e[i];if(!s.da&&s.listener==t&&s.capture==!!n&&s.ha==r)return i}return-1}$.prototype.add=function(e,t,n,r,i){var s=e.toString();(e=this.g[s])||(e=this.g[s]=[],this.h++);var o=G(e,t,r,i);return-1<o?(t=e[o],n||(t.fa=!1)):((t=new U(t,this.src,s,!!r,i)).fa=n,e.push(t)),t};var K="closure_lm_"+(1e6*Math.random()|0),Q={};function H(e,t,n,r,i){if(r&&r.once)return J(e,t,n,r,i);if(Array.isArray(t)){for(var s=0;s<t.length;s++)H(e,t[s],n,r,i);return null}return n=re(n),e&&e[q]?e.K(t,n,c(r)?!!r.capture:!!r,i):W(e,t,n,!1,r,i)}function W(e,t,n,r,i,s){if(!t)throw Error("Invalid event type");var o=c(i)?!!i.capture:!!i,a=te(e);if(a||(e[K]=a=new $(e)),(n=a.add(t,n,r,o,s)).proxy)return n;if(r=function(){const e=ee;return function t(n){return e.call(t.src,t.listener,n)}}(),n.proxy=r,r.src=e,r.listener=n,e.addEventListener)P||(i=o),void 0===i&&(i=!1),e.addEventListener(t.toString(),r,i);else if(e.attachEvent)e.attachEvent(Z(t.toString()),r);else{if(!e.addListener||!e.removeListener)throw Error("addEventListener and attachEvent are unavailable.");e.addListener(r)}return n}function J(e,t,n,r,i){if(Array.isArray(t)){for(var s=0;s<t.length;s++)J(e,t[s],n,r,i);return null}return n=re(n),e&&e[q]?e.L(t,n,c(r)?!!r.capture:!!r,i):W(e,t,n,!0,r,i)}function X(e,t,n,r,i){if(Array.isArray(t))for(var s=0;s<t.length;s++)X(e,t[s],n,r,i);else r=c(r)?!!r.capture:!!r,n=re(n),e&&e[q]?(e=e.i,(t=String(t).toString())in e.g&&-1<(n=G(s=e.g[t],n,r,i))&&(j(s[n]),Array.prototype.splice.call(s,n,1),0==s.length&&(delete e.g[t],e.h--))):e&&(e=te(e))&&(t=e.g[t.toString()],e=-1,t&&(e=G(t,n,r,i)),(n=-1<e?t[e]:null)&&Y(n))}function Y(e){if("number"!=typeof e&&e&&!e.da){var t=e.src;if(t&&t[q])z(t.i,e);else{var n=e.type,r=e.proxy;t.removeEventListener?t.removeEventListener(n,r,e.capture):t.detachEvent?t.detachEvent(Z(n),r):t.addListener&&t.removeListener&&t.removeListener(r),(n=te(t))?(z(n,e),0==n.h&&(n.src=null,t[K]=null)):j(e)}}}function Z(e){return e in Q?Q[e]:Q[e]="on"+e}function ee(e,t){if(e.da)e=!0;else{t=new F(t,this);var n=e.listener,r=e.ha||e.src;e.fa&&Y(e),e=n.call(r,t)}return e}function te(e){return(e=e[K])instanceof $?e:null}var ne="__closure_events_fn_"+(1e9*Math.random()>>>0);function re(e){return"function"==typeof e?e:(e[ne]||(e[ne]=function(t){return e.handleEvent(t)}),e[ne])}function ie(){M.call(this),this.i=new $(this),this.M=this,this.F=null}function se(e,t){var n,r=e.F;if(r)for(n=[];r;r=r.F)n.push(r);if(e=e.M,r=t.type||t,"string"==typeof t)t=new R(t,e);else if(t instanceof R)t.target=t.target||e;else{var i=t;E(t=new R(r,e),i)}if(i=!0,n)for(var s=n.length-1;0<=s;s--){var o=t.g=n[s];i=oe(o,r,!0,t)&&i}if(i=oe(o=t.g=e,r,!0,t)&&i,i=oe(o,r,!1,t)&&i,n)for(s=0;s<n.length;s++)i=oe(o=t.g=n[s],r,!1,t)&&i}function oe(e,t,n,r){if(!(t=e.i.g[String(t)]))return!0;t=t.concat();for(var i=!0,s=0;s<t.length;++s){var o=t[s];if(o&&!o.da&&o.capture==n){var a=o.listener,c=o.ha||o.src;o.fa&&z(e.i,o),i=!1!==a.call(c,r)&&i}}return i&&!r.defaultPrevented}function ae(e,t,n){if("function"==typeof e)n&&(e=h(e,n));else{if(!e||"function"!=typeof e.handleEvent)throw Error("Invalid listener argument");e=h(e.handleEvent,e)}return 2147483647<Number(t)?-1:o.setTimeout(e,t||0)}function ce(e){e.g=ae((()=>{e.g=null,e.i&&(e.i=!1,ce(e))}),e.l);const t=e.h;e.h=null,e.m.apply(null,t)}f(ie,M),ie.prototype[q]=!0,ie.prototype.removeEventListener=function(e,t,n,r){X(this,e,t,n,r)},ie.prototype.N=function(){if(ie.aa.N.call(this),this.i){var e,t=this.i;for(e in t.g){for(var n=t.g[e],r=0;r<n.length;r++)j(n[r]);delete t.g[e],t.h--}}this.F=null},ie.prototype.K=function(e,t,n,r){return this.i.add(String(e),t,!1,n,r)},ie.prototype.L=function(e,t,n,r){return this.i.add(String(e),t,!0,n,r)};class ue extends M{constructor(e,t){super(),this.m=e,this.l=t,this.h=null,this.i=!1,this.g=null}j(e){this.h=arguments,this.g?this.i=!0:ce(this)}N(){super.N(),this.g&&(o.clearTimeout(this.g),this.g=null,this.i=!1,this.h=null)}}function le(e){M.call(this),this.h=e,this.g={}}f(le,M);var he=[];function de(e){b(e.g,(function(e,t){this.g.hasOwnProperty(t)&&Y(e)}),e),e.g={}}le.prototype.N=function(){le.aa.N.call(this),de(this)},le.prototype.handleEvent=function(){throw Error("EventHandler.handleEvent not implemented")};var fe=o.JSON.stringify,ge=o.JSON.parse,pe=class{stringify(e){return o.JSON.stringify(e,void 0)}parse(e){return o.JSON.parse(e,void 0)}};function me(){}function ye(e){return e.h||(e.h=e.i())}function ve(){}me.prototype.h=null;var we={OPEN:"a",kb:"b",Ja:"c",wb:"d"};function be(){R.call(this,"d")}function _e(){R.call(this,"c")}f(be,R),f(_e,R);var Ie={},Ee=null;function Te(){return Ee=Ee||new ie}function Se(e){R.call(this,Ie.La,e)}function xe(e){const t=Te();se(t,new Se(t,e))}function Ce(e,t){R.call(this,Ie.STAT_EVENT,e),this.stat=t}function De(e){const t=Te();se(t,new Ce(t,e))}function Ae(e,t){R.call(this,Ie.Ma,e),this.size=t}function ke(e,t){if("function"!=typeof e)throw Error("Fn must not be null and must be a function");return o.setTimeout((function(){e()}),t)}function Ne(){this.g=!0}function Le(e,t,n,r){e.info((function(){return"XMLHTTP TEXT ("+t+"): "+function(e,t){if(!e.g)return t;if(!t)return null;try{var n=JSON.parse(t);if(n)for(e=0;e<n.length;e++)if(Array.isArray(n[e])){var r=n[e];if(!(2>r.length)){var i=r[1];if(Array.isArray(i)&&!(1>i.length)){var s=i[0];if("noop"!=s&&"stop"!=s&&"close"!=s)for(var o=1;o<i.length;o++)i[o]=""}}}return fe(n)}catch(e){return t}}(e,n)+(r?" "+r:"")}))}Ie.La="serverreachability",f(Se,R),Ie.STAT_EVENT="statevent",f(Ce,R),Ie.Ma="timingevent",f(Ae,R),Ne.prototype.xa=function(){this.g=!1},Ne.prototype.info=function(){};var Oe,Me={NO_ERROR:0,gb:1,tb:2,sb:3,nb:4,rb:5,ub:6,Ia:7,TIMEOUT:8,xb:9},Re={lb:"complete",Hb:"success",Ja:"error",Ia:"abort",zb:"ready",Ab:"readystatechange",TIMEOUT:"timeout",vb:"incrementaldata",yb:"progress",ob:"downloadprogress",Pb:"uploadprogress"};function Pe(){}function Fe(e,t,n,r){this.j=e,this.i=t,this.l=n,this.R=r||1,this.U=new le(this),this.I=45e3,this.H=null,this.o=!1,this.m=this.A=this.v=this.L=this.F=this.S=this.B=null,this.D=[],this.g=null,this.C=0,this.s=this.u=null,this.X=-1,this.J=!1,this.O=0,this.M=null,this.W=this.K=this.T=this.P=!1,this.h=new Ve}function Ve(){this.i=null,this.g="",this.h=!1}f(Pe,me),Pe.prototype.g=function(){return new XMLHttpRequest},Pe.prototype.i=function(){return{}},Oe=new Pe;var qe={},Be={};function Ue(e,t,n){e.L=1,e.v=ft(ct(t)),e.m=n,e.P=!0,je(e,null)}function je(e,t){e.F=Date.now(),Ge(e),e.A=ct(e.v);var n=e.A,r=e.R;Array.isArray(r)||(r=[String(r)]),Ct(n.i,"t",r),e.C=0,n=e.j.J,e.h=new Ve,e.g=pn(e.j,n?t:null,!e.m),0<e.O&&(e.M=new ue(h(e.Y,e,e.g),e.O)),t=e.U,n=e.g,r=e.ca;var i="readystatechange";Array.isArray(i)||(i&&(he[0]=i.toString()),i=he);for(var s=0;s<i.length;s++){var o=H(n,i[s],r||t.handleEvent,!1,t.h||t);if(!o)break;t.g[o.key]=o}t=e.H?_(e.H):{},e.m?(e.u||(e.u="POST"),t["Content-Type"]="application/x-www-form-urlencoded",e.g.ea(e.A,e.u,e.m,t)):(e.u="GET",e.g.ea(e.A,e.u,null,t)),xe(1),function(e,t,n,r,i,s){e.info((function(){if(e.g)if(s)for(var o="",a=s.split("&"),c=0;c<a.length;c++){var u=a[c].split("=");if(1<u.length){var l=u[0];u=u[1];var h=l.split("_");o=2<=h.length&&"type"==h[1]?o+(l+"=")+u+"&":o+(l+"=redacted&")}}else o=null;else o=s;return"XMLHTTP REQ ("+r+") [attempt "+i+"]: "+t+"\n"+n+"\n"+o}))}(e.i,e.u,e.A,e.l,e.R,e.m)}function $e(e){return!!e.g&&"GET"==e.u&&2!=e.L&&e.j.Ca}function ze(e,t){var n=e.C,r=t.indexOf("\n",n);return-1==r?Be:(n=Number(t.substring(n,r)),isNaN(n)?qe:(r+=1)+n>t.length?Be:(t=t.slice(r,r+n),e.C=r+n,t))}function Ge(e){e.S=Date.now()+e.I,Ke(e,e.I)}function Ke(e,t){if(null!=e.B)throw Error("WatchDog timer not null");e.B=ke(h(e.ba,e),t)}function Qe(e){e.B&&(o.clearTimeout(e.B),e.B=null)}function He(e){0==e.j.G||e.J||ln(e.j,e)}function We(e){Qe(e);var t=e.M;t&&"function"==typeof t.ma&&t.ma(),e.M=null,de(e.U),e.g&&(t=e.g,e.g=null,t.abort(),t.ma())}function Je(e,t){try{var n=e.j;if(0!=n.G&&(n.g==e||tt(n.h,e)))if(!e.K&&tt(n.h,e)&&3==n.G){try{var r=n.Da.g.parse(t)}catch(e){r=null}if(Array.isArray(r)&&3==r.length){var i=r;if(0==i[0]){e:if(!n.u){if(n.g){if(!(n.g.F+3e3<e.F))break e;un(n),Yt(n)}on(n),De(18)}}else n.za=i[1],0<n.za-n.T&&37500>i[2]&&n.F&&0==n.v&&!n.C&&(n.C=ke(h(n.Za,n),6e3));if(1>=et(n.h)&&n.ca){try{n.ca()}catch(e){}n.ca=void 0}}else dn(n,11)}else if((e.K||n.g==e)&&un(n),!m(t))for(i=n.Da.g.parse(t),t=0;t<i.length;t++){let u=i[t];if(n.T=u[0],u=u[1],2==n.G)if("c"==u[0]){n.K=u[1],n.ia=u[2];const t=u[3];null!=t&&(n.la=t,n.j.info("VER="+n.la));const i=u[4];null!=i&&(n.Aa=i,n.j.info("SVER="+n.Aa));const l=u[5];null!=l&&"number"==typeof l&&0<l&&(r=1.5*l,n.L=r,n.j.info("backChannelRequestTimeoutMs_="+r)),r=n;const h=e.g;if(h){const e=h.g?h.g.getResponseHeader("X-Client-Wire-Protocol"):null;if(e){var s=r.h;s.g||-1==e.indexOf("spdy")&&-1==e.indexOf("quic")&&-1==e.indexOf("h2")||(s.j=s.l,s.g=new Set,s.h&&(nt(s,s.h),s.h=null))}if(r.D){const e=h.g?h.g.getResponseHeader("X-HTTP-Session-Id"):null;e&&(r.ya=e,dt(r.I,r.D,e))}}n.G=3,n.l&&n.l.ua(),n.ba&&(n.R=Date.now()-e.F,n.j.info("Handshake RTT: "+n.R+"ms"));var o=e;if((r=n).qa=gn(r,r.J?r.ia:null,r.W),o.K){rt(r.h,o);var a=o,c=r.L;c&&(a.I=c),a.B&&(Qe(a),Ge(a)),r.g=o}else sn(r);0<n.i.length&&en(n)}else"stop"!=u[0]&&"close"!=u[0]||dn(n,7);else 3==n.G&&("stop"==u[0]||"close"==u[0]?"stop"==u[0]?dn(n,7):Xt(n):"noop"!=u[0]&&n.l&&n.l.ta(u),n.v=0)}xe(4)}catch(e){}}Fe.prototype.ca=function(e){e=e.target;const t=this.M;t&&3==Qt(e)?t.j():this.Y(e)},Fe.prototype.Y=function(e){try{if(e==this.g)e:{const d=Qt(this.g);var t=this.g.Ba();const f=this.g.Z();if(!(3>d)&&(3!=d||this.g&&(this.h.h||this.g.oa()||Ht(this.g)))){this.J||4!=d||7==t||xe(8==t||0>=f?3:2),Qe(this);var n=this.g.Z();this.X=n;t:if($e(this)){var r=Ht(this.g);e="";var i=r.length,s=4==Qt(this.g);if(!this.h.i){if("undefined"==typeof TextDecoder){We(this),He(this);var a="";break t}this.h.i=new o.TextDecoder}for(t=0;t<i;t++)this.h.h=!0,e+=this.h.i.decode(r[t],{stream:!(s&&t==i-1)});r.length=0,this.h.g+=e,this.C=0,a=this.h.g}else a=this.g.oa();if(this.o=200==n,function(e,t,n,r,i,s,o){e.info((function(){return"XMLHTTP RESP ("+r+") [ attempt "+i+"]: "+t+"\n"+n+"\n"+s+" "+o}))}(this.i,this.u,this.A,this.l,this.R,d,n),this.o){if(this.T&&!this.K){t:{if(this.g){var c,u=this.g;if((c=u.g?u.g.getResponseHeader("X-HTTP-Initial-Response"):null)&&!m(c)){var l=c;break t}}l=null}if(!(n=l)){this.o=!1,this.s=3,De(12),We(this),He(this);break e}Le(this.i,this.l,n,"Initial handshake response via X-HTTP-Initial-Response"),this.K=!0,Je(this,n)}if(this.P){let e;for(n=!0;!this.J&&this.C<a.length;){if(e=ze(this,a),e==Be){4==d&&(this.s=4,De(14),n=!1),Le(this.i,this.l,null,"[Incomplete Response]");break}if(e==qe){this.s=4,De(15),Le(this.i,this.l,a,"[Invalid Chunk]"),n=!1;break}Le(this.i,this.l,e,null),Je(this,e)}if($e(this)&&0!=this.C&&(this.h.g=this.h.g.slice(this.C),this.C=0),4!=d||0!=a.length||this.h.h||(this.s=1,De(16),n=!1),this.o=this.o&&n,n){if(0<a.length&&!this.W){this.W=!0;var h=this.j;h.g==this&&h.ba&&!h.M&&(h.j.info("Great, no buffering proxy detected. Bytes received: "+a.length),an(h),h.M=!0,De(11))}}else Le(this.i,this.l,a,"[Invalid Chunked Response]"),We(this),He(this)}else Le(this.i,this.l,a,null),Je(this,a);4==d&&We(this),this.o&&!this.J&&(4==d?ln(this.j,this):(this.o=!1,Ge(this)))}else(function(e){const t={};e=(e.g&&2<=Qt(e)&&e.g.getAllResponseHeaders()||"").split("\r\n");for(let r=0;r<e.length;r++){if(m(e[r]))continue;var n=T(e[r]);const i=n[0];if("string"!=typeof(n=n[1]))continue;n=n.trim();const s=t[i]||[];t[i]=s,s.push(n)}!function(e,t){for(const n in e)t.call(void 0,e[n],n,e)}(t,(function(e){return e.join(", ")}))})(this.g),400==n&&0<a.indexOf("Unknown SID")?(this.s=3,De(12)):(this.s=0,De(13)),We(this),He(this)}}}catch(e){}},Fe.prototype.cancel=function(){this.J=!0,We(this)},Fe.prototype.ba=function(){this.B=null;const e=Date.now();0<=e-this.S?(function(e,t){e.info((function(){return"TIMEOUT: "+t}))}(this.i,this.A),2!=this.L&&(xe(3),De(17)),We(this),this.s=2,He(this)):Ke(this,this.S-e)};var Xe=class{constructor(e,t){this.g=e,this.map=t}};function Ye(e){this.l=e||10,e=o.PerformanceNavigationTiming?0<(e=o.performance.getEntriesByType("navigation")).length&&("hq"==e[0].nextHopProtocol||"h2"==e[0].nextHopProtocol):!!(o.chrome&&o.chrome.loadTimes&&o.chrome.loadTimes()&&o.chrome.loadTimes().wasFetchedViaSpdy),this.j=e?this.l:1,this.g=null,1<this.j&&(this.g=new Set),this.h=null,this.i=[]}function Ze(e){return!!e.h||!!e.g&&e.g.size>=e.j}function et(e){return e.h?1:e.g?e.g.size:0}function tt(e,t){return e.h?e.h==t:!!e.g&&e.g.has(t)}function nt(e,t){e.g?e.g.add(t):e.h=t}function rt(e,t){e.h&&e.h==t?e.h=null:e.g&&e.g.has(t)&&e.g.delete(t)}function it(e){if(null!=e.h)return e.i.concat(e.h.D);if(null!=e.g&&0!==e.g.size){let t=e.i;for(const n of e.g.values())t=t.concat(n.D);return t}return g(e.i)}function st(e,t){if(e.forEach&&"function"==typeof e.forEach)e.forEach(t,void 0);else if(a(e)||"string"==typeof e)Array.prototype.forEach.call(e,t,void 0);else for(var n=function(e){if(e.na&&"function"==typeof e.na)return e.na();if(!e.V||"function"!=typeof e.V){if("undefined"!=typeof Map&&e instanceof Map)return Array.from(e.keys());if(!("undefined"!=typeof Set&&e instanceof Set)){if(a(e)||"string"==typeof e){var t=[];e=e.length;for(var n=0;n<e;n++)t.push(n);return t}t=[],n=0;for(const r in e)t[n++]=r;return t}}}(e),r=function(e){if(e.V&&"function"==typeof e.V)return e.V();if("undefined"!=typeof Map&&e instanceof Map||"undefined"!=typeof Set&&e instanceof Set)return Array.from(e.values());if("string"==typeof e)return e.split("");if(a(e)){for(var t=[],n=e.length,r=0;r<n;r++)t.push(e[r]);return t}for(r in t=[],n=0,e)t[n++]=e[r];return t}(e),i=r.length,s=0;s<i;s++)t.call(void 0,r[s],n&&n[s],e)}Ye.prototype.cancel=function(){if(this.i=it(this),this.h)this.h.cancel(),this.h=null;else if(this.g&&0!==this.g.size){for(const e of this.g.values())e.cancel();this.g.clear()}};var ot=RegExp("^(?:([^:/?#.]+):)?(?://(?:([^\\\\/?#]*)@)?([^\\\\/?#]*?)(?::([0-9]+))?(?=[\\\\/?#]|$))?([^?#]+)?(?:\\?([^#]*))?(?:#([\\s\\S]*))?$");function at(e){if(this.g=this.o=this.j="",this.s=null,this.m=this.l="",this.h=!1,e instanceof at){this.h=e.h,ut(this,e.j),this.o=e.o,this.g=e.g,lt(this,e.s),this.l=e.l;var t=e.i,n=new Et;n.i=t.i,t.g&&(n.g=new Map(t.g),n.h=t.h),ht(this,n),this.m=e.m}else e&&(t=String(e).match(ot))?(this.h=!1,ut(this,t[1]||"",!0),this.o=gt(t[2]||""),this.g=gt(t[3]||"",!0),lt(this,t[4]),this.l=gt(t[5]||"",!0),ht(this,t[6]||"",!0),this.m=gt(t[7]||"")):(this.h=!1,this.i=new Et(null,this.h))}function ct(e){return new at(e)}function ut(e,t,n){e.j=n?gt(t,!0):t,e.j&&(e.j=e.j.replace(/:$/,""))}function lt(e,t){if(t){if(t=Number(t),isNaN(t)||0>t)throw Error("Bad port number "+t);e.s=t}else e.s=null}function ht(e,t,n){t instanceof Et?(e.i=t,function(e,t){t&&!e.j&&(Tt(e),e.i=null,e.g.forEach((function(e,t){var n=t.toLowerCase();t!=n&&(St(this,t),Ct(this,n,e))}),e)),e.j=t}(e.i,e.h)):(n||(t=pt(t,_t)),e.i=new Et(t,e.h))}function dt(e,t,n){e.i.set(t,n)}function ft(e){return dt(e,"zx",Math.floor(2147483648*Math.random()).toString(36)+Math.abs(Math.floor(2147483648*Math.random())^Date.now()).toString(36)),e}function gt(e,t){return e?t?decodeURI(e.replace(/%25/g,"%2525")):decodeURIComponent(e):""}function pt(e,t,n){return"string"==typeof e?(e=encodeURI(e).replace(t,mt),n&&(e=e.replace(/%25([0-9a-fA-F]{2})/g,"%$1")),e):null}function mt(e){return"%"+((e=e.charCodeAt(0))>>4&15).toString(16)+(15&e).toString(16)}at.prototype.toString=function(){var e=[],t=this.j;t&&e.push(pt(t,vt,!0),":");var n=this.g;return(n||"file"==t)&&(e.push("//"),(t=this.o)&&e.push(pt(t,vt,!0),"@"),e.push(encodeURIComponent(String(n)).replace(/%25([0-9a-fA-F]{2})/g,"%$1")),null!=(n=this.s)&&e.push(":",String(n))),(n=this.l)&&(this.g&&"/"!=n.charAt(0)&&e.push("/"),e.push(pt(n,"/"==n.charAt(0)?bt:wt,!0))),(n=this.i.toString())&&e.push("?",n),(n=this.m)&&e.push("#",pt(n,It)),e.join("")};var yt,vt=/[#\/\?@]/g,wt=/[#\?:]/g,bt=/[#\?]/g,_t=/[#\?@]/g,It=/#/g;function Et(e,t){this.h=this.g=null,this.i=e||null,this.j=!!t}function Tt(e){e.g||(e.g=new Map,e.h=0,e.i&&function(e,t){if(e){e=e.split("&");for(var n=0;n<e.length;n++){var r=e[n].indexOf("="),i=null;if(0<=r){var s=e[n].substring(0,r);i=e[n].substring(r+1)}else s=e[n];t(s,i?decodeURIComponent(i.replace(/\+/g," ")):"")}}}(e.i,(function(t,n){e.add(decodeURIComponent(t.replace(/\+/g," ")),n)})))}function St(e,t){Tt(e),t=Dt(e,t),e.g.has(t)&&(e.i=null,e.h-=e.g.get(t).length,e.g.delete(t))}function xt(e,t){return Tt(e),t=Dt(e,t),e.g.has(t)}function Ct(e,t,n){St(e,t),0<n.length&&(e.i=null,e.g.set(Dt(e,t),g(n)),e.h+=n.length)}function Dt(e,t){return t=String(t),e.j&&(t=t.toLowerCase()),t}function At(e,t,n,r,i){try{i&&(i.onload=null,i.onerror=null,i.onabort=null,i.ontimeout=null),r(n)}catch(e){}}function kt(){this.g=new pe}function Nt(e,t,n){const r=n||"";try{st(e,(function(e,n){let i=e;c(e)&&(i=fe(e)),t.push(r+n+"="+encodeURIComponent(i))}))}catch(e){throw t.push(r+"type="+encodeURIComponent("_badmap")),e}}function Lt(e){this.l=e.Ub||null,this.j=e.eb||!1}function Ot(e,t){ie.call(this),this.D=e,this.o=t,this.m=void 0,this.status=this.readyState=0,this.responseType=this.responseText=this.response=this.statusText="",this.onreadystatechange=null,this.u=new Headers,this.h=null,this.B="GET",this.A="",this.g=!1,this.v=this.j=this.l=null}function Mt(e){e.j.read().then(e.Pa.bind(e)).catch(e.ga.bind(e))}function Rt(e){e.readyState=4,e.l=null,e.j=null,e.v=null,Pt(e)}function Pt(e){e.onreadystatechange&&e.onreadystatechange.call(e)}function Ft(e){let t="";return b(e,(function(e,n){t+=n,t+=":",t+=e,t+="\r\n"})),t}function Vt(e,t,n){e:{for(r in n){var r=!1;break e}r=!0}r||(n=Ft(n),"string"==typeof e?(encodeURIComponent(String(t)),null!=n&&encodeURIComponent(String(n))):dt(e,t,n))}function qt(e){ie.call(this),this.headers=new Map,this.o=e||null,this.h=!1,this.v=this.g=null,this.D="",this.m=0,this.l="",this.j=this.B=this.u=this.A=!1,this.I=null,this.H="",this.J=!1}(t=Et.prototype).add=function(e,t){Tt(this),this.i=null,e=Dt(this,e);var n=this.g.get(e);return n||this.g.set(e,n=[]),n.push(t),this.h+=1,this},t.forEach=function(e,t){Tt(this),this.g.forEach((function(n,r){n.forEach((function(n){e.call(t,n,r,this)}),this)}),this)},t.na=function(){Tt(this);const e=Array.from(this.g.values()),t=Array.from(this.g.keys()),n=[];for(let r=0;r<t.length;r++){const i=e[r];for(let e=0;e<i.length;e++)n.push(t[r])}return n},t.V=function(e){Tt(this);let t=[];if("string"==typeof e)xt(this,e)&&(t=t.concat(this.g.get(Dt(this,e))));else{e=Array.from(this.g.values());for(let n=0;n<e.length;n++)t=t.concat(e[n])}return t},t.set=function(e,t){return Tt(this),this.i=null,xt(this,e=Dt(this,e))&&(this.h-=this.g.get(e).length),this.g.set(e,[t]),this.h+=1,this},t.get=function(e,t){return e&&0<(e=this.V(e)).length?String(e[0]):t},t.toString=function(){if(this.i)return this.i;if(!this.g)return"";const e=[],t=Array.from(this.g.keys());for(var n=0;n<t.length;n++){var r=t[n];const s=encodeURIComponent(String(r)),o=this.V(r);for(r=0;r<o.length;r++){var i=s;""!==o[r]&&(i+="="+encodeURIComponent(String(o[r]))),e.push(i)}}return this.i=e.join("&")},f(Lt,me),Lt.prototype.g=function(){return new Ot(this.l,this.j)},Lt.prototype.i=(yt={},function(){return yt}),f(Ot,ie),(t=Ot.prototype).open=function(e,t){if(0!=this.readyState)throw this.abort(),Error("Error reopening a connection");this.B=e,this.A=t,this.readyState=1,Pt(this)},t.send=function(e){if(1!=this.readyState)throw this.abort(),Error("need to call open() first. ");this.g=!0;const t={headers:this.u,method:this.B,credentials:this.m,cache:void 0};e&&(t.body=e),(this.D||o).fetch(new Request(this.A,t)).then(this.Sa.bind(this),this.ga.bind(this))},t.abort=function(){this.response=this.responseText="",this.u=new Headers,this.status=0,this.j&&this.j.cancel("Request was aborted.").catch((()=>{})),1<=this.readyState&&this.g&&4!=this.readyState&&(this.g=!1,Rt(this)),this.readyState=0},t.Sa=function(e){if(this.g&&(this.l=e,this.h||(this.status=this.l.status,this.statusText=this.l.statusText,this.h=e.headers,this.readyState=2,Pt(this)),this.g&&(this.readyState=3,Pt(this),this.g)))if("arraybuffer"===this.responseType)e.arrayBuffer().then(this.Qa.bind(this),this.ga.bind(this));else if(void 0!==o.ReadableStream&&"body"in e){if(this.j=e.body.getReader(),this.o){if(this.responseType)throw Error('responseType must be empty for "streamBinaryChunks" mode responses.');this.response=[]}else this.response=this.responseText="",this.v=new TextDecoder;Mt(this)}else e.text().then(this.Ra.bind(this),this.ga.bind(this))},t.Pa=function(e){if(this.g){if(this.o&&e.value)this.response.push(e.value);else if(!this.o){var t=e.value?e.value:new Uint8Array(0);(t=this.v.decode(t,{stream:!e.done}))&&(this.response=this.responseText+=t)}e.done?Rt(this):Pt(this),3==this.readyState&&Mt(this)}},t.Ra=function(e){this.g&&(this.response=this.responseText=e,Rt(this))},t.Qa=function(e){this.g&&(this.response=e,Rt(this))},t.ga=function(){this.g&&Rt(this)},t.setRequestHeader=function(e,t){this.u.append(e,t)},t.getResponseHeader=function(e){return this.h&&this.h.get(e.toLowerCase())||""},t.getAllResponseHeaders=function(){if(!this.h)return"";const e=[],t=this.h.entries();for(var n=t.next();!n.done;)n=n.value,e.push(n[0]+": "+n[1]),n=t.next();return e.join("\r\n")},Object.defineProperty(Ot.prototype,"withCredentials",{get:function(){return"include"===this.m},set:function(e){this.m=e?"include":"same-origin"}}),f(qt,ie);var Bt=/^https?$/i,Ut=["POST","PUT"];function jt(e,t){e.h=!1,e.g&&(e.j=!0,e.g.abort(),e.j=!1),e.l=t,e.m=5,$t(e),Gt(e)}function $t(e){e.A||(e.A=!0,se(e,"complete"),se(e,"error"))}function zt(e){if(e.h&&void 0!==s&&(!e.v[1]||4!=Qt(e)||2!=e.Z()))if(e.u&&4==Qt(e))ae(e.Ea,0,e);else if(se(e,"readystatechange"),4==Qt(e)){e.h=!1;try{const s=e.Z();e:switch(s){case 200:case 201:case 202:case 204:case 206:case 304:case 1223:var t=!0;break e;default:t=!1}var n;if(!(n=t)){var r;if(r=0===s){var i=String(e.D).match(ot)[1]||null;!i&&o.self&&o.self.location&&(i=o.self.location.protocol.slice(0,-1)),r=!Bt.test(i?i.toLowerCase():"")}n=r}if(n)se(e,"complete"),se(e,"success");else{e.m=6;try{var a=2<Qt(e)?e.g.statusText:""}catch(e){a=""}e.l=a+" ["+e.Z()+"]",$t(e)}}finally{Gt(e)}}}function Gt(e,t){if(e.g){Kt(e);const n=e.g,r=e.v[0]?()=>{}:null;e.g=null,e.v=null,t||se(e,"ready");try{n.onreadystatechange=r}catch(e){}}}function Kt(e){e.I&&(o.clearTimeout(e.I),e.I=null)}function Qt(e){return e.g?e.g.readyState:0}function Ht(e){try{if(!e.g)return null;if("response"in e.g)return e.g.response;switch(e.H){case"":case"text":return e.g.responseText;case"arraybuffer":if("mozResponseArrayBuffer"in e.g)return e.g.mozResponseArrayBuffer}return null}catch(e){return null}}function Wt(e,t,n){return n&&n.internalChannelParams&&n.internalChannelParams[e]||t}function Jt(e){this.Aa=0,this.i=[],this.j=new Ne,this.ia=this.qa=this.I=this.W=this.g=this.ya=this.D=this.H=this.m=this.S=this.o=null,this.Ya=this.U=0,this.Va=Wt("failFast",!1,e),this.F=this.C=this.u=this.s=this.l=null,this.X=!0,this.za=this.T=-1,this.Y=this.v=this.B=0,this.Ta=Wt("baseRetryDelayMs",5e3,e),this.cb=Wt("retryDelaySeedMs",1e4,e),this.Wa=Wt("forwardChannelMaxRetries",2,e),this.wa=Wt("forwardChannelRequestTimeoutMs",2e4,e),this.pa=e&&e.xmlHttpFactory||void 0,this.Xa=e&&e.Tb||void 0,this.Ca=e&&e.useFetchStreams||!1,this.L=void 0,this.J=e&&e.supportsCrossDomainXhr||!1,this.K="",this.h=new Ye(e&&e.concurrentRequestLimit),this.Da=new kt,this.P=e&&e.fastHandshake||!1,this.O=e&&e.encodeInitMessageHeaders||!1,this.P&&this.O&&(this.O=!1),this.Ua=e&&e.Rb||!1,e&&e.xa&&this.j.xa(),e&&e.forceLongPolling&&(this.X=!1),this.ba=!this.P&&this.X&&e&&e.detectBufferingProxy||!1,this.ja=void 0,e&&e.longPollingTimeout&&0<e.longPollingTimeout&&(this.ja=e.longPollingTimeout),this.ca=void 0,this.R=0,this.M=!1,this.ka=this.A=null}function Xt(e){if(Zt(e),3==e.G){var t=e.U++,n=ct(e.I);if(dt(n,"SID",e.K),dt(n,"RID",t),dt(n,"TYPE","terminate"),nn(e,n),(t=new Fe(e,e.j,t)).L=2,t.v=ft(ct(n)),n=!1,o.navigator&&o.navigator.sendBeacon)try{n=o.navigator.sendBeacon(t.v.toString(),"")}catch(e){}!n&&o.Image&&((new Image).src=t.v,n=!0),n||(t.g=pn(t.j,null),t.g.ea(t.v)),t.F=Date.now(),Ge(t)}fn(e)}function Yt(e){e.g&&(an(e),e.g.cancel(),e.g=null)}function Zt(e){Yt(e),e.u&&(o.clearTimeout(e.u),e.u=null),un(e),e.h.cancel(),e.s&&("number"==typeof e.s&&o.clearTimeout(e.s),e.s=null)}function en(e){if(!Ze(e.h)&&!e.s){e.s=!0;var t=e.Ga;A||L(),k||(A(),k=!0),N.add(t,e),e.B=0}}function tn(e,t){var n;n=t?t.l:e.U++;const r=ct(e.I);dt(r,"SID",e.K),dt(r,"RID",n),dt(r,"AID",e.T),nn(e,r),e.m&&e.o&&Vt(r,e.m,e.o),n=new Fe(e,e.j,n,e.B+1),null===e.m&&(n.H=e.o),t&&(e.i=t.D.concat(e.i)),t=rn(e,n,1e3),n.I=Math.round(.5*e.wa)+Math.round(.5*e.wa*Math.random()),nt(e.h,n),Ue(n,r,t)}function nn(e,t){e.H&&b(e.H,(function(e,n){dt(t,n,e)})),e.l&&st({},(function(e,n){dt(t,n,e)}))}function rn(e,t,n){n=Math.min(e.i.length,n);var r=e.l?h(e.l.Na,e.l,e):null;e:{var i=e.i;let t=-1;for(;;){const e=["count="+n];-1==t?0<n?(t=i[0].g,e.push("ofs="+t)):t=0:e.push("ofs="+t);let s=!0;for(let o=0;o<n;o++){let n=i[o].g;const a=i[o].map;if(n-=t,0>n)t=Math.max(0,i[o].g-100),s=!1;else try{Nt(a,e,"req"+n+"_")}catch(e){r&&r(a)}}if(s){r=e.join("&");break e}}}return e=e.i.splice(0,n),t.D=e,r}function sn(e){if(!e.g&&!e.u){e.Y=1;var t=e.Fa;A||L(),k||(A(),k=!0),N.add(t,e),e.v=0}}function on(e){return!(e.g||e.u||3<=e.v||(e.Y++,e.u=ke(h(e.Fa,e),hn(e,e.v)),e.v++,0))}function an(e){null!=e.A&&(o.clearTimeout(e.A),e.A=null)}function cn(e){e.g=new Fe(e,e.j,"rpc",e.Y),null===e.m&&(e.g.H=e.o),e.g.O=0;var t=ct(e.qa);dt(t,"RID","rpc"),dt(t,"SID",e.K),dt(t,"AID",e.T),dt(t,"CI",e.F?"0":"1"),!e.F&&e.ja&&dt(t,"TO",e.ja),dt(t,"TYPE","xmlhttp"),nn(e,t),e.m&&e.o&&Vt(t,e.m,e.o),e.L&&(e.g.I=e.L);var n=e.g;e=e.ia,n.L=1,n.v=ft(ct(t)),n.m=null,n.P=!0,je(n,e)}function un(e){null!=e.C&&(o.clearTimeout(e.C),e.C=null)}function ln(e,t){var n=null;if(e.g==t){un(e),an(e),e.g=null;var r=2}else{if(!tt(e.h,t))return;n=t.D,rt(e.h,t),r=1}if(0!=e.G)if(t.o)if(1==r){n=t.m?t.m.length:0,t=Date.now()-t.F;var i=e.B;se(r=Te(),new Ae(r,n,t,i)),en(e)}else sn(e);else if(3==(i=t.s)||0==i&&0<t.X||!(1==r&&function(e,t){return!(et(e.h)>=e.h.j-(e.s?1:0)||(e.s?(e.i=t.D.concat(e.i),0):1==e.G||2==e.G||e.B>=(e.Va?0:e.Wa)||(e.s=ke(h(e.Ga,e,t),hn(e,e.B)),e.B++,0)))}(e,t)||2==r&&on(e)))switch(n&&0<n.length&&(t=e.h,t.i=t.i.concat(n)),i){case 1:dn(e,5);break;case 4:dn(e,10);break;case 3:dn(e,6);break;default:dn(e,2)}}function hn(e,t){let n=e.Ta+Math.floor(Math.random()*e.cb);return e.isActive()||(n*=2),n*t}function dn(e,t){if(e.j.info("Error code "+t),2==t){var n=h(e.fb,e),r=e.Xa;const t=!r;r=new at(r||"//www.google.com/images/cleardot.gif"),o.location&&"http"==o.location.protocol||ut(r,"https"),ft(r),t?function(e,t){const n=new Ne;if(o.Image){const r=new Image;r.onload=d(At,n,"TestLoadImage: loaded",!0,t,r),r.onerror=d(At,n,"TestLoadImage: error",!1,t,r),r.onabort=d(At,n,"TestLoadImage: abort",!1,t,r),r.ontimeout=d(At,n,"TestLoadImage: timeout",!1,t,r),o.setTimeout((function(){r.ontimeout&&r.ontimeout()}),1e4),r.src=e}else t(!1)}(r.toString(),n):function(e,t){new Ne;const n=new AbortController,r=setTimeout((()=>{n.abort(),At(0,0,!1,t)}),1e4);fetch(e,{signal:n.signal}).then((e=>{clearTimeout(r),e.ok?At(0,0,!0,t):At(0,0,!1,t)})).catch((()=>{clearTimeout(r),At(0,0,!1,t)}))}(r.toString(),n)}else De(2);e.G=0,e.l&&e.l.sa(t),fn(e),Zt(e)}function fn(e){if(e.G=0,e.ka=[],e.l){const t=it(e.h);0==t.length&&0==e.i.length||(p(e.ka,t),p(e.ka,e.i),e.h.i.length=0,g(e.i),e.i.length=0),e.l.ra()}}function gn(e,t,n){var r=n instanceof at?ct(n):new at(n);if(""!=r.g)t&&(r.g=t+"."+r.g),lt(r,r.s);else{var i=o.location;r=i.protocol,t=t?t+"."+i.hostname:i.hostname,i=+i.port;var s=new at(null);r&&ut(s,r),t&&(s.g=t),i&&lt(s,i),n&&(s.l=n),r=s}return n=e.D,t=e.ya,n&&t&&dt(r,n,t),dt(r,"VER",e.la),nn(e,r),r}function pn(e,t,n){if(t&&!e.J)throw Error("Can't create secondary domain capable XhrIo object.");return(t=e.Ca&&!e.pa?new qt(new Lt({eb:n})):new qt(e.pa)).Ha(e.J),t}function mn(){}function yn(){}function vn(e,t){ie.call(this),this.g=new Jt(t),this.l=e,this.h=t&&t.messageUrlParams||null,e=t&&t.messageHeaders||null,t&&t.clientProtocolHeaderRequired&&(e?e["X-Client-Protocol"]="webchannel":e={"X-Client-Protocol":"webchannel"}),this.g.o=e,e=t&&t.initMessageHeaders||null,t&&t.messageContentType&&(e?e["X-WebChannel-Content-Type"]=t.messageContentType:e={"X-WebChannel-Content-Type":t.messageContentType}),t&&t.va&&(e?e["X-WebChannel-Client-Profile"]=t.va:e={"X-WebChannel-Client-Profile":t.va}),this.g.S=e,(e=t&&t.Sb)&&!m(e)&&(this.g.m=e),this.v=t&&t.supportsCrossDomainXhr||!1,this.u=t&&t.sendRawJson||!1,(t=t&&t.httpSessionIdParam)&&!m(t)&&(this.g.D=t,null!==(e=this.h)&&t in e&&t in(e=this.h)&&delete e[t]),this.j=new _n(this)}function wn(e){be.call(this),e.__headers__&&(this.headers=e.__headers__,this.statusCode=e.__status__,delete e.__headers__,delete e.__status__);var t=e.__sm__;if(t){e:{for(const n in t){e=n;break e}e=void 0}(this.i=e)&&(e=this.i,t=null!==t&&e in t?t[e]:void 0),this.data=t}else this.data=e}function bn(){_e.call(this),this.status=1}function _n(e){this.g=e}(t=qt.prototype).Ha=function(e){this.J=e},t.ea=function(e,t,n,r){if(this.g)throw Error("[goog.net.XhrIo] Object is active with another request="+this.D+"; newUri="+e);t=t?t.toUpperCase():"GET",this.D=e,this.l="",this.m=0,this.A=!1,this.h=!0,this.g=this.o?this.o.g():Oe.g(),this.v=this.o?ye(this.o):ye(Oe),this.g.onreadystatechange=h(this.Ea,this);try{this.B=!0,this.g.open(t,String(e),!0),this.B=!1}catch(e){return void jt(this,e)}if(e=n||"",n=new Map(this.headers),r)if(Object.getPrototypeOf(r)===Object.prototype)for(var i in r)n.set(i,r[i]);else{if("function"!=typeof r.keys||"function"!=typeof r.get)throw Error("Unknown input type for opt_headers: "+String(r));for(const e of r.keys())n.set(e,r.get(e))}r=Array.from(n.keys()).find((e=>"content-type"==e.toLowerCase())),i=o.FormData&&e instanceof o.FormData,!(0<=Array.prototype.indexOf.call(Ut,t,void 0))||r||i||n.set("Content-Type","application/x-www-form-urlencoded;charset=utf-8");for(const[e,t]of n)this.g.setRequestHeader(e,t);this.H&&(this.g.responseType=this.H),"withCredentials"in this.g&&this.g.withCredentials!==this.J&&(this.g.withCredentials=this.J);try{Kt(this),this.u=!0,this.g.send(e),this.u=!1}catch(e){jt(this,e)}},t.abort=function(e){this.g&&this.h&&(this.h=!1,this.j=!0,this.g.abort(),this.j=!1,this.m=e||7,se(this,"complete"),se(this,"abort"),Gt(this))},t.N=function(){this.g&&(this.h&&(this.h=!1,this.j=!0,this.g.abort(),this.j=!1),Gt(this,!0)),qt.aa.N.call(this)},t.Ea=function(){this.s||(this.B||this.u||this.j?zt(this):this.bb())},t.bb=function(){zt(this)},t.isActive=function(){return!!this.g},t.Z=function(){try{return 2<Qt(this)?this.g.status:-1}catch(e){return-1}},t.oa=function(){try{return this.g?this.g.responseText:""}catch(e){return""}},t.Oa=function(e){if(this.g){var t=this.g.responseText;return e&&0==t.indexOf(e)&&(t=t.substring(e.length)),ge(t)}},t.Ba=function(){return this.m},t.Ka=function(){return"string"==typeof this.l?this.l:String(this.l)},(t=Jt.prototype).la=8,t.G=1,t.connect=function(e,t,n,r){De(0),this.W=e,this.H=t||{},n&&void 0!==r&&(this.H.OSID=n,this.H.OAID=r),this.F=this.X,this.I=gn(this,null,this.W),en(this)},t.Ga=function(e){if(this.s)if(this.s=null,1==this.G){if(!e){this.U=Math.floor(1e5*Math.random()),e=this.U++;const i=new Fe(this,this.j,e);let s=this.o;if(this.S&&(s?(s=_(s),E(s,this.S)):s=this.S),null!==this.m||this.O||(i.H=s,s=null),this.P)e:{for(var t=0,n=0;n<this.i.length;n++){var r=this.i[n];if(void 0===(r="__data__"in r.map&&"string"==typeof(r=r.map.__data__)?r.length:void 0))break;if(4096<(t+=r)){t=n;break e}if(4096===t||n===this.i.length-1){t=n+1;break e}}t=1e3}else t=1e3;t=rn(this,i,t),dt(n=ct(this.I),"RID",e),dt(n,"CVER",22),this.D&&dt(n,"X-HTTP-Session-Id",this.D),nn(this,n),s&&(this.O?t="headers="+encodeURIComponent(String(Ft(s)))+"&"+t:this.m&&Vt(n,this.m,s)),nt(this.h,i),this.Ua&&dt(n,"TYPE","init"),this.P?(dt(n,"$req",t),dt(n,"SID","null"),i.T=!0,Ue(i,n,null)):Ue(i,n,t),this.G=2}}else 3==this.G&&(e?tn(this,e):0==this.i.length||Ze(this.h)||tn(this))},t.Fa=function(){if(this.u=null,cn(this),this.ba&&!(this.M||null==this.g||0>=this.R)){var e=2*this.R;this.j.info("BP detection timer enabled: "+e),this.A=ke(h(this.ab,this),e)}},t.ab=function(){this.A&&(this.A=null,this.j.info("BP detection timeout reached."),this.j.info("Buffering proxy detected and switch to long-polling!"),this.F=!1,this.M=!0,De(10),Yt(this),cn(this))},t.Za=function(){null!=this.C&&(this.C=null,Yt(this),on(this),De(19))},t.fb=function(e){e?(this.j.info("Successfully pinged google.com"),De(2)):(this.j.info("Failed to ping google.com"),De(1))},t.isActive=function(){return!!this.l&&this.l.isActive(this)},(t=mn.prototype).ua=function(){},t.ta=function(){},t.sa=function(){},t.ra=function(){},t.isActive=function(){return!0},t.Na=function(){},yn.prototype.g=function(e,t){return new vn(e,t)},f(vn,ie),vn.prototype.m=function(){this.g.l=this.j,this.v&&(this.g.J=!0),this.g.connect(this.l,this.h||void 0)},vn.prototype.close=function(){Xt(this.g)},vn.prototype.o=function(e){var t=this.g;if("string"==typeof e){var n={};n.__data__=e,e=n}else this.u&&((n={}).__data__=fe(e),e=n);t.i.push(new Xe(t.Ya++,e)),3==t.G&&en(t)},vn.prototype.N=function(){this.g.l=null,delete this.j,Xt(this.g),delete this.g,vn.aa.N.call(this)},f(wn,be),f(bn,_e),f(_n,mn),_n.prototype.ua=function(){se(this.g,"a")},_n.prototype.ta=function(e){se(this.g,new wn(e))},_n.prototype.sa=function(e){se(this.g,new bn(e))},_n.prototype.ra=function(){se(this.g,"b")},yn.prototype.createWebChannel=yn.prototype.g,vn.prototype.send=vn.prototype.o,vn.prototype.open=vn.prototype.m,vn.prototype.close=vn.prototype.close,e.exports.createWebChannelTransport=function(){return new yn},e.exports.getStatEventTarget=function(){return Te()},e.exports.Event=Ie,e.exports.Stat={mb:0,pb:1,qb:2,Jb:3,Ob:4,Lb:5,Mb:6,Kb:7,Ib:8,Nb:9,PROXY:10,NOPROXY:11,Gb:12,Cb:13,Db:14,Bb:15,Eb:16,Fb:17,ib:18,hb:19,jb:20},Me.NO_ERROR=0,Me.TIMEOUT=8,Me.HTTP_ERROR=6,e.exports.ErrorCode=Me,Re.COMPLETE="complete",e.exports.EventType=Re,ve.EventType=we,we.OPEN="a",we.CLOSE="b",we.ERROR="c",we.MESSAGE="d",ie.prototype.listen=ie.prototype.K,e.exports.WebChannel=ve,e.exports.FetchXmlHttpFactory=Lt,qt.prototype.listenOnce=qt.prototype.L,qt.prototype.getLastError=qt.prototype.Ka,qt.prototype.getLastErrorCode=qt.prototype.Ba,qt.prototype.getStatus=qt.prototype.Z,qt.prototype.getResponseJson=qt.prototype.Oa,qt.prototype.getResponseText=qt.prototype.oa,qt.prototype.send=qt.prototype.ea,qt.prototype.setWithCredentials=qt.prototype.Ha,e.exports.XhrIo=qt}).apply(void 0!==n.g?n.g:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},577:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(199);r.registerVersion("firebase","11.1.0","app"),Object.keys(r).forEach((function(e){"default"===e||t.hasOwnProperty(e)||Object.defineProperty(t,e,{enumerable:!0,get:function(){return r[e]}})}))},815:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(241);Object.keys(r).forEach((function(e){"default"===e||t.hasOwnProperty(e)||Object.defineProperty(t,e,{enumerable:!0,get:function(){return r[e]}})}))},619:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(249);Object.keys(r).forEach((function(e){"default"===e||t.hasOwnProperty(e)||Object.defineProperty(t,e,{enumerable:!0,get:function(){return r[e]}})}))},264:(e,t,n)=>{"use strict";n.r(t)},846:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.initCalculator=function(e,t){e.innerHTML=`\n <div class="mortgage-calculator">\n <div class="section-heading"><span>Mortgage</span> Payment <span>Calculator</span></div>\n <div class="calculator-fields">\n <div class="mortgage-amount-wrapper">\n <div class="calculator-floating-label-field">\n <label>Mortgage Amount</label>\n <input type="text" id="mortgage-amount-field" />\n </div>\n </div>\n <div class="rate-amortization-period-wrapper">\n <div class="calculator-fixed-label-field">\n <label>Rates</label>\n <input type="text" id="rate-field" />\n </div>\n <div class="calculator-fixed-label-field">\n <label>Amortization</label>\n <select id="amortization-field">\n <option value="10">10 years</option>\n <option value="15">15 years</option>\n <option value="20">20 years</option>\n <option value="25">25 years</option>\n </select>\n </div>\n <div class="calculator-fixed-label-field">\n <label>Payment Period</label>\n <select id="payment-period-field">\n <option value="monthly">Monthly</option>\n <option value="biweekly">Bi-weekly</option>\n <option value="weekly">Weekly</option>\n </select>\n </div>\n </div>\n <div class="apply-wrapper">\n <div id="mortagage-payment"></div>\n <a class="mortgage-apply-link disabled" href="${t}" target="_blank">Apply</button>\n </div>\n </div>\n </div>\n `;const n=document.getElementById("mortgage-amount-field"),r=document.getElementById("rate-field"),s=document.getElementById("amortization-field"),o=document.getElementById("payment-period-field"),a=(e,t)=>{e.addEventListener("input",(e=>{const n=e.target;if(n){let e=n.value;e=e.replace(/[^0-9.]/g,""),n.value=e?"$"===t?`${t}${parseInt(e).toLocaleString("en-US")}`:`${e}${t}`:""}}))};a(n,"$"),a(r,"%"),n.addEventListener("input",i),r.addEventListener("input",i),s.addEventListener("change",i),o.addEventListener("change",i),r.addEventListener("focus",(e=>{var t;null===(t=e.target.parentElement)||void 0===t||t.classList.add("child-input-focused")})),r.addEventListener("blur",(e=>{var t;null===(t=e.target.parentElement)||void 0===t||t.classList.remove("child-input-focused")})),s.addEventListener("focus",(e=>{var t;null===(t=e.target.parentElement)||void 0===t||t.classList.add("child-input-focused")})),s.addEventListener("blur",(e=>{var t;null===(t=e.target.parentElement)||void 0===t||t.classList.remove("child-input-focused")})),o.addEventListener("focus",(e=>{var t;null===(t=e.target.parentElement)||void 0===t||t.classList.add("child-input-focused")})),o.addEventListener("blur",(e=>{var t;null===(t=e.target.parentElement)||void 0===t||t.classList.remove("child-input-focused")}))};const r=n(185);function i(){const e=document.getElementById("mortgage-amount-field"),t=document.getElementById("rate-field"),n=document.getElementById("amortization-field"),i=document.getElementById("payment-period-field"),s=document.getElementById("mortagage-payment"),o=document.querySelector(".mortgage-apply-link"),a=parseFloat(e.value.replace(/\$/g,"").replace(/\,/g,"")),c=parseFloat(t.value.replace(/%/g,"")),u=parseInt(n.value),l=i.value;if(isNaN(a)||isNaN(c)||isNaN(u)||!l)return s.textContent="",void(o.classList.contains("disabled")||o.classList.add("disabled"));const h=(0,r.calculateMortgage)(a,c,u,l);s.textContent=`$${parseFloat(h.toFixed(2)).toLocaleString("en-US")}`,o.classList.contains("disabled")&&o.classList.remove("disabled")}},958:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.initCockpit=function(e){const t=window.innerWidth<992?window.innerWidth-32:600,n=window.innerWidth<992?350:450,r=[{id:"housing-indicators",name:"Housing Indicators",description:"The Canadian housing market is influenced by a range of important indicators that provide insights into the overall economic health and housing trends.",stats:[{title:"Residential sales activity",embed_code:`<iframe width="${t}" height="${n}" src="https://lookerstudio.google.com/embed/reporting/4c4cf585-74d2-4d90-938c-ec3ca0ddf85f/page/48IDE" frameborder="0" style="border:0" allowfullscreen sandbox="allow-storage-access-by-user-activation allow-scripts allow-same-origin allow-popups allow-popups-to-escape-sandbox"></iframe>`},{title:"Residential Average Price",embed_code:`<iframe width="${t}" height="${n}" src="https://lookerstudio.google.com/embed/reporting/918ac56b-3efc-4f8c-b455-9fe2be8c9e0c/page/HEJDE" frameborder="0" style="border:0" allowfullscreen sandbox="allow-storage-access-by-user-activation allow-scripts allow-same-origin allow-popups allow-popups-to-escape-sandbox"></iframe>`},{title:"Residential Market Balance",embed_code:`<iframe width="${t}" height="${n}" src="https://lookerstudio.google.com/embed/reporting/0e5fee3d-3c53-4469-9baa-36cb60aac28d/page/KHJDE" frameborder="0" style="border:0" allowfullscreen sandbox="allow-storage-access-by-user-activation allow-scripts allow-same-origin allow-popups allow-popups-to-escape-sandbox"></iframe>`},{title:"Residential New Listings",embed_code:`<iframe width="${t}" height="${n}" src="https://lookerstudio.google.com/embed/reporting/5994b7fe-d4ac-4a8d-b17d-4aee90fc1958/page/4CJDE" frameborder="0" style="border:0" allowfullscreen sandbox="allow-storage-access-by-user-activation allow-scripts allow-same-origin allow-popups allow-popups-to-escape-sandbox"></iframe>`},{title:"Residential Average Price (year over year percentage change )",embed_code:`<iframe width="${t}" height="${n}" src="https://lookerstudio.google.com/embed/reporting/0bbb457e-e130-4164-92ad-1f313f3d1d1c/page/6EJDE" frameborder="0" style="border:0" allowfullscreen sandbox="allow-storage-access-by-user-activation allow-scripts allow-same-origin allow-popups allow-popups-to-escape-sandbox"></iframe>`},{title:"MLS HPI Benchmark Price",embed_code:`<iframe width="${t}" height="${n}" src="https://lookerstudio.google.com/embed/reporting/5d0b79b4-7ae4-4f92-bdfb-1fbcc70b4ffb/page/IGJDE" frameborder="0" style="border:0" allowfullscreen sandbox="allow-storage-access-by-user-activation allow-scripts allow-same-origin allow-popups allow-popups-to-escape-sandbox"></iframe>`},{title:"Housing affordability index",embed_code:`<iframe width="${t}" height="${n}" src="https://lookerstudio.google.com/embed/reporting/643969af-c85b-4b53-bd43-ad2c35ea3dbf/page/56FHE" frameborder="0" style="border:0" allowfullscreen sandbox="allow-storage-access-by-user-activation allow-scripts allow-same-origin allow-popups allow-popups-to-escape-sandbox"></iframe>`}]},{id:"economic-indicators",name:"Economic Indicators",description:"Canadian economic indicators provide valuable insights into the health and performance of the country’s economy. These indicators are used by policymakers, economists, businesses, and investors to assess economic conditions and make informed decisions.",stats:[{title:"Retail sales increase ",embed_code:`<iframe width="${t}" height="${n}" src="https://lookerstudio.google.com/embed/reporting/e78b80fa-b1bc-4f2c-a021-e2de7308134e/page/CgeGE" frameborder="0" style="border:0" allowfullscreen sandbox="allow-storage-access-by-user-activation allow-scripts allow-same-origin allow-popups allow-popups-to-escape-sandbox"></iframe>`},{title:"Employment rate",embed_code:`<iframe width="${t}" height="${n}" src="https://lookerstudio.google.com/embed/reporting/53c524e5-ebfb-475c-81c8-94b461482a6d/page/hyeGE" frameborder="0" style="border:0" allowfullscreen sandbox="allow-storage-access-by-user-activation allow-scripts allow-same-origin allow-popups allow-popups-to-escape-sandbox"></iframe>`},{title:"Quarterly population estimate",embed_code:`<iframe width="${t}" height="${n}" src="https://lookerstudio.google.com/embed/reporting/55188dfc-ba3d-48fb-865f-f30869596420/page/C0eGE" frameborder="0" style="border:0" allowfullscreen sandbox="allow-storage-access-by-user-activation allow-scripts allow-same-origin allow-popups allow-popups-to-escape-sandbox"></iframe>`},{title:"CPI and CPI excluding gasoline",embed_code:`<iframe width="${t}" height="${n}" src="https://lookerstudio.google.com/embed/reporting/bf06875f-f5f4-4a3a-8a3b-82c11a1346a6/page/g2eGE" frameborder="0" style="border:0" allowfullscreen sandbox="allow-storage-access-by-user-activation allow-scripts allow-same-origin allow-popups allow-popups-to-escape-sandbox"></iframe>`}]},{id:"mortgage-indicators",name:"Mortgage Indicators",description:"",stats:[]},{id:"key-rates",name:"Key Rates",description:"",stats:[]}];let i='\n <div class="cockpit">\n <div class="header-wrapper">\n <div class="tab-selectors">\n ',s=0;for(let e of r)i+=`<div class="tab-selector ${0===s?"selected":""}" data-tab-id="${e.id}">${e.name}</div>`,s++;i+="\n </div>",s=0;for(let e of r)i+=`\n <div id="tab-content-${e.id}" class="tab-content ${0===s?"selected":""}">\n <div class="title">${e.name}</div>\n <div class="description">${e.description}</div>\n </div>`,s++;i+='\n </div>\n <div class="stats"></div>\n </div>\n ',e.innerHTML=i;const o=e.querySelector(".cockpit"),a=e.querySelector(".tab-selectors"),c=(e.querySelector(".header-wrapper"),e.querySelector(".stats")),u=r.filter((e=>"housing-indicators"===e.id))[0];let l="";for(let e of u.stats)l+=`\n <div class="stat">\n <div class="title">${e.title}</div>\n <div class="stat-graph">${e.embed_code}</div>\n </div>\n `;c.innerHTML=l,o.addEventListener("click",(e=>{var t,n;const i=e.target;if(i.closest(".tab-selector")){null===(t=a.querySelector(".selected"))||void 0===t||t.classList.remove("selected"),i.classList.add("selected"),o.querySelectorAll(".tab-content").forEach((e=>{e.classList.remove("selected")})),null===(n=document.getElementById(`tab-content-${i.dataset.tabId}`))||void 0===n||n.classList.add("selected");const e=r.filter((e=>e.id===i.dataset.tabId))[0];let s="";for(let t of e.stats)s+=`\n <div class="stat">\n <div class="title">${t.title}</div>\n <div class="stat-graph">${t.embed_code}</div>\n </div>\n `;c.innerHTML=s}}))}},260:function(e,t,n){"use strict";var r=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(i,s){function o(e){try{c(r.next(e))}catch(e){s(e)}}function a(e){try{c(r.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,a)}c((r=r.apply(e,t||[])).next())}))},i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.initEducationalVideos=function(e){e.innerHTML='\n <div class="educational-videos">\n <div class="section-heading">Educational Videos</div>\n <div class="filters">\n <div class="filter selected">All Videos</div>\n <div class="filter">First time home buyers in Canada</div>\n <div class="filter">Mortgage Fundamentals</div>\n <div class="filter">Renewal</div>\n <div class="filter">Mortgage Repayment</div>\n </div>\n <div class="videos"></div>\n <div id="video-player" class="modal" style="display: none;">\n <div class="modal-content">\n <span class="close">&times;</span>\n <iframe id="video-frame" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>\n </div>\n </div>\n </div>\n ';const t=e.querySelector(".educational-videos"),n=e.querySelector(".section-heading"),i=e.querySelector(".filters"),s=e.querySelector(".videos");if(!t||!n||!s)return;f(e);let o=!1,a=!0;window.addEventListener("scroll",(e=>{let t=0;return(...n)=>{const r=Date.now();r-t>=200&&(t=r,e(...n))}})((()=>r(this,void 0,void 0,(function*(){const t=s.getBoundingClientRect().bottom<=window.innerHeight+100;if(!o&&a&&t){o=!0;try{const t=yield f(e);a=t}catch(e){console.error("Error loading educational videos:",e)}finally{o=!1}}}))))),i.addEventListener("click",(t=>{const n=t.target;if(n.closest(".filter")){i.querySelectorAll(".filter").forEach((e=>{e.classList.remove("selected")})),n.classList.add("selected");const t="All Videos"===n.textContent?"":n.textContent;d=t||"",h=null,s.innerHTML="",f(e)}}))};const s=n(487),o=n(815),a=i(n(757)),c=n(185),u="educational_videos",l=9;let h=null,d="";function f(e){return r(this,void 0,void 0,(function*(){const t=e.querySelector(".videos");if(!t)return!1;try{const e=yield(0,s.getFirestoreInstance)();let n=(0,o.query)((0,o.collection)(e,u),(0,o.orderBy)("date","desc"),(0,o.limit)(l));d&&(n=(0,o.query)(n,(0,o.where)("category","==",d))),h&&(n=(0,o.query)(n,(0,o.startAfter)(h)));const r=yield(0,o.getDocs)(n);return r.empty?(console.log("No more videos to load"),!1):(r.forEach((e=>{var n,r,i;const s=e.data(),o=document.createElement("div");o.classList.add("video"),o.setAttribute("data-video-url",s.video_link),o.innerHTML=`\n <div class="thumbnail" style="background-image: url('${s.img_link}');">\n <div class="thumbnail-overlay" style="">\n <div class="play-icon">\n <img src="${a.default}" alt="Play Video" />\n </div>\n </div>\n </div>\n <div class="date">${(0,c.formatDate)(null===(n=s.date)||void 0===n?void 0:n.trim())}</div>\n <div class="title">${null===(r=s.headline)||void 0===r?void 0:r.trim()}</div>\n <div class="source">Source: <span>${null===(i=s.source)||void 0===i?void 0:i.trim()}</span></div>\n `,t.appendChild(o)})),t.addEventListener("click",(e=>{const t=e.target;if(t.closest(".play-icon")){const e=t.closest(".video");if(e){const t=e.getAttribute("data-video-url");t&&function(e){const t=document.querySelector("#video-player"),n=t.querySelector("#video-frame"),r=t.querySelector(".close");t&&n&&r&&(n.src=e,t.style.display="flex",r.addEventListener("click",(()=>{t.style.display="none",n.src=""})),t.addEventListener("click",(e=>{e.target===t&&(t.style.display="none",n.src="")})))}(t)}}})),h=r.docs[r.docs.length-1],!0)}catch(e){return console.error("Error loading educational videos:",e),!1}}))}},987:function(e,t,n){"use strict";var r=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(i,s){function o(e){try{c(r.next(e))}catch(e){s(e)}}function a(e){try{c(r.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,a)}c((r=r.apply(e,t||[])).next())}))},i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.initFaqs=function(e){e.innerHTML='\n <div class="faqs">\n <div class="section-heading">Frequently Asked Questions</div>\n <div class="faq-list"></div>\n </div>\n ';const t=e.querySelector(".faqs"),n=e.querySelector(".section-heading"),i=e.querySelector(".faq-list");t&&n&&i&&function(e){r(this,void 0,void 0,(function*(){const t=e.querySelector(".faq-list");if(t)try{const e=yield(0,s.getFirestoreInstance)();let n=(0,o.query)((0,o.collection)(e,c),(0,o.orderBy)("question","asc"));const r=yield(0,o.getDocs)(n);if(r.empty)return void console.log("No FAQs available");r.forEach((e=>{var n,r;const i=e.data();console.log("faqData - ",i);const s=document.createElement("div");s.classList.add("faq"),s.innerHTML=`\n <div class="content-wrapper">\n <div class="question">${null===(n=i.question)||void 0===n?void 0:n.trim()}</div>\n <div class="answer">${null===(r=i.answer)||void 0===r?void 0:r.trim()}</div>\n </div>\n <div class="expand-collapse-wrapper">\n <img src="${a.default}" alt="Expand/Collapse" />\n </div>\n `,t.appendChild(s)})),t.addEventListener("click",(e=>{const t=e.target;if(t.closest(".expand-collapse-wrapper")){const e=t.closest(".faq");e.classList.contains("expand")?e.classList.remove("expand"):e.classList.add("expand")}}))}catch(e){console.error("Error loading faqs:",e)}}))}(e)};const s=n(487),o=n(815),a=i(n(573)),c="faqs"},487:function(e,t,n){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),i=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&r(t,e,n);return i(t,e),t},o=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(i,s){function o(e){try{c(r.next(e))}catch(e){s(e)}}function a(e){try{c(r.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,a)}c((r=r.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.getFirestoreInstance=function(){return o(this,void 0,void 0,(function*(){if(!u){const{getFirestore:e}=yield Promise.resolve().then((()=>s(n(815)))),t=(0,a.initializeApp)(c);u=e(t)}return u}))},t.getFirebaseFunctions=function(){return o(this,void 0,void 0,(function*(){if(!l){const{getFunctions:e}=yield Promise.resolve().then((()=>s(n(619)))),t=(0,a.initializeApp)(c);l=e(t)}return l}))};const a=n(577),c={apiKey:"AIzaSyAdZy_OGph3BeMs0CqwjYkV7NNQR40MjJQ",authDomain:"superkreatives-product-data.firebaseapp.com",projectId:"superkreatives-product-data",storageBucket:"superkreatives-product-data.firebasestorage.app",messagingSenderId:"942901361121",appId:"1:942901361121:web:f17909f805333fd79f7aa0"};let u=null,l=null},536:function(e,t,n){"use strict";var r=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(i,s){function o(e){try{c(r.next(e))}catch(e){s(e)}}function a(e){try{c(r.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,a)}c((r=r.apply(e,t||[])).next())}))},i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.initFreeGuides=function(e){let t=`\n <div class="free-guides">\n <div class="section-heading">Free guides</div>\n <div class="free-guides-form">\n <div class="icon-wrapper">\n <img src="${a.default}" alt="Free guides icon"/>\n </div>\n <div class="form-wrapper">\n <div class="info">Grab your free guide for first-time <br/>homebuyers today!</div>\n <div class="fields">\n <input type="text" class="name-field" placeholder="Name" />\n <input type="email" class="email-field" placeholder="Email" />\n <div class="submit-button disabled">Yes, I want this</div>\n </div>\n <div class="consent-wrapper">\n <input type="checkbox" id="consent-checkbox" name="consent" value="Promotional emails consent">\n <label for="consent-checkbox">I consent to use my details here for future promotional emails.</label>\n </div>\n </div>\n </div>\n </div>\n `;e.innerHTML=t;const n=e.querySelector(".free-guides-form .form-wrapper"),i=e.querySelector(".free-guides-form .fields"),c=e.querySelector(".free-guides-form .consent-wrapper"),u=e.querySelector(".free-guides-form .name-field"),l=e.querySelector(".free-guides-form .email-field"),h=e.querySelector(".free-guides-form #consent-checkbox"),d=e.querySelector(".free-guides-form .submit-button"),f=()=>r(this,void 0,void 0,(function*(){const e=u.value,t=l.value;e&&t&&g(t)?d.classList.remove("disabled"):d.classList.add("disabled")})),g=e=>/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(e);u.addEventListener("change",(e=>{f()})),l.addEventListener("change",(e=>{f()})),h.addEventListener("change",(e=>{f()})),d.addEventListener("click",(e=>r(this,void 0,void 0,(function*(){const e=u.value.trim(),t=l.value.trim(),r=h.checked;try{d.textContent="Processing...",d.disabled=!0,d.classList.toggle("disabled");const a=yield(0,o.getFirebaseFunctions)(),u=(0,s.httpsCallable)(a,"sendGuideEmail"),l=(yield u({name:e,email:t,consent:r,file:"test-1.pdf"})).data;if(l.success){i.remove(),c.remove();const e=document.createElement("div");e.classList.add("status"),e.classList.add("success"),e.textContent="Your homebuyer free guide has been emailed to you!",n.appendChild(e)}else{d.textContent="Yes, I want this",d.disabled=!1,d.classList.toggle("disabled");const e=document.createElement("div");e.classList.add("status"),e.classList.add("error"),e.textContent=l.message,n.appendChild(e)}}catch(e){d.textContent="Yes, I want this",d.disabled=!1,d.classList.toggle("disabled"),console.error("Error sending email:",e);const t=e,r=document.createElement("div");r.classList.add("status"),r.classList.add("error"),r.textContent=t,n.appendChild(r)}}))))};const s=n(619),o=n(487),a=i(n(765))},137:function(e,t,n){"use strict";var r=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(i,s){function o(e){try{c(r.next(e))}catch(e){s(e)}}function a(e){try{c(r.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,a)}c((r=r.apply(e,t||[])).next())}))},i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.initMarketTrendVideos=function(e){e.innerHTML='\n <div class="market-trend-videos">\n <div class="section-heading">Market Trend Videos</div>\n <div class="videos"></div>\n <div id="video-player" class="modal" style="display: none;">\n <div class="modal-content">\n <span class="close">&times;</span>\n <iframe id="video-frame" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>\n </div>\n </div>\n </div>\n ';const t=e.querySelector(".market-trend-videos"),n=e.querySelector(".section-heading"),i=e.querySelector(".videos");if(!t||!n||!i)return;d(e);let s=!1,o=!0;window.addEventListener("scroll",(e=>{let t=0;return(...n)=>{const r=Date.now();r-t>=200&&(t=r,e(...n))}})((()=>r(this,void 0,void 0,(function*(){const t=i.getBoundingClientRect().bottom<=window.innerHeight+100;if(!s&&o&&t){s=!0;try{const t=yield d(e);o=t}catch(e){console.error("Error loading market trend videos:",e)}finally{s=!1}}})))))};const s=n(487),o=n(815),a=i(n(757)),c=n(185),u="market_trend_videos",l=9;let h=null;function d(e){return r(this,void 0,void 0,(function*(){const t=e.querySelector(".videos");if(!t)return!1;try{const e=yield(0,s.getFirestoreInstance)();let n=(0,o.query)((0,o.collection)(e,u),(0,o.orderBy)("date","desc"),(0,o.limit)(l));h&&(n=(0,o.query)(n,(0,o.startAfter)(h)));const r=yield(0,o.getDocs)(n);return r.empty?(console.log("No more videos to load"),!1):(r.forEach((e=>{var n,r,i;const s=e.data();console.log("videoData - ",s);const o=document.createElement("div");o.classList.add("video"),o.setAttribute("data-video-url",s.video_link),o.innerHTML=`\n <div class="thumbnail" style="background-image: url('${s.img_link}');">\n <div class="thumbnail-overlay" style="">\n <div class="play-icon">\n <img src="${a.default}" alt="Play Video" />\n </div>\n </div>\n </div>\n <div class="date">${(0,c.formatDate)(null===(n=s.date)||void 0===n?void 0:n.trim())}</div>\n <div class="title">${null===(r=s.headline)||void 0===r?void 0:r.trim()}</div>\n <div class="source">Source: <span>${null===(i=s.source)||void 0===i?void 0:i.trim()}</span></div>\n `,t.appendChild(o)})),t.addEventListener("click",(e=>{const t=e.target;if(t.closest(".play-icon")){const e=t.closest(".video");if(e){const t=e.getAttribute("data-video-url");t&&function(e){const t=document.querySelector("#video-player"),n=t.querySelector("#video-frame"),r=t.querySelector(".close");t&&n&&r&&(n.src=e,t.style.display="flex",r.addEventListener("click",(()=>{t.style.display="none",n.src=""})),t.addEventListener("click",(e=>{e.target===t&&(t.style.display="none",n.src="")})))}(t)}}})),h=r.docs[r.docs.length-1],!0)}catch(e){return console.error("Error loading trending videos:",e),!1}}))}},0:function(e,t,n){"use strict";var r=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(i,s){function o(e){try{c(r.next(e))}catch(e){s(e)}}function a(e){try{c(r.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,a)}c((r=r.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.initMortgageCalendar=function(e){e.innerHTML='\n <div class="mortgage-calender">\n <div class="section-heading">Mortgage Calender</div>\n <div class="filters">\n <div class="filter selected">Interest Rate</div>\n <div class="filter">Gross domestic product, income, and expenditure</div>\n <div class="filter">Housing</div>\n </div>\n <div class="calendar-content">\n <div class="calendar-header"></div>\n <div class="calendar-events"></div>\n </div>\n </div>\n ';const t=e.querySelector(".mortgage-calender"),n=e.querySelector(".section-heading"),i=e.querySelector(".filters"),s=e.querySelector(".calendar-events"),o=e.querySelector(".calendar-header");if(!t||!n||!s)return;h(e);let a=!1,c=!0;window.addEventListener("scroll",(e=>{let t=0;return(...n)=>{const r=Date.now();r-t>=200&&(t=r,e(...n))}})((()=>r(this,void 0,void 0,(function*(){const t=s.getBoundingClientRect().bottom<=window.innerHeight+100;if(!a&&c&&t){a=!0;try{c=yield h(e)}catch(e){console.error("Error loading mortgage calendar events:",e)}finally{a=!1}}}))))),i.addEventListener("click",(t=>{const n=t.target;n.closest(".filter")&&(i.querySelectorAll(".filter").forEach((e=>{e.classList.remove("selected")})),n.classList.add("selected"),l=n.textContent?n.textContent:"",u=null,o.classList.remove("show","three-col-layout"),s.innerHTML="",o.innerHTML="",h(e))}))};const i=n(487),s=n(815),o=n(185),a="mortgage_calender",c=9;let u=null,l="Interest Rate";function h(e){return r(this,void 0,void 0,(function*(){const t=e.querySelector(".calendar-header"),n=e.querySelector(".calendar-events");if(!t||!n)return!1;try{const e=yield(0,i.getFirestoreInstance)();let r=(0,s.query)((0,s.collection)(e,a),(0,s.orderBy)("schedule_date","asc"),(0,s.limit)(c));l&&(r=(0,s.query)(r,(0,s.where)("category","==",l))),u&&(r=(0,s.query)(r,(0,s.startAfter)(u)));const h=yield(0,s.getDocs)(r);return h.empty?(console.log("No more calendar events to load"),!1):(h.forEach((e=>{var r,i,s,a,c,u,h,d;const f=e.data(),g=document.createElement("div");g.classList.add("calendar-event"),t.classList.remove("show","three-col-layout"),"Interest Rate"===l?(t.classList.add("show"),t.innerHTML='\n <div class="calendar-header-col">Interest Rate</div>\n <div class="calendar-header-col">Schedule Date</div>\n ',g.innerHTML=`\n <div class="calendar-event-col">${null===(r=f.title)||void 0===r?void 0:r.trim()}</div>\n <div class="calendar-event-col date">${(0,o.formatDate)(null===(i=f.schedule_date)||void 0===i?void 0:i.trim())}</div>\n `):"Gross domestic product, income, and expenditure"===l?(t.classList.add("show","three-col-layout"),t.innerHTML='\n <div class="calendar-header-col">Gross domestic product, income, and expenditure</div>\n <div class="calendar-header-col">Release Date</div>\n <div class="calendar-header-col">Reference Period</div>\n ',g.classList.add("three-col-layout"),g.innerHTML=`\n <div class="calendar-event-col">${null===(s=f.title)||void 0===s?void 0:s.trim()}</div>\n <div class="calendar-event-col date">${(0,o.formatDate)(null===(a=f.release_date)||void 0===a?void 0:a.trim())}</div>\n <div class="calendar-event-col date">${(0,o.formatDate)(null===(c=f.reference_period)||void 0===c?void 0:c.trim())}</div>\n `):"Housing"===l&&(t.classList.add("show","three-col-layout"),t.innerHTML='\n <div class="calendar-header-col">Housing</div>\n <div class="calendar-header-col">Release Date</div>\n <div class="calendar-header-col">Last Published Date</div>\n ',g.classList.add("three-col-layout"),g.innerHTML=`\n <div class="calendar-event-col">${null===(u=f.title)||void 0===u?void 0:u.trim()}</div>\n <div class="calendar-event-col date">${(0,o.formatDate)(null===(h=f.release_date)||void 0===h?void 0:h.trim())}</div>\n <div class="calendar-event-col date">${(0,o.formatDate)(null===(d=f.last_published_date)||void 0===d?void 0:d.trim())}</div>\n `),n.appendChild(g)})),u=h.docs[h.docs.length-1],!0)}catch(e){return console.error("Error loading mortgage calendar events:",e),!1}}))}},533:function(e,t,n){"use strict";var r=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(i,s){function o(e){try{c(r.next(e))}catch(e){s(e)}}function a(e){try{c(r.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,a)}c((r=r.apply(e,t||[])).next())}))},i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.initMortgageGlossary=function(e){e.innerHTML=`\n <div class="mortgage-glossary">\n <div class="header-wrapper">\n <div class="section-heading">Mortgage Glossary</div>\n <div class="glossary-controls">\n <div class="arrow-left"><img src="${a.default}" alt="Expand/Collapse" /></div>\n <div class="alphabets"></div>\n <div class="arrow-right"><img src="${c.default}" alt="Expand/Collapse" /></div>\n </div>\n </div>\n <div class="glossary-list"></div>\n </div>\n `;const t=e.querySelector(".mortgage-glossary"),n=e.querySelector(".header-wrapper"),i=e.querySelector(".glossary-list");t&&n&&i&&function(e){r(this,void 0,void 0,(function*(){const t=e.querySelector(".mortgage-glossary"),n=e.querySelector(".glossary-list"),r=e.querySelector(".alphabets");if(n)try{const e=yield(0,s.getFirestoreInstance)();let i=(0,o.query)((0,o.collection)(e,u),(0,o.orderBy)("term","asc"));const a=yield(0,o.getDocs)(i);if(a.empty)return void console.log("No mortgage glossary available");let c={};a.forEach((e=>{var t,r;const i=e.data(),s=i.term.charAt(0).toUpperCase();let o=!1;c[s]||(c[s]=[],o=!0),c[s].push(i);const a=document.createElement("div");a.classList.add("glossary-item"),o&&a.setAttribute("data-glosssary-control-letter",s),a.innerHTML=`\n <div class="term">${null===(t=i.term)||void 0===t?void 0:t.trim()}</div>\n <div class="definition">${null===(r=i.definition)||void 0===r?void 0:r.trim()}</div>\n `,n.appendChild(a)})),console.log(c," - groupedGlossary");const l=Object.keys(c);let h="";l.forEach((e=>{h+=`<div class="alphabet">${e}</div>`})),r.innerHTML=h,t.addEventListener("click",(e=>{const t=e.target;if(t.closest(".arrow-right"))r.scrollLeft+=150;else if(t.closest(".arrow-left "))r.scrollLeft-=150;else if(t.closest(".alphabet")){const e=document.querySelector(`[data-glosssary-control-letter="${t.textContent}"]`);if(e){const t=e.getBoundingClientRect().top+window.scrollY,n=window.innerWidth<992?200:275;window.scrollTo({top:t-n,behavior:"smooth"})}}}))}catch(e){console.error("Error loading mortgage glossary:",e)}}))}(e)};const s=n(487),o=n(815),a=i(n(648)),c=i(n(415)),u="mortgage_glossary"},242:function(e,t,n){"use strict";var r=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(i,s){function o(e){try{c(r.next(e))}catch(e){s(e)}}function a(e){try{c(r.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,a)}c((r=r.apply(e,t||[])).next())}))},i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.initMortgageNews=function(e){e.innerHTML='\n <div class="mortgage-news">\n <div class="section-heading">Mortgage News</div>\n <div class="mortgage-news-list"></div>\n </div>\n ';const t=e.querySelector(".mortgage-news"),n=e.querySelector(".section-heading"),i=e.querySelector(".mortgage-news-list");if(!t||!n||!i)return;d(e);let s=!1,o=!0;window.addEventListener("scroll",(e=>{let t=0;return(...n)=>{const r=Date.now();r-t>=200&&(t=r,e(...n))}})((()=>r(this,void 0,void 0,(function*(){const t=i.getBoundingClientRect().bottom<=window.innerHeight+100;if(!s&&o&&t){s=!0;try{const t=yield d(e);o=t}catch(e){console.error("Error loading mortgage news:",e)}finally{s=!1}}})))))};const s=n(487),o=n(815),a=n(185),c=i(n(501)),u="mortgage_news",l=9;let h=null;function d(e){return r(this,void 0,void 0,(function*(){const t=e.querySelector(".mortgage-news-list");if(!t)return!1;try{const e=yield(0,s.getFirestoreInstance)();let n=(0,o.query)((0,o.collection)(e,u),(0,o.orderBy)("date","desc"),(0,o.limit)(l));h&&(n=(0,o.query)(n,(0,o.startAfter)(h)));const r=yield(0,o.getDocs)(n);return r.empty?(console.log("No more mortgage news to load"),!1):(r.forEach((e=>{const n=e.data();console.log("mortgageNewsData - ",n);const r=document.createElement("div");r.classList.add("mortgage-news-item"),r.innerHTML=`\n <div class="thumbnail" style="background-image: url('${n.img_link}');"></div>\n <div class="date">${(0,a.formatDate)(n.date)}</div>\n <div class="title">${n.headline}</div>\n <a class="read-more-link" href="${n.source}" target="_blank">\n Read More\n <div class="read-more-icon">\n <img src="${c.default}" alt="Read More" />\n </div>\n </a>\n `,t.appendChild(r)})),h=r.docs[r.docs.length-1],!0)}catch(e){return console.error("Error loading mortgage news:",e),!1}}))}},659:function(e,t,n){"use strict";var r=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(i,s){function o(e){try{c(r.next(e))}catch(e){s(e)}}function a(e){try{c(r.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,a)}c((r=r.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.initResearchArticles=function(e){e.innerHTML='\n <div class="research-articles">\n <div class="section-heading">Research Articles</div>\n <div class="research-articles-list"></div>\n </div>\n ';const t=e.querySelector(".research-articles"),n=e.querySelector(".section-heading"),i=e.querySelector(".research-articles-list");if(!t||!n||!i)return;l(e);let s=!1,o=!0;window.addEventListener("scroll",(e=>{let t=0;return(...n)=>{const r=Date.now();r-t>=200&&(t=r,e(...n))}})((()=>r(this,void 0,void 0,(function*(){const t=i.getBoundingClientRect().bottom<=window.innerHeight+100;if(!s&&o&&t){s=!0;try{const t=yield l(e);o=t}catch(e){console.error("Error loading research articles:",e)}finally{s=!1}}})))))};const i=n(487),s=n(815),o=n(185),a="research_articles",c=9;let u=null;function l(e){return r(this,void 0,void 0,(function*(){const t=e.querySelector(".research-articles-list");if(!t)return!1;try{const e=yield(0,i.getFirestoreInstance)();let n=(0,s.query)((0,s.collection)(e,a),(0,s.orderBy)("date","desc"),(0,s.limit)(c));u&&(n=(0,s.query)(n,(0,s.startAfter)(u)));const r=yield(0,s.getDocs)(n);return r.empty?(console.log("No more research articles to load"),!1):(r.forEach((e=>{var n,r;const i=e.data();console.log("researchArticleData - ",i);const s=document.createElement("div");s.classList.add("research-article"),s.innerHTML=`\n <div class="thumbnail" style="background-image: url('${i.img_link}');"></div>\n <div class="date">${(0,o.formatDate)(i.date)}</div>\n <div class="title">${null===(n=i.headline)||void 0===n?void 0:n.trim()}</div>\n <div class="description">${null===(r=i.description)||void 0===r?void 0:r.trim()}</div>\n <a class="read-more-link" href="${i.source}" target="_blank">Read More</a>\n `,t.appendChild(s)})),u=r.docs[r.docs.length-1],!0)}catch(e){return console.error("Error loading research articles:",e),!1}}))}},185:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.calculateMortgage=function(e,t,n,r){const i=t/100/2,s=Math.pow(1+i,2/12)-1,o=12*n,a=e*(s*Math.pow(1+s,o))/(Math.pow(1+s,o)-1);let c;switch(r){case"weekly":c=12*a/52;break;case"biweekly":c=12*a/26;break;default:c=a}return c},t.formatDate=function(e){const t=new Date(e);return new Intl.DateTimeFormat("en-US",{month:"long",day:"numeric",year:"numeric"}).format(t)}},648:(e,t,n)=>{"use strict";e.exports=n.p+"94d7adc1c3f7df08c5dc.svg"},415:(e,t,n)=>{"use strict";e.exports=n.p+"0134ef940feb41dedc27.svg"},573:(e,t,n)=>{"use strict";e.exports=n.p+"05e0aac3f5f644c344d6.svg"},501:(e,t,n)=>{"use strict";e.exports=n.p+"7acafcdacd8c7574dbdc.svg"},765:(e,t,n)=>{"use strict";e.exports=n.p+"d686a45650560ddaa773.svg"},757:(e,t,n)=>{"use strict";e.exports=n.p+"dec0b8717bf0d582857b.svg"},148:(e,t,n)=>{"use strict";n.r(t),n.d(t,{deleteDB:()=>m,openDB:()=>p,unwrap:()=>g,wrap:()=>f});const r=(e,t)=>t.some((t=>e instanceof t));let i,s;const o=new WeakMap,a=new WeakMap,c=new WeakMap,u=new WeakMap,l=new WeakMap;let h={get(e,t,n){if(e instanceof IDBTransaction){if("done"===t)return a.get(e);if("objectStoreNames"===t)return e.objectStoreNames||c.get(e);if("store"===t)return n.objectStoreNames[1]?void 0:n.objectStore(n.objectStoreNames[0])}return f(e[t])},set:(e,t,n)=>(e[t]=n,!0),has:(e,t)=>e instanceof IDBTransaction&&("done"===t||"store"===t)||t in e};function d(e){return"function"==typeof e?(t=e)!==IDBDatabase.prototype.transaction||"objectStoreNames"in IDBTransaction.prototype?(s||(s=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])).includes(t)?function(...e){return t.apply(g(this),e),f(o.get(this))}:function(...e){return f(t.apply(g(this),e))}:function(e,...n){const r=t.call(g(this),e,...n);return c.set(r,e.sort?e.sort():[e]),f(r)}:(e instanceof IDBTransaction&&function(e){if(a.has(e))return;const t=new Promise(((t,n)=>{const r=()=>{e.removeEventListener("complete",i),e.removeEventListener("error",s),e.removeEventListener("abort",s)},i=()=>{t(),r()},s=()=>{n(e.error||new DOMException("AbortError","AbortError")),r()};e.addEventListener("complete",i),e.addEventListener("error",s),e.addEventListener("abort",s)}));a.set(e,t)}(e),r(e,i||(i=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction]))?new Proxy(e,h):e);var t}function f(e){if(e instanceof IDBRequest)return function(e){const t=new Promise(((t,n)=>{const r=()=>{e.removeEventListener("success",i),e.removeEventListener("error",s)},i=()=>{t(f(e.result)),r()},s=()=>{n(e.error),r()};e.addEventListener("success",i),e.addEventListener("error",s)}));return t.then((t=>{t instanceof IDBCursor&&o.set(t,e)})).catch((()=>{})),l.set(t,e),t}(e);if(u.has(e))return u.get(e);const t=d(e);return t!==e&&(u.set(e,t),l.set(t,e)),t}const g=e=>l.get(e);function p(e,t,{blocked:n,upgrade:r,blocking:i,terminated:s}={}){const o=indexedDB.open(e,t),a=f(o);return r&&o.addEventListener("upgradeneeded",(e=>{r(f(o.result),e.oldVersion,e.newVersion,f(o.transaction),e)})),n&&o.addEventListener("blocked",(e=>n(e.oldVersion,e.newVersion,e))),a.then((e=>{s&&e.addEventListener("close",(()=>s())),i&&e.addEventListener("versionchange",(e=>i(e.oldVersion,e.newVersion,e)))})).catch((()=>{})),a}function m(e,{blocked:t}={}){const n=indexedDB.deleteDatabase(e);return t&&n.addEventListener("blocked",(e=>t(e.oldVersion,e))),f(n).then((()=>{}))}const y=["get","getKey","getAll","getAllKeys","count"],v=["put","add","delete","clear"],w=new Map;function b(e,t){if(!(e instanceof IDBDatabase)||t in e||"string"!=typeof t)return;if(w.get(t))return w.get(t);const n=t.replace(/FromIndex$/,""),r=t!==n,i=v.includes(n);if(!(n in(r?IDBIndex:IDBObjectStore).prototype)||!i&&!y.includes(n))return;const s=async function(e,...t){const s=this.transaction(e,i?"readwrite":"readonly");let o=s.store;return r&&(o=o.index(t.shift())),(await Promise.all([o[n](...t),i&&s.done]))[0]};return w.set(t,s),s}var _;_=h,h={..._,get:(e,t,n)=>b(e,t)||_.get(e,t,n),has:(e,t)=>!!b(e,t)||_.has(e,t)}}},t={};function n(r){var i=t[r];if(void 0!==i)return i.exports;var s=t[r]={exports:{}};return e[r].call(s.exports,s,s.exports,n),s.exports}n.d=(e,t)=>{for(var r in t)n.o(t,r)&&!n.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},n.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),n.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},(()=>{var e;n.g.importScripts&&(e=n.g.location+"");var t=n.g.document;if(!e&&t&&(t.currentScript&&"SCRIPT"===t.currentScript.tagName.toUpperCase()&&(e=t.currentScript.src),!e)){var r=t.getElementsByTagName("script");if(r.length)for(var i=r.length-1;i>-1&&(!e||!/^http(s?):/.test(e));)e=r[i--].src}if(!e)throw new Error("Automatic publicPath is not supported in this browser");e=e.replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/"),n.p=e})();var r={};return(()=>{"use strict";var e=r;Object.defineProperty(e,"__esModule",{value:!0}),e.init=function(e){var n;const r=document.getElementById(e.containerId);if(r)switch(e.product){case"calculator":(0,t.initCalculator)(r,(null===(n=e.options)||void 0===n?void 0:n.applyUrl)||"");break;case"cockpit":(0,l.initCockpit)(r);break;case"educational-videos":(0,u.initEducationalVideos)(r);break;case"faqs":(0,s.initFaqs)(r);break;case"free-guides":(0,h.initFreeGuides)(r);break;case"market-trend-videos":(0,i.initMarketTrendVideos)(r);break;case"mortgage-calender":(0,d.initMortgageCalendar)(r);break;case"mortgage-glossary":(0,c.initMortgageGlossary)(r);break;case"mortgage-news":(0,a.initMortgageNews)(r);break;case"research-articles":(0,o.initResearchArticles)(r);break;default:console.error(`Unknown product: ${e.product}`)}else console.error("Container not found")},n(264);const t=n(846),i=n(137),s=n(987),o=n(659),a=n(242),c=n(533),u=n(260),l=n(958),h=n(536),d=n(0)})(),r})()));
2
+ !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define("MortgageCalculator",[],t):"object"==typeof exports?exports.MortgageCalculator=t():e.MortgageCalculator=t()}(self,(()=>(()=>{var e={199:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(319),i=n(844),s=n(336),o=n(148);class a{constructor(e){this.container=e}getPlatformInfoString(){return this.container.getProviders().map((e=>{if(function(e){const t=e.getComponent();return"VERSION"===(null==t?void 0:t.type)}(e)){const t=e.getImmediate();return`${t.library}/${t.version}`}return null})).filter((e=>e)).join(" ")}}const c="@firebase/app",u="0.10.17",l=new i.Logger("@firebase/app"),h="@firebase/app-compat",d="@firebase/analytics-compat",f="@firebase/analytics",g="@firebase/app-check-compat",p="@firebase/app-check",m="@firebase/auth",y="@firebase/auth-compat",v="@firebase/database",w="@firebase/data-connect",b="@firebase/database-compat",_="@firebase/functions",I="@firebase/functions-compat",E="@firebase/installations",T="@firebase/installations-compat",S="@firebase/messaging",x="@firebase/messaging-compat",C="@firebase/performance",D="@firebase/performance-compat",A="@firebase/remote-config",k="@firebase/remote-config-compat",N="@firebase/storage",L="@firebase/storage-compat",O="@firebase/firestore",M="@firebase/vertexai",R="@firebase/firestore-compat",P="firebase",F="[DEFAULT]",V={[c]:"fire-core",[h]:"fire-core-compat",[f]:"fire-analytics",[d]:"fire-analytics-compat",[p]:"fire-app-check",[g]:"fire-app-check-compat",[m]:"fire-auth",[y]:"fire-auth-compat",[v]:"fire-rtdb",[w]:"fire-data-connect",[b]:"fire-rtdb-compat",[_]:"fire-fn",[I]:"fire-fn-compat",[E]:"fire-iid",[T]:"fire-iid-compat",[S]:"fire-fcm",[x]:"fire-fcm-compat",[C]:"fire-perf",[D]:"fire-perf-compat",[A]:"fire-rc",[k]:"fire-rc-compat",[N]:"fire-gcs",[L]:"fire-gcs-compat",[O]:"fire-fst",[R]:"fire-fst-compat",[M]:"fire-vertex","fire-js":"fire-js",[P]:"fire-js-all"},q=new Map,B=new Map,U=new Map;function j(e,t){try{e.container.addComponent(t)}catch(n){l.debug(`Component ${t.name} failed to register with FirebaseApp ${e.name}`,n)}}function $(e){const t=e.name;if(U.has(t))return l.debug(`There were multiple attempts to register component ${t}.`),!1;U.set(t,e);for(const t of q.values())j(t,e);for(const t of B.values())j(t,e);return!0}function z(e,t){const n=e.container.getProvider("heartbeat").getImmediate({optional:!0});return n&&n.triggerHeartbeat(),e.container.getProvider(t)}function G(e){return void 0!==e.options}const K=new s.ErrorFactory("app","Firebase",{"no-app":"No Firebase App '{$appName}' has been created - call initializeApp() first","bad-app-name":"Illegal App name: '{$appName}'","duplicate-app":"Firebase App named '{$appName}' already exists with different options or config","app-deleted":"Firebase App named '{$appName}' already deleted","server-app-deleted":"Firebase Server App has been deleted","no-options":"Need to provide options, when not being deployed to hosting via source.","invalid-app-argument":"firebase.{$appName}() takes either no argument or a Firebase App instance.","invalid-log-argument":"First argument to `onLog` must be null or a function.","idb-open":"Error thrown when opening IndexedDB. Original error: {$originalErrorMessage}.","idb-get":"Error thrown when reading from IndexedDB. Original error: {$originalErrorMessage}.","idb-set":"Error thrown when writing to IndexedDB. Original error: {$originalErrorMessage}.","idb-delete":"Error thrown when deleting from IndexedDB. Original error: {$originalErrorMessage}.","finalization-registry-not-supported":"FirebaseServerApp deleteOnDeref field defined but the JS runtime does not support FinalizationRegistry.","invalid-server-app-environment":"FirebaseServerApp is not for use in browser environments."});class Q{constructor(e,t,n){this._isDeleted=!1,this._options=Object.assign({},e),this._config=Object.assign({},t),this._name=t.name,this._automaticDataCollectionEnabled=t.automaticDataCollectionEnabled,this._container=n,this.container.addComponent(new r.Component("app",(()=>this),"PUBLIC"))}get automaticDataCollectionEnabled(){return this.checkDestroyed(),this._automaticDataCollectionEnabled}set automaticDataCollectionEnabled(e){this.checkDestroyed(),this._automaticDataCollectionEnabled=e}get name(){return this.checkDestroyed(),this._name}get options(){return this.checkDestroyed(),this._options}get config(){return this.checkDestroyed(),this._config}get container(){return this._container}get isDeleted(){return this._isDeleted}set isDeleted(e){this._isDeleted=e}checkDestroyed(){if(this.isDeleted)throw K.create("app-deleted",{appName:this._name})}}class H extends Q{constructor(e,t,n,r){const i=void 0!==t.automaticDataCollectionEnabled&&t.automaticDataCollectionEnabled,s={name:n,automaticDataCollectionEnabled:i};void 0!==e.apiKey?super(e,s,r):super(e.options,s,r),this._serverConfig=Object.assign({automaticDataCollectionEnabled:i},t),this._finalizationRegistry=null,"undefined"!=typeof FinalizationRegistry&&(this._finalizationRegistry=new FinalizationRegistry((()=>{this.automaticCleanup()}))),this._refCount=0,this.incRefCount(this._serverConfig.releaseOnDeref),this._serverConfig.releaseOnDeref=void 0,t.releaseOnDeref=void 0,X(c,u,"serverapp")}toJSON(){}get refCount(){return this._refCount}incRefCount(e){this.isDeleted||(this._refCount++,void 0!==e&&null!==this._finalizationRegistry&&this._finalizationRegistry.register(e,this))}decRefCount(){return this.isDeleted?0:--this._refCount}automaticCleanup(){J(this)}get settings(){return this.checkDestroyed(),this._serverConfig}checkDestroyed(){if(this.isDeleted)throw K.create("server-app-deleted")}}function W(e,t={}){let n=e;"object"!=typeof t&&(t={name:t});const i=Object.assign({name:F,automaticDataCollectionEnabled:!1},t),o=i.name;if("string"!=typeof o||!o)throw K.create("bad-app-name",{appName:String(o)});if(n||(n=s.getDefaultAppConfig()),!n)throw K.create("no-options");const a=q.get(o);if(a){if(s.deepEqual(n,a.options)&&s.deepEqual(i,a.config))return a;throw K.create("duplicate-app",{appName:o})}const c=new r.ComponentContainer(o);for(const e of U.values())c.addComponent(e);const u=new Q(n,i,c);return q.set(o,u),u}async function J(e){let t=!1;const n=e.name;q.has(n)?(t=!0,q.delete(n)):B.has(n)&&e.decRefCount()<=0&&(B.delete(n),t=!0),t&&(await Promise.all(e.container.getProviders().map((e=>e.delete()))),e.isDeleted=!0)}function X(e,t,n){var i;let s=null!==(i=V[e])&&void 0!==i?i:e;n&&(s+=`-${n}`);const o=s.match(/\s|\//),a=t.match(/\s|\//);if(o||a){const e=[`Unable to register library "${s}" with version "${t}":`];return o&&e.push(`library name "${s}" contains illegal characters (whitespace or "/")`),o&&a&&e.push("and"),a&&e.push(`version name "${t}" contains illegal characters (whitespace or "/")`),void l.warn(e.join(" "))}$(new r.Component(`${s}-version`,(()=>({library:s,version:t})),"VERSION"))}const Y="firebase-heartbeat-store";let Z=null;function ee(){return Z||(Z=o.openDB("firebase-heartbeat-database",1,{upgrade:(e,t)=>{if(0===t)try{e.createObjectStore(Y)}catch(e){console.warn(e)}}}).catch((e=>{throw K.create("idb-open",{originalErrorMessage:e.message})}))),Z}async function te(e,t){try{const n=(await ee()).transaction(Y,"readwrite"),r=n.objectStore(Y);await r.put(t,ne(e)),await n.done}catch(e){if(e instanceof s.FirebaseError)l.warn(e.message);else{const t=K.create("idb-set",{originalErrorMessage:null==e?void 0:e.message});l.warn(t.message)}}}function ne(e){return`${e.name}!${e.options.appId}`}class re{constructor(e){this.container=e,this._heartbeatsCache=null;const t=this.container.getProvider("app").getImmediate();this._storage=new se(t),this._heartbeatsCachePromise=this._storage.read().then((e=>(this._heartbeatsCache=e,e)))}async triggerHeartbeat(){var e,t;try{const n=this.container.getProvider("platform-logger").getImmediate().getPlatformInfoString(),r=ie();if(null==(null===(e=this._heartbeatsCache)||void 0===e?void 0:e.heartbeats)&&(this._heartbeatsCache=await this._heartbeatsCachePromise,null==(null===(t=this._heartbeatsCache)||void 0===t?void 0:t.heartbeats)))return;if(this._heartbeatsCache.lastSentHeartbeatDate===r||this._heartbeatsCache.heartbeats.some((e=>e.date===r)))return;return this._heartbeatsCache.heartbeats.push({date:r,agent:n}),this._heartbeatsCache.heartbeats=this._heartbeatsCache.heartbeats.filter((e=>{const t=new Date(e.date).valueOf();return Date.now()-t<=2592e6})),this._storage.overwrite(this._heartbeatsCache)}catch(e){l.warn(e)}}async getHeartbeatsHeader(){var e;try{if(null===this._heartbeatsCache&&await this._heartbeatsCachePromise,null==(null===(e=this._heartbeatsCache)||void 0===e?void 0:e.heartbeats)||0===this._heartbeatsCache.heartbeats.length)return"";const t=ie(),{heartbeatsToSend:n,unsentEntries:r}=function(e,t=1024){const n=[];let r=e.slice();for(const i of e){const e=n.find((e=>e.agent===i.agent));if(e){if(e.dates.push(i.date),oe(n)>t){e.dates.pop();break}}else if(n.push({agent:i.agent,dates:[i.date]}),oe(n)>t){n.pop();break}r=r.slice(1)}return{heartbeatsToSend:n,unsentEntries:r}}(this._heartbeatsCache.heartbeats),i=s.base64urlEncodeWithoutPadding(JSON.stringify({version:2,heartbeats:n}));return this._heartbeatsCache.lastSentHeartbeatDate=t,r.length>0?(this._heartbeatsCache.heartbeats=r,await this._storage.overwrite(this._heartbeatsCache)):(this._heartbeatsCache.heartbeats=[],this._storage.overwrite(this._heartbeatsCache)),i}catch(e){return l.warn(e),""}}}function ie(){return(new Date).toISOString().substring(0,10)}class se{constructor(e){this.app=e,this._canUseIndexedDBPromise=this.runIndexedDBEnvironmentCheck()}async runIndexedDBEnvironmentCheck(){return!!s.isIndexedDBAvailable()&&s.validateIndexedDBOpenable().then((()=>!0)).catch((()=>!1))}async read(){if(await this._canUseIndexedDBPromise){const e=await async function(e){try{const t=(await ee()).transaction(Y),n=await t.objectStore(Y).get(ne(e));return await t.done,n}catch(e){if(e instanceof s.FirebaseError)l.warn(e.message);else{const t=K.create("idb-get",{originalErrorMessage:null==e?void 0:e.message});l.warn(t.message)}}}(this.app);return(null==e?void 0:e.heartbeats)?e:{heartbeats:[]}}return{heartbeats:[]}}async overwrite(e){var t;if(await this._canUseIndexedDBPromise){const n=await this.read();return te(this.app,{lastSentHeartbeatDate:null!==(t=e.lastSentHeartbeatDate)&&void 0!==t?t:n.lastSentHeartbeatDate,heartbeats:e.heartbeats})}}async add(e){var t;if(await this._canUseIndexedDBPromise){const n=await this.read();return te(this.app,{lastSentHeartbeatDate:null!==(t=e.lastSentHeartbeatDate)&&void 0!==t?t:n.lastSentHeartbeatDate,heartbeats:[...n.heartbeats,...e.heartbeats]})}}}function oe(e){return s.base64urlEncodeWithoutPadding(JSON.stringify({version:2,heartbeats:e})).length}$(new r.Component("platform-logger",(e=>new a(e)),"PRIVATE")),$(new r.Component("heartbeat",(e=>new re(e)),"PRIVATE")),X(c,u,"node"),X(c,u,"cjs2017"),X("fire-js",""),Object.defineProperty(t,"FirebaseError",{enumerable:!0,get:function(){return s.FirebaseError}}),t.SDK_VERSION="11.1.0",t._DEFAULT_ENTRY_NAME=F,t._addComponent=j,t._addOrOverwriteComponent=function(e,t){e.container.addOrOverwriteComponent(t)},t._apps=q,t._clearComponents=function(){U.clear()},t._components=U,t._getProvider=z,t._isFirebaseApp=G,t._isFirebaseServerApp=function(e){return void 0!==e.settings},t._registerComponent=$,t._removeServiceInstance=function(e,t,n=F){z(e,t).clearInstance(n)},t._serverApps=B,t.deleteApp=J,t.getApp=function(e=F){const t=q.get(e);if(!t&&e===F&&s.getDefaultAppConfig())return W();if(!t)throw K.create("no-app",{appName:e});return t},t.getApps=function(){return Array.from(q.values())},t.initializeApp=W,t.initializeServerApp=function(e,t){if(s.isBrowser()&&!s.isWebWorker())throw K.create("invalid-server-app-environment");let n;void 0===t.automaticDataCollectionEnabled&&(t.automaticDataCollectionEnabled=!1),n=G(e)?e.options:e;const i=Object.assign(Object.assign({},t),n);if(void 0!==i.releaseOnDeref&&delete i.releaseOnDeref,void 0!==t.releaseOnDeref&&"undefined"==typeof FinalizationRegistry)throw K.create("finalization-registry-not-supported",{});const o=""+(a=JSON.stringify(i),[...a].reduce(((e,t)=>Math.imul(31,e)+t.charCodeAt(0)|0),0));var a;const c=B.get(o);if(c)return c.incRefCount(t.releaseOnDeref),c;const u=new r.ComponentContainer(o);for(const e of U.values())u.addComponent(e);const l=new H(n,t,o,u);return B.set(o,l),l},t.onLog=function(e,t){if(null!==e&&"function"!=typeof e)throw K.create("invalid-log-argument");i.setUserLogHandler(e,t)},t.registerVersion=X,t.setLogLevel=function(e){i.setLogLevel(e)}},319:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(336);const i="[DEFAULT]";class s{constructor(e,t){this.name=e,this.container=t,this.component=null,this.instances=new Map,this.instancesDeferred=new Map,this.instancesOptions=new Map,this.onInitCallbacks=new Map}get(e){const t=this.normalizeInstanceIdentifier(e);if(!this.instancesDeferred.has(t)){const e=new r.Deferred;if(this.instancesDeferred.set(t,e),this.isInitialized(t)||this.shouldAutoInitialize())try{const n=this.getOrInitializeService({instanceIdentifier:t});n&&e.resolve(n)}catch(e){}}return this.instancesDeferred.get(t).promise}getImmediate(e){var t;const n=this.normalizeInstanceIdentifier(null==e?void 0:e.identifier),r=null!==(t=null==e?void 0:e.optional)&&void 0!==t&&t;if(!this.isInitialized(n)&&!this.shouldAutoInitialize()){if(r)return null;throw Error(`Service ${this.name} is not available`)}try{return this.getOrInitializeService({instanceIdentifier:n})}catch(e){if(r)return null;throw e}}getComponent(){return this.component}setComponent(e){if(e.name!==this.name)throw Error(`Mismatching Component ${e.name} for Provider ${this.name}.`);if(this.component)throw Error(`Component for ${this.name} has already been provided`);if(this.component=e,this.shouldAutoInitialize()){if(function(e){return"EAGER"===e.instantiationMode}(e))try{this.getOrInitializeService({instanceIdentifier:i})}catch(e){}for(const[e,t]of this.instancesDeferred.entries()){const n=this.normalizeInstanceIdentifier(e);try{const e=this.getOrInitializeService({instanceIdentifier:n});t.resolve(e)}catch(e){}}}}clearInstance(e=i){this.instancesDeferred.delete(e),this.instancesOptions.delete(e),this.instances.delete(e)}async delete(){const e=Array.from(this.instances.values());await Promise.all([...e.filter((e=>"INTERNAL"in e)).map((e=>e.INTERNAL.delete())),...e.filter((e=>"_delete"in e)).map((e=>e._delete()))])}isComponentSet(){return null!=this.component}isInitialized(e=i){return this.instances.has(e)}getOptions(e=i){return this.instancesOptions.get(e)||{}}initialize(e={}){const{options:t={}}=e,n=this.normalizeInstanceIdentifier(e.instanceIdentifier);if(this.isInitialized(n))throw Error(`${this.name}(${n}) has already been initialized`);if(!this.isComponentSet())throw Error(`Component ${this.name} has not been registered yet`);const r=this.getOrInitializeService({instanceIdentifier:n,options:t});for(const[e,t]of this.instancesDeferred.entries())n===this.normalizeInstanceIdentifier(e)&&t.resolve(r);return r}onInit(e,t){var n;const r=this.normalizeInstanceIdentifier(t),i=null!==(n=this.onInitCallbacks.get(r))&&void 0!==n?n:new Set;i.add(e),this.onInitCallbacks.set(r,i);const s=this.instances.get(r);return s&&e(s,r),()=>{i.delete(e)}}invokeOnInitCallbacks(e,t){const n=this.onInitCallbacks.get(t);if(n)for(const r of n)try{r(e,t)}catch(e){}}getOrInitializeService({instanceIdentifier:e,options:t={}}){let n=this.instances.get(e);if(!n&&this.component&&(n=this.component.instanceFactory(this.container,{instanceIdentifier:(r=e,r===i?void 0:r),options:t}),this.instances.set(e,n),this.instancesOptions.set(e,t),this.invokeOnInitCallbacks(n,e),this.component.onInstanceCreated))try{this.component.onInstanceCreated(this.container,e,n)}catch(e){}var r;return n||null}normalizeInstanceIdentifier(e=i){return this.component?this.component.multipleInstances?e:i:e}shouldAutoInitialize(){return!!this.component&&"EXPLICIT"!==this.component.instantiationMode}}t.Component=class{constructor(e,t,n){this.name=e,this.instanceFactory=t,this.type=n,this.multipleInstances=!1,this.serviceProps={},this.instantiationMode="LAZY",this.onInstanceCreated=null}setInstantiationMode(e){return this.instantiationMode=e,this}setMultipleInstances(e){return this.multipleInstances=e,this}setServiceProps(e){return this.serviceProps=e,this}setInstanceCreatedCallback(e){return this.onInstanceCreated=e,this}},t.ComponentContainer=class{constructor(e){this.name=e,this.providers=new Map}addComponent(e){const t=this.getProvider(e.name);if(t.isComponentSet())throw new Error(`Component ${e.name} has already been registered with ${this.name}`);t.setComponent(e)}addOrOverwriteComponent(e){this.getProvider(e.name).isComponentSet()&&this.providers.delete(e.name),this.addComponent(e)}getProvider(e){if(this.providers.has(e))return this.providers.get(e);const t=new s(e,this);return this.providers.set(e,t),t}getProviders(){return Array.from(this.providers.values())}},t.Provider=s},241:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(199),i=n(319),s=n(844),o=n(336),a=n(860),c=n(832);const u="@firebase/firestore";class l{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}}l.UNAUTHENTICATED=new l(null),l.GOOGLE_CREDENTIALS=new l("google-credentials-uid"),l.FIRST_PARTY=new l("first-party-uid"),l.MOCK_USER=new l("mock-user");let h="11.0.2";const d=new s.Logger("@firebase/firestore");function f(){return d.logLevel}function g(e,...t){if(d.logLevel<=s.LogLevel.DEBUG){const n=t.map(y);d.debug(`Firestore (${h}): ${e}`,...n)}}function p(e,...t){if(d.logLevel<=s.LogLevel.ERROR){const n=t.map(y);d.error(`Firestore (${h}): ${e}`,...n)}}function m(e,...t){if(d.logLevel<=s.LogLevel.WARN){const n=t.map(y);d.warn(`Firestore (${h}): ${e}`,...n)}}function y(e){if("string"==typeof e)return e;try{return function(e){return JSON.stringify(e)}(e)}catch(t){return e}}function v(e="Unexpected state"){const t=`FIRESTORE (${h}) INTERNAL ASSERTION FAILED: `+e;throw p(t),new Error(t)}function w(e,t){e||v()}function b(e,t){return e}const _={OK:"ok",CANCELLED:"cancelled",UNKNOWN:"unknown",INVALID_ARGUMENT:"invalid-argument",DEADLINE_EXCEEDED:"deadline-exceeded",NOT_FOUND:"not-found",ALREADY_EXISTS:"already-exists",PERMISSION_DENIED:"permission-denied",UNAUTHENTICATED:"unauthenticated",RESOURCE_EXHAUSTED:"resource-exhausted",FAILED_PRECONDITION:"failed-precondition",ABORTED:"aborted",OUT_OF_RANGE:"out-of-range",UNIMPLEMENTED:"unimplemented",INTERNAL:"internal",UNAVAILABLE:"unavailable",DATA_LOSS:"data-loss"};class I extends o.FirebaseError{constructor(e,t){super(e,t),this.code=e,this.message=t,this.toString=()=>`${this.name}: [code=${this.code}]: ${this.message}`}}class E{constructor(){this.promise=new Promise(((e,t)=>{this.resolve=e,this.reject=t}))}}class T{constructor(e,t){this.user=t,this.type="OAuth",this.headers=new Map,this.headers.set("Authorization",`Bearer ${e}`)}}class S{getToken(){return Promise.resolve(null)}invalidateToken(){}start(e,t){e.enqueueRetryable((()=>t(l.UNAUTHENTICATED)))}shutdown(){}}class x{constructor(e){this.token=e,this.changeListener=null}getToken(){return Promise.resolve(this.token)}invalidateToken(){}start(e,t){this.changeListener=t,e.enqueueRetryable((()=>t(this.token.user)))}shutdown(){this.changeListener=null}}class C{constructor(e){this.t=e,this.currentUser=l.UNAUTHENTICATED,this.i=0,this.forceRefresh=!1,this.auth=null}start(e,t){w(void 0===this.o);let n=this.i;const r=e=>this.i!==n?(n=this.i,t(e)):Promise.resolve();let i=new E;this.o=()=>{this.i++,this.currentUser=this.u(),i.resolve(),i=new E,e.enqueueRetryable((()=>r(this.currentUser)))};const s=()=>{const t=i;e.enqueueRetryable((async()=>{await t.promise,await r(this.currentUser)}))},o=e=>{g("FirebaseAuthCredentialsProvider","Auth detected"),this.auth=e,this.o&&(this.auth.addAuthTokenListener(this.o),s())};this.t.onInit((e=>o(e))),setTimeout((()=>{if(!this.auth){const e=this.t.getImmediate({optional:!0});e?o(e):(g("FirebaseAuthCredentialsProvider","Auth not yet detected"),i.resolve(),i=new E)}}),0),s()}getToken(){const e=this.i,t=this.forceRefresh;return this.forceRefresh=!1,this.auth?this.auth.getToken(t).then((t=>this.i!==e?(g("FirebaseAuthCredentialsProvider","getToken aborted due to token change."),this.getToken()):t?(w("string"==typeof t.accessToken),new T(t.accessToken,this.currentUser)):null)):Promise.resolve(null)}invalidateToken(){this.forceRefresh=!0}shutdown(){this.auth&&this.o&&this.auth.removeAuthTokenListener(this.o),this.o=void 0}u(){const e=this.auth&&this.auth.getUid();return w(null===e||"string"==typeof e),new l(e)}}class D{constructor(e,t,n){this.l=e,this.h=t,this.P=n,this.type="FirstParty",this.user=l.FIRST_PARTY,this.T=new Map}I(){return this.P?this.P():null}get headers(){this.T.set("X-Goog-AuthUser",this.l);const e=this.I();return e&&this.T.set("Authorization",e),this.h&&this.T.set("X-Goog-Iam-Authorization-Token",this.h),this.T}}class A{constructor(e,t,n){this.l=e,this.h=t,this.P=n}getToken(){return Promise.resolve(new D(this.l,this.h,this.P))}start(e,t){e.enqueueRetryable((()=>t(l.FIRST_PARTY)))}shutdown(){}invalidateToken(){}}class k{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 N{constructor(e){this.A=e,this.forceRefresh=!1,this.appCheck=null,this.R=null}start(e,t){w(void 0===this.o);const n=e=>{null!=e.error&&g("FirebaseAppCheckTokenProvider",`Error getting App Check token; using placeholder token instead. Error: ${e.error.message}`);const n=e.token!==this.R;return this.R=e.token,g("FirebaseAppCheckTokenProvider",`Received ${n?"new":"existing"} token.`),n?t(e.token):Promise.resolve()};this.o=t=>{e.enqueueRetryable((()=>n(t)))};const r=e=>{g("FirebaseAppCheckTokenProvider","AppCheck detected"),this.appCheck=e,this.o&&this.appCheck.addTokenListener(this.o)};this.A.onInit((e=>r(e))),setTimeout((()=>{if(!this.appCheck){const e=this.A.getImmediate({optional:!0});e?r(e):g("FirebaseAppCheckTokenProvider","AppCheck not yet detected")}}),0)}getToken(){const e=this.forceRefresh;return this.forceRefresh=!1,this.appCheck?this.appCheck.getToken(e).then((e=>e?(w("string"==typeof e.token),this.R=e.token,new k(e.token)):null)):Promise.resolve(null)}invalidateToken(){this.forceRefresh=!0}shutdown(){this.appCheck&&this.o&&this.appCheck.removeTokenListener(this.o),this.o=void 0}}function L(e){const t="undefined"!=typeof self&&(self.crypto||self.msCrypto),n=new Uint8Array(e);if(t&&"function"==typeof t.getRandomValues)t.getRandomValues(n);else for(let t=0;t<e;t++)n[t]=Math.floor(256*Math.random());return n}class O{static newId(){const e=62*Math.floor(256/62);let t="";for(;t.length<20;){const n=L(40);for(let r=0;r<n.length;++r)t.length<20&&n[r]<e&&(t+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".charAt(n[r]%62))}return t}}function M(e,t){return e<t?-1:e>t?1:0}function R(e,t,n){return e.length===t.length&&e.every(((e,r)=>n(e,t[r])))}function P(e){return e+"\0"}class F{static now(){return F.fromMillis(Date.now())}static fromDate(e){return F.fromMillis(e.getTime())}static fromMillis(e){const t=Math.floor(e/1e3),n=Math.floor(1e6*(e-1e3*t));return new F(t,n)}constructor(e,t){if(this.seconds=e,this.nanoseconds=t,t<0)throw new I(_.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+t);if(t>=1e9)throw new I(_.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+t);if(e<-62135596800)throw new I(_.INVALID_ARGUMENT,"Timestamp seconds out of range: "+e);if(e>=253402300800)throw new I(_.INVALID_ARGUMENT,"Timestamp seconds out of range: "+e)}toDate(){return new Date(this.toMillis())}toMillis(){return 1e3*this.seconds+this.nanoseconds/1e6}_compareTo(e){return this.seconds===e.seconds?M(this.nanoseconds,e.nanoseconds):M(this.seconds,e.seconds)}isEqual(e){return e.seconds===this.seconds&&e.nanoseconds===this.nanoseconds}toString(){return"Timestamp(seconds="+this.seconds+", nanoseconds="+this.nanoseconds+")"}toJSON(){return{seconds:this.seconds,nanoseconds:this.nanoseconds}}valueOf(){const e=this.seconds- -62135596800;return String(e).padStart(12,"0")+"."+String(this.nanoseconds).padStart(9,"0")}}class V{static fromTimestamp(e){return new V(e)}static min(){return new V(new F(0,0))}static max(){return new V(new F(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 q{constructor(e,t,n){void 0===t?t=0:t>e.length&&v(),void 0===n?n=e.length-t:n>e.length-t&&v(),this.segments=e,this.offset=t,this.len=n}get length(){return this.len}isEqual(e){return 0===q.comparator(this,e)}child(e){const t=this.segments.slice(this.offset,this.limit());return e instanceof q?e.forEach((e=>{t.push(e)})):t.push(e),this.construct(t)}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 t=0;t<this.length;t++)if(this.get(t)!==e.get(t))return!1;return!0}isImmediateParentOf(e){if(this.length+1!==e.length)return!1;for(let t=0;t<this.length;t++)if(this.get(t)!==e.get(t))return!1;return!0}forEach(e){for(let t=this.offset,n=this.limit();t<n;t++)e(this.segments[t])}toArray(){return this.segments.slice(this.offset,this.limit())}static comparator(e,t){const n=Math.min(e.length,t.length);for(let r=0;r<n;r++){const n=e.get(r),i=t.get(r);if(n<i)return-1;if(n>i)return 1}return e.length<t.length?-1:e.length>t.length?1:0}}class B extends q{construct(e,t,n){return new B(e,t,n)}canonicalString(){return this.toArray().join("/")}toString(){return this.canonicalString()}toUriEncodedString(){return this.toArray().map(encodeURIComponent).join("/")}static fromString(...e){const t=[];for(const n of e){if(n.indexOf("//")>=0)throw new I(_.INVALID_ARGUMENT,`Invalid segment (${n}). Paths must not contain // in them.`);t.push(...n.split("/").filter((e=>e.length>0)))}return new B(t)}static emptyPath(){return new B([])}}const U=/^[_a-zA-Z][_a-zA-Z0-9]*$/;class j extends q{construct(e,t,n){return new j(e,t,n)}static isValidIdentifier(e){return U.test(e)}canonicalString(){return this.toArray().map((e=>(e=e.replace(/\\/g,"\\\\").replace(/`/g,"\\`"),j.isValidIdentifier(e)||(e="`"+e+"`"),e))).join(".")}toString(){return this.canonicalString()}isKeyField(){return 1===this.length&&"__name__"===this.get(0)}static keyField(){return new j(["__name__"])}static fromServerFormat(e){const t=[];let n="",r=0;const i=()=>{if(0===n.length)throw new I(_.INVALID_ARGUMENT,`Invalid field path (${e}). Paths must not be empty, begin with '.', end with '.', or contain '..'`);t.push(n),n=""};let s=!1;for(;r<e.length;){const t=e[r];if("\\"===t){if(r+1===e.length)throw new I(_.INVALID_ARGUMENT,"Path has trailing escape character: "+e);const t=e[r+1];if("\\"!==t&&"."!==t&&"`"!==t)throw new I(_.INVALID_ARGUMENT,"Path has invalid escape sequence: "+e);n+=t,r+=2}else"`"===t?(s=!s,r++):"."!==t||s?(n+=t,r++):(i(),r++)}if(i(),s)throw new I(_.INVALID_ARGUMENT,"Unterminated ` in path: "+e);return new j(t)}static emptyPath(){return new j([])}}class ${constructor(e){this.path=e}static fromPath(e){return new $(B.fromString(e))}static fromName(e){return new $(B.fromString(e).popFirst(5))}static empty(){return new $(B.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===B.comparator(this.path,e.path)}toString(){return this.path.toString()}static comparator(e,t){return B.comparator(e.path,t.path)}static isDocumentKey(e){return e.length%2==0}static fromSegments(e){return new $(new B(e.slice()))}}class z{constructor(e,t,n,r){this.indexId=e,this.collectionGroup=t,this.fields=n,this.indexState=r}}function G(e){return e.fields.find((e=>2===e.kind))}function K(e){return e.fields.filter((e=>2!==e.kind))}function Q(e,t){let n=M(e.collectionGroup,t.collectionGroup);if(0!==n)return n;for(let r=0;r<Math.min(e.fields.length,t.fields.length);++r)if(n=W(e.fields[r],t.fields[r]),0!==n)return n;return M(e.fields.length,t.fields.length)}z.UNKNOWN_ID=-1;class H{constructor(e,t){this.fieldPath=e,this.kind=t}}function W(e,t){const n=j.comparator(e.fieldPath,t.fieldPath);return 0!==n?n:M(e.kind,t.kind)}class J{constructor(e,t){this.sequenceNumber=e,this.offset=t}static empty(){return new J(0,Z.min())}}function X(e,t){const n=e.toTimestamp().seconds,r=e.toTimestamp().nanoseconds+1,i=V.fromTimestamp(1e9===r?new F(n+1,0):new F(n,r));return new Z(i,$.empty(),t)}function Y(e){return new Z(e.readTime,e.key,-1)}class Z{constructor(e,t,n){this.readTime=e,this.documentKey=t,this.largestBatchId=n}static min(){return new Z(V.min(),$.empty(),-1)}static max(){return new Z(V.max(),$.empty(),-1)}}function ee(e,t){let n=e.readTime.compareTo(t.readTime);return 0!==n?n:(n=$.comparator(e.documentKey,t.documentKey),0!==n?n:M(e.largestBatchId,t.largestBatchId))}const te="The current tab is not in the required state to perform this operation. It might be necessary to refresh the browser tab.";class ne{constructor(){this.onCommittedListeners=[]}addOnCommittedListener(e){this.onCommittedListeners.push(e)}raiseOnCommittedEvent(){this.onCommittedListeners.forEach((e=>e()))}}async function re(e){if(e.code!==_.FAILED_PRECONDITION||e.message!==te)throw e;g("LocalStore","Unexpectedly lost primary lease")}class ie{constructor(e){this.nextCallback=null,this.catchCallback=null,this.result=void 0,this.error=void 0,this.isDone=!1,this.callbackAttached=!1,e((e=>{this.isDone=!0,this.result=e,this.nextCallback&&this.nextCallback(e)}),(e=>{this.isDone=!0,this.error=e,this.catchCallback&&this.catchCallback(e)}))}catch(e){return this.next(void 0,e)}next(e,t){return this.callbackAttached&&v(),this.callbackAttached=!0,this.isDone?this.error?this.wrapFailure(t,this.error):this.wrapSuccess(e,this.result):new ie(((n,r)=>{this.nextCallback=t=>{this.wrapSuccess(e,t).next(n,r)},this.catchCallback=e=>{this.wrapFailure(t,e).next(n,r)}}))}toPromise(){return new Promise(((e,t)=>{this.next(e,t)}))}wrapUserFunction(e){try{const t=e();return t instanceof ie?t:ie.resolve(t)}catch(e){return ie.reject(e)}}wrapSuccess(e,t){return e?this.wrapUserFunction((()=>e(t))):ie.resolve(t)}wrapFailure(e,t){return e?this.wrapUserFunction((()=>e(t))):ie.reject(t)}static resolve(e){return new ie(((t,n)=>{t(e)}))}static reject(e){return new ie(((t,n)=>{n(e)}))}static waitFor(e){return new ie(((t,n)=>{let r=0,i=0,s=!1;e.forEach((e=>{++r,e.next((()=>{++i,s&&i===r&&t()}),(e=>n(e)))})),s=!0,i===r&&t()}))}static or(e){let t=ie.resolve(!1);for(const n of e)t=t.next((e=>e?ie.resolve(e):n()));return t}static forEach(e,t){const n=[];return e.forEach(((e,r)=>{n.push(t.call(this,e,r))})),this.waitFor(n)}static mapArray(e,t){return new ie(((n,r)=>{const i=e.length,s=new Array(i);let o=0;for(let a=0;a<i;a++){const c=a;t(e[c]).next((e=>{s[c]=e,++o,o===i&&n(s)}),(e=>r(e)))}}))}static doWhile(e,t){return new ie(((n,r)=>{const i=()=>{!0===e()?t().next((()=>{i()}),r):n()};i()}))}}class se{static open(e,t,n,r){try{return new se(t,e.transaction(r,n))}catch(e){throw new ue(t,e)}}constructor(e,t){this.action=e,this.transaction=t,this.aborted=!1,this.V=new E,this.transaction.oncomplete=()=>{this.V.resolve()},this.transaction.onabort=()=>{t.error?this.V.reject(new ue(e,t.error)):this.V.resolve()},this.transaction.onerror=t=>{const n=ge(t.target.error);this.V.reject(new ue(e,n))}}get m(){return this.V.promise}abort(e){e&&this.V.reject(e),this.aborted||(g("SimpleDb","Aborting transaction:",e?e.message:"Client-initiated abort"),this.aborted=!0,this.transaction.abort())}g(){const e=this.transaction;this.aborted||"function"!=typeof e.commit||e.commit()}store(e){const t=this.transaction.objectStore(e);return new he(t)}}class oe{static delete(e){return g("SimpleDb","Removing database:",e),de(window.indexedDB.deleteDatabase(e)).toPromise()}static p(){if(!o.isIndexedDBAvailable())return!1;if(oe.S())return!0;const e=o.getUA(),t=oe.D(e),n=0<t&&t<10,r=ae(e),i=0<r&&r<4.5;return!(e.indexOf("MSIE ")>0||e.indexOf("Trident/")>0||e.indexOf("Edge/")>0||n||i)}static S(){var e;return"undefined"!=typeof process&&"YES"===(null===(e=process.__PRIVATE_env)||void 0===e?void 0:e.v)}static C(e,t){return e.store(t)}static D(e){const t=e.match(/i(?:phone|pad|pod) os ([\d_]+)/i),n=t?t[1].split("_").slice(0,2).join("."):"-1";return Number(n)}constructor(e,t,n){this.name=e,this.version=t,this.F=n,12.2===oe.D(o.getUA())&&p("Firestore persistence suffers from a bug in iOS 12.2 Safari that may cause your app to stop working. See https://stackoverflow.com/q/56496296/110915 for details and a potential workaround.")}async M(e){return this.db||(g("SimpleDb","Opening database:",this.name),this.db=await new Promise(((t,n)=>{const r=indexedDB.open(this.name,this.version);r.onsuccess=e=>{const n=e.target.result;t(n)},r.onblocked=()=>{n(new ue(e,"Cannot upgrade IndexedDB schema while another tab is open. Close all tabs that access Firestore and reload this page to proceed."))},r.onerror=t=>{const r=t.target.error;"VersionError"===r.name?n(new I(_.FAILED_PRECONDITION,"A newer version of the Firestore SDK was previously used and so the persisted data is not compatible with the version of the SDK you are now using. The SDK will operate with persistence disabled. If you need persistence, please re-upgrade to a newer version of the SDK or else clear the persisted IndexedDB data for your app to start fresh.")):"InvalidStateError"===r.name?n(new I(_.FAILED_PRECONDITION,"Unable to open an IndexedDB connection. This could be due to running in a private browsing session on a browser whose private browsing sessions do not support IndexedDB: "+r)):n(new ue(e,r))},r.onupgradeneeded=e=>{g("SimpleDb",'Database "'+this.name+'" requires upgrade from version:',e.oldVersion);const t=e.target.result;this.F.O(t,r.transaction,e.oldVersion,this.version).next((()=>{g("SimpleDb","Database upgrade to version "+this.version+" complete")}))}}))),this.N&&(this.db.onversionchange=e=>this.N(e)),this.db}L(e){this.N=e,this.db&&(this.db.onversionchange=t=>e(t))}async runTransaction(e,t,n,r){const i="readonly"===t;let s=0;for(;;){++s;try{this.db=await this.M(e);const t=se.open(this.db,e,i?"readonly":"readwrite",n),s=r(t).next((e=>(t.g(),e))).catch((e=>(t.abort(e),ie.reject(e)))).toPromise();return s.catch((()=>{})),await t.m,s}catch(e){const t=e,n="FirebaseError"!==t.name&&s<3;if(g("SimpleDb","Transaction failed with error:",t.message,"Retrying:",n),this.close(),!n)return Promise.reject(t)}}}close(){this.db&&this.db.close(),this.db=void 0}}function ae(e){const t=e.match(/Android ([\d.]+)/i),n=t?t[1].split(".").slice(0,2).join("."):"-1";return Number(n)}class ce{constructor(e){this.B=e,this.k=!1,this.q=null}get isDone(){return this.k}get K(){return this.q}set cursor(e){this.B=e}done(){this.k=!0}$(e){this.q=e}delete(){return de(this.B.delete())}}class ue extends I{constructor(e,t){super(_.UNAVAILABLE,`IndexedDB transaction '${e}' failed: ${t}`),this.name="IndexedDbTransactionError"}}function le(e){return"IndexedDbTransactionError"===e.name}class he{constructor(e){this.store=e}put(e,t){let n;return void 0!==t?(g("SimpleDb","PUT",this.store.name,e,t),n=this.store.put(t,e)):(g("SimpleDb","PUT",this.store.name,"<auto-key>",e),n=this.store.put(e)),de(n)}add(e){return g("SimpleDb","ADD",this.store.name,e,e),de(this.store.add(e))}get(e){return de(this.store.get(e)).next((t=>(void 0===t&&(t=null),g("SimpleDb","GET",this.store.name,e,t),t)))}delete(e){return g("SimpleDb","DELETE",this.store.name,e),de(this.store.delete(e))}count(){return g("SimpleDb","COUNT",this.store.name),de(this.store.count())}U(e,t){const n=this.options(e,t),r=n.index?this.store.index(n.index):this.store;if("function"==typeof r.getAll){const e=r.getAll(n.range);return new ie(((t,n)=>{e.onerror=e=>{n(e.target.error)},e.onsuccess=e=>{t(e.target.result)}}))}{const e=this.cursor(n),t=[];return this.W(e,((e,n)=>{t.push(n)})).next((()=>t))}}G(e,t){const n=this.store.getAll(e,null===t?void 0:t);return new ie(((e,t)=>{n.onerror=e=>{t(e.target.error)},n.onsuccess=t=>{e(t.target.result)}}))}j(e,t){g("SimpleDb","DELETE ALL",this.store.name);const n=this.options(e,t);n.H=!1;const r=this.cursor(n);return this.W(r,((e,t,n)=>n.delete()))}J(e,t){let n;t?n=e:(n={},t=e);const r=this.cursor(n);return this.W(r,t)}Y(e){const t=this.cursor({});return new ie(((n,r)=>{t.onerror=e=>{const t=ge(e.target.error);r(t)},t.onsuccess=t=>{const r=t.target.result;r?e(r.primaryKey,r.value).next((e=>{e?r.continue():n()})):n()}}))}W(e,t){const n=[];return new ie(((r,i)=>{e.onerror=e=>{i(e.target.error)},e.onsuccess=e=>{const i=e.target.result;if(!i)return void r();const s=new ce(i),o=t(i.primaryKey,i.value,s);if(o instanceof ie){const e=o.catch((e=>(s.done(),ie.reject(e))));n.push(e)}s.isDone?r():null===s.K?i.continue():i.continue(s.K)}})).next((()=>ie.waitFor(n)))}options(e,t){let n;return void 0!==e&&("string"==typeof e?n=e:t=e),{index:n,range:t}}cursor(e){let t="next";if(e.reverse&&(t="prev"),e.index){const n=this.store.index(e.index);return e.H?n.openKeyCursor(e.range,t):n.openCursor(e.range,t)}return this.store.openCursor(e.range,t)}}function de(e){return new ie(((t,n)=>{e.onsuccess=e=>{const n=e.target.result;t(n)},e.onerror=e=>{const t=ge(e.target.error);n(t)}}))}let fe=!1;function ge(e){const t=oe.D(o.getUA());if(t>=12.2&&t<13){const t="An internal error was encountered in the Indexed Database server";if(e.message.indexOf(t)>=0){const e=new I("internal",`IOS_INDEXEDDB_BUG1: IndexedDb has thrown '${t}'. This is likely due to an unavoidable bug in iOS. See https://stackoverflow.com/q/56496296/110915 for details and a potential workaround.`);return fe||(fe=!0,setTimeout((()=>{throw e}),0)),e}}return e}class pe{constructor(e,t){this.asyncQueue=e,this.Z=t,this.task=null}start(){this.X(15e3)}stop(){this.task&&(this.task.cancel(),this.task=null)}get started(){return null!==this.task}X(e){g("IndexBackfiller",`Scheduled in ${e}ms`),this.task=this.asyncQueue.enqueueAfterDelay("index_backfill",e,(async()=>{this.task=null;try{g("IndexBackfiller",`Documents written: ${await this.Z.ee()}`)}catch(e){le(e)?g("IndexBackfiller","Ignoring IndexedDB error during index backfill: ",e):await re(e)}await this.X(6e4)}))}}class me{constructor(e,t){this.localStore=e,this.persistence=t}async ee(e=50){return this.persistence.runTransaction("Backfill Indexes","readwrite-primary",(t=>this.te(t,e)))}te(e,t){const n=new Set;let r=t,i=!0;return ie.doWhile((()=>!0===i&&r>0),(()=>this.localStore.indexManager.getNextCollectionGroupToUpdate(e).next((t=>{if(null!==t&&!n.has(t))return g("IndexBackfiller",`Processing collection: ${t}`),this.ne(e,t,r).next((e=>{r-=e,n.add(t)}));i=!1})))).next((()=>t-r))}ne(e,t,n){return this.localStore.indexManager.getMinOffsetFromCollectionGroup(e,t).next((r=>this.localStore.localDocuments.getNextDocuments(e,t,r,n).next((n=>{const i=n.changes;return this.localStore.indexManager.updateIndexEntries(e,i).next((()=>this.re(r,n))).next((n=>(g("IndexBackfiller",`Updating offset: ${n}`),this.localStore.indexManager.updateCollectionGroup(e,t,n)))).next((()=>i.size))}))))}re(e,t){let n=e;return t.changes.forEach(((e,t)=>{const r=Y(t);ee(r,n)>0&&(n=r)})),new Z(n.readTime,n.documentKey,Math.max(t.batchId,e.largestBatchId))}}class ye{constructor(e,t){this.previousValue=e,t&&(t.sequenceNumberHandler=e=>this.ie(e),this.se=e=>t.writeSequenceNumber(e))}ie(e){return this.previousValue=Math.max(e,this.previousValue),this.previousValue}next(){const e=++this.previousValue;return this.se&&this.se(e),e}}function ve(e){return null==e}function we(e){return 0===e&&1/e==-1/0}function be(e){return"number"==typeof e&&Number.isInteger(e)&&!we(e)&&e<=Number.MAX_SAFE_INTEGER&&e>=Number.MIN_SAFE_INTEGER}function _e(e){let t="";for(let n=0;n<e.length;n++)t.length>0&&(t=Ee(t)),t=Ie(e.get(n),t);return Ee(t)}function Ie(e,t){let n=t;const r=e.length;for(let t=0;t<r;t++){const r=e.charAt(t);switch(r){case"\0":n+="";break;case"":n+="";break;default:n+=r}}return n}function Ee(e){return e+""}function Te(e){const t=e.length;if(w(t>=2),2===t)return w(""===e.charAt(0)&&""===e.charAt(1)),B.emptyPath();const n=t-2,r=[];let i="";for(let s=0;s<t;){const t=e.indexOf("",s);switch((t<0||t>n)&&v(),e.charAt(t+1)){case"":const n=e.substring(s,t);let o;0===i.length?o=n:(i+=n,o=i,i=""),r.push(o);break;case"":i+=e.substring(s,t),i+="\0";break;case"":i+=e.substring(s,t+1);break;default:v()}s=t+2}return new B(r)}ye.oe=-1;const Se=["userId","batchId"];function xe(e,t){return[e,_e(t)]}function Ce(e,t,n){return[e,_e(t),n]}const De={},Ae=["prefixPath","collectionGroup","readTime","documentId"],ke=["prefixPath","collectionGroup","documentId"],Ne=["collectionGroup","readTime","prefixPath","documentId"],Le=["canonicalId","targetId"],Oe=["targetId","path"],Me=["path","targetId"],Re=["collectionId","parent"],Pe=["indexId","uid"],Fe=["uid","sequenceNumber"],Ve=["indexId","uid","arrayValue","directionalValue","orderedDocumentKey","documentKey"],qe=["indexId","uid","orderedDocumentKey"],Be=["userId","collectionPath","documentId"],Ue=["userId","collectionPath","largestBatchId"],je=["userId","collectionGroup","largestBatchId"],$e=["mutationQueues","mutations","documentMutations","remoteDocuments","targets","owner","targetGlobal","targetDocuments","clientMetadata","remoteDocumentGlobal","collectionParents","bundles","namedQueries"],ze=[...$e,"documentOverlays"],Ge=["mutationQueues","mutations","documentMutations","remoteDocumentsV14","targets","owner","targetGlobal","targetDocuments","clientMetadata","remoteDocumentGlobal","collectionParents","bundles","namedQueries","documentOverlays"],Ke=Ge,Qe=[...Ke,"indexConfiguration","indexState","indexEntries"],He=Qe,We=[...Qe,"globals"];class Je extends ne{constructor(e,t){super(),this._e=e,this.currentSequenceNumber=t}}function Xe(e,t){const n=b(e);return oe.C(n._e,t)}function Ye(e){let t=0;for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&t++;return t}function Ze(e,t){for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&t(n,e[n])}function et(e,t){const n=[];for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&n.push(t(e[r],r,e));return n}function tt(e){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}class nt{constructor(e,t){this.comparator=e,this.root=t||it.EMPTY}insert(e,t){return new nt(this.comparator,this.root.insert(e,t,this.comparator).copy(null,null,it.BLACK,null,null))}remove(e){return new nt(this.comparator,this.root.remove(e,this.comparator).copy(null,null,it.BLACK,null,null))}get(e){let t=this.root;for(;!t.isEmpty();){const n=this.comparator(e,t.key);if(0===n)return t.value;n<0?t=t.left:n>0&&(t=t.right)}return null}indexOf(e){let t=0,n=this.root;for(;!n.isEmpty();){const r=this.comparator(e,n.key);if(0===r)return t+n.left.size;r<0?n=n.left:(t+=n.left.size+1,n=n.right)}return-1}isEmpty(){return this.root.isEmpty()}get size(){return this.root.size}minKey(){return this.root.minKey()}maxKey(){return this.root.maxKey()}inorderTraversal(e){return this.root.inorderTraversal(e)}forEach(e){this.inorderTraversal(((t,n)=>(e(t,n),!1)))}toString(){const e=[];return this.inorderTraversal(((t,n)=>(e.push(`${t}:${n}`),!1))),`{${e.join(", ")}}`}reverseTraversal(e){return this.root.reverseTraversal(e)}getIterator(){return new rt(this.root,null,this.comparator,!1)}getIteratorFrom(e){return new rt(this.root,e,this.comparator,!1)}getReverseIterator(){return new rt(this.root,null,this.comparator,!0)}getReverseIteratorFrom(e){return new rt(this.root,e,this.comparator,!0)}}class rt{constructor(e,t,n,r){this.isReverse=r,this.nodeStack=[];let i=1;for(;!e.isEmpty();)if(i=t?n(e.key,t):1,t&&r&&(i*=-1),i<0)e=this.isReverse?e.left:e.right;else{if(0===i){this.nodeStack.push(e);break}this.nodeStack.push(e),e=this.isReverse?e.right:e.left}}getNext(){let e=this.nodeStack.pop();const t={key:e.key,value:e.value};if(this.isReverse)for(e=e.left;!e.isEmpty();)this.nodeStack.push(e),e=e.right;else for(e=e.right;!e.isEmpty();)this.nodeStack.push(e),e=e.left;return t}hasNext(){return 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 it{constructor(e,t,n,r,i){this.key=e,this.value=t,this.color=null!=n?n:it.RED,this.left=null!=r?r:it.EMPTY,this.right=null!=i?i:it.EMPTY,this.size=this.left.size+1+this.right.size}copy(e,t,n,r,i){return new it(null!=e?e:this.key,null!=t?t:this.value,null!=n?n:this.color,null!=r?r:this.left,null!=i?i:this.right)}isEmpty(){return!1}inorderTraversal(e){return this.left.inorderTraversal(e)||e(this.key,this.value)||this.right.inorderTraversal(e)}reverseTraversal(e){return this.right.reverseTraversal(e)||e(this.key,this.value)||this.left.reverseTraversal(e)}min(){return this.left.isEmpty()?this:this.left.min()}minKey(){return this.min().key}maxKey(){return this.right.isEmpty()?this.key:this.right.maxKey()}insert(e,t,n){let r=this;const i=n(e,r.key);return r=i<0?r.copy(null,null,null,r.left.insert(e,t,n),null):0===i?r.copy(null,t,null,null,null):r.copy(null,null,null,null,r.right.insert(e,t,n)),r.fixUp()}removeMin(){if(this.left.isEmpty())return it.EMPTY;let e=this;return e.left.isRed()||e.left.left.isRed()||(e=e.moveRedLeft()),e=e.copy(null,null,null,e.left.removeMin(),null),e.fixUp()}remove(e,t){let n,r=this;if(t(e,r.key)<0)r.left.isEmpty()||r.left.isRed()||r.left.left.isRed()||(r=r.moveRedLeft()),r=r.copy(null,null,null,r.left.remove(e,t),null);else{if(r.left.isRed()&&(r=r.rotateRight()),r.right.isEmpty()||r.right.isRed()||r.right.left.isRed()||(r=r.moveRedRight()),0===t(e,r.key)){if(r.right.isEmpty())return it.EMPTY;n=r.right.min(),r=r.copy(n.key,n.value,null,null,r.right.removeMin())}r=r.copy(null,null,null,null,r.right.remove(e,t))}return r.fixUp()}isRed(){return this.color}fixUp(){let e=this;return e.right.isRed()&&!e.left.isRed()&&(e=e.rotateLeft()),e.left.isRed()&&e.left.left.isRed()&&(e=e.rotateRight()),e.left.isRed()&&e.right.isRed()&&(e=e.colorFlip()),e}moveRedLeft(){let e=this.colorFlip();return e.right.left.isRed()&&(e=e.copy(null,null,null,null,e.right.rotateRight()),e=e.rotateLeft(),e=e.colorFlip()),e}moveRedRight(){let e=this.colorFlip();return e.left.left.isRed()&&(e=e.rotateRight(),e=e.colorFlip()),e}rotateLeft(){const e=this.copy(null,null,it.RED,null,this.right.left);return this.right.copy(null,null,this.color,e,null)}rotateRight(){const e=this.copy(null,null,it.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),t=this.right.copy(null,null,!this.right.color,null,null);return this.copy(null,null,!this.color,e,t)}checkMaxDepth(){const e=this.check();return Math.pow(2,e)<=this.size+1}check(){if(this.isRed()&&this.left.isRed())throw v();if(this.right.isRed())throw v();const e=this.left.check();if(e!==this.right.check())throw v();return e+(this.isRed()?0:1)}}it.EMPTY=null,it.RED=!0,it.BLACK=!1,it.EMPTY=new class{constructor(){this.size=0}get key(){throw v()}get value(){throw v()}get color(){throw v()}get left(){throw v()}get right(){throw v()}copy(e,t,n,r,i){return this}insert(e,t,n){return new it(e,t)}remove(e,t){return this}isEmpty(){return!0}inorderTraversal(e){return!1}reverseTraversal(e){return!1}minKey(){return null}maxKey(){return null}isRed(){return!1}checkMaxDepth(){return!0}check(){return 0}};class st{constructor(e){this.comparator=e,this.data=new nt(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(((t,n)=>(e(t),!1)))}forEachInRange(e,t){const n=this.data.getIteratorFrom(e[0]);for(;n.hasNext();){const r=n.getNext();if(this.comparator(r.key,e[1])>=0)return;t(r.key)}}forEachWhile(e,t){let n;for(n=void 0!==t?this.data.getIteratorFrom(t):this.data.getIterator();n.hasNext();)if(!e(n.getNext().key))return}firstAfterOrEqual(e){const t=this.data.getIteratorFrom(e);return t.hasNext()?t.getNext().key:null}getIterator(){return new ot(this.data.getIterator())}getIteratorFrom(e){return new ot(this.data.getIteratorFrom(e))}add(e){return this.copy(this.data.remove(e).insert(e,!0))}delete(e){return this.has(e)?this.copy(this.data.remove(e)):this}isEmpty(){return this.data.isEmpty()}unionWith(e){let t=this;return t.size<e.size&&(t=e,e=this),e.forEach((e=>{t=t.add(e)})),t}isEqual(e){if(!(e instanceof st))return!1;if(this.size!==e.size)return!1;const t=this.data.getIterator(),n=e.data.getIterator();for(;t.hasNext();){const e=t.getNext().key,r=n.getNext().key;if(0!==this.comparator(e,r))return!1}return!0}toArray(){const e=[];return this.forEach((t=>{e.push(t)})),e}toString(){const e=[];return this.forEach((t=>e.push(t))),"SortedSet("+e.toString()+")"}copy(e){const t=new st(this.comparator);return t.data=e,t}}class ot{constructor(e){this.iter=e}getNext(){return this.iter.getNext().key}hasNext(){return this.iter.hasNext()}}function at(e){return e.hasNext()?e.getNext():void 0}class ct{constructor(e){this.fields=e,e.sort(j.comparator)}static empty(){return new ct([])}unionWith(e){let t=new st(j.comparator);for(const e of this.fields)t=t.add(e);for(const n of e)t=t.add(n);return new ct(t.toArray())}covers(e){for(const t of this.fields)if(t.isPrefixOf(e))return!0;return!1}isEqual(e){return R(this.fields,e.fields,((e,t)=>e.isEqual(t)))}}class ut extends Error{constructor(){super(...arguments),this.name="Base64DecodeError"}}class lt{constructor(e){this.binaryString=e}static fromBase64String(e){const t=function(e){try{return atob(e)}catch(e){throw"undefined"!=typeof DOMException&&e instanceof DOMException?new ut("Invalid base64 string: "+e):e}}(e);return new lt(t)}static fromUint8Array(e){const t=function(e){let t="";for(let n=0;n<e.length;++n)t+=String.fromCharCode(e[n]);return t}(e);return new lt(t)}[Symbol.iterator](){let e=0;return{next:()=>e<this.binaryString.length?{value:this.binaryString.charCodeAt(e++),done:!1}:{value:void 0,done:!0}}}toBase64(){return e=this.binaryString,btoa(e);var e}toUint8Array(){return function(e){const t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t}(this.binaryString)}approximateByteSize(){return 2*this.binaryString.length}compareTo(e){return M(this.binaryString,e.binaryString)}isEqual(e){return this.binaryString===e.binaryString}}lt.EMPTY_BYTE_STRING=new lt("");const ht=new RegExp(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.(\d+))?Z$/);function dt(e){if(w(!!e),"string"==typeof e){let t=0;const n=ht.exec(e);if(w(!!n),n[1]){let e=n[1];e=(e+"000000000").substr(0,9),t=Number(e)}const r=new Date(e);return{seconds:Math.floor(r.getTime()/1e3),nanos:t}}return{seconds:ft(e.seconds),nanos:ft(e.nanos)}}function ft(e){return"number"==typeof e?e:"string"==typeof e?Number(e):0}function gt(e){return"string"==typeof e?lt.fromBase64String(e):lt.fromUint8Array(e)}function pt(e){var t,n;return"server_timestamp"===(null===(n=((null===(t=null==e?void 0:e.mapValue)||void 0===t?void 0:t.fields)||{}).__type__)||void 0===n?void 0:n.stringValue)}function mt(e){const t=e.mapValue.fields.__previous_value__;return pt(t)?mt(t):t}function yt(e){const t=dt(e.mapValue.fields.__local_write_time__.timestampValue);return new F(t.seconds,t.nanos)}class vt{constructor(e,t,n,r,i,s,o,a,c){this.databaseId=e,this.appId=t,this.persistenceKey=n,this.host=r,this.ssl=i,this.forceLongPolling=s,this.autoDetectLongPolling=o,this.longPollingOptions=a,this.useFetchStreams=c}}class wt{constructor(e,t){this.projectId=e,this.database=t||"(default)"}static empty(){return new wt("","")}get isDefaultDatabase(){return"(default)"===this.database}isEqual(e){return e instanceof wt&&e.projectId===this.projectId&&e.database===this.database}}const bt={mapValue:{fields:{__type__:{stringValue:"__max__"}}}},_t={nullValue:"NULL_VALUE"};function It(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?pt(e)?4:qt(e)?9007199254740991:Ft(e)?10:11:v()}function Et(e,t){if(e===t)return!0;const n=It(e);if(n!==It(t))return!1;switch(n){case 0:case 9007199254740991:return!0;case 1:return e.booleanValue===t.booleanValue;case 4:return yt(e).isEqual(yt(t));case 3:return function(e,t){if("string"==typeof e.timestampValue&&"string"==typeof t.timestampValue&&e.timestampValue.length===t.timestampValue.length)return e.timestampValue===t.timestampValue;const n=dt(e.timestampValue),r=dt(t.timestampValue);return n.seconds===r.seconds&&n.nanos===r.nanos}(e,t);case 5:return e.stringValue===t.stringValue;case 6:return function(e,t){return gt(e.bytesValue).isEqual(gt(t.bytesValue))}(e,t);case 7:return e.referenceValue===t.referenceValue;case 8:return function(e,t){return ft(e.geoPointValue.latitude)===ft(t.geoPointValue.latitude)&&ft(e.geoPointValue.longitude)===ft(t.geoPointValue.longitude)}(e,t);case 2:return function(e,t){if("integerValue"in e&&"integerValue"in t)return ft(e.integerValue)===ft(t.integerValue);if("doubleValue"in e&&"doubleValue"in t){const n=ft(e.doubleValue),r=ft(t.doubleValue);return n===r?we(n)===we(r):isNaN(n)&&isNaN(r)}return!1}(e,t);case 9:return R(e.arrayValue.values||[],t.arrayValue.values||[],Et);case 10:case 11:return function(e,t){const n=e.mapValue.fields||{},r=t.mapValue.fields||{};if(Ye(n)!==Ye(r))return!1;for(const e in n)if(n.hasOwnProperty(e)&&(void 0===r[e]||!Et(n[e],r[e])))return!1;return!0}(e,t);default:return v()}}function Tt(e,t){return void 0!==(e.values||[]).find((e=>Et(e,t)))}function St(e,t){if(e===t)return 0;const n=It(e),r=It(t);if(n!==r)return M(n,r);switch(n){case 0:case 9007199254740991:return 0;case 1:return M(e.booleanValue,t.booleanValue);case 2:return function(e,t){const n=ft(e.integerValue||e.doubleValue),r=ft(t.integerValue||t.doubleValue);return n<r?-1:n>r?1:n===r?0:isNaN(n)?isNaN(r)?0:-1:1}(e,t);case 3:return xt(e.timestampValue,t.timestampValue);case 4:return xt(yt(e),yt(t));case 5:return M(e.stringValue,t.stringValue);case 6:return function(e,t){const n=gt(e),r=gt(t);return n.compareTo(r)}(e.bytesValue,t.bytesValue);case 7:return function(e,t){const n=e.split("/"),r=t.split("/");for(let e=0;e<n.length&&e<r.length;e++){const t=M(n[e],r[e]);if(0!==t)return t}return M(n.length,r.length)}(e.referenceValue,t.referenceValue);case 8:return function(e,t){const n=M(ft(e.latitude),ft(t.latitude));return 0!==n?n:M(ft(e.longitude),ft(t.longitude))}(e.geoPointValue,t.geoPointValue);case 9:return Ct(e.arrayValue,t.arrayValue);case 10:return function(e,t){var n,r,i,s;const o=e.fields||{},a=t.fields||{},c=null===(n=o.value)||void 0===n?void 0:n.arrayValue,u=null===(r=a.value)||void 0===r?void 0:r.arrayValue,l=M((null===(i=null==c?void 0:c.values)||void 0===i?void 0:i.length)||0,(null===(s=null==u?void 0:u.values)||void 0===s?void 0:s.length)||0);return 0!==l?l:Ct(c,u)}(e.mapValue,t.mapValue);case 11:return function(e,t){if(e===bt.mapValue&&t===bt.mapValue)return 0;if(e===bt.mapValue)return 1;if(t===bt.mapValue)return-1;const n=e.fields||{},r=Object.keys(n),i=t.fields||{},s=Object.keys(i);r.sort(),s.sort();for(let e=0;e<r.length&&e<s.length;++e){const t=M(r[e],s[e]);if(0!==t)return t;const o=St(n[r[e]],i[s[e]]);if(0!==o)return o}return M(r.length,s.length)}(e.mapValue,t.mapValue);default:throw v()}}function xt(e,t){if("string"==typeof e&&"string"==typeof t&&e.length===t.length)return M(e,t);const n=dt(e),r=dt(t),i=M(n.seconds,r.seconds);return 0!==i?i:M(n.nanos,r.nanos)}function Ct(e,t){const n=e.values||[],r=t.values||[];for(let e=0;e<n.length&&e<r.length;++e){const t=St(n[e],r[e]);if(t)return t}return M(n.length,r.length)}function Dt(e){return At(e)}function At(e){return"nullValue"in e?"null":"booleanValue"in e?""+e.booleanValue:"integerValue"in e?""+e.integerValue:"doubleValue"in e?""+e.doubleValue:"timestampValue"in e?function(e){const t=dt(e);return`time(${t.seconds},${t.nanos})`}(e.timestampValue):"stringValue"in e?e.stringValue:"bytesValue"in e?function(e){return gt(e).toBase64()}(e.bytesValue):"referenceValue"in e?function(e){return $.fromName(e).toString()}(e.referenceValue):"geoPointValue"in e?function(e){return`geo(${e.latitude},${e.longitude})`}(e.geoPointValue):"arrayValue"in e?function(e){let t="[",n=!0;for(const r of e.values||[])n?n=!1:t+=",",t+=At(r);return t+"]"}(e.arrayValue):"mapValue"in e?function(e){const t=Object.keys(e.fields||{}).sort();let n="{",r=!0;for(const i of t)r?r=!1:n+=",",n+=`${i}:${At(e.fields[i])}`;return n+"}"}(e.mapValue):v()}function kt(e){switch(It(e)){case 0:case 1:return 4;case 2:return 8;case 3:case 8:return 16;case 4:const t=mt(e);return t?16+kt(t):16;case 5:return 2*e.stringValue.length;case 6:return gt(e.bytesValue).approximateByteSize();case 7:return e.referenceValue.length;case 9:return function(e){return(e.values||[]).reduce(((e,t)=>e+kt(t)),0)}(e.arrayValue);case 10:case 11:return function(e){let t=0;return Ze(e.fields,((e,n)=>{t+=e.length+kt(n)})),t}(e.mapValue);default:throw v()}}function Nt(e,t){return{referenceValue:`projects/${e.projectId}/databases/${e.database}/documents/${t.path.canonicalString()}`}}function Lt(e){return!!e&&"integerValue"in e}function Ot(e){return!!e&&"arrayValue"in e}function Mt(e){return!!e&&"nullValue"in e}function Rt(e){return!!e&&"doubleValue"in e&&isNaN(Number(e.doubleValue))}function Pt(e){return!!e&&"mapValue"in e}function Ft(e){var t,n;return"__vector__"===(null===(n=((null===(t=null==e?void 0:e.mapValue)||void 0===t?void 0:t.fields)||{}).__type__)||void 0===n?void 0:n.stringValue)}function Vt(e){if(e.geoPointValue)return{geoPointValue:Object.assign({},e.geoPointValue)};if(e.timestampValue&&"object"==typeof e.timestampValue)return{timestampValue:Object.assign({},e.timestampValue)};if(e.mapValue){const t={mapValue:{fields:{}}};return Ze(e.mapValue.fields,((e,n)=>t.mapValue.fields[e]=Vt(n))),t}if(e.arrayValue){const t={arrayValue:{values:[]}};for(let n=0;n<(e.arrayValue.values||[]).length;++n)t.arrayValue.values[n]=Vt(e.arrayValue.values[n]);return t}return Object.assign({},e)}function qt(e){return"__max__"===(((e.mapValue||{}).fields||{}).__type__||{}).stringValue}const Bt={mapValue:{fields:{__type__:{stringValue:"__vector__"},value:{arrayValue:{}}}}};function Ut(e){return"nullValue"in e?_t:"booleanValue"in e?{booleanValue:!1}:"integerValue"in e||"doubleValue"in e?{doubleValue:NaN}:"timestampValue"in e?{timestampValue:{seconds:Number.MIN_SAFE_INTEGER}}:"stringValue"in e?{stringValue:""}:"bytesValue"in e?{bytesValue:""}:"referenceValue"in e?Nt(wt.empty(),$.empty()):"geoPointValue"in e?{geoPointValue:{latitude:-90,longitude:-180}}:"arrayValue"in e?{arrayValue:{}}:"mapValue"in e?Ft(e)?Bt:{mapValue:{}}:v()}function jt(e){return"nullValue"in e?{booleanValue:!1}:"booleanValue"in e?{doubleValue:NaN}:"integerValue"in e||"doubleValue"in e?{timestampValue:{seconds:Number.MIN_SAFE_INTEGER}}:"timestampValue"in e?{stringValue:""}:"stringValue"in e?{bytesValue:""}:"bytesValue"in e?Nt(wt.empty(),$.empty()):"referenceValue"in e?{geoPointValue:{latitude:-90,longitude:-180}}:"geoPointValue"in e?{arrayValue:{}}:"arrayValue"in e?Bt:"mapValue"in e?Ft(e)?{mapValue:{}}:bt:v()}function $t(e,t){const n=St(e.value,t.value);return 0!==n?n:e.inclusive&&!t.inclusive?-1:!e.inclusive&&t.inclusive?1:0}function zt(e,t){const n=St(e.value,t.value);return 0!==n?n:e.inclusive&&!t.inclusive?1:!e.inclusive&&t.inclusive?-1:0}class Gt{constructor(e){this.value=e}static empty(){return new Gt({mapValue:{}})}field(e){if(e.isEmpty())return this.value;{let t=this.value;for(let n=0;n<e.length-1;++n)if(t=(t.mapValue.fields||{})[e.get(n)],!Pt(t))return null;return t=(t.mapValue.fields||{})[e.lastSegment()],t||null}}set(e,t){this.getFieldsMap(e.popLast())[e.lastSegment()]=Vt(t)}setAll(e){let t=j.emptyPath(),n={},r=[];e.forEach(((e,i)=>{if(!t.isImmediateParentOf(i)){const e=this.getFieldsMap(t);this.applyChanges(e,n,r),n={},r=[],t=i.popLast()}e?n[i.lastSegment()]=Vt(e):r.push(i.lastSegment())}));const i=this.getFieldsMap(t);this.applyChanges(i,n,r)}delete(e){const t=this.field(e.popLast());Pt(t)&&t.mapValue.fields&&delete t.mapValue.fields[e.lastSegment()]}isEqual(e){return Et(this.value,e.value)}getFieldsMap(e){let t=this.value;t.mapValue.fields||(t.mapValue={fields:{}});for(let n=0;n<e.length;++n){let r=t.mapValue.fields[e.get(n)];Pt(r)&&r.mapValue.fields||(r={mapValue:{fields:{}}},t.mapValue.fields[e.get(n)]=r),t=r}return t.mapValue.fields}applyChanges(e,t,n){Ze(t,((t,n)=>e[t]=n));for(const t of n)delete e[t]}clone(){return new Gt(Vt(this.value))}}function Kt(e){const t=[];return Ze(e.fields,((e,n)=>{const r=new j([e]);if(Pt(n)){const e=Kt(n.mapValue).fields;if(0===e.length)t.push(r);else for(const n of e)t.push(r.child(n))}else t.push(r)})),new ct(t)}class Qt{constructor(e,t,n,r,i,s,o){this.key=e,this.documentType=t,this.version=n,this.readTime=r,this.createTime=i,this.data=s,this.documentState=o}static newInvalidDocument(e){return new Qt(e,0,V.min(),V.min(),V.min(),Gt.empty(),0)}static newFoundDocument(e,t,n,r){return new Qt(e,1,t,V.min(),n,r,0)}static newNoDocument(e,t){return new Qt(e,2,t,V.min(),V.min(),Gt.empty(),0)}static newUnknownDocument(e,t){return new Qt(e,3,t,V.min(),V.min(),Gt.empty(),2)}convertToFoundDocument(e,t){return!this.createTime.isEqual(V.min())||2!==this.documentType&&0!==this.documentType||(this.createTime=e),this.version=e,this.documentType=1,this.data=t,this.documentState=0,this}convertToNoDocument(e){return this.version=e,this.documentType=2,this.data=Gt.empty(),this.documentState=0,this}convertToUnknownDocument(e){return this.version=e,this.documentType=3,this.data=Gt.empty(),this.documentState=2,this}setHasCommittedMutations(){return this.documentState=2,this}setHasLocalMutations(){return this.documentState=1,this.version=V.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 Qt&&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 Qt(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 Ht{constructor(e,t){this.position=e,this.inclusive=t}}function Wt(e,t,n){let r=0;for(let i=0;i<e.position.length;i++){const s=t[i],o=e.position[i];if(r=s.field.isKeyField()?$.comparator($.fromName(o.referenceValue),n.key):St(o,n.data.field(s.field)),"desc"===s.dir&&(r*=-1),0!==r)break}return r}function Jt(e,t){if(null===e)return null===t;if(null===t)return!1;if(e.inclusive!==t.inclusive||e.position.length!==t.position.length)return!1;for(let n=0;n<e.position.length;n++)if(!Et(e.position[n],t.position[n]))return!1;return!0}class Xt{constructor(e,t="asc"){this.field=e,this.dir=t}}function Yt(e,t){return e.dir===t.dir&&e.field.isEqual(t.field)}class Zt{}class en extends Zt{constructor(e,t,n){super(),this.field=e,this.op=t,this.value=n}static create(e,t,n){return e.isKeyField()?"in"===t||"not-in"===t?this.createKeyFieldInFilter(e,t,n):new hn(e,t,n):"array-contains"===t?new pn(e,n):"in"===t?new mn(e,n):"not-in"===t?new yn(e,n):"array-contains-any"===t?new vn(e,n):new en(e,t,n)}static createKeyFieldInFilter(e,t,n){return"in"===t?new dn(e,n):new fn(e,n)}matches(e){const t=e.data.field(this.field);return"!="===this.op?null!==t&&this.matchesComparison(St(t,this.value)):null!==t&&It(this.value)===It(t)&&this.matchesComparison(St(t,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 v()}}isInequality(){return["<","<=",">",">=","!=","not-in"].indexOf(this.op)>=0}getFlattenedFilters(){return[this]}getFilters(){return[this]}}class tn extends Zt{constructor(e,t){super(),this.filters=e,this.op=t,this.ae=null}static create(e,t){return new tn(e,t)}matches(e){return nn(this)?void 0===this.filters.find((t=>!t.matches(e))):void 0!==this.filters.find((t=>t.matches(e)))}getFlattenedFilters(){return null!==this.ae||(this.ae=this.filters.reduce(((e,t)=>e.concat(t.getFlattenedFilters())),[])),this.ae}getFilters(){return Object.assign([],this.filters)}}function nn(e){return"and"===e.op}function rn(e){return"or"===e.op}function sn(e){return on(e)&&nn(e)}function on(e){for(const t of e.filters)if(t instanceof tn)return!1;return!0}function an(e){if(e instanceof en)return e.field.canonicalString()+e.op.toString()+Dt(e.value);if(sn(e))return e.filters.map((e=>an(e))).join(",");{const t=e.filters.map((e=>an(e))).join(",");return`${e.op}(${t})`}}function cn(e,t){return e instanceof en?function(e,t){return t instanceof en&&e.op===t.op&&e.field.isEqual(t.field)&&Et(e.value,t.value)}(e,t):e instanceof tn?function(e,t){return t instanceof tn&&e.op===t.op&&e.filters.length===t.filters.length&&e.filters.reduce(((e,n,r)=>e&&cn(n,t.filters[r])),!0)}(e,t):void v()}function un(e,t){const n=e.filters.concat(t);return tn.create(n,e.op)}function ln(e){return e instanceof en?function(e){return`${e.field.canonicalString()} ${e.op} ${Dt(e.value)}`}(e):e instanceof tn?function(e){return e.op.toString()+" {"+e.getFilters().map(ln).join(" ,")+"}"}(e):"Filter"}class hn extends en{constructor(e,t,n){super(e,t,n),this.key=$.fromName(n.referenceValue)}matches(e){const t=$.comparator(e.key,this.key);return this.matchesComparison(t)}}class dn extends en{constructor(e,t){super(e,"in",t),this.keys=gn(0,t)}matches(e){return this.keys.some((t=>t.isEqual(e.key)))}}class fn extends en{constructor(e,t){super(e,"not-in",t),this.keys=gn(0,t)}matches(e){return!this.keys.some((t=>t.isEqual(e.key)))}}function gn(e,t){var n;return((null===(n=t.arrayValue)||void 0===n?void 0:n.values)||[]).map((e=>$.fromName(e.referenceValue)))}class pn extends en{constructor(e,t){super(e,"array-contains",t)}matches(e){const t=e.data.field(this.field);return Ot(t)&&Tt(t.arrayValue,this.value)}}class mn extends en{constructor(e,t){super(e,"in",t)}matches(e){const t=e.data.field(this.field);return null!==t&&Tt(this.value.arrayValue,t)}}class yn extends en{constructor(e,t){super(e,"not-in",t)}matches(e){if(Tt(this.value.arrayValue,{nullValue:"NULL_VALUE"}))return!1;const t=e.data.field(this.field);return null!==t&&!Tt(this.value.arrayValue,t)}}class vn extends en{constructor(e,t){super(e,"array-contains-any",t)}matches(e){const t=e.data.field(this.field);return!(!Ot(t)||!t.arrayValue.values)&&t.arrayValue.values.some((e=>Tt(this.value.arrayValue,e)))}}class wn{constructor(e,t=null,n=[],r=[],i=null,s=null,o=null){this.path=e,this.collectionGroup=t,this.orderBy=n,this.filters=r,this.limit=i,this.startAt=s,this.endAt=o,this.ue=null}}function bn(e,t=null,n=[],r=[],i=null,s=null,o=null){return new wn(e,t,n,r,i,s,o)}function _n(e){const t=b(e);if(null===t.ue){let e=t.path.canonicalString();null!==t.collectionGroup&&(e+="|cg:"+t.collectionGroup),e+="|f:",e+=t.filters.map((e=>an(e))).join(","),e+="|ob:",e+=t.orderBy.map((e=>function(e){return e.field.canonicalString()+e.dir}(e))).join(","),ve(t.limit)||(e+="|l:",e+=t.limit),t.startAt&&(e+="|lb:",e+=t.startAt.inclusive?"b:":"a:",e+=t.startAt.position.map((e=>Dt(e))).join(",")),t.endAt&&(e+="|ub:",e+=t.endAt.inclusive?"a:":"b:",e+=t.endAt.position.map((e=>Dt(e))).join(",")),t.ue=e}return t.ue}function In(e,t){if(e.limit!==t.limit)return!1;if(e.orderBy.length!==t.orderBy.length)return!1;for(let n=0;n<e.orderBy.length;n++)if(!Yt(e.orderBy[n],t.orderBy[n]))return!1;if(e.filters.length!==t.filters.length)return!1;for(let n=0;n<e.filters.length;n++)if(!cn(e.filters[n],t.filters[n]))return!1;return e.collectionGroup===t.collectionGroup&&!!e.path.isEqual(t.path)&&!!Jt(e.startAt,t.startAt)&&Jt(e.endAt,t.endAt)}function En(e){return $.isDocumentKey(e.path)&&null===e.collectionGroup&&0===e.filters.length}function Tn(e,t){return e.filters.filter((e=>e instanceof en&&e.field.isEqual(t)))}function Sn(e,t,n){let r=_t,i=!0;for(const n of Tn(e,t)){let e=_t,t=!0;switch(n.op){case"<":case"<=":e=Ut(n.value);break;case"==":case"in":case">=":e=n.value;break;case">":e=n.value,t=!1;break;case"!=":case"not-in":e=_t}$t({value:r,inclusive:i},{value:e,inclusive:t})<0&&(r=e,i=t)}if(null!==n)for(let s=0;s<e.orderBy.length;++s)if(e.orderBy[s].field.isEqual(t)){const e=n.position[s];$t({value:r,inclusive:i},{value:e,inclusive:n.inclusive})<0&&(r=e,i=n.inclusive);break}return{value:r,inclusive:i}}function xn(e,t,n){let r=bt,i=!0;for(const n of Tn(e,t)){let e=bt,t=!0;switch(n.op){case">=":case">":e=jt(n.value),t=!1;break;case"==":case"in":case"<=":e=n.value;break;case"<":e=n.value,t=!1;break;case"!=":case"not-in":e=bt}zt({value:r,inclusive:i},{value:e,inclusive:t})>0&&(r=e,i=t)}if(null!==n)for(let s=0;s<e.orderBy.length;++s)if(e.orderBy[s].field.isEqual(t)){const e=n.position[s];zt({value:r,inclusive:i},{value:e,inclusive:n.inclusive})>0&&(r=e,i=n.inclusive);break}return{value:r,inclusive:i}}class Cn{constructor(e,t=null,n=[],r=[],i=null,s="F",o=null,a=null){this.path=e,this.collectionGroup=t,this.explicitOrderBy=n,this.filters=r,this.limit=i,this.limitType=s,this.startAt=o,this.endAt=a,this.ce=null,this.le=null,this.he=null,this.startAt,this.endAt}}function Dn(e,t,n,r,i,s,o,a){return new Cn(e,t,n,r,i,s,o,a)}function An(e){return new Cn(e)}function kn(e){return 0===e.filters.length&&null===e.limit&&null==e.startAt&&null==e.endAt&&(0===e.explicitOrderBy.length||1===e.explicitOrderBy.length&&e.explicitOrderBy[0].field.isKeyField())}function Nn(e){return null!==e.collectionGroup}function Ln(e){const t=b(e);if(null===t.ce){t.ce=[];const e=new Set;for(const n of t.explicitOrderBy)t.ce.push(n),e.add(n.field.canonicalString());const n=t.explicitOrderBy.length>0?t.explicitOrderBy[t.explicitOrderBy.length-1].dir:"asc",r=function(e){let t=new st(j.comparator);return e.filters.forEach((e=>{e.getFlattenedFilters().forEach((e=>{e.isInequality()&&(t=t.add(e.field))}))})),t}(t);r.forEach((r=>{e.has(r.canonicalString())||r.isKeyField()||t.ce.push(new Xt(r,n))})),e.has(j.keyField().canonicalString())||t.ce.push(new Xt(j.keyField(),n))}return t.ce}function On(e){const t=b(e);return t.le||(t.le=Rn(t,Ln(e))),t.le}function Mn(e){const t=b(e);return t.he||(t.he=Rn(t,e.explicitOrderBy)),t.he}function Rn(e,t){if("F"===e.limitType)return bn(e.path,e.collectionGroup,t,e.filters,e.limit,e.startAt,e.endAt);{t=t.map((e=>{const t="desc"===e.dir?"asc":"desc";return new Xt(e.field,t)}));const n=e.endAt?new Ht(e.endAt.position,e.endAt.inclusive):null,r=e.startAt?new Ht(e.startAt.position,e.startAt.inclusive):null;return bn(e.path,e.collectionGroup,t,e.filters,e.limit,n,r)}}function Pn(e,t){const n=e.filters.concat([t]);return new Cn(e.path,e.collectionGroup,e.explicitOrderBy.slice(),n,e.limit,e.limitType,e.startAt,e.endAt)}function Fn(e,t,n){return new Cn(e.path,e.collectionGroup,e.explicitOrderBy.slice(),e.filters.slice(),t,n,e.startAt,e.endAt)}function Vn(e,t){return In(On(e),On(t))&&e.limitType===t.limitType}function qn(e){return`${_n(On(e))}|lt:${e.limitType}`}function Bn(e){return`Query(target=${function(e){let t=e.path.canonicalString();return null!==e.collectionGroup&&(t+=" collectionGroup="+e.collectionGroup),e.filters.length>0&&(t+=`, filters: [${e.filters.map((e=>ln(e))).join(", ")}]`),ve(e.limit)||(t+=", limit: "+e.limit),e.orderBy.length>0&&(t+=`, orderBy: [${e.orderBy.map((e=>function(e){return`${e.field.canonicalString()} (${e.dir})`}(e))).join(", ")}]`),e.startAt&&(t+=", startAt: ",t+=e.startAt.inclusive?"b:":"a:",t+=e.startAt.position.map((e=>Dt(e))).join(",")),e.endAt&&(t+=", endAt: ",t+=e.endAt.inclusive?"a:":"b:",t+=e.endAt.position.map((e=>Dt(e))).join(",")),`Target(${t})`}(On(e))}; limitType=${e.limitType})`}function Un(e,t){return t.isFoundDocument()&&function(e,t){const n=t.key.path;return null!==e.collectionGroup?t.key.hasCollectionId(e.collectionGroup)&&e.path.isPrefixOf(n):$.isDocumentKey(e.path)?e.path.isEqual(n):e.path.isImmediateParentOf(n)}(e,t)&&function(e,t){for(const n of Ln(e))if(!n.field.isKeyField()&&null===t.data.field(n.field))return!1;return!0}(e,t)&&function(e,t){for(const n of e.filters)if(!n.matches(t))return!1;return!0}(e,t)&&function(e,t){return!(e.startAt&&!function(e,t,n){const r=Wt(e,t,n);return e.inclusive?r<=0:r<0}(e.startAt,Ln(e),t)||e.endAt&&!function(e,t,n){const r=Wt(e,t,n);return e.inclusive?r>=0:r>0}(e.endAt,Ln(e),t))}(e,t)}function jn(e){return e.collectionGroup||(e.path.length%2==1?e.path.lastSegment():e.path.get(e.path.length-2))}function $n(e){return(t,n)=>{let r=!1;for(const i of Ln(e)){const e=zn(i,t,n);if(0!==e)return e;r=r||i.field.isKeyField()}return 0}}function zn(e,t,n){const r=e.field.isKeyField()?$.comparator(t.key,n.key):function(e,t,n){const r=t.data.field(e),i=n.data.field(e);return null!==r&&null!==i?St(r,i):v()}(e.field,t,n);switch(e.dir){case"asc":return r;case"desc":return-1*r;default:return v()}}class Gn{constructor(e,t){this.mapKeyFn=e,this.equalsFn=t,this.inner={},this.innerSize=0}get(e){const t=this.mapKeyFn(e),n=this.inner[t];if(void 0!==n)for(const[t,r]of n)if(this.equalsFn(t,e))return r}has(e){return void 0!==this.get(e)}set(e,t){const n=this.mapKeyFn(e),r=this.inner[n];if(void 0===r)return this.inner[n]=[[e,t]],void this.innerSize++;for(let n=0;n<r.length;n++)if(this.equalsFn(r[n][0],e))return void(r[n]=[e,t]);r.push([e,t]),this.innerSize++}delete(e){const t=this.mapKeyFn(e),n=this.inner[t];if(void 0===n)return!1;for(let r=0;r<n.length;r++)if(this.equalsFn(n[r][0],e))return 1===n.length?delete this.inner[t]:n.splice(r,1),this.innerSize--,!0;return!1}forEach(e){Ze(this.inner,((t,n)=>{for(const[t,r]of n)e(t,r)}))}isEmpty(){return tt(this.inner)}size(){return this.innerSize}}const Kn=new nt($.comparator);function Qn(){return Kn}const Hn=new nt($.comparator);function Wn(...e){let t=Hn;for(const n of e)t=t.insert(n.key,n);return t}function Jn(e){let t=Hn;return e.forEach(((e,n)=>t=t.insert(e,n.overlayedDocument))),t}function Xn(){return Zn()}function Yn(){return Zn()}function Zn(){return new Gn((e=>e.toString()),((e,t)=>e.isEqual(t)))}const er=new nt($.comparator),tr=new st($.comparator);function nr(...e){let t=tr;for(const n of e)t=t.add(n);return t}const rr=new st(M);function ir(){return rr}function sr(e,t){if(e.useProto3Json){if(isNaN(t))return{doubleValue:"NaN"};if(t===1/0)return{doubleValue:"Infinity"};if(t===-1/0)return{doubleValue:"-Infinity"}}return{doubleValue:we(t)?"-0":t}}function or(e){return{integerValue:""+e}}function ar(e,t){return be(t)?or(t):sr(e,t)}class cr{constructor(){this._=void 0}}function ur(e,t,n){return e instanceof dr?function(e,t){const n={fields:{__type__:{stringValue:"server_timestamp"},__local_write_time__:{timestampValue:{seconds:e.seconds,nanos:e.nanoseconds}}}};return t&&pt(t)&&(t=mt(t)),t&&(n.fields.__previous_value__=t),{mapValue:n}}(n,t):e instanceof fr?gr(e,t):e instanceof pr?mr(e,t):function(e,t){const n=hr(e,t),r=vr(n)+vr(e.Pe);return Lt(n)&&Lt(e.Pe)?or(r):sr(e.serializer,r)}(e,t)}function lr(e,t,n){return e instanceof fr?gr(e,t):e instanceof pr?mr(e,t):n}function hr(e,t){return e instanceof yr?function(e){return Lt(e)||function(e){return!!e&&"doubleValue"in e}(e)}(t)?t:{integerValue:0}:null}class dr extends cr{}class fr extends cr{constructor(e){super(),this.elements=e}}function gr(e,t){const n=wr(t);for(const t of e.elements)n.some((e=>Et(e,t)))||n.push(t);return{arrayValue:{values:n}}}class pr extends cr{constructor(e){super(),this.elements=e}}function mr(e,t){let n=wr(t);for(const t of e.elements)n=n.filter((e=>!Et(e,t)));return{arrayValue:{values:n}}}class yr extends cr{constructor(e,t){super(),this.serializer=e,this.Pe=t}}function vr(e){return ft(e.integerValue||e.doubleValue)}function wr(e){return Ot(e)&&e.arrayValue.values?e.arrayValue.values.slice():[]}class br{constructor(e,t){this.field=e,this.transform=t}}class _r{constructor(e,t){this.version=e,this.transformResults=t}}class Ir{constructor(e,t){this.updateTime=e,this.exists=t}static none(){return new Ir}static exists(e){return new Ir(void 0,e)}static updateTime(e){return new Ir(e)}get isNone(){return void 0===this.updateTime&&void 0===this.exists}isEqual(e){return this.exists===e.exists&&(this.updateTime?!!e.updateTime&&this.updateTime.isEqual(e.updateTime):!e.updateTime)}}function Er(e,t){return void 0!==e.updateTime?t.isFoundDocument()&&t.version.isEqual(e.updateTime):void 0===e.exists||e.exists===t.isFoundDocument()}class Tr{}function Sr(e,t){if(!e.hasLocalMutations||t&&0===t.fields.length)return null;if(null===t)return e.isNoDocument()?new Rr(e.key,Ir.none()):new kr(e.key,e.data,Ir.none());{const n=e.data,r=Gt.empty();let i=new st(j.comparator);for(let e of t.fields)if(!i.has(e)){let t=n.field(e);null===t&&e.length>1&&(e=e.popLast(),t=n.field(e)),null===t?r.delete(e):r.set(e,t),i=i.add(e)}return new Nr(e.key,r,new ct(i.toArray()),Ir.none())}}function xr(e,t,n){e instanceof kr?function(e,t,n){const r=e.value.clone(),i=Or(e.fieldTransforms,t,n.transformResults);r.setAll(i),t.convertToFoundDocument(n.version,r).setHasCommittedMutations()}(e,t,n):e instanceof Nr?function(e,t,n){if(!Er(e.precondition,t))return void t.convertToUnknownDocument(n.version);const r=Or(e.fieldTransforms,t,n.transformResults),i=t.data;i.setAll(Lr(e)),i.setAll(r),t.convertToFoundDocument(n.version,i).setHasCommittedMutations()}(e,t,n):function(e,t,n){t.convertToNoDocument(n.version).setHasCommittedMutations()}(0,t,n)}function Cr(e,t,n,r){return e instanceof kr?function(e,t,n,r){if(!Er(e.precondition,t))return n;const i=e.value.clone(),s=Mr(e.fieldTransforms,r,t);return i.setAll(s),t.convertToFoundDocument(t.version,i).setHasLocalMutations(),null}(e,t,n,r):e instanceof Nr?function(e,t,n,r){if(!Er(e.precondition,t))return n;const i=Mr(e.fieldTransforms,r,t),s=t.data;return s.setAll(Lr(e)),s.setAll(i),t.convertToFoundDocument(t.version,s).setHasLocalMutations(),null===n?null:n.unionWith(e.fieldMask.fields).unionWith(e.fieldTransforms.map((e=>e.field)))}(e,t,n,r):function(e,t,n){return Er(e.precondition,t)?(t.convertToNoDocument(t.version).setHasLocalMutations(),null):n}(e,t,n)}function Dr(e,t){let n=null;for(const r of e.fieldTransforms){const e=t.data.field(r.field),i=hr(r.transform,e||null);null!=i&&(null===n&&(n=Gt.empty()),n.set(r.field,i))}return n||null}function Ar(e,t){return e.type===t.type&&!!e.key.isEqual(t.key)&&!!e.precondition.isEqual(t.precondition)&&!!function(e,t){return void 0===e&&void 0===t||!(!e||!t)&&R(e,t,((e,t)=>function(e,t){return e.field.isEqual(t.field)&&function(e,t){return e instanceof fr&&t instanceof fr||e instanceof pr&&t instanceof pr?R(e.elements,t.elements,Et):e instanceof yr&&t instanceof yr?Et(e.Pe,t.Pe):e instanceof dr&&t instanceof dr}(e.transform,t.transform)}(e,t)))}(e.fieldTransforms,t.fieldTransforms)&&(0===e.type?e.value.isEqual(t.value):1!==e.type||e.data.isEqual(t.data)&&e.fieldMask.isEqual(t.fieldMask))}class kr extends Tr{constructor(e,t,n,r=[]){super(),this.key=e,this.value=t,this.precondition=n,this.fieldTransforms=r,this.type=0}getFieldMask(){return null}}class Nr extends Tr{constructor(e,t,n,r,i=[]){super(),this.key=e,this.data=t,this.fieldMask=n,this.precondition=r,this.fieldTransforms=i,this.type=1}getFieldMask(){return this.fieldMask}}function Lr(e){const t=new Map;return e.fieldMask.fields.forEach((n=>{if(!n.isEmpty()){const r=e.data.field(n);t.set(n,r)}})),t}function Or(e,t,n){const r=new Map;w(e.length===n.length);for(let i=0;i<n.length;i++){const s=e[i],o=s.transform,a=t.data.field(s.field);r.set(s.field,lr(o,a,n[i]))}return r}function Mr(e,t,n){const r=new Map;for(const i of e){const e=i.transform,s=n.data.field(i.field);r.set(i.field,ur(e,s,t))}return r}class Rr extends Tr{constructor(e,t){super(),this.key=e,this.precondition=t,this.type=2,this.fieldTransforms=[]}getFieldMask(){return null}}class Pr extends Tr{constructor(e,t){super(),this.key=e,this.precondition=t,this.type=3,this.fieldTransforms=[]}getFieldMask(){return null}}class Fr{constructor(e,t,n,r){this.batchId=e,this.localWriteTime=t,this.baseMutations=n,this.mutations=r}applyToRemoteDocument(e,t){const n=t.mutationResults;for(let t=0;t<this.mutations.length;t++){const r=this.mutations[t];r.key.isEqual(e.key)&&xr(r,e,n[t])}}applyToLocalView(e,t){for(const n of this.baseMutations)n.key.isEqual(e.key)&&(t=Cr(n,e,t,this.localWriteTime));for(const n of this.mutations)n.key.isEqual(e.key)&&(t=Cr(n,e,t,this.localWriteTime));return t}applyToLocalDocumentSet(e,t){const n=Yn();return this.mutations.forEach((r=>{const i=e.get(r.key),s=i.overlayedDocument;let o=this.applyToLocalView(s,i.mutatedFields);o=t.has(r.key)?null:o;const a=Sr(s,o);null!==a&&n.set(r.key,a),s.isValidDocument()||s.convertToNoDocument(V.min())})),n}keys(){return this.mutations.reduce(((e,t)=>e.add(t.key)),nr())}isEqual(e){return this.batchId===e.batchId&&R(this.mutations,e.mutations,((e,t)=>Ar(e,t)))&&R(this.baseMutations,e.baseMutations,((e,t)=>Ar(e,t)))}}class Vr{constructor(e,t,n,r){this.batch=e,this.commitVersion=t,this.mutationResults=n,this.docVersions=r}static from(e,t,n){w(e.mutations.length===n.length);let r=er;const i=e.mutations;for(let e=0;e<i.length;e++)r=r.insert(i[e].key,n[e].version);return new Vr(e,t,n,r)}}class qr{constructor(e,t){this.largestBatchId=e,this.mutation=t}getKey(){return this.mutation.key}isEqual(e){return null!==e&&this.mutation===e.mutation}toString(){return`Overlay{\n largestBatchId: ${this.largestBatchId},\n mutation: ${this.mutation.toString()}\n }`}}class Br{constructor(e,t,n){this.alias=e,this.aggregateType=t,this.fieldPath=n}}class Ur{constructor(e,t){this.count=e,this.unchangedNames=t}}var jr,$r;function zr(e){switch(e){default:return v();case _.CANCELLED:case _.UNKNOWN:case _.DEADLINE_EXCEEDED:case _.RESOURCE_EXHAUSTED:case _.INTERNAL:case _.UNAVAILABLE:case _.UNAUTHENTICATED:return!1;case _.INVALID_ARGUMENT:case _.NOT_FOUND:case _.ALREADY_EXISTS:case _.PERMISSION_DENIED:case _.FAILED_PRECONDITION:case _.ABORTED:case _.OUT_OF_RANGE:case _.UNIMPLEMENTED:case _.DATA_LOSS:return!0}}function Gr(e){if(void 0===e)return p("GRPC error has no .code"),_.UNKNOWN;switch(e){case jr.OK:return _.OK;case jr.CANCELLED:return _.CANCELLED;case jr.UNKNOWN:return _.UNKNOWN;case jr.DEADLINE_EXCEEDED:return _.DEADLINE_EXCEEDED;case jr.RESOURCE_EXHAUSTED:return _.RESOURCE_EXHAUSTED;case jr.INTERNAL:return _.INTERNAL;case jr.UNAVAILABLE:return _.UNAVAILABLE;case jr.UNAUTHENTICATED:return _.UNAUTHENTICATED;case jr.INVALID_ARGUMENT:return _.INVALID_ARGUMENT;case jr.NOT_FOUND:return _.NOT_FOUND;case jr.ALREADY_EXISTS:return _.ALREADY_EXISTS;case jr.PERMISSION_DENIED:return _.PERMISSION_DENIED;case jr.FAILED_PRECONDITION:return _.FAILED_PRECONDITION;case jr.ABORTED:return _.ABORTED;case jr.OUT_OF_RANGE:return _.OUT_OF_RANGE;case jr.UNIMPLEMENTED:return _.UNIMPLEMENTED;case jr.DATA_LOSS:return _.DATA_LOSS;default:return v()}}($r=jr||(jr={}))[$r.OK=0]="OK",$r[$r.CANCELLED=1]="CANCELLED",$r[$r.UNKNOWN=2]="UNKNOWN",$r[$r.INVALID_ARGUMENT=3]="INVALID_ARGUMENT",$r[$r.DEADLINE_EXCEEDED=4]="DEADLINE_EXCEEDED",$r[$r.NOT_FOUND=5]="NOT_FOUND",$r[$r.ALREADY_EXISTS=6]="ALREADY_EXISTS",$r[$r.PERMISSION_DENIED=7]="PERMISSION_DENIED",$r[$r.UNAUTHENTICATED=16]="UNAUTHENTICATED",$r[$r.RESOURCE_EXHAUSTED=8]="RESOURCE_EXHAUSTED",$r[$r.FAILED_PRECONDITION=9]="FAILED_PRECONDITION",$r[$r.ABORTED=10]="ABORTED",$r[$r.OUT_OF_RANGE=11]="OUT_OF_RANGE",$r[$r.UNIMPLEMENTED=12]="UNIMPLEMENTED",$r[$r.INTERNAL=13]="INTERNAL",$r[$r.UNAVAILABLE=14]="UNAVAILABLE",$r[$r.DATA_LOSS=15]="DATA_LOSS";let Kr=null;function Qr(){return new TextEncoder}const Hr=new a.Integer([4294967295,4294967295],0);function Wr(e){const t=Qr().encode(e),n=new a.Md5;return n.update(t),new Uint8Array(n.digest())}function Jr(e){const t=new DataView(e.buffer),n=t.getUint32(0,!0),r=t.getUint32(4,!0),i=t.getUint32(8,!0),s=t.getUint32(12,!0);return[new a.Integer([n,r],0),new a.Integer([i,s],0)]}class Xr{constructor(e,t,n){if(this.bitmap=e,this.padding=t,this.hashCount=n,t<0||t>=8)throw new Yr(`Invalid padding: ${t}`);if(n<0)throw new Yr(`Invalid hash count: ${n}`);if(e.length>0&&0===this.hashCount)throw new Yr(`Invalid hash count: ${n}`);if(0===e.length&&0!==t)throw new Yr(`Invalid padding when bitmap length is 0: ${t}`);this.Te=8*e.length-t,this.Ie=a.Integer.fromNumber(this.Te)}Ee(e,t,n){let r=e.add(t.multiply(a.Integer.fromNumber(n)));return 1===r.compare(Hr)&&(r=new a.Integer([r.getBits(0),r.getBits(1)],0)),r.modulo(this.Ie).toNumber()}de(e){return!!(this.bitmap[Math.floor(e/8)]&1<<e%8)}mightContain(e){if(0===this.Te)return!1;const t=Wr(e),[n,r]=Jr(t);for(let e=0;e<this.hashCount;e++){const t=this.Ee(n,r,e);if(!this.de(t))return!1}return!0}static create(e,t,n){const r=e%8==0?0:8-e%8,i=new Uint8Array(Math.ceil(e/8)),s=new Xr(i,r,t);return n.forEach((e=>s.insert(e))),s}insert(e){if(0===this.Te)return;const t=Wr(e),[n,r]=Jr(t);for(let e=0;e<this.hashCount;e++){const t=this.Ee(n,r,e);this.Ae(t)}}Ae(e){const t=Math.floor(e/8),n=e%8;this.bitmap[t]|=1<<n}}class Yr extends Error{constructor(){super(...arguments),this.name="BloomFilterError"}}class Zr{constructor(e,t,n,r,i){this.snapshotVersion=e,this.targetChanges=t,this.targetMismatches=n,this.documentUpdates=r,this.resolvedLimboDocuments=i}static createSynthesizedRemoteEventForCurrentChange(e,t,n){const r=new Map;return r.set(e,ei.createSynthesizedTargetChangeForCurrentChange(e,t,n)),new Zr(V.min(),r,new nt(M),Qn(),nr())}}class ei{constructor(e,t,n,r,i){this.resumeToken=e,this.current=t,this.addedDocuments=n,this.modifiedDocuments=r,this.removedDocuments=i}static createSynthesizedTargetChangeForCurrentChange(e,t,n){return new ei(n,t,nr(),nr(),nr())}}class ti{constructor(e,t,n,r){this.Re=e,this.removedTargetIds=t,this.key=n,this.Ve=r}}class ni{constructor(e,t){this.targetId=e,this.me=t}}class ri{constructor(e,t,n=lt.EMPTY_BYTE_STRING,r=null){this.state=e,this.targetIds=t,this.resumeToken=n,this.cause=r}}class ii{constructor(){this.fe=0,this.ge=ai(),this.pe=lt.EMPTY_BYTE_STRING,this.ye=!1,this.we=!0}get current(){return this.ye}get resumeToken(){return this.pe}get Se(){return 0!==this.fe}get be(){return this.we}De(e){e.approximateByteSize()>0&&(this.we=!0,this.pe=e)}ve(){let e=nr(),t=nr(),n=nr();return this.ge.forEach(((r,i)=>{switch(i){case 0:e=e.add(r);break;case 2:t=t.add(r);break;case 1:n=n.add(r);break;default:v()}})),new ei(this.pe,this.ye,e,t,n)}Ce(){this.we=!1,this.ge=ai()}Fe(e,t){this.we=!0,this.ge=this.ge.insert(e,t)}Me(e){this.we=!0,this.ge=this.ge.remove(e)}xe(){this.fe+=1}Oe(){this.fe-=1,w(this.fe>=0)}Ne(){this.we=!0,this.ye=!0}}class si{constructor(e){this.Le=e,this.Be=new Map,this.ke=Qn(),this.qe=oi(),this.Qe=oi(),this.Ke=new nt(M)}$e(e){for(const t of e.Re)e.Ve&&e.Ve.isFoundDocument()?this.Ue(t,e.Ve):this.We(t,e.key,e.Ve);for(const t of e.removedTargetIds)this.We(t,e.key,e.Ve)}Ge(e){this.forEachTarget(e,(t=>{const n=this.ze(t);switch(e.state){case 0:this.je(t)&&n.De(e.resumeToken);break;case 1:n.Oe(),n.Se||n.Ce(),n.De(e.resumeToken);break;case 2:n.Oe(),n.Se||this.removeTarget(t);break;case 3:this.je(t)&&(n.Ne(),n.De(e.resumeToken));break;case 4:this.je(t)&&(this.He(t),n.De(e.resumeToken));break;default:v()}}))}forEachTarget(e,t){e.targetIds.length>0?e.targetIds.forEach(t):this.Be.forEach(((e,n)=>{this.je(n)&&t(n)}))}Je(e){const t=e.targetId,n=e.me.count,r=this.Ye(t);if(r){const i=r.target;if(En(i))if(0===n){const e=new $(i.path);this.We(t,e,Qt.newNoDocument(e,V.min()))}else w(1===n);else{const r=this.Ze(t);if(r!==n){const n=this.Xe(e),i=n?this.et(n,e,r):1;if(0!==i){this.He(t);const e=2===i?"TargetPurposeExistenceFilterMismatchBloom":"TargetPurposeExistenceFilterMismatch";this.Ke=this.Ke.insert(t,e)}null==Kr||Kr.tt(function(e,t,n,r,i){var s,o,a,c,u,l;const h={localCacheCount:e,existenceFilterCount:t.count,databaseId:n.database,projectId:n.projectId},d=t.unchangedNames;return d&&(h.bloomFilter={applied:0===i,hashCount:null!==(s=null==d?void 0:d.hashCount)&&void 0!==s?s:0,bitmapLength:null!==(c=null===(a=null===(o=null==d?void 0:d.bits)||void 0===o?void 0:o.bitmap)||void 0===a?void 0:a.length)&&void 0!==c?c:0,padding:null!==(l=null===(u=null==d?void 0:d.bits)||void 0===u?void 0:u.padding)&&void 0!==l?l:0,mightContain:e=>{var t;return null!==(t=null==r?void 0:r.mightContain(e))&&void 0!==t&&t}}),h}(r,e.me,this.Le.nt(),n,i))}}}}Xe(e){const t=e.me.unchangedNames;if(!t||!t.bits)return null;const{bits:{bitmap:n="",padding:r=0},hashCount:i=0}=t;let s,o;try{s=gt(n).toUint8Array()}catch(e){if(e instanceof ut)return m("Decoding the base64 bloom filter in existence filter failed ("+e.message+"); ignoring the bloom filter and falling back to full re-query."),null;throw e}try{o=new Xr(s,r,i)}catch(e){return m(e instanceof Yr?"BloomFilter error: ":"Applying bloom filter failed: ",e),null}return 0===o.Te?null:o}et(e,t,n){return t.me.count===n-this.rt(e,t.targetId)?0:2}rt(e,t){const n=this.Le.getRemoteKeysForTarget(t);let r=0;return n.forEach((n=>{const i=this.Le.nt(),s=`projects/${i.projectId}/databases/${i.database}/documents/${n.path.canonicalString()}`;e.mightContain(s)||(this.We(t,n,null),r++)})),r}it(e){const t=new Map;this.Be.forEach(((n,r)=>{const i=this.Ye(r);if(i){if(n.current&&En(i.target)){const t=new $(i.target.path);this.st(t).has(r)||this.ot(r,t)||this.We(r,t,Qt.newNoDocument(t,e))}n.be&&(t.set(r,n.ve()),n.Ce())}}));let n=nr();this.Qe.forEach(((e,t)=>{let r=!0;t.forEachWhile((e=>{const t=this.Ye(e);return!t||"TargetPurposeLimboResolution"===t.purpose||(r=!1,!1)})),r&&(n=n.add(e))})),this.ke.forEach(((t,n)=>n.setReadTime(e)));const r=new Zr(e,t,this.Ke,this.ke,n);return this.ke=Qn(),this.qe=oi(),this.Qe=oi(),this.Ke=new nt(M),r}Ue(e,t){if(!this.je(e))return;const n=this.ot(e,t.key)?2:0;this.ze(e).Fe(t.key,n),this.ke=this.ke.insert(t.key,t),this.qe=this.qe.insert(t.key,this.st(t.key).add(e)),this.Qe=this.Qe.insert(t.key,this._t(t.key).add(e))}We(e,t,n){if(!this.je(e))return;const r=this.ze(e);this.ot(e,t)?r.Fe(t,1):r.Me(t),this.Qe=this.Qe.insert(t,this._t(t).delete(e)),this.Qe=this.Qe.insert(t,this._t(t).add(e)),n&&(this.ke=this.ke.insert(t,n))}removeTarget(e){this.Be.delete(e)}Ze(e){const t=this.ze(e).ve();return this.Le.getRemoteKeysForTarget(e).size+t.addedDocuments.size-t.removedDocuments.size}xe(e){this.ze(e).xe()}ze(e){let t=this.Be.get(e);return t||(t=new ii,this.Be.set(e,t)),t}_t(e){let t=this.Qe.get(e);return t||(t=new st(M),this.Qe=this.Qe.insert(e,t)),t}st(e){let t=this.qe.get(e);return t||(t=new st(M),this.qe=this.qe.insert(e,t)),t}je(e){const t=null!==this.Ye(e);return t||g("WatchChangeAggregator","Detected inactive target",e),t}Ye(e){const t=this.Be.get(e);return t&&t.Se?null:this.Le.ut(e)}He(e){this.Be.set(e,new ii),this.Le.getRemoteKeysForTarget(e).forEach((t=>{this.We(e,t,null)}))}ot(e,t){return this.Le.getRemoteKeysForTarget(e).has(t)}}function oi(){return new nt($.comparator)}function ai(){return new nt($.comparator)}const ci={asc:"ASCENDING",desc:"DESCENDING"},ui={"<":"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"},li={and:"AND",or:"OR"};class hi{constructor(e,t){this.databaseId=e,this.useProto3Json=t}}function di(e,t){return e.useProto3Json||ve(t)?t:{value:t}}function fi(e,t){return e.useProto3Json?`${new Date(1e3*t.seconds).toISOString().replace(/\.\d*/,"").replace("Z","")}.${("000000000"+t.nanoseconds).slice(-9)}Z`:{seconds:""+t.seconds,nanos:t.nanoseconds}}function gi(e,t){return e.useProto3Json?t.toBase64():t.toUint8Array()}function pi(e,t){return fi(e,t.toTimestamp())}function mi(e){return w(!!e),V.fromTimestamp(function(e){const t=dt(e);return new F(t.seconds,t.nanos)}(e))}function yi(e,t){return vi(e,t).canonicalString()}function vi(e,t){const n=function(e){return new B(["projects",e.projectId,"databases",e.database])}(e).child("documents");return void 0===t?n:n.child(t)}function wi(e){const t=B.fromString(e);return w(ji(t)),t}function bi(e,t){return yi(e.databaseId,t.path)}function _i(e,t){const n=wi(t);if(n.get(1)!==e.databaseId.projectId)throw new I(_.INVALID_ARGUMENT,"Tried to deserialize key from different project: "+n.get(1)+" vs "+e.databaseId.projectId);if(n.get(3)!==e.databaseId.database)throw new I(_.INVALID_ARGUMENT,"Tried to deserialize key from different database: "+n.get(3)+" vs "+e.databaseId.database);return new $(Si(n))}function Ii(e,t){return yi(e.databaseId,t)}function Ei(e){const t=wi(e);return 4===t.length?B.emptyPath():Si(t)}function Ti(e){return new B(["projects",e.databaseId.projectId,"databases",e.databaseId.database]).canonicalString()}function Si(e){return w(e.length>4&&"documents"===e.get(4)),e.popFirst(5)}function xi(e,t,n){return{name:bi(e,t),fields:n.value.mapValue.fields}}function Ci(e,t,n){const r=_i(e,t.name),i=mi(t.updateTime),s=t.createTime?mi(t.createTime):V.min(),o=new Gt({mapValue:{fields:t.fields}}),a=Qt.newFoundDocument(r,i,s,o);return n&&a.setHasCommittedMutations(),n?a.setHasCommittedMutations():a}function Di(e,t){let n;if(t instanceof kr)n={update:xi(e,t.key,t.value)};else if(t instanceof Rr)n={delete:bi(e,t.key)};else if(t instanceof Nr)n={update:xi(e,t.key,t.data),updateMask:Ui(t.fieldMask)};else{if(!(t instanceof Pr))return v();n={verify:bi(e,t.key)}}return t.fieldTransforms.length>0&&(n.updateTransforms=t.fieldTransforms.map((e=>function(e,t){const n=t.transform;if(n instanceof dr)return{fieldPath:t.field.canonicalString(),setToServerValue:"REQUEST_TIME"};if(n instanceof fr)return{fieldPath:t.field.canonicalString(),appendMissingElements:{values:n.elements}};if(n instanceof pr)return{fieldPath:t.field.canonicalString(),removeAllFromArray:{values:n.elements}};if(n instanceof yr)return{fieldPath:t.field.canonicalString(),increment:n.Pe};throw v()}(0,e)))),t.precondition.isNone||(n.currentDocument=function(e,t){return void 0!==t.updateTime?{updateTime:pi(e,t.updateTime)}:void 0!==t.exists?{exists:t.exists}:v()}(e,t.precondition)),n}function Ai(e,t){const n=t.currentDocument?function(e){return void 0!==e.updateTime?Ir.updateTime(mi(e.updateTime)):void 0!==e.exists?Ir.exists(e.exists):Ir.none()}(t.currentDocument):Ir.none(),r=t.updateTransforms?t.updateTransforms.map((t=>function(e,t){let n=null;if("setToServerValue"in t)w("REQUEST_TIME"===t.setToServerValue),n=new dr;else if("appendMissingElements"in t){const e=t.appendMissingElements.values||[];n=new fr(e)}else if("removeAllFromArray"in t){const e=t.removeAllFromArray.values||[];n=new pr(e)}else"increment"in t?n=new yr(e,t.increment):v();const r=j.fromServerFormat(t.fieldPath);return new br(r,n)}(e,t))):[];if(t.update){t.update.name;const i=_i(e,t.update.name),s=new Gt({mapValue:{fields:t.update.fields}});if(t.updateMask){const e=function(e){const t=e.fieldPaths||[];return new ct(t.map((e=>j.fromServerFormat(e))))}(t.updateMask);return new Nr(i,s,e,n,r)}return new kr(i,s,n,r)}if(t.delete){const r=_i(e,t.delete);return new Rr(r,n)}if(t.verify){const r=_i(e,t.verify);return new Pr(r,n)}return v()}function ki(e,t){return{documents:[Ii(e,t.path)]}}function Ni(e,t){const n={structuredQuery:{}},r=t.path;let i;null!==t.collectionGroup?(i=r,n.structuredQuery.from=[{collectionId:t.collectionGroup,allDescendants:!0}]):(i=r.popLast(),n.structuredQuery.from=[{collectionId:r.lastSegment()}]),n.parent=Ii(e,i);const s=function(e){if(0!==e.length)return Bi(tn.create(e,"and"))}(t.filters);s&&(n.structuredQuery.where=s);const o=function(e){if(0!==e.length)return e.map((e=>function(e){return{field:Vi(e.field),direction:Ri(e.dir)}}(e)))}(t.orderBy);o&&(n.structuredQuery.orderBy=o);const a=di(e,t.limit);return null!==a&&(n.structuredQuery.limit=a),t.startAt&&(n.structuredQuery.startAt=function(e){return{before:e.inclusive,values:e.position}}(t.startAt)),t.endAt&&(n.structuredQuery.endAt=function(e){return{before:!e.inclusive,values:e.position}}(t.endAt)),{ct:n,parent:i}}function Li(e,t,n,r){const{ct:i,parent:s}=Ni(e,t),o={},a=[];let c=0;return n.forEach((e=>{const t=r?e.alias:"aggregate_"+c++;o[t]=e.alias,"count"===e.aggregateType?a.push({alias:t,count:{}}):"avg"===e.aggregateType?a.push({alias:t,avg:{field:Vi(e.fieldPath)}}):"sum"===e.aggregateType&&a.push({alias:t,sum:{field:Vi(e.fieldPath)}})})),{request:{structuredAggregationQuery:{aggregations:a,structuredQuery:i.structuredQuery},parent:i.parent},lt:o,parent:s}}function Oi(e){let t=Ei(e.parent);const n=e.structuredQuery,r=n.from?n.from.length:0;let i=null;if(r>0){w(1===r);const e=n.from[0];e.allDescendants?i=e.collectionId:t=t.child(e.collectionId)}let s=[];n.where&&(s=function(e){const t=Mi(e);return t instanceof tn&&sn(t)?t.getFilters():[t]}(n.where));let o=[];n.orderBy&&(o=function(e){return e.map((e=>function(e){return new Xt(qi(e.field),function(e){switch(e){case"ASCENDING":return"asc";case"DESCENDING":return"desc";default:return}}(e.direction))}(e)))}(n.orderBy));let a=null;n.limit&&(a=function(e){let t;return t="object"==typeof e?e.value:e,ve(t)?null:t}(n.limit));let c=null;n.startAt&&(c=function(e){const t=!!e.before,n=e.values||[];return new Ht(n,t)}(n.startAt));let u=null;return n.endAt&&(u=function(e){const t=!e.before,n=e.values||[];return new Ht(n,t)}(n.endAt)),Dn(t,i,o,s,a,"F",c,u)}function Mi(e){return void 0!==e.unaryFilter?function(e){switch(e.unaryFilter.op){case"IS_NAN":const t=qi(e.unaryFilter.field);return en.create(t,"==",{doubleValue:NaN});case"IS_NULL":const n=qi(e.unaryFilter.field);return en.create(n,"==",{nullValue:"NULL_VALUE"});case"IS_NOT_NAN":const r=qi(e.unaryFilter.field);return en.create(r,"!=",{doubleValue:NaN});case"IS_NOT_NULL":const i=qi(e.unaryFilter.field);return en.create(i,"!=",{nullValue:"NULL_VALUE"});default:return v()}}(e):void 0!==e.fieldFilter?function(e){return en.create(qi(e.fieldFilter.field),function(e){switch(e){case"EQUAL":return"==";case"NOT_EQUAL":return"!=";case"GREATER_THAN":return">";case"GREATER_THAN_OR_EQUAL":return">=";case"LESS_THAN":return"<";case"LESS_THAN_OR_EQUAL":return"<=";case"ARRAY_CONTAINS":return"array-contains";case"IN":return"in";case"NOT_IN":return"not-in";case"ARRAY_CONTAINS_ANY":return"array-contains-any";default:return v()}}(e.fieldFilter.op),e.fieldFilter.value)}(e):void 0!==e.compositeFilter?function(e){return tn.create(e.compositeFilter.filters.map((e=>Mi(e))),function(e){switch(e){case"AND":return"and";case"OR":return"or";default:return v()}}(e.compositeFilter.op))}(e):v()}function Ri(e){return ci[e]}function Pi(e){return ui[e]}function Fi(e){return li[e]}function Vi(e){return{fieldPath:e.canonicalString()}}function qi(e){return j.fromServerFormat(e.fieldPath)}function Bi(e){return e instanceof en?function(e){if("=="===e.op){if(Rt(e.value))return{unaryFilter:{field:Vi(e.field),op:"IS_NAN"}};if(Mt(e.value))return{unaryFilter:{field:Vi(e.field),op:"IS_NULL"}}}else if("!="===e.op){if(Rt(e.value))return{unaryFilter:{field:Vi(e.field),op:"IS_NOT_NAN"}};if(Mt(e.value))return{unaryFilter:{field:Vi(e.field),op:"IS_NOT_NULL"}}}return{fieldFilter:{field:Vi(e.field),op:Pi(e.op),value:e.value}}}(e):e instanceof tn?function(e){const t=e.getFilters().map((e=>Bi(e)));return 1===t.length?t[0]:{compositeFilter:{op:Fi(e.op),filters:t}}}(e):v()}function Ui(e){const t=[];return e.fields.forEach((e=>t.push(e.canonicalString()))),{fieldPaths:t}}function ji(e){return e.length>=4&&"projects"===e.get(0)&&"databases"===e.get(2)}class $i{constructor(e,t,n,r,i=V.min(),s=V.min(),o=lt.EMPTY_BYTE_STRING,a=null){this.target=e,this.targetId=t,this.purpose=n,this.sequenceNumber=r,this.snapshotVersion=i,this.lastLimboFreeSnapshotVersion=s,this.resumeToken=o,this.expectedCount=a}withSequenceNumber(e){return new $i(this.target,this.targetId,this.purpose,e,this.snapshotVersion,this.lastLimboFreeSnapshotVersion,this.resumeToken,this.expectedCount)}withResumeToken(e,t){return new $i(this.target,this.targetId,this.purpose,this.sequenceNumber,t,this.lastLimboFreeSnapshotVersion,e,null)}withExpectedCount(e){return new $i(this.target,this.targetId,this.purpose,this.sequenceNumber,this.snapshotVersion,this.lastLimboFreeSnapshotVersion,this.resumeToken,e)}withLastLimboFreeSnapshotVersion(e){return new $i(this.target,this.targetId,this.purpose,this.sequenceNumber,this.snapshotVersion,e,this.resumeToken,this.expectedCount)}}class zi{constructor(e){this.ht=e}}function Gi(e,t){const n=t.key,r={prefixPath:n.getCollectionPath().popLast().toArray(),collectionGroup:n.collectionGroup,documentId:n.path.lastSegment(),readTime:Ki(t.readTime),hasCommittedMutations:t.hasCommittedMutations};if(t.isFoundDocument())r.document=function(e,t){return{name:bi(e,t.key),fields:t.data.value.mapValue.fields,updateTime:fi(e,t.version.toTimestamp()),createTime:fi(e,t.createTime.toTimestamp())}}(e.ht,t);else if(t.isNoDocument())r.noDocument={path:n.path.toArray(),readTime:Qi(t.version)};else{if(!t.isUnknownDocument())return v();r.unknownDocument={path:n.path.toArray(),version:Qi(t.version)}}return r}function Ki(e){const t=e.toTimestamp();return[t.seconds,t.nanoseconds]}function Qi(e){const t=e.toTimestamp();return{seconds:t.seconds,nanoseconds:t.nanoseconds}}function Hi(e){const t=new F(e.seconds,e.nanoseconds);return V.fromTimestamp(t)}function Wi(e,t){const n=(t.baseMutations||[]).map((t=>Ai(e.ht,t)));for(let e=0;e<t.mutations.length-1;++e){const n=t.mutations[e];if(e+1<t.mutations.length&&void 0!==t.mutations[e+1].transform){const r=t.mutations[e+1];n.updateTransforms=r.transform.fieldTransforms,t.mutations.splice(e+1,1),++e}}const r=t.mutations.map((t=>Ai(e.ht,t))),i=F.fromMillis(t.localWriteTimeMs);return new Fr(t.batchId,i,n,r)}function Ji(e){const t=Hi(e.readTime),n=void 0!==e.lastLimboFreeSnapshotVersion?Hi(e.lastLimboFreeSnapshotVersion):V.min();let r;return r=function(e){return void 0!==e.documents}(e.query)?function(e){return w(1===e.documents.length),On(An(Ei(e.documents[0])))}(e.query):function(e){return On(Oi(e))}(e.query),new $i(r,e.targetId,"TargetPurposeListen",e.lastListenSequenceNumber,t,n,lt.fromBase64String(e.resumeToken))}function Xi(e,t){const n=Qi(t.snapshotVersion),r=Qi(t.lastLimboFreeSnapshotVersion);let i;i=En(t.target)?ki(e.ht,t.target):Ni(e.ht,t.target).ct;const s=t.resumeToken.toBase64();return{targetId:t.targetId,canonicalId:_n(t.target),readTime:n,resumeToken:s,lastListenSequenceNumber:t.sequenceNumber,lastLimboFreeSnapshotVersion:r,query:i}}function Yi(e){const t=Oi({parent:e.parent,structuredQuery:e.structuredQuery});return"LAST"===e.limitType?Fn(t,t.limit,"L"):t}function Zi(e,t){return new qr(t.largestBatchId,Ai(e.ht,t.overlayMutation))}function es(e,t){const n=t.path.lastSegment();return[e,_e(t.path.popLast()),n]}function ts(e,t,n,r){return{indexId:e,uid:t,sequenceNumber:n,readTime:Qi(r.readTime),documentKey:_e(r.documentKey.path),largestBatchId:r.largestBatchId}}class ns{getBundleMetadata(e,t){return rs(e).get(t).next((e=>{if(e)return function(e){return{id:e.bundleId,createTime:Hi(e.createTime),version:e.version}}(e)}))}saveBundleMetadata(e,t){return rs(e).put(function(e){return{bundleId:e.id,createTime:Qi(mi(e.createTime)),version:e.version}}(t))}getNamedQuery(e,t){return is(e).get(t).next((e=>{if(e)return function(e){return{name:e.name,query:Yi(e.bundledQuery),readTime:Hi(e.readTime)}}(e)}))}saveNamedQuery(e,t){return is(e).put(function(e){return{name:e.name,readTime:Qi(mi(e.readTime)),bundledQuery:e.bundledQuery}}(t))}}function rs(e){return Xe(e,"bundles")}function is(e){return Xe(e,"namedQueries")}class ss{constructor(e,t){this.serializer=e,this.userId=t}static Pt(e,t){const n=t.uid||"";return new ss(e,n)}getOverlay(e,t){return os(e).get(es(this.userId,t)).next((e=>e?Zi(this.serializer,e):null))}getOverlays(e,t){const n=Xn();return ie.forEach(t,(t=>this.getOverlay(e,t).next((e=>{null!==e&&n.set(t,e)})))).next((()=>n))}saveOverlays(e,t,n){const r=[];return n.forEach(((n,i)=>{const s=new qr(t,i);r.push(this.Tt(e,s))})),ie.waitFor(r)}removeOverlaysForBatchId(e,t,n){const r=new Set;t.forEach((e=>r.add(_e(e.getCollectionPath()))));const i=[];return r.forEach((t=>{const r=IDBKeyRange.bound([this.userId,t,n],[this.userId,t,n+1],!1,!0);i.push(os(e).j("collectionPathOverlayIndex",r))})),ie.waitFor(i)}getOverlaysForCollection(e,t,n){const r=Xn(),i=_e(t),s=IDBKeyRange.bound([this.userId,i,n],[this.userId,i,Number.POSITIVE_INFINITY],!0);return os(e).U("collectionPathOverlayIndex",s).next((e=>{for(const t of e){const e=Zi(this.serializer,t);r.set(e.getKey(),e)}return r}))}getOverlaysForCollectionGroup(e,t,n,r){const i=Xn();let s;const o=IDBKeyRange.bound([this.userId,t,n],[this.userId,t,Number.POSITIVE_INFINITY],!0);return os(e).J({index:"collectionGroupOverlayIndex",range:o},((e,t,n)=>{const o=Zi(this.serializer,t);i.size()<r||o.largestBatchId===s?(i.set(o.getKey(),o),s=o.largestBatchId):n.done()})).next((()=>i))}Tt(e,t){return os(e).put(function(e,t,n){const[r,i,s]=es(t,n.mutation.key);return{userId:t,collectionPath:i,documentId:s,collectionGroup:n.mutation.key.getCollectionGroup(),largestBatchId:n.largestBatchId,overlayMutation:Di(e.ht,n.mutation)}}(this.serializer,this.userId,t))}}function os(e){return Xe(e,"documentOverlays")}class as{It(e){return Xe(e,"globals")}getSessionToken(e){return this.It(e).get("sessionToken").next((e=>{const t=null==e?void 0:e.value;return t?lt.fromUint8Array(t):lt.EMPTY_BYTE_STRING}))}setSessionToken(e,t){return this.It(e).put({name:"sessionToken",value:t.toUint8Array()})}}class cs{constructor(){}Et(e,t){this.dt(e,t),t.At()}dt(e,t){if("nullValue"in e)this.Rt(t,5);else if("booleanValue"in e)this.Rt(t,10),t.Vt(e.booleanValue?1:0);else if("integerValue"in e)this.Rt(t,15),t.Vt(ft(e.integerValue));else if("doubleValue"in e){const n=ft(e.doubleValue);isNaN(n)?this.Rt(t,13):(this.Rt(t,15),we(n)?t.Vt(0):t.Vt(n))}else if("timestampValue"in e){let n=e.timestampValue;this.Rt(t,20),"string"==typeof n&&(n=dt(n)),t.ft(`${n.seconds||""}`),t.Vt(n.nanos||0)}else if("stringValue"in e)this.gt(e.stringValue,t),this.yt(t);else if("bytesValue"in e)this.Rt(t,30),t.wt(gt(e.bytesValue)),this.yt(t);else if("referenceValue"in e)this.St(e.referenceValue,t);else if("geoPointValue"in e){const n=e.geoPointValue;this.Rt(t,45),t.Vt(n.latitude||0),t.Vt(n.longitude||0)}else"mapValue"in e?qt(e)?this.Rt(t,Number.MAX_SAFE_INTEGER):Ft(e)?this.bt(e.mapValue,t):(this.Dt(e.mapValue,t),this.yt(t)):"arrayValue"in e?(this.vt(e.arrayValue,t),this.yt(t)):v()}gt(e,t){this.Rt(t,25),this.Ct(e,t)}Ct(e,t){t.ft(e)}Dt(e,t){const n=e.fields||{};this.Rt(t,55);for(const e of Object.keys(n))this.gt(e,t),this.dt(n[e],t)}bt(e,t){var n,r;const i=e.fields||{};this.Rt(t,53);const s="value",o=(null===(r=null===(n=i[s].arrayValue)||void 0===n?void 0:n.values)||void 0===r?void 0:r.length)||0;this.Rt(t,15),t.Vt(ft(o)),this.gt(s,t),this.dt(i[s],t)}vt(e,t){const n=e.values||[];this.Rt(t,50);for(const e of n)this.dt(e,t)}St(e,t){this.Rt(t,37),$.fromName(e).path.forEach((e=>{this.Rt(t,60),this.Ct(e,t)}))}Rt(e,t){e.Vt(t)}yt(e){e.Vt(2)}}function us(e){if(0===e)return 8;let t=0;return!(e>>4)&&(t+=4,e<<=4),!(e>>6)&&(t+=2,e<<=2),!(e>>7)&&(t+=1),t}function ls(e){const t=64-function(e){let t=0;for(let n=0;n<8;++n){const r=us(255&e[n]);if(t+=r,8!==r)break}return t}(e);return Math.ceil(t/8)}cs.Ft=new cs;class hs{constructor(){this.buffer=new Uint8Array(1024),this.position=0}Mt(e){const t=e[Symbol.iterator]();let n=t.next();for(;!n.done;)this.xt(n.value),n=t.next();this.Ot()}Nt(e){const t=e[Symbol.iterator]();let n=t.next();for(;!n.done;)this.Lt(n.value),n=t.next();this.Bt()}kt(e){for(const t of e){const e=t.charCodeAt(0);if(e<128)this.xt(e);else if(e<2048)this.xt(960|e>>>6),this.xt(128|63&e);else if(t<"\ud800"||"\udbff"<t)this.xt(480|e>>>12),this.xt(128|63&e>>>6),this.xt(128|63&e);else{const e=t.codePointAt(0);this.xt(240|e>>>18),this.xt(128|63&e>>>12),this.xt(128|63&e>>>6),this.xt(128|63&e)}}this.Ot()}qt(e){for(const t of e){const e=t.charCodeAt(0);if(e<128)this.Lt(e);else if(e<2048)this.Lt(960|e>>>6),this.Lt(128|63&e);else if(t<"\ud800"||"\udbff"<t)this.Lt(480|e>>>12),this.Lt(128|63&e>>>6),this.Lt(128|63&e);else{const e=t.codePointAt(0);this.Lt(240|e>>>18),this.Lt(128|63&e>>>12),this.Lt(128|63&e>>>6),this.Lt(128|63&e)}}this.Bt()}Qt(e){const t=this.Kt(e),n=ls(t);this.$t(1+n),this.buffer[this.position++]=255&n;for(let e=t.length-n;e<t.length;++e)this.buffer[this.position++]=255&t[e]}Ut(e){const t=this.Kt(e),n=ls(t);this.$t(1+n),this.buffer[this.position++]=~(255&n);for(let e=t.length-n;e<t.length;++e)this.buffer[this.position++]=~(255&t[e])}Wt(){this.Gt(255),this.Gt(255)}zt(){this.jt(255),this.jt(255)}reset(){this.position=0}seed(e){this.$t(e.length),this.buffer.set(e,this.position),this.position+=e.length}Ht(){return this.buffer.slice(0,this.position)}Kt(e){const t=function(e){const t=new DataView(new ArrayBuffer(8));return t.setFloat64(0,e,!1),new Uint8Array(t.buffer)}(e),n=!!(128&t[0]);t[0]^=n?255:128;for(let e=1;e<t.length;++e)t[e]^=n?255:0;return t}xt(e){const t=255&e;0===t?(this.Gt(0),this.Gt(255)):255===t?(this.Gt(255),this.Gt(0)):this.Gt(t)}Lt(e){const t=255&e;0===t?(this.jt(0),this.jt(255)):255===t?(this.jt(255),this.jt(0)):this.jt(e)}Ot(){this.Gt(0),this.Gt(1)}Bt(){this.jt(0),this.jt(1)}Gt(e){this.$t(1),this.buffer[this.position++]=e}jt(e){this.$t(1),this.buffer[this.position++]=~e}$t(e){const t=e+this.position;if(t<=this.buffer.length)return;let n=2*this.buffer.length;n<t&&(n=t);const r=new Uint8Array(n);r.set(this.buffer),this.buffer=r}}class ds{constructor(e){this.Jt=e}wt(e){this.Jt.Mt(e)}ft(e){this.Jt.kt(e)}Vt(e){this.Jt.Qt(e)}At(){this.Jt.Wt()}}class fs{constructor(e){this.Jt=e}wt(e){this.Jt.Nt(e)}ft(e){this.Jt.qt(e)}Vt(e){this.Jt.Ut(e)}At(){this.Jt.zt()}}class gs{constructor(){this.Jt=new hs,this.Yt=new ds(this.Jt),this.Zt=new fs(this.Jt)}seed(e){this.Jt.seed(e)}Xt(e){return 0===e?this.Yt:this.Zt}Ht(){return this.Jt.Ht()}reset(){this.Jt.reset()}}class ps{constructor(e,t,n,r){this.indexId=e,this.documentKey=t,this.arrayValue=n,this.directionalValue=r}en(){const e=this.directionalValue.length,t=0===e||255===this.directionalValue[e-1]?e+1:e,n=new Uint8Array(t);return n.set(this.directionalValue,0),t!==e?n.set([0],this.directionalValue.length):++n[n.length-1],new ps(this.indexId,this.documentKey,this.arrayValue,n)}}function ms(e,t){let n=e.indexId-t.indexId;return 0!==n?n:(n=ys(e.arrayValue,t.arrayValue),0!==n?n:(n=ys(e.directionalValue,t.directionalValue),0!==n?n:$.comparator(e.documentKey,t.documentKey)))}function ys(e,t){for(let n=0;n<e.length&&n<t.length;++n){const r=e[n]-t[n];if(0!==r)return r}return e.length-t.length}class vs{constructor(e){this.tn=new st(((e,t)=>j.comparator(e.field,t.field))),this.collectionId=null!=e.collectionGroup?e.collectionGroup:e.path.lastSegment(),this.nn=e.orderBy,this.rn=[];for(const t of e.filters){const e=t;e.isInequality()?this.tn=this.tn.add(e):this.rn.push(e)}}get sn(){return this.tn.size>1}on(e){if(w(e.collectionGroup===this.collectionId),this.sn)return!1;const t=G(e);if(void 0!==t&&!this._n(t))return!1;const n=K(e);let r=new Set,i=0,s=0;for(;i<n.length&&this._n(n[i]);++i)r=r.add(n[i].fieldPath.canonicalString());if(i===n.length)return!0;if(this.tn.size>0){const e=this.tn.getIterator().getNext();if(!r.has(e.field.canonicalString())){const t=n[i];if(!this.an(e,t)||!this.un(this.nn[s++],t))return!1}++i}for(;i<n.length;++i){const e=n[i];if(s>=this.nn.length||!this.un(this.nn[s++],e))return!1}return!0}cn(){if(this.sn)return null;let e=new st(j.comparator);const t=[];for(const n of this.rn)if(!n.field.isKeyField())if("array-contains"===n.op||"array-contains-any"===n.op)t.push(new H(n.field,2));else{if(e.has(n.field))continue;e=e.add(n.field),t.push(new H(n.field,0))}for(const n of this.nn)n.field.isKeyField()||e.has(n.field)||(e=e.add(n.field),t.push(new H(n.field,"asc"===n.dir?0:1)));return new z(z.UNKNOWN_ID,this.collectionId,t,J.empty())}_n(e){for(const t of this.rn)if(this.an(t,e))return!0;return!1}an(e,t){if(void 0===e||!e.field.isEqual(t.fieldPath))return!1;const n="array-contains"===e.op||"array-contains-any"===e.op;return 2===t.kind===n}un(e,t){return!!e.field.isEqual(t.fieldPath)&&(0===t.kind&&"asc"===e.dir||1===t.kind&&"desc"===e.dir)}}function ws(e){var t,n;if(w(e instanceof en||e instanceof tn),e instanceof en){if(e instanceof mn){const r=(null===(n=null===(t=e.value.arrayValue)||void 0===t?void 0:t.values)||void 0===n?void 0:n.map((t=>en.create(e.field,"==",t))))||[];return tn.create(r,"or")}return e}const r=e.filters.map((e=>ws(e)));return tn.create(r,e.op)}function bs(e){if(0===e.getFilters().length)return[];const t=Ts(ws(e));return w(Es(t)),_s(t)||Is(t)?[t]:t.getFilters()}function _s(e){return e instanceof en}function Is(e){return e instanceof tn&&sn(e)}function Es(e){return _s(e)||Is(e)||function(e){if(e instanceof tn&&rn(e)){for(const t of e.getFilters())if(!_s(t)&&!Is(t))return!1;return!0}return!1}(e)}function Ts(e){if(w(e instanceof en||e instanceof tn),e instanceof en)return e;if(1===e.filters.length)return Ts(e.filters[0]);const t=e.filters.map((e=>Ts(e)));let n=tn.create(t,e.op);return n=Cs(n),Es(n)?n:(w(n instanceof tn),w(nn(n)),w(n.filters.length>1),n.filters.reduce(((e,t)=>Ss(e,t))))}function Ss(e,t){let n;return w(e instanceof en||e instanceof tn),w(t instanceof en||t instanceof tn),n=e instanceof en?t instanceof en?function(e,t){return tn.create([e,t],"and")}(e,t):xs(e,t):t instanceof en?xs(t,e):function(e,t){if(w(e.filters.length>0&&t.filters.length>0),nn(e)&&nn(t))return un(e,t.getFilters());const n=rn(e)?e:t,r=rn(e)?t:e,i=n.filters.map((e=>Ss(e,r)));return tn.create(i,"or")}(e,t),Cs(n)}function xs(e,t){if(nn(t))return un(t,e.getFilters());{const n=t.filters.map((t=>Ss(e,t)));return tn.create(n,"or")}}function Cs(e){if(w(e instanceof en||e instanceof tn),e instanceof en)return e;const t=e.getFilters();if(1===t.length)return Cs(t[0]);if(on(e))return e;const n=t.map((e=>Cs(e))),r=[];return n.forEach((t=>{t instanceof en?r.push(t):t instanceof tn&&(t.op===e.op?r.push(...t.filters):r.push(t))})),1===r.length?r[0]:tn.create(r,e.op)}class Ds{constructor(){this.ln=new As}addToCollectionParentIndex(e,t){return this.ln.add(t),ie.resolve()}getCollectionParents(e,t){return ie.resolve(this.ln.getEntries(t))}addFieldIndex(e,t){return ie.resolve()}deleteFieldIndex(e,t){return ie.resolve()}deleteAllFieldIndexes(e){return ie.resolve()}createTargetIndexes(e,t){return ie.resolve()}getDocumentsMatchingTarget(e,t){return ie.resolve(null)}getIndexType(e,t){return ie.resolve(0)}getFieldIndexes(e,t){return ie.resolve([])}getNextCollectionGroupToUpdate(e){return ie.resolve(null)}getMinOffset(e,t){return ie.resolve(Z.min())}getMinOffsetFromCollectionGroup(e,t){return ie.resolve(Z.min())}updateCollectionGroup(e,t,n){return ie.resolve()}updateIndexEntries(e,t){return ie.resolve()}}class As{constructor(){this.index={}}add(e){const t=e.lastSegment(),n=e.popLast(),r=this.index[t]||new st(B.comparator),i=!r.has(n);return this.index[t]=r.add(n),i}has(e){const t=e.lastSegment(),n=e.popLast(),r=this.index[t];return r&&r.has(n)}getEntries(e){return(this.index[e]||new st(B.comparator)).toArray()}}const ks=new Uint8Array(0);class Ns{constructor(e,t){this.databaseId=t,this.hn=new As,this.Pn=new Gn((e=>_n(e)),((e,t)=>In(e,t))),this.uid=e.uid||""}addToCollectionParentIndex(e,t){if(!this.hn.has(t)){const n=t.lastSegment(),r=t.popLast();e.addOnCommittedListener((()=>{this.hn.add(t)}));const i={collectionId:n,parent:_e(r)};return Ls(e).put(i)}return ie.resolve()}getCollectionParents(e,t){const n=[],r=IDBKeyRange.bound([t,""],[P(t),""],!1,!0);return Ls(e).U(r).next((e=>{for(const r of e){if(r.collectionId!==t)break;n.push(Te(r.parent))}return n}))}addFieldIndex(e,t){const n=Ms(e),r=function(e){return{indexId:e.indexId,collectionGroup:e.collectionGroup,fields:e.fields.map((e=>[e.fieldPath.canonicalString(),e.kind]))}}(t);delete r.indexId;const i=n.add(r);if(t.indexState){const n=Rs(e);return i.next((e=>{n.put(ts(e,this.uid,t.indexState.sequenceNumber,t.indexState.offset))}))}return i.next()}deleteFieldIndex(e,t){const n=Ms(e),r=Rs(e),i=Os(e);return n.delete(t.indexId).next((()=>r.delete(IDBKeyRange.bound([t.indexId],[t.indexId+1],!1,!0)))).next((()=>i.delete(IDBKeyRange.bound([t.indexId],[t.indexId+1],!1,!0))))}deleteAllFieldIndexes(e){const t=Ms(e),n=Os(e),r=Rs(e);return t.j().next((()=>n.j())).next((()=>r.j()))}createTargetIndexes(e,t){return ie.forEach(this.Tn(t),(t=>this.getIndexType(e,t).next((n=>{if(0===n||1===n){const n=new vs(t).cn();if(null!=n)return this.addFieldIndex(e,n)}}))))}getDocumentsMatchingTarget(e,t){const n=Os(e);let r=!0;const i=new Map;return ie.forEach(this.Tn(t),(t=>this.In(e,t).next((e=>{r&&(r=!!e),i.set(t,e)})))).next((()=>{if(r){let e=nr();const r=[];return ie.forEach(i,((i,s)=>{g("IndexedDbIndexManager",`Using index ${function(e){return`id=${e.indexId}|cg=${e.collectionGroup}|f=${e.fields.map((e=>`${e.fieldPath}:${e.kind}`)).join(",")}`}(i)} to execute ${_n(t)}`);const o=function(e,t){const n=G(t);if(void 0===n)return null;for(const t of Tn(e,n.fieldPath))switch(t.op){case"array-contains-any":return t.value.arrayValue.values||[];case"array-contains":return[t.value]}return null}(s,i),a=function(e,t){const n=new Map;for(const r of K(t))for(const t of Tn(e,r.fieldPath))switch(t.op){case"==":case"in":n.set(r.fieldPath.canonicalString(),t.value);break;case"not-in":case"!=":return n.set(r.fieldPath.canonicalString(),t.value),Array.from(n.values())}return null}(s,i),c=function(e,t){const n=[];let r=!0;for(const i of K(t)){const t=0===i.kind?Sn(e,i.fieldPath,e.startAt):xn(e,i.fieldPath,e.startAt);n.push(t.value),r&&(r=t.inclusive)}return new Ht(n,r)}(s,i),u=function(e,t){const n=[];let r=!0;for(const i of K(t)){const t=0===i.kind?xn(e,i.fieldPath,e.endAt):Sn(e,i.fieldPath,e.endAt);n.push(t.value),r&&(r=t.inclusive)}return new Ht(n,r)}(s,i),l=this.En(i,s,c),h=this.En(i,s,u),d=this.dn(i,s,a),f=this.An(i.indexId,o,l,c.inclusive,h,u.inclusive,d);return ie.forEach(f,(i=>n.G(i,t.limit).next((t=>{t.forEach((t=>{const n=$.fromSegments(t.documentKey);e.has(n)||(e=e.add(n),r.push(n))}))}))))})).next((()=>r))}return ie.resolve(null)}))}Tn(e){let t=this.Pn.get(e);return t||(t=0===e.filters.length?[e]:bs(tn.create(e.filters,"and")).map((t=>bn(e.path,e.collectionGroup,e.orderBy,t.getFilters(),e.limit,e.startAt,e.endAt))),this.Pn.set(e,t),t)}An(e,t,n,r,i,s,o){const a=(null!=t?t.length:1)*Math.max(n.length,i.length),c=a/(null!=t?t.length:1),u=[];for(let l=0;l<a;++l){const a=t?this.Rn(t[l/c]):ks,h=this.Vn(e,a,n[l%c],r),d=this.mn(e,a,i[l%c],s),f=o.map((t=>this.Vn(e,a,t,!0)));u.push(...this.createRange(h,d,f))}return u}Vn(e,t,n,r){const i=new ps(e,$.empty(),t,n);return r?i:i.en()}mn(e,t,n,r){const i=new ps(e,$.empty(),t,n);return r?i.en():i}In(e,t){const n=new vs(t),r=null!=t.collectionGroup?t.collectionGroup:t.path.lastSegment();return this.getFieldIndexes(e,r).next((e=>{let t=null;for(const r of e)n.on(r)&&(!t||r.fields.length>t.fields.length)&&(t=r);return t}))}getIndexType(e,t){let n=2;const r=this.Tn(t);return ie.forEach(r,(t=>this.In(e,t).next((e=>{e?0!==n&&e.fields.length<function(e){let t=new st(j.comparator),n=!1;for(const r of e.filters)for(const e of r.getFlattenedFilters())e.field.isKeyField()||("array-contains"===e.op||"array-contains-any"===e.op?n=!0:t=t.add(e.field));for(const n of e.orderBy)n.field.isKeyField()||(t=t.add(n.field));return t.size+(n?1:0)}(t)&&(n=1):n=0})))).next((()=>function(e){return null!==e.limit}(t)&&r.length>1&&2===n?1:n))}fn(e,t){const n=new gs;for(const r of K(e)){const e=t.data.field(r.fieldPath);if(null==e)return null;const i=n.Xt(r.kind);cs.Ft.Et(e,i)}return n.Ht()}Rn(e){const t=new gs;return cs.Ft.Et(e,t.Xt(0)),t.Ht()}gn(e,t){const n=new gs;return cs.Ft.Et(Nt(this.databaseId,t),n.Xt(function(e){const t=K(e);return 0===t.length?0:t[t.length-1].kind}(e))),n.Ht()}dn(e,t,n){if(null===n)return[];let r=[];r.push(new gs);let i=0;for(const s of K(e)){const e=n[i++];for(const n of r)if(this.pn(t,s.fieldPath)&&Ot(e))r=this.yn(r,s,e);else{const t=n.Xt(s.kind);cs.Ft.Et(e,t)}}return this.wn(r)}En(e,t,n){return this.dn(e,t,n.position)}wn(e){const t=[];for(let n=0;n<e.length;++n)t[n]=e[n].Ht();return t}yn(e,t,n){const r=[...e],i=[];for(const e of n.arrayValue.values||[])for(const n of r){const r=new gs;r.seed(n.Ht()),cs.Ft.Et(e,r.Xt(t.kind)),i.push(r)}return i}pn(e,t){return!!e.filters.find((e=>e instanceof en&&e.field.isEqual(t)&&("in"===e.op||"not-in"===e.op)))}getFieldIndexes(e,t){const n=Ms(e),r=Rs(e);return(t?n.U("collectionGroupIndex",IDBKeyRange.bound(t,t)):n.U()).next((e=>{const t=[];return ie.forEach(e,(e=>r.get([e.indexId,this.uid]).next((n=>{t.push(function(e,t){const n=t?new J(t.sequenceNumber,new Z(Hi(t.readTime),new $(Te(t.documentKey)),t.largestBatchId)):J.empty(),r=e.fields.map((([e,t])=>new H(j.fromServerFormat(e),t)));return new z(e.indexId,e.collectionGroup,r,n)}(e,n))})))).next((()=>t))}))}getNextCollectionGroupToUpdate(e){return this.getFieldIndexes(e).next((e=>0===e.length?null:(e.sort(((e,t)=>{const n=e.indexState.sequenceNumber-t.indexState.sequenceNumber;return 0!==n?n:M(e.collectionGroup,t.collectionGroup)})),e[0].collectionGroup)))}updateCollectionGroup(e,t,n){const r=Ms(e),i=Rs(e);return this.Sn(e).next((e=>r.U("collectionGroupIndex",IDBKeyRange.bound(t,t)).next((t=>ie.forEach(t,(t=>i.put(ts(t.indexId,this.uid,e,n))))))))}updateIndexEntries(e,t){const n=new Map;return ie.forEach(t,((t,r)=>{const i=n.get(t.collectionGroup);return(i?ie.resolve(i):this.getFieldIndexes(e,t.collectionGroup)).next((i=>(n.set(t.collectionGroup,i),ie.forEach(i,(n=>this.bn(e,t,n).next((t=>{const i=this.Dn(r,n);return t.isEqual(i)?ie.resolve():this.vn(e,r,n,t,i)})))))))}))}Cn(e,t,n,r){return Os(e).put({indexId:r.indexId,uid:this.uid,arrayValue:r.arrayValue,directionalValue:r.directionalValue,orderedDocumentKey:this.gn(n,t.key),documentKey:t.key.path.toArray()})}Fn(e,t,n,r){return Os(e).delete([r.indexId,this.uid,r.arrayValue,r.directionalValue,this.gn(n,t.key),t.key.path.toArray()])}bn(e,t,n){const r=Os(e);let i=new st(ms);return r.J({index:"documentKeyIndex",range:IDBKeyRange.only([n.indexId,this.uid,this.gn(n,t)])},((e,r)=>{i=i.add(new ps(n.indexId,t,r.arrayValue,r.directionalValue))})).next((()=>i))}Dn(e,t){let n=new st(ms);const r=this.fn(t,e);if(null==r)return n;const i=G(t);if(null!=i){const s=e.data.field(i.fieldPath);if(Ot(s))for(const i of s.arrayValue.values||[])n=n.add(new ps(t.indexId,e.key,this.Rn(i),r))}else n=n.add(new ps(t.indexId,e.key,ks,r));return n}vn(e,t,n,r,i){g("IndexedDbIndexManager","Updating index entries for document '%s'",t.key);const s=[];return function(e,t,n,r,i){const s=e.getIterator(),o=t.getIterator();let a=at(s),c=at(o);for(;a||c;){let e=!1,t=!1;if(a&&c){const r=n(a,c);r<0?t=!0:r>0&&(e=!0)}else null!=a?t=!0:e=!0;e?(r(c),c=at(o)):t?(i(a),a=at(s)):(a=at(s),c=at(o))}}(r,i,ms,(r=>{s.push(this.Cn(e,t,n,r))}),(r=>{s.push(this.Fn(e,t,n,r))})),ie.waitFor(s)}Sn(e){let t=1;return Rs(e).J({index:"sequenceNumberIndex",reverse:!0,range:IDBKeyRange.upperBound([this.uid,Number.MAX_SAFE_INTEGER])},((e,n,r)=>{r.done(),t=n.sequenceNumber+1})).next((()=>t))}createRange(e,t,n){n=n.sort(((e,t)=>ms(e,t))).filter(((e,t,n)=>!t||0!==ms(e,n[t-1])));const r=[];r.push(e);for(const i of n){const n=ms(i,e),s=ms(i,t);if(0===n)r[0]=e.en();else if(n>0&&s<0)r.push(i),r.push(i.en());else if(s>0)break}r.push(t);const i=[];for(let e=0;e<r.length;e+=2){if(this.Mn(r[e],r[e+1]))return[];const t=[r[e].indexId,this.uid,r[e].arrayValue,r[e].directionalValue,ks,[]],n=[r[e+1].indexId,this.uid,r[e+1].arrayValue,r[e+1].directionalValue,ks,[]];i.push(IDBKeyRange.bound(t,n))}return i}Mn(e,t){return ms(e,t)>0}getMinOffsetFromCollectionGroup(e,t){return this.getFieldIndexes(e,t).next(Ps)}getMinOffset(e,t){return ie.mapArray(this.Tn(t),(t=>this.In(e,t).next((e=>e||v())))).next(Ps)}}function Ls(e){return Xe(e,"collectionParents")}function Os(e){return Xe(e,"indexEntries")}function Ms(e){return Xe(e,"indexConfiguration")}function Rs(e){return Xe(e,"indexState")}function Ps(e){w(0!==e.length);let t=e[0].indexState.offset,n=t.largestBatchId;for(let r=1;r<e.length;r++){const i=e[r].indexState.offset;ee(i,t)<0&&(t=i),n<i.largestBatchId&&(n=i.largestBatchId)}return new Z(t.readTime,t.documentKey,n)}const Fs={didRun:!1,sequenceNumbersCollected:0,targetsRemoved:0,documentsRemoved:0};class Vs{static withCacheSize(e){return new Vs(e,Vs.DEFAULT_COLLECTION_PERCENTILE,Vs.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT)}constructor(e,t,n){this.cacheSizeCollectionThreshold=e,this.percentileToCollect=t,this.maximumSequenceNumbersToCollect=n}}function qs(e,t,n){const r=e.store("mutations"),i=e.store("documentMutations"),s=[],o=IDBKeyRange.only(n.batchId);let a=0;const c=r.J({range:o},((e,t,n)=>(a++,n.delete())));s.push(c.next((()=>{w(1===a)})));const u=[];for(const e of n.mutations){const r=Ce(t,e.key.path,n.batchId);s.push(i.delete(r)),u.push(e.key)}return ie.waitFor(s).next((()=>u))}function Bs(e){if(!e)return 0;let t;if(e.document)t=e.document;else if(e.unknownDocument)t=e.unknownDocument;else{if(!e.noDocument)throw v();t=e.noDocument}return JSON.stringify(t).length}Vs.DEFAULT_COLLECTION_PERCENTILE=10,Vs.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT=1e3,Vs.DEFAULT=new Vs(41943040,Vs.DEFAULT_COLLECTION_PERCENTILE,Vs.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT),Vs.DISABLED=new Vs(-1,0,0);class Us{constructor(e,t,n,r){this.userId=e,this.serializer=t,this.indexManager=n,this.referenceDelegate=r,this.xn={}}static Pt(e,t,n,r){w(""!==e.uid);const i=e.isAuthenticated()?e.uid:"";return new Us(i,t,n,r)}checkEmpty(e){let t=!0;const n=IDBKeyRange.bound([this.userId,Number.NEGATIVE_INFINITY],[this.userId,Number.POSITIVE_INFINITY]);return $s(e).J({index:"userMutationsIndex",range:n},((e,n,r)=>{t=!1,r.done()})).next((()=>t))}addMutationBatch(e,t,n,r){const i=zs(e),s=$s(e);return s.add({}).next((o=>{w("number"==typeof o);const a=new Fr(o,t,n,r),c=function(e,t,n){const r=n.baseMutations.map((t=>Di(e.ht,t))),i=n.mutations.map((t=>Di(e.ht,t)));return{userId:t,batchId:n.batchId,localWriteTimeMs:n.localWriteTime.toMillis(),baseMutations:r,mutations:i}}(this.serializer,this.userId,a),u=[];let l=new st(((e,t)=>M(e.canonicalString(),t.canonicalString())));for(const e of r){const t=Ce(this.userId,e.key.path,o);l=l.add(e.key.path.popLast()),u.push(s.put(c)),u.push(i.put(t,De))}return l.forEach((t=>{u.push(this.indexManager.addToCollectionParentIndex(e,t))})),e.addOnCommittedListener((()=>{this.xn[o]=a.keys()})),ie.waitFor(u).next((()=>a))}))}lookupMutationBatch(e,t){return $s(e).get(t).next((e=>e?(w(e.userId===this.userId),Wi(this.serializer,e)):null))}On(e,t){return this.xn[t]?ie.resolve(this.xn[t]):this.lookupMutationBatch(e,t).next((e=>{if(e){const n=e.keys();return this.xn[t]=n,n}return null}))}getNextMutationBatchAfterBatchId(e,t){const n=t+1,r=IDBKeyRange.lowerBound([this.userId,n]);let i=null;return $s(e).J({index:"userMutationsIndex",range:r},((e,t,r)=>{t.userId===this.userId&&(w(t.batchId>=n),i=Wi(this.serializer,t)),r.done()})).next((()=>i))}getHighestUnacknowledgedBatchId(e){const t=IDBKeyRange.upperBound([this.userId,Number.POSITIVE_INFINITY]);let n=-1;return $s(e).J({index:"userMutationsIndex",range:t,reverse:!0},((e,t,r)=>{n=t.batchId,r.done()})).next((()=>n))}getAllMutationBatches(e){const t=IDBKeyRange.bound([this.userId,-1],[this.userId,Number.POSITIVE_INFINITY]);return $s(e).U("userMutationsIndex",t).next((e=>e.map((e=>Wi(this.serializer,e)))))}getAllMutationBatchesAffectingDocumentKey(e,t){const n=xe(this.userId,t.path),r=IDBKeyRange.lowerBound(n),i=[];return zs(e).J({range:r},((n,r,s)=>{const[o,a,c]=n,u=Te(a);if(o===this.userId&&t.path.isEqual(u))return $s(e).get(c).next((e=>{if(!e)throw v();w(e.userId===this.userId),i.push(Wi(this.serializer,e))}));s.done()})).next((()=>i))}getAllMutationBatchesAffectingDocumentKeys(e,t){let n=new st(M);const r=[];return t.forEach((t=>{const i=xe(this.userId,t.path),s=IDBKeyRange.lowerBound(i),o=zs(e).J({range:s},((e,r,i)=>{const[s,o,a]=e,c=Te(o);s===this.userId&&t.path.isEqual(c)?n=n.add(a):i.done()}));r.push(o)})),ie.waitFor(r).next((()=>this.Nn(e,n)))}getAllMutationBatchesAffectingQuery(e,t){const n=t.path,r=n.length+1,i=xe(this.userId,n),s=IDBKeyRange.lowerBound(i);let o=new st(M);return zs(e).J({range:s},((e,t,i)=>{const[s,a,c]=e,u=Te(a);s===this.userId&&n.isPrefixOf(u)?u.length===r&&(o=o.add(c)):i.done()})).next((()=>this.Nn(e,o)))}Nn(e,t){const n=[],r=[];return t.forEach((t=>{r.push($s(e).get(t).next((e=>{if(null===e)throw v();w(e.userId===this.userId),n.push(Wi(this.serializer,e))})))})),ie.waitFor(r).next((()=>n))}removeMutationBatch(e,t){return qs(e._e,this.userId,t).next((n=>(e.addOnCommittedListener((()=>{this.Ln(t.batchId)})),ie.forEach(n,(t=>this.referenceDelegate.markPotentiallyOrphaned(e,t))))))}Ln(e){delete this.xn[e]}performConsistencyCheck(e){return this.checkEmpty(e).next((t=>{if(!t)return ie.resolve();const n=IDBKeyRange.lowerBound(function(e){return[e]}(this.userId)),r=[];return zs(e).J({range:n},((e,t,n)=>{if(e[0]===this.userId){const t=Te(e[1]);r.push(t)}else n.done()})).next((()=>{w(0===r.length)}))}))}containsKey(e,t){return js(e,this.userId,t)}Bn(e){return Gs(e).get(this.userId).next((e=>e||{userId:this.userId,lastAcknowledgedBatchId:-1,lastStreamToken:""}))}}function js(e,t,n){const r=xe(t,n.path),i=r[1],s=IDBKeyRange.lowerBound(r);let o=!1;return zs(e).J({range:s,H:!0},((e,n,r)=>{const[s,a,c]=e;s===t&&a===i&&(o=!0),r.done()})).next((()=>o))}function $s(e){return Xe(e,"mutations")}function zs(e){return Xe(e,"documentMutations")}function Gs(e){return Xe(e,"mutationQueues")}class Ks{constructor(e){this.kn=e}next(){return this.kn+=2,this.kn}static qn(){return new Ks(0)}static Qn(){return new Ks(-1)}}class Qs{constructor(e,t){this.referenceDelegate=e,this.serializer=t}allocateTargetId(e){return this.Kn(e).next((t=>{const n=new Ks(t.highestTargetId);return t.highestTargetId=n.next(),this.$n(e,t).next((()=>t.highestTargetId))}))}getLastRemoteSnapshotVersion(e){return this.Kn(e).next((e=>V.fromTimestamp(new F(e.lastRemoteSnapshotVersion.seconds,e.lastRemoteSnapshotVersion.nanoseconds))))}getHighestSequenceNumber(e){return this.Kn(e).next((e=>e.highestListenSequenceNumber))}setTargetsMetadata(e,t,n){return this.Kn(e).next((r=>(r.highestListenSequenceNumber=t,n&&(r.lastRemoteSnapshotVersion=n.toTimestamp()),t>r.highestListenSequenceNumber&&(r.highestListenSequenceNumber=t),this.$n(e,r))))}addTargetData(e,t){return this.Un(e,t).next((()=>this.Kn(e).next((n=>(n.targetCount+=1,this.Wn(t,n),this.$n(e,n))))))}updateTargetData(e,t){return this.Un(e,t)}removeTargetData(e,t){return this.removeMatchingKeysForTargetId(e,t.targetId).next((()=>Hs(e).delete(t.targetId))).next((()=>this.Kn(e))).next((t=>(w(t.targetCount>0),t.targetCount-=1,this.$n(e,t))))}removeTargets(e,t,n){let r=0;const i=[];return Hs(e).J(((s,o)=>{const a=Ji(o);a.sequenceNumber<=t&&null===n.get(a.targetId)&&(r++,i.push(this.removeTargetData(e,a)))})).next((()=>ie.waitFor(i))).next((()=>r))}forEachTarget(e,t){return Hs(e).J(((e,n)=>{const r=Ji(n);t(r)}))}Kn(e){return Ws(e).get("targetGlobalKey").next((e=>(w(null!==e),e)))}$n(e,t){return Ws(e).put("targetGlobalKey",t)}Un(e,t){return Hs(e).put(Xi(this.serializer,t))}Wn(e,t){let n=!1;return e.targetId>t.highestTargetId&&(t.highestTargetId=e.targetId,n=!0),e.sequenceNumber>t.highestListenSequenceNumber&&(t.highestListenSequenceNumber=e.sequenceNumber,n=!0),n}getTargetCount(e){return this.Kn(e).next((e=>e.targetCount))}getTargetData(e,t){const n=_n(t),r=IDBKeyRange.bound([n,Number.NEGATIVE_INFINITY],[n,Number.POSITIVE_INFINITY]);let i=null;return Hs(e).J({range:r,index:"queryTargetsIndex"},((e,n,r)=>{const s=Ji(n);In(t,s.target)&&(i=s,r.done())})).next((()=>i))}addMatchingKeys(e,t,n){const r=[],i=Js(e);return t.forEach((t=>{const s=_e(t.path);r.push(i.put({targetId:n,path:s})),r.push(this.referenceDelegate.addReference(e,n,t))})),ie.waitFor(r)}removeMatchingKeys(e,t,n){const r=Js(e);return ie.forEach(t,(t=>{const i=_e(t.path);return ie.waitFor([r.delete([n,i]),this.referenceDelegate.removeReference(e,n,t)])}))}removeMatchingKeysForTargetId(e,t){const n=Js(e),r=IDBKeyRange.bound([t],[t+1],!1,!0);return n.delete(r)}getMatchingKeysForTargetId(e,t){const n=IDBKeyRange.bound([t],[t+1],!1,!0),r=Js(e);let i=nr();return r.J({range:n,H:!0},((e,t,n)=>{const r=Te(e[1]),s=new $(r);i=i.add(s)})).next((()=>i))}containsKey(e,t){const n=_e(t.path),r=IDBKeyRange.bound([n],[P(n)],!1,!0);let i=0;return Js(e).J({index:"documentTargetsIndex",H:!0,range:r},(([e,t],n,r)=>{0!==e&&(i++,r.done())})).next((()=>i>0))}ut(e,t){return Hs(e).get(t).next((e=>e?Ji(e):null))}}function Hs(e){return Xe(e,"targets")}function Ws(e){return Xe(e,"targetGlobal")}function Js(e){return Xe(e,"targetDocuments")}function Xs([e,t],[n,r]){const i=M(e,n);return 0===i?M(t,r):i}class Ys{constructor(e){this.Gn=e,this.buffer=new st(Xs),this.zn=0}jn(){return++this.zn}Hn(e){const t=[e,this.jn()];if(this.buffer.size<this.Gn)this.buffer=this.buffer.add(t);else{const e=this.buffer.last();Xs(t,e)<0&&(this.buffer=this.buffer.delete(e).add(t))}}get maxValue(){return this.buffer.last()[0]}}class Zs{constructor(e,t,n){this.garbageCollector=e,this.asyncQueue=t,this.localStore=n,this.Jn=null}start(){-1!==this.garbageCollector.params.cacheSizeCollectionThreshold&&this.Yn(6e4)}stop(){this.Jn&&(this.Jn.cancel(),this.Jn=null)}get started(){return null!==this.Jn}Yn(e){g("LruGarbageCollector",`Garbage collection scheduled in ${e}ms`),this.Jn=this.asyncQueue.enqueueAfterDelay("lru_garbage_collection",e,(async()=>{this.Jn=null;try{await this.localStore.collectGarbage(this.garbageCollector)}catch(e){le(e)?g("LruGarbageCollector","Ignoring IndexedDB error during garbage collection: ",e):await re(e)}await this.Yn(3e5)}))}}class eo{constructor(e,t){this.Zn=e,this.params=t}calculateTargetCount(e,t){return this.Zn.Xn(e).next((e=>Math.floor(t/100*e)))}nthSequenceNumber(e,t){if(0===t)return ie.resolve(ye.oe);const n=new Ys(t);return this.Zn.forEachTarget(e,(e=>n.Hn(e.sequenceNumber))).next((()=>this.Zn.er(e,(e=>n.Hn(e))))).next((()=>n.maxValue))}removeTargets(e,t,n){return this.Zn.removeTargets(e,t,n)}removeOrphanedDocuments(e,t){return this.Zn.removeOrphanedDocuments(e,t)}collect(e,t){return-1===this.params.cacheSizeCollectionThreshold?(g("LruGarbageCollector","Garbage collection skipped; disabled"),ie.resolve(Fs)):this.getCacheSize(e).next((n=>n<this.params.cacheSizeCollectionThreshold?(g("LruGarbageCollector",`Garbage collection skipped; Cache size ${n} is lower than threshold ${this.params.cacheSizeCollectionThreshold}`),Fs):this.tr(e,t)))}getCacheSize(e){return this.Zn.getCacheSize(e)}tr(e,t){let n,r,i,o,a,c,u;const l=Date.now();return this.calculateTargetCount(e,this.params.percentileToCollect).next((t=>(t>this.params.maximumSequenceNumbersToCollect?(g("LruGarbageCollector",`Capping sequence numbers to collect down to the maximum of ${this.params.maximumSequenceNumbersToCollect} from ${t}`),r=this.params.maximumSequenceNumbersToCollect):r=t,o=Date.now(),this.nthSequenceNumber(e,r)))).next((r=>(n=r,a=Date.now(),this.removeTargets(e,n,t)))).next((t=>(i=t,c=Date.now(),this.removeOrphanedDocuments(e,n)))).next((e=>(u=Date.now(),f()<=s.LogLevel.DEBUG&&g("LruGarbageCollector",`LRU Garbage Collection\n\tCounted targets in ${o-l}ms\n\tDetermined least recently used ${r} in `+(a-o)+"ms\n"+`\tRemoved ${i} targets in `+(c-a)+"ms\n"+`\tRemoved ${e} documents in `+(u-c)+"ms\n"+`Total Duration: ${u-l}ms`),ie.resolve({didRun:!0,sequenceNumbersCollected:r,targetsRemoved:i,documentsRemoved:e}))))}}function to(e,t){return new eo(e,t)}class no{constructor(e,t){this.db=e,this.garbageCollector=to(this,t)}Xn(e){const t=this.nr(e);return this.db.getTargetCache().getTargetCount(e).next((e=>t.next((t=>e+t))))}nr(e){let t=0;return this.er(e,(e=>{t++})).next((()=>t))}forEachTarget(e,t){return this.db.getTargetCache().forEachTarget(e,t)}er(e,t){return this.rr(e,((e,n)=>t(n)))}addReference(e,t,n){return ro(e,n)}removeReference(e,t,n){return ro(e,n)}removeTargets(e,t,n){return this.db.getTargetCache().removeTargets(e,t,n)}markPotentiallyOrphaned(e,t){return ro(e,t)}ir(e,t){return function(e,t){let n=!1;return Gs(e).Y((r=>js(e,r,t).next((e=>(e&&(n=!0),ie.resolve(!e)))))).next((()=>n))}(e,t)}removeOrphanedDocuments(e,t){const n=this.db.getRemoteDocumentCache().newChangeBuffer(),r=[];let i=0;return this.rr(e,((s,o)=>{if(o<=t){const t=this.ir(e,s).next((t=>{if(!t)return i++,n.getEntry(e,s).next((()=>(n.removeEntry(s,V.min()),Js(e).delete(function(e){return[0,_e(e.path)]}(s)))))}));r.push(t)}})).next((()=>ie.waitFor(r))).next((()=>n.apply(e))).next((()=>i))}removeTarget(e,t){const n=t.withSequenceNumber(e.currentSequenceNumber);return this.db.getTargetCache().updateTargetData(e,n)}updateLimboDocument(e,t){return ro(e,t)}rr(e,t){const n=Js(e);let r,i=ye.oe;return n.J({index:"documentTargetsIndex"},(([e,n],{path:s,sequenceNumber:o})=>{0===e?(i!==ye.oe&&t(new $(Te(r)),i),i=o,r=s):i=ye.oe})).next((()=>{i!==ye.oe&&t(new $(Te(r)),i)}))}getCacheSize(e){return this.db.getRemoteDocumentCache().getSize(e)}}function ro(e,t){return Js(e).put(function(e,t){return{targetId:0,path:_e(e.path),sequenceNumber:t}}(t,e.currentSequenceNumber))}class io{constructor(){this.changes=new Gn((e=>e.toString()),((e,t)=>e.isEqual(t))),this.changesApplied=!1}addEntry(e){this.assertNotApplied(),this.changes.set(e.key,e)}removeEntry(e,t){this.assertNotApplied(),this.changes.set(e,Qt.newInvalidDocument(e).setReadTime(t))}getEntry(e,t){this.assertNotApplied();const n=this.changes.get(t);return void 0!==n?ie.resolve(n):this.getFromCache(e,t)}getEntries(e,t){return this.getAllFromCache(e,t)}apply(e){return this.assertNotApplied(),this.changesApplied=!0,this.applyChanges(e)}assertNotApplied(){}}class so{constructor(e){this.serializer=e}setIndexManager(e){this.indexManager=e}addEntry(e,t,n){return uo(e).put(n)}removeEntry(e,t,n){return uo(e).delete(function(e,t){const n=e.path.toArray();return[n.slice(0,n.length-2),n[n.length-2],Ki(t),n[n.length-1]]}(t,n))}updateMetadata(e,t){return this.getMetadata(e).next((n=>(n.byteSize+=t,this.sr(e,n))))}getEntry(e,t){let n=Qt.newInvalidDocument(t);return uo(e).J({index:"documentKeyIndex",range:IDBKeyRange.only(lo(t))},((e,r)=>{n=this._r(t,r)})).next((()=>n))}ar(e,t){let n={size:0,document:Qt.newInvalidDocument(t)};return uo(e).J({index:"documentKeyIndex",range:IDBKeyRange.only(lo(t))},((e,r)=>{n={document:this._r(t,r),size:Bs(r)}})).next((()=>n))}getEntries(e,t){let n=Qn();return this.ur(e,t,((e,t)=>{const r=this._r(e,t);n=n.insert(e,r)})).next((()=>n))}cr(e,t){let n=Qn(),r=new nt($.comparator);return this.ur(e,t,((e,t)=>{const i=this._r(e,t);n=n.insert(e,i),r=r.insert(e,Bs(t))})).next((()=>({documents:n,lr:r})))}ur(e,t,n){if(t.isEmpty())return ie.resolve();let r=new st(fo);t.forEach((e=>r=r.add(e)));const i=IDBKeyRange.bound(lo(r.first()),lo(r.last())),s=r.getIterator();let o=s.getNext();return uo(e).J({index:"documentKeyIndex",range:i},((e,t,r)=>{const i=$.fromSegments([...t.prefixPath,t.collectionGroup,t.documentId]);for(;o&&fo(o,i)<0;)n(o,null),o=s.getNext();o&&o.isEqual(i)&&(n(o,t),o=s.hasNext()?s.getNext():null),o?r.$(lo(o)):r.done()})).next((()=>{for(;o;)n(o,null),o=s.hasNext()?s.getNext():null}))}getDocumentsMatchingQuery(e,t,n,r,i){const s=t.path,o=[s.popLast().toArray(),s.lastSegment(),Ki(n.readTime),n.documentKey.path.isEmpty()?"":n.documentKey.path.lastSegment()],a=[s.popLast().toArray(),s.lastSegment(),[Number.MAX_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],""];return uo(e).U(IDBKeyRange.bound(o,a,!0)).next((e=>{null==i||i.incrementDocumentReadCount(e.length);let n=Qn();for(const i of e){const e=this._r($.fromSegments(i.prefixPath.concat(i.collectionGroup,i.documentId)),i);e.isFoundDocument()&&(Un(t,e)||r.has(e.key))&&(n=n.insert(e.key,e))}return n}))}getAllFromCollectionGroup(e,t,n,r){let i=Qn();const s=ho(t,n),o=ho(t,Z.max());return uo(e).J({index:"collectionGroupIndex",range:IDBKeyRange.bound(s,o,!0)},((e,t,n)=>{const s=this._r($.fromSegments(t.prefixPath.concat(t.collectionGroup,t.documentId)),t);i=i.insert(s.key,s),i.size===r&&n.done()})).next((()=>i))}newChangeBuffer(e){return new ao(this,!!e&&e.trackRemovals)}getSize(e){return this.getMetadata(e).next((e=>e.byteSize))}getMetadata(e){return co(e).get("remoteDocumentGlobalKey").next((e=>(w(!!e),e)))}sr(e,t){return co(e).put("remoteDocumentGlobalKey",t)}_r(e,t){if(t){const e=function(e,t){let n;if(t.document)n=Ci(e.ht,t.document,!!t.hasCommittedMutations);else if(t.noDocument){const e=$.fromSegments(t.noDocument.path),r=Hi(t.noDocument.readTime);n=Qt.newNoDocument(e,r),t.hasCommittedMutations&&n.setHasCommittedMutations()}else{if(!t.unknownDocument)return v();{const e=$.fromSegments(t.unknownDocument.path),r=Hi(t.unknownDocument.version);n=Qt.newUnknownDocument(e,r)}}return t.readTime&&n.setReadTime(function(e){const t=new F(e[0],e[1]);return V.fromTimestamp(t)}(t.readTime)),n}(this.serializer,t);if(!e.isNoDocument()||!e.version.isEqual(V.min()))return e}return Qt.newInvalidDocument(e)}}function oo(e){return new so(e)}class ao extends io{constructor(e,t){super(),this.hr=e,this.trackRemovals=t,this.Pr=new Gn((e=>e.toString()),((e,t)=>e.isEqual(t)))}applyChanges(e){const t=[];let n=0,r=new st(((e,t)=>M(e.canonicalString(),t.canonicalString())));return this.changes.forEach(((i,s)=>{const o=this.Pr.get(i);if(t.push(this.hr.removeEntry(e,i,o.readTime)),s.isValidDocument()){const a=Gi(this.hr.serializer,s);r=r.add(i.path.popLast());const c=Bs(a);n+=c-o.size,t.push(this.hr.addEntry(e,i,a))}else if(n-=o.size,this.trackRemovals){const n=Gi(this.hr.serializer,s.convertToNoDocument(V.min()));t.push(this.hr.addEntry(e,i,n))}})),r.forEach((n=>{t.push(this.hr.indexManager.addToCollectionParentIndex(e,n))})),t.push(this.hr.updateMetadata(e,n)),ie.waitFor(t)}getFromCache(e,t){return this.hr.ar(e,t).next((e=>(this.Pr.set(t,{size:e.size,readTime:e.document.readTime}),e.document)))}getAllFromCache(e,t){return this.hr.cr(e,t).next((({documents:e,lr:t})=>(t.forEach(((t,n)=>{this.Pr.set(t,{size:n,readTime:e.get(t).readTime})})),e)))}}function co(e){return Xe(e,"remoteDocumentGlobal")}function uo(e){return Xe(e,"remoteDocumentsV14")}function lo(e){const t=e.path.toArray();return[t.slice(0,t.length-2),t[t.length-2],t[t.length-1]]}function ho(e,t){const n=t.documentKey.path.toArray();return[e,Ki(t.readTime),n.slice(0,n.length-2),n.length>0?n[n.length-1]:""]}function fo(e,t){const n=e.path.toArray(),r=t.path.toArray();let i=0;for(let e=0;e<n.length-2&&e<r.length-2;++e)if(i=M(n[e],r[e]),i)return i;return i=M(n.length,r.length),i||(i=M(n[n.length-2],r[r.length-2]),i||M(n[n.length-1],r[r.length-1]))}class go{constructor(e,t){this.overlayedDocument=e,this.mutatedFields=t}}class po{constructor(e,t,n,r){this.remoteDocumentCache=e,this.mutationQueue=t,this.documentOverlayCache=n,this.indexManager=r}getDocument(e,t){let n=null;return this.documentOverlayCache.getOverlay(e,t).next((r=>(n=r,this.remoteDocumentCache.getEntry(e,t)))).next((e=>(null!==n&&Cr(n.mutation,e,ct.empty(),F.now()),e)))}getDocuments(e,t){return this.remoteDocumentCache.getEntries(e,t).next((t=>this.getLocalViewOfDocuments(e,t,nr()).next((()=>t))))}getLocalViewOfDocuments(e,t,n=nr()){const r=Xn();return this.populateOverlays(e,r,t).next((()=>this.computeViews(e,t,r,n).next((e=>{let t=Wn();return e.forEach(((e,n)=>{t=t.insert(e,n.overlayedDocument)})),t}))))}getOverlayedDocuments(e,t){const n=Xn();return this.populateOverlays(e,n,t).next((()=>this.computeViews(e,t,n,nr())))}populateOverlays(e,t,n){const r=[];return n.forEach((e=>{t.has(e)||r.push(e)})),this.documentOverlayCache.getOverlays(e,r).next((e=>{e.forEach(((e,n)=>{t.set(e,n)}))}))}computeViews(e,t,n,r){let i=Qn();const s=Zn(),o=Zn();return t.forEach(((e,t)=>{const o=n.get(t.key);r.has(t.key)&&(void 0===o||o.mutation instanceof Nr)?i=i.insert(t.key,t):void 0!==o?(s.set(t.key,o.mutation.getFieldMask()),Cr(o.mutation,t,o.mutation.getFieldMask(),F.now())):s.set(t.key,ct.empty())})),this.recalculateAndSaveOverlays(e,i).next((e=>(e.forEach(((e,t)=>s.set(e,t))),t.forEach(((e,t)=>{var n;return o.set(e,new go(t,null!==(n=s.get(e))&&void 0!==n?n:null))})),o)))}recalculateAndSaveOverlays(e,t){const n=Zn();let r=new nt(((e,t)=>e-t)),i=nr();return this.mutationQueue.getAllMutationBatchesAffectingDocumentKeys(e,t).next((e=>{for(const i of e)i.keys().forEach((e=>{const s=t.get(e);if(null===s)return;let o=n.get(e)||ct.empty();o=i.applyToLocalView(s,o),n.set(e,o);const a=(r.get(i.batchId)||nr()).add(e);r=r.insert(i.batchId,a)}))})).next((()=>{const s=[],o=r.getReverseIterator();for(;o.hasNext();){const r=o.getNext(),a=r.key,c=r.value,u=Yn();c.forEach((e=>{if(!i.has(e)){const r=Sr(t.get(e),n.get(e));null!==r&&u.set(e,r),i=i.add(e)}})),s.push(this.documentOverlayCache.saveOverlays(e,a,u))}return ie.waitFor(s)})).next((()=>n))}recalculateAndSaveOverlaysForDocumentKeys(e,t){return this.remoteDocumentCache.getEntries(e,t).next((t=>this.recalculateAndSaveOverlays(e,t)))}getDocumentsMatchingQuery(e,t,n,r){return function(e){return $.isDocumentKey(e.path)&&null===e.collectionGroup&&0===e.filters.length}(t)?this.getDocumentsMatchingDocumentQuery(e,t.path):Nn(t)?this.getDocumentsMatchingCollectionGroupQuery(e,t,n,r):this.getDocumentsMatchingCollectionQuery(e,t,n,r)}getNextDocuments(e,t,n,r){return this.remoteDocumentCache.getAllFromCollectionGroup(e,t,n,r).next((i=>{const s=r-i.size>0?this.documentOverlayCache.getOverlaysForCollectionGroup(e,t,n.largestBatchId,r-i.size):ie.resolve(Xn());let o=-1,a=i;return s.next((t=>ie.forEach(t,((t,n)=>(o<n.largestBatchId&&(o=n.largestBatchId),i.get(t)?ie.resolve():this.remoteDocumentCache.getEntry(e,t).next((e=>{a=a.insert(t,e)}))))).next((()=>this.populateOverlays(e,t,i))).next((()=>this.computeViews(e,a,t,nr()))).next((e=>({batchId:o,changes:Jn(e)})))))}))}getDocumentsMatchingDocumentQuery(e,t){return this.getDocument(e,new $(t)).next((e=>{let t=Wn();return e.isFoundDocument()&&(t=t.insert(e.key,e)),t}))}getDocumentsMatchingCollectionGroupQuery(e,t,n,r){const i=t.collectionGroup;let s=Wn();return this.indexManager.getCollectionParents(e,i).next((o=>ie.forEach(o,(o=>{const a=function(e,t){return new Cn(t,null,e.explicitOrderBy.slice(),e.filters.slice(),e.limit,e.limitType,e.startAt,e.endAt)}(t,o.child(i));return this.getDocumentsMatchingCollectionQuery(e,a,n,r).next((e=>{e.forEach(((e,t)=>{s=s.insert(e,t)}))}))})).next((()=>s))))}getDocumentsMatchingCollectionQuery(e,t,n,r){let i;return this.documentOverlayCache.getOverlaysForCollection(e,t.path,n.largestBatchId).next((s=>(i=s,this.remoteDocumentCache.getDocumentsMatchingQuery(e,t,n,i,r)))).next((e=>{i.forEach(((t,n)=>{const r=n.getKey();null===e.get(r)&&(e=e.insert(r,Qt.newInvalidDocument(r)))}));let n=Wn();return e.forEach(((e,r)=>{const s=i.get(e);void 0!==s&&Cr(s.mutation,r,ct.empty(),F.now()),Un(t,r)&&(n=n.insert(e,r))})),n}))}}class mo{constructor(e){this.serializer=e,this.Tr=new Map,this.Ir=new Map}getBundleMetadata(e,t){return ie.resolve(this.Tr.get(t))}saveBundleMetadata(e,t){return this.Tr.set(t.id,function(e){return{id:e.id,version:e.version,createTime:mi(e.createTime)}}(t)),ie.resolve()}getNamedQuery(e,t){return ie.resolve(this.Ir.get(t))}saveNamedQuery(e,t){return this.Ir.set(t.name,function(e){return{name:e.name,query:Yi(e.bundledQuery),readTime:mi(e.readTime)}}(t)),ie.resolve()}}class yo{constructor(){this.overlays=new nt($.comparator),this.Er=new Map}getOverlay(e,t){return ie.resolve(this.overlays.get(t))}getOverlays(e,t){const n=Xn();return ie.forEach(t,(t=>this.getOverlay(e,t).next((e=>{null!==e&&n.set(t,e)})))).next((()=>n))}saveOverlays(e,t,n){return n.forEach(((n,r)=>{this.Tt(e,t,r)})),ie.resolve()}removeOverlaysForBatchId(e,t,n){const r=this.Er.get(n);return void 0!==r&&(r.forEach((e=>this.overlays=this.overlays.remove(e))),this.Er.delete(n)),ie.resolve()}getOverlaysForCollection(e,t,n){const r=Xn(),i=t.length+1,s=new $(t.child("")),o=this.overlays.getIteratorFrom(s);for(;o.hasNext();){const e=o.getNext().value,s=e.getKey();if(!t.isPrefixOf(s.path))break;s.path.length===i&&e.largestBatchId>n&&r.set(e.getKey(),e)}return ie.resolve(r)}getOverlaysForCollectionGroup(e,t,n,r){let i=new nt(((e,t)=>e-t));const s=this.overlays.getIterator();for(;s.hasNext();){const e=s.getNext().value;if(e.getKey().getCollectionGroup()===t&&e.largestBatchId>n){let t=i.get(e.largestBatchId);null===t&&(t=Xn(),i=i.insert(e.largestBatchId,t)),t.set(e.getKey(),e)}}const o=Xn(),a=i.getIterator();for(;a.hasNext()&&(a.getNext().value.forEach(((e,t)=>o.set(e,t))),!(o.size()>=r)););return ie.resolve(o)}Tt(e,t,n){const r=this.overlays.get(n.key);if(null!==r){const e=this.Er.get(r.largestBatchId).delete(n.key);this.Er.set(r.largestBatchId,e)}this.overlays=this.overlays.insert(n.key,new qr(t,n));let i=this.Er.get(t);void 0===i&&(i=nr(),this.Er.set(t,i)),this.Er.set(t,i.add(n.key))}}class vo{constructor(){this.sessionToken=lt.EMPTY_BYTE_STRING}getSessionToken(e){return ie.resolve(this.sessionToken)}setSessionToken(e,t){return this.sessionToken=t,ie.resolve()}}class wo{constructor(){this.dr=new st(bo.Ar),this.Rr=new st(bo.Vr)}isEmpty(){return this.dr.isEmpty()}addReference(e,t){const n=new bo(e,t);this.dr=this.dr.add(n),this.Rr=this.Rr.add(n)}mr(e,t){e.forEach((e=>this.addReference(e,t)))}removeReference(e,t){this.gr(new bo(e,t))}pr(e,t){e.forEach((e=>this.removeReference(e,t)))}yr(e){const t=new $(new B([])),n=new bo(t,e),r=new bo(t,e+1),i=[];return this.Rr.forEachInRange([n,r],(e=>{this.gr(e),i.push(e.key)})),i}wr(){this.dr.forEach((e=>this.gr(e)))}gr(e){this.dr=this.dr.delete(e),this.Rr=this.Rr.delete(e)}Sr(e){const t=new $(new B([])),n=new bo(t,e),r=new bo(t,e+1);let i=nr();return this.Rr.forEachInRange([n,r],(e=>{i=i.add(e.key)})),i}containsKey(e){const t=new bo(e,0),n=this.dr.firstAfterOrEqual(t);return null!==n&&e.isEqual(n.key)}}class bo{constructor(e,t){this.key=e,this.br=t}static Ar(e,t){return $.comparator(e.key,t.key)||M(e.br,t.br)}static Vr(e,t){return M(e.br,t.br)||$.comparator(e.key,t.key)}}class _o{constructor(e,t){this.indexManager=e,this.referenceDelegate=t,this.mutationQueue=[],this.Dr=1,this.vr=new st(bo.Ar)}checkEmpty(e){return ie.resolve(0===this.mutationQueue.length)}addMutationBatch(e,t,n,r){const i=this.Dr;this.Dr++,this.mutationQueue.length>0&&this.mutationQueue[this.mutationQueue.length-1];const s=new Fr(i,t,n,r);this.mutationQueue.push(s);for(const t of r)this.vr=this.vr.add(new bo(t.key,i)),this.indexManager.addToCollectionParentIndex(e,t.key.path.popLast());return ie.resolve(s)}lookupMutationBatch(e,t){return ie.resolve(this.Cr(t))}getNextMutationBatchAfterBatchId(e,t){const n=t+1,r=this.Fr(n),i=r<0?0:r;return ie.resolve(this.mutationQueue.length>i?this.mutationQueue[i]:null)}getHighestUnacknowledgedBatchId(){return ie.resolve(0===this.mutationQueue.length?-1:this.Dr-1)}getAllMutationBatches(e){return ie.resolve(this.mutationQueue.slice())}getAllMutationBatchesAffectingDocumentKey(e,t){const n=new bo(t,0),r=new bo(t,Number.POSITIVE_INFINITY),i=[];return this.vr.forEachInRange([n,r],(e=>{const t=this.Cr(e.br);i.push(t)})),ie.resolve(i)}getAllMutationBatchesAffectingDocumentKeys(e,t){let n=new st(M);return t.forEach((e=>{const t=new bo(e,0),r=new bo(e,Number.POSITIVE_INFINITY);this.vr.forEachInRange([t,r],(e=>{n=n.add(e.br)}))})),ie.resolve(this.Mr(n))}getAllMutationBatchesAffectingQuery(e,t){const n=t.path,r=n.length+1;let i=n;$.isDocumentKey(i)||(i=i.child(""));const s=new bo(new $(i),0);let o=new st(M);return this.vr.forEachWhile((e=>{const t=e.key.path;return!!n.isPrefixOf(t)&&(t.length===r&&(o=o.add(e.br)),!0)}),s),ie.resolve(this.Mr(o))}Mr(e){const t=[];return e.forEach((e=>{const n=this.Cr(e);null!==n&&t.push(n)})),t}removeMutationBatch(e,t){w(0===this.Or(t.batchId,"removed")),this.mutationQueue.shift();let n=this.vr;return ie.forEach(t.mutations,(r=>{const i=new bo(r.key,t.batchId);return n=n.delete(i),this.referenceDelegate.markPotentiallyOrphaned(e,r.key)})).next((()=>{this.vr=n}))}Ln(e){}containsKey(e,t){const n=new bo(t,0),r=this.vr.firstAfterOrEqual(n);return ie.resolve(t.isEqual(r&&r.key))}performConsistencyCheck(e){return this.mutationQueue.length,ie.resolve()}Or(e,t){return this.Fr(e)}Fr(e){return 0===this.mutationQueue.length?0:e-this.mutationQueue[0].batchId}Cr(e){const t=this.Fr(e);return t<0||t>=this.mutationQueue.length?null:this.mutationQueue[t]}}class Io{constructor(e){this.Nr=e,this.docs=new nt($.comparator),this.size=0}setIndexManager(e){this.indexManager=e}addEntry(e,t){const n=t.key,r=this.docs.get(n),i=r?r.size:0,s=this.Nr(t);return this.docs=this.docs.insert(n,{document:t.mutableCopy(),size:s}),this.size+=s-i,this.indexManager.addToCollectionParentIndex(e,n.path.popLast())}removeEntry(e){const t=this.docs.get(e);t&&(this.docs=this.docs.remove(e),this.size-=t.size)}getEntry(e,t){const n=this.docs.get(t);return ie.resolve(n?n.document.mutableCopy():Qt.newInvalidDocument(t))}getEntries(e,t){let n=Qn();return t.forEach((e=>{const t=this.docs.get(e);n=n.insert(e,t?t.document.mutableCopy():Qt.newInvalidDocument(e))})),ie.resolve(n)}getDocumentsMatchingQuery(e,t,n,r){let i=Qn();const s=t.path,o=new $(s.child("")),a=this.docs.getIteratorFrom(o);for(;a.hasNext();){const{key:e,value:{document:o}}=a.getNext();if(!s.isPrefixOf(e.path))break;e.path.length>s.length+1||ee(Y(o),n)<=0||(r.has(o.key)||Un(t,o))&&(i=i.insert(o.key,o.mutableCopy()))}return ie.resolve(i)}getAllFromCollectionGroup(e,t,n,r){v()}Lr(e,t){return ie.forEach(this.docs,(e=>t(e)))}newChangeBuffer(e){return new Eo(this)}getSize(e){return ie.resolve(this.size)}}class Eo extends io{constructor(e){super(),this.hr=e}applyChanges(e){const t=[];return this.changes.forEach(((n,r)=>{r.isValidDocument()?t.push(this.hr.addEntry(e,r)):this.hr.removeEntry(n)})),ie.waitFor(t)}getFromCache(e,t){return this.hr.getEntry(e,t)}getAllFromCache(e,t){return this.hr.getEntries(e,t)}}class To{constructor(e){this.persistence=e,this.Br=new Gn((e=>_n(e)),In),this.lastRemoteSnapshotVersion=V.min(),this.highestTargetId=0,this.kr=0,this.qr=new wo,this.targetCount=0,this.Qr=Ks.qn()}forEachTarget(e,t){return this.Br.forEach(((e,n)=>t(n))),ie.resolve()}getLastRemoteSnapshotVersion(e){return ie.resolve(this.lastRemoteSnapshotVersion)}getHighestSequenceNumber(e){return ie.resolve(this.kr)}allocateTargetId(e){return this.highestTargetId=this.Qr.next(),ie.resolve(this.highestTargetId)}setTargetsMetadata(e,t,n){return n&&(this.lastRemoteSnapshotVersion=n),t>this.kr&&(this.kr=t),ie.resolve()}Un(e){this.Br.set(e.target,e);const t=e.targetId;t>this.highestTargetId&&(this.Qr=new Ks(t),this.highestTargetId=t),e.sequenceNumber>this.kr&&(this.kr=e.sequenceNumber)}addTargetData(e,t){return this.Un(t),this.targetCount+=1,ie.resolve()}updateTargetData(e,t){return this.Un(t),ie.resolve()}removeTargetData(e,t){return this.Br.delete(t.target),this.qr.yr(t.targetId),this.targetCount-=1,ie.resolve()}removeTargets(e,t,n){let r=0;const i=[];return this.Br.forEach(((s,o)=>{o.sequenceNumber<=t&&null===n.get(o.targetId)&&(this.Br.delete(s),i.push(this.removeMatchingKeysForTargetId(e,o.targetId)),r++)})),ie.waitFor(i).next((()=>r))}getTargetCount(e){return ie.resolve(this.targetCount)}getTargetData(e,t){const n=this.Br.get(t)||null;return ie.resolve(n)}addMatchingKeys(e,t,n){return this.qr.mr(t,n),ie.resolve()}removeMatchingKeys(e,t,n){this.qr.pr(t,n);const r=this.persistence.referenceDelegate,i=[];return r&&t.forEach((t=>{i.push(r.markPotentiallyOrphaned(e,t))})),ie.waitFor(i)}removeMatchingKeysForTargetId(e,t){return this.qr.yr(t),ie.resolve()}getMatchingKeysForTargetId(e,t){const n=this.qr.Sr(t);return ie.resolve(n)}containsKey(e,t){return ie.resolve(this.qr.containsKey(t))}}class So{constructor(e,t){this.Kr={},this.overlays={},this.$r=new ye(0),this.Ur=!1,this.Ur=!0,this.Wr=new vo,this.referenceDelegate=e(this),this.Gr=new To(this),this.indexManager=new Ds,this.remoteDocumentCache=function(e){return new Io(e)}((e=>this.referenceDelegate.zr(e))),this.serializer=new zi(t),this.jr=new mo(this.serializer)}start(){return Promise.resolve()}shutdown(){return this.Ur=!1,Promise.resolve()}get started(){return this.Ur}setDatabaseDeletedListener(){}setNetworkEnabled(){}getIndexManager(e){return this.indexManager}getDocumentOverlayCache(e){let t=this.overlays[e.toKey()];return t||(t=new yo,this.overlays[e.toKey()]=t),t}getMutationQueue(e,t){let n=this.Kr[e.toKey()];return n||(n=new _o(t,this.referenceDelegate),this.Kr[e.toKey()]=n),n}getGlobalsCache(){return this.Wr}getTargetCache(){return this.Gr}getRemoteDocumentCache(){return this.remoteDocumentCache}getBundleCache(){return this.jr}runTransaction(e,t,n){g("MemoryPersistence","Starting transaction:",e);const r=new xo(this.$r.next());return this.referenceDelegate.Hr(),n(r).next((e=>this.referenceDelegate.Jr(r).next((()=>e)))).toPromise().then((e=>(r.raiseOnCommittedEvent(),e)))}Yr(e,t){return ie.or(Object.values(this.Kr).map((n=>()=>n.containsKey(e,t))))}}class xo extends ne{constructor(e){super(),this.currentSequenceNumber=e}}class Co{constructor(e){this.persistence=e,this.Zr=new wo,this.Xr=null}static ei(e){return new Co(e)}get ti(){if(this.Xr)return this.Xr;throw v()}addReference(e,t,n){return this.Zr.addReference(n,t),this.ti.delete(n.toString()),ie.resolve()}removeReference(e,t,n){return this.Zr.removeReference(n,t),this.ti.add(n.toString()),ie.resolve()}markPotentiallyOrphaned(e,t){return this.ti.add(t.toString()),ie.resolve()}removeTarget(e,t){this.Zr.yr(t.targetId).forEach((e=>this.ti.add(e.toString())));const n=this.persistence.getTargetCache();return n.getMatchingKeysForTargetId(e,t.targetId).next((e=>{e.forEach((e=>this.ti.add(e.toString())))})).next((()=>n.removeTargetData(e,t)))}Hr(){this.Xr=new Set}Jr(e){const t=this.persistence.getRemoteDocumentCache().newChangeBuffer();return ie.forEach(this.ti,(n=>{const r=$.fromPath(n);return this.ni(e,r).next((e=>{e||t.removeEntry(r,V.min())}))})).next((()=>(this.Xr=null,t.apply(e))))}updateLimboDocument(e,t){return this.ni(e,t).next((e=>{e?this.ti.delete(t.toString()):this.ti.add(t.toString())}))}zr(e){return 0}ni(e,t){return ie.or([()=>ie.resolve(this.Zr.containsKey(t)),()=>this.persistence.getTargetCache().containsKey(e,t),()=>this.persistence.Yr(e,t)])}}class Do{constructor(e,t){this.persistence=e,this.ri=new Gn((e=>_e(e.path)),((e,t)=>e.isEqual(t))),this.garbageCollector=to(this,t)}static ei(e,t){return new Do(e,t)}Hr(){}Jr(e){return ie.resolve()}forEachTarget(e,t){return this.persistence.getTargetCache().forEachTarget(e,t)}Xn(e){const t=this.nr(e);return this.persistence.getTargetCache().getTargetCount(e).next((e=>t.next((t=>e+t))))}nr(e){let t=0;return this.er(e,(e=>{t++})).next((()=>t))}er(e,t){return ie.forEach(this.ri,((n,r)=>this.ir(e,n,r).next((e=>e?ie.resolve():t(r)))))}removeTargets(e,t,n){return this.persistence.getTargetCache().removeTargets(e,t,n)}removeOrphanedDocuments(e,t){let n=0;const r=this.persistence.getRemoteDocumentCache(),i=r.newChangeBuffer();return r.Lr(e,(r=>this.ir(e,r,t).next((e=>{e||(n++,i.removeEntry(r,V.min()))})))).next((()=>i.apply(e))).next((()=>n))}markPotentiallyOrphaned(e,t){return this.ri.set(t,e.currentSequenceNumber),ie.resolve()}removeTarget(e,t){const n=t.withSequenceNumber(e.currentSequenceNumber);return this.persistence.getTargetCache().updateTargetData(e,n)}addReference(e,t,n){return this.ri.set(n,e.currentSequenceNumber),ie.resolve()}removeReference(e,t,n){return this.ri.set(n,e.currentSequenceNumber),ie.resolve()}updateLimboDocument(e,t){return this.ri.set(t,e.currentSequenceNumber),ie.resolve()}zr(e){let t=e.key.toString().length;return e.isFoundDocument()&&(t+=kt(e.data.value)),t}ir(e,t,n){return ie.or([()=>this.persistence.Yr(e,t),()=>this.persistence.getTargetCache().containsKey(e,t),()=>{const e=this.ri.get(t);return ie.resolve(void 0!==e&&e>n)}])}getCacheSize(e){return this.persistence.getRemoteDocumentCache().getSize(e)}}class Ao{constructor(e){this.serializer=e}O(e,t,n,r){const i=new se("createOrUpgrade",t);n<1&&r>=1&&(function(e){e.createObjectStore("owner")}(e),function(e){e.createObjectStore("mutationQueues",{keyPath:"userId"}),e.createObjectStore("mutations",{keyPath:"batchId",autoIncrement:!0}).createIndex("userMutationsIndex",Se,{unique:!0}),e.createObjectStore("documentMutations")}(e),ko(e),function(e){e.createObjectStore("remoteDocuments")}(e));let s=ie.resolve();return n<3&&r>=3&&(0!==n&&(function(e){e.deleteObjectStore("targetDocuments"),e.deleteObjectStore("targets"),e.deleteObjectStore("targetGlobal")}(e),ko(e)),s=s.next((()=>function(e){const t=e.store("targetGlobal"),n={highestTargetId:0,highestListenSequenceNumber:0,lastRemoteSnapshotVersion:V.min().toTimestamp(),targetCount:0};return t.put("targetGlobalKey",n)}(i)))),n<4&&r>=4&&(0!==n&&(s=s.next((()=>function(e,t){return t.store("mutations").U().next((n=>{e.deleteObjectStore("mutations"),e.createObjectStore("mutations",{keyPath:"batchId",autoIncrement:!0}).createIndex("userMutationsIndex",Se,{unique:!0});const r=t.store("mutations"),i=n.map((e=>r.put(e)));return ie.waitFor(i)}))}(e,i)))),s=s.next((()=>{!function(e){e.createObjectStore("clientMetadata",{keyPath:"clientId"})}(e)}))),n<5&&r>=5&&(s=s.next((()=>this.ii(i)))),n<6&&r>=6&&(s=s.next((()=>(function(e){e.createObjectStore("remoteDocumentGlobal")}(e),this.si(i))))),n<7&&r>=7&&(s=s.next((()=>this.oi(i)))),n<8&&r>=8&&(s=s.next((()=>this._i(e,i)))),n<9&&r>=9&&(s=s.next((()=>{!function(e){e.objectStoreNames.contains("remoteDocumentChanges")&&e.deleteObjectStore("remoteDocumentChanges")}(e)}))),n<10&&r>=10&&(s=s.next((()=>this.ai(i)))),n<11&&r>=11&&(s=s.next((()=>{!function(e){e.createObjectStore("bundles",{keyPath:"bundleId"})}(e),function(e){e.createObjectStore("namedQueries",{keyPath:"name"})}(e)}))),n<12&&r>=12&&(s=s.next((()=>{!function(e){const t=e.createObjectStore("documentOverlays",{keyPath:Be});t.createIndex("collectionPathOverlayIndex",Ue,{unique:!1}),t.createIndex("collectionGroupOverlayIndex",je,{unique:!1})}(e)}))),n<13&&r>=13&&(s=s.next((()=>function(e){const t=e.createObjectStore("remoteDocumentsV14",{keyPath:Ae});t.createIndex("documentKeyIndex",ke),t.createIndex("collectionGroupIndex",Ne)}(e))).next((()=>this.ui(e,i))).next((()=>e.deleteObjectStore("remoteDocuments")))),n<14&&r>=14&&(s=s.next((()=>this.ci(e,i)))),n<15&&r>=15&&(s=s.next((()=>function(e){e.createObjectStore("indexConfiguration",{keyPath:"indexId",autoIncrement:!0}).createIndex("collectionGroupIndex","collectionGroup",{unique:!1}),e.createObjectStore("indexState",{keyPath:Pe}).createIndex("sequenceNumberIndex",Fe,{unique:!1}),e.createObjectStore("indexEntries",{keyPath:Ve}).createIndex("documentKeyIndex",qe,{unique:!1})}(e)))),n<16&&r>=16&&(s=s.next((()=>{t.objectStore("indexState").clear()})).next((()=>{t.objectStore("indexEntries").clear()}))),n<17&&r>=17&&(s=s.next((()=>{!function(e){e.createObjectStore("globals",{keyPath:"name"})}(e)}))),s}si(e){let t=0;return e.store("remoteDocuments").J(((e,n)=>{t+=Bs(n)})).next((()=>{const n={byteSize:t};return e.store("remoteDocumentGlobal").put("remoteDocumentGlobalKey",n)}))}ii(e){const t=e.store("mutationQueues"),n=e.store("mutations");return t.U().next((t=>ie.forEach(t,(t=>{const r=IDBKeyRange.bound([t.userId,-1],[t.userId,t.lastAcknowledgedBatchId]);return n.U("userMutationsIndex",r).next((n=>ie.forEach(n,(n=>{w(n.userId===t.userId);const r=Wi(this.serializer,n);return qs(e,t.userId,r).next((()=>{}))}))))}))))}oi(e){const t=e.store("targetDocuments"),n=e.store("remoteDocuments");return e.store("targetGlobal").get("targetGlobalKey").next((e=>{const r=[];return n.J(((n,i)=>{const s=new B(n),o=function(e){return[0,_e(e)]}(s);r.push(t.get(o).next((n=>n?ie.resolve():(n=>t.put({targetId:0,path:_e(n),sequenceNumber:e.highestListenSequenceNumber}))(s))))})).next((()=>ie.waitFor(r)))}))}_i(e,t){e.createObjectStore("collectionParents",{keyPath:Re});const n=t.store("collectionParents"),r=new As,i=e=>{if(r.add(e)){const t=e.lastSegment(),r=e.popLast();return n.put({collectionId:t,parent:_e(r)})}};return t.store("remoteDocuments").J({H:!0},((e,t)=>{const n=new B(e);return i(n.popLast())})).next((()=>t.store("documentMutations").J({H:!0},(([e,t,n],r)=>{const s=Te(t);return i(s.popLast())}))))}ai(e){const t=e.store("targets");return t.J(((e,n)=>{const r=Ji(n),i=Xi(this.serializer,r);return t.put(i)}))}ui(e,t){const n=t.store("remoteDocuments"),r=[];return n.J(((e,n)=>{const i=t.store("remoteDocumentsV14"),s=function(e){return e.document?new $(B.fromString(e.document.name).popFirst(5)):e.noDocument?$.fromSegments(e.noDocument.path):e.unknownDocument?$.fromSegments(e.unknownDocument.path):v()}(n).path.toArray(),o={prefixPath:s.slice(0,s.length-2),collectionGroup:s[s.length-2],documentId:s[s.length-1],readTime:n.readTime||[0,0],unknownDocument:n.unknownDocument,noDocument:n.noDocument,document:n.document,hasCommittedMutations:!!n.hasCommittedMutations};r.push(i.put(o))})).next((()=>ie.waitFor(r)))}ci(e,t){const n=t.store("mutations"),r=oo(this.serializer),i=new So(Co.ei,this.serializer.ht);return n.U().next((e=>{const n=new Map;return e.forEach((e=>{var t;let r=null!==(t=n.get(e.userId))&&void 0!==t?t:nr();Wi(this.serializer,e).keys().forEach((e=>r=r.add(e))),n.set(e.userId,r)})),ie.forEach(n,((e,n)=>{const s=new l(n),o=ss.Pt(this.serializer,s),a=i.getIndexManager(s),c=Us.Pt(s,this.serializer,a,i.referenceDelegate);return new po(r,c,o,a).recalculateAndSaveOverlaysForDocumentKeys(new Je(t,ye.oe),e).next()}))}))}}function ko(e){e.createObjectStore("targetDocuments",{keyPath:Oe}).createIndex("documentTargetsIndex",Me,{unique:!0}),e.createObjectStore("targets",{keyPath:"targetId"}).createIndex("queryTargetsIndex",Le,{unique:!0}),e.createObjectStore("targetGlobal")}const No="Failed to obtain exclusive access to the persistence layer. To allow shared access, multi-tab synchronization has to be enabled in all tabs. If you are using `experimentalForceOwningTab:true`, make sure that only one tab has persistence enabled at any given time.";class Lo{constructor(e,t,n,r,i,s,o,a,c,u,l=17){if(this.allowTabSynchronization=e,this.persistenceKey=t,this.clientId=n,this.li=i,this.window=s,this.document=o,this.hi=c,this.Pi=u,this.Ti=l,this.$r=null,this.Ur=!1,this.isPrimary=!1,this.networkEnabled=!0,this.Ii=null,this.inForeground=!1,this.Ei=null,this.di=null,this.Ai=Number.NEGATIVE_INFINITY,this.Ri=e=>Promise.resolve(),!Lo.p())throw new I(_.UNIMPLEMENTED,"This platform is either missing IndexedDB or is known to have an incomplete implementation. Offline persistence has been disabled.");this.referenceDelegate=new no(this,r),this.Vi=t+"main",this.serializer=new zi(a),this.mi=new oe(this.Vi,this.Ti,new Ao(this.serializer)),this.Wr=new as,this.Gr=new Qs(this.referenceDelegate,this.serializer),this.remoteDocumentCache=oo(this.serializer),this.jr=new ns,this.window&&this.window.localStorage?this.fi=this.window.localStorage:(this.fi=null,!1===u&&p("IndexedDbPersistence","LocalStorage is unavailable. As a result, persistence may not work reliably. In particular enablePersistence() could fail immediately after refreshing the page."))}start(){return this.gi().then((()=>{if(!this.isPrimary&&!this.allowTabSynchronization)throw new I(_.FAILED_PRECONDITION,No);return this.pi(),this.yi(),this.wi(),this.runTransaction("getHighestListenSequenceNumber","readonly",(e=>this.Gr.getHighestSequenceNumber(e)))})).then((e=>{this.$r=new ye(e,this.hi)})).then((()=>{this.Ur=!0})).catch((e=>(this.mi&&this.mi.close(),Promise.reject(e))))}Si(e){return this.Ri=async t=>{if(this.started)return e(t)},e(this.isPrimary)}setDatabaseDeletedListener(e){this.mi.L((async t=>{null===t.newVersion&&await e()}))}setNetworkEnabled(e){this.networkEnabled!==e&&(this.networkEnabled=e,this.li.enqueueAndForget((async()=>{this.started&&await this.gi()})))}gi(){return this.runTransaction("updateClientMetadataAndTryBecomePrimary","readwrite",(e=>Mo(e).put({clientId:this.clientId,updateTimeMs:Date.now(),networkEnabled:this.networkEnabled,inForeground:this.inForeground}).next((()=>{if(this.isPrimary)return this.bi(e).next((e=>{e||(this.isPrimary=!1,this.li.enqueueRetryable((()=>this.Ri(!1))))}))})).next((()=>this.Di(e))).next((t=>this.isPrimary&&!t?this.vi(e).next((()=>!1)):!!t&&this.Ci(e).next((()=>!0)))))).catch((e=>{if(le(e))return g("IndexedDbPersistence","Failed to extend owner lease: ",e),this.isPrimary;if(!this.allowTabSynchronization)throw e;return g("IndexedDbPersistence","Releasing owner lease after error during lease refresh",e),!1})).then((e=>{this.isPrimary!==e&&this.li.enqueueRetryable((()=>this.Ri(e))),this.isPrimary=e}))}bi(e){return Oo(e).get("owner").next((e=>ie.resolve(this.Fi(e))))}Mi(e){return Mo(e).delete(this.clientId)}async xi(){if(this.isPrimary&&!this.Oi(this.Ai,18e5)){this.Ai=Date.now();const e=await this.runTransaction("maybeGarbageCollectMultiClientState","readwrite-primary",(e=>{const t=Xe(e,"clientMetadata");return t.U().next((e=>{const n=this.Ni(e,18e5),r=e.filter((e=>-1===n.indexOf(e)));return ie.forEach(r,(e=>t.delete(e.clientId))).next((()=>r))}))})).catch((()=>[]));if(this.fi)for(const t of e)this.fi.removeItem(this.Li(t.clientId))}}wi(){this.di=this.li.enqueueAfterDelay("client_metadata_refresh",4e3,(()=>this.gi().then((()=>this.xi())).then((()=>this.wi()))))}Fi(e){return!!e&&e.ownerId===this.clientId}Di(e){return this.Pi?ie.resolve(!0):Oo(e).get("owner").next((t=>{if(null!==t&&this.Oi(t.leaseTimestampMs,5e3)&&!this.Bi(t.ownerId)){if(this.Fi(t)&&this.networkEnabled)return!0;if(!this.Fi(t)){if(!t.allowTabSynchronization)throw new I(_.FAILED_PRECONDITION,No);return!1}}return!(!this.networkEnabled||!this.inForeground)||Mo(e).U().next((e=>void 0===this.Ni(e,5e3).find((e=>{if(this.clientId!==e.clientId){const t=!this.networkEnabled&&e.networkEnabled,n=!this.inForeground&&e.inForeground,r=this.networkEnabled===e.networkEnabled;if(t||n&&r)return!0}return!1}))))})).next((e=>(this.isPrimary!==e&&g("IndexedDbPersistence",`Client ${e?"is":"is not"} eligible for a primary lease.`),e)))}async shutdown(){this.Ur=!1,this.ki(),this.di&&(this.di.cancel(),this.di=null),this.qi(),this.Qi(),await this.mi.runTransaction("shutdown","readwrite",["owner","clientMetadata"],(e=>{const t=new Je(e,ye.oe);return this.vi(t).next((()=>this.Mi(t)))})),this.mi.close(),this.Ki()}Ni(e,t){return e.filter((e=>this.Oi(e.updateTimeMs,t)&&!this.Bi(e.clientId)))}$i(){return this.runTransaction("getActiveClients","readonly",(e=>Mo(e).U().next((e=>this.Ni(e,18e5).map((e=>e.clientId))))))}get started(){return this.Ur}getGlobalsCache(){return this.Wr}getMutationQueue(e,t){return Us.Pt(e,this.serializer,t,this.referenceDelegate)}getTargetCache(){return this.Gr}getRemoteDocumentCache(){return this.remoteDocumentCache}getIndexManager(e){return new Ns(e,this.serializer.ht.databaseId)}getDocumentOverlayCache(e){return ss.Pt(this.serializer,e)}getBundleCache(){return this.jr}runTransaction(e,t,n){g("IndexedDbPersistence","Starting transaction:",e);const r="readonly"===t?"readonly":"readwrite",i=function(e){return 17===e?We:16===e?He:15===e?Qe:14===e?Ke:13===e?Ge:12===e?ze:11===e?$e:void v()}(this.Ti);let s;return this.mi.runTransaction(e,r,i,(r=>(s=new Je(r,this.$r?this.$r.next():ye.oe),"readwrite-primary"===t?this.bi(s).next((e=>!!e||this.Di(s))).next((t=>{if(!t)throw p(`Failed to obtain primary lease for action '${e}'.`),this.isPrimary=!1,this.li.enqueueRetryable((()=>this.Ri(!1))),new I(_.FAILED_PRECONDITION,te);return n(s)})).next((e=>this.Ci(s).next((()=>e)))):this.Ui(s).next((()=>n(s)))))).then((e=>(s.raiseOnCommittedEvent(),e)))}Ui(e){return Oo(e).get("owner").next((e=>{if(null!==e&&this.Oi(e.leaseTimestampMs,5e3)&&!this.Bi(e.ownerId)&&!this.Fi(e)&&!(this.Pi||this.allowTabSynchronization&&e.allowTabSynchronization))throw new I(_.FAILED_PRECONDITION,No)}))}Ci(e){const t={ownerId:this.clientId,allowTabSynchronization:this.allowTabSynchronization,leaseTimestampMs:Date.now()};return Oo(e).put("owner",t)}static p(){return oe.p()}vi(e){const t=Oo(e);return t.get("owner").next((e=>this.Fi(e)?(g("IndexedDbPersistence","Releasing primary lease."),t.delete("owner")):ie.resolve()))}Oi(e,t){const n=Date.now();return!(e<n-t||e>n&&(p(`Detected an update time that is in the future: ${e} > ${n}`),1))}pi(){null!==this.document&&"function"==typeof this.document.addEventListener&&(this.Ei=()=>{this.li.enqueueAndForget((()=>(this.inForeground="visible"===this.document.visibilityState,this.gi())))},this.document.addEventListener("visibilitychange",this.Ei),this.inForeground="visible"===this.document.visibilityState)}qi(){this.Ei&&(this.document.removeEventListener("visibilitychange",this.Ei),this.Ei=null)}yi(){var e;"function"==typeof(null===(e=this.window)||void 0===e?void 0:e.addEventListener)&&(this.Ii=()=>{this.ki();const e=/(?:Version|Mobile)\/1[456]/;o.isSafari()&&(navigator.appVersion.match(e)||navigator.userAgent.match(e))&&this.li.enterRestrictedMode(!0),this.li.enqueueAndForget((()=>this.shutdown()))},this.window.addEventListener("pagehide",this.Ii))}Qi(){this.Ii&&(this.window.removeEventListener("pagehide",this.Ii),this.Ii=null)}Bi(e){var t;try{const n=null!==(null===(t=this.fi)||void 0===t?void 0:t.getItem(this.Li(e)));return g("IndexedDbPersistence",`Client '${e}' ${n?"is":"is not"} zombied in LocalStorage`),n}catch(e){return p("IndexedDbPersistence","Failed to get zombied client id.",e),!1}}ki(){if(this.fi)try{this.fi.setItem(this.Li(this.clientId),String(Date.now()))}catch(e){p("Failed to set zombie client id.",e)}}Ki(){if(this.fi)try{this.fi.removeItem(this.Li(this.clientId))}catch(e){}}Li(e){return`firestore_zombie_${this.persistenceKey}_${e}`}}function Oo(e){return Xe(e,"owner")}function Mo(e){return Xe(e,"clientMetadata")}function Ro(e,t){let n=e.projectId;return e.isDefaultDatabase||(n+="."+e.database),"firestore/"+t+"/"+n+"/"}class Po{constructor(e,t,n,r){this.targetId=e,this.fromCache=t,this.Wi=n,this.Gi=r}static zi(e,t){let n=nr(),r=nr();for(const e of t.docChanges)switch(e.type){case 0:n=n.add(e.doc.key);break;case 1:r=r.add(e.doc.key)}return new Po(e,t.fromCache,n,r)}}class Fo{constructor(){this._documentReadCount=0}get documentReadCount(){return this._documentReadCount}incrementDocumentReadCount(e){this._documentReadCount+=e}}class Vo{constructor(){this.ji=!1,this.Hi=!1,this.Ji=100,this.Yi=o.isSafari()?8:ae(o.getUA())>0?6:4}initialize(e,t){this.Zi=e,this.indexManager=t,this.ji=!0}getDocumentsMatchingQuery(e,t,n,r){const i={result:null};return this.Xi(e,t).next((e=>{i.result=e})).next((()=>{if(!i.result)return this.es(e,t,r,n).next((e=>{i.result=e}))})).next((()=>{if(i.result)return;const n=new Fo;return this.ts(e,t,n).next((r=>{if(i.result=r,this.Hi)return this.ns(e,t,n,r.size)}))})).next((()=>i.result))}ns(e,t,n,r){return n.documentReadCount<this.Ji?(f()<=s.LogLevel.DEBUG&&g("QueryEngine","SDK will not create cache indexes for query:",Bn(t),"since it only creates cache indexes for collection contains","more than or equal to",this.Ji,"documents"),ie.resolve()):(f()<=s.LogLevel.DEBUG&&g("QueryEngine","Query:",Bn(t),"scans",n.documentReadCount,"local documents and returns",r,"documents as results."),n.documentReadCount>this.Yi*r?(f()<=s.LogLevel.DEBUG&&g("QueryEngine","The SDK decides to create cache indexes for query:",Bn(t),"as using cache indexes may help improve performance."),this.indexManager.createTargetIndexes(e,On(t))):ie.resolve())}Xi(e,t){if(kn(t))return ie.resolve(null);let n=On(t);return this.indexManager.getIndexType(e,n).next((r=>0===r?null:(null!==t.limit&&1===r&&(t=Fn(t,null,"F"),n=On(t)),this.indexManager.getDocumentsMatchingTarget(e,n).next((r=>{const i=nr(...r);return this.Zi.getDocuments(e,i).next((r=>this.indexManager.getMinOffset(e,n).next((n=>{const s=this.rs(t,r);return this.ss(t,s,i,n.readTime)?this.Xi(e,Fn(t,null,"F")):this.os(e,s,t,n)}))))})))))}es(e,t,n,r){return kn(t)||r.isEqual(V.min())?ie.resolve(null):this.Zi.getDocuments(e,n).next((i=>{const o=this.rs(t,i);return this.ss(t,o,n,r)?ie.resolve(null):(f()<=s.LogLevel.DEBUG&&g("QueryEngine","Re-using previous result from %s to execute query: %s",r.toString(),Bn(t)),this.os(e,o,t,X(r,-1)).next((e=>e)))}))}rs(e,t){let n=new st($n(e));return t.forEach(((t,r)=>{Un(e,r)&&(n=n.add(r))})),n}ss(e,t,n,r){if(null===e.limit)return!1;if(n.size!==t.size)return!0;const i="F"===e.limitType?t.last():t.first();return!!i&&(i.hasPendingWrites||i.version.compareTo(r)>0)}ts(e,t,n){return f()<=s.LogLevel.DEBUG&&g("QueryEngine","Using full collection scan to execute query:",Bn(t)),this.Zi.getDocumentsMatchingQuery(e,t,Z.min(),n)}os(e,t,n,r){return this.Zi.getDocumentsMatchingQuery(e,n,r).next((e=>(t.forEach((t=>{e=e.insert(t.key,t)})),e)))}}class qo{constructor(e,t,n,r){this.persistence=e,this._s=t,this.serializer=r,this.us=new nt(M),this.cs=new Gn((e=>_n(e)),In),this.ls=new Map,this.hs=e.getRemoteDocumentCache(),this.Gr=e.getTargetCache(),this.jr=e.getBundleCache(),this.Ps(n)}Ps(e){this.documentOverlayCache=this.persistence.getDocumentOverlayCache(e),this.indexManager=this.persistence.getIndexManager(e),this.mutationQueue=this.persistence.getMutationQueue(e,this.indexManager),this.localDocuments=new po(this.hs,this.mutationQueue,this.documentOverlayCache,this.indexManager),this.hs.setIndexManager(this.indexManager),this._s.initialize(this.localDocuments,this.indexManager)}collectGarbage(e){return this.persistence.runTransaction("Collect garbage","readwrite-primary",(t=>e.collect(t,this.us)))}}function Bo(e,t,n,r){return new qo(e,t,n,r)}async function Uo(e,t){const n=b(e);return await n.persistence.runTransaction("Handle user change","readonly",(e=>{let r;return n.mutationQueue.getAllMutationBatches(e).next((i=>(r=i,n.Ps(t),n.mutationQueue.getAllMutationBatches(e)))).next((t=>{const i=[],s=[];let o=nr();for(const e of r){i.push(e.batchId);for(const t of e.mutations)o=o.add(t.key)}for(const e of t){s.push(e.batchId);for(const t of e.mutations)o=o.add(t.key)}return n.localDocuments.getDocuments(e,o).next((e=>({Ts:e,removedBatchIds:i,addedBatchIds:s})))}))}))}function jo(e){const t=b(e);return t.persistence.runTransaction("Get last remote snapshot version","readonly",(e=>t.Gr.getLastRemoteSnapshotVersion(e)))}function $o(e,t,n){let r=nr(),i=nr();return n.forEach((e=>r=r.add(e))),t.getEntries(e,r).next((e=>{let r=Qn();return n.forEach(((n,s)=>{const o=e.get(n);s.isFoundDocument()!==o.isFoundDocument()&&(i=i.add(n)),s.isNoDocument()&&s.version.isEqual(V.min())?(t.removeEntry(n,s.readTime),r=r.insert(n,s)):!o.isValidDocument()||s.version.compareTo(o.version)>0||0===s.version.compareTo(o.version)&&o.hasPendingWrites?(t.addEntry(s),r=r.insert(n,s)):g("LocalStore","Ignoring outdated watch update for ",n,". Current version:",o.version," Watch version:",s.version)})),{Is:r,Es:i}}))}function zo(e,t){const n=b(e);return n.persistence.runTransaction("Get next mutation batch","readonly",(e=>(void 0===t&&(t=-1),n.mutationQueue.getNextMutationBatchAfterBatchId(e,t))))}function Go(e,t){const n=b(e);return n.persistence.runTransaction("Allocate target","readwrite",(e=>{let r;return n.Gr.getTargetData(e,t).next((i=>i?(r=i,ie.resolve(r)):n.Gr.allocateTargetId(e).next((i=>(r=new $i(t,i,"TargetPurposeListen",e.currentSequenceNumber),n.Gr.addTargetData(e,r).next((()=>r)))))))})).then((e=>{const r=n.us.get(e.targetId);return(null===r||e.snapshotVersion.compareTo(r.snapshotVersion)>0)&&(n.us=n.us.insert(e.targetId,e),n.cs.set(t,e.targetId)),e}))}async function Ko(e,t,n){const r=b(e),i=r.us.get(t),s=n?"readwrite":"readwrite-primary";try{n||await r.persistence.runTransaction("Release target",s,(e=>r.persistence.referenceDelegate.removeTarget(e,i)))}catch(e){if(!le(e))throw e;g("LocalStore",`Failed to update sequence numbers for target ${t}: ${e}`)}r.us=r.us.remove(t),r.cs.delete(i.target)}function Qo(e,t,n){const r=b(e);let i=V.min(),s=nr();return r.persistence.runTransaction("Execute query","readwrite",(e=>function(e,t,n){const r=b(e),i=r.cs.get(n);return void 0!==i?ie.resolve(r.us.get(i)):r.Gr.getTargetData(t,n)}(r,e,On(t)).next((t=>{if(t)return i=t.lastLimboFreeSnapshotVersion,r.Gr.getMatchingKeysForTargetId(e,t.targetId).next((e=>{s=e}))})).next((()=>r._s.getDocumentsMatchingQuery(e,t,n?i:V.min(),n?s:nr()))).next((e=>(Jo(r,jn(t),e),{documents:e,ds:s})))))}function Ho(e,t){const n=b(e),r=b(n.Gr),i=n.us.get(t);return i?Promise.resolve(i.target):n.persistence.runTransaction("Get target data","readonly",(e=>r.ut(e,t).next((e=>e?e.target:null))))}function Wo(e,t){const n=b(e),r=n.ls.get(t)||V.min();return n.persistence.runTransaction("Get new document changes","readonly",(e=>n.hs.getAllFromCollectionGroup(e,t,X(r,-1),Number.MAX_SAFE_INTEGER))).then((e=>(Jo(n,t,e),e)))}function Jo(e,t,n){let r=e.ls.get(t)||V.min();n.forEach(((e,t)=>{t.readTime.compareTo(r)>0&&(r=t.readTime)})),e.ls.set(t,r)}async function Xo(e,t,n=nr()){const r=await Go(e,On(Yi(t.bundledQuery))),i=b(e);return i.persistence.runTransaction("Save named query","readwrite",(e=>{const s=mi(t.readTime);if(r.snapshotVersion.compareTo(s)>=0)return i.jr.saveNamedQuery(e,t);const o=r.withResumeToken(lt.EMPTY_BYTE_STRING,s);return i.us=i.us.insert(o.targetId,o),i.Gr.updateTargetData(e,o).next((()=>i.Gr.removeMatchingKeysForTargetId(e,r.targetId))).next((()=>i.Gr.addMatchingKeys(e,n,r.targetId))).next((()=>i.jr.saveNamedQuery(e,t)))}))}function Yo(e,t){return`firestore_clients_${e}_${t}`}function Zo(e,t,n){let r=`firestore_mutations_${e}_${n}`;return t.isAuthenticated()&&(r+=`_${t.uid}`),r}function ea(e,t){return`firestore_targets_${e}_${t}`}class ta{constructor(e,t,n,r){this.user=e,this.batchId=t,this.state=n,this.error=r}static fs(e,t,n){const r=JSON.parse(n);let i,s="object"==typeof r&&-1!==["pending","acknowledged","rejected"].indexOf(r.state)&&(void 0===r.error||"object"==typeof r.error);return s&&r.error&&(s="string"==typeof r.error.message&&"string"==typeof r.error.code,s&&(i=new I(r.error.code,r.error.message))),s?new ta(e,t,r.state,i):(p("SharedClientState",`Failed to parse mutation state for ID '${t}': ${n}`),null)}gs(){const e={state:this.state,updateTimeMs:Date.now()};return this.error&&(e.error={code:this.error.code,message:this.error.message}),JSON.stringify(e)}}class na{constructor(e,t,n){this.targetId=e,this.state=t,this.error=n}static fs(e,t){const n=JSON.parse(t);let r,i="object"==typeof n&&-1!==["not-current","current","rejected"].indexOf(n.state)&&(void 0===n.error||"object"==typeof n.error);return i&&n.error&&(i="string"==typeof n.error.message&&"string"==typeof n.error.code,i&&(r=new I(n.error.code,n.error.message))),i?new na(e,n.state,r):(p("SharedClientState",`Failed to parse target state for ID '${e}': ${t}`),null)}gs(){const e={state:this.state,updateTimeMs:Date.now()};return this.error&&(e.error={code:this.error.code,message:this.error.message}),JSON.stringify(e)}}class ra{constructor(e,t){this.clientId=e,this.activeTargetIds=t}static fs(e,t){const n=JSON.parse(t);let r="object"==typeof n&&n.activeTargetIds instanceof Array,i=ir();for(let e=0;r&&e<n.activeTargetIds.length;++e)r=be(n.activeTargetIds[e]),i=i.add(n.activeTargetIds[e]);return r?new ra(e,i):(p("SharedClientState",`Failed to parse client data for instance '${e}': ${t}`),null)}}class ia{constructor(e,t){this.clientId=e,this.onlineState=t}static fs(e){const t=JSON.parse(e);return"object"==typeof t&&-1!==["Unknown","Online","Offline"].indexOf(t.onlineState)&&"string"==typeof t.clientId?new ia(t.clientId,t.onlineState):(p("SharedClientState",`Failed to parse online state: ${e}`),null)}}class sa{constructor(){this.activeTargetIds=ir()}ps(e){this.activeTargetIds=this.activeTargetIds.add(e)}ys(e){this.activeTargetIds=this.activeTargetIds.delete(e)}gs(){const e={activeTargetIds:this.activeTargetIds.toArray(),updateTimeMs:Date.now()};return JSON.stringify(e)}}class oa{constructor(e,t,n,r,i){this.window=e,this.li=t,this.persistenceKey=n,this.ws=r,this.syncEngine=null,this.onlineStateHandler=null,this.sequenceNumberHandler=null,this.Ss=this.bs.bind(this),this.Ds=new nt(M),this.started=!1,this.vs=[];const s=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");this.storage=this.window.localStorage,this.currentUser=i,this.Cs=Yo(this.persistenceKey,this.ws),this.Fs=function(e){return`firestore_sequence_number_${e}`}(this.persistenceKey),this.Ds=this.Ds.insert(this.ws,new sa),this.Ms=new RegExp(`^firestore_clients_${s}_([^_]*)$`),this.xs=new RegExp(`^firestore_mutations_${s}_(\\d+)(?:_(.*))?$`),this.Os=new RegExp(`^firestore_targets_${s}_(\\d+)$`),this.Ns=function(e){return`firestore_online_state_${e}`}(this.persistenceKey),this.Ls=function(e){return`firestore_bundle_loaded_v2_${e}`}(this.persistenceKey),this.window.addEventListener("storage",this.Ss)}static p(e){return!(!e||!e.localStorage)}async start(){const e=await this.syncEngine.$i();for(const t of e){if(t===this.ws)continue;const e=this.getItem(Yo(this.persistenceKey,t));if(e){const n=ra.fs(t,e);n&&(this.Ds=this.Ds.insert(n.clientId,n))}}this.Bs();const t=this.storage.getItem(this.Ns);if(t){const e=this.ks(t);e&&this.qs(e)}for(const e of this.vs)this.bs(e);this.vs=[],this.window.addEventListener("pagehide",(()=>this.shutdown())),this.started=!0}writeSequenceNumber(e){this.setItem(this.Fs,JSON.stringify(e))}getAllActiveQueryTargets(){return this.Qs(this.Ds)}isActiveQueryTarget(e){let t=!1;return this.Ds.forEach(((n,r)=>{r.activeTargetIds.has(e)&&(t=!0)})),t}addPendingMutation(e){this.Ks(e,"pending")}updateMutationState(e,t,n){this.Ks(e,t,n),this.$s(e)}addLocalQueryTarget(e,t=!0){let n="not-current";if(this.isActiveQueryTarget(e)){const t=this.storage.getItem(ea(this.persistenceKey,e));if(t){const r=na.fs(e,t);r&&(n=r.state)}}return t&&this.Us.ps(e),this.Bs(),n}removeLocalQueryTarget(e){this.Us.ys(e),this.Bs()}isLocalQueryTarget(e){return this.Us.activeTargetIds.has(e)}clearQueryState(e){this.removeItem(ea(this.persistenceKey,e))}updateQueryState(e,t,n){this.Ws(e,t,n)}handleUserChange(e,t,n){t.forEach((e=>{this.$s(e)})),this.currentUser=e,n.forEach((e=>{this.addPendingMutation(e)}))}setOnlineState(e){this.Gs(e)}notifyBundleLoaded(e){this.zs(e)}shutdown(){this.started&&(this.window.removeEventListener("storage",this.Ss),this.removeItem(this.Cs),this.started=!1)}getItem(e){const t=this.storage.getItem(e);return g("SharedClientState","READ",e,t),t}setItem(e,t){g("SharedClientState","SET",e,t),this.storage.setItem(e,t)}removeItem(e){g("SharedClientState","REMOVE",e),this.storage.removeItem(e)}bs(e){const t=e;if(t.storageArea===this.storage){if(g("SharedClientState","EVENT",t.key,t.newValue),t.key===this.Cs)return void p("Received WebStorage notification for local change. Another client might have garbage-collected our state");this.li.enqueueRetryable((async()=>{if(this.started){if(null!==t.key)if(this.Ms.test(t.key)){if(null==t.newValue){const e=this.js(t.key);return this.Hs(e,null)}{const e=this.Js(t.key,t.newValue);if(e)return this.Hs(e.clientId,e)}}else if(this.xs.test(t.key)){if(null!==t.newValue){const e=this.Ys(t.key,t.newValue);if(e)return this.Zs(e)}}else if(this.Os.test(t.key)){if(null!==t.newValue){const e=this.Xs(t.key,t.newValue);if(e)return this.eo(e)}}else if(t.key===this.Ns){if(null!==t.newValue){const e=this.ks(t.newValue);if(e)return this.qs(e)}}else if(t.key===this.Fs){const e=function(e){let t=ye.oe;if(null!=e)try{const n=JSON.parse(e);w("number"==typeof n),t=n}catch(e){p("SharedClientState","Failed to read sequence number from WebStorage",e)}return t}(t.newValue);e!==ye.oe&&this.sequenceNumberHandler(e)}else if(t.key===this.Ls){const e=this.no(t.newValue);await Promise.all(e.map((e=>this.syncEngine.ro(e))))}}else this.vs.push(t)}))}}get Us(){return this.Ds.get(this.ws)}Bs(){this.setItem(this.Cs,this.Us.gs())}Ks(e,t,n){const r=new ta(this.currentUser,e,t,n),i=Zo(this.persistenceKey,this.currentUser,e);this.setItem(i,r.gs())}$s(e){const t=Zo(this.persistenceKey,this.currentUser,e);this.removeItem(t)}Gs(e){const t={clientId:this.ws,onlineState:e};this.storage.setItem(this.Ns,JSON.stringify(t))}Ws(e,t,n){const r=ea(this.persistenceKey,e),i=new na(e,t,n);this.setItem(r,i.gs())}zs(e){const t=JSON.stringify(Array.from(e));this.setItem(this.Ls,t)}js(e){const t=this.Ms.exec(e);return t?t[1]:null}Js(e,t){const n=this.js(e);return ra.fs(n,t)}Ys(e,t){const n=this.xs.exec(e),r=Number(n[1]),i=void 0!==n[2]?n[2]:null;return ta.fs(new l(i),r,t)}Xs(e,t){const n=this.Os.exec(e),r=Number(n[1]);return na.fs(r,t)}ks(e){return ia.fs(e)}no(e){return JSON.parse(e)}async Zs(e){if(e.user.uid===this.currentUser.uid)return this.syncEngine.io(e.batchId,e.state,e.error);g("SharedClientState",`Ignoring mutation for non-active user ${e.user.uid}`)}eo(e){return this.syncEngine.so(e.targetId,e.state,e.error)}Hs(e,t){const n=t?this.Ds.insert(e,t):this.Ds.remove(e),r=this.Qs(this.Ds),i=this.Qs(n),s=[],o=[];return i.forEach((e=>{r.has(e)||s.push(e)})),r.forEach((e=>{i.has(e)||o.push(e)})),this.syncEngine.oo(s,o).then((()=>{this.Ds=n}))}qs(e){this.Ds.get(e.clientId)&&this.onlineStateHandler(e.onlineState)}Qs(e){let t=ir();return e.forEach(((e,n)=>{t=t.unionWith(n.activeTargetIds)})),t}}class aa{constructor(){this._o=new sa,this.ao={},this.onlineStateHandler=null,this.sequenceNumberHandler=null}addPendingMutation(e){}updateMutationState(e,t,n){}addLocalQueryTarget(e,t=!0){return t&&this._o.ps(e),this.ao[e]||"not-current"}updateQueryState(e,t,n){this.ao[e]=t}removeLocalQueryTarget(e){this._o.ys(e)}isLocalQueryTarget(e){return this._o.activeTargetIds.has(e)}clearQueryState(e){delete this.ao[e]}getAllActiveQueryTargets(){return this._o.activeTargetIds}isActiveQueryTarget(e){return this._o.activeTargetIds.has(e)}start(){return this._o=new sa,Promise.resolve()}handleUserChange(e,t,n){}setOnlineState(e){}shutdown(){}writeSequenceNumber(e){}notifyBundleLoaded(e){}}class ca{uo(e){}shutdown(){}}class ua{constructor(){this.co=()=>this.lo(),this.ho=()=>this.Po(),this.To=[],this.Io()}uo(e){this.To.push(e)}shutdown(){window.removeEventListener("online",this.co),window.removeEventListener("offline",this.ho)}Io(){window.addEventListener("online",this.co),window.addEventListener("offline",this.ho)}lo(){g("ConnectivityMonitor","Network connectivity changed: AVAILABLE");for(const e of this.To)e(0)}Po(){g("ConnectivityMonitor","Network connectivity changed: UNAVAILABLE");for(const e of this.To)e(1)}static p(){return"undefined"!=typeof window&&void 0!==window.addEventListener&&void 0!==window.removeEventListener}}let la=null;function ha(){return null===la?la=268435456+Math.round(2147483648*Math.random()):la++,"0x"+la.toString(16)}const da={BatchGetDocuments:"batchGet",Commit:"commit",RunQuery:"runQuery",RunAggregationQuery:"runAggregationQuery"};class fa{constructor(e){this.Eo=e.Eo,this.Ao=e.Ao}Ro(e){this.Vo=e}mo(e){this.fo=e}po(e){this.yo=e}onMessage(e){this.wo=e}close(){this.Ao()}send(e){this.Eo(e)}So(){this.Vo()}bo(){this.fo()}Do(e){this.yo(e)}vo(e){this.wo(e)}}const ga="WebChannelConnection";class pa extends class{get Co(){return!1}constructor(e){this.databaseInfo=e,this.databaseId=e.databaseId;const t=e.ssl?"https":"http",n=encodeURIComponent(this.databaseId.projectId),r=encodeURIComponent(this.databaseId.database);this.Fo=t+"://"+e.host,this.Mo=`projects/${n}/databases/${r}`,this.xo="(default)"===this.databaseId.database?`project_id=${n}`:`project_id=${n}&database_id=${r}`}Oo(e,t,n,r,i){const s=ha(),o=this.No(e,t.toUriEncodedString());g("RestConnection",`Sending RPC '${e}' ${s}:`,o,n);const a={"google-cloud-resource-prefix":this.Mo,"x-goog-request-params":this.xo};return this.Lo(a,r,i),this.Bo(e,o,a,n).then((t=>(g("RestConnection",`Received RPC '${e}' ${s}: `,t),t)),(t=>{throw m("RestConnection",`RPC '${e}' ${s} failed with error: `,t,"url: ",o,"request:",n),t}))}ko(e,t,n,r,i,s){return this.Oo(e,t,n,r,i)}Lo(e,t,n){e["X-Goog-Api-Client"]="gl-js/ fire/"+h,e["Content-Type"]="text/plain",this.databaseInfo.appId&&(e["X-Firebase-GMPID"]=this.databaseInfo.appId),t&&t.headers.forEach(((t,n)=>e[n]=t)),n&&n.headers.forEach(((t,n)=>e[n]=t))}No(e,t){const n=da[e];return`${this.Fo}/v1/${t}:${n}`}terminate(){}}{constructor(e){super(e),this.forceLongPolling=e.forceLongPolling,this.autoDetectLongPolling=e.autoDetectLongPolling,this.useFetchStreams=e.useFetchStreams,this.longPollingOptions=e.longPollingOptions}Bo(e,t,n,r){const i=ha();return new Promise(((s,o)=>{const a=new c.XhrIo;a.setWithCredentials(!0),a.listenOnce(c.EventType.COMPLETE,(()=>{try{switch(a.getLastErrorCode()){case c.ErrorCode.NO_ERROR:const t=a.getResponseJson();g(ga,`XHR for RPC '${e}' ${i} received:`,JSON.stringify(t)),s(t);break;case c.ErrorCode.TIMEOUT:g(ga,`RPC '${e}' ${i} timed out`),o(new I(_.DEADLINE_EXCEEDED,"Request time out"));break;case c.ErrorCode.HTTP_ERROR:const n=a.getStatus();if(g(ga,`RPC '${e}' ${i} failed with status:`,n,"response text:",a.getResponseText()),n>0){let e=a.getResponseJson();Array.isArray(e)&&(e=e[0]);const t=null==e?void 0:e.error;if(t&&t.status&&t.message){const e=function(e){const t=e.toLowerCase().replace(/_/g,"-");return Object.values(_).indexOf(t)>=0?t:_.UNKNOWN}(t.status);o(new I(e,t.message))}else o(new I(_.UNKNOWN,"Server responded with status "+a.getStatus()))}else o(new I(_.UNAVAILABLE,"Connection failed."));break;default:v()}}finally{g(ga,`RPC '${e}' ${i} completed.`)}}));const u=JSON.stringify(r);g(ga,`RPC '${e}' ${i} sending request:`,r),a.send(t,"POST",u,n,15)}))}qo(e,t,n){const r=ha(),i=[this.Fo,"/","google.firestore.v1.Firestore","/",e,"/channel"],s=c.createWebChannelTransport(),o=c.getStatEventTarget(),a={httpSessionIdParam:"gsessionid",initMessageHeaders:{},messageUrlParams:{database:`projects/${this.databaseId.projectId}/databases/${this.databaseId.database}`},sendRawJson:!0,supportsCrossDomainXhr:!0,internalChannelParams:{forwardChannelRequestTimeoutMs:6e5},forceLongPolling:this.forceLongPolling,detectBufferingProxy:this.autoDetectLongPolling},u=this.longPollingOptions.timeoutSeconds;void 0!==u&&(a.longPollingTimeout=Math.round(1e3*u)),this.useFetchStreams&&(a.useFetchStreams=!0),this.Lo(a.initMessageHeaders,t,n),a.encodeInitMessageHeaders=!0;const l=i.join("");g(ga,`Creating RPC '${e}' stream ${r}: ${l}`,a);const h=s.createWebChannel(l,a);let d=!1,f=!1;const p=new fa({Eo:t=>{f?g(ga,`Not sending because RPC '${e}' stream ${r} is closed:`,t):(d||(g(ga,`Opening RPC '${e}' stream ${r} transport.`),h.open(),d=!0),g(ga,`RPC '${e}' stream ${r} sending:`,t),h.send(t))},Ao:()=>h.close()}),y=(e,t,n)=>{e.listen(t,(e=>{try{n(e)}catch(e){setTimeout((()=>{throw e}),0)}}))};return y(h,c.WebChannel.EventType.OPEN,(()=>{f||(g(ga,`RPC '${e}' stream ${r} transport opened.`),p.So())})),y(h,c.WebChannel.EventType.CLOSE,(()=>{f||(f=!0,g(ga,`RPC '${e}' stream ${r} transport closed`),p.Do())})),y(h,c.WebChannel.EventType.ERROR,(t=>{f||(f=!0,m(ga,`RPC '${e}' stream ${r} transport errored:`,t),p.Do(new I(_.UNAVAILABLE,"The operation could not be completed")))})),y(h,c.WebChannel.EventType.MESSAGE,(t=>{var n;if(!f){const i=t.data[0];w(!!i);const s=i,o=(null==s?void 0:s.error)||(null===(n=s[0])||void 0===n?void 0:n.error);if(o){g(ga,`RPC '${e}' stream ${r} received error:`,o);const t=o.status;let n=function(e){const t=jr[e];if(void 0!==t)return Gr(t)}(t),i=o.message;void 0===n&&(n=_.INTERNAL,i="Unknown error status: "+t+" with message "+o.message),f=!0,p.Do(new I(n,i)),h.close()}else g(ga,`RPC '${e}' stream ${r} received:`,i),p.vo(i)}})),y(o,c.Event.STAT_EVENT,(t=>{t.stat===c.Stat.PROXY?g(ga,`RPC '${e}' stream ${r} detected buffering proxy`):t.stat===c.Stat.NOPROXY&&g(ga,`RPC '${e}' stream ${r} detected no buffering proxy`)})),setTimeout((()=>{p.bo()}),0),p}}function ma(){return"undefined"!=typeof window?window:null}function ya(){return"undefined"!=typeof document?document:null}function va(e){return new hi(e,!0)}class wa{constructor(e,t,n=1e3,r=1.5,i=6e4){this.li=e,this.timerId=t,this.Qo=n,this.Ko=r,this.$o=i,this.Uo=0,this.Wo=null,this.Go=Date.now(),this.reset()}reset(){this.Uo=0}zo(){this.Uo=this.$o}jo(e){this.cancel();const t=Math.floor(this.Uo+this.Ho()),n=Math.max(0,Date.now()-this.Go),r=Math.max(0,t-n);r>0&&g("ExponentialBackoff",`Backing off for ${r} ms (base delay: ${this.Uo} ms, delay with jitter: ${t} ms, last attempt: ${n} ms ago)`),this.Wo=this.li.enqueueAfterDelay(this.timerId,r,(()=>(this.Go=Date.now(),e()))),this.Uo*=this.Ko,this.Uo<this.Qo&&(this.Uo=this.Qo),this.Uo>this.$o&&(this.Uo=this.$o)}Jo(){null!==this.Wo&&(this.Wo.skipDelay(),this.Wo=null)}cancel(){null!==this.Wo&&(this.Wo.cancel(),this.Wo=null)}Ho(){return(Math.random()-.5)*this.Uo}}class ba{constructor(e,t,n,r,i,s,o,a){this.li=e,this.Yo=n,this.Zo=r,this.connection=i,this.authCredentialsProvider=s,this.appCheckCredentialsProvider=o,this.listener=a,this.state=0,this.Xo=0,this.e_=null,this.t_=null,this.stream=null,this.n_=0,this.r_=new wa(e,t)}i_(){return 1===this.state||5===this.state||this.s_()}s_(){return 2===this.state||3===this.state}start(){this.n_=0,4!==this.state?this.auth():this.o_()}async stop(){this.i_()&&await this.close(0)}__(){this.state=0,this.r_.reset()}a_(){this.s_()&&null===this.e_&&(this.e_=this.li.enqueueAfterDelay(this.Yo,6e4,(()=>this.u_())))}c_(e){this.l_(),this.stream.send(e)}async u_(){if(this.s_())return this.close(0)}l_(){this.e_&&(this.e_.cancel(),this.e_=null)}h_(){this.t_&&(this.t_.cancel(),this.t_=null)}async close(e,t){this.l_(),this.h_(),this.r_.cancel(),this.Xo++,4!==e?this.r_.reset():t&&t.code===_.RESOURCE_EXHAUSTED?(p(t.toString()),p("Using maximum backoff delay to prevent overloading the backend."),this.r_.zo()):t&&t.code===_.UNAUTHENTICATED&&3!==this.state&&(this.authCredentialsProvider.invalidateToken(),this.appCheckCredentialsProvider.invalidateToken()),null!==this.stream&&(this.P_(),this.stream.close(),this.stream=null),this.state=e,await this.listener.po(t)}P_(){}auth(){this.state=1;const e=this.T_(this.Xo),t=this.Xo;Promise.all([this.authCredentialsProvider.getToken(),this.appCheckCredentialsProvider.getToken()]).then((([e,n])=>{this.Xo===t&&this.I_(e,n)}),(t=>{e((()=>{const e=new I(_.UNKNOWN,"Fetching auth token failed: "+t.message);return this.E_(e)}))}))}I_(e,t){const n=this.T_(this.Xo);this.stream=this.d_(e,t),this.stream.Ro((()=>{n((()=>this.listener.Ro()))})),this.stream.mo((()=>{n((()=>(this.state=2,this.t_=this.li.enqueueAfterDelay(this.Zo,1e4,(()=>(this.s_()&&(this.state=3),Promise.resolve()))),this.listener.mo())))})),this.stream.po((e=>{n((()=>this.E_(e)))})),this.stream.onMessage((e=>{n((()=>1==++this.n_?this.A_(e):this.onNext(e)))}))}o_(){this.state=5,this.r_.jo((async()=>{this.state=0,this.start()}))}E_(e){return g("PersistentStream",`close with error: ${e}`),this.stream=null,this.close(4,e)}T_(e){return t=>{this.li.enqueueAndForget((()=>this.Xo===e?t():(g("PersistentStream","stream callback skipped by getCloseGuardedDispatcher."),Promise.resolve())))}}}class _a extends ba{constructor(e,t,n,r,i,s){super(e,"listen_stream_connection_backoff","listen_stream_idle","health_check_timeout",t,n,r,s),this.serializer=i}d_(e,t){return this.connection.qo("Listen",e,t)}A_(e){return this.onNext(e)}onNext(e){this.r_.reset();const t=function(e,t){let n;if("targetChange"in t){t.targetChange;const r=function(e){return"NO_CHANGE"===e?0:"ADD"===e?1:"REMOVE"===e?2:"CURRENT"===e?3:"RESET"===e?4:v()}(t.targetChange.targetChangeType||"NO_CHANGE"),i=t.targetChange.targetIds||[],s=function(e,t){return e.useProto3Json?(w(void 0===t||"string"==typeof t),lt.fromBase64String(t||"")):(w(void 0===t||t instanceof Buffer||t instanceof Uint8Array),lt.fromUint8Array(t||new Uint8Array))}(e,t.targetChange.resumeToken),o=t.targetChange.cause,a=o&&function(e){const t=void 0===e.code?_.UNKNOWN:Gr(e.code);return new I(t,e.message||"")}(o);n=new ri(r,i,s,a||null)}else if("documentChange"in t){t.documentChange;const r=t.documentChange;r.document,r.document.name,r.document.updateTime;const i=_i(e,r.document.name),s=mi(r.document.updateTime),o=r.document.createTime?mi(r.document.createTime):V.min(),a=new Gt({mapValue:{fields:r.document.fields}}),c=Qt.newFoundDocument(i,s,o,a),u=r.targetIds||[],l=r.removedTargetIds||[];n=new ti(u,l,c.key,c)}else if("documentDelete"in t){t.documentDelete;const r=t.documentDelete;r.document;const i=_i(e,r.document),s=r.readTime?mi(r.readTime):V.min(),o=Qt.newNoDocument(i,s),a=r.removedTargetIds||[];n=new ti([],a,o.key,o)}else if("documentRemove"in t){t.documentRemove;const r=t.documentRemove;r.document;const i=_i(e,r.document),s=r.removedTargetIds||[];n=new ti([],s,i,null)}else{if(!("filter"in t))return v();{t.filter;const e=t.filter;e.targetId;const{count:r=0,unchangedNames:i}=e,s=new Ur(r,i),o=e.targetId;n=new ni(o,s)}}return n}(this.serializer,e),n=function(e){if(!("targetChange"in e))return V.min();const t=e.targetChange;return t.targetIds&&t.targetIds.length?V.min():t.readTime?mi(t.readTime):V.min()}(e);return this.listener.R_(t,n)}V_(e){const t={};t.database=Ti(this.serializer),t.addTarget=function(e,t){let n;const r=t.target;if(n=En(r)?{documents:ki(e,r)}:{query:Ni(e,r).ct},n.targetId=t.targetId,t.resumeToken.approximateByteSize()>0){n.resumeToken=gi(e,t.resumeToken);const r=di(e,t.expectedCount);null!==r&&(n.expectedCount=r)}else if(t.snapshotVersion.compareTo(V.min())>0){n.readTime=fi(e,t.snapshotVersion.toTimestamp());const r=di(e,t.expectedCount);null!==r&&(n.expectedCount=r)}return n}(this.serializer,e);const n=function(e,t){const n=function(e){switch(e){case"TargetPurposeListen":return null;case"TargetPurposeExistenceFilterMismatch":return"existence-filter-mismatch";case"TargetPurposeExistenceFilterMismatchBloom":return"existence-filter-mismatch-bloom";case"TargetPurposeLimboResolution":return"limbo-document";default:return v()}}(t.purpose);return null==n?null:{"goog-listen-tags":n}}(this.serializer,e);n&&(t.labels=n),this.c_(t)}m_(e){const t={};t.database=Ti(this.serializer),t.removeTarget=e,this.c_(t)}}class Ia extends ba{constructor(e,t,n,r,i,s){super(e,"write_stream_connection_backoff","write_stream_idle","health_check_timeout",t,n,r,s),this.serializer=i}get f_(){return this.n_>0}start(){this.lastStreamToken=void 0,super.start()}P_(){this.f_&&this.g_([])}d_(e,t){return this.connection.qo("Write",e,t)}A_(e){return w(!!e.streamToken),this.lastStreamToken=e.streamToken,w(!e.writeResults||0===e.writeResults.length),this.listener.p_()}onNext(e){w(!!e.streamToken),this.lastStreamToken=e.streamToken,this.r_.reset();const t=function(e,t){return e&&e.length>0?(w(void 0!==t),e.map((e=>function(e,t){let n=e.updateTime?mi(e.updateTime):mi(t);return n.isEqual(V.min())&&(n=mi(t)),new _r(n,e.transformResults||[])}(e,t)))):[]}(e.writeResults,e.commitTime),n=mi(e.commitTime);return this.listener.y_(n,t)}w_(){const e={};e.database=Ti(this.serializer),this.c_(e)}g_(e){const t={streamToken:this.lastStreamToken,writes:e.map((e=>Di(this.serializer,e)))};this.c_(t)}}class Ea extends class{}{constructor(e,t,n,r){super(),this.authCredentials=e,this.appCheckCredentials=t,this.connection=n,this.serializer=r,this.S_=!1}b_(){if(this.S_)throw new I(_.FAILED_PRECONDITION,"The client has already been terminated.")}Oo(e,t,n,r){return this.b_(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then((([i,s])=>this.connection.Oo(e,vi(t,n),r,i,s))).catch((e=>{throw"FirebaseError"===e.name?(e.code===_.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),e):new I(_.UNKNOWN,e.toString())}))}ko(e,t,n,r,i){return this.b_(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then((([s,o])=>this.connection.ko(e,vi(t,n),r,s,o,i))).catch((e=>{throw"FirebaseError"===e.name?(e.code===_.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),e):new I(_.UNKNOWN,e.toString())}))}terminate(){this.S_=!0,this.connection.terminate()}}class Ta{constructor(e,t){this.asyncQueue=e,this.onlineStateHandler=t,this.state="Unknown",this.D_=0,this.v_=null,this.C_=!0}F_(){0===this.D_&&(this.M_("Unknown"),this.v_=this.asyncQueue.enqueueAfterDelay("online_state_timeout",1e4,(()=>(this.v_=null,this.x_("Backend didn't respond within 10 seconds."),this.M_("Offline"),Promise.resolve()))))}O_(e){"Online"===this.state?this.M_("Unknown"):(this.D_++,this.D_>=1&&(this.N_(),this.x_(`Connection failed 1 times. Most recent error: ${e.toString()}`),this.M_("Offline")))}set(e){this.N_(),this.D_=0,"Online"===e&&(this.C_=!1),this.M_(e)}M_(e){e!==this.state&&(this.state=e,this.onlineStateHandler(e))}x_(e){const t=`Could not reach Cloud Firestore backend. ${e}\nThis typically indicates that your device does not have a healthy Internet connection at the moment. The client will operate in offline mode until it is able to successfully connect to the backend.`;this.C_?(p(t),this.C_=!1):g("OnlineStateTracker",t)}N_(){null!==this.v_&&(this.v_.cancel(),this.v_=null)}}class Sa{constructor(e,t,n,r,i){this.localStore=e,this.datastore=t,this.asyncQueue=n,this.remoteSyncer={},this.L_=[],this.B_=new Map,this.k_=new Set,this.q_=[],this.Q_=i,this.Q_.uo((e=>{n.enqueueAndForget((async()=>{Ma(this)&&(g("RemoteStore","Restarting streams for network reachability change."),await async function(e){const t=b(e);t.k_.add(4),await Ca(t),t.K_.set("Unknown"),t.k_.delete(4),await xa(t)}(this))}))})),this.K_=new Ta(n,r)}}async function xa(e){if(Ma(e))for(const t of e.q_)await t(!0)}async function Ca(e){for(const t of e.q_)await t(!1)}function Da(e,t){const n=b(e);n.B_.has(t.targetId)||(n.B_.set(t.targetId,t),Oa(n)?La(n):Za(n).s_()&&ka(n,t))}function Aa(e,t){const n=b(e),r=Za(n);n.B_.delete(t),r.s_()&&Na(n,t),0===n.B_.size&&(r.s_()?r.a_():Ma(n)&&n.K_.set("Unknown"))}function ka(e,t){if(e.U_.xe(t.targetId),t.resumeToken.approximateByteSize()>0||t.snapshotVersion.compareTo(V.min())>0){const n=e.remoteSyncer.getRemoteKeysForTarget(t.targetId).size;t=t.withExpectedCount(n)}Za(e).V_(t)}function Na(e,t){e.U_.xe(t),Za(e).m_(t)}function La(e){e.U_=new si({getRemoteKeysForTarget:t=>e.remoteSyncer.getRemoteKeysForTarget(t),ut:t=>e.B_.get(t)||null,nt:()=>e.datastore.serializer.databaseId}),Za(e).start(),e.K_.F_()}function Oa(e){return Ma(e)&&!Za(e).i_()&&e.B_.size>0}function Ma(e){return 0===b(e).k_.size}function Ra(e){e.U_=void 0}async function Pa(e){e.K_.set("Online")}async function Fa(e){e.B_.forEach(((t,n)=>{ka(e,t)}))}async function Va(e,t){Ra(e),Oa(e)?(e.K_.O_(t),La(e)):e.K_.set("Unknown")}async function qa(e,t,n){if(e.K_.set("Online"),t instanceof ri&&2===t.state&&t.cause)try{await async function(e,t){const n=t.cause;for(const r of t.targetIds)e.B_.has(r)&&(await e.remoteSyncer.rejectListen(r,n),e.B_.delete(r),e.U_.removeTarget(r))}(e,t)}catch(n){g("RemoteStore","Failed to remove targets %s: %s ",t.targetIds.join(","),n),await Ba(e,n)}else if(t instanceof ti?e.U_.$e(t):t instanceof ni?e.U_.Je(t):e.U_.Ge(t),!n.isEqual(V.min()))try{const t=await jo(e.localStore);n.compareTo(t)>=0&&await function(e,t){const n=e.U_.it(t);return n.targetChanges.forEach(((n,r)=>{if(n.resumeToken.approximateByteSize()>0){const i=e.B_.get(r);i&&e.B_.set(r,i.withResumeToken(n.resumeToken,t))}})),n.targetMismatches.forEach(((t,n)=>{const r=e.B_.get(t);if(!r)return;e.B_.set(t,r.withResumeToken(lt.EMPTY_BYTE_STRING,r.snapshotVersion)),Na(e,t);const i=new $i(r.target,t,n,r.sequenceNumber);ka(e,i)})),e.remoteSyncer.applyRemoteEvent(n)}(e,n)}catch(t){g("RemoteStore","Failed to raise snapshot:",t),await Ba(e,t)}}async function Ba(e,t,n){if(!le(t))throw t;e.k_.add(1),await Ca(e),e.K_.set("Offline"),n||(n=()=>jo(e.localStore)),e.asyncQueue.enqueueRetryable((async()=>{g("RemoteStore","Retrying IndexedDB access"),await n(),e.k_.delete(1),await xa(e)}))}function Ua(e,t){return t().catch((n=>Ba(e,n,t)))}async function ja(e){const t=b(e),n=ec(t);let r=t.L_.length>0?t.L_[t.L_.length-1].batchId:-1;for(;$a(t);)try{const e=await zo(t.localStore,r);if(null===e){0===t.L_.length&&n.a_();break}r=e.batchId,za(t,e)}catch(e){await Ba(t,e)}Ga(t)&&Ka(t)}function $a(e){return Ma(e)&&e.L_.length<10}function za(e,t){e.L_.push(t);const n=ec(e);n.s_()&&n.f_&&n.g_(t.mutations)}function Ga(e){return Ma(e)&&!ec(e).i_()&&e.L_.length>0}function Ka(e){ec(e).start()}async function Qa(e){ec(e).w_()}async function Ha(e){const t=ec(e);for(const n of e.L_)t.g_(n.mutations)}async function Wa(e,t,n){const r=e.L_.shift(),i=Vr.from(r,t,n);await Ua(e,(()=>e.remoteSyncer.applySuccessfulWrite(i))),await ja(e)}async function Ja(e,t){t&&ec(e).f_&&await async function(e,t){if(function(e){return zr(e)&&e!==_.ABORTED}(t.code)){const n=e.L_.shift();ec(e).__(),await Ua(e,(()=>e.remoteSyncer.rejectFailedWrite(n.batchId,t))),await ja(e)}}(e,t),Ga(e)&&Ka(e)}async function Xa(e,t){const n=b(e);n.asyncQueue.verifyOperationInProgress(),g("RemoteStore","RemoteStore received new credentials");const r=Ma(n);n.k_.add(3),await Ca(n),r&&n.K_.set("Unknown"),await n.remoteSyncer.handleCredentialChange(t),n.k_.delete(3),await xa(n)}async function Ya(e,t){const n=b(e);t?(n.k_.delete(2),await xa(n)):t||(n.k_.add(2),await Ca(n),n.K_.set("Unknown"))}function Za(e){return e.W_||(e.W_=function(e,t,n){const r=b(e);return r.b_(),new _a(t,r.connection,r.authCredentials,r.appCheckCredentials,r.serializer,n)}(e.datastore,e.asyncQueue,{Ro:Pa.bind(null,e),mo:Fa.bind(null,e),po:Va.bind(null,e),R_:qa.bind(null,e)}),e.q_.push((async t=>{t?(e.W_.__(),Oa(e)?La(e):e.K_.set("Unknown")):(await e.W_.stop(),Ra(e))}))),e.W_}function ec(e){return e.G_||(e.G_=function(e,t,n){const r=b(e);return r.b_(),new Ia(t,r.connection,r.authCredentials,r.appCheckCredentials,r.serializer,n)}(e.datastore,e.asyncQueue,{Ro:()=>Promise.resolve(),mo:Qa.bind(null,e),po:Ja.bind(null,e),p_:Ha.bind(null,e),y_:Wa.bind(null,e)}),e.q_.push((async t=>{t?(e.G_.__(),await ja(e)):(await e.G_.stop(),e.L_.length>0&&(g("RemoteStore",`Stopping write stream with ${e.L_.length} pending writes`),e.L_=[]))}))),e.G_}class tc{constructor(e,t,n,r,i){this.asyncQueue=e,this.timerId=t,this.targetTimeMs=n,this.op=r,this.removalCallback=i,this.deferred=new E,this.then=this.deferred.promise.then.bind(this.deferred.promise),this.deferred.promise.catch((e=>{}))}get promise(){return this.deferred.promise}static createAndSchedule(e,t,n,r,i){const s=Date.now()+n,o=new tc(e,t,s,r,i);return o.start(n),o}start(e){this.timerHandle=setTimeout((()=>this.handleDelayElapsed()),e)}skipDelay(){return this.handleDelayElapsed()}cancel(e){null!==this.timerHandle&&(this.clearTimeout(),this.deferred.reject(new I(_.CANCELLED,"Operation cancelled"+(e?": "+e:""))))}handleDelayElapsed(){this.asyncQueue.enqueueAndForget((()=>null!==this.timerHandle?(this.clearTimeout(),this.op().then((e=>this.deferred.resolve(e)))):Promise.resolve()))}clearTimeout(){null!==this.timerHandle&&(this.removalCallback(this),clearTimeout(this.timerHandle),this.timerHandle=null)}}function nc(e,t){if(p("AsyncQueue",`${t}: ${e}`),le(e))return new I(_.UNAVAILABLE,`${t}: ${e}`);throw e}class rc{static emptySet(e){return new rc(e.comparator)}constructor(e){this.comparator=e?(t,n)=>e(t,n)||$.comparator(t.key,n.key):(e,t)=>$.comparator(e.key,t.key),this.keyedMap=Wn(),this.sortedSet=new nt(this.comparator)}has(e){return null!=this.keyedMap.get(e)}get(e){return this.keyedMap.get(e)}first(){return this.sortedSet.minKey()}last(){return this.sortedSet.maxKey()}isEmpty(){return this.sortedSet.isEmpty()}indexOf(e){const t=this.keyedMap.get(e);return t?this.sortedSet.indexOf(t):-1}get size(){return this.sortedSet.size}forEach(e){this.sortedSet.inorderTraversal(((t,n)=>(e(t),!1)))}add(e){const t=this.delete(e.key);return t.copy(t.keyedMap.insert(e.key,e),t.sortedSet.insert(e,null))}delete(e){const t=this.get(e);return t?this.copy(this.keyedMap.remove(e),this.sortedSet.remove(t)):this}isEqual(e){if(!(e instanceof rc))return!1;if(this.size!==e.size)return!1;const t=this.sortedSet.getIterator(),n=e.sortedSet.getIterator();for(;t.hasNext();){const e=t.getNext().key,r=n.getNext().key;if(!e.isEqual(r))return!1}return!0}toString(){const e=[];return this.forEach((t=>{e.push(t.toString())})),0===e.length?"DocumentSet ()":"DocumentSet (\n "+e.join(" \n")+"\n)"}copy(e,t){const n=new rc;return n.comparator=this.comparator,n.keyedMap=e,n.sortedSet=t,n}}class ic{constructor(){this.z_=new nt($.comparator)}track(e){const t=e.doc.key,n=this.z_.get(t);n?0!==e.type&&3===n.type?this.z_=this.z_.insert(t,e):3===e.type&&1!==n.type?this.z_=this.z_.insert(t,{type:n.type,doc:e.doc}):2===e.type&&2===n.type?this.z_=this.z_.insert(t,{type:2,doc:e.doc}):2===e.type&&0===n.type?this.z_=this.z_.insert(t,{type:0,doc:e.doc}):1===e.type&&0===n.type?this.z_=this.z_.remove(t):1===e.type&&2===n.type?this.z_=this.z_.insert(t,{type:1,doc:n.doc}):0===e.type&&1===n.type?this.z_=this.z_.insert(t,{type:2,doc:e.doc}):v():this.z_=this.z_.insert(t,e)}j_(){const e=[];return this.z_.inorderTraversal(((t,n)=>{e.push(n)})),e}}class sc{constructor(e,t,n,r,i,s,o,a,c){this.query=e,this.docs=t,this.oldDocs=n,this.docChanges=r,this.mutatedKeys=i,this.fromCache=s,this.syncStateChanged=o,this.excludesMetadataChanges=a,this.hasCachedResults=c}static fromInitialDocuments(e,t,n,r,i){const s=[];return t.forEach((e=>{s.push({type:0,doc:e})})),new sc(e,t,rc.emptySet(t),s,n,r,!0,!1,i)}get hasPendingWrites(){return!this.mutatedKeys.isEmpty()}isEqual(e){if(!(this.fromCache===e.fromCache&&this.hasCachedResults===e.hasCachedResults&&this.syncStateChanged===e.syncStateChanged&&this.mutatedKeys.isEqual(e.mutatedKeys)&&Vn(this.query,e.query)&&this.docs.isEqual(e.docs)&&this.oldDocs.isEqual(e.oldDocs)))return!1;const t=this.docChanges,n=e.docChanges;if(t.length!==n.length)return!1;for(let e=0;e<t.length;e++)if(t[e].type!==n[e].type||!t[e].doc.isEqual(n[e].doc))return!1;return!0}}class oc{constructor(){this.H_=void 0,this.J_=[]}Y_(){return this.J_.some((e=>e.Z_()))}}class ac{constructor(){this.queries=cc(),this.onlineState="Unknown",this.X_=new Set}terminate(){!function(e,t){const n=b(e),r=n.queries;n.queries=cc(),r.forEach(((e,n)=>{for(const e of n.J_)e.onError(t)}))}(this,new I(_.ABORTED,"Firestore shutting down"))}}function cc(){return new Gn((e=>qn(e)),Vn)}async function uc(e,t){const n=b(e);let r=3;const i=t.query;let s=n.queries.get(i);s?!s.Y_()&&t.Z_()&&(r=2):(s=new oc,r=t.Z_()?0:1);try{switch(r){case 0:s.H_=await n.onListen(i,!0);break;case 1:s.H_=await n.onListen(i,!1);break;case 2:await n.onFirstRemoteStoreListen(i)}}catch(e){const n=nc(e,`Initialization of query '${Bn(t.query)}' failed`);return void t.onError(n)}n.queries.set(i,s),s.J_.push(t),t.ea(n.onlineState),s.H_&&t.ta(s.H_)&&fc(n)}async function lc(e,t){const n=b(e),r=t.query;let i=3;const s=n.queries.get(r);if(s){const e=s.J_.indexOf(t);e>=0&&(s.J_.splice(e,1),0===s.J_.length?i=t.Z_()?0:1:!s.Y_()&&t.Z_()&&(i=2))}switch(i){case 0:return n.queries.delete(r),n.onUnlisten(r,!0);case 1:return n.queries.delete(r),n.onUnlisten(r,!1);case 2:return n.onLastRemoteStoreUnlisten(r);default:return}}function hc(e,t){const n=b(e);let r=!1;for(const e of t){const t=e.query,i=n.queries.get(t);if(i){for(const t of i.J_)t.ta(e)&&(r=!0);i.H_=e}}r&&fc(n)}function dc(e,t,n){const r=b(e),i=r.queries.get(t);if(i)for(const e of i.J_)e.onError(n);r.queries.delete(t)}function fc(e){e.X_.forEach((e=>{e.next()}))}var gc,pc;(pc=gc||(gc={})).na="default",pc.Cache="cache";class mc{constructor(e,t,n){this.query=e,this.ra=t,this.ia=!1,this.sa=null,this.onlineState="Unknown",this.options=n||{}}ta(e){if(!this.options.includeMetadataChanges){const t=[];for(const n of e.docChanges)3!==n.type&&t.push(n);e=new sc(e.query,e.docs,e.oldDocs,t,e.mutatedKeys,e.fromCache,e.syncStateChanged,!0,e.hasCachedResults)}let t=!1;return this.ia?this.oa(e)&&(this.ra.next(e),t=!0):this._a(e,this.onlineState)&&(this.aa(e),t=!0),this.sa=e,t}onError(e){this.ra.error(e)}ea(e){this.onlineState=e;let t=!1;return this.sa&&!this.ia&&this._a(this.sa,e)&&(this.aa(this.sa),t=!0),t}_a(e,t){if(!e.fromCache)return!0;if(!this.Z_())return!0;const n="Offline"!==t;return(!this.options.ua||!n)&&(!e.docs.isEmpty()||e.hasCachedResults||"Offline"===t)}oa(e){if(e.docChanges.length>0)return!0;const t=this.sa&&this.sa.hasPendingWrites!==e.hasPendingWrites;return!(!e.syncStateChanged&&!t)&&!0===this.options.includeMetadataChanges}aa(e){e=sc.fromInitialDocuments(e.query,e.docs,e.mutatedKeys,e.fromCache,e.hasCachedResults),this.ia=!0,this.ra.next(e)}Z_(){return this.options.source!==gc.Cache}}class yc{constructor(e,t){this.ca=e,this.byteLength=t}la(){return"metadata"in this.ca}}class vc{constructor(e){this.serializer=e}As(e){return _i(this.serializer,e)}Rs(e){return e.metadata.exists?Ci(this.serializer,e.document,!1):Qt.newNoDocument(this.As(e.metadata.name),this.Vs(e.metadata.readTime))}Vs(e){return mi(e)}}class wc{constructor(e,t,n){this.ha=e,this.localStore=t,this.serializer=n,this.queries=[],this.documents=[],this.collectionGroups=new Set,this.progress=bc(e)}Pa(e){this.progress.bytesLoaded+=e.byteLength;let t=this.progress.documentsLoaded;if(e.ca.namedQuery)this.queries.push(e.ca.namedQuery);else if(e.ca.documentMetadata){this.documents.push({metadata:e.ca.documentMetadata}),e.ca.documentMetadata.exists||++t;const n=B.fromString(e.ca.documentMetadata.name);this.collectionGroups.add(n.get(n.length-2))}else e.ca.document&&(this.documents[this.documents.length-1].document=e.ca.document,++t);return t!==this.progress.documentsLoaded?(this.progress.documentsLoaded=t,Object.assign({},this.progress)):null}Ta(e){const t=new Map,n=new vc(this.serializer);for(const r of e)if(r.metadata.queries){const e=n.As(r.metadata.name);for(const n of r.metadata.queries){const r=(t.get(n)||nr()).add(e);t.set(n,r)}}return t}async complete(){const e=await async function(e,t,n,r){const i=b(e);let s=nr(),o=Qn();for(const e of n){const n=t.As(e.metadata.name);e.document&&(s=s.add(n));const r=t.Rs(e);r.setReadTime(t.Vs(e.metadata.readTime)),o=o.insert(n,r)}const a=i.hs.newChangeBuffer({trackRemovals:!0}),c=await Go(i,function(e){return On(An(B.fromString(`__bundle__/docs/${e}`)))}(r));return i.persistence.runTransaction("Apply bundle documents","readwrite",(e=>$o(e,a,o).next((t=>(a.apply(e),t))).next((t=>i.Gr.removeMatchingKeysForTargetId(e,c.targetId).next((()=>i.Gr.addMatchingKeys(e,s,c.targetId))).next((()=>i.localDocuments.getLocalViewOfDocuments(e,t.Is,t.Es))).next((()=>t.Is))))))}(this.localStore,new vc(this.serializer),this.documents,this.ha.id),t=this.Ta(this.documents);for(const e of this.queries)await Xo(this.localStore,e,t.get(e.name));return this.progress.taskState="Success",{progress:this.progress,Ia:this.collectionGroups,Ea:e}}}function bc(e){return{taskState:"Running",documentsLoaded:0,bytesLoaded:0,totalDocuments:e.totalDocuments,totalBytes:e.totalBytes}}class _c{constructor(e){this.key=e}}class Ic{constructor(e){this.key=e}}class Ec{constructor(e,t){this.query=e,this.da=t,this.Aa=null,this.hasCachedResults=!1,this.current=!1,this.Ra=nr(),this.mutatedKeys=nr(),this.Va=$n(e),this.ma=new rc(this.Va)}get fa(){return this.da}ga(e,t){const n=t?t.pa:new ic,r=t?t.ma:this.ma;let i=t?t.mutatedKeys:this.mutatedKeys,s=r,o=!1;const a="F"===this.query.limitType&&r.size===this.query.limit?r.last():null,c="L"===this.query.limitType&&r.size===this.query.limit?r.first():null;if(e.inorderTraversal(((e,t)=>{const u=r.get(e),l=Un(this.query,t)?t:null,h=!!u&&this.mutatedKeys.has(u.key),d=!!l&&(l.hasLocalMutations||this.mutatedKeys.has(l.key)&&l.hasCommittedMutations);let f=!1;u&&l?u.data.isEqual(l.data)?h!==d&&(n.track({type:3,doc:l}),f=!0):this.ya(u,l)||(n.track({type:2,doc:l}),f=!0,(a&&this.Va(l,a)>0||c&&this.Va(l,c)<0)&&(o=!0)):!u&&l?(n.track({type:0,doc:l}),f=!0):u&&!l&&(n.track({type:1,doc:u}),f=!0,(a||c)&&(o=!0)),f&&(l?(s=s.add(l),i=d?i.add(e):i.delete(e)):(s=s.delete(e),i=i.delete(e)))})),null!==this.query.limit)for(;s.size>this.query.limit;){const e="F"===this.query.limitType?s.last():s.first();s=s.delete(e.key),i=i.delete(e.key),n.track({type:1,doc:e})}return{ma:s,pa:n,ss:o,mutatedKeys:i}}ya(e,t){return e.hasLocalMutations&&t.hasCommittedMutations&&!t.hasLocalMutations}applyChanges(e,t,n,r){const i=this.ma;this.ma=e.ma,this.mutatedKeys=e.mutatedKeys;const s=e.pa.j_();s.sort(((e,t)=>function(e,t){const n=e=>{switch(e){case 0:return 1;case 2:case 3:return 2;case 1:return 0;default:return v()}};return n(e)-n(t)}(e.type,t.type)||this.Va(e.doc,t.doc))),this.wa(n),r=null!=r&&r;const o=t&&!r?this.Sa():[],a=0===this.Ra.size&&this.current&&!r?1:0,c=a!==this.Aa;return this.Aa=a,0!==s.length||c?{snapshot:new sc(this.query,e.ma,i,s,e.mutatedKeys,0===a,c,!1,!!n&&n.resumeToken.approximateByteSize()>0),ba:o}:{ba:o}}ea(e){return this.current&&"Offline"===e?(this.current=!1,this.applyChanges({ma:this.ma,pa:new ic,mutatedKeys:this.mutatedKeys,ss:!1},!1)):{ba:[]}}Da(e){return!this.da.has(e)&&!!this.ma.has(e)&&!this.ma.get(e).hasLocalMutations}wa(e){e&&(e.addedDocuments.forEach((e=>this.da=this.da.add(e))),e.modifiedDocuments.forEach((e=>{})),e.removedDocuments.forEach((e=>this.da=this.da.delete(e))),this.current=e.current)}Sa(){if(!this.current)return[];const e=this.Ra;this.Ra=nr(),this.ma.forEach((e=>{this.Da(e.key)&&(this.Ra=this.Ra.add(e.key))}));const t=[];return e.forEach((e=>{this.Ra.has(e)||t.push(new Ic(e))})),this.Ra.forEach((n=>{e.has(n)||t.push(new _c(n))})),t}va(e){this.da=e.ds,this.Ra=nr();const t=this.ga(e.documents);return this.applyChanges(t,!0)}Ca(){return sc.fromInitialDocuments(this.query,this.ma,this.mutatedKeys,0===this.Aa,this.hasCachedResults)}}class Tc{constructor(e,t,n){this.query=e,this.targetId=t,this.view=n}}class Sc{constructor(e){this.key=e,this.Fa=!1}}class xc{constructor(e,t,n,r,i,s){this.localStore=e,this.remoteStore=t,this.eventManager=n,this.sharedClientState=r,this.currentUser=i,this.maxConcurrentLimboResolutions=s,this.Ma={},this.xa=new Gn((e=>qn(e)),Vn),this.Oa=new Map,this.Na=new Set,this.La=new nt($.comparator),this.Ba=new Map,this.ka=new wo,this.qa={},this.Qa=new Map,this.Ka=Ks.Qn(),this.onlineState="Unknown",this.$a=void 0}get isPrimaryClient(){return!0===this.$a}}async function Cc(e,t,n=!0){const r=nu(e);let i;const s=r.xa.get(t);return s?(r.sharedClientState.addLocalQueryTarget(s.targetId),i=s.view.Ca()):i=await Ac(r,t,n,!0),i}async function Dc(e,t){const n=nu(e);await Ac(n,t,!0,!1)}async function Ac(e,t,n,r){const i=await Go(e.localStore,On(t)),s=i.targetId,o=e.sharedClientState.addLocalQueryTarget(s,n);let a;return r&&(a=await kc(e,t,s,"current"===o,i.resumeToken)),e.isPrimaryClient&&n&&Da(e.remoteStore,i),a}async function kc(e,t,n,r,i){e.Ua=(t,n,r)=>async function(e,t,n,r){let i=t.view.ga(n);i.ss&&(i=await Qo(e.localStore,t.query,!1).then((({documents:e})=>t.view.ga(e,i))));const s=r&&r.targetChanges.get(t.targetId),o=r&&null!=r.targetMismatches.get(t.targetId),a=t.view.applyChanges(i,e.isPrimaryClient,s,o);return jc(e,t.targetId,a.ba),a.snapshot}(e,t,n,r);const s=await Qo(e.localStore,t,!0),o=new Ec(t,s.ds),a=o.ga(s.documents),c=ei.createSynthesizedTargetChangeForCurrentChange(n,r&&"Offline"!==e.onlineState,i),u=o.applyChanges(a,e.isPrimaryClient,c);jc(e,n,u.ba);const l=new Tc(t,n,o);return e.xa.set(t,l),e.Oa.has(n)?e.Oa.get(n).push(t):e.Oa.set(n,[t]),u.snapshot}async function Nc(e,t,n){const r=b(e),i=r.xa.get(t),s=r.Oa.get(i.targetId);if(s.length>1)return r.Oa.set(i.targetId,s.filter((e=>!Vn(e,t)))),void r.xa.delete(t);r.isPrimaryClient?(r.sharedClientState.removeLocalQueryTarget(i.targetId),r.sharedClientState.isActiveQueryTarget(i.targetId)||await Ko(r.localStore,i.targetId,!1).then((()=>{r.sharedClientState.clearQueryState(i.targetId),n&&Aa(r.remoteStore,i.targetId),Bc(r,i.targetId)})).catch(re)):(Bc(r,i.targetId),await Ko(r.localStore,i.targetId,!0))}async function Lc(e,t){const n=b(e),r=n.xa.get(t),i=n.Oa.get(r.targetId);n.isPrimaryClient&&1===i.length&&(n.sharedClientState.removeLocalQueryTarget(r.targetId),Aa(n.remoteStore,r.targetId))}async function Oc(e,t){const n=b(e);try{const e=await function(e,t){const n=b(e),r=t.snapshotVersion;let i=n.us;return n.persistence.runTransaction("Apply remote event","readwrite-primary",(e=>{const s=n.hs.newChangeBuffer({trackRemovals:!0});i=n.us;const o=[];t.targetChanges.forEach(((s,a)=>{const c=i.get(a);if(!c)return;o.push(n.Gr.removeMatchingKeys(e,s.removedDocuments,a).next((()=>n.Gr.addMatchingKeys(e,s.addedDocuments,a))));let u=c.withSequenceNumber(e.currentSequenceNumber);null!==t.targetMismatches.get(a)?u=u.withResumeToken(lt.EMPTY_BYTE_STRING,V.min()).withLastLimboFreeSnapshotVersion(V.min()):s.resumeToken.approximateByteSize()>0&&(u=u.withResumeToken(s.resumeToken,r)),i=i.insert(a,u),function(e,t,n){return 0===e.resumeToken.approximateByteSize()||t.snapshotVersion.toMicroseconds()-e.snapshotVersion.toMicroseconds()>=3e8||n.addedDocuments.size+n.modifiedDocuments.size+n.removedDocuments.size>0}(c,u,s)&&o.push(n.Gr.updateTargetData(e,u))}));let a=Qn(),c=nr();if(t.documentUpdates.forEach((r=>{t.resolvedLimboDocuments.has(r)&&o.push(n.persistence.referenceDelegate.updateLimboDocument(e,r))})),o.push($o(e,s,t.documentUpdates).next((e=>{a=e.Is,c=e.Es}))),!r.isEqual(V.min())){const t=n.Gr.getLastRemoteSnapshotVersion(e).next((t=>n.Gr.setTargetsMetadata(e,e.currentSequenceNumber,r)));o.push(t)}return ie.waitFor(o).next((()=>s.apply(e))).next((()=>n.localDocuments.getLocalViewOfDocuments(e,a,c))).next((()=>a))})).then((e=>(n.us=i,e)))}(n.localStore,t);t.targetChanges.forEach(((e,t)=>{const r=n.Ba.get(t);r&&(w(e.addedDocuments.size+e.modifiedDocuments.size+e.removedDocuments.size<=1),e.addedDocuments.size>0?r.Fa=!0:e.modifiedDocuments.size>0?w(r.Fa):e.removedDocuments.size>0&&(w(r.Fa),r.Fa=!1))})),await Gc(n,e,t)}catch(e){await re(e)}}function Mc(e,t,n){const r=b(e);if(r.isPrimaryClient&&0===n||!r.isPrimaryClient&&1===n){const e=[];r.xa.forEach(((n,r)=>{const i=r.view.ea(t);i.snapshot&&e.push(i.snapshot)})),function(e,t){const n=b(e);n.onlineState=t;let r=!1;n.queries.forEach(((e,n)=>{for(const e of n.J_)e.ea(t)&&(r=!0)})),r&&fc(n)}(r.eventManager,t),e.length&&r.Ma.R_(e),r.onlineState=t,r.isPrimaryClient&&r.sharedClientState.setOnlineState(t)}}async function Rc(e,t,n){const r=b(e);r.sharedClientState.updateQueryState(t,"rejected",n);const i=r.Ba.get(t),s=i&&i.key;if(s){let e=new nt($.comparator);e=e.insert(s,Qt.newNoDocument(s,V.min()));const n=nr().add(s),i=new Zr(V.min(),new Map,new nt(M),e,n);await Oc(r,i),r.La=r.La.remove(s),r.Ba.delete(t),zc(r)}else await Ko(r.localStore,t,!1).then((()=>Bc(r,t,n))).catch(re)}async function Pc(e,t){const n=b(e),r=t.batch.batchId;try{const e=await function(e,t){const n=b(e);return n.persistence.runTransaction("Acknowledge batch","readwrite-primary",(e=>{const r=t.batch.keys(),i=n.hs.newChangeBuffer({trackRemovals:!0});return function(e,t,n,r){const i=n.batch,s=i.keys();let o=ie.resolve();return s.forEach((e=>{o=o.next((()=>r.getEntry(t,e))).next((t=>{const s=n.docVersions.get(e);w(null!==s),t.version.compareTo(s)<0&&(i.applyToRemoteDocument(t,n),t.isValidDocument()&&(t.setReadTime(n.commitVersion),r.addEntry(t)))}))})),o.next((()=>e.mutationQueue.removeMutationBatch(t,i)))}(n,e,t,i).next((()=>i.apply(e))).next((()=>n.mutationQueue.performConsistencyCheck(e))).next((()=>n.documentOverlayCache.removeOverlaysForBatchId(e,r,t.batch.batchId))).next((()=>n.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(e,function(e){let t=nr();for(let n=0;n<e.mutationResults.length;++n)e.mutationResults[n].transformResults.length>0&&(t=t.add(e.batch.mutations[n].key));return t}(t)))).next((()=>n.localDocuments.getDocuments(e,r)))}))}(n.localStore,t);qc(n,r,null),Vc(n,r),n.sharedClientState.updateMutationState(r,"acknowledged"),await Gc(n,e)}catch(e){await re(e)}}async function Fc(e,t,n){const r=b(e);try{const e=await function(e,t){const n=b(e);return n.persistence.runTransaction("Reject batch","readwrite-primary",(e=>{let r;return n.mutationQueue.lookupMutationBatch(e,t).next((t=>(w(null!==t),r=t.keys(),n.mutationQueue.removeMutationBatch(e,t)))).next((()=>n.mutationQueue.performConsistencyCheck(e))).next((()=>n.documentOverlayCache.removeOverlaysForBatchId(e,r,t))).next((()=>n.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(e,r))).next((()=>n.localDocuments.getDocuments(e,r)))}))}(r.localStore,t);qc(r,t,n),Vc(r,t),r.sharedClientState.updateMutationState(t,"rejected",n),await Gc(r,e)}catch(n){await re(n)}}function Vc(e,t){(e.Qa.get(t)||[]).forEach((e=>{e.resolve()})),e.Qa.delete(t)}function qc(e,t,n){const r=b(e);let i=r.qa[r.currentUser.toKey()];if(i){const e=i.get(t);e&&(n?e.reject(n):e.resolve(),i=i.remove(t)),r.qa[r.currentUser.toKey()]=i}}function Bc(e,t,n=null){e.sharedClientState.removeLocalQueryTarget(t);for(const r of e.Oa.get(t))e.xa.delete(r),n&&e.Ma.Wa(r,n);e.Oa.delete(t),e.isPrimaryClient&&e.ka.yr(t).forEach((t=>{e.ka.containsKey(t)||Uc(e,t)}))}function Uc(e,t){e.Na.delete(t.path.canonicalString());const n=e.La.get(t);null!==n&&(Aa(e.remoteStore,n),e.La=e.La.remove(t),e.Ba.delete(n),zc(e))}function jc(e,t,n){for(const r of n)r instanceof _c?(e.ka.addReference(r.key,t),$c(e,r)):r instanceof Ic?(g("SyncEngine","Document no longer in limbo: "+r.key),e.ka.removeReference(r.key,t),e.ka.containsKey(r.key)||Uc(e,r.key)):v()}function $c(e,t){const n=t.key,r=n.path.canonicalString();e.La.get(n)||e.Na.has(r)||(g("SyncEngine","New document in limbo: "+n),e.Na.add(r),zc(e))}function zc(e){for(;e.Na.size>0&&e.La.size<e.maxConcurrentLimboResolutions;){const t=e.Na.values().next().value;e.Na.delete(t);const n=new $(B.fromString(t)),r=e.Ka.next();e.Ba.set(r,new Sc(n)),e.La=e.La.insert(n,r),Da(e.remoteStore,new $i(On(An(n.path)),r,"TargetPurposeLimboResolution",ye.oe))}}async function Gc(e,t,n){const r=b(e),i=[],s=[],o=[];r.xa.isEmpty()||(r.xa.forEach(((e,a)=>{o.push(r.Ua(a,t,n).then((e=>{var t;if((e||n)&&r.isPrimaryClient){const i=e?!e.fromCache:null===(t=null==n?void 0:n.targetChanges.get(a.targetId))||void 0===t?void 0:t.current;r.sharedClientState.updateQueryState(a.targetId,i?"current":"not-current")}if(e){i.push(e);const t=Po.zi(a.targetId,e);s.push(t)}})))})),await Promise.all(o),r.Ma.R_(i),await async function(e,t){const n=b(e);try{await n.persistence.runTransaction("notifyLocalViewChanges","readwrite",(e=>ie.forEach(t,(t=>ie.forEach(t.Wi,(r=>n.persistence.referenceDelegate.addReference(e,t.targetId,r))).next((()=>ie.forEach(t.Gi,(r=>n.persistence.referenceDelegate.removeReference(e,t.targetId,r)))))))))}catch(e){if(!le(e))throw e;g("LocalStore","Failed to update sequence numbers: "+e)}for(const e of t){const t=e.targetId;if(!e.fromCache){const e=n.us.get(t),r=e.snapshotVersion,i=e.withLastLimboFreeSnapshotVersion(r);n.us=n.us.insert(t,i)}}}(r.localStore,s))}async function Kc(e,t){const n=b(e);if(!n.currentUser.isEqual(t)){g("SyncEngine","User change. New user:",t.toKey());const e=await Uo(n.localStore,t);n.currentUser=t,function(e){e.Qa.forEach((e=>{e.forEach((e=>{e.reject(new I(_.CANCELLED,"'waitForPendingWrites' promise is rejected due to a user change."))}))})),e.Qa.clear()}(n),n.sharedClientState.handleUserChange(t,e.removedBatchIds,e.addedBatchIds),await Gc(n,e.Ts)}}function Qc(e,t){const n=b(e),r=n.Ba.get(t);if(r&&r.Fa)return nr().add(r.key);{let e=nr();const r=n.Oa.get(t);if(!r)return e;for(const t of r){const r=n.xa.get(t);e=e.unionWith(r.view.fa)}return e}}async function Hc(e,t){const n=b(e),r=await Qo(n.localStore,t.query,!0),i=t.view.va(r);return n.isPrimaryClient&&jc(n,t.targetId,i.ba),i}async function Wc(e,t){const n=b(e);return Wo(n.localStore,t).then((e=>Gc(n,e)))}async function Jc(e,t,n,r){const i=b(e),s=await function(e,t){const n=b(e),r=b(n.mutationQueue);return n.persistence.runTransaction("Lookup mutation documents","readonly",(e=>r.On(e,t).next((t=>t?n.localDocuments.getDocuments(e,t):ie.resolve(null)))))}(i.localStore,t);null!==s?("pending"===n?await ja(i.remoteStore):"acknowledged"===n||"rejected"===n?(qc(i,t,r||null),Vc(i,t),function(e,t){b(b(e).mutationQueue).Ln(t)}(i.localStore,t)):v(),await Gc(i,s)):g("SyncEngine","Cannot apply mutation batch with id: "+t)}async function Xc(e,t,n){const r=b(e),i=[],s=[];for(const e of t){let t;const n=r.Oa.get(e);if(n&&0!==n.length){t=await Go(r.localStore,On(n[0]));for(const e of n){const t=r.xa.get(e),n=await Hc(r,t);n.snapshot&&s.push(n.snapshot)}}else{const n=await Ho(r.localStore,e);t=await Go(r.localStore,n),await kc(r,Yc(n),e,!1,t.resumeToken)}i.push(t)}return r.Ma.R_(s),i}function Yc(e){return Dn(e.path,e.collectionGroup,e.orderBy,e.filters,e.limit,"F",e.startAt,e.endAt)}function Zc(e){return function(e){return b(b(e).persistence).$i()}(b(e).localStore)}async function eu(e,t,n,r){const i=b(e);if(i.$a)return void g("SyncEngine","Ignoring unexpected query state notification.");const s=i.Oa.get(t);if(s&&s.length>0)switch(n){case"current":case"not-current":{const e=await Wo(i.localStore,jn(s[0])),r=Zr.createSynthesizedRemoteEventForCurrentChange(t,"current"===n,lt.EMPTY_BYTE_STRING);await Gc(i,e,r);break}case"rejected":await Ko(i.localStore,t,!0),Bc(i,t,r);break;default:v()}}async function tu(e,t,n){const r=nu(e);if(r.$a){for(const e of t){if(r.Oa.has(e)&&r.sharedClientState.isActiveQueryTarget(e)){g("SyncEngine","Adding an already active target "+e);continue}const t=await Ho(r.localStore,e),n=await Go(r.localStore,t);await kc(r,Yc(t),n.targetId,!1,n.resumeToken),Da(r.remoteStore,n)}for(const e of n)r.Oa.has(e)&&await Ko(r.localStore,e,!1).then((()=>{Aa(r.remoteStore,e),Bc(r,e)})).catch(re)}}function nu(e){const t=b(e);return t.remoteStore.remoteSyncer.applyRemoteEvent=Oc.bind(null,t),t.remoteStore.remoteSyncer.getRemoteKeysForTarget=Qc.bind(null,t),t.remoteStore.remoteSyncer.rejectListen=Rc.bind(null,t),t.Ma.R_=hc.bind(null,t.eventManager),t.Ma.Wa=dc.bind(null,t.eventManager),t}function ru(e){const t=b(e);return t.remoteStore.remoteSyncer.applySuccessfulWrite=Pc.bind(null,t),t.remoteStore.remoteSyncer.rejectFailedWrite=Fc.bind(null,t),t}class iu{constructor(){this.kind="memory",this.synchronizeTabs=!1}async initialize(e){this.serializer=va(e.databaseInfo.databaseId),this.sharedClientState=this.za(e),this.persistence=this.ja(e),await this.persistence.start(),this.localStore=this.Ha(e),this.gcScheduler=this.Ja(e,this.localStore),this.indexBackfillerScheduler=this.Ya(e,this.localStore)}Ja(e,t){return null}Ya(e,t){return null}Ha(e){return Bo(this.persistence,new Vo,e.initialUser,this.serializer)}ja(e){return new So(Co.ei,this.serializer)}za(e){return new aa}async terminate(){var e,t;null===(e=this.gcScheduler)||void 0===e||e.stop(),null===(t=this.indexBackfillerScheduler)||void 0===t||t.stop(),this.sharedClientState.shutdown(),await this.persistence.shutdown()}}iu.provider={build:()=>new iu};class su extends iu{constructor(e){super(),this.cacheSizeBytes=e}Ja(e,t){w(this.persistence.referenceDelegate instanceof Do);const n=this.persistence.referenceDelegate.garbageCollector;return new Zs(n,e.asyncQueue,t)}ja(e){const t=void 0!==this.cacheSizeBytes?Vs.withCacheSize(this.cacheSizeBytes):Vs.DEFAULT;return new So((e=>Do.ei(e,t)),this.serializer)}}class ou extends iu{constructor(e,t,n){super(),this.Za=e,this.cacheSizeBytes=t,this.forceOwnership=n,this.kind="persistent",this.synchronizeTabs=!1}async initialize(e){await super.initialize(e),await this.Za.initialize(this,e),await ru(this.Za.syncEngine),await ja(this.Za.remoteStore),await this.persistence.Si((()=>(this.gcScheduler&&!this.gcScheduler.started&&this.gcScheduler.start(),this.indexBackfillerScheduler&&!this.indexBackfillerScheduler.started&&this.indexBackfillerScheduler.start(),Promise.resolve())))}Ha(e){return Bo(this.persistence,new Vo,e.initialUser,this.serializer)}Ja(e,t){const n=this.persistence.referenceDelegate.garbageCollector;return new Zs(n,e.asyncQueue,t)}Ya(e,t){const n=new me(t,this.persistence);return new pe(e.asyncQueue,n)}ja(e){const t=Ro(e.databaseInfo.databaseId,e.databaseInfo.persistenceKey),n=void 0!==this.cacheSizeBytes?Vs.withCacheSize(this.cacheSizeBytes):Vs.DEFAULT;return new Lo(this.synchronizeTabs,t,e.clientId,n,e.asyncQueue,ma(),ya(),this.serializer,this.sharedClientState,!!this.forceOwnership)}za(e){return new aa}}class au extends ou{constructor(e,t){super(e,t,!1),this.Za=e,this.cacheSizeBytes=t,this.synchronizeTabs=!0}async initialize(e){await super.initialize(e);const t=this.Za.syncEngine;this.sharedClientState instanceof oa&&(this.sharedClientState.syncEngine={io:Jc.bind(null,t),so:eu.bind(null,t),oo:tu.bind(null,t),$i:Zc.bind(null,t),ro:Wc.bind(null,t)},await this.sharedClientState.start()),await this.persistence.Si((async e=>{await async function(e,t){const n=b(e);if(nu(n),ru(n),!0===t&&!0!==n.$a){const e=n.sharedClientState.getAllActiveQueryTargets(),t=await Xc(n,e.toArray());n.$a=!0,await Ya(n.remoteStore,!0);for(const e of t)Da(n.remoteStore,e)}else if(!1===t&&!1!==n.$a){const e=[];let t=Promise.resolve();n.Oa.forEach(((r,i)=>{n.sharedClientState.isLocalQueryTarget(i)?e.push(i):t=t.then((()=>(Bc(n,i),Ko(n.localStore,i,!0)))),Aa(n.remoteStore,i)})),await t,await Xc(n,e),function(e){const t=b(e);t.Ba.forEach(((e,n)=>{Aa(t.remoteStore,n)})),t.ka.wr(),t.Ba=new Map,t.La=new nt($.comparator)}(n),n.$a=!1,await Ya(n.remoteStore,!1)}}(this.Za.syncEngine,e),this.gcScheduler&&(e&&!this.gcScheduler.started?this.gcScheduler.start():e||this.gcScheduler.stop()),this.indexBackfillerScheduler&&(e&&!this.indexBackfillerScheduler.started?this.indexBackfillerScheduler.start():e||this.indexBackfillerScheduler.stop())}))}za(e){const t=ma();if(!oa.p(t))throw new I(_.UNIMPLEMENTED,"IndexedDB persistence is only available on platforms that support LocalStorage.");const n=Ro(e.databaseInfo.databaseId,e.databaseInfo.persistenceKey);return new oa(t,e.asyncQueue,n,e.clientId,e.initialUser)}}class cu{async initialize(e,t){this.localStore||(this.localStore=e.localStore,this.sharedClientState=e.sharedClientState,this.datastore=this.createDatastore(t),this.remoteStore=this.createRemoteStore(t),this.eventManager=this.createEventManager(t),this.syncEngine=this.createSyncEngine(t,!e.synchronizeTabs),this.sharedClientState.onlineStateHandler=e=>Mc(this.syncEngine,e,1),this.remoteStore.remoteSyncer.handleCredentialChange=Kc.bind(null,this.syncEngine),await Ya(this.remoteStore,this.syncEngine.isPrimaryClient))}createEventManager(e){return new ac}createDatastore(e){const t=va(e.databaseInfo.databaseId),n=function(e){return new pa(e)}(e.databaseInfo);return function(e,t,n,r){return new Ea(e,t,n,r)}(e.authCredentials,e.appCheckCredentials,n,t)}createRemoteStore(e){return function(e,t,n,r,i){return new Sa(e,t,n,r,i)}(this.localStore,this.datastore,e.asyncQueue,(e=>Mc(this.syncEngine,e,0)),ua.p()?new ua:new ca)}createSyncEngine(e,t){return function(e,t,n,r,i,s,o){const a=new xc(e,t,n,r,i,s);return o&&(a.$a=!0),a}(this.localStore,this.remoteStore,this.eventManager,this.sharedClientState,e.initialUser,e.maxConcurrentLimboResolutions,t)}async terminate(){var e,t;await async function(e){const t=b(e);g("RemoteStore","RemoteStore shutting down."),t.k_.add(5),await Ca(t),t.Q_.shutdown(),t.K_.set("Unknown")}(this.remoteStore),null===(e=this.datastore)||void 0===e||e.terminate(),null===(t=this.eventManager)||void 0===t||t.terminate()}}function uu(e,t=10240){let n=0;return{async read(){if(n<e.byteLength){const r={value:e.slice(n,n+t),done:!1};return n+=t,r}return{done:!0}},async cancel(){},releaseLock(){},closed:Promise.resolve()}}cu.provider={build:()=>new cu};class lu{constructor(e){this.observer=e,this.muted=!1}next(e){this.muted||this.observer.next&&this.Xa(this.observer.next,e)}error(e){this.muted||(this.observer.error?this.Xa(this.observer.error,e):p("Uncaught Error in snapshot listener:",e.toString()))}eu(){this.muted=!0}Xa(e,t){setTimeout((()=>{this.muted||e(t)}),0)}}class hu{constructor(e,t){this.tu=e,this.serializer=t,this.metadata=new E,this.buffer=new Uint8Array,this.nu=new TextDecoder("utf-8"),this.ru().then((e=>{e&&e.la()?this.metadata.resolve(e.ca.metadata):this.metadata.reject(new Error(`The first element of the bundle is not a metadata, it is\n ${JSON.stringify(null==e?void 0:e.ca)}`))}),(e=>this.metadata.reject(e)))}close(){return this.tu.cancel()}async getMetadata(){return this.metadata.promise}async Ga(){return await this.getMetadata(),this.ru()}async ru(){const e=await this.iu();if(null===e)return null;const t=this.nu.decode(e),n=Number(t);isNaN(n)&&this.su(`length string (${t}) is not valid number`);const r=await this.ou(n);return new yc(JSON.parse(r),e.length+n)}_u(){return this.buffer.findIndex((e=>e==="{".charCodeAt(0)))}async iu(){for(;this._u()<0&&!await this.au(););if(0===this.buffer.length)return null;const e=this._u();e<0&&this.su("Reached the end of bundle when a length string is expected.");const t=this.buffer.slice(0,e);return this.buffer=this.buffer.slice(e),t}async ou(e){for(;this.buffer.length<e;)await this.au()&&this.su("Reached the end of bundle when more is expected.");const t=this.nu.decode(this.buffer.slice(0,e));return this.buffer=this.buffer.slice(e),t}su(e){throw this.tu.cancel(),new Error(`Invalid bundle format: ${e}`)}async au(){const e=await this.tu.read();if(!e.done){const t=new Uint8Array(this.buffer.length+e.value.length);t.set(this.buffer),t.set(e.value,this.buffer.length),this.buffer=t}return e.done}}class du{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 I(_.INVALID_ARGUMENT,"Firestore transactions require all reads to be executed before all writes."),this.lastTransactionError;const t=await async function(e,t){const n=b(e),r={documents:t.map((e=>bi(n.serializer,e)))},i=await n.ko("BatchGetDocuments",n.serializer.databaseId,B.emptyPath(),r,t.length),s=new Map;i.forEach((e=>{const t=function(e,t){return"found"in t?function(e,t){w(!!t.found),t.found.name,t.found.updateTime;const n=_i(e,t.found.name),r=mi(t.found.updateTime),i=t.found.createTime?mi(t.found.createTime):V.min(),s=new Gt({mapValue:{fields:t.found.fields}});return Qt.newFoundDocument(n,r,i,s)}(e,t):"missing"in t?function(e,t){w(!!t.missing),w(!!t.readTime);const n=_i(e,t.missing),r=mi(t.readTime);return Qt.newNoDocument(n,r)}(e,t):v()}(n.serializer,e);s.set(t.key.toString(),t)}));const o=[];return t.forEach((e=>{const t=s.get(e.toString());w(!!t),o.push(t)})),o}(this.datastore,e);return t.forEach((e=>this.recordVersion(e))),t}set(e,t){this.write(t.toMutation(e,this.precondition(e))),this.writtenDocs.add(e.toString())}update(e,t){try{this.write(t.toMutation(e,this.preconditionForUpdate(e)))}catch(e){this.lastTransactionError=e}this.writtenDocs.add(e.toString())}delete(e){this.write(new Rr(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((t=>{e.delete(t.key.toString())})),e.forEach(((e,t)=>{const n=$.fromPath(t);this.mutations.push(new Pr(n,this.precondition(n)))})),await async function(e,t){const n=b(e),r={writes:t.map((e=>Di(n.serializer,e)))};await n.Oo("Commit",n.serializer.databaseId,B.emptyPath(),r)}(this.datastore,this.mutations),this.committed=!0}recordVersion(e){let t;if(e.isFoundDocument())t=e.version;else{if(!e.isNoDocument())throw v();t=V.min()}const n=this.readVersions.get(e.key.toString());if(n){if(!t.isEqual(n))throw new I(_.ABORTED,"Document version changed between two reads.")}else this.readVersions.set(e.key.toString(),t)}precondition(e){const t=this.readVersions.get(e.toString());return!this.writtenDocs.has(e.toString())&&t?t.isEqual(V.min())?Ir.exists(!1):Ir.updateTime(t):Ir.none()}preconditionForUpdate(e){const t=this.readVersions.get(e.toString());if(!this.writtenDocs.has(e.toString())&&t){if(t.isEqual(V.min()))throw new I(_.INVALID_ARGUMENT,"Can't update a document that doesn't exist.");return Ir.updateTime(t)}return Ir.exists(!0)}write(e){this.ensureCommitNotCalled(),this.mutations.push(e)}ensureCommitNotCalled(){}}class fu{constructor(e,t,n,r,i){this.asyncQueue=e,this.datastore=t,this.options=n,this.updateFunction=r,this.deferred=i,this.uu=n.maxAttempts,this.r_=new wa(this.asyncQueue,"transaction_retry")}cu(){this.uu-=1,this.lu()}lu(){this.r_.jo((async()=>{const e=new du(this.datastore),t=this.hu(e);t&&t.then((t=>{this.asyncQueue.enqueueAndForget((()=>e.commit().then((()=>{this.deferred.resolve(t)})).catch((e=>{this.Pu(e)}))))})).catch((e=>{this.Pu(e)}))}))}hu(e){try{const t=this.updateFunction(e);return!ve(t)&&t.catch&&t.then?t:(this.deferred.reject(Error("Transaction callback must return a Promise")),null)}catch(e){return this.deferred.reject(e),null}}Pu(e){this.uu>0&&this.Tu(e)?(this.uu-=1,this.asyncQueue.enqueueAndForget((()=>(this.lu(),Promise.resolve())))):this.deferred.reject(e)}Tu(e){if("FirebaseError"===e.name){const t=e.code;return"aborted"===t||"failed-precondition"===t||"already-exists"===t||!zr(t)}return!1}}class gu{constructor(e,t,n,r,i){this.authCredentials=e,this.appCheckCredentials=t,this.asyncQueue=n,this.databaseInfo=r,this.user=l.UNAUTHENTICATED,this.clientId=O.newId(),this.authCredentialListener=()=>Promise.resolve(),this.appCheckCredentialListener=()=>Promise.resolve(),this._uninitializedComponentsProvider=i,this.authCredentials.start(n,(async e=>{g("FirestoreClient","Received user=",e.uid),await this.authCredentialListener(e),this.user=e})),this.appCheckCredentials.start(n,(e=>(g("FirestoreClient","Received new app check token=",e),this.appCheckCredentialListener(e,this.user))))}get configuration(){return{asyncQueue:this.asyncQueue,databaseInfo:this.databaseInfo,clientId:this.clientId,authCredentials:this.authCredentials,appCheckCredentials:this.appCheckCredentials,initialUser:this.user,maxConcurrentLimboResolutions:100}}setCredentialChangeListener(e){this.authCredentialListener=e}setAppCheckTokenChangeListener(e){this.appCheckCredentialListener=e}terminate(){this.asyncQueue.enterRestrictedMode();const e=new E;return this.asyncQueue.enqueueAndForgetEvenWhileRestricted((async()=>{try{this._onlineComponents&&await this._onlineComponents.terminate(),this._offlineComponents&&await this._offlineComponents.terminate(),this.authCredentials.shutdown(),this.appCheckCredentials.shutdown(),e.resolve()}catch(t){const n=nc(t,"Failed to shutdown persistence");e.reject(n)}})),e.promise}}async function pu(e,t){e.asyncQueue.verifyOperationInProgress(),g("FirestoreClient","Initializing OfflineComponentProvider");const n=e.configuration;await t.initialize(n);let r=n.initialUser;e.setCredentialChangeListener((async e=>{r.isEqual(e)||(await Uo(t.localStore,e),r=e)})),t.persistence.setDatabaseDeletedListener((()=>e.terminate())),e._offlineComponents=t}async function mu(e,t){e.asyncQueue.verifyOperationInProgress();const n=await yu(e);g("FirestoreClient","Initializing OnlineComponentProvider"),await t.initialize(n,e.configuration),e.setCredentialChangeListener((e=>Xa(t.remoteStore,e))),e.setAppCheckTokenChangeListener(((e,n)=>Xa(t.remoteStore,n))),e._onlineComponents=t}async function yu(e){if(!e._offlineComponents)if(e._uninitializedComponentsProvider){g("FirestoreClient","Using user provided OfflineComponentProvider");try{await pu(e,e._uninitializedComponentsProvider._offline)}catch(t){const n=t;if(!function(e){return"FirebaseError"===e.name?e.code===_.FAILED_PRECONDITION||e.code===_.UNIMPLEMENTED:!("undefined"!=typeof DOMException&&e instanceof DOMException)||22===e.code||20===e.code||11===e.code}(n))throw n;m("Error using user provided cache. Falling back to memory cache: "+n),await pu(e,new iu)}}else g("FirestoreClient","Using default OfflineComponentProvider"),await pu(e,new su(void 0));return e._offlineComponents}async function vu(e){return e._onlineComponents||(e._uninitializedComponentsProvider?(g("FirestoreClient","Using user provided OnlineComponentProvider"),await mu(e,e._uninitializedComponentsProvider._online)):(g("FirestoreClient","Using default OnlineComponentProvider"),await mu(e,new cu))),e._onlineComponents}function wu(e){return yu(e).then((e=>e.persistence))}function bu(e){return yu(e).then((e=>e.localStore))}function _u(e){return vu(e).then((e=>e.remoteStore))}function Iu(e){return vu(e).then((e=>e.syncEngine))}function Eu(e){return vu(e).then((e=>e.datastore))}async function Tu(e){const t=await vu(e),n=t.eventManager;return n.onListen=Cc.bind(null,t.syncEngine),n.onUnlisten=Nc.bind(null,t.syncEngine),n.onFirstRemoteStoreListen=Dc.bind(null,t.syncEngine),n.onLastRemoteStoreUnlisten=Lc.bind(null,t.syncEngine),n}function Su(e,t,n={}){const r=new E;return e.asyncQueue.enqueueAndForget((async()=>function(e,t,n,r,i){const s=new lu({next:a=>{s.eu(),t.enqueueAndForget((()=>lc(e,o)));const c=a.docs.has(n);!c&&a.fromCache?i.reject(new I(_.UNAVAILABLE,"Failed to get document because the client is offline.")):c&&a.fromCache&&r&&"server"===r.source?i.reject(new I(_.UNAVAILABLE,'Failed to get document from server. (However, this document does exist in the local cache. Run again without setting source to "server" to retrieve the cached document.)')):i.resolve(a)},error:e=>i.reject(e)}),o=new mc(An(n.path),s,{includeMetadataChanges:!0,ua:!0});return uc(e,o)}(await Tu(e),e.asyncQueue,t,n,r))),r.promise}function xu(e,t,n={}){const r=new E;return e.asyncQueue.enqueueAndForget((async()=>function(e,t,n,r,i){const s=new lu({next:n=>{s.eu(),t.enqueueAndForget((()=>lc(e,o))),n.fromCache&&"server"===r.source?i.reject(new I(_.UNAVAILABLE,'Failed to get documents from server. (However, these documents may exist in the local cache. Run again without setting source to "server" to retrieve the cached documents.)')):i.resolve(n)},error:e=>i.reject(e)}),o=new mc(n,s,{includeMetadataChanges:!0,ua:!0});return uc(e,o)}(await Tu(e),e.asyncQueue,t,n,r))),r.promise}function Cu(e){const t={};return void 0!==e.timeoutSeconds&&(t.timeoutSeconds=e.timeoutSeconds),t}const Du=new Map;function Au(e,t,n){if(!n)throw new I(_.INVALID_ARGUMENT,`Function ${e}() cannot be called with an empty ${t}.`)}function ku(e,t,n,r){if(!0===t&&!0===r)throw new I(_.INVALID_ARGUMENT,`${e} and ${n} cannot be used together.`)}function Nu(e){if(!$.isDocumentKey(e))throw new I(_.INVALID_ARGUMENT,`Invalid document reference. Document references must have an even number of segments, but ${e} has ${e.length}.`)}function Lu(e){if($.isDocumentKey(e))throw new I(_.INVALID_ARGUMENT,`Invalid collection reference. Collection references must have an odd number of segments, but ${e} has ${e.length}.`)}function Ou(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 t=function(e){return e.constructor?e.constructor.name:null}(e);return t?`a custom ${t} object`:"an object"}}return"function"==typeof e?"a function":v()}function Mu(e,t){if("_delegate"in e&&(e=e._delegate),!(e instanceof t)){if(t.name===e.constructor.name)throw new I(_.INVALID_ARGUMENT,"Type does not match the expected instance. Did you pass a reference from a different Firestore SDK?");{const n=Ou(e);throw new I(_.INVALID_ARGUMENT,`Expected type '${t.name}', but it was: ${n}`)}}return e}function Ru(e,t){if(t<=0)throw new I(_.INVALID_ARGUMENT,`Function ${e}() requires a positive number, but it was: ${t}.`)}class Pu{constructor(e){var t,n;if(void 0===e.host){if(void 0!==e.ssl)throw new I(_.INVALID_ARGUMENT,"Can't provide ssl option if host option is not set");this.host="firestore.googleapis.com",this.ssl=!0}else this.host=e.host,this.ssl=null===(t=e.ssl)||void 0===t||t;if(this.credentials=e.credentials,this.ignoreUndefinedProperties=!!e.ignoreUndefinedProperties,this.localCache=e.localCache,void 0===e.cacheSizeBytes)this.cacheSizeBytes=41943040;else{if(-1!==e.cacheSizeBytes&&e.cacheSizeBytes<1048576)throw new I(_.INVALID_ARGUMENT,"cacheSizeBytes must be at least 1048576");this.cacheSizeBytes=e.cacheSizeBytes}ku("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=Cu(null!==(n=e.experimentalLongPollingOptions)&&void 0!==n?n:{}),function(e){if(void 0!==e.timeoutSeconds){if(isNaN(e.timeoutSeconds))throw new I(_.INVALID_ARGUMENT,`invalid long polling timeout: ${e.timeoutSeconds} (must not be NaN)`);if(e.timeoutSeconds<5)throw new I(_.INVALID_ARGUMENT,`invalid long polling timeout: ${e.timeoutSeconds} (minimum allowed value is 5)`);if(e.timeoutSeconds>30)throw new I(_.INVALID_ARGUMENT,`invalid long polling timeout: ${e.timeoutSeconds} (maximum allowed value is 30)`)}}(this.experimentalLongPollingOptions),this.useFetchStreams=!!e.useFetchStreams}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(e,t){return e.timeoutSeconds===t.timeoutSeconds}(this.experimentalLongPollingOptions,e.experimentalLongPollingOptions)&&this.ignoreUndefinedProperties===e.ignoreUndefinedProperties&&this.useFetchStreams===e.useFetchStreams}}class Fu{constructor(e,t,n,r){this._authCredentials=e,this._appCheckCredentials=t,this._databaseId=n,this._app=r,this.type="firestore-lite",this._persistenceKey="(lite)",this._settings=new Pu({}),this._settingsFrozen=!1,this._terminateTask="notTerminated"}get app(){if(!this._app)throw new I(_.FAILED_PRECONDITION,"Firestore was not initialized using the Firebase SDK. 'app' is not available");return this._app}get _initialized(){return this._settingsFrozen}get _terminated(){return"notTerminated"!==this._terminateTask}_setSettings(e){if(this._settingsFrozen)throw new I(_.FAILED_PRECONDITION,"Firestore has already been started and its settings can no longer be changed. You can only modify settings before calling any other methods on a Firestore object.");this._settings=new Pu(e),void 0!==e.credentials&&(this._authCredentials=function(e){if(!e)return new S;switch(e.type){case"firstParty":return new A(e.sessionIndex||"0",e.iamToken||null,e.authTokenFactory||null);case"provider":return e.client;default:throw new I(_.INVALID_ARGUMENT,"makeAuthCredentialsProvider failed due to invalid credential type")}}(e.credentials))}_getSettings(){return this._settings}_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(e){const t=Du.get(e);t&&(g("ComponentProvider","Removing Datastore"),Du.delete(e),t.terminate())}(this),Promise.resolve()}}function Vu(e,t,n,r={}){var i;const s=(e=Mu(e,Fu))._getSettings(),a=`${t}:${n}`;if("firestore.googleapis.com"!==s.host&&s.host!==a&&m("Host has been set in both settings() and connectFirestoreEmulator(), emulator host will be used."),e._setSettings(Object.assign(Object.assign({},s),{host:a,ssl:!1})),r.mockUserToken){let t,n;if("string"==typeof r.mockUserToken)t=r.mockUserToken,n=l.MOCK_USER;else{t=o.createMockUserToken(r.mockUserToken,null===(i=e._app)||void 0===i?void 0:i.options.projectId);const s=r.mockUserToken.sub||r.mockUserToken.user_id;if(!s)throw new I(_.INVALID_ARGUMENT,"mockUserToken must contain 'sub' or 'user_id' field!");n=new l(s)}e._authCredentials=new x(new T(t,n))}}class qu{constructor(e,t,n){this.converter=t,this._query=n,this.type="query",this.firestore=e}withConverter(e){return new qu(this.firestore,e,this._query)}}class Bu{constructor(e,t,n){this.converter=t,this._key=n,this.type="document",this.firestore=e}get _path(){return this._key.path}get id(){return this._key.path.lastSegment()}get path(){return this._key.path.canonicalString()}get parent(){return new Uu(this.firestore,this.converter,this._key.path.popLast())}withConverter(e){return new Bu(this.firestore,e,this._key)}}class Uu extends qu{constructor(e,t,n){super(e,t,An(n)),this._path=n,this.type="collection"}get id(){return this._query.path.lastSegment()}get path(){return this._query.path.canonicalString()}get parent(){const e=this._path.popLast();return e.isEmpty()?null:new Bu(this.firestore,null,new $(e))}withConverter(e){return new Uu(this.firestore,e,this._path)}}function ju(e,t,...n){if(e=o.getModularInstance(e),1===arguments.length&&(t=O.newId()),Au("doc","path",t),e instanceof Fu){const r=B.fromString(t,...n);return Nu(r),new Bu(e,null,new $(r))}{if(!(e instanceof Bu||e instanceof Uu))throw new I(_.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");const r=e._path.child(B.fromString(t,...n));return Nu(r),new Bu(e.firestore,e instanceof Uu?e.converter:null,new $(r))}}function $u(e,t){return e=o.getModularInstance(e),t=o.getModularInstance(t),e instanceof qu&&t instanceof qu&&e.firestore===t.firestore&&Vn(e._query,t._query)&&e.converter===t.converter}class zu{constructor(e=Promise.resolve()){this.Iu=[],this.Eu=!1,this.du=[],this.Au=null,this.Ru=!1,this.Vu=!1,this.mu=[],this.r_=new wa(this,"async_queue_retry"),this.fu=()=>{const e=ya();e&&g("AsyncQueue","Visibility state changed to "+e.visibilityState),this.r_.Jo()},this.gu=e;const t=ya();t&&"function"==typeof t.addEventListener&&t.addEventListener("visibilitychange",this.fu)}get isShuttingDown(){return this.Eu}enqueueAndForget(e){this.enqueue(e)}enqueueAndForgetEvenWhileRestricted(e){this.pu(),this.yu(e)}enterRestrictedMode(e){if(!this.Eu){this.Eu=!0,this.Vu=e||!1;const t=ya();t&&"function"==typeof t.removeEventListener&&t.removeEventListener("visibilitychange",this.fu)}}enqueue(e){if(this.pu(),this.Eu)return new Promise((()=>{}));const t=new E;return this.yu((()=>this.Eu&&this.Vu?Promise.resolve():(e().then(t.resolve,t.reject),t.promise))).then((()=>t.promise))}enqueueRetryable(e){this.enqueueAndForget((()=>(this.Iu.push(e),this.wu())))}async wu(){if(0!==this.Iu.length){try{await this.Iu[0](),this.Iu.shift(),this.r_.reset()}catch(e){if(!le(e))throw e;g("AsyncQueue","Operation failed with retryable error: "+e)}this.Iu.length>0&&this.r_.jo((()=>this.wu()))}}yu(e){const t=this.gu.then((()=>(this.Ru=!0,e().catch((e=>{this.Au=e,this.Ru=!1;const t=function(e){let t=e.message||"";return e.stack&&(t=e.stack.includes(e.message)?e.stack:e.message+"\n"+e.stack),t}(e);throw p("INTERNAL UNHANDLED ERROR: ",t),e})).then((e=>(this.Ru=!1,e))))));return this.gu=t,t}enqueueAfterDelay(e,t,n){this.pu(),this.mu.indexOf(e)>-1&&(t=0);const r=tc.createAndSchedule(this,e,t,n,(e=>this.Su(e)));return this.du.push(r),r}pu(){this.Au&&v()}verifyOperationInProgress(){}async bu(){let e;do{e=this.gu,await e}while(e!==this.gu)}Du(e){for(const t of this.du)if(t.timerId===e)return!0;return!1}vu(e){return this.bu().then((()=>{this.du.sort(((e,t)=>e.targetTimeMs-t.targetTimeMs));for(const t of this.du)if(t.skipDelay(),"all"!==e&&t.timerId===e)break;return this.bu()}))}Cu(e){this.mu.push(e)}Su(e){const t=this.du.indexOf(e);this.du.splice(t,1)}}function Gu(e){return function(e){if("object"!=typeof e||null===e)return!1;const t=e;for(const e of["next","error","complete"])if(e in t&&"function"==typeof t[e])return!0;return!1}(e)}class Ku{constructor(){this._progressObserver={},this._taskCompletionResolver=new E,this._lastProgress={taskState:"Running",totalBytes:0,totalDocuments:0,bytesLoaded:0,documentsLoaded:0}}onProgress(e,t,n){this._progressObserver={next:e,error:t,complete:n}}catch(e){return this._taskCompletionResolver.promise.catch(e)}then(e,t){return this._taskCompletionResolver.promise.then(e,t)}_completeWith(e){this._updateProgress(e),this._progressObserver.complete&&this._progressObserver.complete(),this._taskCompletionResolver.resolve(e)}_failWith(e){this._lastProgress.taskState="Error",this._progressObserver.next&&this._progressObserver.next(this._lastProgress),this._progressObserver.error&&this._progressObserver.error(e),this._taskCompletionResolver.reject(e)}_updateProgress(e){this._lastProgress=e,this._progressObserver.next&&this._progressObserver.next(e)}}class Qu extends Fu{constructor(e,t,n,r){super(e,t,n,r),this.type="firestore",this._queue=new zu,this._persistenceKey=(null==r?void 0:r.name)||"[DEFAULT]"}async _terminate(){if(this._firestoreClient){const e=this._firestoreClient.terminate();this._queue=new zu(e),this._firestoreClient=void 0,await e}}}function Hu(e){if(e._terminated)throw new I(_.FAILED_PRECONDITION,"The client has already been terminated.");return e._firestoreClient||Wu(e),e._firestoreClient}function Wu(e){var t,n,r;const i=e._freezeSettings(),s=function(e,t,n,r){return new vt(e,t,n,r.host,r.ssl,r.experimentalForceLongPolling,r.experimentalAutoDetectLongPolling,Cu(r.experimentalLongPollingOptions),r.useFetchStreams)}(e._databaseId,(null===(t=e._app)||void 0===t?void 0:t.options.appId)||"",e._persistenceKey,i);e._componentsProvider||(null===(n=i.localCache)||void 0===n?void 0:n._offlineComponentProvider)&&(null===(r=i.localCache)||void 0===r?void 0:r._onlineComponentProvider)&&(e._componentsProvider={_offline:i.localCache._offlineComponentProvider,_online:i.localCache._onlineComponentProvider}),e._firestoreClient=new gu(e._authCredentials,e._appCheckCredentials,e._queue,s,e._componentsProvider&&function(e){const t=null==e?void 0:e._online.build();return{_offline:null==e?void 0:e._offline.build(t),_online:t}}(e._componentsProvider))}function Ju(e,t,n){if((e=Mu(e,Qu))._firestoreClient||e._terminated)throw new I(_.FAILED_PRECONDITION,"Firestore has already been started and persistence can no longer be enabled. You can only enable persistence before calling any other methods on a Firestore object.");if(e._componentsProvider||e._getSettings().localCache)throw new I(_.FAILED_PRECONDITION,"SDK cache is already specified.");e._componentsProvider={_online:t,_offline:n},Wu(e)}class Xu{constructor(e="count",t){this._internalFieldPath=t,this.type="AggregateField",this.aggregateType=e}}class Yu{constructor(e,t,n){this._userDataWriter=t,this._data=n,this.type="AggregateQuerySnapshot",this.query=e}data(){return this._userDataWriter.convertObjectMap(this._data)}}class Zu{constructor(e){this._byteString=e}static fromBase64String(e){try{return new Zu(lt.fromBase64String(e))}catch(e){throw new I(_.INVALID_ARGUMENT,"Failed to construct data from Base64 string: "+e)}}static fromUint8Array(e){return new Zu(lt.fromUint8Array(e))}toBase64(){return this._byteString.toBase64()}toUint8Array(){return this._byteString.toUint8Array()}toString(){return"Bytes(base64: "+this.toBase64()+")"}isEqual(e){return this._byteString.isEqual(e._byteString)}}class el{constructor(...e){for(let t=0;t<e.length;++t)if(0===e[t].length)throw new I(_.INVALID_ARGUMENT,"Invalid field name at argument $(i + 1). Field names must not be empty.");this._internalPath=new j(e)}isEqual(e){return this._internalPath.isEqual(e._internalPath)}}class tl{constructor(e){this._methodName=e}}class nl{constructor(e,t){if(!isFinite(e)||e<-90||e>90)throw new I(_.INVALID_ARGUMENT,"Latitude must be a number between -90 and 90, but was: "+e);if(!isFinite(t)||t<-180||t>180)throw new I(_.INVALID_ARGUMENT,"Longitude must be a number between -180 and 180, but was: "+t);this._lat=e,this._long=t}get latitude(){return this._lat}get longitude(){return this._long}isEqual(e){return this._lat===e._lat&&this._long===e._long}toJSON(){return{latitude:this._lat,longitude:this._long}}_compareTo(e){return M(this._lat,e._lat)||M(this._long,e._long)}}class rl{constructor(e){this._values=(e||[]).map((e=>e))}toArray(){return this._values.map((e=>e))}isEqual(e){return function(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;++n)if(e[n]!==t[n])return!1;return!0}(this._values,e._values)}}const il=/^__.*__$/;class sl{constructor(e,t,n){this.data=e,this.fieldMask=t,this.fieldTransforms=n}toMutation(e,t){return null!==this.fieldMask?new Nr(e,this.data,this.fieldMask,t,this.fieldTransforms):new kr(e,this.data,t,this.fieldTransforms)}}class ol{constructor(e,t,n){this.data=e,this.fieldMask=t,this.fieldTransforms=n}toMutation(e,t){return new Nr(e,this.data,this.fieldMask,t,this.fieldTransforms)}}function al(e){switch(e){case 0:case 2:case 1:return!0;case 3:case 4:return!1;default:throw v()}}class cl{constructor(e,t,n,r,i,s){this.settings=e,this.databaseId=t,this.serializer=n,this.ignoreUndefinedProperties=r,void 0===i&&this.Fu(),this.fieldTransforms=i||[],this.fieldMask=s||[]}get path(){return this.settings.path}get Mu(){return this.settings.Mu}xu(e){return new cl(Object.assign(Object.assign({},this.settings),e),this.databaseId,this.serializer,this.ignoreUndefinedProperties,this.fieldTransforms,this.fieldMask)}Ou(e){var t;const n=null===(t=this.path)||void 0===t?void 0:t.child(e),r=this.xu({path:n,Nu:!1});return r.Lu(e),r}Bu(e){var t;const n=null===(t=this.path)||void 0===t?void 0:t.child(e),r=this.xu({path:n,Nu:!1});return r.Fu(),r}ku(e){return this.xu({path:void 0,Nu:!0})}qu(e){return Dl(e,this.settings.methodName,this.settings.Qu||!1,this.path,this.settings.Ku)}contains(e){return void 0!==this.fieldMask.find((t=>e.isPrefixOf(t)))||void 0!==this.fieldTransforms.find((t=>e.isPrefixOf(t.field)))}Fu(){if(this.path)for(let e=0;e<this.path.length;e++)this.Lu(this.path.get(e))}Lu(e){if(0===e.length)throw this.qu("Document fields must not be empty");if(al(this.Mu)&&il.test(e))throw this.qu('Document fields cannot begin and end with "__"')}}class ul{constructor(e,t,n){this.databaseId=e,this.ignoreUndefinedProperties=t,this.serializer=n||va(e)}$u(e,t,n,r=!1){return new cl({Mu:e,methodName:t,Ku:n,path:j.emptyPath(),Nu:!1,Qu:r},this.databaseId,this.serializer,this.ignoreUndefinedProperties)}}function ll(e){const t=e._freezeSettings(),n=va(e._databaseId);return new ul(e._databaseId,!!t.ignoreUndefinedProperties,n)}function hl(e,t,n,r,i,s={}){const o=e.$u(s.merge||s.mergeFields?2:0,t,n,i);Tl("Data must be an object, but it was:",o,r);const a=Il(r,o);let c,u;if(s.merge)c=new ct(o.fieldMask),u=o.fieldTransforms;else if(s.mergeFields){const e=[];for(const r of s.mergeFields){const i=Sl(t,r,n);if(!o.contains(i))throw new I(_.INVALID_ARGUMENT,`Field '${i}' is specified in your field mask but missing from your input data.`);Al(e,i)||e.push(i)}c=new ct(e),u=o.fieldTransforms.filter((e=>c.covers(e.field)))}else c=null,u=o.fieldTransforms;return new sl(new Gt(a),c,u)}class dl extends tl{_toFieldTransform(e){if(2!==e.Mu)throw 1===e.Mu?e.qu(`${this._methodName}() can only appear at the top level of your update data`):e.qu(`${this._methodName}() cannot be used with set() unless you pass {merge:true}`);return e.fieldMask.push(e.path),null}isEqual(e){return e instanceof dl}}function fl(e,t,n){return new cl({Mu:3,Ku:t.settings.Ku,methodName:e._methodName,Nu:n},t.databaseId,t.serializer,t.ignoreUndefinedProperties)}class gl extends tl{_toFieldTransform(e){return new br(e.path,new dr)}isEqual(e){return e instanceof gl}}class pl extends tl{constructor(e,t){super(e),this.Uu=t}_toFieldTransform(e){const t=fl(this,e,!0),n=this.Uu.map((e=>_l(e,t))),r=new fr(n);return new br(e.path,r)}isEqual(e){return e instanceof pl&&o.deepEqual(this.Uu,e.Uu)}}class ml extends tl{constructor(e,t){super(e),this.Uu=t}_toFieldTransform(e){const t=fl(this,e,!0),n=this.Uu.map((e=>_l(e,t))),r=new pr(n);return new br(e.path,r)}isEqual(e){return e instanceof ml&&o.deepEqual(this.Uu,e.Uu)}}class yl extends tl{constructor(e,t){super(e),this.Wu=t}_toFieldTransform(e){const t=new yr(e.serializer,ar(e.serializer,this.Wu));return new br(e.path,t)}isEqual(e){return e instanceof yl&&this.Wu===e.Wu}}function vl(e,t,n,r){const i=e.$u(1,t,n);Tl("Data must be an object, but it was:",i,r);const s=[],a=Gt.empty();Ze(r,((e,r)=>{const c=Cl(t,e,n);r=o.getModularInstance(r);const u=i.Bu(c);if(r instanceof dl)s.push(c);else{const e=_l(r,u);null!=e&&(s.push(c),a.set(c,e))}}));const c=new ct(s);return new ol(a,c,i.fieldTransforms)}function wl(e,t,n,r,i,s){const a=e.$u(1,t,n),c=[Sl(t,r,n)],u=[i];if(s.length%2!=0)throw new I(_.INVALID_ARGUMENT,`Function ${t}() needs to be called with an even number of arguments that alternate between field names and values.`);for(let e=0;e<s.length;e+=2)c.push(Sl(t,s[e])),u.push(s[e+1]);const l=[],h=Gt.empty();for(let e=c.length-1;e>=0;--e)if(!Al(l,c[e])){const t=c[e];let n=u[e];n=o.getModularInstance(n);const r=a.Bu(t);if(n instanceof dl)l.push(t);else{const e=_l(n,r);null!=e&&(l.push(t),h.set(t,e))}}const d=new ct(l);return new ol(h,d,a.fieldTransforms)}function bl(e,t,n,r=!1){return _l(n,e.$u(r?4:3,t))}function _l(e,t){if(El(e=o.getModularInstance(e)))return Tl("Unsupported field value:",t,e),Il(e,t);if(e instanceof tl)return function(e,t){if(!al(t.Mu))throw t.qu(`${e._methodName}() can only be used with update() and set()`);if(!t.path)throw t.qu(`${e._methodName}() is not currently supported inside arrays`);const n=e._toFieldTransform(t);n&&t.fieldTransforms.push(n)}(e,t),null;if(void 0===e&&t.ignoreUndefinedProperties)return null;if(t.path&&t.fieldMask.push(t.path),e instanceof Array){if(t.settings.Nu&&4!==t.Mu)throw t.qu("Nested arrays are not supported");return function(e,t){const n=[];let r=0;for(const i of e){let e=_l(i,t.ku(r));null==e&&(e={nullValue:"NULL_VALUE"}),n.push(e),r++}return{arrayValue:{values:n}}}(e,t)}return function(e,t){if(null===(e=o.getModularInstance(e)))return{nullValue:"NULL_VALUE"};if("number"==typeof e)return ar(t.serializer,e);if("boolean"==typeof e)return{booleanValue:e};if("string"==typeof e)return{stringValue:e};if(e instanceof Date){const n=F.fromDate(e);return{timestampValue:fi(t.serializer,n)}}if(e instanceof F){const n=new F(e.seconds,1e3*Math.floor(e.nanoseconds/1e3));return{timestampValue:fi(t.serializer,n)}}if(e instanceof nl)return{geoPointValue:{latitude:e.latitude,longitude:e.longitude}};if(e instanceof Zu)return{bytesValue:gi(t.serializer,e._byteString)};if(e instanceof Bu){const n=t.databaseId,r=e.firestore._databaseId;if(!r.isEqual(n))throw t.qu(`Document reference is for database ${r.projectId}/${r.database} but should be for database ${n.projectId}/${n.database}`);return{referenceValue:yi(e.firestore._databaseId||t.databaseId,e._key.path)}}if(e instanceof rl)return function(e,t){return{mapValue:{fields:{__type__:{stringValue:"__vector__"},value:{arrayValue:{values:e.toArray().map((e=>{if("number"!=typeof e)throw t.qu("VectorValues must only contain numeric values.");return sr(t.serializer,e)}))}}}}}}(e,t);throw t.qu(`Unsupported field value: ${Ou(e)}`)}(e,t)}function Il(e,t){const n={};return tt(e)?t.path&&t.path.length>0&&t.fieldMask.push(t.path):Ze(e,((e,r)=>{const i=_l(r,t.Ou(e));null!=i&&(n[e]=i)})),{mapValue:{fields:n}}}function El(e){return!("object"!=typeof e||null===e||e instanceof Array||e instanceof Date||e instanceof F||e instanceof nl||e instanceof Zu||e instanceof Bu||e instanceof tl||e instanceof rl)}function Tl(e,t,n){if(!El(n)||!function(e){return"object"==typeof e&&null!==e&&(Object.getPrototypeOf(e)===Object.prototype||null===Object.getPrototypeOf(e))}(n)){const r=Ou(n);throw"an object"===r?t.qu(e+" a custom object"):t.qu(e+" "+r)}}function Sl(e,t,n){if((t=o.getModularInstance(t))instanceof el)return t._internalPath;if("string"==typeof t)return Cl(e,t);throw Dl("Field path arguments must be of type string or ",e,!1,void 0,n)}const xl=new RegExp("[~\\*/\\[\\]]");function Cl(e,t,n){if(t.search(xl)>=0)throw Dl(`Invalid field path (${t}). Paths must not contain '~', '*', '/', '[', or ']'`,e,!1,void 0,n);try{return new el(...t.split("."))._internalPath}catch(r){throw Dl(`Invalid field path (${t}). Paths must not be empty, begin with '.', end with '.', or contain '..'`,e,!1,void 0,n)}}function Dl(e,t,n,r,i){const s=r&&!r.isEmpty(),o=void 0!==i;let a=`Function ${t}() called with invalid data`;n&&(a+=" (via `toFirestore()`)"),a+=". ";let c="";return(s||o)&&(c+=" (found",s&&(c+=` in field ${r}`),o&&(c+=` in document ${i}`),c+=")"),new I(_.INVALID_ARGUMENT,a+e+c)}function Al(e,t){return e.some((e=>e.isEqual(t)))}class kl{constructor(e,t,n,r,i){this._firestore=e,this._userDataWriter=t,this._key=n,this._document=r,this._converter=i}get id(){return this._key.path.lastSegment()}get ref(){return new Bu(this._firestore,this._converter,this._key)}exists(){return null!==this._document}data(){if(this._document){if(this._converter){const e=new Nl(this._firestore,this._userDataWriter,this._key,this._document,null);return this._converter.fromFirestore(e)}return this._userDataWriter.convertValue(this._document.data.value)}}get(e){if(this._document){const t=this._document.data.field(Ll("DocumentSnapshot.get",e));if(null!==t)return this._userDataWriter.convertValue(t)}}}class Nl extends kl{data(){return super.data()}}function Ll(e,t){return"string"==typeof t?Cl(e,t):t instanceof el?t._internalPath:t._delegate._internalPath}function Ol(e){if("L"===e.limitType&&0===e.explicitOrderBy.length)throw new I(_.UNIMPLEMENTED,"limitToLast() queries require specifying at least one orderBy() clause")}class Ml{}class Rl extends Ml{}class Pl extends Rl{constructor(e,t,n){super(),this._field=e,this._op=t,this._value=n,this.type="where"}static _create(e,t,n){return new Pl(e,t,n)}_apply(e){const t=this._parse(e);return Gl(e._query,t),new qu(e.firestore,e.converter,Pn(e._query,t))}_parse(e){const t=ll(e.firestore),n=function(e,t,n,r,i,s,o){let a;if(i.isKeyField()){if("array-contains"===s||"array-contains-any"===s)throw new I(_.INVALID_ARGUMENT,`Invalid Query. You can't perform '${s}' queries on documentId().`);if("in"===s||"not-in"===s){zl(o,s);const t=[];for(const n of o)t.push($l(r,e,n));a={arrayValue:{values:t}}}else a=$l(r,e,o)}else"in"!==s&&"not-in"!==s&&"array-contains-any"!==s||zl(o,s),a=bl(n,"where",o,"in"===s||"not-in"===s);return en.create(i,s,a)}(e._query,0,t,e.firestore._databaseId,this._field,this._op,this._value);return n}}class Fl extends Ml{constructor(e,t){super(),this.type=e,this._queryConstraints=t}static _create(e,t){return new Fl(e,t)}_parse(e){const t=this._queryConstraints.map((t=>t._parse(e))).filter((e=>e.getFilters().length>0));return 1===t.length?t[0]:tn.create(t,this._getOperator())}_apply(e){const t=this._parse(e);return 0===t.getFilters().length?e:(function(e,t){let n=e;const r=t.getFlattenedFilters();for(const e of r)Gl(n,e),n=Pn(n,e)}(e._query,t),new qu(e.firestore,e.converter,Pn(e._query,t)))}_getQueryConstraints(){return this._queryConstraints}_getOperator(){return"and"===this.type?"and":"or"}}class Vl extends Rl{constructor(e,t){super(),this._field=e,this._direction=t,this.type="orderBy"}static _create(e,t){return new Vl(e,t)}_apply(e){const t=function(e,t,n){if(null!==e.startAt)throw new I(_.INVALID_ARGUMENT,"Invalid query. You must not call startAt() or startAfter() before calling orderBy().");if(null!==e.endAt)throw new I(_.INVALID_ARGUMENT,"Invalid query. You must not call endAt() or endBefore() before calling orderBy().");return new Xt(t,n)}(e._query,this._field,this._direction);return new qu(e.firestore,e.converter,function(e,t){const n=e.explicitOrderBy.concat([t]);return new Cn(e.path,e.collectionGroup,n,e.filters.slice(),e.limit,e.limitType,e.startAt,e.endAt)}(e._query,t))}}class ql extends Rl{constructor(e,t,n){super(),this.type=e,this._limit=t,this._limitType=n}static _create(e,t,n){return new ql(e,t,n)}_apply(e){return new qu(e.firestore,e.converter,Fn(e._query,this._limit,this._limitType))}}class Bl extends Rl{constructor(e,t,n){super(),this.type=e,this._docOrFields=t,this._inclusive=n}static _create(e,t,n){return new Bl(e,t,n)}_apply(e){const t=jl(e,this.type,this._docOrFields,this._inclusive);return new qu(e.firestore,e.converter,function(e,t){return new Cn(e.path,e.collectionGroup,e.explicitOrderBy.slice(),e.filters.slice(),e.limit,e.limitType,t,e.endAt)}(e._query,t))}}class Ul extends Rl{constructor(e,t,n){super(),this.type=e,this._docOrFields=t,this._inclusive=n}static _create(e,t,n){return new Ul(e,t,n)}_apply(e){const t=jl(e,this.type,this._docOrFields,this._inclusive);return new qu(e.firestore,e.converter,function(e,t){return new Cn(e.path,e.collectionGroup,e.explicitOrderBy.slice(),e.filters.slice(),e.limit,e.limitType,e.startAt,t)}(e._query,t))}}function jl(e,t,n,r){if(n[0]=o.getModularInstance(n[0]),n[0]instanceof kl)return function(e,t,n,r,i){if(!r)throw new I(_.NOT_FOUND,`Can't use a DocumentSnapshot that doesn't exist for ${n}().`);const s=[];for(const n of Ln(e))if(n.field.isKeyField())s.push(Nt(t,r.key));else{const e=r.data.field(n.field);if(pt(e))throw new I(_.INVALID_ARGUMENT,'Invalid query. You are trying to start or end a query using a document for which the field "'+n.field+'" is an uncommitted server timestamp. (Since the value of this field is unknown, you cannot start/end a query with it.)');if(null===e){const e=n.field.canonicalString();throw new I(_.INVALID_ARGUMENT,`Invalid query. You are trying to start or end a query using a document for which the field '${e}' (used as the orderBy) does not exist.`)}s.push(e)}return new Ht(s,i)}(e._query,e.firestore._databaseId,t,n[0]._document,r);{const i=ll(e.firestore);return function(e,t,n,r,i,s){const o=e.explicitOrderBy;if(i.length>o.length)throw new I(_.INVALID_ARGUMENT,`Too many arguments provided to ${r}(). The number of arguments must be less than or equal to the number of orderBy() clauses`);const a=[];for(let s=0;s<i.length;s++){const c=i[s];if(o[s].field.isKeyField()){if("string"!=typeof c)throw new I(_.INVALID_ARGUMENT,`Invalid query. Expected a string for document ID in ${r}(), but got a ${typeof c}`);if(!Nn(e)&&-1!==c.indexOf("/"))throw new I(_.INVALID_ARGUMENT,`Invalid query. When querying a collection and ordering by documentId(), the value passed to ${r}() must be a plain document ID, but '${c}' contains a slash.`);const n=e.path.child(B.fromString(c));if(!$.isDocumentKey(n))throw new I(_.INVALID_ARGUMENT,`Invalid query. When querying a collection group and ordering by documentId(), the value passed to ${r}() must result in a valid document path, but '${n}' is not because it contains an odd number of segments.`);const i=new $(n);a.push(Nt(t,i))}else{const e=bl(n,r,c);a.push(e)}}return new Ht(a,s)}(e._query,e.firestore._databaseId,i,t,n,r)}}function $l(e,t,n){if("string"==typeof(n=o.getModularInstance(n))){if(""===n)throw new I(_.INVALID_ARGUMENT,"Invalid query. When querying with documentId(), you must provide a valid document ID, but it was an empty string.");if(!Nn(t)&&-1!==n.indexOf("/"))throw new I(_.INVALID_ARGUMENT,`Invalid query. When querying a collection by documentId(), you must provide a plain document ID, but '${n}' contains a '/' character.`);const r=t.path.child(B.fromString(n));if(!$.isDocumentKey(r))throw new I(_.INVALID_ARGUMENT,`Invalid query. When querying a collection group by documentId(), the value provided must result in a valid document path, but '${r}' is not because it has an odd number of segments (${r.length}).`);return Nt(e,new $(r))}if(n instanceof Bu)return Nt(e,n._key);throw new I(_.INVALID_ARGUMENT,`Invalid query. When querying with documentId(), you must provide a valid string or a DocumentReference, but it was: ${Ou(n)}.`)}function zl(e,t){if(!Array.isArray(e)||0===e.length)throw new I(_.INVALID_ARGUMENT,`Invalid Query. A non-empty array is required for '${t.toString()}' filters.`)}function Gl(e,t){const n=function(e,t){for(const n of e)for(const e of n.getFlattenedFilters())if(t.indexOf(e.op)>=0)return e.op;return null}(e.filters,function(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[]}}(t.op));if(null!==n)throw n===t.op?new I(_.INVALID_ARGUMENT,`Invalid query. You cannot use more than one '${t.op.toString()}' filter.`):new I(_.INVALID_ARGUMENT,`Invalid query. You cannot use '${t.op.toString()}' filters with '${n.toString()}' filters.`)}function Kl(e,t){if(!(t instanceof Pl||t instanceof Fl))throw new I(_.INVALID_ARGUMENT,`Function ${e}() requires AppliableConstraints created with a call to 'where(...)', 'or(...)', or 'and(...)'.`)}class Ql{convertValue(e,t="none"){switch(It(e)){case 0:return null;case 1:return e.booleanValue;case 2:return ft(e.integerValue||e.doubleValue);case 3:return this.convertTimestamp(e.timestampValue);case 4:return this.convertServerTimestamp(e,t);case 5:return e.stringValue;case 6:return this.convertBytes(gt(e.bytesValue));case 7:return this.convertReference(e.referenceValue);case 8:return this.convertGeoPoint(e.geoPointValue);case 9:return this.convertArray(e.arrayValue,t);case 11:return this.convertObject(e.mapValue,t);case 10:return this.convertVectorValue(e.mapValue);default:throw v()}}convertObject(e,t){return this.convertObjectMap(e.fields,t)}convertObjectMap(e,t="none"){const n={};return Ze(e,((e,r)=>{n[e]=this.convertValue(r,t)})),n}convertVectorValue(e){var t,n,r;const i=null===(r=null===(n=null===(t=e.fields)||void 0===t?void 0:t.value.arrayValue)||void 0===n?void 0:n.values)||void 0===r?void 0:r.map((e=>ft(e.doubleValue)));return new rl(i)}convertGeoPoint(e){return new nl(ft(e.latitude),ft(e.longitude))}convertArray(e,t){return(e.values||[]).map((e=>this.convertValue(e,t)))}convertServerTimestamp(e,t){switch(t){case"previous":const n=mt(e);return null==n?null:this.convertValue(n,t);case"estimate":return this.convertTimestamp(yt(e));default:return null}}convertTimestamp(e){const t=dt(e);return new F(t.seconds,t.nanos)}convertDocumentKey(e,t){const n=B.fromString(e);w(ji(n));const r=new wt(n.get(1),n.get(3)),i=new $(n.popFirst(5));return r.isEqual(t)||p(`Document ${i} contains a document reference within a different database (${r.projectId}/${r.database}) which is not supported. It will be treated as a reference in the current database (${t.projectId}/${t.database}) instead.`),i}}function Hl(e,t,n){let r;return r=e?n&&(n.merge||n.mergeFields)?e.toFirestore(t,n):e.toFirestore(t):t,r}class Wl extends Ql{constructor(e){super(),this.firestore=e}convertBytes(e){return new Zu(e)}convertReference(e){const t=this.convertDocumentKey(e,this.firestore._databaseId);return new Bu(this.firestore,null,t)}}function Jl(){return new Xu("count")}class Xl{constructor(e,t){this.hasPendingWrites=e,this.fromCache=t}isEqual(e){return this.hasPendingWrites===e.hasPendingWrites&&this.fromCache===e.fromCache}}class Yl extends kl{constructor(e,t,n,r,i,s){super(e,t,n,r,s),this._firestore=e,this._firestoreImpl=e,this.metadata=i}exists(){return super.exists()}data(e={}){if(this._document){if(this._converter){const t=new Zl(this._firestore,this._userDataWriter,this._key,this._document,this.metadata,null);return this._converter.fromFirestore(t,e)}return this._userDataWriter.convertValue(this._document.data.value,e.serverTimestamps)}}get(e,t={}){if(this._document){const n=this._document.data.field(Ll("DocumentSnapshot.get",e));if(null!==n)return this._userDataWriter.convertValue(n,t.serverTimestamps)}}}class Zl extends Yl{data(e={}){return super.data(e)}}class eh{constructor(e,t,n,r){this._firestore=e,this._userDataWriter=t,this._snapshot=r,this.metadata=new Xl(r.hasPendingWrites,r.fromCache),this.query=n}get docs(){const e=[];return this.forEach((t=>e.push(t))),e}get size(){return this._snapshot.docs.size}get empty(){return 0===this.size}forEach(e,t){this._snapshot.docs.forEach((n=>{e.call(t,new Zl(this._firestore,this._userDataWriter,n.key,n,new Xl(this._snapshot.mutatedKeys.has(n.key),this._snapshot.fromCache),this.query.converter))}))}docChanges(e={}){const t=!!e.includeMetadataChanges;if(t&&this._snapshot.excludesMetadataChanges)throw new I(_.INVALID_ARGUMENT,"To include metadata changes with your document changes, you must also pass { includeMetadataChanges:true } to onSnapshot().");return this._cachedChanges&&this._cachedChangesIncludeMetadataChanges===t||(this._cachedChanges=function(e,t){if(e._snapshot.oldDocs.isEmpty()){let t=0;return e._snapshot.docChanges.map((n=>{const r=new Zl(e._firestore,e._userDataWriter,n.doc.key,n.doc,new Xl(e._snapshot.mutatedKeys.has(n.doc.key),e._snapshot.fromCache),e.query.converter);return n.doc,{type:"added",doc:r,oldIndex:-1,newIndex:t++}}))}{let n=e._snapshot.oldDocs;return e._snapshot.docChanges.filter((e=>t||3!==e.type)).map((t=>{const r=new Zl(e._firestore,e._userDataWriter,t.doc.key,t.doc,new Xl(e._snapshot.mutatedKeys.has(t.doc.key),e._snapshot.fromCache),e.query.converter);let i=-1,s=-1;return 0!==t.type&&(i=n.indexOf(t.doc.key),n=n.delete(t.doc.key)),1!==t.type&&(n=n.add(t.doc),s=n.indexOf(t.doc.key)),{type:th(t.type),doc:r,oldIndex:i,newIndex:s}}))}}(this,t),this._cachedChangesIncludeMetadataChanges=t),this._cachedChanges}}function th(e){switch(e){case 0:return"added";case 2:case 3:return"modified";case 1:return"removed";default:return v()}}class nh extends Ql{constructor(e){super(),this.firestore=e}convertBytes(e){return new Zu(e)}convertReference(e){const t=this.convertDocumentKey(e,this.firestore._databaseId);return new Bu(this.firestore,null,t)}}function rh(e,t){return function(e,t){const n=new E;return e.asyncQueue.enqueueAndForget((async()=>async function(e,t,n){const r=ru(e);try{const e=await function(e,t){const n=b(e),r=F.now(),i=t.reduce(((e,t)=>e.add(t.key)),nr());let s,o;return n.persistence.runTransaction("Locally write mutations","readwrite",(e=>{let a=Qn(),c=nr();return n.hs.getEntries(e,i).next((e=>{a=e,a.forEach(((e,t)=>{t.isValidDocument()||(c=c.add(e))}))})).next((()=>n.localDocuments.getOverlayedDocuments(e,a))).next((i=>{s=i;const o=[];for(const e of t){const t=Dr(e,s.get(e.key).overlayedDocument);null!=t&&o.push(new Nr(e.key,t,Kt(t.value.mapValue),Ir.exists(!0)))}return n.mutationQueue.addMutationBatch(e,r,o,t)})).next((t=>{o=t;const r=t.applyToLocalDocumentSet(s,c);return n.documentOverlayCache.saveOverlays(e,t.batchId,r)}))})).then((()=>({batchId:o.batchId,changes:Jn(s)})))}(r.localStore,t);r.sharedClientState.addPendingMutation(e.batchId),function(e,t,n){let r=e.qa[e.currentUser.toKey()];r||(r=new nt(M)),r=r.insert(t,n),e.qa[e.currentUser.toKey()]=r}(r,e.batchId,n),await Gc(r,e.changes),await ja(r.remoteStore)}catch(e){const t=nc(e,"Failed to persist write");n.reject(t)}}(await Iu(e),t,n))),n.promise}(Hu(e),t)}function ih(e,t,n){const r=n.docs.get(t._key),i=new nh(e);return new Yl(e,i,t._key,r,new Xl(n.hasPendingWrites,n.fromCache),t.converter)}function sh(e,t){const n=Mu(e.firestore,Qu),r=Hu(n),i=et(t,((e,t)=>new Br(t,e.aggregateType,e._internalFieldPath)));return function(e,t,n){const r=new E;return e.asyncQueue.enqueueAndForget((async()=>{try{const i=await Eu(e);r.resolve(async function(e,t,n){var r;const i=b(e),{request:s,lt:o,parent:a}=Li(i.serializer,Mn(t),n);i.connection.Co||delete s.parent;const c=(await i.ko("RunAggregationQuery",i.serializer.databaseId,a,s,1)).filter((e=>!!e.result));w(1===c.length);const u=null===(r=c[0].result)||void 0===r?void 0:r.aggregateFields;return Object.keys(u).reduce(((e,t)=>(e[o[t]]=u[t],e)),{})}(i,t,n))}catch(e){r.reject(e)}})),r.promise}(r,e._query,i).then((t=>function(e,t,n){const r=new nh(e);return new Yu(t,r,n)}(n,e,t)))}class oh{constructor(e){this.kind="memory",this._onlineComponentProvider=cu.provider,(null==e?void 0:e.garbageCollector)?this._offlineComponentProvider=e.garbageCollector._offlineComponentProvider:this._offlineComponentProvider={build:()=>new su(void 0)}}toJSON(){return{kind:this.kind}}}class ah{constructor(e){let t;this.kind="persistent",(null==e?void 0:e.tabManager)?(e.tabManager._initialize(e),t=e.tabManager):(t=dh(void 0),t._initialize(e)),this._onlineComponentProvider=t._onlineComponentProvider,this._offlineComponentProvider=t._offlineComponentProvider}toJSON(){return{kind:this.kind}}}class ch{constructor(){this.kind="memoryEager",this._offlineComponentProvider=iu.provider}toJSON(){return{kind:this.kind}}}class uh{constructor(e){this.kind="memoryLru",this._offlineComponentProvider={build:()=>new su(e)}}toJSON(){return{kind:this.kind}}}class lh{constructor(e){this.forceOwnership=e,this.kind="persistentSingleTab"}toJSON(){return{kind:this.kind}}_initialize(e){this._onlineComponentProvider=cu.provider,this._offlineComponentProvider={build:t=>new ou(t,null==e?void 0:e.cacheSizeBytes,this.forceOwnership)}}}class hh{constructor(){this.kind="PersistentMultipleTab"}toJSON(){return{kind:this.kind}}_initialize(e){this._onlineComponentProvider=cu.provider,this._offlineComponentProvider={build:t=>new au(t,null==e?void 0:e.cacheSizeBytes)}}}function dh(e){return new lh(null==e?void 0:e.forceOwnership)}const fh={maxAttempts:5};class gh{constructor(e,t){this._firestore=e,this._commitHandler=t,this._mutations=[],this._committed=!1,this._dataReader=ll(e)}set(e,t,n){this._verifyNotCommitted();const r=ph(e,this._firestore),i=Hl(r.converter,t,n),s=hl(this._dataReader,"WriteBatch.set",r._key,i,null!==r.converter,n);return this._mutations.push(s.toMutation(r._key,Ir.none())),this}update(e,t,n,...r){this._verifyNotCommitted();const i=ph(e,this._firestore);let s;return s="string"==typeof(t=o.getModularInstance(t))||t instanceof el?wl(this._dataReader,"WriteBatch.update",i._key,t,n,r):vl(this._dataReader,"WriteBatch.update",i._key,t),this._mutations.push(s.toMutation(i._key,Ir.exists(!0))),this}delete(e){this._verifyNotCommitted();const t=ph(e,this._firestore);return this._mutations=this._mutations.concat(new Rr(t._key,Ir.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 I(_.FAILED_PRECONDITION,"A write batch can no longer be used after commit() has been called.")}}function ph(e,t){if((e=o.getModularInstance(e)).firestore!==t)throw new I(_.INVALID_ARGUMENT,"Provided document reference is from a different Firestore instance.");return e}class mh extends class{constructor(e,t){this._firestore=e,this._transaction=t,this._dataReader=ll(e)}get(e){const t=ph(e,this._firestore),n=new Wl(this._firestore);return this._transaction.lookup([t._key]).then((e=>{if(!e||1!==e.length)return v();const r=e[0];if(r.isFoundDocument())return new kl(this._firestore,n,r.key,r,t.converter);if(r.isNoDocument())return new kl(this._firestore,n,t._key,null,t.converter);throw v()}))}set(e,t,n){const r=ph(e,this._firestore),i=Hl(r.converter,t,n),s=hl(this._dataReader,"Transaction.set",r._key,i,null!==r.converter,n);return this._transaction.set(r._key,s),this}update(e,t,n,...r){const i=ph(e,this._firestore);let s;return s="string"==typeof(t=o.getModularInstance(t))||t instanceof el?wl(this._dataReader,"Transaction.update",i._key,t,n,r):vl(this._dataReader,"Transaction.update",i._key,t),this._transaction.update(i._key,s),this}delete(e){const t=ph(e,this._firestore);return this._transaction.delete(t._key),this}}{constructor(e,t){super(e,t),this._firestore=e}get(e){const t=ph(e,this._firestore),n=new nh(this._firestore);return super.get(e).then((e=>new Yl(this._firestore,n,t._key,e._document,new Xl(!1,!1),t.converter)))}}function yh(e,t){if("string"!=typeof e[t])throw new I(_.INVALID_ARGUMENT,"Missing string value for: "+t);return e[t]}class vh{constructor(e){this._firestore=e,this.type="PersistentCacheIndexManager"}}function wh(e,t){(function(e,t){return e.asyncQueue.enqueue((async()=>function(e,t){b(e)._s.Hi=t}(await bu(e),t)))})(Hu(e._firestore),t).then((e=>g(`setting persistent cache index auto creation isEnabled=${t} succeeded`))).catch((e=>m(`setting persistent cache index auto creation isEnabled=${t} failed`,e)))}const bh=new WeakMap;class _h{constructor(){this.Gu=new Map}static get instance(){return Ih||(Ih=new _h,function(e){if(Kr)throw new Error("a TestingHooksSpi instance is already set");Kr=e}(Ih)),Ih}tt(e){this.Gu.forEach((t=>t(e)))}onExistenceFilterMismatch(e){const t=Symbol(),n=this.Gu;return n.set(t,e),()=>n.delete(t)}}let Ih=null;!function(e,t=!0){!function(e){h=e}(r.SDK_VERSION),r._registerComponent(new i.Component("firestore",((e,{instanceIdentifier:n,options:r})=>{const i=e.getProvider("app").getImmediate(),s=new Qu(new C(e.getProvider("auth-internal")),new N(e.getProvider("app-check-internal")),function(e,t){if(!Object.prototype.hasOwnProperty.apply(e.options,["projectId"]))throw new I(_.INVALID_ARGUMENT,'"projectId" not provided in firebase.initializeApp.');return new wt(e.options.projectId,t)}(i,n),i);return r=Object.assign({useFetchStreams:t},r),s._setSettings(r),s}),"PUBLIC").setMultipleInstances(!0)),r.registerVersion(u,"4.7.5",e),r.registerVersion(u,"4.7.5","cjs2017")}(),t.AbstractUserDataWriter=Ql,t.AggregateField=Xu,t.AggregateQuerySnapshot=Yu,t.Bytes=Zu,t.CACHE_SIZE_UNLIMITED=-1,t.CollectionReference=Uu,t.DocumentReference=Bu,t.DocumentSnapshot=Yl,t.FieldPath=el,t.FieldValue=tl,t.Firestore=Qu,t.FirestoreError=I,t.GeoPoint=nl,t.LoadBundleTask=Ku,t.PersistentCacheIndexManager=vh,t.Query=qu,t.QueryCompositeFilterConstraint=Fl,t.QueryConstraint=Rl,t.QueryDocumentSnapshot=Zl,t.QueryEndAtConstraint=Ul,t.QueryFieldFilterConstraint=Pl,t.QueryLimitConstraint=ql,t.QueryOrderByConstraint=Vl,t.QuerySnapshot=eh,t.QueryStartAtConstraint=Bl,t.SnapshotMetadata=Xl,t.Timestamp=F,t.Transaction=mh,t.VectorValue=rl,t.WriteBatch=gh,t._AutoId=O,t._ByteString=lt,t._DatabaseId=wt,t._DocumentKey=$,t._EmptyAppCheckTokenProvider=class{getToken(){return Promise.resolve(new k(""))}invalidateToken(){}start(e,t){}shutdown(){}},t._EmptyAuthCredentialsProvider=S,t._FieldPath=j,t._TestingHooks=class{constructor(){throw new Error("instances of this class should not be created")}static onExistenceFilterMismatch(e){return _h.instance.onExistenceFilterMismatch(e)}},t._cast=Mu,t._debugAssert=function(e,t){e||v()},t._internalAggregationQueryToProtoRunAggregationQueryRequest=function(e,t){var n;const r=et(t,((e,t)=>new Br(t,e.aggregateType,e._internalFieldPath))),i=null===(n=Hu(Mu(e.firestore,Qu))._onlineComponents)||void 0===n?void 0:n.datastore.serializer;return void 0===i?null:Li(i,Mn(e._query),r,!0).request},t._internalQueryToProtoQueryTarget=function(e){var t;const n=null===(t=Hu(Mu(e.firestore,Qu))._onlineComponents)||void 0===t?void 0:t.datastore.serializer;return void 0===n?null:Ni(n,On(e._query)).ct},t._isBase64Available=function(){return"undefined"!=typeof atob},t._logWarn=m,t._validateIsNotUsedTogether=ku,t.addDoc=function(e,t){const n=Mu(e.firestore,Qu),r=ju(e),i=Hl(e.converter,t);return rh(n,[hl(ll(e.firestore),"addDoc",r._key,i,null!==e.converter,{}).toMutation(r._key,Ir.exists(!1))]).then((()=>r))},t.aggregateFieldEqual=function(e,t){var n,r;return e instanceof Xu&&t instanceof Xu&&e.aggregateType===t.aggregateType&&(null===(n=e._internalFieldPath)||void 0===n?void 0:n.canonicalString())===(null===(r=t._internalFieldPath)||void 0===r?void 0:r.canonicalString())},t.aggregateQuerySnapshotEqual=function(e,t){return $u(e.query,t.query)&&o.deepEqual(e.data(),t.data())},t.and=function(...e){return e.forEach((e=>Kl("and",e))),Fl._create("and",e)},t.arrayRemove=function(...e){return new ml("arrayRemove",e)},t.arrayUnion=function(...e){return new pl("arrayUnion",e)},t.average=function(e){return new Xu("avg",Sl("average",e))},t.clearIndexedDbPersistence=function(e){if(e._initialized&&!e._terminated)throw new I(_.FAILED_PRECONDITION,"Persistence can only be cleared before a Firestore instance is initialized or after it is terminated.");const t=new E;return e._queue.enqueueAndForgetEvenWhileRestricted((async()=>{try{await async function(e){if(!oe.p())return Promise.resolve();const t=e+"main";await oe.delete(t)}(Ro(e._databaseId,e._persistenceKey)),t.resolve()}catch(e){t.reject(e)}})),t.promise},t.collection=function(e,t,...n){if(e=o.getModularInstance(e),Au("collection","path",t),e instanceof Fu){const r=B.fromString(t,...n);return Lu(r),new Uu(e,null,r)}{if(!(e instanceof Bu||e instanceof Uu))throw new I(_.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");const r=e._path.child(B.fromString(t,...n));return Lu(r),new Uu(e.firestore,null,r)}},t.collectionGroup=function(e,t){if(e=Mu(e,Fu),Au("collectionGroup","collection id",t),t.indexOf("/")>=0)throw new I(_.INVALID_ARGUMENT,`Invalid collection ID '${t}' passed to function collectionGroup(). Collection IDs must not contain '/'.`);return new qu(e,null,function(e){return new Cn(B.emptyPath(),e)}(t))},t.connectFirestoreEmulator=Vu,t.count=Jl,t.deleteAllPersistentCacheIndexes=function(e){(function(e){return e.asyncQueue.enqueue((async()=>function(e){const t=b(e),n=t.indexManager;return t.persistence.runTransaction("Delete All Indexes","readwrite",(e=>n.deleteAllFieldIndexes(e)))}(await bu(e))))})(Hu(e._firestore)).then((e=>g("deleting all persistent cache indexes succeeded"))).catch((e=>m("deleting all persistent cache indexes failed",e)))},t.deleteDoc=function(e){return rh(Mu(e.firestore,Qu),[new Rr(e._key,Ir.none())])},t.deleteField=function(){return new dl("deleteField")},t.disableNetwork=function(e){return function(e){return e.asyncQueue.enqueue((async()=>{const t=await wu(e),n=await _u(e);return t.setNetworkEnabled(!1),async function(e){const t=b(e);t.k_.add(0),await Ca(t),t.K_.set("Offline")}(n)}))}(Hu(e=Mu(e,Qu)))},t.disablePersistentCacheIndexAutoCreation=function(e){wh(e,!1)},t.doc=ju,t.documentId=function(){return new el("__name__")},t.enableIndexedDbPersistence=function(e,t){m("enableIndexedDbPersistence() will be deprecated in the future, you can use `FirestoreSettings.cache` instead.");const n=e._freezeSettings();return Ju(e,cu.provider,{build:e=>new ou(e,n.cacheSizeBytes,null==t?void 0:t.forceOwnership)}),Promise.resolve()},t.enableMultiTabIndexedDbPersistence=async function(e){m("enableMultiTabIndexedDbPersistence() will be deprecated in the future, you can use `FirestoreSettings.cache` instead.");const t=e._freezeSettings();Ju(e,cu.provider,{build:e=>new au(e,t.cacheSizeBytes)})},t.enableNetwork=function(e){return function(e){return e.asyncQueue.enqueue((async()=>{const t=await wu(e),n=await _u(e);return t.setNetworkEnabled(!0),function(e){const t=b(e);return t.k_.delete(0),xa(t)}(n)}))}(Hu(e=Mu(e,Qu)))},t.enablePersistentCacheIndexAutoCreation=function(e){wh(e,!0)},t.endAt=function(...e){return Ul._create("endAt",e,!0)},t.endBefore=function(...e){return Ul._create("endBefore",e,!1)},t.ensureFirestoreConfigured=Hu,t.executeWrite=rh,t.getAggregateFromServer=sh,t.getCountFromServer=function(e){return sh(e,{count:Jl()})},t.getDoc=function(e){e=Mu(e,Bu);const t=Mu(e.firestore,Qu);return Su(Hu(t),e._key).then((n=>ih(t,e,n)))},t.getDocFromCache=function(e){e=Mu(e,Bu);const t=Mu(e.firestore,Qu),n=Hu(t),r=new nh(t);return function(e,t){const n=new E;return e.asyncQueue.enqueueAndForget((async()=>async function(e,t,n){try{const r=await function(e,t){const n=b(e);return n.persistence.runTransaction("read document","readonly",(e=>n.localDocuments.getDocument(e,t)))}(e,t);r.isFoundDocument()?n.resolve(r):r.isNoDocument()?n.resolve(null):n.reject(new I(_.UNAVAILABLE,"Failed to get document from cache. (However, this document may exist on the server. Run again without setting 'source' in the GetOptions to attempt to retrieve the document from the server.)"))}catch(e){const r=nc(e,`Failed to get document '${t} from cache`);n.reject(r)}}(await bu(e),t,n))),n.promise}(n,e._key).then((n=>new Yl(t,r,e._key,n,new Xl(null!==n&&n.hasLocalMutations,!0),e.converter)))},t.getDocFromServer=function(e){e=Mu(e,Bu);const t=Mu(e.firestore,Qu);return Su(Hu(t),e._key,{source:"server"}).then((n=>ih(t,e,n)))},t.getDocs=function(e){e=Mu(e,qu);const t=Mu(e.firestore,Qu),n=Hu(t),r=new nh(t);return Ol(e._query),xu(n,e._query).then((n=>new eh(t,r,e,n)))},t.getDocsFromCache=function(e){e=Mu(e,qu);const t=Mu(e.firestore,Qu),n=Hu(t),r=new nh(t);return function(e,t){const n=new E;return e.asyncQueue.enqueueAndForget((async()=>async function(e,t,n){try{const r=await Qo(e,t,!0),i=new Ec(t,r.ds),s=i.ga(r.documents),o=i.applyChanges(s,!1);n.resolve(o.snapshot)}catch(e){const r=nc(e,`Failed to execute query '${t} against cache`);n.reject(r)}}(await bu(e),t,n))),n.promise}(n,e._query).then((n=>new eh(t,r,e,n)))},t.getDocsFromServer=function(e){e=Mu(e,qu);const t=Mu(e.firestore,Qu),n=Hu(t),r=new nh(t);return xu(n,e._query,{source:"server"}).then((n=>new eh(t,r,e,n)))},t.getFirestore=function(e,t){const n="object"==typeof e?e:r.getApp(),i="string"==typeof e?e:t||"(default)",s=r._getProvider(n,"firestore").getImmediate({identifier:i});if(!s._initialized){const e=o.getDefaultEmulatorHostnameAndPort("firestore");e&&Vu(s,...e)}return s},t.getPersistentCacheIndexManager=function(e){var t;e=Mu(e,Qu);const n=bh.get(e);if(n)return n;if("persistent"!==(null===(t=Hu(e)._uninitializedComponentsProvider)||void 0===t?void 0:t._offline.kind))return null;const r=new vh(e);return bh.set(e,r),r},t.increment=function(e){return new yl("increment",e)},t.initializeFirestore=function(e,t,n){n||(n="(default)");const i=r._getProvider(e,"firestore");if(i.isInitialized(n)){const e=i.getImmediate({identifier:n}),r=i.getOptions(n);if(o.deepEqual(r,t))return e;throw new I(_.FAILED_PRECONDITION,"initializeFirestore() has already been called with different options. To avoid this error, call initializeFirestore() with the same options as when it was originally called, or call getFirestore() to return the already initialized instance.")}if(void 0!==t.cacheSizeBytes&&void 0!==t.localCache)throw new I(_.INVALID_ARGUMENT,"cache and cacheSizeBytes cannot be specified at the same time as cacheSizeBytes willbe deprecated. Instead, specify the cache size in the cache object");if(void 0!==t.cacheSizeBytes&&-1!==t.cacheSizeBytes&&t.cacheSizeBytes<1048576)throw new I(_.INVALID_ARGUMENT,"cacheSizeBytes must be at least 1048576");return i.initialize({options:t,instanceIdentifier:n})},t.limit=function(e){return Ru("limit",e),ql._create("limit",e,"F")},t.limitToLast=function(e){return Ru("limitToLast",e),ql._create("limitToLast",e,"L")},t.loadBundle=function(e,t){const n=Hu(e=Mu(e,Qu)),r=new Ku;return function(e,t,n,r){const i=function(e,t){let n;return n="string"==typeof e?Qr().encode(e):e,function(e,t){return new hu(e,t)}(function(e,t){if(e instanceof Uint8Array)return uu(e,t);if(e instanceof ArrayBuffer)return uu(new Uint8Array(e),t);if(e instanceof ReadableStream)return e.getReader();throw new Error("Source of `toByteStreamReader` has to be a ArrayBuffer or ReadableStream")}(n),t)}(n,va(t));e.asyncQueue.enqueueAndForget((async()=>{!function(e,t,n){const r=b(e);(async function(e,t,n){try{const r=await t.getMetadata();if(await function(e,t){const n=b(e),r=mi(t.createTime);return n.persistence.runTransaction("hasNewerBundle","readonly",(e=>n.jr.getBundleMetadata(e,t.id))).then((e=>!!e&&e.createTime.compareTo(r)>=0))}(e.localStore,r))return await t.close(),n._completeWith(function(e){return{taskState:"Success",documentsLoaded:e.totalDocuments,bytesLoaded:e.totalBytes,totalDocuments:e.totalDocuments,totalBytes:e.totalBytes}}(r)),Promise.resolve(new Set);n._updateProgress(bc(r));const i=new wc(r,e.localStore,t.serializer);let s=await t.Ga();for(;s;){const e=await i.Pa(s);e&&n._updateProgress(e),s=await t.Ga()}const o=await i.complete();return await Gc(e,o.Ea,void 0),await function(e,t){const n=b(e);return n.persistence.runTransaction("Save bundle","readwrite",(e=>n.jr.saveBundleMetadata(e,t)))}(e.localStore,r),n._completeWith(o.progress),Promise.resolve(o.Ia)}catch(e){return m("SyncEngine",`Loading bundle failed with ${e}`),n._failWith(e),Promise.resolve(new Set)}})(r,t,n).then((e=>{r.sharedClientState.notifyBundleLoaded(e)}))}(await Iu(e),i,r)}))}(n,e._databaseId,t,r),r},t.memoryEagerGarbageCollector=function(){return new ch},t.memoryLocalCache=function(e){return new oh(e)},t.memoryLruGarbageCollector=function(e){return new uh(null==e?void 0:e.cacheSizeBytes)},t.namedQuery=function(e,t){return function(e,t){return e.asyncQueue.enqueue((async()=>function(e,t){const n=b(e);return n.persistence.runTransaction("Get named query","readonly",(e=>n.jr.getNamedQuery(e,t)))}(await bu(e),t)))}(Hu(e=Mu(e,Qu)),t).then((t=>t?new qu(e,null,t.query):null))},t.onSnapshot=function(e,...t){var n,r,i;e=o.getModularInstance(e);let s={includeMetadataChanges:!1,source:"default"},a=0;"object"!=typeof t[a]||Gu(t[a])||(s=t[a],a++);const c={includeMetadataChanges:s.includeMetadataChanges,source:s.source};if(Gu(t[a])){const e=t[a];t[a]=null===(n=e.next)||void 0===n?void 0:n.bind(e),t[a+1]=null===(r=e.error)||void 0===r?void 0:r.bind(e),t[a+2]=null===(i=e.complete)||void 0===i?void 0:i.bind(e)}let u,l,h;if(e instanceof Bu)l=Mu(e.firestore,Qu),h=An(e._key.path),u={next:n=>{t[a]&&t[a](ih(l,e,n))},error:t[a+1],complete:t[a+2]};else{const n=Mu(e,qu);l=Mu(n.firestore,Qu),h=n._query;const r=new nh(l);u={next:e=>{t[a]&&t[a](new eh(l,r,n,e))},error:t[a+1],complete:t[a+2]},Ol(e._query)}return function(e,t,n,r){const i=new lu(r),s=new mc(t,i,n);return e.asyncQueue.enqueueAndForget((async()=>uc(await Tu(e),s))),()=>{i.eu(),e.asyncQueue.enqueueAndForget((async()=>lc(await Tu(e),s)))}}(Hu(l),h,c,u)},t.onSnapshotsInSync=function(e,t){return function(e,t){const n=new lu(t);return e.asyncQueue.enqueueAndForget((async()=>function(e,t){b(e).X_.add(t),t.next()}(await Tu(e),n))),()=>{n.eu(),e.asyncQueue.enqueueAndForget((async()=>function(e,t){b(e).X_.delete(t)}(await Tu(e),n)))}}(Hu(e=Mu(e,Qu)),Gu(t)?t:{next:t})},t.or=function(...e){return e.forEach((e=>Kl("or",e))),Fl._create("or",e)},t.orderBy=function(e,t="asc"){const n=t,r=Ll("orderBy",e);return Vl._create(r,n)},t.persistentLocalCache=function(e){return new ah(e)},t.persistentMultipleTabManager=function(){return new hh},t.persistentSingleTabManager=dh,t.query=function(e,t,...n){let r=[];t instanceof Ml&&r.push(t),r=r.concat(n),function(e){const t=e.filter((e=>e instanceof Fl)).length,n=e.filter((e=>e instanceof Pl)).length;if(t>1||t>0&&n>0)throw new I(_.INVALID_ARGUMENT,"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(...)))`.")}(r);for(const t of r)e=t._apply(e);return e},t.queryEqual=$u,t.refEqual=function(e,t){return e=o.getModularInstance(e),t=o.getModularInstance(t),(e instanceof Bu||e instanceof Uu)&&(t instanceof Bu||t instanceof Uu)&&e.firestore===t.firestore&&e.path===t.path&&e.converter===t.converter},t.runTransaction=function(e,t,n){e=Mu(e,Qu);const r=Object.assign(Object.assign({},fh),n);return function(e){if(e.maxAttempts<1)throw new I(_.INVALID_ARGUMENT,"Max attempts must be at least 1")}(r),function(e,t,n){const r=new E;return e.asyncQueue.enqueueAndForget((async()=>{const i=await Eu(e);new fu(e.asyncQueue,i,n,t,r).cu()})),r.promise}(Hu(e),(n=>t(new mh(e,n))),r)},t.serverTimestamp=function(){return new gl("serverTimestamp")},t.setDoc=function(e,t,n){e=Mu(e,Bu);const r=Mu(e.firestore,Qu),i=Hl(e.converter,t,n);return rh(r,[hl(ll(r),"setDoc",e._key,i,null!==e.converter,n).toMutation(e._key,Ir.none())])},t.setIndexConfiguration=function(e,t){const n=Hu(e=Mu(e,Qu));if(!n._uninitializedComponentsProvider||"memory"===n._uninitializedComponentsProvider._offline.kind)return m("Cannot enable indexes when persistence is disabled"),Promise.resolve();const r=function(e){const t="string"==typeof e?function(e){try{return JSON.parse(e)}catch(e){throw new I(_.INVALID_ARGUMENT,"Failed to parse JSON: "+(null==e?void 0:e.message))}}(e):e,n=[];if(Array.isArray(t.indexes))for(const e of t.indexes){const t=yh(e,"collectionGroup"),r=[];if(Array.isArray(e.fields))for(const t of e.fields){const e=Cl("setIndexConfiguration",yh(t,"fieldPath"));"CONTAINS"===t.arrayConfig?r.push(new H(e,2)):"ASCENDING"===t.order?r.push(new H(e,0)):"DESCENDING"===t.order&&r.push(new H(e,1))}n.push(new z(z.UNKNOWN_ID,t,r,J.empty()))}return n}(t);return function(e,t){return e.asyncQueue.enqueue((async()=>async function(e,t){const n=b(e),r=n.indexManager,i=[];return n.persistence.runTransaction("Configure indexes","readwrite",(e=>r.getFieldIndexes(e).next((n=>function(e,t,n,r,i){e=[...e],t=[...t],e.sort(n),t.sort(n);const s=e.length,o=t.length;let a=0,c=0;for(;a<o&&c<s;){const s=n(e[c],t[a]);s<0?i(e[c++]):s>0?r(t[a++]):(a++,c++)}for(;a<o;)r(t[a++]);for(;c<s;)i(e[c++])}(n,t,Q,(t=>{i.push(r.addFieldIndex(e,t))}),(t=>{i.push(r.deleteFieldIndex(e,t))})))).next((()=>ie.waitFor(i)))))}(await bu(e),t)))}(n,r)},t.setLogLevel=function(e){d.setLogLevel(e)},t.snapshotEqual=function(e,t){return e instanceof Yl&&t instanceof Yl?e._firestore===t._firestore&&e._key.isEqual(t._key)&&(null===e._document?null===t._document:e._document.isEqual(t._document))&&e._converter===t._converter:e instanceof eh&&t instanceof eh&&e._firestore===t._firestore&&$u(e.query,t.query)&&e.metadata.isEqual(t.metadata)&&e._snapshot.isEqual(t._snapshot)},t.startAfter=function(...e){return Bl._create("startAfter",e,!1)},t.startAt=function(...e){return Bl._create("startAt",e,!0)},t.sum=function(e){return new Xu("sum",Sl("sum",e))},t.terminate=function(e){return r._removeServiceInstance(e.app,"firestore",e._databaseId.database),e._delete()},t.updateDoc=function(e,t,n,...r){e=Mu(e,Bu);const i=Mu(e.firestore,Qu),s=ll(i);let a;return a="string"==typeof(t=o.getModularInstance(t))||t instanceof el?wl(s,"updateDoc",e._key,t,n,r):vl(s,"updateDoc",e._key,t),rh(i,[a.toMutation(e._key,Ir.exists(!0))])},t.vector=function(e){return new rl(e)},t.waitForPendingWrites=function(e){return function(e){const t=new E;return e.asyncQueue.enqueueAndForget((async()=>async function(e,t){const n=b(e);Ma(n.remoteStore)||g("SyncEngine","The network is disabled. The task returned by 'awaitPendingWrites()' will not complete until the network is enabled.");try{const e=await function(e){const t=b(e);return t.persistence.runTransaction("Get highest unacknowledged batch id","readonly",(e=>t.mutationQueue.getHighestUnacknowledgedBatchId(e)))}(n.localStore);if(-1===e)return void t.resolve();const r=n.Qa.get(e)||[];r.push(t),n.Qa.set(e,r)}catch(e){const n=nc(e,"Initialization of waitForPendingWrites() operation failed");t.reject(n)}}(await Iu(e),t))),t.promise}(Hu(e=Mu(e,Qu)))},t.where=function(e,t,n){const r=t,i=Ll("where",e);return Pl._create(i,r,n)},t.writeBatch=function(e){return Hu(e=Mu(e,Qu)),new gh(e,(t=>rh(e,t)))}},249:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(199),i=n(336),s=n(319);function o(e,t){const n={};for(const r in e)e.hasOwnProperty(r)&&(n[r]=t(e[r]));return n}function a(e){if(null==e)return null;if(e instanceof Number&&(e=e.valueOf()),"number"==typeof e&&isFinite(e))return e;if(!0===e||!1===e)return e;if("[object String]"===Object.prototype.toString.call(e))return e;if(e instanceof Date)return e.toISOString();if(Array.isArray(e))return e.map((e=>a(e)));if("function"==typeof e||"object"==typeof e)return o(e,(e=>a(e)));throw new Error("Data cannot be encoded in JSON: "+e)}function c(e){if(null==e)return e;if(e["@type"])switch(e["@type"]){case"type.googleapis.com/google.protobuf.Int64Value":case"type.googleapis.com/google.protobuf.UInt64Value":{const t=Number(e.value);if(isNaN(t))throw new Error("Data cannot be decoded from JSON: "+e);return t}default:throw new Error("Data cannot be decoded from JSON: "+e)}return Array.isArray(e)?e.map((e=>c(e))):"function"==typeof e||"object"==typeof e?o(e,(e=>c(e))):e}const u="functions",l={OK:"ok",CANCELLED:"cancelled",UNKNOWN:"unknown",INVALID_ARGUMENT:"invalid-argument",DEADLINE_EXCEEDED:"deadline-exceeded",NOT_FOUND:"not-found",ALREADY_EXISTS:"already-exists",PERMISSION_DENIED:"permission-denied",UNAUTHENTICATED:"unauthenticated",RESOURCE_EXHAUSTED:"resource-exhausted",FAILED_PRECONDITION:"failed-precondition",ABORTED:"aborted",OUT_OF_RANGE:"out-of-range",UNIMPLEMENTED:"unimplemented",INTERNAL:"internal",UNAVAILABLE:"unavailable",DATA_LOSS:"data-loss"};class h extends i.FirebaseError{constructor(e,t,n){super(`${u}/${e}`,t||""),this.details=n,Object.setPrototypeOf(this,h.prototype)}}function d(e,t){let n,r=function(e){if(e>=200&&e<300)return"ok";switch(e){case 0:case 500:return"internal";case 400:return"invalid-argument";case 401:return"unauthenticated";case 403:return"permission-denied";case 404:return"not-found";case 409:return"aborted";case 429:return"resource-exhausted";case 499:return"cancelled";case 501:return"unimplemented";case 503:return"unavailable";case 504:return"deadline-exceeded"}return"unknown"}(e),i=r;try{const e=t&&t.error;if(e){const t=e.status;if("string"==typeof t){if(!l[t])return new h("internal","internal");r=l[t],i=t}const s=e.message;"string"==typeof s&&(i=s),n=e.details,void 0!==n&&(n=c(n))}}catch(e){}return"ok"===r?null:new h(r,i,n)}class f{constructor(e,t,n){this.auth=null,this.messaging=null,this.appCheck=null,this.auth=e.getImmediate({optional:!0}),this.messaging=t.getImmediate({optional:!0}),this.auth||e.get().then((e=>this.auth=e),(()=>{})),this.messaging||t.get().then((e=>this.messaging=e),(()=>{})),this.appCheck||n.get().then((e=>this.appCheck=e),(()=>{}))}async getAuthToken(){if(this.auth)try{const e=await this.auth.getToken();return null==e?void 0:e.accessToken}catch(e){return}}async getMessagingToken(){if(this.messaging&&"Notification"in self&&"granted"===Notification.permission)try{return await this.messaging.getToken()}catch(e){return}}async getAppCheckToken(e){if(this.appCheck){const t=e?await this.appCheck.getLimitedUseToken():await this.appCheck.getToken();return t.error?null:t.token}return null}async getContext(e){return{authToken:await this.getAuthToken(),messagingToken:await this.getMessagingToken(),appCheckToken:await this.getAppCheckToken(e)}}}const g="us-central1",p=/^data: (.*?)(?:\n|$)/;class m{constructor(e,t,n,r,i=g,s=(...e)=>fetch(...e)){this.app=e,this.fetchImpl=s,this.emulatorOrigin=null,this.contextProvider=new f(t,n,r),this.cancelAllRequests=new Promise((e=>{this.deleteService=()=>Promise.resolve(e())}));try{const e=new URL(i);this.customDomain=e.origin+("/"===e.pathname?"":e.pathname),this.region=g}catch(e){this.customDomain=null,this.region=i}}_delete(){return this.deleteService()}_url(e){const t=this.app.options.projectId;return null!==this.emulatorOrigin?`${this.emulatorOrigin}/${t}/${this.region}/${e}`:null!==this.customDomain?`${this.customDomain}/${e}`:`https://${this.region}-${t}.cloudfunctions.net/${e}`}}async function y(e,t,n,r){let i;n["Content-Type"]="application/json";try{i=await r(e,{method:"POST",body:JSON.stringify(t),headers:n})}catch(e){return{status:0,json:null}}let s=null;try{s=await i.json()}catch(e){}return{status:i.status,json:s}}async function v(e,t){const n={},r=await e.contextProvider.getContext(t.limitedUseAppCheckTokens);return r.authToken&&(n.Authorization="Bearer "+r.authToken),r.messagingToken&&(n["Firebase-Instance-ID-Token"]=r.messagingToken),null!==r.appCheckToken&&(n["X-Firebase-AppCheck"]=r.appCheckToken),n}async function w(e,t,n,r){const i={data:n=a(n)},s=await v(e,r),o=function(e){let t=null;return{promise:new Promise(((n,r)=>{t=setTimeout((()=>{r(new h("deadline-exceeded","deadline-exceeded"))}),e)})),cancel:()=>{t&&clearTimeout(t)}}}(r.timeout||7e4),u=await Promise.race([y(t,i,s,e.fetchImpl),o.promise,e.cancelAllRequests]);if(o.cancel(),!u)throw new h("cancelled","Firebase Functions instance was deleted.");const l=d(u.status,u.json);if(l)throw l;if(!u.json)throw new h("internal","Response is not valid JSON object.");let f=u.json.data;if(void 0===f&&(f=u.json.result),void 0===f)throw new h("internal","Response is missing data field.");return{data:c(f)}}async function b(e,t,n,r){var i;const s={data:n=a(n)},o=await v(e,r);let u,l,f;o["Content-Type"]="application/json",o.Accept="text/event-stream";try{u=await e.fetchImpl(t,{method:"POST",body:JSON.stringify(s),headers:o,signal:null==r?void 0:r.signal})}catch(e){if(e instanceof Error&&"AbortError"===e.name){const e=new h("cancelled","Request was cancelled.");return{data:Promise.reject(e),stream:{[Symbol.asyncIterator]:()=>({next:()=>Promise.reject(e)})}}}const t=d(0,null);return{data:Promise.reject(t),stream:{[Symbol.asyncIterator]:()=>({next:()=>Promise.reject(t)})}}}const g=new Promise(((e,t)=>{l=e,f=t}));null===(i=null==r?void 0:r.signal)||void 0===i||i.addEventListener("abort",(()=>{const e=new h("cancelled","Request was cancelled.");f(e)}));const m=function(e,t,n,r){const i=(e,r)=>{const i=e.match(p);if(!i)return;const s=i[1];try{const e=JSON.parse(s);if("result"in e)return void t(c(e.result));if("message"in e)return void r.enqueue(c(e.message));if("error"in e){const t=d(0,e);return r.error(t),void n(t)}}catch(e){if(e instanceof h)return r.error(e),void n(e)}},s=new TextDecoder;return new ReadableStream({start(t){let o="";return async function a(){if(null==r?void 0:r.aborted){const e=new h("cancelled","Request was cancelled");return t.error(e),n(e),Promise.resolve()}try{const{value:c,done:u}=await e.read();if(u)return o.trim()&&i(o.trim(),t),void t.close();if(null==r?void 0:r.aborted){const r=new h("cancelled","Request was cancelled");return t.error(r),n(r),void await e.cancel()}o+=s.decode(c,{stream:!0});const l=o.split("\n");o=l.pop()||"";for(const e of l)e.trim()&&i(e.trim(),t);return a()}catch(e){const r=e instanceof h?e:d(0,null);t.error(r),n(r)}}()},cancel:()=>e.cancel()})}(u.body.getReader(),l,f,null==r?void 0:r.signal);return{stream:{[Symbol.asyncIterator](){const e=m.getReader();return{async next(){const{value:t,done:n}=await e.read();return{value:t,done:n}},return:async()=>(await e.cancel(),{done:!0,value:void 0})}}},data:g}}const _="@firebase/functions",I="0.12.0";function E(e,t,n){!function(e,t,n){e.emulatorOrigin=`http://${t}:${n}`}(i.getModularInstance(e),t,n)}r._registerComponent(new s.Component(u,((e,{instanceIdentifier:t})=>{const n=e.getProvider("app").getImmediate(),r=e.getProvider("auth-internal"),i=e.getProvider("messaging-internal"),s=e.getProvider("app-check-internal");return new m(n,r,i,s,t)}),"PUBLIC").setMultipleInstances(!0)),r.registerVersion(_,I,undefined),r.registerVersion(_,I,"cjs2017"),t.FunctionsError=h,t.connectFunctionsEmulator=E,t.getFunctions=function(e=r.getApp(),t=g){const n=r._getProvider(i.getModularInstance(e),u).getImmediate({identifier:t}),s=i.getDefaultEmulatorHostnameAndPort("functions");return s&&E(n,...s),n},t.httpsCallable=function(e,t,n){return function(e,t,n){const r=r=>function(e,t,n,r){const i=e._url(t);return w(e,i,n,r)}(e,t,r,n||{});return r.stream=(n,r)=>function(e,t,n,r){const i=e._url(t);return b(e,i,n,r||{})}(e,t,n,r),r}(i.getModularInstance(e),t,n)},t.httpsCallableFromURL=function(e,t,n){return function(e,t,n){const r=r=>w(e,t,r,n||{});return r.stream=(n,r)=>b(e,t,n,r||{}),r}(i.getModularInstance(e),t,n)}},844:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const n=[];var r;t.LogLevel=void 0,(r=t.LogLevel||(t.LogLevel={}))[r.DEBUG=0]="DEBUG",r[r.VERBOSE=1]="VERBOSE",r[r.INFO=2]="INFO",r[r.WARN=3]="WARN",r[r.ERROR=4]="ERROR",r[r.SILENT=5]="SILENT";const i={debug:t.LogLevel.DEBUG,verbose:t.LogLevel.VERBOSE,info:t.LogLevel.INFO,warn:t.LogLevel.WARN,error:t.LogLevel.ERROR,silent:t.LogLevel.SILENT},s=t.LogLevel.INFO,o={[t.LogLevel.DEBUG]:"log",[t.LogLevel.VERBOSE]:"log",[t.LogLevel.INFO]:"info",[t.LogLevel.WARN]:"warn",[t.LogLevel.ERROR]:"error"},a=(e,t,...n)=>{if(t<e.logLevel)return;const r=(new Date).toISOString(),i=o[t];if(!i)throw new Error(`Attempted to log a message with an invalid logType (value: ${t})`);console[i](`[${r}] ${e.name}:`,...n)};t.Logger=class{constructor(e){this.name=e,this._logLevel=s,this._logHandler=a,this._userLogHandler=null,n.push(this)}get logLevel(){return this._logLevel}set logLevel(e){if(!(e in t.LogLevel))throw new TypeError(`Invalid value "${e}" assigned to \`logLevel\``);this._logLevel=e}setLogLevel(e){this._logLevel="string"==typeof e?i[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,t.LogLevel.DEBUG,...e),this._logHandler(this,t.LogLevel.DEBUG,...e)}log(...e){this._userLogHandler&&this._userLogHandler(this,t.LogLevel.VERBOSE,...e),this._logHandler(this,t.LogLevel.VERBOSE,...e)}info(...e){this._userLogHandler&&this._userLogHandler(this,t.LogLevel.INFO,...e),this._logHandler(this,t.LogLevel.INFO,...e)}warn(...e){this._userLogHandler&&this._userLogHandler(this,t.LogLevel.WARN,...e),this._logHandler(this,t.LogLevel.WARN,...e)}error(...e){this._userLogHandler&&this._userLogHandler(this,t.LogLevel.ERROR,...e),this._logHandler(this,t.LogLevel.ERROR,...e)}},t.setLogLevel=function(e){n.forEach((t=>{t.setLogLevel(e)}))},t.setUserLogHandler=function(e,r){for(const s of n){let n=null;r&&r.level&&(n=i[r.level]),s.userLogHandler=null===e?null:(r,i,...s)=>{const o=s.map((e=>{if(null==e)return null;if("string"==typeof e)return e;if("number"==typeof e||"boolean"==typeof e)return e.toString();if(e instanceof Error)return e.message;try{return JSON.stringify(e)}catch(e){return null}})).filter((e=>e)).join(" ");i>=(null!=n?n:r.logLevel)&&e({level:t.LogLevel[i].toLowerCase(),message:o,args:s,type:r.name})}}}},336:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const r={NODE_CLIENT:!1,NODE_ADMIN:!1,SDK_VERSION:"${JSCORE_VERSION}"},i=function(e,t){if(!e)throw s(t)},s=function(e){return new Error("Firebase Database ("+r.SDK_VERSION+") INTERNAL ASSERT FAILED: "+e)},o=function(e){const t=[];let n=0;for(let r=0;r<e.length;r++){let i=e.charCodeAt(r);i<128?t[n++]=i:i<2048?(t[n++]=i>>6|192,t[n++]=63&i|128):55296==(64512&i)&&r+1<e.length&&56320==(64512&e.charCodeAt(r+1))?(i=65536+((1023&i)<<10)+(1023&e.charCodeAt(++r)),t[n++]=i>>18|240,t[n++]=i>>12&63|128,t[n++]=i>>6&63|128,t[n++]=63&i|128):(t[n++]=i>>12|224,t[n++]=i>>6&63|128,t[n++]=63&i|128)}return t},a={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,t){if(!Array.isArray(e))throw Error("encodeByteArray takes an array as a parameter");this.init_();const n=t?this.byteToCharMapWebSafe_:this.byteToCharMap_,r=[];for(let t=0;t<e.length;t+=3){const i=e[t],s=t+1<e.length,o=s?e[t+1]:0,a=t+2<e.length,c=a?e[t+2]:0,u=i>>2,l=(3&i)<<4|o>>4;let h=(15&o)<<2|c>>6,d=63&c;a||(d=64,s||(h=64)),r.push(n[u],n[l],n[h],n[d])}return r.join("")},encodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?btoa(e):this.encodeByteArray(o(e),t)},decodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?atob(e):function(e){const t=[];let n=0,r=0;for(;n<e.length;){const i=e[n++];if(i<128)t[r++]=String.fromCharCode(i);else if(i>191&&i<224){const s=e[n++];t[r++]=String.fromCharCode((31&i)<<6|63&s)}else if(i>239&&i<365){const s=((7&i)<<18|(63&e[n++])<<12|(63&e[n++])<<6|63&e[n++])-65536;t[r++]=String.fromCharCode(55296+(s>>10)),t[r++]=String.fromCharCode(56320+(1023&s))}else{const s=e[n++],o=e[n++];t[r++]=String.fromCharCode((15&i)<<12|(63&s)<<6|63&o)}}return t.join("")}(this.decodeStringToByteArray(e,t))},decodeStringToByteArray(e,t){this.init_();const n=t?this.charToByteMapWebSafe_:this.charToByteMap_,r=[];for(let t=0;t<e.length;){const i=n[e.charAt(t++)],s=t<e.length?n[e.charAt(t)]:0;++t;const o=t<e.length?n[e.charAt(t)]:64;++t;const a=t<e.length?n[e.charAt(t)]:64;if(++t,null==i||null==s||null==o||null==a)throw new c;const u=i<<2|s>>4;if(r.push(u),64!==o){const e=s<<4&240|o>>2;if(r.push(e),64!==a){const e=o<<6&192|a;r.push(e)}}}return r},init_(){if(!this.byteToCharMap_){this.byteToCharMap_={},this.charToByteMap_={},this.byteToCharMapWebSafe_={},this.charToByteMapWebSafe_={};for(let e=0;e<this.ENCODED_VALS.length;e++)this.byteToCharMap_[e]=this.ENCODED_VALS.charAt(e),this.charToByteMap_[this.byteToCharMap_[e]]=e,this.byteToCharMapWebSafe_[e]=this.ENCODED_VALS_WEBSAFE.charAt(e),this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[e]]=e,e>=this.ENCODED_VALS_BASE.length&&(this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(e)]=e,this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(e)]=e)}}};class c extends Error{constructor(){super(...arguments),this.name="DecodeBase64StringError"}}const u=function(e){const t=o(e);return a.encodeByteArray(t,!0)},l=function(e){return u(e).replace(/\./g,"")},h=function(e){try{return a.decodeString(e,!0)}catch(e){console.error("base64Decode failed: ",e)}return null};function d(e,t){if(!(t instanceof Object))return t;switch(t.constructor){case Date:return new Date(t.getTime());case Object:void 0===e&&(e={});break;case Array:e=[];break;default:return t}for(const n in t)t.hasOwnProperty(n)&&"__proto__"!==n&&(e[n]=d(e[n],t[n]));return e}function f(){if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if(void 0!==n.g)return n.g;throw new Error("Unable to locate global object.")}const g=()=>{try{return f().__FIREBASE_DEFAULTS__||(()=>{if("undefined"==typeof process||void 0===process.env)return;const e=process.env.__FIREBASE_DEFAULTS__;return e?JSON.parse(e):void 0})()||(()=>{if("undefined"==typeof document)return;let e;try{e=document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/)}catch(e){return}const t=e&&h(e[1]);return t&&JSON.parse(t)})()}catch(e){return void console.info(`Unable to get __FIREBASE_DEFAULTS__ due to: ${e}`)}},p=e=>{var t,n;return null===(n=null===(t=g())||void 0===t?void 0:t.emulatorHosts)||void 0===n?void 0:n[e]};class m{constructor(){this.reject=()=>{},this.resolve=()=>{},this.promise=new Promise(((e,t)=>{this.resolve=e,this.reject=t}))}wrapCallback(e){return(t,n)=>{t?this.reject(t):this.resolve(n),"function"==typeof e&&(this.promise.catch((()=>{})),1===e.length?e(t):e(t,n))}}}function y(){return"undefined"!=typeof navigator&&"string"==typeof navigator.userAgent?navigator.userAgent:""}function v(){var e;const t=null===(e=g())||void 0===e?void 0:e.forceEnvironment;if("node"===t)return!0;if("browser"===t)return!1;try{return"[object process]"===Object.prototype.toString.call(n.g.process)}catch(e){return!1}}function w(){return"undefined"!=typeof WorkerGlobalScope&&"undefined"!=typeof self&&self instanceof WorkerGlobalScope}class b extends Error{constructor(e,t,n){super(t),this.code=e,this.customData=n,this.name="FirebaseError",Object.setPrototypeOf(this,b.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,_.prototype.create)}}class _{constructor(e,t,n){this.service=e,this.serviceName=t,this.errors=n}create(e,...t){const n=t[0]||{},r=`${this.service}/${e}`,i=this.errors[e],s=i?function(e,t){return e.replace(I,((e,n)=>{const r=t[n];return null!=r?String(r):`<${n}?>`}))}(i,n):"Error",o=`${this.serviceName}: ${s} (${r}).`;return new b(r,o,n)}}const I=/\{\$([^}]+)}/g;function E(e){return JSON.parse(e)}const T=function(e){let t={},n={},r={},i="";try{const s=e.split(".");t=E(h(s[0])||""),n=E(h(s[1])||""),i=s[2],r=n.d||{},delete n.d}catch(e){}return{header:t,claims:n,data:r,signature:i}};function S(e){return null!==e&&"object"==typeof e}class x{constructor(e,t){this.observers=[],this.unsubscribes=[],this.observerCount=0,this.task=Promise.resolve(),this.finalized=!1,this.onNoObservers=t,this.task.then((()=>{e(this)})).catch((e=>{this.error(e)}))}next(e){this.forEachObserver((t=>{t.next(e)}))}error(e){this.forEachObserver((t=>{t.error(e)})),this.close(e)}complete(){this.forEachObserver((e=>{e.complete()})),this.close()}subscribe(e,t,n){let r;if(void 0===e&&void 0===t&&void 0===n)throw new Error("Missing Observer.");r=function(e){if("object"!=typeof e||null===e)return!1;for(const t of["next","error","complete"])if(t in e&&"function"==typeof e[t])return!0;return!1}(e)?e:{next:e,error:t,complete:n},void 0===r.next&&(r.next=C),void 0===r.error&&(r.error=C),void 0===r.complete&&(r.complete=C);const i=this.unsubscribeOne.bind(this,this.observers.length);return this.finalized&&this.task.then((()=>{try{this.finalError?r.error(this.finalError):r.complete()}catch(e){}})),this.observers.push(r),i}unsubscribeOne(e){void 0!==this.observers&&void 0!==this.observers[e]&&(delete this.observers[e],this.observerCount-=1,0===this.observerCount&&void 0!==this.onNoObservers&&this.onNoObservers(this))}forEachObserver(e){if(!this.finalized)for(let t=0;t<this.observers.length;t++)this.sendOne(t,e)}sendOne(e,t){this.task.then((()=>{if(void 0!==this.observers&&void 0!==this.observers[e])try{t(this.observers[e])}catch(e){"undefined"!=typeof console&&console.error&&console.error(e)}}))}close(e){this.finalized||(this.finalized=!0,void 0!==e&&(this.finalError=e),this.task.then((()=>{this.observers=void 0,this.onNoObservers=void 0})))}}function C(){}function D(e,t){return`${e} failed: ${t} argument `}const A=144e5;t.CONSTANTS=r,t.DecodeBase64StringError=c,t.Deferred=m,t.ErrorFactory=_,t.FirebaseError=b,t.MAX_VALUE_MILLIS=A,t.RANDOM_FACTOR=.5,t.Sha1=class{constructor(){this.chain_=[],this.buf_=[],this.W_=[],this.pad_=[],this.inbuf_=0,this.total_=0,this.blockSize=64,this.pad_[0]=128;for(let e=1;e<this.blockSize;++e)this.pad_[e]=0;this.reset()}reset(){this.chain_[0]=1732584193,this.chain_[1]=4023233417,this.chain_[2]=2562383102,this.chain_[3]=271733878,this.chain_[4]=3285377520,this.inbuf_=0,this.total_=0}compress_(e,t){t||(t=0);const n=this.W_;if("string"==typeof e)for(let r=0;r<16;r++)n[r]=e.charCodeAt(t)<<24|e.charCodeAt(t+1)<<16|e.charCodeAt(t+2)<<8|e.charCodeAt(t+3),t+=4;else for(let r=0;r<16;r++)n[r]=e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3],t+=4;for(let e=16;e<80;e++){const t=n[e-3]^n[e-8]^n[e-14]^n[e-16];n[e]=4294967295&(t<<1|t>>>31)}let r,i,s=this.chain_[0],o=this.chain_[1],a=this.chain_[2],c=this.chain_[3],u=this.chain_[4];for(let e=0;e<80;e++){e<40?e<20?(r=c^o&(a^c),i=1518500249):(r=o^a^c,i=1859775393):e<60?(r=o&a|c&(o|a),i=2400959708):(r=o^a^c,i=3395469782);const t=(s<<5|s>>>27)+r+u+i+n[e]&4294967295;u=c,c=a,a=4294967295&(o<<30|o>>>2),o=s,s=t}this.chain_[0]=this.chain_[0]+s&4294967295,this.chain_[1]=this.chain_[1]+o&4294967295,this.chain_[2]=this.chain_[2]+a&4294967295,this.chain_[3]=this.chain_[3]+c&4294967295,this.chain_[4]=this.chain_[4]+u&4294967295}update(e,t){if(null==e)return;void 0===t&&(t=e.length);const n=t-this.blockSize;let r=0;const i=this.buf_;let s=this.inbuf_;for(;r<t;){if(0===s)for(;r<=n;)this.compress_(e,r),r+=this.blockSize;if("string"==typeof e){for(;r<t;)if(i[s]=e.charCodeAt(r),++s,++r,s===this.blockSize){this.compress_(i),s=0;break}}else for(;r<t;)if(i[s]=e[r],++s,++r,s===this.blockSize){this.compress_(i),s=0;break}}this.inbuf_=s,this.total_+=t}digest(){const e=[];let t=8*this.total_;this.inbuf_<56?this.update(this.pad_,56-this.inbuf_):this.update(this.pad_,this.blockSize-(this.inbuf_-56));for(let e=this.blockSize-1;e>=56;e--)this.buf_[e]=255&t,t/=256;this.compress_(this.buf_);let n=0;for(let t=0;t<5;t++)for(let r=24;r>=0;r-=8)e[n]=this.chain_[t]>>r&255,++n;return e}},t.areCookiesEnabled=function(){return!("undefined"==typeof navigator||!navigator.cookieEnabled)},t.assert=i,t.assertionError=s,t.async=function(e,t){return(...n)=>{Promise.resolve(!0).then((()=>{e(...n)})).catch((e=>{t&&t(e)}))}},t.base64=a,t.base64Decode=h,t.base64Encode=u,t.base64urlEncodeWithoutPadding=l,t.calculateBackoffMillis=function(e,t=1e3,n=2){const r=t*Math.pow(n,e),i=Math.round(.5*r*(Math.random()-.5)*2);return Math.min(A,r+i)},t.contains=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},t.createMockUserToken=function(e,t){if(e.uid)throw new Error('The "uid" field is no longer supported by mockUserToken. Please use "sub" instead for Firebase Auth User ID.');const n=t||"demo-project",r=e.iat||0,i=e.sub||e.user_id;if(!i)throw new Error("mockUserToken must contain 'sub' or 'user_id' field!");const s=Object.assign({iss:`https://securetoken.google.com/${n}`,aud:n,iat:r,exp:r+3600,auth_time:r,sub:i,user_id:i,firebase:{sign_in_provider:"custom",identities:{}}},e);return[l(JSON.stringify({alg:"none",type:"JWT"})),l(JSON.stringify(s)),""].join(".")},t.createSubscribe=function(e,t){const n=new x(e,t);return n.subscribe.bind(n)},t.decode=T,t.deepCopy=function(e){return d(void 0,e)},t.deepEqual=function e(t,n){if(t===n)return!0;const r=Object.keys(t),i=Object.keys(n);for(const s of r){if(!i.includes(s))return!1;const r=t[s],o=n[s];if(S(r)&&S(o)){if(!e(r,o))return!1}else if(r!==o)return!1}for(const e of i)if(!r.includes(e))return!1;return!0},t.deepExtend=d,t.errorPrefix=D,t.extractQuerystring=function(e){const t=e.indexOf("?");if(!t)return"";const n=e.indexOf("#",t);return e.substring(t,n>0?n:void 0)},t.getDefaultAppConfig=()=>{var e;return null===(e=g())||void 0===e?void 0:e.config},t.getDefaultEmulatorHost=p,t.getDefaultEmulatorHostnameAndPort=e=>{const t=p(e);if(!t)return;const n=t.lastIndexOf(":");if(n<=0||n+1===t.length)throw new Error(`Invalid host ${t} with no separate hostname and port!`);const r=parseInt(t.substring(n+1),10);return"["===t[0]?[t.substring(1,n-1),r]:[t.substring(0,n),r]},t.getDefaults=g,t.getExperimentalSetting=e=>{var t;return null===(t=g())||void 0===t?void 0:t[`_${e}`]},t.getGlobal=f,t.getModularInstance=function(e){return e&&e._delegate?e._delegate:e},t.getUA=y,t.isAdmin=function(e){const t=T(e).claims;return"object"==typeof t&&!0===t.admin},t.isBrowser=function(){return"undefined"!=typeof window||w()},t.isBrowserExtension=function(){const e="object"==typeof chrome?chrome.runtime:"object"==typeof browser?browser.runtime:void 0;return"object"==typeof e&&void 0!==e.id},t.isCloudflareWorker=function(){return"undefined"!=typeof navigator&&"Cloudflare-Workers"===navigator.userAgent},t.isElectron=function(){return y().indexOf("Electron/")>=0},t.isEmpty=function(e){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0},t.isIE=function(){const e=y();return e.indexOf("MSIE ")>=0||e.indexOf("Trident/")>=0},t.isIndexedDBAvailable=function(){try{return"object"==typeof indexedDB}catch(e){return!1}},t.isMobileCordova=function(){return"undefined"!=typeof window&&!!(window.cordova||window.phonegap||window.PhoneGap)&&/ios|iphone|ipod|ipad|android|blackberry|iemobile/i.test(y())},t.isNode=v,t.isNodeSdk=function(){return!0===r.NODE_CLIENT||!0===r.NODE_ADMIN},t.isReactNative=function(){return"object"==typeof navigator&&"ReactNative"===navigator.product},t.isSafari=function(){return!v()&&!!navigator.userAgent&&navigator.userAgent.includes("Safari")&&!navigator.userAgent.includes("Chrome")},t.isUWP=function(){return y().indexOf("MSAppHost/")>=0},t.isValidFormat=function(e){const t=T(e).claims;return!!t&&"object"==typeof t&&t.hasOwnProperty("iat")},t.isValidTimestamp=function(e){const t=T(e).claims,n=Math.floor((new Date).getTime()/1e3);let r=0,i=0;return"object"==typeof t&&(t.hasOwnProperty("nbf")?r=t.nbf:t.hasOwnProperty("iat")&&(r=t.iat),i=t.hasOwnProperty("exp")?t.exp:r+86400),!!n&&!!r&&!!i&&n>=r&&n<=i},t.isWebWorker=w,t.issuedAtTime=function(e){const t=T(e).claims;return"object"==typeof t&&t.hasOwnProperty("iat")?t.iat:null},t.jsonEval=E,t.map=function(e,t,n){const r={};for(const i in e)Object.prototype.hasOwnProperty.call(e,i)&&(r[i]=t.call(n,e[i],i,e));return r},t.ordinal=function(e){return Number.isFinite(e)?e+function(e){const t=(e=Math.abs(e))%100;if(t>=10&&t<=20)return"th";const n=e%10;return 1===n?"st":2===n?"nd":3===n?"rd":"th"}(e):`${e}`},t.promiseWithTimeout=function(e,t=2e3){const n=new m;return setTimeout((()=>n.reject("timeout!")),t),e.then(n.resolve,n.reject),n.promise},t.querystring=function(e){const t=[];for(const[n,r]of Object.entries(e))Array.isArray(r)?r.forEach((e=>{t.push(encodeURIComponent(n)+"="+encodeURIComponent(e))})):t.push(encodeURIComponent(n)+"="+encodeURIComponent(r));return t.length?"&"+t.join("&"):""},t.querystringDecode=function(e){const t={};return e.replace(/^\?/,"").split("&").forEach((e=>{if(e){const[n,r]=e.split("=");t[decodeURIComponent(n)]=decodeURIComponent(r)}})),t},t.safeGet=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0},t.stringLength=function(e){let t=0;for(let n=0;n<e.length;n++){const r=e.charCodeAt(n);r<128?t++:r<2048?t+=2:r>=55296&&r<=56319?(t+=4,n++):t+=3}return t},t.stringToByteArray=function(e){const t=[];let n=0;for(let r=0;r<e.length;r++){let s=e.charCodeAt(r);if(s>=55296&&s<=56319){const t=s-55296;r++,i(r<e.length,"Surrogate pair missing trail surrogate."),s=65536+(t<<10)+(e.charCodeAt(r)-56320)}s<128?t[n++]=s:s<2048?(t[n++]=s>>6|192,t[n++]=63&s|128):s<65536?(t[n++]=s>>12|224,t[n++]=s>>6&63|128,t[n++]=63&s|128):(t[n++]=s>>18|240,t[n++]=s>>12&63|128,t[n++]=s>>6&63|128,t[n++]=63&s|128)}return t},t.stringify=function(e){return JSON.stringify(e)},t.uuidv4=function(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)}))},t.validateArgCount=function(e,t,n,r){let i;if(r<t?i="at least "+t:r>n&&(i=0===n?"none":"no more than "+n),i)throw new Error(e+" failed: Was called with "+r+(1===r?" argument.":" arguments.")+" Expects "+i+".")},t.validateCallback=function(e,t,n,r){if((!r||n)&&"function"!=typeof n)throw new Error(D(e,t)+"must be a valid function.")},t.validateContextObject=function(e,t,n,r){if((!r||n)&&("object"!=typeof n||null===n))throw new Error(D(e,t)+"must be a valid context object.")},t.validateIndexedDBOpenable=function(){return new Promise(((e,t)=>{try{let n=!0;const r="validate-browser-context-for-indexeddb-analytics-module",i=self.indexedDB.open(r);i.onsuccess=()=>{i.result.close(),n||self.indexedDB.deleteDatabase(r),e(!0)},i.onupgradeneeded=()=>{n=!1},i.onerror=()=>{var e;t((null===(e=i.error)||void 0===e?void 0:e.message)||"")}}catch(e){t(e)}}))},t.validateNamespace=function(e,t,n){if((!n||t)&&"string"!=typeof t)throw new Error(D(e,"namespace")+"must be a valid firebase namespace.")}},860:(e,t,n)=>{(function(){"use strict";var t;function n(){this.blockSize=-1,this.blockSize=64,this.g=Array(4),this.B=Array(this.blockSize),this.o=this.h=0,this.s()}function r(e,t,n){n||(n=0);var r=Array(16);if("string"==typeof t)for(var i=0;16>i;++i)r[i]=t.charCodeAt(n++)|t.charCodeAt(n++)<<8|t.charCodeAt(n++)<<16|t.charCodeAt(n++)<<24;else for(i=0;16>i;++i)r[i]=t[n++]|t[n++]<<8|t[n++]<<16|t[n++]<<24;t=e.g[0],n=e.g[1],i=e.g[2];var s=e.g[3],o=t+(s^n&(i^s))+r[0]+3614090360&4294967295;o=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=(n=(i=(s=(t=n+(o<<7&4294967295|o>>>25))+((o=s+(i^t&(n^i))+r[1]+3905402710&4294967295)<<12&4294967295|o>>>20))+((o=i+(n^s&(t^n))+r[2]+606105819&4294967295)<<17&4294967295|o>>>15))+((o=n+(t^i&(s^t))+r[3]+3250441966&4294967295)<<22&4294967295|o>>>10))+((o=t+(s^n&(i^s))+r[4]+4118548399&4294967295)<<7&4294967295|o>>>25))+((o=s+(i^t&(n^i))+r[5]+1200080426&4294967295)<<12&4294967295|o>>>20))+((o=i+(n^s&(t^n))+r[6]+2821735955&4294967295)<<17&4294967295|o>>>15))+((o=n+(t^i&(s^t))+r[7]+4249261313&4294967295)<<22&4294967295|o>>>10))+((o=t+(s^n&(i^s))+r[8]+1770035416&4294967295)<<7&4294967295|o>>>25))+((o=s+(i^t&(n^i))+r[9]+2336552879&4294967295)<<12&4294967295|o>>>20))+((o=i+(n^s&(t^n))+r[10]+4294925233&4294967295)<<17&4294967295|o>>>15))+((o=n+(t^i&(s^t))+r[11]+2304563134&4294967295)<<22&4294967295|o>>>10))+((o=t+(s^n&(i^s))+r[12]+1804603682&4294967295)<<7&4294967295|o>>>25))+((o=s+(i^t&(n^i))+r[13]+4254626195&4294967295)<<12&4294967295|o>>>20))+((o=i+(n^s&(t^n))+r[14]+2792965006&4294967295)<<17&4294967295|o>>>15))+((o=n+(t^i&(s^t))+r[15]+1236535329&4294967295)<<22&4294967295|o>>>10))+((o=t+(i^s&(n^i))+r[1]+4129170786&4294967295)<<5&4294967295|o>>>27))+((o=s+(n^i&(t^n))+r[6]+3225465664&4294967295)<<9&4294967295|o>>>23))+((o=i+(t^n&(s^t))+r[11]+643717713&4294967295)<<14&4294967295|o>>>18))+((o=n+(s^t&(i^s))+r[0]+3921069994&4294967295)<<20&4294967295|o>>>12))+((o=t+(i^s&(n^i))+r[5]+3593408605&4294967295)<<5&4294967295|o>>>27))+((o=s+(n^i&(t^n))+r[10]+38016083&4294967295)<<9&4294967295|o>>>23))+((o=i+(t^n&(s^t))+r[15]+3634488961&4294967295)<<14&4294967295|o>>>18))+((o=n+(s^t&(i^s))+r[4]+3889429448&4294967295)<<20&4294967295|o>>>12))+((o=t+(i^s&(n^i))+r[9]+568446438&4294967295)<<5&4294967295|o>>>27))+((o=s+(n^i&(t^n))+r[14]+3275163606&4294967295)<<9&4294967295|o>>>23))+((o=i+(t^n&(s^t))+r[3]+4107603335&4294967295)<<14&4294967295|o>>>18))+((o=n+(s^t&(i^s))+r[8]+1163531501&4294967295)<<20&4294967295|o>>>12))+((o=t+(i^s&(n^i))+r[13]+2850285829&4294967295)<<5&4294967295|o>>>27))+((o=s+(n^i&(t^n))+r[2]+4243563512&4294967295)<<9&4294967295|o>>>23))+((o=i+(t^n&(s^t))+r[7]+1735328473&4294967295)<<14&4294967295|o>>>18))+((o=n+(s^t&(i^s))+r[12]+2368359562&4294967295)<<20&4294967295|o>>>12))+((o=t+(n^i^s)+r[5]+4294588738&4294967295)<<4&4294967295|o>>>28))+((o=s+(t^n^i)+r[8]+2272392833&4294967295)<<11&4294967295|o>>>21))+((o=i+(s^t^n)+r[11]+1839030562&4294967295)<<16&4294967295|o>>>16))+((o=n+(i^s^t)+r[14]+4259657740&4294967295)<<23&4294967295|o>>>9))+((o=t+(n^i^s)+r[1]+2763975236&4294967295)<<4&4294967295|o>>>28))+((o=s+(t^n^i)+r[4]+1272893353&4294967295)<<11&4294967295|o>>>21))+((o=i+(s^t^n)+r[7]+4139469664&4294967295)<<16&4294967295|o>>>16))+((o=n+(i^s^t)+r[10]+3200236656&4294967295)<<23&4294967295|o>>>9))+((o=t+(n^i^s)+r[13]+681279174&4294967295)<<4&4294967295|o>>>28))+((o=s+(t^n^i)+r[0]+3936430074&4294967295)<<11&4294967295|o>>>21))+((o=i+(s^t^n)+r[3]+3572445317&4294967295)<<16&4294967295|o>>>16))+((o=n+(i^s^t)+r[6]+76029189&4294967295)<<23&4294967295|o>>>9))+((o=t+(n^i^s)+r[9]+3654602809&4294967295)<<4&4294967295|o>>>28))+((o=s+(t^n^i)+r[12]+3873151461&4294967295)<<11&4294967295|o>>>21))+((o=i+(s^t^n)+r[15]+530742520&4294967295)<<16&4294967295|o>>>16))+((o=n+(i^s^t)+r[2]+3299628645&4294967295)<<23&4294967295|o>>>9))+((o=t+(i^(n|~s))+r[0]+4096336452&4294967295)<<6&4294967295|o>>>26))+((o=s+(n^(t|~i))+r[7]+1126891415&4294967295)<<10&4294967295|o>>>22))+((o=i+(t^(s|~n))+r[14]+2878612391&4294967295)<<15&4294967295|o>>>17))+((o=n+(s^(i|~t))+r[5]+4237533241&4294967295)<<21&4294967295|o>>>11))+((o=t+(i^(n|~s))+r[12]+1700485571&4294967295)<<6&4294967295|o>>>26))+((o=s+(n^(t|~i))+r[3]+2399980690&4294967295)<<10&4294967295|o>>>22))+((o=i+(t^(s|~n))+r[10]+4293915773&4294967295)<<15&4294967295|o>>>17))+((o=n+(s^(i|~t))+r[1]+2240044497&4294967295)<<21&4294967295|o>>>11))+((o=t+(i^(n|~s))+r[8]+1873313359&4294967295)<<6&4294967295|o>>>26))+((o=s+(n^(t|~i))+r[15]+4264355552&4294967295)<<10&4294967295|o>>>22))+((o=i+(t^(s|~n))+r[6]+2734768916&4294967295)<<15&4294967295|o>>>17))+((o=n+(s^(i|~t))+r[13]+1309151649&4294967295)<<21&4294967295|o>>>11))+((s=(t=n+((o=t+(i^(n|~s))+r[4]+4149444226&4294967295)<<6&4294967295|o>>>26))+((o=s+(n^(t|~i))+r[11]+3174756917&4294967295)<<10&4294967295|o>>>22))^((i=s+((o=i+(t^(s|~n))+r[2]+718787259&4294967295)<<15&4294967295|o>>>17))|~t))+r[9]+3951481745&4294967295,e.g[0]=e.g[0]+t&4294967295,e.g[1]=e.g[1]+(i+(o<<21&4294967295|o>>>11))&4294967295,e.g[2]=e.g[2]+i&4294967295,e.g[3]=e.g[3]+s&4294967295}function i(e,t){this.h=t;for(var n=[],r=!0,i=e.length-1;0<=i;i--){var s=0|e[i];r&&s==t||(n[i]=s,r=!1)}this.g=n}!function(e,t){function n(){}n.prototype=t.prototype,e.D=t.prototype,e.prototype=new n,e.prototype.constructor=e,e.C=function(e,n,r){for(var i=Array(arguments.length-2),s=2;s<arguments.length;s++)i[s-2]=arguments[s];return t.prototype[n].apply(e,i)}}(n,(function(){this.blockSize=-1})),n.prototype.s=function(){this.g[0]=1732584193,this.g[1]=4023233417,this.g[2]=2562383102,this.g[3]=271733878,this.o=this.h=0},n.prototype.u=function(e,t){void 0===t&&(t=e.length);for(var n=t-this.blockSize,i=this.B,s=this.h,o=0;o<t;){if(0==s)for(;o<=n;)r(this,e,o),o+=this.blockSize;if("string"==typeof e){for(;o<t;)if(i[s++]=e.charCodeAt(o++),s==this.blockSize){r(this,i),s=0;break}}else for(;o<t;)if(i[s++]=e[o++],s==this.blockSize){r(this,i),s=0;break}}this.h=s,this.o+=t},n.prototype.v=function(){var e=Array((56>this.h?this.blockSize:2*this.blockSize)-this.h);e[0]=128;for(var t=1;t<e.length-8;++t)e[t]=0;var n=8*this.o;for(t=e.length-8;t<e.length;++t)e[t]=255&n,n/=256;for(this.u(e),e=Array(16),t=n=0;4>t;++t)for(var r=0;32>r;r+=8)e[n++]=this.g[t]>>>r&255;return e};var s={};function o(e){return-128<=e&&128>e?function(e){var t=s;return Object.prototype.hasOwnProperty.call(t,e)?t[e]:t[e]=function(e){return new i([0|e],0>e?-1:0)}(e)}(e):new i([0|e],0>e?-1:0)}function a(e){if(isNaN(e)||!isFinite(e))return c;if(0>e)return f(a(-e));for(var t=[],n=1,r=0;e>=n;r++)t[r]=e/n|0,n*=4294967296;return new i(t,0)}var c=o(0),u=o(1),l=o(16777216);function h(e){if(0!=e.h)return!1;for(var t=0;t<e.g.length;t++)if(0!=e.g[t])return!1;return!0}function d(e){return-1==e.h}function f(e){for(var t=e.g.length,n=[],r=0;r<t;r++)n[r]=~e.g[r];return new i(n,~e.h).add(u)}function g(e,t){return e.add(f(t))}function p(e,t){for(;(65535&e[t])!=e[t];)e[t+1]+=e[t]>>>16,e[t]&=65535,t++}function m(e,t){this.g=e,this.h=t}function y(e,t){if(h(t))throw Error("division by zero");if(h(e))return new m(c,c);if(d(e))return t=y(f(e),t),new m(f(t.g),f(t.h));if(d(t))return t=y(e,f(t)),new m(f(t.g),t.h);if(30<e.g.length){if(d(e)||d(t))throw Error("slowDivide_ only works with positive integers.");for(var n=u,r=t;0>=r.l(e);)n=v(n),r=v(r);var i=w(n,1),s=w(r,1);for(r=w(r,2),n=w(n,2);!h(r);){var o=s.add(r);0>=o.l(e)&&(i=i.add(n),s=o),r=w(r,1),n=w(n,1)}return t=g(e,i.j(t)),new m(i,t)}for(i=c;0<=e.l(t);){for(n=Math.max(1,Math.floor(e.m()/t.m())),r=48>=(r=Math.ceil(Math.log(n)/Math.LN2))?1:Math.pow(2,r-48),o=(s=a(n)).j(t);d(o)||0<o.l(e);)o=(s=a(n-=r)).j(t);h(s)&&(s=u),i=i.add(s),e=g(e,o)}return new m(i,e)}function v(e){for(var t=e.g.length+1,n=[],r=0;r<t;r++)n[r]=e.i(r)<<1|e.i(r-1)>>>31;return new i(n,e.h)}function w(e,t){var n=t>>5;t%=32;for(var r=e.g.length-n,s=[],o=0;o<r;o++)s[o]=0<t?e.i(o+n)>>>t|e.i(o+n+1)<<32-t:e.i(o+n);return new i(s,e.h)}(t=i.prototype).m=function(){if(d(this))return-f(this).m();for(var e=0,t=1,n=0;n<this.g.length;n++){var r=this.i(n);e+=(0<=r?r:4294967296+r)*t,t*=4294967296}return e},t.toString=function(e){if(2>(e=e||10)||36<e)throw Error("radix out of range: "+e);if(h(this))return"0";if(d(this))return"-"+f(this).toString(e);for(var t=a(Math.pow(e,6)),n=this,r="";;){var i=y(n,t).g,s=((0<(n=g(n,i.j(t))).g.length?n.g[0]:n.h)>>>0).toString(e);if(h(n=i))return s+r;for(;6>s.length;)s="0"+s;r=s+r}},t.i=function(e){return 0>e?0:e<this.g.length?this.g[e]:this.h},t.l=function(e){return d(e=g(this,e))?-1:h(e)?0:1},t.abs=function(){return d(this)?f(this):this},t.add=function(e){for(var t=Math.max(this.g.length,e.g.length),n=[],r=0,s=0;s<=t;s++){var o=r+(65535&this.i(s))+(65535&e.i(s)),a=(o>>>16)+(this.i(s)>>>16)+(e.i(s)>>>16);r=a>>>16,o&=65535,a&=65535,n[s]=a<<16|o}return new i(n,-2147483648&n[n.length-1]?-1:0)},t.j=function(e){if(h(this)||h(e))return c;if(d(this))return d(e)?f(this).j(f(e)):f(f(this).j(e));if(d(e))return f(this.j(f(e)));if(0>this.l(l)&&0>e.l(l))return a(this.m()*e.m());for(var t=this.g.length+e.g.length,n=[],r=0;r<2*t;r++)n[r]=0;for(r=0;r<this.g.length;r++)for(var s=0;s<e.g.length;s++){var o=this.i(r)>>>16,u=65535&this.i(r),g=e.i(s)>>>16,m=65535&e.i(s);n[2*r+2*s]+=u*m,p(n,2*r+2*s),n[2*r+2*s+1]+=o*m,p(n,2*r+2*s+1),n[2*r+2*s+1]+=u*g,p(n,2*r+2*s+1),n[2*r+2*s+2]+=o*g,p(n,2*r+2*s+2)}for(r=0;r<t;r++)n[r]=n[2*r+1]<<16|n[2*r];for(r=t;r<2*t;r++)n[r]=0;return new i(n,0)},t.A=function(e){return y(this,e).h},t.and=function(e){for(var t=Math.max(this.g.length,e.g.length),n=[],r=0;r<t;r++)n[r]=this.i(r)&e.i(r);return new i(n,this.h&e.h)},t.or=function(e){for(var t=Math.max(this.g.length,e.g.length),n=[],r=0;r<t;r++)n[r]=this.i(r)|e.i(r);return new i(n,this.h|e.h)},t.xor=function(e){for(var t=Math.max(this.g.length,e.g.length),n=[],r=0;r<t;r++)n[r]=this.i(r)^e.i(r);return new i(n,this.h^e.h)},n.prototype.digest=n.prototype.v,n.prototype.reset=n.prototype.s,n.prototype.update=n.prototype.u,e.exports.Md5=n,i.prototype.add=i.prototype.add,i.prototype.multiply=i.prototype.j,i.prototype.modulo=i.prototype.A,i.prototype.compare=i.prototype.l,i.prototype.toNumber=i.prototype.m,i.prototype.toString=i.prototype.toString,i.prototype.getBits=i.prototype.i,i.fromNumber=a,i.fromString=function e(t,n){if(0==t.length)throw Error("number format error: empty string");if(2>(n=n||10)||36<n)throw Error("radix out of range: "+n);if("-"==t.charAt(0))return f(e(t.substring(1),n));if(0<=t.indexOf("-"))throw Error('number format error: interior "-" character');for(var r=a(Math.pow(n,8)),i=c,s=0;s<t.length;s+=8){var o=Math.min(8,t.length-s),u=parseInt(t.substring(s,s+o),n);8>o?(o=a(Math.pow(n,o)),i=i.j(o).add(a(u))):i=(i=i.j(r)).add(a(u))}return i},e.exports.Integer=i}).apply(void 0!==n.g?n.g:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},832:(e,t,n)=>{(function(){"use strict";var t,r="function"==typeof Object.defineProperties?Object.defineProperty:function(e,t,n){return e==Array.prototype||e==Object.prototype||(e[t]=n.value),e},i=function(e){e=["object"==typeof globalThis&&globalThis,e,"object"==typeof window&&window,"object"==typeof self&&self,"object"==typeof n.g&&n.g];for(var t=0;t<e.length;++t){var r=e[t];if(r&&r.Math==Math)return r}throw Error("Cannot find global object")}(this);!function(e,t){if(t)e:{var n=i;e=e.split(".");for(var s=0;s<e.length-1;s++){var o=e[s];if(!(o in n))break e;n=n[o]}(t=t(s=n[e=e[e.length-1]]))!=s&&null!=t&&r(n,e,{configurable:!0,writable:!0,value:t})}}("Array.prototype.values",(function(e){return e||function(){return function(e,t){e instanceof String&&(e+="");var n=0,r=!1,i={next:function(){if(!r&&n<e.length){var i=n++;return{value:t(0,e[i]),done:!1}}return r=!0,{done:!0,value:void 0}}};return i[Symbol.iterator]=function(){return i},i}(this,(function(e,t){return t}))}}));var s=s||{},o=this||self;function a(e){var t=typeof e;return"array"==(t="object"!=t?t:e?Array.isArray(e)?"array":t:"null")||"object"==t&&"number"==typeof e.length}function c(e){var t=typeof e;return"object"==t&&null!=e||"function"==t}function u(e,t,n){return e.call.apply(e.bind,arguments)}function l(e,t,n){if(!e)throw Error();if(2<arguments.length){var r=Array.prototype.slice.call(arguments,2);return function(){var n=Array.prototype.slice.call(arguments);return Array.prototype.unshift.apply(n,r),e.apply(t,n)}}return function(){return e.apply(t,arguments)}}function h(e,t,n){return(h=Function.prototype.bind&&-1!=Function.prototype.bind.toString().indexOf("native code")?u:l).apply(null,arguments)}function d(e,t){var n=Array.prototype.slice.call(arguments,1);return function(){var t=n.slice();return t.push.apply(t,arguments),e.apply(this,t)}}function f(e,t){function n(){}n.prototype=t.prototype,e.aa=t.prototype,e.prototype=new n,e.prototype.constructor=e,e.Qb=function(e,n,r){for(var i=Array(arguments.length-2),s=2;s<arguments.length;s++)i[s-2]=arguments[s];return t.prototype[n].apply(e,i)}}function g(e){const t=e.length;if(0<t){const n=Array(t);for(let r=0;r<t;r++)n[r]=e[r];return n}return[]}function p(e,t){for(let t=1;t<arguments.length;t++){const n=arguments[t];if(a(n)){const t=e.length||0,r=n.length||0;e.length=t+r;for(let i=0;i<r;i++)e[t+i]=n[i]}else e.push(n)}}function m(e){return/^[\s\xa0]*$/.test(e)}function y(){var e=o.navigator;return e&&(e=e.userAgent)?e:""}function v(e){return v[" "](e),e}v[" "]=function(){};var w=!(-1==y().indexOf("Gecko")||-1!=y().toLowerCase().indexOf("webkit")&&-1==y().indexOf("Edge")||-1!=y().indexOf("Trident")||-1!=y().indexOf("MSIE")||-1!=y().indexOf("Edge"));function b(e,t,n){for(const r in e)t.call(n,e[r],r,e)}function _(e){const t={};for(const n in e)t[n]=e[n];return t}const I="constructor hasOwnProperty isPrototypeOf propertyIsEnumerable toLocaleString toString valueOf".split(" ");function E(e,t){let n,r;for(let t=1;t<arguments.length;t++){for(n in r=arguments[t],r)e[n]=r[n];for(let t=0;t<I.length;t++)n=I[t],Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}}function T(e){var t=1;e=e.split(":");const n=[];for(;0<t&&e.length;)n.push(e.shift()),t--;return e.length&&n.push(e.join(":")),n}function S(e){o.setTimeout((()=>{throw e}),0)}function x(){var e=N;let t=null;return e.g&&(t=e.g,e.g=e.g.next,e.g||(e.h=null),t.next=null),t}var C=new class{constructor(e,t){this.i=e,this.j=t,this.h=0,this.g=null}get(){let e;return 0<this.h?(this.h--,e=this.g,this.g=e.next,e.next=null):e=this.i(),e}}((()=>new D),(e=>e.reset()));class D{constructor(){this.next=this.g=this.h=null}set(e,t){this.h=e,this.g=t,this.next=null}reset(){this.next=this.g=this.h=null}}let A,k=!1,N=new class{constructor(){this.h=this.g=null}add(e,t){const n=C.get();n.set(e,t),this.h?this.h.next=n:this.g=n,this.h=n}},L=()=>{const e=o.Promise.resolve(void 0);A=()=>{e.then(O)}};var O=()=>{for(var e;e=x();){try{e.h.call(e.g)}catch(e){S(e)}var t=C;t.j(e),100>t.h&&(t.h++,e.next=t.g,t.g=e)}k=!1};function M(){this.s=this.s,this.C=this.C}function R(e,t){this.type=e,this.g=this.target=t,this.defaultPrevented=!1}M.prototype.s=!1,M.prototype.ma=function(){this.s||(this.s=!0,this.N())},M.prototype.N=function(){if(this.C)for(;this.C.length;)this.C.shift()()},R.prototype.h=function(){this.defaultPrevented=!0};var P=function(){if(!o.addEventListener||!Object.defineProperty)return!1;var e=!1,t=Object.defineProperty({},"passive",{get:function(){e=!0}});try{const e=()=>{};o.addEventListener("test",e,t),o.removeEventListener("test",e,t)}catch(e){}return e}();function F(e,t){if(R.call(this,e?e.type:""),this.relatedTarget=this.g=this.target=null,this.button=this.screenY=this.screenX=this.clientY=this.clientX=0,this.key="",this.metaKey=this.shiftKey=this.altKey=this.ctrlKey=!1,this.state=null,this.pointerId=0,this.pointerType="",this.i=null,e){var n=this.type=e.type,r=e.changedTouches&&e.changedTouches.length?e.changedTouches[0]:null;if(this.target=e.target||e.srcElement,this.g=t,t=e.relatedTarget){if(w){e:{try{v(t.nodeName);var i=!0;break e}catch(e){}i=!1}i||(t=null)}}else"mouseover"==n?t=e.fromElement:"mouseout"==n&&(t=e.toElement);this.relatedTarget=t,r?(this.clientX=void 0!==r.clientX?r.clientX:r.pageX,this.clientY=void 0!==r.clientY?r.clientY:r.pageY,this.screenX=r.screenX||0,this.screenY=r.screenY||0):(this.clientX=void 0!==e.clientX?e.clientX:e.pageX,this.clientY=void 0!==e.clientY?e.clientY:e.pageY,this.screenX=e.screenX||0,this.screenY=e.screenY||0),this.button=e.button,this.key=e.key||"",this.ctrlKey=e.ctrlKey,this.altKey=e.altKey,this.shiftKey=e.shiftKey,this.metaKey=e.metaKey,this.pointerId=e.pointerId||0,this.pointerType="string"==typeof e.pointerType?e.pointerType:V[e.pointerType]||"",this.state=e.state,this.i=e,e.defaultPrevented&&F.aa.h.call(this)}}f(F,R);var V={2:"touch",3:"pen",4:"mouse"};F.prototype.h=function(){F.aa.h.call(this);var e=this.i;e.preventDefault?e.preventDefault():e.returnValue=!1};var q="closure_listenable_"+(1e6*Math.random()|0),B=0;function U(e,t,n,r,i){this.listener=e,this.proxy=null,this.src=t,this.type=n,this.capture=!!r,this.ha=i,this.key=++B,this.da=this.fa=!1}function j(e){e.da=!0,e.listener=null,e.proxy=null,e.src=null,e.ha=null}function $(e){this.src=e,this.g={},this.h=0}function z(e,t){var n=t.type;if(n in e.g){var r,i=e.g[n],s=Array.prototype.indexOf.call(i,t,void 0);(r=0<=s)&&Array.prototype.splice.call(i,s,1),r&&(j(t),0==e.g[n].length&&(delete e.g[n],e.h--))}}function G(e,t,n,r){for(var i=0;i<e.length;++i){var s=e[i];if(!s.da&&s.listener==t&&s.capture==!!n&&s.ha==r)return i}return-1}$.prototype.add=function(e,t,n,r,i){var s=e.toString();(e=this.g[s])||(e=this.g[s]=[],this.h++);var o=G(e,t,r,i);return-1<o?(t=e[o],n||(t.fa=!1)):((t=new U(t,this.src,s,!!r,i)).fa=n,e.push(t)),t};var K="closure_lm_"+(1e6*Math.random()|0),Q={};function H(e,t,n,r,i){if(r&&r.once)return J(e,t,n,r,i);if(Array.isArray(t)){for(var s=0;s<t.length;s++)H(e,t[s],n,r,i);return null}return n=re(n),e&&e[q]?e.K(t,n,c(r)?!!r.capture:!!r,i):W(e,t,n,!1,r,i)}function W(e,t,n,r,i,s){if(!t)throw Error("Invalid event type");var o=c(i)?!!i.capture:!!i,a=te(e);if(a||(e[K]=a=new $(e)),(n=a.add(t,n,r,o,s)).proxy)return n;if(r=function(){const e=ee;return function t(n){return e.call(t.src,t.listener,n)}}(),n.proxy=r,r.src=e,r.listener=n,e.addEventListener)P||(i=o),void 0===i&&(i=!1),e.addEventListener(t.toString(),r,i);else if(e.attachEvent)e.attachEvent(Z(t.toString()),r);else{if(!e.addListener||!e.removeListener)throw Error("addEventListener and attachEvent are unavailable.");e.addListener(r)}return n}function J(e,t,n,r,i){if(Array.isArray(t)){for(var s=0;s<t.length;s++)J(e,t[s],n,r,i);return null}return n=re(n),e&&e[q]?e.L(t,n,c(r)?!!r.capture:!!r,i):W(e,t,n,!0,r,i)}function X(e,t,n,r,i){if(Array.isArray(t))for(var s=0;s<t.length;s++)X(e,t[s],n,r,i);else r=c(r)?!!r.capture:!!r,n=re(n),e&&e[q]?(e=e.i,(t=String(t).toString())in e.g&&-1<(n=G(s=e.g[t],n,r,i))&&(j(s[n]),Array.prototype.splice.call(s,n,1),0==s.length&&(delete e.g[t],e.h--))):e&&(e=te(e))&&(t=e.g[t.toString()],e=-1,t&&(e=G(t,n,r,i)),(n=-1<e?t[e]:null)&&Y(n))}function Y(e){if("number"!=typeof e&&e&&!e.da){var t=e.src;if(t&&t[q])z(t.i,e);else{var n=e.type,r=e.proxy;t.removeEventListener?t.removeEventListener(n,r,e.capture):t.detachEvent?t.detachEvent(Z(n),r):t.addListener&&t.removeListener&&t.removeListener(r),(n=te(t))?(z(n,e),0==n.h&&(n.src=null,t[K]=null)):j(e)}}}function Z(e){return e in Q?Q[e]:Q[e]="on"+e}function ee(e,t){if(e.da)e=!0;else{t=new F(t,this);var n=e.listener,r=e.ha||e.src;e.fa&&Y(e),e=n.call(r,t)}return e}function te(e){return(e=e[K])instanceof $?e:null}var ne="__closure_events_fn_"+(1e9*Math.random()>>>0);function re(e){return"function"==typeof e?e:(e[ne]||(e[ne]=function(t){return e.handleEvent(t)}),e[ne])}function ie(){M.call(this),this.i=new $(this),this.M=this,this.F=null}function se(e,t){var n,r=e.F;if(r)for(n=[];r;r=r.F)n.push(r);if(e=e.M,r=t.type||t,"string"==typeof t)t=new R(t,e);else if(t instanceof R)t.target=t.target||e;else{var i=t;E(t=new R(r,e),i)}if(i=!0,n)for(var s=n.length-1;0<=s;s--){var o=t.g=n[s];i=oe(o,r,!0,t)&&i}if(i=oe(o=t.g=e,r,!0,t)&&i,i=oe(o,r,!1,t)&&i,n)for(s=0;s<n.length;s++)i=oe(o=t.g=n[s],r,!1,t)&&i}function oe(e,t,n,r){if(!(t=e.i.g[String(t)]))return!0;t=t.concat();for(var i=!0,s=0;s<t.length;++s){var o=t[s];if(o&&!o.da&&o.capture==n){var a=o.listener,c=o.ha||o.src;o.fa&&z(e.i,o),i=!1!==a.call(c,r)&&i}}return i&&!r.defaultPrevented}function ae(e,t,n){if("function"==typeof e)n&&(e=h(e,n));else{if(!e||"function"!=typeof e.handleEvent)throw Error("Invalid listener argument");e=h(e.handleEvent,e)}return 2147483647<Number(t)?-1:o.setTimeout(e,t||0)}function ce(e){e.g=ae((()=>{e.g=null,e.i&&(e.i=!1,ce(e))}),e.l);const t=e.h;e.h=null,e.m.apply(null,t)}f(ie,M),ie.prototype[q]=!0,ie.prototype.removeEventListener=function(e,t,n,r){X(this,e,t,n,r)},ie.prototype.N=function(){if(ie.aa.N.call(this),this.i){var e,t=this.i;for(e in t.g){for(var n=t.g[e],r=0;r<n.length;r++)j(n[r]);delete t.g[e],t.h--}}this.F=null},ie.prototype.K=function(e,t,n,r){return this.i.add(String(e),t,!1,n,r)},ie.prototype.L=function(e,t,n,r){return this.i.add(String(e),t,!0,n,r)};class ue extends M{constructor(e,t){super(),this.m=e,this.l=t,this.h=null,this.i=!1,this.g=null}j(e){this.h=arguments,this.g?this.i=!0:ce(this)}N(){super.N(),this.g&&(o.clearTimeout(this.g),this.g=null,this.i=!1,this.h=null)}}function le(e){M.call(this),this.h=e,this.g={}}f(le,M);var he=[];function de(e){b(e.g,(function(e,t){this.g.hasOwnProperty(t)&&Y(e)}),e),e.g={}}le.prototype.N=function(){le.aa.N.call(this),de(this)},le.prototype.handleEvent=function(){throw Error("EventHandler.handleEvent not implemented")};var fe=o.JSON.stringify,ge=o.JSON.parse,pe=class{stringify(e){return o.JSON.stringify(e,void 0)}parse(e){return o.JSON.parse(e,void 0)}};function me(){}function ye(e){return e.h||(e.h=e.i())}function ve(){}me.prototype.h=null;var we={OPEN:"a",kb:"b",Ja:"c",wb:"d"};function be(){R.call(this,"d")}function _e(){R.call(this,"c")}f(be,R),f(_e,R);var Ie={},Ee=null;function Te(){return Ee=Ee||new ie}function Se(e){R.call(this,Ie.La,e)}function xe(e){const t=Te();se(t,new Se(t,e))}function Ce(e,t){R.call(this,Ie.STAT_EVENT,e),this.stat=t}function De(e){const t=Te();se(t,new Ce(t,e))}function Ae(e,t){R.call(this,Ie.Ma,e),this.size=t}function ke(e,t){if("function"!=typeof e)throw Error("Fn must not be null and must be a function");return o.setTimeout((function(){e()}),t)}function Ne(){this.g=!0}function Le(e,t,n,r){e.info((function(){return"XMLHTTP TEXT ("+t+"): "+function(e,t){if(!e.g)return t;if(!t)return null;try{var n=JSON.parse(t);if(n)for(e=0;e<n.length;e++)if(Array.isArray(n[e])){var r=n[e];if(!(2>r.length)){var i=r[1];if(Array.isArray(i)&&!(1>i.length)){var s=i[0];if("noop"!=s&&"stop"!=s&&"close"!=s)for(var o=1;o<i.length;o++)i[o]=""}}}return fe(n)}catch(e){return t}}(e,n)+(r?" "+r:"")}))}Ie.La="serverreachability",f(Se,R),Ie.STAT_EVENT="statevent",f(Ce,R),Ie.Ma="timingevent",f(Ae,R),Ne.prototype.xa=function(){this.g=!1},Ne.prototype.info=function(){};var Oe,Me={NO_ERROR:0,gb:1,tb:2,sb:3,nb:4,rb:5,ub:6,Ia:7,TIMEOUT:8,xb:9},Re={lb:"complete",Hb:"success",Ja:"error",Ia:"abort",zb:"ready",Ab:"readystatechange",TIMEOUT:"timeout",vb:"incrementaldata",yb:"progress",ob:"downloadprogress",Pb:"uploadprogress"};function Pe(){}function Fe(e,t,n,r){this.j=e,this.i=t,this.l=n,this.R=r||1,this.U=new le(this),this.I=45e3,this.H=null,this.o=!1,this.m=this.A=this.v=this.L=this.F=this.S=this.B=null,this.D=[],this.g=null,this.C=0,this.s=this.u=null,this.X=-1,this.J=!1,this.O=0,this.M=null,this.W=this.K=this.T=this.P=!1,this.h=new Ve}function Ve(){this.i=null,this.g="",this.h=!1}f(Pe,me),Pe.prototype.g=function(){return new XMLHttpRequest},Pe.prototype.i=function(){return{}},Oe=new Pe;var qe={},Be={};function Ue(e,t,n){e.L=1,e.v=ft(ct(t)),e.m=n,e.P=!0,je(e,null)}function je(e,t){e.F=Date.now(),Ge(e),e.A=ct(e.v);var n=e.A,r=e.R;Array.isArray(r)||(r=[String(r)]),Ct(n.i,"t",r),e.C=0,n=e.j.J,e.h=new Ve,e.g=pn(e.j,n?t:null,!e.m),0<e.O&&(e.M=new ue(h(e.Y,e,e.g),e.O)),t=e.U,n=e.g,r=e.ca;var i="readystatechange";Array.isArray(i)||(i&&(he[0]=i.toString()),i=he);for(var s=0;s<i.length;s++){var o=H(n,i[s],r||t.handleEvent,!1,t.h||t);if(!o)break;t.g[o.key]=o}t=e.H?_(e.H):{},e.m?(e.u||(e.u="POST"),t["Content-Type"]="application/x-www-form-urlencoded",e.g.ea(e.A,e.u,e.m,t)):(e.u="GET",e.g.ea(e.A,e.u,null,t)),xe(1),function(e,t,n,r,i,s){e.info((function(){if(e.g)if(s)for(var o="",a=s.split("&"),c=0;c<a.length;c++){var u=a[c].split("=");if(1<u.length){var l=u[0];u=u[1];var h=l.split("_");o=2<=h.length&&"type"==h[1]?o+(l+"=")+u+"&":o+(l+"=redacted&")}}else o=null;else o=s;return"XMLHTTP REQ ("+r+") [attempt "+i+"]: "+t+"\n"+n+"\n"+o}))}(e.i,e.u,e.A,e.l,e.R,e.m)}function $e(e){return!!e.g&&"GET"==e.u&&2!=e.L&&e.j.Ca}function ze(e,t){var n=e.C,r=t.indexOf("\n",n);return-1==r?Be:(n=Number(t.substring(n,r)),isNaN(n)?qe:(r+=1)+n>t.length?Be:(t=t.slice(r,r+n),e.C=r+n,t))}function Ge(e){e.S=Date.now()+e.I,Ke(e,e.I)}function Ke(e,t){if(null!=e.B)throw Error("WatchDog timer not null");e.B=ke(h(e.ba,e),t)}function Qe(e){e.B&&(o.clearTimeout(e.B),e.B=null)}function He(e){0==e.j.G||e.J||ln(e.j,e)}function We(e){Qe(e);var t=e.M;t&&"function"==typeof t.ma&&t.ma(),e.M=null,de(e.U),e.g&&(t=e.g,e.g=null,t.abort(),t.ma())}function Je(e,t){try{var n=e.j;if(0!=n.G&&(n.g==e||tt(n.h,e)))if(!e.K&&tt(n.h,e)&&3==n.G){try{var r=n.Da.g.parse(t)}catch(e){r=null}if(Array.isArray(r)&&3==r.length){var i=r;if(0==i[0]){e:if(!n.u){if(n.g){if(!(n.g.F+3e3<e.F))break e;un(n),Yt(n)}on(n),De(18)}}else n.za=i[1],0<n.za-n.T&&37500>i[2]&&n.F&&0==n.v&&!n.C&&(n.C=ke(h(n.Za,n),6e3));if(1>=et(n.h)&&n.ca){try{n.ca()}catch(e){}n.ca=void 0}}else dn(n,11)}else if((e.K||n.g==e)&&un(n),!m(t))for(i=n.Da.g.parse(t),t=0;t<i.length;t++){let u=i[t];if(n.T=u[0],u=u[1],2==n.G)if("c"==u[0]){n.K=u[1],n.ia=u[2];const t=u[3];null!=t&&(n.la=t,n.j.info("VER="+n.la));const i=u[4];null!=i&&(n.Aa=i,n.j.info("SVER="+n.Aa));const l=u[5];null!=l&&"number"==typeof l&&0<l&&(r=1.5*l,n.L=r,n.j.info("backChannelRequestTimeoutMs_="+r)),r=n;const h=e.g;if(h){const e=h.g?h.g.getResponseHeader("X-Client-Wire-Protocol"):null;if(e){var s=r.h;s.g||-1==e.indexOf("spdy")&&-1==e.indexOf("quic")&&-1==e.indexOf("h2")||(s.j=s.l,s.g=new Set,s.h&&(nt(s,s.h),s.h=null))}if(r.D){const e=h.g?h.g.getResponseHeader("X-HTTP-Session-Id"):null;e&&(r.ya=e,dt(r.I,r.D,e))}}n.G=3,n.l&&n.l.ua(),n.ba&&(n.R=Date.now()-e.F,n.j.info("Handshake RTT: "+n.R+"ms"));var o=e;if((r=n).qa=gn(r,r.J?r.ia:null,r.W),o.K){rt(r.h,o);var a=o,c=r.L;c&&(a.I=c),a.B&&(Qe(a),Ge(a)),r.g=o}else sn(r);0<n.i.length&&en(n)}else"stop"!=u[0]&&"close"!=u[0]||dn(n,7);else 3==n.G&&("stop"==u[0]||"close"==u[0]?"stop"==u[0]?dn(n,7):Xt(n):"noop"!=u[0]&&n.l&&n.l.ta(u),n.v=0)}xe(4)}catch(e){}}Fe.prototype.ca=function(e){e=e.target;const t=this.M;t&&3==Qt(e)?t.j():this.Y(e)},Fe.prototype.Y=function(e){try{if(e==this.g)e:{const d=Qt(this.g);var t=this.g.Ba();const f=this.g.Z();if(!(3>d)&&(3!=d||this.g&&(this.h.h||this.g.oa()||Ht(this.g)))){this.J||4!=d||7==t||xe(8==t||0>=f?3:2),Qe(this);var n=this.g.Z();this.X=n;t:if($e(this)){var r=Ht(this.g);e="";var i=r.length,s=4==Qt(this.g);if(!this.h.i){if("undefined"==typeof TextDecoder){We(this),He(this);var a="";break t}this.h.i=new o.TextDecoder}for(t=0;t<i;t++)this.h.h=!0,e+=this.h.i.decode(r[t],{stream:!(s&&t==i-1)});r.length=0,this.h.g+=e,this.C=0,a=this.h.g}else a=this.g.oa();if(this.o=200==n,function(e,t,n,r,i,s,o){e.info((function(){return"XMLHTTP RESP ("+r+") [ attempt "+i+"]: "+t+"\n"+n+"\n"+s+" "+o}))}(this.i,this.u,this.A,this.l,this.R,d,n),this.o){if(this.T&&!this.K){t:{if(this.g){var c,u=this.g;if((c=u.g?u.g.getResponseHeader("X-HTTP-Initial-Response"):null)&&!m(c)){var l=c;break t}}l=null}if(!(n=l)){this.o=!1,this.s=3,De(12),We(this),He(this);break e}Le(this.i,this.l,n,"Initial handshake response via X-HTTP-Initial-Response"),this.K=!0,Je(this,n)}if(this.P){let e;for(n=!0;!this.J&&this.C<a.length;){if(e=ze(this,a),e==Be){4==d&&(this.s=4,De(14),n=!1),Le(this.i,this.l,null,"[Incomplete Response]");break}if(e==qe){this.s=4,De(15),Le(this.i,this.l,a,"[Invalid Chunk]"),n=!1;break}Le(this.i,this.l,e,null),Je(this,e)}if($e(this)&&0!=this.C&&(this.h.g=this.h.g.slice(this.C),this.C=0),4!=d||0!=a.length||this.h.h||(this.s=1,De(16),n=!1),this.o=this.o&&n,n){if(0<a.length&&!this.W){this.W=!0;var h=this.j;h.g==this&&h.ba&&!h.M&&(h.j.info("Great, no buffering proxy detected. Bytes received: "+a.length),an(h),h.M=!0,De(11))}}else Le(this.i,this.l,a,"[Invalid Chunked Response]"),We(this),He(this)}else Le(this.i,this.l,a,null),Je(this,a);4==d&&We(this),this.o&&!this.J&&(4==d?ln(this.j,this):(this.o=!1,Ge(this)))}else(function(e){const t={};e=(e.g&&2<=Qt(e)&&e.g.getAllResponseHeaders()||"").split("\r\n");for(let r=0;r<e.length;r++){if(m(e[r]))continue;var n=T(e[r]);const i=n[0];if("string"!=typeof(n=n[1]))continue;n=n.trim();const s=t[i]||[];t[i]=s,s.push(n)}!function(e,t){for(const n in e)t.call(void 0,e[n],n,e)}(t,(function(e){return e.join(", ")}))})(this.g),400==n&&0<a.indexOf("Unknown SID")?(this.s=3,De(12)):(this.s=0,De(13)),We(this),He(this)}}}catch(e){}},Fe.prototype.cancel=function(){this.J=!0,We(this)},Fe.prototype.ba=function(){this.B=null;const e=Date.now();0<=e-this.S?(function(e,t){e.info((function(){return"TIMEOUT: "+t}))}(this.i,this.A),2!=this.L&&(xe(3),De(17)),We(this),this.s=2,He(this)):Ke(this,this.S-e)};var Xe=class{constructor(e,t){this.g=e,this.map=t}};function Ye(e){this.l=e||10,e=o.PerformanceNavigationTiming?0<(e=o.performance.getEntriesByType("navigation")).length&&("hq"==e[0].nextHopProtocol||"h2"==e[0].nextHopProtocol):!!(o.chrome&&o.chrome.loadTimes&&o.chrome.loadTimes()&&o.chrome.loadTimes().wasFetchedViaSpdy),this.j=e?this.l:1,this.g=null,1<this.j&&(this.g=new Set),this.h=null,this.i=[]}function Ze(e){return!!e.h||!!e.g&&e.g.size>=e.j}function et(e){return e.h?1:e.g?e.g.size:0}function tt(e,t){return e.h?e.h==t:!!e.g&&e.g.has(t)}function nt(e,t){e.g?e.g.add(t):e.h=t}function rt(e,t){e.h&&e.h==t?e.h=null:e.g&&e.g.has(t)&&e.g.delete(t)}function it(e){if(null!=e.h)return e.i.concat(e.h.D);if(null!=e.g&&0!==e.g.size){let t=e.i;for(const n of e.g.values())t=t.concat(n.D);return t}return g(e.i)}function st(e,t){if(e.forEach&&"function"==typeof e.forEach)e.forEach(t,void 0);else if(a(e)||"string"==typeof e)Array.prototype.forEach.call(e,t,void 0);else for(var n=function(e){if(e.na&&"function"==typeof e.na)return e.na();if(!e.V||"function"!=typeof e.V){if("undefined"!=typeof Map&&e instanceof Map)return Array.from(e.keys());if(!("undefined"!=typeof Set&&e instanceof Set)){if(a(e)||"string"==typeof e){var t=[];e=e.length;for(var n=0;n<e;n++)t.push(n);return t}t=[],n=0;for(const r in e)t[n++]=r;return t}}}(e),r=function(e){if(e.V&&"function"==typeof e.V)return e.V();if("undefined"!=typeof Map&&e instanceof Map||"undefined"!=typeof Set&&e instanceof Set)return Array.from(e.values());if("string"==typeof e)return e.split("");if(a(e)){for(var t=[],n=e.length,r=0;r<n;r++)t.push(e[r]);return t}for(r in t=[],n=0,e)t[n++]=e[r];return t}(e),i=r.length,s=0;s<i;s++)t.call(void 0,r[s],n&&n[s],e)}Ye.prototype.cancel=function(){if(this.i=it(this),this.h)this.h.cancel(),this.h=null;else if(this.g&&0!==this.g.size){for(const e of this.g.values())e.cancel();this.g.clear()}};var ot=RegExp("^(?:([^:/?#.]+):)?(?://(?:([^\\\\/?#]*)@)?([^\\\\/?#]*?)(?::([0-9]+))?(?=[\\\\/?#]|$))?([^?#]+)?(?:\\?([^#]*))?(?:#([\\s\\S]*))?$");function at(e){if(this.g=this.o=this.j="",this.s=null,this.m=this.l="",this.h=!1,e instanceof at){this.h=e.h,ut(this,e.j),this.o=e.o,this.g=e.g,lt(this,e.s),this.l=e.l;var t=e.i,n=new Et;n.i=t.i,t.g&&(n.g=new Map(t.g),n.h=t.h),ht(this,n),this.m=e.m}else e&&(t=String(e).match(ot))?(this.h=!1,ut(this,t[1]||"",!0),this.o=gt(t[2]||""),this.g=gt(t[3]||"",!0),lt(this,t[4]),this.l=gt(t[5]||"",!0),ht(this,t[6]||"",!0),this.m=gt(t[7]||"")):(this.h=!1,this.i=new Et(null,this.h))}function ct(e){return new at(e)}function ut(e,t,n){e.j=n?gt(t,!0):t,e.j&&(e.j=e.j.replace(/:$/,""))}function lt(e,t){if(t){if(t=Number(t),isNaN(t)||0>t)throw Error("Bad port number "+t);e.s=t}else e.s=null}function ht(e,t,n){t instanceof Et?(e.i=t,function(e,t){t&&!e.j&&(Tt(e),e.i=null,e.g.forEach((function(e,t){var n=t.toLowerCase();t!=n&&(St(this,t),Ct(this,n,e))}),e)),e.j=t}(e.i,e.h)):(n||(t=pt(t,_t)),e.i=new Et(t,e.h))}function dt(e,t,n){e.i.set(t,n)}function ft(e){return dt(e,"zx",Math.floor(2147483648*Math.random()).toString(36)+Math.abs(Math.floor(2147483648*Math.random())^Date.now()).toString(36)),e}function gt(e,t){return e?t?decodeURI(e.replace(/%25/g,"%2525")):decodeURIComponent(e):""}function pt(e,t,n){return"string"==typeof e?(e=encodeURI(e).replace(t,mt),n&&(e=e.replace(/%25([0-9a-fA-F]{2})/g,"%$1")),e):null}function mt(e){return"%"+((e=e.charCodeAt(0))>>4&15).toString(16)+(15&e).toString(16)}at.prototype.toString=function(){var e=[],t=this.j;t&&e.push(pt(t,vt,!0),":");var n=this.g;return(n||"file"==t)&&(e.push("//"),(t=this.o)&&e.push(pt(t,vt,!0),"@"),e.push(encodeURIComponent(String(n)).replace(/%25([0-9a-fA-F]{2})/g,"%$1")),null!=(n=this.s)&&e.push(":",String(n))),(n=this.l)&&(this.g&&"/"!=n.charAt(0)&&e.push("/"),e.push(pt(n,"/"==n.charAt(0)?bt:wt,!0))),(n=this.i.toString())&&e.push("?",n),(n=this.m)&&e.push("#",pt(n,It)),e.join("")};var yt,vt=/[#\/\?@]/g,wt=/[#\?:]/g,bt=/[#\?]/g,_t=/[#\?@]/g,It=/#/g;function Et(e,t){this.h=this.g=null,this.i=e||null,this.j=!!t}function Tt(e){e.g||(e.g=new Map,e.h=0,e.i&&function(e,t){if(e){e=e.split("&");for(var n=0;n<e.length;n++){var r=e[n].indexOf("="),i=null;if(0<=r){var s=e[n].substring(0,r);i=e[n].substring(r+1)}else s=e[n];t(s,i?decodeURIComponent(i.replace(/\+/g," ")):"")}}}(e.i,(function(t,n){e.add(decodeURIComponent(t.replace(/\+/g," ")),n)})))}function St(e,t){Tt(e),t=Dt(e,t),e.g.has(t)&&(e.i=null,e.h-=e.g.get(t).length,e.g.delete(t))}function xt(e,t){return Tt(e),t=Dt(e,t),e.g.has(t)}function Ct(e,t,n){St(e,t),0<n.length&&(e.i=null,e.g.set(Dt(e,t),g(n)),e.h+=n.length)}function Dt(e,t){return t=String(t),e.j&&(t=t.toLowerCase()),t}function At(e,t,n,r,i){try{i&&(i.onload=null,i.onerror=null,i.onabort=null,i.ontimeout=null),r(n)}catch(e){}}function kt(){this.g=new pe}function Nt(e,t,n){const r=n||"";try{st(e,(function(e,n){let i=e;c(e)&&(i=fe(e)),t.push(r+n+"="+encodeURIComponent(i))}))}catch(e){throw t.push(r+"type="+encodeURIComponent("_badmap")),e}}function Lt(e){this.l=e.Ub||null,this.j=e.eb||!1}function Ot(e,t){ie.call(this),this.D=e,this.o=t,this.m=void 0,this.status=this.readyState=0,this.responseType=this.responseText=this.response=this.statusText="",this.onreadystatechange=null,this.u=new Headers,this.h=null,this.B="GET",this.A="",this.g=!1,this.v=this.j=this.l=null}function Mt(e){e.j.read().then(e.Pa.bind(e)).catch(e.ga.bind(e))}function Rt(e){e.readyState=4,e.l=null,e.j=null,e.v=null,Pt(e)}function Pt(e){e.onreadystatechange&&e.onreadystatechange.call(e)}function Ft(e){let t="";return b(e,(function(e,n){t+=n,t+=":",t+=e,t+="\r\n"})),t}function Vt(e,t,n){e:{for(r in n){var r=!1;break e}r=!0}r||(n=Ft(n),"string"==typeof e?(encodeURIComponent(String(t)),null!=n&&encodeURIComponent(String(n))):dt(e,t,n))}function qt(e){ie.call(this),this.headers=new Map,this.o=e||null,this.h=!1,this.v=this.g=null,this.D="",this.m=0,this.l="",this.j=this.B=this.u=this.A=!1,this.I=null,this.H="",this.J=!1}(t=Et.prototype).add=function(e,t){Tt(this),this.i=null,e=Dt(this,e);var n=this.g.get(e);return n||this.g.set(e,n=[]),n.push(t),this.h+=1,this},t.forEach=function(e,t){Tt(this),this.g.forEach((function(n,r){n.forEach((function(n){e.call(t,n,r,this)}),this)}),this)},t.na=function(){Tt(this);const e=Array.from(this.g.values()),t=Array.from(this.g.keys()),n=[];for(let r=0;r<t.length;r++){const i=e[r];for(let e=0;e<i.length;e++)n.push(t[r])}return n},t.V=function(e){Tt(this);let t=[];if("string"==typeof e)xt(this,e)&&(t=t.concat(this.g.get(Dt(this,e))));else{e=Array.from(this.g.values());for(let n=0;n<e.length;n++)t=t.concat(e[n])}return t},t.set=function(e,t){return Tt(this),this.i=null,xt(this,e=Dt(this,e))&&(this.h-=this.g.get(e).length),this.g.set(e,[t]),this.h+=1,this},t.get=function(e,t){return e&&0<(e=this.V(e)).length?String(e[0]):t},t.toString=function(){if(this.i)return this.i;if(!this.g)return"";const e=[],t=Array.from(this.g.keys());for(var n=0;n<t.length;n++){var r=t[n];const s=encodeURIComponent(String(r)),o=this.V(r);for(r=0;r<o.length;r++){var i=s;""!==o[r]&&(i+="="+encodeURIComponent(String(o[r]))),e.push(i)}}return this.i=e.join("&")},f(Lt,me),Lt.prototype.g=function(){return new Ot(this.l,this.j)},Lt.prototype.i=(yt={},function(){return yt}),f(Ot,ie),(t=Ot.prototype).open=function(e,t){if(0!=this.readyState)throw this.abort(),Error("Error reopening a connection");this.B=e,this.A=t,this.readyState=1,Pt(this)},t.send=function(e){if(1!=this.readyState)throw this.abort(),Error("need to call open() first. ");this.g=!0;const t={headers:this.u,method:this.B,credentials:this.m,cache:void 0};e&&(t.body=e),(this.D||o).fetch(new Request(this.A,t)).then(this.Sa.bind(this),this.ga.bind(this))},t.abort=function(){this.response=this.responseText="",this.u=new Headers,this.status=0,this.j&&this.j.cancel("Request was aborted.").catch((()=>{})),1<=this.readyState&&this.g&&4!=this.readyState&&(this.g=!1,Rt(this)),this.readyState=0},t.Sa=function(e){if(this.g&&(this.l=e,this.h||(this.status=this.l.status,this.statusText=this.l.statusText,this.h=e.headers,this.readyState=2,Pt(this)),this.g&&(this.readyState=3,Pt(this),this.g)))if("arraybuffer"===this.responseType)e.arrayBuffer().then(this.Qa.bind(this),this.ga.bind(this));else if(void 0!==o.ReadableStream&&"body"in e){if(this.j=e.body.getReader(),this.o){if(this.responseType)throw Error('responseType must be empty for "streamBinaryChunks" mode responses.');this.response=[]}else this.response=this.responseText="",this.v=new TextDecoder;Mt(this)}else e.text().then(this.Ra.bind(this),this.ga.bind(this))},t.Pa=function(e){if(this.g){if(this.o&&e.value)this.response.push(e.value);else if(!this.o){var t=e.value?e.value:new Uint8Array(0);(t=this.v.decode(t,{stream:!e.done}))&&(this.response=this.responseText+=t)}e.done?Rt(this):Pt(this),3==this.readyState&&Mt(this)}},t.Ra=function(e){this.g&&(this.response=this.responseText=e,Rt(this))},t.Qa=function(e){this.g&&(this.response=e,Rt(this))},t.ga=function(){this.g&&Rt(this)},t.setRequestHeader=function(e,t){this.u.append(e,t)},t.getResponseHeader=function(e){return this.h&&this.h.get(e.toLowerCase())||""},t.getAllResponseHeaders=function(){if(!this.h)return"";const e=[],t=this.h.entries();for(var n=t.next();!n.done;)n=n.value,e.push(n[0]+": "+n[1]),n=t.next();return e.join("\r\n")},Object.defineProperty(Ot.prototype,"withCredentials",{get:function(){return"include"===this.m},set:function(e){this.m=e?"include":"same-origin"}}),f(qt,ie);var Bt=/^https?$/i,Ut=["POST","PUT"];function jt(e,t){e.h=!1,e.g&&(e.j=!0,e.g.abort(),e.j=!1),e.l=t,e.m=5,$t(e),Gt(e)}function $t(e){e.A||(e.A=!0,se(e,"complete"),se(e,"error"))}function zt(e){if(e.h&&void 0!==s&&(!e.v[1]||4!=Qt(e)||2!=e.Z()))if(e.u&&4==Qt(e))ae(e.Ea,0,e);else if(se(e,"readystatechange"),4==Qt(e)){e.h=!1;try{const s=e.Z();e:switch(s){case 200:case 201:case 202:case 204:case 206:case 304:case 1223:var t=!0;break e;default:t=!1}var n;if(!(n=t)){var r;if(r=0===s){var i=String(e.D).match(ot)[1]||null;!i&&o.self&&o.self.location&&(i=o.self.location.protocol.slice(0,-1)),r=!Bt.test(i?i.toLowerCase():"")}n=r}if(n)se(e,"complete"),se(e,"success");else{e.m=6;try{var a=2<Qt(e)?e.g.statusText:""}catch(e){a=""}e.l=a+" ["+e.Z()+"]",$t(e)}}finally{Gt(e)}}}function Gt(e,t){if(e.g){Kt(e);const n=e.g,r=e.v[0]?()=>{}:null;e.g=null,e.v=null,t||se(e,"ready");try{n.onreadystatechange=r}catch(e){}}}function Kt(e){e.I&&(o.clearTimeout(e.I),e.I=null)}function Qt(e){return e.g?e.g.readyState:0}function Ht(e){try{if(!e.g)return null;if("response"in e.g)return e.g.response;switch(e.H){case"":case"text":return e.g.responseText;case"arraybuffer":if("mozResponseArrayBuffer"in e.g)return e.g.mozResponseArrayBuffer}return null}catch(e){return null}}function Wt(e,t,n){return n&&n.internalChannelParams&&n.internalChannelParams[e]||t}function Jt(e){this.Aa=0,this.i=[],this.j=new Ne,this.ia=this.qa=this.I=this.W=this.g=this.ya=this.D=this.H=this.m=this.S=this.o=null,this.Ya=this.U=0,this.Va=Wt("failFast",!1,e),this.F=this.C=this.u=this.s=this.l=null,this.X=!0,this.za=this.T=-1,this.Y=this.v=this.B=0,this.Ta=Wt("baseRetryDelayMs",5e3,e),this.cb=Wt("retryDelaySeedMs",1e4,e),this.Wa=Wt("forwardChannelMaxRetries",2,e),this.wa=Wt("forwardChannelRequestTimeoutMs",2e4,e),this.pa=e&&e.xmlHttpFactory||void 0,this.Xa=e&&e.Tb||void 0,this.Ca=e&&e.useFetchStreams||!1,this.L=void 0,this.J=e&&e.supportsCrossDomainXhr||!1,this.K="",this.h=new Ye(e&&e.concurrentRequestLimit),this.Da=new kt,this.P=e&&e.fastHandshake||!1,this.O=e&&e.encodeInitMessageHeaders||!1,this.P&&this.O&&(this.O=!1),this.Ua=e&&e.Rb||!1,e&&e.xa&&this.j.xa(),e&&e.forceLongPolling&&(this.X=!1),this.ba=!this.P&&this.X&&e&&e.detectBufferingProxy||!1,this.ja=void 0,e&&e.longPollingTimeout&&0<e.longPollingTimeout&&(this.ja=e.longPollingTimeout),this.ca=void 0,this.R=0,this.M=!1,this.ka=this.A=null}function Xt(e){if(Zt(e),3==e.G){var t=e.U++,n=ct(e.I);if(dt(n,"SID",e.K),dt(n,"RID",t),dt(n,"TYPE","terminate"),nn(e,n),(t=new Fe(e,e.j,t)).L=2,t.v=ft(ct(n)),n=!1,o.navigator&&o.navigator.sendBeacon)try{n=o.navigator.sendBeacon(t.v.toString(),"")}catch(e){}!n&&o.Image&&((new Image).src=t.v,n=!0),n||(t.g=pn(t.j,null),t.g.ea(t.v)),t.F=Date.now(),Ge(t)}fn(e)}function Yt(e){e.g&&(an(e),e.g.cancel(),e.g=null)}function Zt(e){Yt(e),e.u&&(o.clearTimeout(e.u),e.u=null),un(e),e.h.cancel(),e.s&&("number"==typeof e.s&&o.clearTimeout(e.s),e.s=null)}function en(e){if(!Ze(e.h)&&!e.s){e.s=!0;var t=e.Ga;A||L(),k||(A(),k=!0),N.add(t,e),e.B=0}}function tn(e,t){var n;n=t?t.l:e.U++;const r=ct(e.I);dt(r,"SID",e.K),dt(r,"RID",n),dt(r,"AID",e.T),nn(e,r),e.m&&e.o&&Vt(r,e.m,e.o),n=new Fe(e,e.j,n,e.B+1),null===e.m&&(n.H=e.o),t&&(e.i=t.D.concat(e.i)),t=rn(e,n,1e3),n.I=Math.round(.5*e.wa)+Math.round(.5*e.wa*Math.random()),nt(e.h,n),Ue(n,r,t)}function nn(e,t){e.H&&b(e.H,(function(e,n){dt(t,n,e)})),e.l&&st({},(function(e,n){dt(t,n,e)}))}function rn(e,t,n){n=Math.min(e.i.length,n);var r=e.l?h(e.l.Na,e.l,e):null;e:{var i=e.i;let t=-1;for(;;){const e=["count="+n];-1==t?0<n?(t=i[0].g,e.push("ofs="+t)):t=0:e.push("ofs="+t);let s=!0;for(let o=0;o<n;o++){let n=i[o].g;const a=i[o].map;if(n-=t,0>n)t=Math.max(0,i[o].g-100),s=!1;else try{Nt(a,e,"req"+n+"_")}catch(e){r&&r(a)}}if(s){r=e.join("&");break e}}}return e=e.i.splice(0,n),t.D=e,r}function sn(e){if(!e.g&&!e.u){e.Y=1;var t=e.Fa;A||L(),k||(A(),k=!0),N.add(t,e),e.v=0}}function on(e){return!(e.g||e.u||3<=e.v||(e.Y++,e.u=ke(h(e.Fa,e),hn(e,e.v)),e.v++,0))}function an(e){null!=e.A&&(o.clearTimeout(e.A),e.A=null)}function cn(e){e.g=new Fe(e,e.j,"rpc",e.Y),null===e.m&&(e.g.H=e.o),e.g.O=0;var t=ct(e.qa);dt(t,"RID","rpc"),dt(t,"SID",e.K),dt(t,"AID",e.T),dt(t,"CI",e.F?"0":"1"),!e.F&&e.ja&&dt(t,"TO",e.ja),dt(t,"TYPE","xmlhttp"),nn(e,t),e.m&&e.o&&Vt(t,e.m,e.o),e.L&&(e.g.I=e.L);var n=e.g;e=e.ia,n.L=1,n.v=ft(ct(t)),n.m=null,n.P=!0,je(n,e)}function un(e){null!=e.C&&(o.clearTimeout(e.C),e.C=null)}function ln(e,t){var n=null;if(e.g==t){un(e),an(e),e.g=null;var r=2}else{if(!tt(e.h,t))return;n=t.D,rt(e.h,t),r=1}if(0!=e.G)if(t.o)if(1==r){n=t.m?t.m.length:0,t=Date.now()-t.F;var i=e.B;se(r=Te(),new Ae(r,n,t,i)),en(e)}else sn(e);else if(3==(i=t.s)||0==i&&0<t.X||!(1==r&&function(e,t){return!(et(e.h)>=e.h.j-(e.s?1:0)||(e.s?(e.i=t.D.concat(e.i),0):1==e.G||2==e.G||e.B>=(e.Va?0:e.Wa)||(e.s=ke(h(e.Ga,e,t),hn(e,e.B)),e.B++,0)))}(e,t)||2==r&&on(e)))switch(n&&0<n.length&&(t=e.h,t.i=t.i.concat(n)),i){case 1:dn(e,5);break;case 4:dn(e,10);break;case 3:dn(e,6);break;default:dn(e,2)}}function hn(e,t){let n=e.Ta+Math.floor(Math.random()*e.cb);return e.isActive()||(n*=2),n*t}function dn(e,t){if(e.j.info("Error code "+t),2==t){var n=h(e.fb,e),r=e.Xa;const t=!r;r=new at(r||"//www.google.com/images/cleardot.gif"),o.location&&"http"==o.location.protocol||ut(r,"https"),ft(r),t?function(e,t){const n=new Ne;if(o.Image){const r=new Image;r.onload=d(At,n,"TestLoadImage: loaded",!0,t,r),r.onerror=d(At,n,"TestLoadImage: error",!1,t,r),r.onabort=d(At,n,"TestLoadImage: abort",!1,t,r),r.ontimeout=d(At,n,"TestLoadImage: timeout",!1,t,r),o.setTimeout((function(){r.ontimeout&&r.ontimeout()}),1e4),r.src=e}else t(!1)}(r.toString(),n):function(e,t){new Ne;const n=new AbortController,r=setTimeout((()=>{n.abort(),At(0,0,!1,t)}),1e4);fetch(e,{signal:n.signal}).then((e=>{clearTimeout(r),e.ok?At(0,0,!0,t):At(0,0,!1,t)})).catch((()=>{clearTimeout(r),At(0,0,!1,t)}))}(r.toString(),n)}else De(2);e.G=0,e.l&&e.l.sa(t),fn(e),Zt(e)}function fn(e){if(e.G=0,e.ka=[],e.l){const t=it(e.h);0==t.length&&0==e.i.length||(p(e.ka,t),p(e.ka,e.i),e.h.i.length=0,g(e.i),e.i.length=0),e.l.ra()}}function gn(e,t,n){var r=n instanceof at?ct(n):new at(n);if(""!=r.g)t&&(r.g=t+"."+r.g),lt(r,r.s);else{var i=o.location;r=i.protocol,t=t?t+"."+i.hostname:i.hostname,i=+i.port;var s=new at(null);r&&ut(s,r),t&&(s.g=t),i&&lt(s,i),n&&(s.l=n),r=s}return n=e.D,t=e.ya,n&&t&&dt(r,n,t),dt(r,"VER",e.la),nn(e,r),r}function pn(e,t,n){if(t&&!e.J)throw Error("Can't create secondary domain capable XhrIo object.");return(t=e.Ca&&!e.pa?new qt(new Lt({eb:n})):new qt(e.pa)).Ha(e.J),t}function mn(){}function yn(){}function vn(e,t){ie.call(this),this.g=new Jt(t),this.l=e,this.h=t&&t.messageUrlParams||null,e=t&&t.messageHeaders||null,t&&t.clientProtocolHeaderRequired&&(e?e["X-Client-Protocol"]="webchannel":e={"X-Client-Protocol":"webchannel"}),this.g.o=e,e=t&&t.initMessageHeaders||null,t&&t.messageContentType&&(e?e["X-WebChannel-Content-Type"]=t.messageContentType:e={"X-WebChannel-Content-Type":t.messageContentType}),t&&t.va&&(e?e["X-WebChannel-Client-Profile"]=t.va:e={"X-WebChannel-Client-Profile":t.va}),this.g.S=e,(e=t&&t.Sb)&&!m(e)&&(this.g.m=e),this.v=t&&t.supportsCrossDomainXhr||!1,this.u=t&&t.sendRawJson||!1,(t=t&&t.httpSessionIdParam)&&!m(t)&&(this.g.D=t,null!==(e=this.h)&&t in e&&t in(e=this.h)&&delete e[t]),this.j=new _n(this)}function wn(e){be.call(this),e.__headers__&&(this.headers=e.__headers__,this.statusCode=e.__status__,delete e.__headers__,delete e.__status__);var t=e.__sm__;if(t){e:{for(const n in t){e=n;break e}e=void 0}(this.i=e)&&(e=this.i,t=null!==t&&e in t?t[e]:void 0),this.data=t}else this.data=e}function bn(){_e.call(this),this.status=1}function _n(e){this.g=e}(t=qt.prototype).Ha=function(e){this.J=e},t.ea=function(e,t,n,r){if(this.g)throw Error("[goog.net.XhrIo] Object is active with another request="+this.D+"; newUri="+e);t=t?t.toUpperCase():"GET",this.D=e,this.l="",this.m=0,this.A=!1,this.h=!0,this.g=this.o?this.o.g():Oe.g(),this.v=this.o?ye(this.o):ye(Oe),this.g.onreadystatechange=h(this.Ea,this);try{this.B=!0,this.g.open(t,String(e),!0),this.B=!1}catch(e){return void jt(this,e)}if(e=n||"",n=new Map(this.headers),r)if(Object.getPrototypeOf(r)===Object.prototype)for(var i in r)n.set(i,r[i]);else{if("function"!=typeof r.keys||"function"!=typeof r.get)throw Error("Unknown input type for opt_headers: "+String(r));for(const e of r.keys())n.set(e,r.get(e))}r=Array.from(n.keys()).find((e=>"content-type"==e.toLowerCase())),i=o.FormData&&e instanceof o.FormData,!(0<=Array.prototype.indexOf.call(Ut,t,void 0))||r||i||n.set("Content-Type","application/x-www-form-urlencoded;charset=utf-8");for(const[e,t]of n)this.g.setRequestHeader(e,t);this.H&&(this.g.responseType=this.H),"withCredentials"in this.g&&this.g.withCredentials!==this.J&&(this.g.withCredentials=this.J);try{Kt(this),this.u=!0,this.g.send(e),this.u=!1}catch(e){jt(this,e)}},t.abort=function(e){this.g&&this.h&&(this.h=!1,this.j=!0,this.g.abort(),this.j=!1,this.m=e||7,se(this,"complete"),se(this,"abort"),Gt(this))},t.N=function(){this.g&&(this.h&&(this.h=!1,this.j=!0,this.g.abort(),this.j=!1),Gt(this,!0)),qt.aa.N.call(this)},t.Ea=function(){this.s||(this.B||this.u||this.j?zt(this):this.bb())},t.bb=function(){zt(this)},t.isActive=function(){return!!this.g},t.Z=function(){try{return 2<Qt(this)?this.g.status:-1}catch(e){return-1}},t.oa=function(){try{return this.g?this.g.responseText:""}catch(e){return""}},t.Oa=function(e){if(this.g){var t=this.g.responseText;return e&&0==t.indexOf(e)&&(t=t.substring(e.length)),ge(t)}},t.Ba=function(){return this.m},t.Ka=function(){return"string"==typeof this.l?this.l:String(this.l)},(t=Jt.prototype).la=8,t.G=1,t.connect=function(e,t,n,r){De(0),this.W=e,this.H=t||{},n&&void 0!==r&&(this.H.OSID=n,this.H.OAID=r),this.F=this.X,this.I=gn(this,null,this.W),en(this)},t.Ga=function(e){if(this.s)if(this.s=null,1==this.G){if(!e){this.U=Math.floor(1e5*Math.random()),e=this.U++;const i=new Fe(this,this.j,e);let s=this.o;if(this.S&&(s?(s=_(s),E(s,this.S)):s=this.S),null!==this.m||this.O||(i.H=s,s=null),this.P)e:{for(var t=0,n=0;n<this.i.length;n++){var r=this.i[n];if(void 0===(r="__data__"in r.map&&"string"==typeof(r=r.map.__data__)?r.length:void 0))break;if(4096<(t+=r)){t=n;break e}if(4096===t||n===this.i.length-1){t=n+1;break e}}t=1e3}else t=1e3;t=rn(this,i,t),dt(n=ct(this.I),"RID",e),dt(n,"CVER",22),this.D&&dt(n,"X-HTTP-Session-Id",this.D),nn(this,n),s&&(this.O?t="headers="+encodeURIComponent(String(Ft(s)))+"&"+t:this.m&&Vt(n,this.m,s)),nt(this.h,i),this.Ua&&dt(n,"TYPE","init"),this.P?(dt(n,"$req",t),dt(n,"SID","null"),i.T=!0,Ue(i,n,null)):Ue(i,n,t),this.G=2}}else 3==this.G&&(e?tn(this,e):0==this.i.length||Ze(this.h)||tn(this))},t.Fa=function(){if(this.u=null,cn(this),this.ba&&!(this.M||null==this.g||0>=this.R)){var e=2*this.R;this.j.info("BP detection timer enabled: "+e),this.A=ke(h(this.ab,this),e)}},t.ab=function(){this.A&&(this.A=null,this.j.info("BP detection timeout reached."),this.j.info("Buffering proxy detected and switch to long-polling!"),this.F=!1,this.M=!0,De(10),Yt(this),cn(this))},t.Za=function(){null!=this.C&&(this.C=null,Yt(this),on(this),De(19))},t.fb=function(e){e?(this.j.info("Successfully pinged google.com"),De(2)):(this.j.info("Failed to ping google.com"),De(1))},t.isActive=function(){return!!this.l&&this.l.isActive(this)},(t=mn.prototype).ua=function(){},t.ta=function(){},t.sa=function(){},t.ra=function(){},t.isActive=function(){return!0},t.Na=function(){},yn.prototype.g=function(e,t){return new vn(e,t)},f(vn,ie),vn.prototype.m=function(){this.g.l=this.j,this.v&&(this.g.J=!0),this.g.connect(this.l,this.h||void 0)},vn.prototype.close=function(){Xt(this.g)},vn.prototype.o=function(e){var t=this.g;if("string"==typeof e){var n={};n.__data__=e,e=n}else this.u&&((n={}).__data__=fe(e),e=n);t.i.push(new Xe(t.Ya++,e)),3==t.G&&en(t)},vn.prototype.N=function(){this.g.l=null,delete this.j,Xt(this.g),delete this.g,vn.aa.N.call(this)},f(wn,be),f(bn,_e),f(_n,mn),_n.prototype.ua=function(){se(this.g,"a")},_n.prototype.ta=function(e){se(this.g,new wn(e))},_n.prototype.sa=function(e){se(this.g,new bn(e))},_n.prototype.ra=function(){se(this.g,"b")},yn.prototype.createWebChannel=yn.prototype.g,vn.prototype.send=vn.prototype.o,vn.prototype.open=vn.prototype.m,vn.prototype.close=vn.prototype.close,e.exports.createWebChannelTransport=function(){return new yn},e.exports.getStatEventTarget=function(){return Te()},e.exports.Event=Ie,e.exports.Stat={mb:0,pb:1,qb:2,Jb:3,Ob:4,Lb:5,Mb:6,Kb:7,Ib:8,Nb:9,PROXY:10,NOPROXY:11,Gb:12,Cb:13,Db:14,Bb:15,Eb:16,Fb:17,ib:18,hb:19,jb:20},Me.NO_ERROR=0,Me.TIMEOUT=8,Me.HTTP_ERROR=6,e.exports.ErrorCode=Me,Re.COMPLETE="complete",e.exports.EventType=Re,ve.EventType=we,we.OPEN="a",we.CLOSE="b",we.ERROR="c",we.MESSAGE="d",ie.prototype.listen=ie.prototype.K,e.exports.WebChannel=ve,e.exports.FetchXmlHttpFactory=Lt,qt.prototype.listenOnce=qt.prototype.L,qt.prototype.getLastError=qt.prototype.Ka,qt.prototype.getLastErrorCode=qt.prototype.Ba,qt.prototype.getStatus=qt.prototype.Z,qt.prototype.getResponseJson=qt.prototype.Oa,qt.prototype.getResponseText=qt.prototype.oa,qt.prototype.send=qt.prototype.ea,qt.prototype.setWithCredentials=qt.prototype.Ha,e.exports.XhrIo=qt}).apply(void 0!==n.g?n.g:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},577:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(199);r.registerVersion("firebase","11.1.0","app"),Object.keys(r).forEach((function(e){"default"===e||t.hasOwnProperty(e)||Object.defineProperty(t,e,{enumerable:!0,get:function(){return r[e]}})}))},815:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(241);Object.keys(r).forEach((function(e){"default"===e||t.hasOwnProperty(e)||Object.defineProperty(t,e,{enumerable:!0,get:function(){return r[e]}})}))},619:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(249);Object.keys(r).forEach((function(e){"default"===e||t.hasOwnProperty(e)||Object.defineProperty(t,e,{enumerable:!0,get:function(){return r[e]}})}))},264:(e,t,n)=>{"use strict";n.r(t)},846:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.initCalculator=function(e,t){e.innerHTML=`\n <div class="mortgage-calculator">\n <div class="section-heading"><span>Mortgage</span> Payment <span>Calculator</span></div>\n <div class="calculator-fields">\n <div class="mortgage-amount-wrapper">\n <div class="calculator-floating-label-field">\n <label>Mortgage Amount</label>\n <input type="text" id="mortgage-amount-field" />\n </div>\n </div>\n <div class="rate-amortization-period-wrapper">\n <div class="calculator-fixed-label-field">\n <label>Rates</label>\n <input type="text" id="rate-field" />\n </div>\n <div class="calculator-fixed-label-field">\n <label>Amortization</label>\n <select id="amortization-field">\n <option value="10">10 years</option>\n <option value="15">15 years</option>\n <option value="20">20 years</option>\n <option value="25">25 years</option>\n </select>\n </div>\n <div class="calculator-fixed-label-field">\n <label>Payment Period</label>\n <select id="payment-period-field">\n <option value="monthly">Monthly</option>\n <option value="biweekly">Bi-weekly</option>\n <option value="weekly">Weekly</option>\n </select>\n </div>\n </div>\n <div class="apply-wrapper">\n <div id="mortagage-payment"></div>\n <a class="mortgage-apply-link disabled" href="${t}" target="_blank">Apply</button>\n </div>\n </div>\n </div>\n `;const n=document.getElementById("mortgage-amount-field"),r=document.getElementById("rate-field"),s=document.getElementById("amortization-field"),o=document.getElementById("payment-period-field"),a=(e,t)=>{e.addEventListener("input",(e=>{const n=e.target;if(n){let e=n.value;e=e.replace(/[^0-9.]/g,""),n.value=e?"$"===t?`${t}${parseInt(e).toLocaleString("en-US")}`:`${e}${t}`:""}}))};a(n,"$"),a(r,"%"),n.addEventListener("input",i),r.addEventListener("input",i),s.addEventListener("change",i),o.addEventListener("change",i),r.addEventListener("focus",(e=>{var t;null===(t=e.target.parentElement)||void 0===t||t.classList.add("child-input-focused")})),r.addEventListener("blur",(e=>{var t;null===(t=e.target.parentElement)||void 0===t||t.classList.remove("child-input-focused")})),s.addEventListener("focus",(e=>{var t;null===(t=e.target.parentElement)||void 0===t||t.classList.add("child-input-focused")})),s.addEventListener("blur",(e=>{var t;null===(t=e.target.parentElement)||void 0===t||t.classList.remove("child-input-focused")})),o.addEventListener("focus",(e=>{var t;null===(t=e.target.parentElement)||void 0===t||t.classList.add("child-input-focused")})),o.addEventListener("blur",(e=>{var t;null===(t=e.target.parentElement)||void 0===t||t.classList.remove("child-input-focused")}))};const r=n(185);function i(){const e=document.getElementById("mortgage-amount-field"),t=document.getElementById("rate-field"),n=document.getElementById("amortization-field"),i=document.getElementById("payment-period-field"),s=document.getElementById("mortagage-payment"),o=document.querySelector(".mortgage-apply-link"),a=parseFloat(e.value.replace(/\$/g,"").replace(/\,/g,"")),c=parseFloat(t.value.replace(/%/g,"")),u=parseInt(n.value),l=i.value;if(isNaN(a)||isNaN(c)||isNaN(u)||!l)return s.textContent="",void(o.classList.contains("disabled")||o.classList.add("disabled"));const h=(0,r.calculateMortgage)(a,c,u,l);s.textContent=`$${parseFloat(h.toFixed(2)).toLocaleString("en-US")}`,o.classList.contains("disabled")&&o.classList.remove("disabled")}},958:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.initCockpit=function(e){const t=window.innerWidth<992?window.innerWidth-32:600,n=window.innerWidth<992?350:450,r=[{id:"housing-indicators",name:"Housing Indicators",description:"The Canadian housing market is influenced by a range of important indicators that provide insights into the overall economic health and housing trends.",stats:[{title:"Residential sales activity",embed_code:`<iframe width="${t}" height="${n}" src="https://lookerstudio.google.com/embed/reporting/4c4cf585-74d2-4d90-938c-ec3ca0ddf85f/page/48IDE" frameborder="0" style="border:0" allowfullscreen sandbox="allow-storage-access-by-user-activation allow-scripts allow-same-origin allow-popups allow-popups-to-escape-sandbox"></iframe>`},{title:"Residential Average Price",embed_code:`<iframe width="${t}" height="${n}" src="https://lookerstudio.google.com/embed/reporting/918ac56b-3efc-4f8c-b455-9fe2be8c9e0c/page/HEJDE" frameborder="0" style="border:0" allowfullscreen sandbox="allow-storage-access-by-user-activation allow-scripts allow-same-origin allow-popups allow-popups-to-escape-sandbox"></iframe>`},{title:"Residential Market Balance",embed_code:`<iframe width="${t}" height="${n}" src="https://lookerstudio.google.com/embed/reporting/0e5fee3d-3c53-4469-9baa-36cb60aac28d/page/KHJDE" frameborder="0" style="border:0" allowfullscreen sandbox="allow-storage-access-by-user-activation allow-scripts allow-same-origin allow-popups allow-popups-to-escape-sandbox"></iframe>`},{title:"Residential New Listings",embed_code:`<iframe width="${t}" height="${n}" src="https://lookerstudio.google.com/embed/reporting/5994b7fe-d4ac-4a8d-b17d-4aee90fc1958/page/4CJDE" frameborder="0" style="border:0" allowfullscreen sandbox="allow-storage-access-by-user-activation allow-scripts allow-same-origin allow-popups allow-popups-to-escape-sandbox"></iframe>`},{title:"Residential Average Price (year over year percentage change )",embed_code:`<iframe width="${t}" height="${n}" src="https://lookerstudio.google.com/embed/reporting/0bbb457e-e130-4164-92ad-1f313f3d1d1c/page/6EJDE" frameborder="0" style="border:0" allowfullscreen sandbox="allow-storage-access-by-user-activation allow-scripts allow-same-origin allow-popups allow-popups-to-escape-sandbox"></iframe>`},{title:"MLS HPI Benchmark Price",embed_code:`<iframe width="${t}" height="${n}" src="https://lookerstudio.google.com/embed/reporting/5d0b79b4-7ae4-4f92-bdfb-1fbcc70b4ffb/page/IGJDE" frameborder="0" style="border:0" allowfullscreen sandbox="allow-storage-access-by-user-activation allow-scripts allow-same-origin allow-popups allow-popups-to-escape-sandbox"></iframe>`},{title:"Housing affordability index",embed_code:`<iframe width="${t}" height="${n}" src="https://lookerstudio.google.com/embed/reporting/643969af-c85b-4b53-bd43-ad2c35ea3dbf/page/56FHE" frameborder="0" style="border:0" allowfullscreen sandbox="allow-storage-access-by-user-activation allow-scripts allow-same-origin allow-popups allow-popups-to-escape-sandbox"></iframe>`}]},{id:"economic-indicators",name:"Economic Indicators",description:"Canadian economic indicators provide valuable insights into the health and performance of the country’s economy. These indicators are used by policymakers, economists, businesses, and investors to assess economic conditions and make informed decisions.",stats:[{title:"Retail sales increase ",embed_code:`<iframe width="${t}" height="${n}" src="https://lookerstudio.google.com/embed/reporting/e78b80fa-b1bc-4f2c-a021-e2de7308134e/page/CgeGE" frameborder="0" style="border:0" allowfullscreen sandbox="allow-storage-access-by-user-activation allow-scripts allow-same-origin allow-popups allow-popups-to-escape-sandbox"></iframe>`},{title:"Employment rate",embed_code:`<iframe width="${t}" height="${n}" src="https://lookerstudio.google.com/embed/reporting/53c524e5-ebfb-475c-81c8-94b461482a6d/page/hyeGE" frameborder="0" style="border:0" allowfullscreen sandbox="allow-storage-access-by-user-activation allow-scripts allow-same-origin allow-popups allow-popups-to-escape-sandbox"></iframe>`},{title:"Quarterly population estimate",embed_code:`<iframe width="${t}" height="${n}" src="https://lookerstudio.google.com/embed/reporting/55188dfc-ba3d-48fb-865f-f30869596420/page/C0eGE" frameborder="0" style="border:0" allowfullscreen sandbox="allow-storage-access-by-user-activation allow-scripts allow-same-origin allow-popups allow-popups-to-escape-sandbox"></iframe>`},{title:"CPI and CPI excluding gasoline",embed_code:`<iframe width="${t}" height="${n}" src="https://lookerstudio.google.com/embed/reporting/bf06875f-f5f4-4a3a-8a3b-82c11a1346a6/page/g2eGE" frameborder="0" style="border:0" allowfullscreen sandbox="allow-storage-access-by-user-activation allow-scripts allow-same-origin allow-popups allow-popups-to-escape-sandbox"></iframe>`}]}];let i='\n <div class="cockpit">\n <div class="header-wrapper">\n <div class="tab-selectors">\n ',s=0;for(let e of r)i+=`<div class="tab-selector ${0===s?"selected":""}" data-tab-id="${e.id}">${e.name}</div>`,s++;i+="\n </div>",s=0;for(let e of r)i+=`\n <div id="tab-content-${e.id}" class="tab-content ${0===s?"selected":""}">\n <div class="title">${e.name}</div>\n <div class="description">${e.description}</div>\n </div>`,s++;i+='\n </div>\n <div class="stats"></div>\n </div>\n ',e.innerHTML=i;const o=e.querySelector(".cockpit"),a=e.querySelector(".tab-selectors"),c=(e.querySelector(".header-wrapper"),e.querySelector(".stats")),u=r.filter((e=>"housing-indicators"===e.id))[0];let l="";for(let e of u.stats)l+=`\n <div class="stat">\n <div class="title">${e.title}</div>\n <div class="stat-graph">${e.embed_code}</div>\n </div>\n `;c.innerHTML=l,o.addEventListener("click",(e=>{var t,n;const i=e.target;if(i.closest(".tab-selector")){null===(t=a.querySelector(".selected"))||void 0===t||t.classList.remove("selected"),i.classList.add("selected"),o.querySelectorAll(".tab-content").forEach((e=>{e.classList.remove("selected")})),null===(n=document.getElementById(`tab-content-${i.dataset.tabId}`))||void 0===n||n.classList.add("selected");const e=r.filter((e=>e.id===i.dataset.tabId))[0];let s="";for(let t of e.stats)s+=`\n <div class="stat">\n <div class="title">${t.title}</div>\n <div class="stat-graph">${t.embed_code}</div>\n </div>\n `;c.innerHTML=s}}))}},260:function(e,t,n){"use strict";var r=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(i,s){function o(e){try{c(r.next(e))}catch(e){s(e)}}function a(e){try{c(r.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,a)}c((r=r.apply(e,t||[])).next())}))},i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.initEducationalVideos=function(e){e.innerHTML='\n <div class="educational-videos">\n <div class="section-heading">Educational Videos</div>\n <div class="filters">\n <div class="filter selected">All Videos</div>\n <div class="filter">First time home buyers in Canada</div>\n <div class="filter">Mortgage Fundamentals</div>\n <div class="filter">Renewal</div>\n <div class="filter">Mortgage Repayment</div>\n </div>\n <div class="videos"></div>\n <div id="video-player" class="modal" style="display: none;">\n <div class="modal-content">\n <span class="close">&times;</span>\n <iframe id="video-frame" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>\n </div>\n </div>\n </div>\n ';const t=e.querySelector(".educational-videos"),n=e.querySelector(".section-heading"),i=e.querySelector(".filters"),s=e.querySelector(".videos");if(!t||!n||!s)return;f(e);let o=!1,a=!0;window.addEventListener("scroll",(e=>{let t=0;return(...n)=>{const r=Date.now();r-t>=200&&(t=r,e(...n))}})((()=>r(this,void 0,void 0,(function*(){const t=s.getBoundingClientRect().bottom<=window.innerHeight+100;if(!o&&a&&t){o=!0;try{const t=yield f(e);a=t}catch(e){console.error("Error loading educational videos:",e)}finally{o=!1}}}))))),i.addEventListener("click",(t=>{const n=t.target;if(n.closest(".filter")){i.querySelectorAll(".filter").forEach((e=>{e.classList.remove("selected")})),n.classList.add("selected");const t="All Videos"===n.textContent?"":n.textContent;d=t||"",h=null,s.innerHTML="",f(e)}}))};const s=n(487),o=n(815),a=i(n(757)),c=n(185),u="educational_videos",l=9;let h=null,d="";function f(e){return r(this,void 0,void 0,(function*(){const t=e.querySelector(".videos");if(!t)return!1;try{const e=yield(0,s.getFirestoreInstance)();let n=(0,o.query)((0,o.collection)(e,u),(0,o.orderBy)("date","desc"),(0,o.limit)(l));d&&(n=(0,o.query)(n,(0,o.where)("category","==",d))),h&&(n=(0,o.query)(n,(0,o.startAfter)(h)));const r=yield(0,o.getDocs)(n);return r.empty?(console.log("No more videos to load"),!1):(r.forEach((e=>{var n,r,i;const s=e.data(),o=document.createElement("div");o.classList.add("video"),o.setAttribute("data-video-url",s.video_link),o.innerHTML=`\n <div class="thumbnail" style="background-image: url('${s.img_link}');">\n <div class="thumbnail-overlay" style="">\n <div class="play-icon">\n <img src="${a.default}" alt="Play Video" />\n </div>\n </div>\n </div>\n <div class="date">${(0,c.formatDate)(null===(n=s.date)||void 0===n?void 0:n.trim())}</div>\n <div class="title">${null===(r=s.headline)||void 0===r?void 0:r.trim()}</div>\n <div class="source">Source: <span>${null===(i=s.source)||void 0===i?void 0:i.trim()}</span></div>\n `,t.appendChild(o)})),t.addEventListener("click",(e=>{const t=e.target;if(t.closest(".play-icon")){const e=t.closest(".video");if(e){const t=e.getAttribute("data-video-url");t&&function(e){const t=document.querySelector("#video-player"),n=t.querySelector("#video-frame"),r=t.querySelector(".close");t&&n&&r&&(n.src=e,t.style.display="flex",r.addEventListener("click",(()=>{t.style.display="none",n.src=""})),t.addEventListener("click",(e=>{e.target===t&&(t.style.display="none",n.src="")})))}(t)}}})),h=r.docs[r.docs.length-1],!0)}catch(e){return console.error("Error loading educational videos:",e),!1}}))}},987:function(e,t,n){"use strict";var r=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(i,s){function o(e){try{c(r.next(e))}catch(e){s(e)}}function a(e){try{c(r.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,a)}c((r=r.apply(e,t||[])).next())}))},i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.initFaqs=function(e){e.innerHTML='\n <div class="faqs">\n <div class="section-heading">Frequently Asked Questions</div>\n <div class="faq-list"></div>\n </div>\n ';const t=e.querySelector(".faqs"),n=e.querySelector(".section-heading"),i=e.querySelector(".faq-list");t&&n&&i&&function(e){r(this,void 0,void 0,(function*(){const t=e.querySelector(".faq-list");if(t)try{const e=yield(0,s.getFirestoreInstance)();let n=(0,o.query)((0,o.collection)(e,c),(0,o.orderBy)("question","asc"));const r=yield(0,o.getDocs)(n);if(r.empty)return void console.log("No FAQs available");r.forEach((e=>{var n,r;const i=e.data();console.log("faqData - ",i);const s=document.createElement("div");s.classList.add("faq"),s.innerHTML=`\n <div class="content-wrapper">\n <div class="question">${null===(n=i.question)||void 0===n?void 0:n.trim()}</div>\n <div class="answer">${null===(r=i.answer)||void 0===r?void 0:r.trim()}</div>\n </div>\n <div class="expand-collapse-wrapper">\n <img src="${a.default}" alt="Expand/Collapse" />\n </div>\n `,t.appendChild(s)})),t.addEventListener("click",(e=>{const t=e.target;if(t.closest(".expand-collapse-wrapper")){const e=t.closest(".faq");e.classList.contains("expand")?e.classList.remove("expand"):e.classList.add("expand")}}))}catch(e){console.error("Error loading faqs:",e)}}))}(e)};const s=n(487),o=n(815),a=i(n(573)),c="faqs"},487:function(e,t,n){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),i=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&r(t,e,n);return i(t,e),t},o=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(i,s){function o(e){try{c(r.next(e))}catch(e){s(e)}}function a(e){try{c(r.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,a)}c((r=r.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.getFirestoreInstance=function(){return o(this,void 0,void 0,(function*(){if(!u){const{getFirestore:e}=yield Promise.resolve().then((()=>s(n(815)))),t=(0,a.initializeApp)(c);u=e(t)}return u}))},t.getFirebaseFunctions=function(){return o(this,void 0,void 0,(function*(){if(!l){const{getFunctions:e}=yield Promise.resolve().then((()=>s(n(619)))),t=(0,a.initializeApp)(c);l=e(t)}return l}))};const a=n(577),c={apiKey:"AIzaSyAdZy_OGph3BeMs0CqwjYkV7NNQR40MjJQ",authDomain:"superkreatives-product-data.firebaseapp.com",projectId:"superkreatives-product-data",storageBucket:"superkreatives-product-data.firebasestorage.app",messagingSenderId:"942901361121",appId:"1:942901361121:web:f17909f805333fd79f7aa0"};let u=null,l=null},536:function(e,t,n){"use strict";var r=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(i,s){function o(e){try{c(r.next(e))}catch(e){s(e)}}function a(e){try{c(r.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,a)}c((r=r.apply(e,t||[])).next())}))},i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.initFreeGuides=function(e){let t=`\n <div class="free-guides">\n <div class="section-heading">Free guides</div>\n <div class="free-guides-form">\n <div class="icon-wrapper">\n <img src="${a.default}" alt="Free guides icon"/>\n </div>\n <div class="form-wrapper">\n <div class="info">Grab your free guide for first-time <br/>homebuyers today!</div>\n <div class="fields">\n <input type="text" class="name-field" placeholder="Name" />\n <input type="email" class="email-field" placeholder="Email" />\n <div class="submit-button disabled">Yes, I want this</div>\n </div>\n <div class="consent-wrapper">\n <input type="checkbox" id="consent-checkbox" name="consent" value="Promotional emails consent">\n <label for="consent-checkbox">I consent to use my details here for future promotional emails.</label>\n </div>\n </div>\n </div>\n </div>\n `;e.innerHTML=t;const n=e.querySelector(".free-guides-form .form-wrapper"),i=e.querySelector(".free-guides-form .fields"),c=e.querySelector(".free-guides-form .consent-wrapper"),u=e.querySelector(".free-guides-form .name-field"),l=e.querySelector(".free-guides-form .email-field"),h=e.querySelector(".free-guides-form #consent-checkbox"),d=e.querySelector(".free-guides-form .submit-button"),f=()=>r(this,void 0,void 0,(function*(){const e=u.value,t=l.value;e&&t&&g(t)?d.classList.remove("disabled"):d.classList.add("disabled")})),g=e=>/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(e);u.addEventListener("change",(e=>{f()})),l.addEventListener("change",(e=>{f()})),h.addEventListener("change",(e=>{f()})),d.addEventListener("click",(e=>r(this,void 0,void 0,(function*(){const e=u.value.trim(),t=l.value.trim(),r=h.checked;try{d.textContent="Processing...",d.disabled=!0,d.classList.toggle("disabled");const a=yield(0,o.getFirebaseFunctions)(),u=(0,s.httpsCallable)(a,"sendGuideEmail"),l=(yield u({name:e,email:t,consent:r,file:"test-1.pdf"})).data;if(l.success){i.remove(),c.remove();const e=document.createElement("div");e.classList.add("status"),e.classList.add("success"),e.textContent="Your homebuyer free guide has been emailed to you!",n.appendChild(e)}else{d.textContent="Yes, I want this",d.disabled=!1,d.classList.toggle("disabled");const e=document.createElement("div");e.classList.add("status"),e.classList.add("error"),e.textContent=l.message,n.appendChild(e)}}catch(e){d.textContent="Yes, I want this",d.disabled=!1,d.classList.toggle("disabled"),console.error("Error sending email:",e);const t=e,r=document.createElement("div");r.classList.add("status"),r.classList.add("error"),r.textContent=t,n.appendChild(r)}}))))};const s=n(619),o=n(487),a=i(n(765))},137:function(e,t,n){"use strict";var r=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(i,s){function o(e){try{c(r.next(e))}catch(e){s(e)}}function a(e){try{c(r.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,a)}c((r=r.apply(e,t||[])).next())}))},i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.initMarketTrendVideos=function(e){e.innerHTML='\n <div class="market-trend-videos">\n <div class="section-heading">Market Trend Videos</div>\n <div class="videos"></div>\n <div id="video-player" class="modal" style="display: none;">\n <div class="modal-content">\n <span class="close">&times;</span>\n <iframe id="video-frame" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>\n </div>\n </div>\n </div>\n ';const t=e.querySelector(".market-trend-videos"),n=e.querySelector(".section-heading"),i=e.querySelector(".videos");if(!t||!n||!i)return;d(e);let s=!1,o=!0;window.addEventListener("scroll",(e=>{let t=0;return(...n)=>{const r=Date.now();r-t>=200&&(t=r,e(...n))}})((()=>r(this,void 0,void 0,(function*(){const t=i.getBoundingClientRect().bottom<=window.innerHeight+100;if(!s&&o&&t){s=!0;try{const t=yield d(e);o=t}catch(e){console.error("Error loading market trend videos:",e)}finally{s=!1}}})))))};const s=n(487),o=n(815),a=i(n(757)),c=n(185),u="market_trend_videos",l=9;let h=null;function d(e){return r(this,void 0,void 0,(function*(){const t=e.querySelector(".videos");if(!t)return!1;try{const e=yield(0,s.getFirestoreInstance)();let n=(0,o.query)((0,o.collection)(e,u),(0,o.orderBy)("date","desc"),(0,o.limit)(l));h&&(n=(0,o.query)(n,(0,o.startAfter)(h)));const r=yield(0,o.getDocs)(n);return r.empty?(console.log("No more videos to load"),!1):(r.forEach((e=>{var n,r,i;const s=e.data();console.log("videoData - ",s);const o=document.createElement("div");o.classList.add("video"),o.setAttribute("data-video-url",s.video_link),o.innerHTML=`\n <div class="thumbnail" style="background-image: url('${s.img_link}');">\n <div class="thumbnail-overlay" style="">\n <div class="play-icon">\n <img src="${a.default}" alt="Play Video" />\n </div>\n </div>\n </div>\n <div class="date">${(0,c.formatDate)(null===(n=s.date)||void 0===n?void 0:n.trim())}</div>\n <div class="title">${null===(r=s.headline)||void 0===r?void 0:r.trim()}</div>\n <div class="source">Source: <span>${null===(i=s.source)||void 0===i?void 0:i.trim()}</span></div>\n `,t.appendChild(o)})),t.addEventListener("click",(e=>{const t=e.target;if(t.closest(".play-icon")){const e=t.closest(".video");if(e){const t=e.getAttribute("data-video-url");t&&function(e){const t=document.querySelector("#video-player"),n=t.querySelector("#video-frame"),r=t.querySelector(".close");t&&n&&r&&(n.src=e,t.style.display="flex",r.addEventListener("click",(()=>{t.style.display="none",n.src=""})),t.addEventListener("click",(e=>{e.target===t&&(t.style.display="none",n.src="")})))}(t)}}})),h=r.docs[r.docs.length-1],!0)}catch(e){return console.error("Error loading trending videos:",e),!1}}))}},0:function(e,t,n){"use strict";var r=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(i,s){function o(e){try{c(r.next(e))}catch(e){s(e)}}function a(e){try{c(r.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,a)}c((r=r.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.initMortgageCalendar=function(e){e.innerHTML='\n <div class="mortgage-calender">\n <div class="section-heading">Mortgage Calender</div>\n <div class="filters">\n <div class="filter selected">Interest Rate</div>\n <div class="filter">Gross domestic product, income, and expenditure</div>\n <div class="filter">Housing</div>\n </div>\n <div class="calendar-content">\n <div class="calendar-header"></div>\n <div class="calendar-events"></div>\n </div>\n </div>\n ';const t=e.querySelector(".mortgage-calender"),n=e.querySelector(".section-heading"),i=e.querySelector(".filters"),s=e.querySelector(".calendar-events"),o=e.querySelector(".calendar-header");if(!t||!n||!s)return;h(e);let a=!1,c=!0;window.addEventListener("scroll",(e=>{let t=0;return(...n)=>{const r=Date.now();r-t>=200&&(t=r,e(...n))}})((()=>r(this,void 0,void 0,(function*(){const t=s.getBoundingClientRect().bottom<=window.innerHeight+100;if(!a&&c&&t){a=!0;try{c=yield h(e)}catch(e){console.error("Error loading mortgage calendar events:",e)}finally{a=!1}}}))))),i.addEventListener("click",(t=>{const n=t.target;n.closest(".filter")&&(i.querySelectorAll(".filter").forEach((e=>{e.classList.remove("selected")})),n.classList.add("selected"),l=n.textContent?n.textContent:"",u=null,o.classList.remove("show","three-col-layout"),s.innerHTML="",o.innerHTML="",h(e))}))};const i=n(487),s=n(815),o=n(185),a="mortgage_calender",c=9;let u=null,l="Interest Rate";function h(e){return r(this,void 0,void 0,(function*(){const t=e.querySelector(".calendar-header"),n=e.querySelector(".calendar-events");if(!t||!n)return!1;try{const e=yield(0,i.getFirestoreInstance)();let r=(0,s.query)((0,s.collection)(e,a),(0,s.orderBy)("schedule_date","asc"),(0,s.limit)(c));l&&(r=(0,s.query)(r,(0,s.where)("category","==",l))),u&&(r=(0,s.query)(r,(0,s.startAfter)(u)));const h=yield(0,s.getDocs)(r);return h.empty?(console.log("No more calendar events to load"),!1):(h.forEach((e=>{var r,i,s,a,c,u,h,d;const f=e.data(),g=document.createElement("div");g.classList.add("calendar-event"),t.classList.remove("show","three-col-layout"),"Interest Rate"===l?(t.classList.add("show"),t.innerHTML='\n <div class="calendar-header-col">Interest Rate</div>\n <div class="calendar-header-col">Schedule Date</div>\n ',g.innerHTML=`\n <div class="calendar-event-col">${null===(r=f.title)||void 0===r?void 0:r.trim()}</div>\n <div class="calendar-event-col date">${(0,o.formatDate)(null===(i=f.schedule_date)||void 0===i?void 0:i.trim())}</div>\n `):"Gross domestic product, income, and expenditure"===l?(t.classList.add("show","three-col-layout"),t.innerHTML='\n <div class="calendar-header-col">Gross domestic product, income, and expenditure</div>\n <div class="calendar-header-col">Release Date</div>\n <div class="calendar-header-col">Reference Period</div>\n ',g.classList.add("three-col-layout"),g.innerHTML=`\n <div class="calendar-event-col">${null===(s=f.title)||void 0===s?void 0:s.trim()}</div>\n <div class="calendar-event-col date">${(0,o.formatDate)(null===(a=f.release_date)||void 0===a?void 0:a.trim())}</div>\n <div class="calendar-event-col date">${(0,o.formatDate)(null===(c=f.reference_period)||void 0===c?void 0:c.trim())}</div>\n `):"Housing"===l&&(t.classList.add("show","three-col-layout"),t.innerHTML='\n <div class="calendar-header-col">Housing</div>\n <div class="calendar-header-col">Release Date</div>\n <div class="calendar-header-col">Last Published Date</div>\n ',g.classList.add("three-col-layout"),g.innerHTML=`\n <div class="calendar-event-col">${null===(u=f.title)||void 0===u?void 0:u.trim()}</div>\n <div class="calendar-event-col date">${(0,o.formatDate)(null===(h=f.release_date)||void 0===h?void 0:h.trim())}</div>\n <div class="calendar-event-col date">${(0,o.formatDate)(null===(d=f.last_published_date)||void 0===d?void 0:d.trim())}</div>\n `),n.appendChild(g)})),u=h.docs[h.docs.length-1],!0)}catch(e){return console.error("Error loading mortgage calendar events:",e),!1}}))}},533:function(e,t,n){"use strict";var r=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(i,s){function o(e){try{c(r.next(e))}catch(e){s(e)}}function a(e){try{c(r.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,a)}c((r=r.apply(e,t||[])).next())}))},i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.initMortgageGlossary=function(e){e.innerHTML=`\n <div class="mortgage-glossary">\n <div class="header-wrapper">\n <div class="section-heading">Mortgage Glossary</div>\n <div class="glossary-controls">\n <div class="arrow-left"><img src="${a.default}" alt="Expand/Collapse" /></div>\n <div class="alphabets"></div>\n <div class="arrow-right"><img src="${c.default}" alt="Expand/Collapse" /></div>\n </div>\n </div>\n <div class="glossary-list"></div>\n </div>\n `;const t=e.querySelector(".mortgage-glossary"),n=e.querySelector(".header-wrapper"),i=e.querySelector(".glossary-list");t&&n&&i&&function(e){r(this,void 0,void 0,(function*(){const t=e.querySelector(".mortgage-glossary"),n=e.querySelector(".glossary-list"),r=e.querySelector(".alphabets");if(n)try{const e=yield(0,s.getFirestoreInstance)();let i=(0,o.query)((0,o.collection)(e,u),(0,o.orderBy)("term","asc"));const a=yield(0,o.getDocs)(i);if(a.empty)return void console.log("No mortgage glossary available");let c={};a.forEach((e=>{var t,r;const i=e.data(),s=i.term.charAt(0).toUpperCase();let o=!1;c[s]||(c[s]=[],o=!0),c[s].push(i);const a=document.createElement("div");a.classList.add("glossary-item"),o&&a.setAttribute("data-glosssary-control-letter",s),a.innerHTML=`\n <div class="term">${null===(t=i.term)||void 0===t?void 0:t.trim()}</div>\n <div class="definition">${null===(r=i.definition)||void 0===r?void 0:r.trim()}</div>\n `,n.appendChild(a)})),console.log(c," - groupedGlossary");const l=Object.keys(c);let h="";l.forEach((e=>{h+=`<div class="alphabet">${e}</div>`})),r.innerHTML=h,t.addEventListener("click",(e=>{const t=e.target;if(t.closest(".arrow-right"))r.scrollLeft+=150;else if(t.closest(".arrow-left "))r.scrollLeft-=150;else if(t.closest(".alphabet")){const e=document.querySelector(`[data-glosssary-control-letter="${t.textContent}"]`);if(e){const t=e.getBoundingClientRect().top+window.scrollY,n=window.innerWidth<992?200:275;window.scrollTo({top:t-n,behavior:"smooth"})}}}))}catch(e){console.error("Error loading mortgage glossary:",e)}}))}(e)};const s=n(487),o=n(815),a=i(n(648)),c=i(n(415)),u="mortgage_glossary"},242:function(e,t,n){"use strict";var r=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(i,s){function o(e){try{c(r.next(e))}catch(e){s(e)}}function a(e){try{c(r.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,a)}c((r=r.apply(e,t||[])).next())}))},i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.initMortgageNews=function(e){e.innerHTML='\n <div class="mortgage-news">\n <div class="section-heading">Mortgage News</div>\n <div class="mortgage-news-list"></div>\n </div>\n ';const t=e.querySelector(".mortgage-news"),n=e.querySelector(".section-heading"),i=e.querySelector(".mortgage-news-list");if(!t||!n||!i)return;d(e);let s=!1,o=!0;window.addEventListener("scroll",(e=>{let t=0;return(...n)=>{const r=Date.now();r-t>=200&&(t=r,e(...n))}})((()=>r(this,void 0,void 0,(function*(){const t=i.getBoundingClientRect().bottom<=window.innerHeight+100;if(!s&&o&&t){s=!0;try{const t=yield d(e);o=t}catch(e){console.error("Error loading mortgage news:",e)}finally{s=!1}}})))))};const s=n(487),o=n(815),a=n(185),c=i(n(501)),u="mortgage_news",l=9;let h=null;function d(e){return r(this,void 0,void 0,(function*(){const t=e.querySelector(".mortgage-news-list");if(!t)return!1;try{const e=yield(0,s.getFirestoreInstance)();let n=(0,o.query)((0,o.collection)(e,u),(0,o.orderBy)("date","desc"),(0,o.limit)(l));h&&(n=(0,o.query)(n,(0,o.startAfter)(h)));const r=yield(0,o.getDocs)(n);return r.empty?(console.log("No more mortgage news to load"),!1):(r.forEach((e=>{const n=e.data();console.log("mortgageNewsData - ",n);const r=document.createElement("div");r.classList.add("mortgage-news-item"),r.innerHTML=`\n <div class="thumbnail" style="background-image: url('${n.img_link}');"></div>\n <div class="date">${(0,a.formatDate)(n.date)}</div>\n <div class="title">${n.headline}</div>\n <a class="read-more-link" href="${n.source}" target="_blank">\n Read More\n <div class="read-more-icon">\n <img src="${c.default}" alt="Read More" />\n </div>\n </a>\n `,t.appendChild(r)})),h=r.docs[r.docs.length-1],!0)}catch(e){return console.error("Error loading mortgage news:",e),!1}}))}},659:function(e,t,n){"use strict";var r=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(i,s){function o(e){try{c(r.next(e))}catch(e){s(e)}}function a(e){try{c(r.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,a)}c((r=r.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.initResearchArticles=function(e){e.innerHTML='\n <div class="research-articles">\n <div class="section-heading">Research Articles</div>\n <div class="research-articles-list"></div>\n </div>\n ';const t=e.querySelector(".research-articles"),n=e.querySelector(".section-heading"),i=e.querySelector(".research-articles-list");if(!t||!n||!i)return;l(e);let s=!1,o=!0;window.addEventListener("scroll",(e=>{let t=0;return(...n)=>{const r=Date.now();r-t>=200&&(t=r,e(...n))}})((()=>r(this,void 0,void 0,(function*(){const t=i.getBoundingClientRect().bottom<=window.innerHeight+100;if(!s&&o&&t){s=!0;try{const t=yield l(e);o=t}catch(e){console.error("Error loading research articles:",e)}finally{s=!1}}})))))};const i=n(487),s=n(815),o=n(185),a="research_articles",c=9;let u=null;function l(e){return r(this,void 0,void 0,(function*(){const t=e.querySelector(".research-articles-list");if(!t)return!1;try{const e=yield(0,i.getFirestoreInstance)();let n=(0,s.query)((0,s.collection)(e,a),(0,s.orderBy)("date","desc"),(0,s.limit)(c));u&&(n=(0,s.query)(n,(0,s.startAfter)(u)));const r=yield(0,s.getDocs)(n);return r.empty?(console.log("No more research articles to load"),!1):(r.forEach((e=>{var n,r;const i=e.data();console.log("researchArticleData - ",i);const s=document.createElement("div");s.classList.add("research-article"),s.innerHTML=`\n <div class="thumbnail" style="background-image: url('${i.img_link}');"></div>\n <div class="date">${(0,o.formatDate)(i.date)}</div>\n <div class="title">${null===(n=i.headline)||void 0===n?void 0:n.trim()}</div>\n <div class="description">${null===(r=i.description)||void 0===r?void 0:r.trim()}</div>\n <a class="read-more-link" href="${i.source}" target="_blank">Read More</a>\n `,t.appendChild(s)})),u=r.docs[r.docs.length-1],!0)}catch(e){return console.error("Error loading research articles:",e),!1}}))}},185:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.calculateMortgage=function(e,t,n,r){const i=t/100/2,s=Math.pow(1+i,2/12)-1,o=12*n,a=e*(s*Math.pow(1+s,o))/(Math.pow(1+s,o)-1);let c;switch(r){case"weekly":c=12*a/52;break;case"biweekly":c=12*a/26;break;default:c=a}return c},t.formatDate=function(e){const t=new Date(e);return new Intl.DateTimeFormat("en-US",{month:"long",day:"numeric",year:"numeric"}).format(t)}},648:(e,t,n)=>{"use strict";e.exports=n.p+"94d7adc1c3f7df08c5dc.svg"},415:(e,t,n)=>{"use strict";e.exports=n.p+"0134ef940feb41dedc27.svg"},573:(e,t,n)=>{"use strict";e.exports=n.p+"05e0aac3f5f644c344d6.svg"},501:(e,t,n)=>{"use strict";e.exports=n.p+"7acafcdacd8c7574dbdc.svg"},765:(e,t,n)=>{"use strict";e.exports=n.p+"d686a45650560ddaa773.svg"},757:(e,t,n)=>{"use strict";e.exports=n.p+"dec0b8717bf0d582857b.svg"},148:(e,t,n)=>{"use strict";n.r(t),n.d(t,{deleteDB:()=>m,openDB:()=>p,unwrap:()=>g,wrap:()=>f});const r=(e,t)=>t.some((t=>e instanceof t));let i,s;const o=new WeakMap,a=new WeakMap,c=new WeakMap,u=new WeakMap,l=new WeakMap;let h={get(e,t,n){if(e instanceof IDBTransaction){if("done"===t)return a.get(e);if("objectStoreNames"===t)return e.objectStoreNames||c.get(e);if("store"===t)return n.objectStoreNames[1]?void 0:n.objectStore(n.objectStoreNames[0])}return f(e[t])},set:(e,t,n)=>(e[t]=n,!0),has:(e,t)=>e instanceof IDBTransaction&&("done"===t||"store"===t)||t in e};function d(e){return"function"==typeof e?(t=e)!==IDBDatabase.prototype.transaction||"objectStoreNames"in IDBTransaction.prototype?(s||(s=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])).includes(t)?function(...e){return t.apply(g(this),e),f(o.get(this))}:function(...e){return f(t.apply(g(this),e))}:function(e,...n){const r=t.call(g(this),e,...n);return c.set(r,e.sort?e.sort():[e]),f(r)}:(e instanceof IDBTransaction&&function(e){if(a.has(e))return;const t=new Promise(((t,n)=>{const r=()=>{e.removeEventListener("complete",i),e.removeEventListener("error",s),e.removeEventListener("abort",s)},i=()=>{t(),r()},s=()=>{n(e.error||new DOMException("AbortError","AbortError")),r()};e.addEventListener("complete",i),e.addEventListener("error",s),e.addEventListener("abort",s)}));a.set(e,t)}(e),r(e,i||(i=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction]))?new Proxy(e,h):e);var t}function f(e){if(e instanceof IDBRequest)return function(e){const t=new Promise(((t,n)=>{const r=()=>{e.removeEventListener("success",i),e.removeEventListener("error",s)},i=()=>{t(f(e.result)),r()},s=()=>{n(e.error),r()};e.addEventListener("success",i),e.addEventListener("error",s)}));return t.then((t=>{t instanceof IDBCursor&&o.set(t,e)})).catch((()=>{})),l.set(t,e),t}(e);if(u.has(e))return u.get(e);const t=d(e);return t!==e&&(u.set(e,t),l.set(t,e)),t}const g=e=>l.get(e);function p(e,t,{blocked:n,upgrade:r,blocking:i,terminated:s}={}){const o=indexedDB.open(e,t),a=f(o);return r&&o.addEventListener("upgradeneeded",(e=>{r(f(o.result),e.oldVersion,e.newVersion,f(o.transaction),e)})),n&&o.addEventListener("blocked",(e=>n(e.oldVersion,e.newVersion,e))),a.then((e=>{s&&e.addEventListener("close",(()=>s())),i&&e.addEventListener("versionchange",(e=>i(e.oldVersion,e.newVersion,e)))})).catch((()=>{})),a}function m(e,{blocked:t}={}){const n=indexedDB.deleteDatabase(e);return t&&n.addEventListener("blocked",(e=>t(e.oldVersion,e))),f(n).then((()=>{}))}const y=["get","getKey","getAll","getAllKeys","count"],v=["put","add","delete","clear"],w=new Map;function b(e,t){if(!(e instanceof IDBDatabase)||t in e||"string"!=typeof t)return;if(w.get(t))return w.get(t);const n=t.replace(/FromIndex$/,""),r=t!==n,i=v.includes(n);if(!(n in(r?IDBIndex:IDBObjectStore).prototype)||!i&&!y.includes(n))return;const s=async function(e,...t){const s=this.transaction(e,i?"readwrite":"readonly");let o=s.store;return r&&(o=o.index(t.shift())),(await Promise.all([o[n](...t),i&&s.done]))[0]};return w.set(t,s),s}var _;_=h,h={..._,get:(e,t,n)=>b(e,t)||_.get(e,t,n),has:(e,t)=>!!b(e,t)||_.has(e,t)}}},t={};function n(r){var i=t[r];if(void 0!==i)return i.exports;var s=t[r]={exports:{}};return e[r].call(s.exports,s,s.exports,n),s.exports}n.d=(e,t)=>{for(var r in t)n.o(t,r)&&!n.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},n.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),n.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},(()=>{var e;n.g.importScripts&&(e=n.g.location+"");var t=n.g.document;if(!e&&t&&(t.currentScript&&"SCRIPT"===t.currentScript.tagName.toUpperCase()&&(e=t.currentScript.src),!e)){var r=t.getElementsByTagName("script");if(r.length)for(var i=r.length-1;i>-1&&(!e||!/^http(s?):/.test(e));)e=r[i--].src}if(!e)throw new Error("Automatic publicPath is not supported in this browser");e=e.replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/"),n.p=e})();var r={};return(()=>{"use strict";var e=r;Object.defineProperty(e,"__esModule",{value:!0}),e.init=function(e){var n;const r=document.getElementById(e.containerId);if(r)switch(e.product){case"calculator":(0,t.initCalculator)(r,(null===(n=e.options)||void 0===n?void 0:n.applyUrl)||"");break;case"cockpit":(0,l.initCockpit)(r);break;case"educational-videos":(0,u.initEducationalVideos)(r);break;case"faqs":(0,s.initFaqs)(r);break;case"free-guides":(0,h.initFreeGuides)(r);break;case"market-trend-videos":(0,i.initMarketTrendVideos)(r);break;case"mortgage-calender":(0,d.initMortgageCalendar)(r);break;case"mortgage-glossary":(0,c.initMortgageGlossary)(r);break;case"mortgage-news":(0,a.initMortgageNews)(r);break;case"research-articles":(0,o.initResearchArticles)(r);break;default:console.error(`Unknown product: ${e.product}`)}else console.error("Container not found")},n(264);const t=n(846),i=n(137),s=n(987),o=n(659),a=n(242),c=n(533),u=n(260),l=n(958),h=n(536),d=n(0)})(),r})()));
3
3
  //# sourceMappingURL=index.js.map