mortgage-calculator-package 2.3.5 → 2.4.1
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/README.md +22 -1
- package/dist/{eed2bfb095ae763cb632.svg → 1405b9b234fc3159c8f5.svg} +1 -1
- package/dist/{4cf66e75d98ed1b6111b.svg → 1d67c5fb9d42f53718b2.svg} +1 -1
- package/dist/{c0479e777ea346aaaa27.svg → 30b99c60fafb65be19cd.svg} +1 -1
- package/dist/3e74f701b4efddab859b.svg +5 -0
- package/dist/6f14f50227dba9b6de9c.svg +5 -0
- package/dist/{255c94be199eb8f10a50.svg → 81149ed26f2beeb606db.svg} +4 -4
- package/dist/{204629feb4301824d2a9.svg → 91153cd53d2ed08a0a2e.svg} +9 -9
- package/dist/{f45122777360c8743959.svg → a5f2f91315fae21adce3.svg} +5 -5
- package/dist/{f788593ff71e33e36caf.svg → a630985df1564d70133d.svg} +4 -4
- package/dist/{1358c7e31687624f57e2.svg → bd4ffa72a63f585acc95.svg} +5 -5
- package/dist/{7a6c5262adc1cd432101.svg → dafac920656692f6c6be.svg} +7 -7
- package/dist/{43c55608a5fb15ce54c5.svg → e3ef864cb6d9c860c30e.svg} +1 -1
- package/dist/{0aedc236b853cf75f799.svg → ec59ff28ecbf77d31249.svg} +4 -4
- package/dist/{9494550fdfafc3ef2c95.svg → ec67e568eccf383cda9e.svg} +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/mortgage-calculator.d.ts +1 -0
- package/dist/styles.css +1 -1
- package/dist/styles.css.map +1 -1
- package/dist/utils-mortgage-calculator.d.ts +54 -0
- package/package.json +1 -1
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",l="0.10.17",u=new i.Logger("@firebase/app"),h="@firebase/app-compat",d="@firebase/analytics-compat",f="@firebase/analytics",p="@firebase/app-check-compat",g="@firebase/app-check",m="@firebase/auth",v="@firebase/auth-compat",y="@firebase/database",w="@firebase/data-connect",b="@firebase/database-compat",_="@firebase/functions",I="@firebase/functions-compat",E="@firebase/installations",S="@firebase/installations-compat",T="@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",M="@firebase/firestore",P="@firebase/vertexai",O="@firebase/firestore-compat",R="firebase",F="[DEFAULT]",V={[c]:"fire-core",[h]:"fire-core-compat",[f]:"fire-analytics",[d]:"fire-analytics-compat",[g]:"fire-app-check",[p]:"fire-app-check-compat",[m]:"fire-auth",[v]:"fire-auth-compat",[y]:"fire-rtdb",[w]:"fire-data-connect",[b]:"fire-rtdb-compat",[_]:"fire-fn",[I]:"fire-fn-compat",[E]:"fire-iid",[S]:"fire-iid-compat",[T]:"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",[M]:"fire-fst",[O]:"fire-fst-compat",[P]:"fire-vertex","fire-js":"fire-js",[R]:"fire-js-all"},q=new Map,$=new Map,B=new Map;function U(e,t){try{e.container.addComponent(t)}catch(n){u.debug(`Component ${t.name} failed to register with FirebaseApp ${e.name}`,n)}}function j(e){const t=e.name;if(B.has(t))return u.debug(`There were multiple attempts to register component ${t}.`),!1;B.set(t,e);for(const t of q.values())U(t,e);for(const t of $.values())U(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 H{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 Q extends H{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,Y(c,l,"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 B.values())c.addComponent(e);const l=new H(n,i,c);return q.set(o,l),l}async function J(e){let t=!1;const n=e.name;q.has(n)?(t=!0,q.delete(n)):$.has(n)&&e.decRefCount()<=0&&($.delete(n),t=!0),t&&(await Promise.all(e.container.getProviders().map((e=>e.delete()))),e.isDeleted=!0)}function Y(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 u.warn(e.join(" "))}j(new r.Component(`${s}-version`,(()=>({library:s,version:t})),"VERSION"))}const X="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(X)}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(X,"readwrite"),r=n.objectStore(X);await r.put(t,ne(e)),await n.done}catch(e){if(e instanceof s.FirebaseError)u.warn(e.message);else{const t=K.create("idb-set",{originalErrorMessage:null==e?void 0:e.message});u.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){u.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 u.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(X),n=await t.objectStore(X).get(ne(e));return await t.done,n}catch(e){if(e instanceof s.FirebaseError)u.warn(e.message);else{const t=K.create("idb-get",{originalErrorMessage:null==e?void 0:e.message});u.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}j(new r.Component("platform-logger",(e=>new a(e)),"PRIVATE")),j(new r.Component("heartbeat",(e=>new re(e)),"PRIVATE")),Y(c,l,"node"),Y(c,l,"cjs2017"),Y("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=U,t._addOrOverwriteComponent=function(e,t){e.container.addOrOverwriteComponent(t)},t._apps=q,t._clearComponents=function(){B.clear()},t._components=B,t._getProvider=z,t._isFirebaseApp=G,t._isFirebaseServerApp=function(e){return void 0!==e.settings},t._registerComponent=j,t._removeServiceInstance=function(e,t,n=F){z(e,t).clearInstance(n)},t._serverApps=$,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=$.get(o);if(c)return c.incRefCount(t.releaseOnDeref),c;const l=new r.ComponentContainer(o);for(const e of B.values())l.addComponent(e);const u=new Q(n,t,o,l);return $.set(o,u),u},t.onLog=function(e,t){if(null!==e&&"function"!=typeof e)throw K.create("invalid-log-argument");i.setUserLogHandler(e,t)},t.registerVersion=Y,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 l="@firebase/firestore";class u{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}}u.UNAUTHENTICATED=new u(null),u.GOOGLE_CREDENTIALS=new u("google-credentials-uid"),u.FIRST_PARTY=new u("first-party-uid"),u.MOCK_USER=new u("mock-user");let h="11.0.2";const d=new s.Logger("@firebase/firestore");function f(){return d.logLevel}function p(e,...t){if(d.logLevel<=s.LogLevel.DEBUG){const n=t.map(v);d.debug(`Firestore (${h}): ${e}`,...n)}}function g(e,...t){if(d.logLevel<=s.LogLevel.ERROR){const n=t.map(v);d.error(`Firestore (${h}): ${e}`,...n)}}function m(e,...t){if(d.logLevel<=s.LogLevel.WARN){const n=t.map(v);d.warn(`Firestore (${h}): ${e}`,...n)}}function v(e){if("string"==typeof e)return e;try{return function(e){return JSON.stringify(e)}(e)}catch(t){return e}}function y(e="Unexpected state"){const t=`FIRESTORE (${h}) INTERNAL ASSERTION FAILED: `+e;throw g(t),new Error(t)}function w(e,t){e||y()}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 S{constructor(e,t){this.user=t,this.type="OAuth",this.headers=new Map,this.headers.set("Authorization",`Bearer ${e}`)}}class T{getToken(){return Promise.resolve(null)}invalidateToken(){}start(e,t){e.enqueueRetryable((()=>t(u.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=u.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=>{p("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):(p("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?(p("FirebaseAuthCredentialsProvider","getToken aborted due to token change."),this.getToken()):t?(w("string"==typeof t.accessToken),new S(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 u(e)}}class D{constructor(e,t,n){this.l=e,this.h=t,this.P=n,this.type="FirstParty",this.user=u.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(u.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&&p("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,p("FirebaseAppCheckTokenProvider",`Received ${n?"new":"existing"} token.`),n?t(e.token):Promise.resolve()};this.o=t=>{e.enqueueRetryable((()=>n(t)))};const r=e=>{p("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):p("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 M{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 P(e,t){return e<t?-1:e>t?1:0}function O(e,t,n){return e.length===t.length&&e.every(((e,r)=>n(e,t[r])))}function R(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?P(this.nanoseconds,e.nanoseconds):P(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&&y(),void 0===n?n=e.length-t:n>e.length-t&&y(),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 $ extends q{construct(e,t,n){return new $(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 $(t)}static emptyPath(){return new $([])}}const B=/^[_a-zA-Z][_a-zA-Z0-9]*$/;class U extends q{construct(e,t,n){return new U(e,t,n)}static isValidIdentifier(e){return B.test(e)}canonicalString(){return this.toArray().map((e=>(e=e.replace(/\\/g,"\\\\").replace(/`/g,"\\`"),U.isValidIdentifier(e)||(e="`"+e+"`"),e))).join(".")}toString(){return this.canonicalString()}isKeyField(){return 1===this.length&&"__name__"===this.get(0)}static keyField(){return new U(["__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 U(t)}static emptyPath(){return new U([])}}class j{constructor(e){this.path=e}static fromPath(e){return new j($.fromString(e))}static fromName(e){return new j($.fromString(e).popFirst(5))}static empty(){return new j($.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===$.comparator(this.path,e.path)}toString(){return this.path.toString()}static comparator(e,t){return $.comparator(e.path,t.path)}static isDocumentKey(e){return e.length%2==0}static fromSegments(e){return new j(new $(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 H(e,t){let n=P(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 P(e.fields.length,t.fields.length)}z.UNKNOWN_ID=-1;class Q{constructor(e,t){this.fieldPath=e,this.kind=t}}function W(e,t){const n=U.comparator(e.fieldPath,t.fieldPath);return 0!==n?n:P(e.kind,t.kind)}class J{constructor(e,t){this.sequenceNumber=e,this.offset=t}static empty(){return new J(0,Z.min())}}function Y(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,j.empty(),t)}function X(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(),j.empty(),-1)}static max(){return new Z(V.max(),j.empty(),-1)}}function ee(e,t){let n=e.readTime.compareTo(t.readTime);return 0!==n?n:(n=j.comparator(e.documentKey,t.documentKey),0!==n?n:P(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;p("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&&y(),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 le(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 le(e,t.error)):this.V.resolve()},this.transaction.onerror=t=>{const n=pe(t.target.error);this.V.reject(new le(e,n))}}get m(){return this.V.promise}abort(e){e&&this.V.reject(e),this.aborted||(p("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 p("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())&&g("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||(p("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 le(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 le(e,r))},r.onupgradeneeded=e=>{p("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((()=>{p("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(p("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 le extends I{constructor(e,t){super(_.UNAVAILABLE,`IndexedDB transaction '${e}' failed: ${t}`),this.name="IndexedDbTransactionError"}}function ue(e){return"IndexedDbTransactionError"===e.name}class he{constructor(e){this.store=e}put(e,t){let n;return void 0!==t?(p("SimpleDb","PUT",this.store.name,e,t),n=this.store.put(t,e)):(p("SimpleDb","PUT",this.store.name,"<auto-key>",e),n=this.store.put(e)),de(n)}add(e){return p("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),p("SimpleDb","GET",this.store.name,e,t),t)))}delete(e){return p("SimpleDb","DELETE",this.store.name,e),de(this.store.delete(e))}count(){return p("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){p("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=pe(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=pe(e.target.error);n(t)}}))}let fe=!1;function pe(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 ge{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){p("IndexBackfiller",`Scheduled in ${e}ms`),this.task=this.asyncQueue.enqueueAfterDelay("index_backfill",e,(async()=>{this.task=null;try{p("IndexBackfiller",`Documents written: ${await this.Z.ee()}`)}catch(e){ue(e)?p("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 p("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=>(p("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=X(t);ee(r,n)>0&&(n=r)})),new Z(n.readTime,n.documentKey,Math.max(t.batchId,e.largestBatchId))}}class ve{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 ye(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 Se(e){const t=e.length;if(w(t>=2),2===t)return w(""===e.charAt(0)&&""===e.charAt(1)),$.emptyPath();const n=t-2,r=[];let i="";for(let s=0;s<t;){const t=e.indexOf("",s);switch((t<0||t>n)&&y(),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:y()}s=t+2}return new $(r)}ve.oe=-1;const Te=["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"],Me=["targetId","path"],Pe=["path","targetId"],Oe=["collectionId","parent"],Re=["indexId","uid"],Fe=["uid","sequenceNumber"],Ve=["indexId","uid","arrayValue","directionalValue","orderedDocumentKey","documentKey"],qe=["indexId","uid","orderedDocumentKey"],$e=["userId","collectionPath","documentId"],Be=["userId","collectionPath","largestBatchId"],Ue=["userId","collectionGroup","largestBatchId"],je=["mutationQueues","mutations","documentMutations","remoteDocuments","targets","owner","targetGlobal","targetDocuments","clientMetadata","remoteDocumentGlobal","collectionParents","bundles","namedQueries"],ze=[...je,"documentOverlays"],Ge=["mutationQueues","mutations","documentMutations","remoteDocumentsV14","targets","owner","targetGlobal","targetDocuments","clientMetadata","remoteDocumentGlobal","collectionParents","bundles","namedQueries","documentOverlays"],Ke=Ge,He=[...Ke,"indexConfiguration","indexState","indexEntries"],Qe=He,We=[...He,"globals"];class Je extends ne{constructor(e,t){super(),this._e=e,this.currentSequenceNumber=t}}function Ye(e,t){const n=b(e);return oe.C(n._e,t)}function Xe(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 y();if(this.right.isRed())throw y();const e=this.left.check();if(e!==this.right.check())throw y();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 y()}get value(){throw y()}get color(){throw y()}get left(){throw y()}get right(){throw y()}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(U.comparator)}static empty(){return new ct([])}unionWith(e){let t=new st(U.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 O(this.fields,e.fields,((e,t)=>e.isEqual(t)))}}class lt extends Error{constructor(){super(...arguments),this.name="Base64DecodeError"}}class ut{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 lt("Invalid base64 string: "+e):e}}(e);return new ut(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 ut(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 P(this.binaryString,e.binaryString)}isEqual(e){return this.binaryString===e.binaryString}}ut.EMPTY_BYTE_STRING=new ut("");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 pt(e){return"string"==typeof e?ut.fromBase64String(e):ut.fromUint8Array(e)}function gt(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 gt(t)?mt(t):t}function vt(e){const t=dt(e.mapValue.fields.__local_write_time__.timestampValue);return new F(t.seconds,t.nanos)}class yt{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?gt(e)?4:qt(e)?9007199254740991:Ft(e)?10:11:y()}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 vt(e).isEqual(vt(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 pt(e.bytesValue).isEqual(pt(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 O(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(Xe(n)!==Xe(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 y()}}function St(e,t){return void 0!==(e.values||[]).find((e=>Et(e,t)))}function Tt(e,t){if(e===t)return 0;const n=It(e),r=It(t);if(n!==r)return P(n,r);switch(n){case 0:case 9007199254740991:return 0;case 1:return P(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(vt(e),vt(t));case 5:return P(e.stringValue,t.stringValue);case 6:return function(e,t){const n=pt(e),r=pt(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=P(n[e],r[e]);if(0!==t)return t}return P(n.length,r.length)}(e.referenceValue,t.referenceValue);case 8:return function(e,t){const n=P(ft(e.latitude),ft(t.latitude));return 0!==n?n:P(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,l=null===(r=a.value)||void 0===r?void 0:r.arrayValue,u=P((null===(i=null==c?void 0:c.values)||void 0===i?void 0:i.length)||0,(null===(s=null==l?void 0:l.values)||void 0===s?void 0:s.length)||0);return 0!==u?u:Ct(c,l)}(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=P(r[e],s[e]);if(0!==t)return t;const o=Tt(n[r[e]],i[s[e]]);if(0!==o)return o}return P(r.length,s.length)}(e.mapValue,t.mapValue);default:throw y()}}function xt(e,t){if("string"==typeof e&&"string"==typeof t&&e.length===t.length)return P(e,t);const n=dt(e),r=dt(t),i=P(n.seconds,r.seconds);return 0!==i?i:P(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=Tt(n[e],r[e]);if(t)return t}return P(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 pt(e).toBase64()}(e.bytesValue):"referenceValue"in e?function(e){return j.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):y()}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 pt(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 y()}}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 Mt(e){return!!e&&"arrayValue"in e}function Pt(e){return!!e&&"nullValue"in e}function Ot(e){return!!e&&"doubleValue"in e&&isNaN(Number(e.doubleValue))}function Rt(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 $t={mapValue:{fields:{__type__:{stringValue:"__vector__"},value:{arrayValue:{}}}}};function Bt(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(),j.empty()):"geoPointValue"in e?{geoPointValue:{latitude:-90,longitude:-180}}:"arrayValue"in e?{arrayValue:{}}:"mapValue"in e?Ft(e)?$t:{mapValue:{}}:y()}function Ut(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(),j.empty()):"referenceValue"in e?{geoPointValue:{latitude:-90,longitude:-180}}:"geoPointValue"in e?{arrayValue:{}}:"arrayValue"in e?$t:"mapValue"in e?Ft(e)?{mapValue:{}}:bt:y()}function jt(e,t){const n=Tt(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=Tt(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)],!Rt(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=U.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());Rt(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)];Rt(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 U([e]);if(Rt(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 Ht{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 Ht(e,0,V.min(),V.min(),V.min(),Gt.empty(),0)}static newFoundDocument(e,t,n,r){return new Ht(e,1,t,V.min(),n,r,0)}static newNoDocument(e,t){return new Ht(e,2,t,V.min(),V.min(),Gt.empty(),0)}static newUnknownDocument(e,t){return new Ht(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 Ht&&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 Ht(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 Qt{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()?j.comparator(j.fromName(o.referenceValue),n.key):Tt(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 Yt{constructor(e,t="asc"){this.field=e,this.dir=t}}function Xt(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 gn(e,n):"in"===t?new mn(e,n):"not-in"===t?new vn(e,n):"array-contains-any"===t?new yn(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(Tt(t,this.value)):null!==t&&It(this.value)===It(t)&&this.matchesComparison(Tt(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 y()}}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 y()}function ln(e,t){const n=e.filters.concat(t);return tn.create(n,e.op)}function un(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(un).join(" ,")+"}"}(e):"Filter"}class hn extends en{constructor(e,t,n){super(e,t,n),this.key=j.fromName(n.referenceValue)}matches(e){const t=j.comparator(e.key,this.key);return this.matchesComparison(t)}}class dn extends en{constructor(e,t){super(e,"in",t),this.keys=pn(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=pn(0,t)}matches(e){return!this.keys.some((t=>t.isEqual(e.key)))}}function pn(e,t){var n;return((null===(n=t.arrayValue)||void 0===n?void 0:n.values)||[]).map((e=>j.fromName(e.referenceValue)))}class gn extends en{constructor(e,t){super(e,"array-contains",t)}matches(e){const t=e.data.field(this.field);return Mt(t)&&St(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&&St(this.value.arrayValue,t)}}class vn extends en{constructor(e,t){super(e,"not-in",t)}matches(e){if(St(this.value.arrayValue,{nullValue:"NULL_VALUE"}))return!1;const t=e.data.field(this.field);return null!==t&&!St(this.value.arrayValue,t)}}class yn extends en{constructor(e,t){super(e,"array-contains-any",t)}matches(e){const t=e.data.field(this.field);return!(!Mt(t)||!t.arrayValue.values)&&t.arrayValue.values.some((e=>St(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(","),ye(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(!Xt(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 j.isDocumentKey(e.path)&&null===e.collectionGroup&&0===e.filters.length}function Sn(e,t){return e.filters.filter((e=>e instanceof en&&e.field.isEqual(t)))}function Tn(e,t,n){let r=_t,i=!0;for(const n of Sn(e,t)){let e=_t,t=!0;switch(n.op){case"<":case"<=":e=Bt(n.value);break;case"==":case"in":case">=":e=n.value;break;case">":e=n.value,t=!1;break;case"!=":case"not-in":e=_t}jt({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];jt({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 Sn(e,t)){let e=bt,t=!0;switch(n.op){case">=":case">":e=Ut(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(U.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 Yt(r,n))})),e.has(U.keyField().canonicalString())||t.ce.push(new Yt(U.keyField(),n))}return t.ce}function Mn(e){const t=b(e);return t.le||(t.le=On(t,Ln(e))),t.le}function Pn(e){const t=b(e);return t.he||(t.he=On(t,e.explicitOrderBy)),t.he}function On(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 Yt(e.field,t)}));const n=e.endAt?new Qt(e.endAt.position,e.endAt.inclusive):null,r=e.startAt?new Qt(e.startAt.position,e.startAt.inclusive):null;return bn(e.path,e.collectionGroup,t,e.filters,e.limit,n,r)}}function Rn(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(Mn(e),Mn(t))&&e.limitType===t.limitType}function qn(e){return`${_n(Mn(e))}|lt:${e.limitType}`}function $n(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=>un(e))).join(", ")}]`),ye(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})`}(Mn(e))}; limitType=${e.limitType})`}function Bn(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):j.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 Un(e){return e.collectionGroup||(e.path.length%2==1?e.path.lastSegment():e.path.get(e.path.length-2))}function jn(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()?j.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?Tt(r,i):y()}(e.field,t,n);switch(e.dir){case"asc":return r;case"desc":return-1*r;default:return y()}}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(j.comparator);function Hn(){return Kn}const Qn=new nt(j.comparator);function Wn(...e){let t=Qn;for(const n of e)t=t.insert(n.key,n);return t}function Jn(e){let t=Qn;return e.forEach(((e,n)=>t=t.insert(e,n.overlayedDocument))),t}function Yn(){return Zn()}function Xn(){return Zn()}function Zn(){return new Gn((e=>e.toString()),((e,t)=>e.isEqual(t)))}const er=new nt(j.comparator),tr=new st(j.comparator);function nr(...e){let t=tr;for(const n of e)t=t.add(n);return t}const rr=new st(P);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 lr(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&>(t)&&(t=mt(t)),t&&(n.fields.__previous_value__=t),{mapValue:n}}(n,t):e instanceof fr?pr(e,t):e instanceof gr?mr(e,t):function(e,t){const n=hr(e,t),r=yr(n)+yr(e.Pe);return Lt(n)&&Lt(e.Pe)?or(r):sr(e.serializer,r)}(e,t)}function ur(e,t,n){return e instanceof fr?pr(e,t):e instanceof gr?mr(e,t):n}function hr(e,t){return e instanceof vr?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 pr(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 gr 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 vr extends cr{constructor(e,t){super(),this.serializer=e,this.Pe=t}}function yr(e){return ft(e.integerValue||e.doubleValue)}function wr(e){return Mt(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 Sr{}function Tr(e,t){if(!e.hasLocalMutations||t&&0===t.fields.length)return null;if(null===t)return e.isNoDocument()?new Or(e.key,Ir.none()):new kr(e.key,e.data,Ir.none());{const n=e.data,r=Gt.empty();let i=new st(U.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=Mr(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=Mr(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=Pr(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=Pr(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)&&O(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 gr&&t instanceof gr?O(e.elements,t.elements,Et):e instanceof vr&&t instanceof vr?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 Sr{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 Sr{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 Mr(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,ur(o,a,n[i]))}return r}function Pr(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,lr(e,s,t))}return r}class Or extends Sr{constructor(e,t){super(),this.key=e,this.precondition=t,this.type=2,this.fieldTransforms=[]}getFieldMask(){return null}}class Rr extends Sr{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=Xn();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=Tr(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&&O(this.mutations,e.mutations,((e,t)=>Ar(e,t)))&&O(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 $r{constructor(e,t,n){this.alias=e,this.aggregateType=t,this.fieldPath=n}}class Br{constructor(e,t){this.count=e,this.unchangedNames=t}}var Ur,jr;function zr(e){switch(e){default:return y();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 g("GRPC error has no .code"),_.UNKNOWN;switch(e){case Ur.OK:return _.OK;case Ur.CANCELLED:return _.CANCELLED;case Ur.UNKNOWN:return _.UNKNOWN;case Ur.DEADLINE_EXCEEDED:return _.DEADLINE_EXCEEDED;case Ur.RESOURCE_EXHAUSTED:return _.RESOURCE_EXHAUSTED;case Ur.INTERNAL:return _.INTERNAL;case Ur.UNAVAILABLE:return _.UNAVAILABLE;case Ur.UNAUTHENTICATED:return _.UNAUTHENTICATED;case Ur.INVALID_ARGUMENT:return _.INVALID_ARGUMENT;case Ur.NOT_FOUND:return _.NOT_FOUND;case Ur.ALREADY_EXISTS:return _.ALREADY_EXISTS;case Ur.PERMISSION_DENIED:return _.PERMISSION_DENIED;case Ur.FAILED_PRECONDITION:return _.FAILED_PRECONDITION;case Ur.ABORTED:return _.ABORTED;case Ur.OUT_OF_RANGE:return _.OUT_OF_RANGE;case Ur.UNIMPLEMENTED:return _.UNIMPLEMENTED;case Ur.DATA_LOSS:return _.DATA_LOSS;default:return y()}}(jr=Ur||(Ur={}))[jr.OK=0]="OK",jr[jr.CANCELLED=1]="CANCELLED",jr[jr.UNKNOWN=2]="UNKNOWN",jr[jr.INVALID_ARGUMENT=3]="INVALID_ARGUMENT",jr[jr.DEADLINE_EXCEEDED=4]="DEADLINE_EXCEEDED",jr[jr.NOT_FOUND=5]="NOT_FOUND",jr[jr.ALREADY_EXISTS=6]="ALREADY_EXISTS",jr[jr.PERMISSION_DENIED=7]="PERMISSION_DENIED",jr[jr.UNAUTHENTICATED=16]="UNAUTHENTICATED",jr[jr.RESOURCE_EXHAUSTED=8]="RESOURCE_EXHAUSTED",jr[jr.FAILED_PRECONDITION=9]="FAILED_PRECONDITION",jr[jr.ABORTED=10]="ABORTED",jr[jr.OUT_OF_RANGE=11]="OUT_OF_RANGE",jr[jr.UNIMPLEMENTED=12]="UNIMPLEMENTED",jr[jr.INTERNAL=13]="INTERNAL",jr[jr.UNAVAILABLE=14]="UNAVAILABLE",jr[jr.DATA_LOSS=15]="DATA_LOSS";let Kr=null;function Hr(){return new TextEncoder}const Qr=new a.Integer([4294967295,4294967295],0);function Wr(e){const t=Hr().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 Yr{constructor(e,t,n){if(this.bitmap=e,this.padding=t,this.hashCount=n,t<0||t>=8)throw new Xr(`Invalid padding: ${t}`);if(n<0)throw new Xr(`Invalid hash count: ${n}`);if(e.length>0&&0===this.hashCount)throw new Xr(`Invalid hash count: ${n}`);if(0===e.length&&0!==t)throw new Xr(`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(Qr)&&(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 Yr(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 Xr 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(P),Hn(),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=ut.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=ut.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:y()}})),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=Hn(),this.qe=oi(),this.Qe=oi(),this.Ke=new nt(P)}$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:y()}}))}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 j(i.path);this.We(t,e,Ht.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,l,u;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!==(u=null===(l=null==d?void 0:d.bits)||void 0===l?void 0:l.padding)&&void 0!==u?u: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=pt(n).toUint8Array()}catch(e){if(e instanceof lt)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 Yr(s,r,i)}catch(e){return m(e instanceof Xr?"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 j(i.target.path);this.st(t).has(r)||this.ot(r,t)||this.We(r,t,Ht.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=Hn(),this.qe=oi(),this.Qe=oi(),this.Ke=new nt(P),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(P),this.Qe=this.Qe.insert(e,t)),t}st(e){let t=this.qe.get(e);return t||(t=new st(P),this.qe=this.qe.insert(e,t)),t}je(e){const t=null!==this.Ye(e);return t||p("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(j.comparator)}function ai(){return new nt(j.comparator)}const ci={asc:"ASCENDING",desc:"DESCENDING"},li={"<":"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"},ui={and:"AND",or:"OR"};class hi{constructor(e,t){this.databaseId=e,this.useProto3Json=t}}function di(e,t){return e.useProto3Json||ye(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 pi(e,t){return e.useProto3Json?t.toBase64():t.toUint8Array()}function gi(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 vi(e,t){return yi(e,t).canonicalString()}function yi(e,t){const n=function(e){return new $(["projects",e.projectId,"databases",e.database])}(e).child("documents");return void 0===t?n:n.child(t)}function wi(e){const t=$.fromString(e);return w(Ui(t)),t}function bi(e,t){return vi(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 j(Ti(n))}function Ii(e,t){return vi(e.databaseId,t)}function Ei(e){const t=wi(e);return 4===t.length?$.emptyPath():Ti(t)}function Si(e){return new $(["projects",e.databaseId.projectId,"databases",e.databaseId.database]).canonicalString()}function Ti(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=Ht.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 Or)n={delete:bi(e,t.key)};else if(t instanceof Nr)n={update:xi(e,t.key,t.data),updateMask:Bi(t.fieldMask)};else{if(!(t instanceof Rr))return y();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 gr)return{fieldPath:t.field.canonicalString(),removeAllFromArray:{values:n.elements}};if(n instanceof vr)return{fieldPath:t.field.canonicalString(),increment:n.Pe};throw y()}(0,e)))),t.precondition.isNone||(n.currentDocument=function(e,t){return void 0!==t.updateTime?{updateTime:gi(e,t.updateTime)}:void 0!==t.exists?{exists:t.exists}:y()}(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 gr(e)}else"increment"in t?n=new vr(e,t.increment):y();const r=U.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=>U.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 Or(r,n)}if(t.verify){const r=_i(e,t.verify);return new Rr(r,n)}return y()}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 $i(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:Oi(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 Mi(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=Pi(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 Yt(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,ye(t)?null:t}(n.limit));let c=null;n.startAt&&(c=function(e){const t=!!e.before,n=e.values||[];return new Qt(n,t)}(n.startAt));let l=null;return n.endAt&&(l=function(e){const t=!e.before,n=e.values||[];return new Qt(n,t)}(n.endAt)),Dn(t,i,o,s,a,"F",c,l)}function Pi(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 y()}}(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 y()}}(e.fieldFilter.op),e.fieldFilter.value)}(e):void 0!==e.compositeFilter?function(e){return tn.create(e.compositeFilter.filters.map((e=>Pi(e))),function(e){switch(e){case"AND":return"and";case"OR":return"or";default:return y()}}(e.compositeFilter.op))}(e):y()}function Oi(e){return ci[e]}function Ri(e){return li[e]}function Fi(e){return ui[e]}function Vi(e){return{fieldPath:e.canonicalString()}}function qi(e){return U.fromServerFormat(e.fieldPath)}function $i(e){return e instanceof en?function(e){if("=="===e.op){if(Ot(e.value))return{unaryFilter:{field:Vi(e.field),op:"IS_NAN"}};if(Pt(e.value))return{unaryFilter:{field:Vi(e.field),op:"IS_NULL"}}}else if("!="===e.op){if(Ot(e.value))return{unaryFilter:{field:Vi(e.field),op:"IS_NOT_NAN"}};if(Pt(e.value))return{unaryFilter:{field:Vi(e.field),op:"IS_NOT_NULL"}}}return{fieldFilter:{field:Vi(e.field),op:Ri(e.op),value:e.value}}}(e):e instanceof tn?function(e){const t=e.getFilters().map((e=>$i(e)));return 1===t.length?t[0]:{compositeFilter:{op:Fi(e.op),filters:t}}}(e):y()}function Bi(e){const t=[];return e.fields.forEach((e=>t.push(e.canonicalString()))),{fieldPaths:t}}function Ui(e){return e.length>=4&&"projects"===e.get(0)&&"databases"===e.get(2)}class ji{constructor(e,t,n,r,i=V.min(),s=V.min(),o=ut.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 ji(this.target,this.targetId,this.purpose,e,this.snapshotVersion,this.lastLimboFreeSnapshotVersion,this.resumeToken,this.expectedCount)}withResumeToken(e,t){return new ji(this.target,this.targetId,this.purpose,this.sequenceNumber,t,this.lastLimboFreeSnapshotVersion,e,null)}withExpectedCount(e){return new ji(this.target,this.targetId,this.purpose,this.sequenceNumber,this.snapshotVersion,this.lastLimboFreeSnapshotVersion,this.resumeToken,e)}withLastLimboFreeSnapshotVersion(e){return new ji(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:Hi(t.version)};else{if(!t.isUnknownDocument())return y();r.unknownDocument={path:n.path.toArray(),version:Hi(t.version)}}return r}function Ki(e){const t=e.toTimestamp();return[t.seconds,t.nanoseconds]}function Hi(e){const t=e.toTimestamp();return{seconds:t.seconds,nanoseconds:t.nanoseconds}}function Qi(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=Qi(e.readTime),n=void 0!==e.lastLimboFreeSnapshotVersion?Qi(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),Mn(An(Ei(e.documents[0])))}(e.query):function(e){return Mn(Mi(e))}(e.query),new ji(r,e.targetId,"TargetPurposeListen",e.lastListenSequenceNumber,t,n,ut.fromBase64String(e.resumeToken))}function Yi(e,t){const n=Hi(t.snapshotVersion),r=Hi(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 Xi(e){const t=Mi({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:Hi(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:Qi(e.createTime),version:e.version}}(e)}))}saveBundleMetadata(e,t){return rs(e).put(function(e){return{bundleId:e.id,createTime:Hi(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:Xi(e.bundledQuery),readTime:Qi(e.readTime)}}(e)}))}saveNamedQuery(e,t){return is(e).put(function(e){return{name:e.name,readTime:Hi(mi(e.readTime)),bundledQuery:e.bundledQuery}}(t))}}function rs(e){return Ye(e,"bundles")}function is(e){return Ye(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=Yn();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=Yn(),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=Yn();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 Ye(e,"documentOverlays")}class as{It(e){return Ye(e,"globals")}getSessionToken(e){return this.It(e).get("sessionToken").next((e=>{const t=null==e?void 0:e.value;return t?ut.fromUint8Array(t):ut.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(pt(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)):y()}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),j.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 ls(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 us(e){const t=64-function(e){let t=0;for(let n=0;n<8;++n){const r=ls(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=us(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=us(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 ps{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 gs{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 gs(this.indexId,this.documentKey,this.arrayValue,n)}}function ms(e,t){let n=e.indexId-t.indexId;return 0!==n?n:(n=vs(e.arrayValue,t.arrayValue),0!==n?n:(n=vs(e.directionalValue,t.directionalValue),0!==n?n:j.comparator(e.documentKey,t.documentKey)))}function vs(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 ys{constructor(e){this.tn=new st(((e,t)=>U.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(U.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 Q(n.field,2));else{if(e.has(n.field))continue;e=e.add(n.field),t.push(new Q(n.field,0))}for(const n of this.nn)n.field.isKeyField()||e.has(n.field)||(e=e.add(n.field),t.push(new Q(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=Ss(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 Ss(e){if(w(e instanceof en||e instanceof tn),e instanceof en)return e;if(1===e.filters.length)return Ss(e.filters[0]);const t=e.filters.map((e=>Ss(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)=>Ts(e,t))))}function Ts(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 ln(e,t.getFilters());const n=rn(e)?e:t,r=rn(e)?t:e,i=n.filters.map((e=>Ts(e,r)));return tn.create(i,"or")}(e,t),Cs(n)}function xs(e,t){if(nn(t))return ln(t,e.getFilters());{const n=t.filters.map((t=>Ts(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($.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($.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,""],[R(t),""],!1,!0);return Ls(e).U(r).next((e=>{for(const r of e){if(r.collectionId!==t)break;n.push(Se(r.parent))}return n}))}addFieldIndex(e,t){const n=Ps(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=Os(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=Ps(e),r=Os(e),i=Ms(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=Ps(e),n=Ms(e),r=Os(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 ys(t).cn();if(null!=n)return this.addFieldIndex(e,n)}}))))}getDocumentsMatchingTarget(e,t){const n=Ms(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)=>{p("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 Sn(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 Sn(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?Tn(e,i.fieldPath,e.startAt):xn(e,i.fieldPath,e.startAt);n.push(t.value),r&&(r=t.inclusive)}return new Qt(n,r)}(s,i),l=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):Tn(e,i.fieldPath,e.endAt);n.push(t.value),r&&(r=t.inclusive)}return new Qt(n,r)}(s,i),u=this.En(i,s,c),h=this.En(i,s,l),d=this.dn(i,s,a),f=this.An(i.indexId,o,u,c.inclusive,h,l.inclusive,d);return ie.forEach(f,(i=>n.G(i,t.limit).next((t=>{t.forEach((t=>{const n=j.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),l=[];for(let u=0;u<a;++u){const a=t?this.Rn(t[u/c]):ks,h=this.Vn(e,a,n[u%c],r),d=this.mn(e,a,i[u%c],s),f=o.map((t=>this.Vn(e,a,t,!0)));l.push(...this.createRange(h,d,f))}return l}Vn(e,t,n,r){const i=new gs(e,j.empty(),t,n);return r?i:i.en()}mn(e,t,n,r){const i=new gs(e,j.empty(),t,n);return r?i.en():i}In(e,t){const n=new ys(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(U.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 ps;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 ps;return cs.Ft.Et(e,t.Xt(0)),t.Ht()}gn(e,t){const n=new ps;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 ps);let i=0;for(const s of K(e)){const e=n[i++];for(const n of r)if(this.pn(t,s.fieldPath)&&Mt(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 ps;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=Ps(e),r=Os(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(Qi(t.readTime),new j(Se(t.documentKey)),t.largestBatchId)):J.empty(),r=e.fields.map((([e,t])=>new Q(U.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:P(e.collectionGroup,t.collectionGroup)})),e[0].collectionGroup)))}updateCollectionGroup(e,t,n){const r=Ps(e),i=Os(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 Ms(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 Ms(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=Ms(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 gs(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(Mt(s))for(const i of s.arrayValue.values||[])n=n.add(new gs(t.indexId,e.key,this.Rn(i),r))}else n=n.add(new gs(t.indexId,e.key,ks,r));return n}vn(e,t,n,r,i){p("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 Os(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(Rs)}getMinOffset(e,t){return ie.mapArray(this.Tn(t),(t=>this.In(e,t).next((e=>e||y())))).next(Rs)}}function Ls(e){return Ye(e,"collectionParents")}function Ms(e){return Ye(e,"indexEntries")}function Ps(e){return Ye(e,"indexConfiguration")}function Os(e){return Ye(e,"indexState")}function Rs(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 l=[];for(const e of n.mutations){const r=Ce(t,e.key.path,n.batchId);s.push(i.delete(r)),l.push(e.key)}return ie.waitFor(s).next((()=>l))}function $s(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 y();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 Bs{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 Bs(i,t,n,r)}checkEmpty(e){let t=!0;const n=IDBKeyRange.bound([this.userId,Number.NEGATIVE_INFINITY],[this.userId,Number.POSITIVE_INFINITY]);return js(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=js(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),l=[];let u=new st(((e,t)=>P(e.canonicalString(),t.canonicalString())));for(const e of r){const t=Ce(this.userId,e.key.path,o);u=u.add(e.key.path.popLast()),l.push(s.put(c)),l.push(i.put(t,De))}return u.forEach((t=>{l.push(this.indexManager.addToCollectionParentIndex(e,t))})),e.addOnCommittedListener((()=>{this.xn[o]=a.keys()})),ie.waitFor(l).next((()=>a))}))}lookupMutationBatch(e,t){return js(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 js(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 js(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 js(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,l=Se(a);if(o===this.userId&&t.path.isEqual(l))return js(e).get(c).next((e=>{if(!e)throw y();w(e.userId===this.userId),i.push(Wi(this.serializer,e))}));s.done()})).next((()=>i))}getAllMutationBatchesAffectingDocumentKeys(e,t){let n=new st(P);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=Se(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(P);return zs(e).J({range:s},((e,t,i)=>{const[s,a,c]=e,l=Se(a);s===this.userId&&n.isPrefixOf(l)?l.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(js(e).get(t).next((e=>{if(null===e)throw y();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=Se(e[1]);r.push(t)}else n.done()})).next((()=>{w(0===r.length)}))}))}containsKey(e,t){return Us(e,this.userId,t)}Bn(e){return Gs(e).get(this.userId).next((e=>e||{userId:this.userId,lastAcknowledgedBatchId:-1,lastStreamToken:""}))}}function Us(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 js(e){return Ye(e,"mutations")}function zs(e){return Ye(e,"documentMutations")}function Gs(e){return Ye(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 Hs{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((()=>Qs(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 Qs(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 Qs(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 Qs(e).put(Yi(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 Qs(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=Se(e[1]),s=new j(r);i=i.add(s)})).next((()=>i))}containsKey(e,t){const n=_e(t.path),r=IDBKeyRange.bound([n],[R(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 Qs(e).get(t).next((e=>e?Ji(e):null))}}function Qs(e){return Ye(e,"targets")}function Ws(e){return Ye(e,"targetGlobal")}function Js(e){return Ye(e,"targetDocuments")}function Ys([e,t],[n,r]){const i=P(e,n);return 0===i?P(t,r):i}class Xs{constructor(e){this.Gn=e,this.buffer=new st(Ys),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();Ys(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){p("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){ue(e)?p("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(ve.oe);const n=new Xs(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?(p("LruGarbageCollector","Garbage collection skipped; disabled"),ie.resolve(Fs)):this.getCacheSize(e).next((n=>n<this.params.cacheSizeCollectionThreshold?(p("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,l;const u=Date.now();return this.calculateTargetCount(e,this.params.percentileToCollect).next((t=>(t>this.params.maximumSequenceNumbersToCollect?(p("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=>(l=Date.now(),f()<=s.LogLevel.DEBUG&&p("LruGarbageCollector",`LRU Garbage Collection\n\tCounted targets in ${o-u}ms\n\tDetermined least recently used ${r} in `+(a-o)+"ms\n"+`\tRemoved ${i} targets in `+(c-a)+"ms\n"+`\tRemoved ${e} documents in `+(l-c)+"ms\n"+`Total Duration: ${l-u}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=>Us(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=ve.oe;return n.J({index:"documentTargetsIndex"},(([e,n],{path:s,sequenceNumber:o})=>{0===e?(i!==ve.oe&&t(new j(Se(r)),i),i=o,r=s):i=ve.oe})).next((()=>{i!==ve.oe&&t(new j(Se(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,Ht.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 lo(e).put(n)}removeEntry(e,t,n){return lo(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=Ht.newInvalidDocument(t);return lo(e).J({index:"documentKeyIndex",range:IDBKeyRange.only(uo(t))},((e,r)=>{n=this._r(t,r)})).next((()=>n))}ar(e,t){let n={size:0,document:Ht.newInvalidDocument(t)};return lo(e).J({index:"documentKeyIndex",range:IDBKeyRange.only(uo(t))},((e,r)=>{n={document:this._r(t,r),size:$s(r)}})).next((()=>n))}getEntries(e,t){let n=Hn();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=Hn(),r=new nt(j.comparator);return this.ur(e,t,((e,t)=>{const i=this._r(e,t);n=n.insert(e,i),r=r.insert(e,$s(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(uo(r.first()),uo(r.last())),s=r.getIterator();let o=s.getNext();return lo(e).J({index:"documentKeyIndex",range:i},((e,t,r)=>{const i=j.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.$(uo(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 lo(e).U(IDBKeyRange.bound(o,a,!0)).next((e=>{null==i||i.incrementDocumentReadCount(e.length);let n=Hn();for(const i of e){const e=this._r(j.fromSegments(i.prefixPath.concat(i.collectionGroup,i.documentId)),i);e.isFoundDocument()&&(Bn(t,e)||r.has(e.key))&&(n=n.insert(e.key,e))}return n}))}getAllFromCollectionGroup(e,t,n,r){let i=Hn();const s=ho(t,n),o=ho(t,Z.max());return lo(e).J({index:"collectionGroupIndex",range:IDBKeyRange.bound(s,o,!0)},((e,t,n)=>{const s=this._r(j.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=j.fromSegments(t.noDocument.path),r=Qi(t.noDocument.readTime);n=Ht.newNoDocument(e,r),t.hasCommittedMutations&&n.setHasCommittedMutations()}else{if(!t.unknownDocument)return y();{const e=j.fromSegments(t.unknownDocument.path),r=Qi(t.unknownDocument.version);n=Ht.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 Ht.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)=>P(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=$s(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 Ye(e,"remoteDocumentGlobal")}function lo(e){return Ye(e,"remoteDocumentsV14")}function uo(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=P(n[e],r[e]),i)return i;return i=P(n.length,r.length),i||(i=P(n[n.length-2],r[r.length-2]),i||P(n[n.length-1],r[r.length-1]))}class po{constructor(e,t){this.overlayedDocument=e,this.mutatedFields=t}}class go{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=Yn();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=Yn();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=Hn();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 po(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,l=Xn();c.forEach((e=>{if(!i.has(e)){const r=Tr(t.get(e),n.get(e));null!==r&&l.set(e,r),i=i.add(e)}})),s.push(this.documentOverlayCache.saveOverlays(e,a,l))}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 j.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(Yn());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 j(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,Ht.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()),Bn(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:Xi(e.bundledQuery),readTime:mi(e.readTime)}}(t)),ie.resolve()}}class vo{constructor(){this.overlays=new nt(j.comparator),this.Er=new Map}getOverlay(e,t){return ie.resolve(this.overlays.get(t))}getOverlays(e,t){const n=Yn();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=Yn(),i=t.length+1,s=new j(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=Yn(),i=i.insert(e.largestBatchId,t)),t.set(e.getKey(),e)}}const o=Yn(),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 yo{constructor(){this.sessionToken=ut.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 j(new $([])),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 j(new $([])),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 j.comparator(e.key,t.key)||P(e.br,t.br)}static Vr(e,t){return P(e.br,t.br)||j.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(P);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;j.isDocumentKey(i)||(i=i.child(""));const s=new bo(new j(i),0);let o=new st(P);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(j.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():Ht.newInvalidDocument(t))}getEntries(e,t){let n=Hn();return t.forEach((e=>{const t=this.docs.get(e);n=n.insert(e,t?t.document.mutableCopy():Ht.newInvalidDocument(e))})),ie.resolve(n)}getDocumentsMatchingQuery(e,t,n,r){let i=Hn();const s=t.path,o=new j(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(X(o),n)<=0||(r.has(o.key)||Bn(t,o))&&(i=i.insert(o.key,o.mutableCopy()))}return ie.resolve(i)}getAllFromCollectionGroup(e,t,n,r){y()}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 So{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 To{constructor(e,t){this.Kr={},this.overlays={},this.$r=new ve(0),this.Ur=!1,this.Ur=!0,this.Wr=new yo,this.referenceDelegate=e(this),this.Gr=new So(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 vo,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){p("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 y()}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=j.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",Te,{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",Te,{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:$e});t.createIndex("collectionPathOverlayIndex",Be,{unique:!1}),t.createIndex("collectionGroupOverlayIndex",Ue,{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:Re}).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+=$s(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 $(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:Oe});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 $(e);return i(n.popLast())})).next((()=>t.store("documentMutations").J({H:!0},(([e,t,n],r)=>{const s=Se(t);return i(s.popLast())}))))}ai(e){const t=e.store("targets");return t.J(((e,n)=>{const r=Ji(n),i=Yi(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 j($.fromString(e.document.name).popFirst(5)):e.noDocument?j.fromSegments(e.noDocument.path):e.unknownDocument?j.fromSegments(e.unknownDocument.path):y()}(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 To(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 u(n),o=ss.Pt(this.serializer,s),a=i.getIndexManager(s),c=Bs.Pt(s,this.serializer,a,i.referenceDelegate);return new go(r,c,o,a).recalculateAndSaveOverlaysForDocumentKeys(new Je(t,ve.oe),e).next()}))}))}}function ko(e){e.createObjectStore("targetDocuments",{keyPath:Me}).createIndex("documentTargetsIndex",Pe,{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,l,u=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=l,this.Ti=u,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 Hs(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===l&&g("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 ve(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=>Po(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(ue(e))return p("IndexedDbPersistence","Failed to extend owner lease: ",e),this.isPrimary;if(!this.allowTabSynchronization)throw e;return p("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 Mo(e).get("owner").next((e=>ie.resolve(this.Fi(e))))}Mi(e){return Po(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=Ye(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):Mo(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)||Po(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&&p("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,ve.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=>Po(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 Bs.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){p("IndexedDbPersistence","Starting transaction:",e);const r="readonly"===t?"readonly":"readwrite",i=function(e){return 17===e?We:16===e?Qe:15===e?He:14===e?Ke:13===e?Ge:12===e?ze:11===e?je:void y()}(this.Ti);let s;return this.mi.runTransaction(e,r,i,(r=>(s=new Je(r,this.$r?this.$r.next():ve.oe),"readwrite-primary"===t?this.bi(s).next((e=>!!e||this.Di(s))).next((t=>{if(!t)throw g(`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 Mo(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 Mo(e).put("owner",t)}static p(){return oe.p()}vi(e){const t=Mo(e);return t.get("owner").next((e=>this.Fi(e)?(p("IndexedDbPersistence","Releasing primary lease."),t.delete("owner")):ie.resolve()))}Oi(e,t){const n=Date.now();return!(e<n-t||e>n&&(g(`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 p("IndexedDbPersistence",`Client '${e}' ${n?"is":"is not"} zombied in LocalStorage`),n}catch(e){return g("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){g("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 Mo(e){return Ye(e,"owner")}function Po(e){return Ye(e,"clientMetadata")}function Oo(e,t){let n=e.projectId;return e.isDefaultDatabase||(n+="."+e.database),"firestore/"+t+"/"+n+"/"}class Ro{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 Ro(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&&p("QueryEngine","SDK will not create cache indexes for query:",$n(t),"since it only creates cache indexes for collection contains","more than or equal to",this.Ji,"documents"),ie.resolve()):(f()<=s.LogLevel.DEBUG&&p("QueryEngine","Query:",$n(t),"scans",n.documentReadCount,"local documents and returns",r,"documents as results."),n.documentReadCount>this.Yi*r?(f()<=s.LogLevel.DEBUG&&p("QueryEngine","The SDK decides to create cache indexes for query:",$n(t),"as using cache indexes may help improve performance."),this.indexManager.createTargetIndexes(e,Mn(t))):ie.resolve())}Xi(e,t){if(kn(t))return ie.resolve(null);let n=Mn(t);return this.indexManager.getIndexType(e,n).next((r=>0===r?null:(null!==t.limit&&1===r&&(t=Fn(t,null,"F"),n=Mn(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&&p("QueryEngine","Re-using previous result from %s to execute query: %s",r.toString(),$n(t)),this.os(e,o,t,Y(r,-1)).next((e=>e)))}))}rs(e,t){let n=new st(jn(e));return t.forEach(((t,r)=>{Bn(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&&p("QueryEngine","Using full collection scan to execute query:",$n(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(P),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 go(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 $o(e,t,n,r){return new qo(e,t,n,r)}async function Bo(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 Uo(e){const t=b(e);return t.persistence.runTransaction("Get last remote snapshot version","readonly",(e=>t.Gr.getLastRemoteSnapshotVersion(e)))}function jo(e,t,n){let r=nr(),i=nr();return n.forEach((e=>r=r.add(e))),t.getEntries(e,r).next((e=>{let r=Hn();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)):p("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 ji(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(!ue(e))throw e;p("LocalStore",`Failed to update sequence numbers for target ${t}: ${e}`)}r.us=r.us.remove(t),r.cs.delete(i.target)}function Ho(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,Mn(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,Un(t),e),{documents:e,ds:s})))))}function Qo(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,Y(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 Yo(e,t,n=nr()){const r=await Go(e,Mn(Xi(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(ut.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 Xo(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):(g("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):(g("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):(g("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):(g("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(P),this.started=!1,this.vs=[];const s=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");this.storage=this.window.localStorage,this.currentUser=i,this.Cs=Xo(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(Xo(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 p("SharedClientState","READ",e,t),t}setItem(e,t){p("SharedClientState","SET",e,t),this.storage.setItem(e,t)}removeItem(e){p("SharedClientState","REMOVE",e),this.storage.removeItem(e)}bs(e){const t=e;if(t.storageArea===this.storage){if(p("SharedClientState","EVENT",t.key,t.newValue),t.key===this.Cs)return void g("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=ve.oe;if(null!=e)try{const n=JSON.parse(e);w("number"==typeof n),t=n}catch(e){g("SharedClientState","Failed to read sequence number from WebStorage",e)}return t}(t.newValue);e!==ve.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 u(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);p("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 la{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(){p("ConnectivityMonitor","Network connectivity changed: AVAILABLE");for(const e of this.To)e(0)}Po(){p("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 ua=null;function ha(){return null===ua?ua=268435456+Math.round(2147483648*Math.random()):ua++,"0x"+ua.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 pa="WebChannelConnection";class ga 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());p("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=>(p("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();p(pa,`XHR for RPC '${e}' ${i} received:`,JSON.stringify(t)),s(t);break;case c.ErrorCode.TIMEOUT:p(pa,`RPC '${e}' ${i} timed out`),o(new I(_.DEADLINE_EXCEEDED,"Request time out"));break;case c.ErrorCode.HTTP_ERROR:const n=a.getStatus();if(p(pa,`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:y()}}finally{p(pa,`RPC '${e}' ${i} completed.`)}}));const l=JSON.stringify(r);p(pa,`RPC '${e}' ${i} sending request:`,r),a.send(t,"POST",l,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},l=this.longPollingOptions.timeoutSeconds;void 0!==l&&(a.longPollingTimeout=Math.round(1e3*l)),this.useFetchStreams&&(a.useFetchStreams=!0),this.Lo(a.initMessageHeaders,t,n),a.encodeInitMessageHeaders=!0;const u=i.join("");p(pa,`Creating RPC '${e}' stream ${r}: ${u}`,a);const h=s.createWebChannel(u,a);let d=!1,f=!1;const g=new fa({Eo:t=>{f?p(pa,`Not sending because RPC '${e}' stream ${r} is closed:`,t):(d||(p(pa,`Opening RPC '${e}' stream ${r} transport.`),h.open(),d=!0),p(pa,`RPC '${e}' stream ${r} sending:`,t),h.send(t))},Ao:()=>h.close()}),v=(e,t,n)=>{e.listen(t,(e=>{try{n(e)}catch(e){setTimeout((()=>{throw e}),0)}}))};return v(h,c.WebChannel.EventType.OPEN,(()=>{f||(p(pa,`RPC '${e}' stream ${r} transport opened.`),g.So())})),v(h,c.WebChannel.EventType.CLOSE,(()=>{f||(f=!0,p(pa,`RPC '${e}' stream ${r} transport closed`),g.Do())})),v(h,c.WebChannel.EventType.ERROR,(t=>{f||(f=!0,m(pa,`RPC '${e}' stream ${r} transport errored:`,t),g.Do(new I(_.UNAVAILABLE,"The operation could not be completed")))})),v(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){p(pa,`RPC '${e}' stream ${r} received error:`,o);const t=o.status;let n=function(e){const t=Ur[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,g.Do(new I(n,i)),h.close()}else p(pa,`RPC '${e}' stream ${r} received:`,i),g.vo(i)}})),v(o,c.Event.STAT_EVENT,(t=>{t.stat===c.Stat.PROXY?p(pa,`RPC '${e}' stream ${r} detected buffering proxy`):t.stat===c.Stat.NOPROXY&&p(pa,`RPC '${e}' stream ${r} detected no buffering proxy`)})),setTimeout((()=>{g.bo()}),0),g}}function ma(){return"undefined"!=typeof window?window:null}function va(){return"undefined"!=typeof document?document:null}function ya(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&&p("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?(g(t.toString()),g("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 p("PersistentStream",`close with error: ${e}`),this.stream=null,this.close(4,e)}T_(e){return t=>{this.li.enqueueAndForget((()=>this.Xo===e?t():(p("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:y()}(t.targetChange.targetChangeType||"NO_CHANGE"),i=t.targetChange.targetIds||[],s=function(e,t){return e.useProto3Json?(w(void 0===t||"string"==typeof t),ut.fromBase64String(t||"")):(w(void 0===t||t instanceof Buffer||t instanceof Uint8Array),ut.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=Ht.newFoundDocument(i,s,o,a),l=r.targetIds||[],u=r.removedTargetIds||[];n=new ti(l,u,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=Ht.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 y();{t.filter;const e=t.filter;e.targetId;const{count:r=0,unchangedNames:i}=e,s=new Br(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=Si(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=pi(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 y()}}(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=Si(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=Si(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,yi(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,yi(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 Sa{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_?(g(t),this.C_=!1):p("OnlineStateTracker",t)}N_(){null!==this.v_&&(this.v_.cancel(),this.v_=null)}}class Ta{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()=>{Pa(this)&&(p("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 Sa(n,r)}}async function xa(e){if(Pa(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),Ma(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_():Pa(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 Ma(e){return Pa(e)&&!Za(e).i_()&&e.B_.size>0}function Pa(e){return 0===b(e).k_.size}function Oa(e){e.U_=void 0}async function Ra(e){e.K_.set("Online")}async function Fa(e){e.B_.forEach(((t,n)=>{ka(e,t)}))}async function Va(e,t){Oa(e),Ma(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){p("RemoteStore","Failed to remove targets %s: %s ",t.targetIds.join(","),n),await $a(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 Uo(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(ut.EMPTY_BYTE_STRING,r.snapshotVersion)),Na(e,t);const i=new ji(r.target,t,n,r.sequenceNumber);ka(e,i)})),e.remoteSyncer.applyRemoteEvent(n)}(e,n)}catch(t){p("RemoteStore","Failed to raise snapshot:",t),await $a(e,t)}}async function $a(e,t,n){if(!ue(t))throw t;e.k_.add(1),await Ca(e),e.K_.set("Offline"),n||(n=()=>Uo(e.localStore)),e.asyncQueue.enqueueRetryable((async()=>{p("RemoteStore","Retrying IndexedDB access"),await n(),e.k_.delete(1),await xa(e)}))}function Ba(e,t){return t().catch((n=>$a(e,n,t)))}async function Ua(e){const t=b(e),n=ec(t);let r=t.L_.length>0?t.L_[t.L_.length-1].batchId:-1;for(;ja(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 $a(t,e)}Ga(t)&&Ka(t)}function ja(e){return Pa(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 Pa(e)&&!ec(e).i_()&&e.L_.length>0}function Ka(e){ec(e).start()}async function Ha(e){ec(e).w_()}async function Qa(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 Ba(e,(()=>e.remoteSyncer.applySuccessfulWrite(i))),await Ua(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 Ba(e,(()=>e.remoteSyncer.rejectFailedWrite(n.batchId,t))),await Ua(e)}}(e,t),Ga(e)&&Ka(e)}async function Ya(e,t){const n=b(e);n.asyncQueue.verifyOperationInProgress(),p("RemoteStore","RemoteStore received new credentials");const r=Pa(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 Xa(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:Ra.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_.__(),Ma(e)?La(e):e.K_.set("Unknown")):(await e.W_.stop(),Oa(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:Ha.bind(null,e),po:Ja.bind(null,e),p_:Qa.bind(null,e),y_:Wa.bind(null,e)}),e.q_.push((async t=>{t?(e.G_.__(),await Ua(e)):(await e.G_.stop(),e.L_.length>0&&(p("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(g("AsyncQueue",`${t}: ${e}`),ue(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)||j.comparator(t.key,n.key):(e,t)=>j.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(j.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}):y():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 lc(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 '${$n(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 uc(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 pc,gc;(gc=pc||(pc={})).na="default",gc.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!==pc.Cache}}class vc{constructor(e,t){this.ca=e,this.byteLength=t}la(){return"metadata"in this.ca}}class yc{constructor(e){this.serializer=e}As(e){return _i(this.serializer,e)}Rs(e){return e.metadata.exists?Ci(this.serializer,e.document,!1):Ht.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=$.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 yc(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=Hn();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 Mn(An($.fromString(`__bundle__/docs/${e}`)))}(r));return i.persistence.runTransaction("Apply bundle documents","readwrite",(e=>jo(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 yc(this.serializer),this.documents,this.ha.id),t=this.Ta(this.documents);for(const e of this.queries)await Yo(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=jn(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 l=r.get(e),u=Bn(this.query,t)?t:null,h=!!l&&this.mutatedKeys.has(l.key),d=!!u&&(u.hasLocalMutations||this.mutatedKeys.has(u.key)&&u.hasCommittedMutations);let f=!1;l&&u?l.data.isEqual(u.data)?h!==d&&(n.track({type:3,doc:u}),f=!0):this.ya(l,u)||(n.track({type:2,doc:u}),f=!0,(a&&this.Va(u,a)>0||c&&this.Va(u,c)<0)&&(o=!0)):!l&&u?(n.track({type:0,doc:u}),f=!0):l&&!u&&(n.track({type:1,doc:l}),f=!0,(a||c)&&(o=!0)),f&&(u?(s=s.add(u),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 y()}};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 Sc{constructor(e,t,n){this.query=e,this.targetId=t,this.view=n}}class Tc{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(j.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=nl(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=nl(e);await Ac(n,t,!0,!1)}async function Ac(e,t,n,r){const i=await Go(e.localStore,Mn(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 Ho(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 Uc(e,t.targetId,a.ba),a.snapshot}(e,t,n,r);const s=await Ho(e.localStore,t,!0),o=new Ec(t,s.ds),a=o.ga(s.documents),c=ei.createSynthesizedTargetChangeForCurrentChange(n,r&&"Offline"!==e.onlineState,i),l=o.applyChanges(a,e.isPrimaryClient,c);Uc(e,n,l.ba);const u=new Sc(t,n,o);return e.xa.set(t,u),e.Oa.has(n)?e.Oa.get(n).push(t):e.Oa.set(n,[t]),l.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),$c(r,i.targetId)})).catch(re)):($c(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 Mc(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 l=c.withSequenceNumber(e.currentSequenceNumber);null!==t.targetMismatches.get(a)?l=l.withResumeToken(ut.EMPTY_BYTE_STRING,V.min()).withLastLimboFreeSnapshotVersion(V.min()):s.resumeToken.approximateByteSize()>0&&(l=l.withResumeToken(s.resumeToken,r)),i=i.insert(a,l),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,l,s)&&o.push(n.Gr.updateTargetData(e,l))}));let a=Hn(),c=nr();if(t.documentUpdates.forEach((r=>{t.resolvedLimboDocuments.has(r)&&o.push(n.persistence.referenceDelegate.updateLimboDocument(e,r))})),o.push(jo(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 Pc(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 Oc(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(j.comparator);e=e.insert(s,Ht.newNoDocument(s,V.min()));const n=nr().add(s),i=new Zr(V.min(),new Map,new nt(P),e,n);await Mc(r,i),r.La=r.La.remove(s),r.Ba.delete(t),zc(r)}else await Ko(r.localStore,t,!1).then((()=>$c(r,t,n))).catch(re)}async function Rc(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 $c(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)||Bc(e,t)}))}function Bc(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 Uc(e,t,n){for(const r of n)r instanceof _c?(e.ka.addReference(r.key,t),jc(e,r)):r instanceof Ic?(p("SyncEngine","Document no longer in limbo: "+r.key),e.ka.removeReference(r.key,t),e.ka.containsKey(r.key)||Bc(e,r.key)):y()}function jc(e,t){const n=t.key,r=n.path.canonicalString();e.La.get(n)||e.Na.has(r)||(p("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 j($.fromString(t)),r=e.Ka.next();e.Ba.set(r,new Tc(n)),e.La=e.La.insert(n,r),Da(e.remoteStore,new ji(Mn(An(n.path)),r,"TargetPurposeLimboResolution",ve.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=Ro.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(!ue(e))throw e;p("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)){p("SyncEngine","User change. New user:",t.toKey());const e=await Bo(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 Hc(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 Qc(e,t){const n=b(e),r=await Ho(n.localStore,t.query,!0),i=t.view.va(r);return n.isPrimaryClient&&Uc(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 Ua(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)):y(),await Gc(i,s)):p("SyncEngine","Cannot apply mutation batch with id: "+t)}async function Yc(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,Mn(n[0]));for(const e of n){const t=r.xa.get(e),n=await Qc(r,t);n.snapshot&&s.push(n.snapshot)}}else{const n=await Qo(r.localStore,e);t=await Go(r.localStore,n),await kc(r,Xc(n),e,!1,t.resumeToken)}i.push(t)}return r.Ma.R_(s),i}function Xc(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 el(e,t,n,r){const i=b(e);if(i.$a)return void p("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,Un(s[0])),r=Zr.createSynthesizedRemoteEventForCurrentChange(t,"current"===n,ut.EMPTY_BYTE_STRING);await Gc(i,e,r);break}case"rejected":await Ko(i.localStore,t,!0),$c(i,t,r);break;default:y()}}async function tl(e,t,n){const r=nl(e);if(r.$a){for(const e of t){if(r.Oa.has(e)&&r.sharedClientState.isActiveQueryTarget(e)){p("SyncEngine","Adding an already active target "+e);continue}const t=await Qo(r.localStore,e),n=await Go(r.localStore,t);await kc(r,Xc(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),$c(r,e)})).catch(re)}}function nl(e){const t=b(e);return t.remoteStore.remoteSyncer.applyRemoteEvent=Mc.bind(null,t),t.remoteStore.remoteSyncer.getRemoteKeysForTarget=Hc.bind(null,t),t.remoteStore.remoteSyncer.rejectListen=Oc.bind(null,t),t.Ma.R_=hc.bind(null,t.eventManager),t.Ma.Wa=dc.bind(null,t.eventManager),t}function rl(e){const t=b(e);return t.remoteStore.remoteSyncer.applySuccessfulWrite=Rc.bind(null,t),t.remoteStore.remoteSyncer.rejectFailedWrite=Fc.bind(null,t),t}class il{constructor(){this.kind="memory",this.synchronizeTabs=!1}async initialize(e){this.serializer=ya(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 $o(this.persistence,new Vo,e.initialUser,this.serializer)}ja(e){return new To(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()}}il.provider={build:()=>new il};class sl extends il{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 To((e=>Do.ei(e,t)),this.serializer)}}class ol extends il{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 rl(this.Za.syncEngine),await Ua(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 $o(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 ge(e.asyncQueue,n)}ja(e){const t=Oo(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(),va(),this.serializer,this.sharedClientState,!!this.forceOwnership)}za(e){return new aa}}class al extends ol{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:el.bind(null,t),oo:tl.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(nl(n),rl(n),!0===t&&!0!==n.$a){const e=n.sharedClientState.getAllActiveQueryTargets(),t=await Yc(n,e.toArray());n.$a=!0,await Xa(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((()=>($c(n,i),Ko(n.localStore,i,!0)))),Aa(n.remoteStore,i)})),await t,await Yc(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(j.comparator)}(n),n.$a=!1,await Xa(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=Oo(e.databaseInfo.databaseId,e.databaseInfo.persistenceKey);return new oa(t,e.asyncQueue,n,e.clientId,e.initialUser)}}class cl{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=>Pc(this.syncEngine,e,1),this.remoteStore.remoteSyncer.handleCredentialChange=Kc.bind(null,this.syncEngine),await Xa(this.remoteStore,this.syncEngine.isPrimaryClient))}createEventManager(e){return new ac}createDatastore(e){const t=ya(e.databaseInfo.databaseId),n=function(e){return new ga(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 Ta(e,t,n,r,i)}(this.localStore,this.datastore,e.asyncQueue,(e=>Pc(this.syncEngine,e,0)),la.p()?new la: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);p("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 ll(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()}}cl.provider={build:()=>new cl};class ul{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):g("Uncaught Error in snapshot listener:",e.toString()))}eu(){this.muted=!0}Xa(e,t){setTimeout((()=>{this.muted||e(t)}),0)}}class hl{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 vc(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 dl{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,$.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 Ht.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 Ht.newNoDocument(n,r)}(e,t):y()}(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 Or(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=j.fromPath(t);this.mutations.push(new Rr(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,$.emptyPath(),r)}(this.datastore,this.mutations),this.committed=!0}recordVersion(e){let t;if(e.isFoundDocument())t=e.version;else{if(!e.isNoDocument())throw y();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 fl{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 dl(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!ye(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 pl{constructor(e,t,n,r,i){this.authCredentials=e,this.appCheckCredentials=t,this.asyncQueue=n,this.databaseInfo=r,this.user=u.UNAUTHENTICATED,this.clientId=M.newId(),this.authCredentialListener=()=>Promise.resolve(),this.appCheckCredentialListener=()=>Promise.resolve(),this._uninitializedComponentsProvider=i,this.authCredentials.start(n,(async e=>{p("FirestoreClient","Received user=",e.uid),await this.authCredentialListener(e),this.user=e})),this.appCheckCredentials.start(n,(e=>(p("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 gl(e,t){e.asyncQueue.verifyOperationInProgress(),p("FirestoreClient","Initializing OfflineComponentProvider");const n=e.configuration;await t.initialize(n);let r=n.initialUser;e.setCredentialChangeListener((async e=>{r.isEqual(e)||(await Bo(t.localStore,e),r=e)})),t.persistence.setDatabaseDeletedListener((()=>e.terminate())),e._offlineComponents=t}async function ml(e,t){e.asyncQueue.verifyOperationInProgress();const n=await vl(e);p("FirestoreClient","Initializing OnlineComponentProvider"),await t.initialize(n,e.configuration),e.setCredentialChangeListener((e=>Ya(t.remoteStore,e))),e.setAppCheckTokenChangeListener(((e,n)=>Ya(t.remoteStore,n))),e._onlineComponents=t}async function vl(e){if(!e._offlineComponents)if(e._uninitializedComponentsProvider){p("FirestoreClient","Using user provided OfflineComponentProvider");try{await gl(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 gl(e,new il)}}else p("FirestoreClient","Using default OfflineComponentProvider"),await gl(e,new sl(void 0));return e._offlineComponents}async function yl(e){return e._onlineComponents||(e._uninitializedComponentsProvider?(p("FirestoreClient","Using user provided OnlineComponentProvider"),await ml(e,e._uninitializedComponentsProvider._online)):(p("FirestoreClient","Using default OnlineComponentProvider"),await ml(e,new cl))),e._onlineComponents}function wl(e){return vl(e).then((e=>e.persistence))}function bl(e){return vl(e).then((e=>e.localStore))}function _l(e){return yl(e).then((e=>e.remoteStore))}function Il(e){return yl(e).then((e=>e.syncEngine))}function El(e){return yl(e).then((e=>e.datastore))}async function Sl(e){const t=await yl(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 Tl(e,t,n={}){const r=new E;return e.asyncQueue.enqueueAndForget((async()=>function(e,t,n,r,i){const s=new ul({next:a=>{s.eu(),t.enqueueAndForget((()=>uc(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 lc(e,o)}(await Sl(e),e.asyncQueue,t,n,r))),r.promise}function xl(e,t,n={}){const r=new E;return e.asyncQueue.enqueueAndForget((async()=>function(e,t,n,r,i){const s=new ul({next:n=>{s.eu(),t.enqueueAndForget((()=>uc(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 lc(e,o)}(await Sl(e),e.asyncQueue,t,n,r))),r.promise}function Cl(e){const t={};return void 0!==e.timeoutSeconds&&(t.timeoutSeconds=e.timeoutSeconds),t}const Dl=new Map;function Al(e,t,n){if(!n)throw new I(_.INVALID_ARGUMENT,`Function ${e}() cannot be called with an empty ${t}.`)}function kl(e,t,n,r){if(!0===t&&!0===r)throw new I(_.INVALID_ARGUMENT,`${e} and ${n} cannot be used together.`)}function Nl(e){if(!j.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 Ll(e){if(j.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 Ml(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":y()}function Pl(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=Ml(e);throw new I(_.INVALID_ARGUMENT,`Expected type '${t.name}', but it was: ${n}`)}}return e}function Ol(e,t){if(t<=0)throw new I(_.INVALID_ARGUMENT,`Function ${e}() requires a positive number, but it was: ${t}.`)}class Rl{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}kl("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=Cl(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 Fl{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 Rl({}),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 Rl(e),void 0!==e.credentials&&(this._authCredentials=function(e){if(!e)return new T;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=Dl.get(e);t&&(p("ComponentProvider","Removing Datastore"),Dl.delete(e),t.terminate())}(this),Promise.resolve()}}function Vl(e,t,n,r={}){var i;const s=(e=Pl(e,Fl))._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=u.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 u(s)}e._authCredentials=new x(new S(t,n))}}class ql{constructor(e,t,n){this.converter=t,this._query=n,this.type="query",this.firestore=e}withConverter(e){return new ql(this.firestore,e,this._query)}}class $l{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 Bl(this.firestore,this.converter,this._key.path.popLast())}withConverter(e){return new $l(this.firestore,e,this._key)}}class Bl extends ql{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 $l(this.firestore,null,new j(e))}withConverter(e){return new Bl(this.firestore,e,this._path)}}function Ul(e,t,...n){if(e=o.getModularInstance(e),1===arguments.length&&(t=M.newId()),Al("doc","path",t),e instanceof Fl){const r=$.fromString(t,...n);return Nl(r),new $l(e,null,new j(r))}{if(!(e instanceof $l||e instanceof Bl))throw new I(_.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");const r=e._path.child($.fromString(t,...n));return Nl(r),new $l(e.firestore,e instanceof Bl?e.converter:null,new j(r))}}function jl(e,t){return e=o.getModularInstance(e),t=o.getModularInstance(t),e instanceof ql&&t instanceof ql&&e.firestore===t.firestore&&Vn(e._query,t._query)&&e.converter===t.converter}class zl{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=va();e&&p("AsyncQueue","Visibility state changed to "+e.visibilityState),this.r_.Jo()},this.gu=e;const t=va();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=va();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(!ue(e))throw e;p("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 g("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&&y()}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 Gl(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 Kl{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 Hl extends Fl{constructor(e,t,n,r){super(e,t,n,r),this.type="firestore",this._queue=new zl,this._persistenceKey=(null==r?void 0:r.name)||"[DEFAULT]"}async _terminate(){if(this._firestoreClient){const e=this._firestoreClient.terminate();this._queue=new zl(e),this._firestoreClient=void 0,await e}}}function Ql(e){if(e._terminated)throw new I(_.FAILED_PRECONDITION,"The client has already been terminated.");return e._firestoreClient||Wl(e),e._firestoreClient}function Wl(e){var t,n,r;const i=e._freezeSettings(),s=function(e,t,n,r){return new yt(e,t,n,r.host,r.ssl,r.experimentalForceLongPolling,r.experimentalAutoDetectLongPolling,Cl(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 pl(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 Jl(e,t,n){if((e=Pl(e,Hl))._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},Wl(e)}class Yl{constructor(e="count",t){this._internalFieldPath=t,this.type="AggregateField",this.aggregateType=e}}class Xl{constructor(e,t,n){this._userDataWriter=t,this._data=n,this.type="AggregateQuerySnapshot",this.query=e}data(){return this._userDataWriter.convertObjectMap(this._data)}}class Zl{constructor(e){this._byteString=e}static fromBase64String(e){try{return new Zl(ut.fromBase64String(e))}catch(e){throw new I(_.INVALID_ARGUMENT,"Failed to construct data from Base64 string: "+e)}}static fromUint8Array(e){return new Zl(ut.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 eu{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 U(e)}isEqual(e){return this._internalPath.isEqual(e._internalPath)}}class tu{constructor(e){this._methodName=e}}class nu{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 P(this._lat,e._lat)||P(this._long,e._long)}}class ru{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 iu=/^__.*__$/;class su{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 ou{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 au(e){switch(e){case 0:case 2:case 1:return!0;case 3:case 4:return!1;default:throw y()}}class cu{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 cu(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 Du(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(au(this.Mu)&&iu.test(e))throw this.qu('Document fields cannot begin and end with "__"')}}class lu{constructor(e,t,n){this.databaseId=e,this.ignoreUndefinedProperties=t,this.serializer=n||ya(e)}$u(e,t,n,r=!1){return new cu({Mu:e,methodName:t,Ku:n,path:U.emptyPath(),Nu:!1,Qu:r},this.databaseId,this.serializer,this.ignoreUndefinedProperties)}}function uu(e){const t=e._freezeSettings(),n=ya(e._databaseId);return new lu(e._databaseId,!!t.ignoreUndefinedProperties,n)}function hu(e,t,n,r,i,s={}){const o=e.$u(s.merge||s.mergeFields?2:0,t,n,i);Su("Data must be an object, but it was:",o,r);const a=Iu(r,o);let c,l;if(s.merge)c=new ct(o.fieldMask),l=o.fieldTransforms;else if(s.mergeFields){const e=[];for(const r of s.mergeFields){const i=Tu(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.`);Au(e,i)||e.push(i)}c=new ct(e),l=o.fieldTransforms.filter((e=>c.covers(e.field)))}else c=null,l=o.fieldTransforms;return new su(new Gt(a),c,l)}class du extends tu{_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 du}}function fu(e,t,n){return new cu({Mu:3,Ku:t.settings.Ku,methodName:e._methodName,Nu:n},t.databaseId,t.serializer,t.ignoreUndefinedProperties)}class pu extends tu{_toFieldTransform(e){return new br(e.path,new dr)}isEqual(e){return e instanceof pu}}class gu extends tu{constructor(e,t){super(e),this.Uu=t}_toFieldTransform(e){const t=fu(this,e,!0),n=this.Uu.map((e=>_u(e,t))),r=new fr(n);return new br(e.path,r)}isEqual(e){return e instanceof gu&&o.deepEqual(this.Uu,e.Uu)}}class mu extends tu{constructor(e,t){super(e),this.Uu=t}_toFieldTransform(e){const t=fu(this,e,!0),n=this.Uu.map((e=>_u(e,t))),r=new gr(n);return new br(e.path,r)}isEqual(e){return e instanceof mu&&o.deepEqual(this.Uu,e.Uu)}}class vu extends tu{constructor(e,t){super(e),this.Wu=t}_toFieldTransform(e){const t=new vr(e.serializer,ar(e.serializer,this.Wu));return new br(e.path,t)}isEqual(e){return e instanceof vu&&this.Wu===e.Wu}}function yu(e,t,n,r){const i=e.$u(1,t,n);Su("Data must be an object, but it was:",i,r);const s=[],a=Gt.empty();Ze(r,((e,r)=>{const c=Cu(t,e,n);r=o.getModularInstance(r);const l=i.Bu(c);if(r instanceof du)s.push(c);else{const e=_u(r,l);null!=e&&(s.push(c),a.set(c,e))}}));const c=new ct(s);return new ou(a,c,i.fieldTransforms)}function wu(e,t,n,r,i,s){const a=e.$u(1,t,n),c=[Tu(t,r,n)],l=[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(Tu(t,s[e])),l.push(s[e+1]);const u=[],h=Gt.empty();for(let e=c.length-1;e>=0;--e)if(!Au(u,c[e])){const t=c[e];let n=l[e];n=o.getModularInstance(n);const r=a.Bu(t);if(n instanceof du)u.push(t);else{const e=_u(n,r);null!=e&&(u.push(t),h.set(t,e))}}const d=new ct(u);return new ou(h,d,a.fieldTransforms)}function bu(e,t,n,r=!1){return _u(n,e.$u(r?4:3,t))}function _u(e,t){if(Eu(e=o.getModularInstance(e)))return Su("Unsupported field value:",t,e),Iu(e,t);if(e instanceof tu)return function(e,t){if(!au(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=_u(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 nu)return{geoPointValue:{latitude:e.latitude,longitude:e.longitude}};if(e instanceof Zl)return{bytesValue:pi(t.serializer,e._byteString)};if(e instanceof $l){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:vi(e.firestore._databaseId||t.databaseId,e._key.path)}}if(e instanceof ru)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: ${Ml(e)}`)}(e,t)}function Iu(e,t){const n={};return tt(e)?t.path&&t.path.length>0&&t.fieldMask.push(t.path):Ze(e,((e,r)=>{const i=_u(r,t.Ou(e));null!=i&&(n[e]=i)})),{mapValue:{fields:n}}}function Eu(e){return!("object"!=typeof e||null===e||e instanceof Array||e instanceof Date||e instanceof F||e instanceof nu||e instanceof Zl||e instanceof $l||e instanceof tu||e instanceof ru)}function Su(e,t,n){if(!Eu(n)||!function(e){return"object"==typeof e&&null!==e&&(Object.getPrototypeOf(e)===Object.prototype||null===Object.getPrototypeOf(e))}(n)){const r=Ml(n);throw"an object"===r?t.qu(e+" a custom object"):t.qu(e+" "+r)}}function Tu(e,t,n){if((t=o.getModularInstance(t))instanceof eu)return t._internalPath;if("string"==typeof t)return Cu(e,t);throw Du("Field path arguments must be of type string or ",e,!1,void 0,n)}const xu=new RegExp("[~\\*/\\[\\]]");function Cu(e,t,n){if(t.search(xu)>=0)throw Du(`Invalid field path (${t}). Paths must not contain '~', '*', '/', '[', or ']'`,e,!1,void 0,n);try{return new eu(...t.split("."))._internalPath}catch(r){throw Du(`Invalid field path (${t}). Paths must not be empty, begin with '.', end with '.', or contain '..'`,e,!1,void 0,n)}}function Du(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 Au(e,t){return e.some((e=>e.isEqual(t)))}class ku{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 $l(this._firestore,this._converter,this._key)}exists(){return null!==this._document}data(){if(this._document){if(this._converter){const e=new Nu(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(Lu("DocumentSnapshot.get",e));if(null!==t)return this._userDataWriter.convertValue(t)}}}class Nu extends ku{data(){return super.data()}}function Lu(e,t){return"string"==typeof t?Cu(e,t):t instanceof eu?t._internalPath:t._delegate._internalPath}function Mu(e){if("L"===e.limitType&&0===e.explicitOrderBy.length)throw new I(_.UNIMPLEMENTED,"limitToLast() queries require specifying at least one orderBy() clause")}class Pu{}class Ou extends Pu{}class Ru extends Ou{constructor(e,t,n){super(),this._field=e,this._op=t,this._value=n,this.type="where"}static _create(e,t,n){return new Ru(e,t,n)}_apply(e){const t=this._parse(e);return Gu(e._query,t),new ql(e.firestore,e.converter,Rn(e._query,t))}_parse(e){const t=uu(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){zu(o,s);const t=[];for(const n of o)t.push(ju(r,e,n));a={arrayValue:{values:t}}}else a=ju(r,e,o)}else"in"!==s&&"not-in"!==s&&"array-contains-any"!==s||zu(o,s),a=bu(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 Fu extends Pu{constructor(e,t){super(),this.type=e,this._queryConstraints=t}static _create(e,t){return new Fu(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)Gu(n,e),n=Rn(n,e)}(e._query,t),new ql(e.firestore,e.converter,Rn(e._query,t)))}_getQueryConstraints(){return this._queryConstraints}_getOperator(){return"and"===this.type?"and":"or"}}class Vu extends Ou{constructor(e,t){super(),this._field=e,this._direction=t,this.type="orderBy"}static _create(e,t){return new Vu(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 Yt(t,n)}(e._query,this._field,this._direction);return new ql(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 qu extends Ou{constructor(e,t,n){super(),this.type=e,this._limit=t,this._limitType=n}static _create(e,t,n){return new qu(e,t,n)}_apply(e){return new ql(e.firestore,e.converter,Fn(e._query,this._limit,this._limitType))}}class $u extends Ou{constructor(e,t,n){super(),this.type=e,this._docOrFields=t,this._inclusive=n}static _create(e,t,n){return new $u(e,t,n)}_apply(e){const t=Uu(e,this.type,this._docOrFields,this._inclusive);return new ql(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 Bu extends Ou{constructor(e,t,n){super(),this.type=e,this._docOrFields=t,this._inclusive=n}static _create(e,t,n){return new Bu(e,t,n)}_apply(e){const t=Uu(e,this.type,this._docOrFields,this._inclusive);return new ql(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 Uu(e,t,n,r){if(n[0]=o.getModularInstance(n[0]),n[0]instanceof ku)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(gt(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 Qt(s,i)}(e._query,e.firestore._databaseId,t,n[0]._document,r);{const i=uu(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($.fromString(c));if(!j.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 j(n);a.push(Nt(t,i))}else{const e=bu(n,r,c);a.push(e)}}return new Qt(a,s)}(e._query,e.firestore._databaseId,i,t,n,r)}}function ju(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($.fromString(n));if(!j.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 j(r))}if(n instanceof $l)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: ${Ml(n)}.`)}function zu(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 Gu(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 Ku(e,t){if(!(t instanceof Ru||t instanceof Fu))throw new I(_.INVALID_ARGUMENT,`Function ${e}() requires AppliableConstraints created with a call to 'where(...)', 'or(...)', or 'and(...)'.`)}class Hu{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(pt(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 y()}}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 ru(i)}convertGeoPoint(e){return new nu(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(vt(e));default:return null}}convertTimestamp(e){const t=dt(e);return new F(t.seconds,t.nanos)}convertDocumentKey(e,t){const n=$.fromString(e);w(Ui(n));const r=new wt(n.get(1),n.get(3)),i=new j(n.popFirst(5));return r.isEqual(t)||g(`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 Qu(e,t,n){let r;return r=e?n&&(n.merge||n.mergeFields)?e.toFirestore(t,n):e.toFirestore(t):t,r}class Wu extends Hu{constructor(e){super(),this.firestore=e}convertBytes(e){return new Zl(e)}convertReference(e){const t=this.convertDocumentKey(e,this.firestore._databaseId);return new $l(this.firestore,null,t)}}function Ju(){return new Yl("count")}class Yu{constructor(e,t){this.hasPendingWrites=e,this.fromCache=t}isEqual(e){return this.hasPendingWrites===e.hasPendingWrites&&this.fromCache===e.fromCache}}class Xu extends ku{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 Zu(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(Lu("DocumentSnapshot.get",e));if(null!==n)return this._userDataWriter.convertValue(n,t.serverTimestamps)}}}class Zu extends Xu{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 Yu(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 Zu(this._firestore,this._userDataWriter,n.key,n,new Yu(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 Zu(e._firestore,e._userDataWriter,n.doc.key,n.doc,new Yu(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 Zu(e._firestore,e._userDataWriter,t.doc.key,t.doc,new Yu(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 y()}}class nh extends Hu{constructor(e){super(),this.firestore=e}convertBytes(e){return new Zl(e)}convertReference(e){const t=this.convertDocumentKey(e,this.firestore._databaseId);return new $l(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=rl(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=Hn(),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(P)),r=r.insert(t,n),e.qa[e.currentUser.toKey()]=r}(r,e.batchId,n),await Gc(r,e.changes),await Ua(r.remoteStore)}catch(e){const t=nc(e,"Failed to persist write");n.reject(t)}}(await Il(e),t,n))),n.promise}(Ql(e),t)}function ih(e,t,n){const r=n.docs.get(t._key),i=new nh(e);return new Xu(e,i,t._key,r,new Yu(n.hasPendingWrites,n.fromCache),t.converter)}function sh(e,t){const n=Pl(e.firestore,Hl),r=Ql(n),i=et(t,((e,t)=>new $r(t,e.aggregateType,e._internalFieldPath)));return function(e,t,n){const r=new E;return e.asyncQueue.enqueueAndForget((async()=>{try{const i=await El(e);r.resolve(async function(e,t,n){var r;const i=b(e),{request:s,lt:o,parent:a}=Li(i.serializer,Pn(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 l=null===(r=c[0].result)||void 0===r?void 0:r.aggregateFields;return Object.keys(l).reduce(((e,t)=>(e[o[t]]=l[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 Xl(t,r,n)}(n,e,t)))}class oh{constructor(e){this.kind="memory",this._onlineComponentProvider=cl.provider,(null==e?void 0:e.garbageCollector)?this._offlineComponentProvider=e.garbageCollector._offlineComponentProvider:this._offlineComponentProvider={build:()=>new sl(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=il.provider}toJSON(){return{kind:this.kind}}}class lh{constructor(e){this.kind="memoryLru",this._offlineComponentProvider={build:()=>new sl(e)}}toJSON(){return{kind:this.kind}}}class uh{constructor(e){this.forceOwnership=e,this.kind="persistentSingleTab"}toJSON(){return{kind:this.kind}}_initialize(e){this._onlineComponentProvider=cl.provider,this._offlineComponentProvider={build:t=>new ol(t,null==e?void 0:e.cacheSizeBytes,this.forceOwnership)}}}class hh{constructor(){this.kind="PersistentMultipleTab"}toJSON(){return{kind:this.kind}}_initialize(e){this._onlineComponentProvider=cl.provider,this._offlineComponentProvider={build:t=>new al(t,null==e?void 0:e.cacheSizeBytes)}}}function dh(e){return new uh(null==e?void 0:e.forceOwnership)}const fh={maxAttempts:5};class ph{constructor(e,t){this._firestore=e,this._commitHandler=t,this._mutations=[],this._committed=!1,this._dataReader=uu(e)}set(e,t,n){this._verifyNotCommitted();const r=gh(e,this._firestore),i=Qu(r.converter,t,n),s=hu(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=gh(e,this._firestore);let s;return s="string"==typeof(t=o.getModularInstance(t))||t instanceof eu?wu(this._dataReader,"WriteBatch.update",i._key,t,n,r):yu(this._dataReader,"WriteBatch.update",i._key,t),this._mutations.push(s.toMutation(i._key,Ir.exists(!0))),this}delete(e){this._verifyNotCommitted();const t=gh(e,this._firestore);return this._mutations=this._mutations.concat(new Or(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 gh(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=uu(e)}get(e){const t=gh(e,this._firestore),n=new Wu(this._firestore);return this._transaction.lookup([t._key]).then((e=>{if(!e||1!==e.length)return y();const r=e[0];if(r.isFoundDocument())return new ku(this._firestore,n,r.key,r,t.converter);if(r.isNoDocument())return new ku(this._firestore,n,t._key,null,t.converter);throw y()}))}set(e,t,n){const r=gh(e,this._firestore),i=Qu(r.converter,t,n),s=hu(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=gh(e,this._firestore);let s;return s="string"==typeof(t=o.getModularInstance(t))||t instanceof eu?wu(this._dataReader,"Transaction.update",i._key,t,n,r):yu(this._dataReader,"Transaction.update",i._key,t),this._transaction.update(i._key,s),this}delete(e){const t=gh(e,this._firestore);return this._transaction.delete(t._key),this}}{constructor(e,t){super(e,t),this._firestore=e}get(e){const t=gh(e,this._firestore),n=new nh(this._firestore);return super.get(e).then((e=>new Xu(this._firestore,n,t._key,e._document,new Yu(!1,!1),t.converter)))}}function vh(e,t){if("string"!=typeof e[t])throw new I(_.INVALID_ARGUMENT,"Missing string value for: "+t);return e[t]}class yh{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 bl(e),t)))})(Ql(e._firestore),t).then((e=>p(`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 Hl(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(l,"4.7.5",e),r.registerVersion(l,"4.7.5","cjs2017")}(),t.AbstractUserDataWriter=Hu,t.AggregateField=Yl,t.AggregateQuerySnapshot=Xl,t.Bytes=Zl,t.CACHE_SIZE_UNLIMITED=-1,t.CollectionReference=Bl,t.DocumentReference=$l,t.DocumentSnapshot=Xu,t.FieldPath=eu,t.FieldValue=tu,t.Firestore=Hl,t.FirestoreError=I,t.GeoPoint=nu,t.LoadBundleTask=Kl,t.PersistentCacheIndexManager=yh,t.Query=ql,t.QueryCompositeFilterConstraint=Fu,t.QueryConstraint=Ou,t.QueryDocumentSnapshot=Zu,t.QueryEndAtConstraint=Bu,t.QueryFieldFilterConstraint=Ru,t.QueryLimitConstraint=qu,t.QueryOrderByConstraint=Vu,t.QuerySnapshot=eh,t.QueryStartAtConstraint=$u,t.SnapshotMetadata=Yu,t.Timestamp=F,t.Transaction=mh,t.VectorValue=ru,t.WriteBatch=ph,t._AutoId=M,t._ByteString=ut,t._DatabaseId=wt,t._DocumentKey=j,t._EmptyAppCheckTokenProvider=class{getToken(){return Promise.resolve(new k(""))}invalidateToken(){}start(e,t){}shutdown(){}},t._EmptyAuthCredentialsProvider=T,t._FieldPath=U,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=Pl,t._debugAssert=function(e,t){e||y()},t._internalAggregationQueryToProtoRunAggregationQueryRequest=function(e,t){var n;const r=et(t,((e,t)=>new $r(t,e.aggregateType,e._internalFieldPath))),i=null===(n=Ql(Pl(e.firestore,Hl))._onlineComponents)||void 0===n?void 0:n.datastore.serializer;return void 0===i?null:Li(i,Pn(e._query),r,!0).request},t._internalQueryToProtoQueryTarget=function(e){var t;const n=null===(t=Ql(Pl(e.firestore,Hl))._onlineComponents)||void 0===t?void 0:t.datastore.serializer;return void 0===n?null:Ni(n,Mn(e._query)).ct},t._isBase64Available=function(){return"undefined"!=typeof atob},t._logWarn=m,t._validateIsNotUsedTogether=kl,t.addDoc=function(e,t){const n=Pl(e.firestore,Hl),r=Ul(e),i=Qu(e.converter,t);return rh(n,[hu(uu(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 Yl&&t instanceof Yl&&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 jl(e.query,t.query)&&o.deepEqual(e.data(),t.data())},t.and=function(...e){return e.forEach((e=>Ku("and",e))),Fu._create("and",e)},t.arrayRemove=function(...e){return new mu("arrayRemove",e)},t.arrayUnion=function(...e){return new gu("arrayUnion",e)},t.average=function(e){return new Yl("avg",Tu("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)}(Oo(e._databaseId,e._persistenceKey)),t.resolve()}catch(e){t.reject(e)}})),t.promise},t.collection=function(e,t,...n){if(e=o.getModularInstance(e),Al("collection","path",t),e instanceof Fl){const r=$.fromString(t,...n);return Ll(r),new Bl(e,null,r)}{if(!(e instanceof $l||e instanceof Bl))throw new I(_.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");const r=e._path.child($.fromString(t,...n));return Ll(r),new Bl(e.firestore,null,r)}},t.collectionGroup=function(e,t){if(e=Pl(e,Fl),Al("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 ql(e,null,function(e){return new Cn($.emptyPath(),e)}(t))},t.connectFirestoreEmulator=Vl,t.count=Ju,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 bl(e))))})(Ql(e._firestore)).then((e=>p("deleting all persistent cache indexes succeeded"))).catch((e=>m("deleting all persistent cache indexes failed",e)))},t.deleteDoc=function(e){return rh(Pl(e.firestore,Hl),[new Or(e._key,Ir.none())])},t.deleteField=function(){return new du("deleteField")},t.disableNetwork=function(e){return function(e){return e.asyncQueue.enqueue((async()=>{const t=await wl(e),n=await _l(e);return t.setNetworkEnabled(!1),async function(e){const t=b(e);t.k_.add(0),await Ca(t),t.K_.set("Offline")}(n)}))}(Ql(e=Pl(e,Hl)))},t.disablePersistentCacheIndexAutoCreation=function(e){wh(e,!1)},t.doc=Ul,t.documentId=function(){return new eu("__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 Jl(e,cl.provider,{build:e=>new ol(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();Jl(e,cl.provider,{build:e=>new al(e,t.cacheSizeBytes)})},t.enableNetwork=function(e){return function(e){return e.asyncQueue.enqueue((async()=>{const t=await wl(e),n=await _l(e);return t.setNetworkEnabled(!0),function(e){const t=b(e);return t.k_.delete(0),xa(t)}(n)}))}(Ql(e=Pl(e,Hl)))},t.enablePersistentCacheIndexAutoCreation=function(e){wh(e,!0)},t.endAt=function(...e){return Bu._create("endAt",e,!0)},t.endBefore=function(...e){return Bu._create("endBefore",e,!1)},t.ensureFirestoreConfigured=Ql,t.executeWrite=rh,t.getAggregateFromServer=sh,t.getCountFromServer=function(e){return sh(e,{count:Ju()})},t.getDoc=function(e){e=Pl(e,$l);const t=Pl(e.firestore,Hl);return Tl(Ql(t),e._key).then((n=>ih(t,e,n)))},t.getDocFromCache=function(e){e=Pl(e,$l);const t=Pl(e.firestore,Hl),n=Ql(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 bl(e),t,n))),n.promise}(n,e._key).then((n=>new Xu(t,r,e._key,n,new Yu(null!==n&&n.hasLocalMutations,!0),e.converter)))},t.getDocFromServer=function(e){e=Pl(e,$l);const t=Pl(e.firestore,Hl);return Tl(Ql(t),e._key,{source:"server"}).then((n=>ih(t,e,n)))},t.getDocs=function(e){e=Pl(e,ql);const t=Pl(e.firestore,Hl),n=Ql(t),r=new nh(t);return Mu(e._query),xl(n,e._query).then((n=>new eh(t,r,e,n)))},t.getDocsFromCache=function(e){e=Pl(e,ql);const t=Pl(e.firestore,Hl),n=Ql(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 Ho(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 bl(e),t,n))),n.promise}(n,e._query).then((n=>new eh(t,r,e,n)))},t.getDocsFromServer=function(e){e=Pl(e,ql);const t=Pl(e.firestore,Hl),n=Ql(t),r=new nh(t);return xl(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&&Vl(s,...e)}return s},t.getPersistentCacheIndexManager=function(e){var t;e=Pl(e,Hl);const n=bh.get(e);if(n)return n;if("persistent"!==(null===(t=Ql(e)._uninitializedComponentsProvider)||void 0===t?void 0:t._offline.kind))return null;const r=new yh(e);return bh.set(e,r),r},t.increment=function(e){return new vu("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 Ol("limit",e),qu._create("limit",e,"F")},t.limitToLast=function(e){return Ol("limitToLast",e),qu._create("limitToLast",e,"L")},t.loadBundle=function(e,t){const n=Ql(e=Pl(e,Hl)),r=new Kl;return function(e,t,n,r){const i=function(e,t){let n;return n="string"==typeof e?Hr().encode(e):e,function(e,t){return new hl(e,t)}(function(e,t){if(e instanceof Uint8Array)return ll(e,t);if(e instanceof ArrayBuffer)return ll(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,ya(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 Il(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 lh(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 bl(e),t)))}(Ql(e=Pl(e,Hl)),t).then((t=>t?new ql(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]||Gl(t[a])||(s=t[a],a++);const c={includeMetadataChanges:s.includeMetadataChanges,source:s.source};if(Gl(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 l,u,h;if(e instanceof $l)u=Pl(e.firestore,Hl),h=An(e._key.path),l={next:n=>{t[a]&&t[a](ih(u,e,n))},error:t[a+1],complete:t[a+2]};else{const n=Pl(e,ql);u=Pl(n.firestore,Hl),h=n._query;const r=new nh(u);l={next:e=>{t[a]&&t[a](new eh(u,r,n,e))},error:t[a+1],complete:t[a+2]},Mu(e._query)}return function(e,t,n,r){const i=new ul(r),s=new mc(t,i,n);return e.asyncQueue.enqueueAndForget((async()=>lc(await Sl(e),s))),()=>{i.eu(),e.asyncQueue.enqueueAndForget((async()=>uc(await Sl(e),s)))}}(Ql(u),h,c,l)},t.onSnapshotsInSync=function(e,t){return function(e,t){const n=new ul(t);return e.asyncQueue.enqueueAndForget((async()=>function(e,t){b(e).X_.add(t),t.next()}(await Sl(e),n))),()=>{n.eu(),e.asyncQueue.enqueueAndForget((async()=>function(e,t){b(e).X_.delete(t)}(await Sl(e),n)))}}(Ql(e=Pl(e,Hl)),Gl(t)?t:{next:t})},t.or=function(...e){return e.forEach((e=>Ku("or",e))),Fu._create("or",e)},t.orderBy=function(e,t="asc"){const n=t,r=Lu("orderBy",e);return Vu._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 Pu&&r.push(t),r=r.concat(n),function(e){const t=e.filter((e=>e instanceof Fu)).length,n=e.filter((e=>e instanceof Ru)).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=jl,t.refEqual=function(e,t){return e=o.getModularInstance(e),t=o.getModularInstance(t),(e instanceof $l||e instanceof Bl)&&(t instanceof $l||t instanceof Bl)&&e.firestore===t.firestore&&e.path===t.path&&e.converter===t.converter},t.runTransaction=function(e,t,n){e=Pl(e,Hl);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 El(e);new fl(e.asyncQueue,i,n,t,r).cu()})),r.promise}(Ql(e),(n=>t(new mh(e,n))),r)},t.serverTimestamp=function(){return new pu("serverTimestamp")},t.setDoc=function(e,t,n){e=Pl(e,$l);const r=Pl(e.firestore,Hl),i=Qu(e.converter,t,n);return rh(r,[hu(uu(r),"setDoc",e._key,i,null!==e.converter,n).toMutation(e._key,Ir.none())])},t.setIndexConfiguration=function(e,t){const n=Ql(e=Pl(e,Hl));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=vh(e,"collectionGroup"),r=[];if(Array.isArray(e.fields))for(const t of e.fields){const e=Cu("setIndexConfiguration",vh(t,"fieldPath"));"CONTAINS"===t.arrayConfig?r.push(new Q(e,2)):"ASCENDING"===t.order?r.push(new Q(e,0)):"DESCENDING"===t.order&&r.push(new Q(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,H,(t=>{i.push(r.addFieldIndex(e,t))}),(t=>{i.push(r.deleteFieldIndex(e,t))})))).next((()=>ie.waitFor(i)))))}(await bl(e),t)))}(n,r)},t.setLogLevel=function(e){d.setLogLevel(e)},t.snapshotEqual=function(e,t){return e instanceof Xu&&t instanceof Xu?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&&jl(e.query,t.query)&&e.metadata.isEqual(t.metadata)&&e._snapshot.isEqual(t._snapshot)},t.startAfter=function(...e){return $u._create("startAfter",e,!1)},t.startAt=function(...e){return $u._create("startAt",e,!0)},t.sum=function(e){return new Yl("sum",Tu("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=Pl(e,$l);const i=Pl(e.firestore,Hl),s=uu(i);let a;return a="string"==typeof(t=o.getModularInstance(t))||t instanceof eu?wu(s,"updateDoc",e._key,t,n,r):yu(s,"updateDoc",e._key,t),rh(i,[a.toMutation(e._key,Ir.exists(!0))])},t.vector=function(e){return new ru(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);Pa(n.remoteStore)||p("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 Il(e),t))),t.promise}(Ql(e=Pl(e,Hl)))},t.where=function(e,t,n){const r=t,i=Lu("where",e);return Ru._create(i,r,n)},t.writeBatch=function(e){return Ql(e=Pl(e,Hl)),new ph(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 l="functions",u={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(`${l}/${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(!u[t])return new h("internal","internal");r=u[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 p="us-central1",g=/^data: (.*?)(?:\n|$)/;class m{constructor(e,t,n,r,i=p,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=p}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 v(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 y(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 y(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),l=await Promise.race([v(t,i,s,e.fetchImpl),o.promise,e.cancelAllRequests]);if(o.cancel(),!l)throw new h("cancelled","Firebase Functions instance was deleted.");const u=d(l.status,l.json);if(u)throw u;if(!l.json)throw new h("internal","Response is not valid JSON object.");let f=l.json.data;if(void 0===f&&(f=l.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 y(e,r);let l,u,f;o["Content-Type"]="application/json",o.Accept="text/event-stream";try{l=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 p=new Promise(((e,t)=>{u=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(g);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:l}=await e.read();if(l)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 u=o.split("\n");o=u.pop()||"";for(const e of u)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()})}(l.body.getReader(),u,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:p}}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(l,((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=p){const n=r._getProvider(i.getModularInstance(e),l).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,l=i>>2,u=(3&i)<<4|o>>4;let h=(15&o)<<2|c>>6,d=63&c;a||(d=64,s||(h=64)),r.push(n[l],n[u],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 l=i<<2|s>>4;if(r.push(l),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 l=function(e){const t=o(e);return a.encodeByteArray(t,!0)},u=function(e){return l(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 p=()=>{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}`)}},g=e=>{var t,n;return null===(n=null===(t=p())||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 v(){return"undefined"!=typeof navigator&&"string"==typeof navigator.userAgent?navigator.userAgent:""}function y(){var e;const t=null===(e=p())||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 S=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 T(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],l=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+l+i+n[e]&4294967295;l=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]+l&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=l,t.base64urlEncodeWithoutPadding=u,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[u(JSON.stringify({alg:"none",type:"JWT"})),u(JSON.stringify(s)),""].join(".")},t.createSubscribe=function(e,t){const n=new x(e,t);return n.subscribe.bind(n)},t.decode=S,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(T(r)&&T(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=p())||void 0===e?void 0:e.config},t.getDefaultEmulatorHost=g,t.getDefaultEmulatorHostnameAndPort=e=>{const t=g(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=p,t.getExperimentalSetting=e=>{var t;return null===(t=p())||void 0===t?void 0:t[`_${e}`]},t.getGlobal=f,t.getModularInstance=function(e){return e&&e._delegate?e._delegate:e},t.getUA=v,t.isAdmin=function(e){const t=S(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 v().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=v();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(v())},t.isNode=y,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!y()&&!!navigator.userAgent&&navigator.userAgent.includes("Safari")&&!navigator.userAgent.includes("Chrome")},t.isUWP=function(){return v().indexOf("MSAppHost/")>=0},t.isValidFormat=function(e){const t=S(e).claims;return!!t&&"object"==typeof t&&t.hasOwnProperty("iat")},t.isValidTimestamp=function(e){const t=S(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=S(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),l=o(1),u=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(l)}function p(e,t){return e.add(f(t))}function g(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 v(e,t){if(h(t))throw Error("division by zero");if(h(e))return new m(c,c);if(d(e))return t=v(f(e),t),new m(f(t.g),f(t.h));if(d(t))return t=v(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=l,r=t;0>=r.l(e);)n=y(n),r=y(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=p(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=l),i=i.add(s),e=p(e,o)}return new m(i,e)}function y(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=v(n,t).g,s=((0<(n=p(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=p(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(u)&&0>e.l(u))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,l=65535&this.i(r),p=e.i(s)>>>16,m=65535&e.i(s);n[2*r+2*s]+=l*m,g(n,2*r+2*s),n[2*r+2*s+1]+=o*m,g(n,2*r+2*s+1),n[2*r+2*s+1]+=l*p,g(n,2*r+2*s+1),n[2*r+2*s+2]+=o*p,g(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 v(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),l=parseInt(t.substring(s,s+o),n);8>o?(o=a(Math.pow(n,o)),i=i.j(o).add(a(l))):i=(i=i.j(r)).add(a(l))}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 l(e,t,n){return e.call.apply(e.bind,arguments)}function u(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")?l:u).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 p(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 g(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 v(){var e=o.navigator;return e&&(e=e.userAgent)?e:""}function y(e){return y[" "](e),e}y[" "]=function(){};var w=!(-1==v().indexOf("Gecko")||-1!=v().toLowerCase().indexOf("webkit")&&-1==v().indexOf("Edge")||-1!=v().indexOf("Trident")||-1!=v().indexOf("MSIE")||-1!=v().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 S(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 T(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(M)}};var M=()=>{for(var e;e=x();){try{e.h.call(e.g)}catch(e){T(e)}var t=C;t.j(e),100>t.h&&(t.h++,e.next=t.g,t.g=e)}k=!1};function P(){this.s=this.s,this.C=this.C}function O(e,t){this.type=e,this.g=this.target=t,this.defaultPrevented=!1}P.prototype.s=!1,P.prototype.ma=function(){this.s||(this.s=!0,this.N())},P.prototype.N=function(){if(this.C)for(;this.C.length;)this.C.shift()()},O.prototype.h=function(){this.defaultPrevented=!0};var R=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(O.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{y(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,O);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),$=0;function B(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=++$,this.da=this.fa=!1}function U(e){e.da=!0,e.listener=null,e.proxy=null,e.src=null,e.ha=null}function j(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&&(U(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}j.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 B(t,this.src,s,!!r,i)).fa=n,e.push(t)),t};var K="closure_lm_"+(1e6*Math.random()|0),H={};function Q(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++)Q(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 j(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)R||(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 Y(e,t,n,r,i){if(Array.isArray(t))for(var s=0;s<t.length;s++)Y(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))&&(U(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)&&X(n))}function X(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)):U(e)}}}function Z(e){return e in H?H[e]:H[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&&X(e),e=n.call(r,t)}return e}function te(e){return(e=e[K])instanceof j?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(){P.call(this),this.i=new j(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 O(t,e);else if(t instanceof O)t.target=t.target||e;else{var i=t;E(t=new O(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,P),ie.prototype[q]=!0,ie.prototype.removeEventListener=function(e,t,n,r){Y(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++)U(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 le extends P{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 ue(e){P.call(this),this.h=e,this.g={}}f(ue,P);var he=[];function de(e){b(e.g,(function(e,t){this.g.hasOwnProperty(t)&&X(e)}),e),e.g={}}ue.prototype.N=function(){ue.aa.N.call(this),de(this)},ue.prototype.handleEvent=function(){throw Error("EventHandler.handleEvent not implemented")};var fe=o.JSON.stringify,pe=o.JSON.parse,ge=class{stringify(e){return o.JSON.stringify(e,void 0)}parse(e){return o.JSON.parse(e,void 0)}};function me(){}function ve(e){return e.h||(e.h=e.i())}function ye(){}me.prototype.h=null;var we={OPEN:"a",kb:"b",Ja:"c",wb:"d"};function be(){O.call(this,"d")}function _e(){O.call(this,"c")}f(be,O),f(_e,O);var Ie={},Ee=null;function Se(){return Ee=Ee||new ie}function Te(e){O.call(this,Ie.La,e)}function xe(e){const t=Se();se(t,new Te(t,e))}function Ce(e,t){O.call(this,Ie.STAT_EVENT,e),this.stat=t}function De(e){const t=Se();se(t,new Ce(t,e))}function Ae(e,t){O.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(Te,O),Ie.STAT_EVENT="statevent",f(Ce,O),Ie.Ma="timingevent",f(Ae,O),Ne.prototype.xa=function(){this.g=!1},Ne.prototype.info=function(){};var Me,Pe={NO_ERROR:0,gb:1,tb:2,sb:3,nb:4,rb:5,ub:6,Ia:7,TIMEOUT:8,xb:9},Oe={lb:"complete",Hb:"success",Ja:"error",Ia:"abort",zb:"ready",Ab:"readystatechange",TIMEOUT:"timeout",vb:"incrementaldata",yb:"progress",ob:"downloadprogress",Pb:"uploadprogress"};function Re(){}function Fe(e,t,n,r){this.j=e,this.i=t,this.l=n,this.R=r||1,this.U=new ue(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(Re,me),Re.prototype.g=function(){return new XMLHttpRequest},Re.prototype.i=function(){return{}},Me=new Re;var qe={},$e={};function Be(e,t,n){e.L=1,e.v=ft(ct(t)),e.m=n,e.P=!0,Ue(e,null)}function Ue(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=gn(e.j,n?t:null,!e.m),0<e.O&&(e.M=new le(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=Q(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 l=a[c].split("=");if(1<l.length){var u=l[0];l=l[1];var h=u.split("_");o=2<=h.length&&"type"==h[1]?o+(u+"=")+l+"&":o+(u+"=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 je(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?$e:(n=Number(t.substring(n,r)),isNaN(n)?qe:(r+=1)+n>t.length?$e:(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 He(e){e.B&&(o.clearTimeout(e.B),e.B=null)}function Qe(e){0==e.j.G||e.J||un(e.j,e)}function We(e){He(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;ln(n),Xt(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)&&ln(n),!m(t))for(i=n.Da.g.parse(t),t=0;t<i.length;t++){let l=i[t];if(n.T=l[0],l=l[1],2==n.G)if("c"==l[0]){n.K=l[1],n.ia=l[2];const t=l[3];null!=t&&(n.la=t,n.j.info("VER="+n.la));const i=l[4];null!=i&&(n.Aa=i,n.j.info("SVER="+n.Aa));const u=l[5];null!=u&&"number"==typeof u&&0<u&&(r=1.5*u,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=pn(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&&(He(a),Ge(a)),r.g=o}else sn(r);0<n.i.length&&en(n)}else"stop"!=l[0]&&"close"!=l[0]||dn(n,7);else 3==n.G&&("stop"==l[0]||"close"==l[0]?"stop"==l[0]?dn(n,7):Yt(n):"noop"!=l[0]&&n.l&&n.l.ta(l),n.v=0)}xe(4)}catch(e){}}Fe.prototype.ca=function(e){e=e.target;const t=this.M;t&&3==Ht(e)?t.j():this.Y(e)},Fe.prototype.Y=function(e){try{if(e==this.g)e:{const d=Ht(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()||Qt(this.g)))){this.J||4!=d||7==t||xe(8==t||0>=f?3:2),He(this);var n=this.g.Z();this.X=n;t:if(je(this)){var r=Qt(this.g);e="";var i=r.length,s=4==Ht(this.g);if(!this.h.i){if("undefined"==typeof TextDecoder){We(this),Qe(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,l=this.g;if((c=l.g?l.g.getResponseHeader("X-HTTP-Initial-Response"):null)&&!m(c)){var u=c;break t}}u=null}if(!(n=u)){this.o=!1,this.s=3,De(12),We(this),Qe(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==$e){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(je(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),Qe(this)}else Le(this.i,this.l,a,null),Je(this,a);4==d&&We(this),this.o&&!this.J&&(4==d?un(this.j,this):(this.o=!1,Ge(this)))}else(function(e){const t={};e=(e.g&&2<=Ht(e)&&e.g.getAllResponseHeaders()||"").split("\r\n");for(let r=0;r<e.length;r++){if(m(e[r]))continue;var n=S(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),Qe(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,Qe(this)):Ke(this,this.S-e)};var Ye=class{constructor(e,t){this.g=e,this.map=t}};function Xe(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 p(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)}Xe.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,lt(this,e.j),this.o=e.o,this.g=e.g,ut(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,lt(this,t[1]||"",!0),this.o=pt(t[2]||""),this.g=pt(t[3]||"",!0),ut(this,t[4]),this.l=pt(t[5]||"",!0),ht(this,t[6]||"",!0),this.m=pt(t[7]||"")):(this.h=!1,this.i=new Et(null,this.h))}function ct(e){return new at(e)}function lt(e,t,n){e.j=n?pt(t,!0):t,e.j&&(e.j=e.j.replace(/:$/,""))}function ut(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&&(St(e),e.i=null,e.g.forEach((function(e,t){var n=t.toLowerCase();t!=n&&(Tt(this,t),Ct(this,n,e))}),e)),e.j=t}(e.i,e.h)):(n||(t=gt(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 pt(e,t){return e?t?decodeURI(e.replace(/%25/g,"%2525")):decodeURIComponent(e):""}function gt(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(gt(t,yt,!0),":");var n=this.g;return(n||"file"==t)&&(e.push("//"),(t=this.o)&&e.push(gt(t,yt,!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(gt(n,"/"==n.charAt(0)?bt:wt,!0))),(n=this.i.toString())&&e.push("?",n),(n=this.m)&&e.push("#",gt(n,It)),e.join("")};var vt,yt=/[#\/\?@]/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 St(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 Tt(e,t){St(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 St(e),t=Dt(e,t),e.g.has(t)}function Ct(e,t,n){Tt(e,t),0<n.length&&(e.i=null,e.g.set(Dt(e,t),p(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 ge}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 Mt(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 Pt(e){e.j.read().then(e.Pa.bind(e)).catch(e.ga.bind(e))}function Ot(e){e.readyState=4,e.l=null,e.j=null,e.v=null,Rt(e)}function Rt(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){St(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){St(this),this.g.forEach((function(n,r){n.forEach((function(n){e.call(t,n,r,this)}),this)}),this)},t.na=function(){St(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){St(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 St(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 Mt(this.l,this.j)},Lt.prototype.i=(vt={},function(){return vt}),f(Mt,ie),(t=Mt.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,Rt(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,Ot(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,Rt(this)),this.g&&(this.readyState=3,Rt(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;Pt(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?Ot(this):Rt(this),3==this.readyState&&Pt(this)}},t.Ra=function(e){this.g&&(this.response=this.responseText=e,Ot(this))},t.Qa=function(e){this.g&&(this.response=e,Ot(this))},t.ga=function(){this.g&&Ot(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(Mt.prototype,"withCredentials",{get:function(){return"include"===this.m},set:function(e){this.m=e?"include":"same-origin"}}),f(qt,ie);var $t=/^https?$/i,Bt=["POST","PUT"];function Ut(e,t){e.h=!1,e.g&&(e.j=!0,e.g.abort(),e.j=!1),e.l=t,e.m=5,jt(e),Gt(e)}function jt(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!=Ht(e)||2!=e.Z()))if(e.u&&4==Ht(e))ae(e.Ea,0,e);else if(se(e,"readystatechange"),4==Ht(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=!$t.test(i?i.toLowerCase():"")}n=r}if(n)se(e,"complete"),se(e,"success");else{e.m=6;try{var a=2<Ht(e)?e.g.statusText:""}catch(e){a=""}e.l=a+" ["+e.Z()+"]",jt(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 Ht(e){return e.g?e.g.readyState:0}function Qt(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 Xe(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 Yt(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=gn(t.j,null),t.g.ea(t.v)),t.F=Date.now(),Ge(t)}fn(e)}function Xt(e){e.g&&(an(e),e.g.cancel(),e.g=null)}function Zt(e){Xt(e),e.u&&(o.clearTimeout(e.u),e.u=null),ln(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),Be(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,Ue(n,e)}function ln(e){null!=e.C&&(o.clearTimeout(e.C),e.C=null)}function un(e,t){var n=null;if(e.g==t){ln(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=Se(),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||lt(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||(g(e.ka,t),g(e.ka,e.i),e.h.i.length=0,p(e.i),e.i.length=0),e.l.ra()}}function pn(e,t,n){var r=n instanceof at?ct(n):new at(n);if(""!=r.g)t&&(r.g=t+"."+r.g),ut(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&<(s,r),t&&(s.g=t),i&&ut(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 gn(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 vn(){}function yn(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():Me.g(),this.v=this.o?ve(this.o):ve(Me),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 Ut(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(Bt,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){Ut(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<Ht(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)),pe(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=pn(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,Be(i,n,null)):Be(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),Xt(this),cn(this))},t.Za=function(){null!=this.C&&(this.C=null,Xt(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(){},vn.prototype.g=function(e,t){return new yn(e,t)},f(yn,ie),yn.prototype.m=function(){this.g.l=this.j,this.v&&(this.g.J=!0),this.g.connect(this.l,this.h||void 0)},yn.prototype.close=function(){Yt(this.g)},yn.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 Ye(t.Ya++,e)),3==t.G&&en(t)},yn.prototype.N=function(){this.g.l=null,delete this.j,Yt(this.g),delete this.g,yn.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")},vn.prototype.createWebChannel=vn.prototype.g,yn.prototype.send=yn.prototype.o,yn.prototype.open=yn.prototype.m,yn.prototype.close=yn.prototype.close,e.exports.createWebChannelTransport=function(){return new vn},e.exports.getStatEventTarget=function(){return Se()},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},Pe.NO_ERROR=0,Pe.TIMEOUT=8,Pe.HTTP_ERROR=6,e.exports.ErrorCode=Pe,Oe.COMPLETE="complete",e.exports.EventType=Oe,ye.EventType=we,we.OPEN="a",we.CLOSE="b",we.ERROR="c",we.MESSAGE="d",ie.prototype.listen=ie.prototype.K,e.exports.WebChannel=ye,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:function(e,t,n){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.initCalculator=function(e,t){const n=`\n <div class="calculator-input purchase-price">\n <div class="header">\n <div class="title-wrapper">\n <img src="${s.default}" alt="Purchase Price icon"/>\n <div class="title">Purchase Price</div>\n </div>\n <img class="info-icon" src="${m.default}" alt="Info icon" data-tooltip="The total purchase price of the property"/>\n </div>\n <div class="input-field">\n <input type="text" value="$ 500,000" data-previous-value="500000" class="value-input">\n <input type="range" min="0" max="2000000" value="500000" class="slider">\n <div class="range-label">\n <span>$0</span>\n <span>$2M</span>\n </div>\n </div>\n </div>\n\n <div class="calculator-input down-payment">\n <div class="header">\n <div class="title-wrapper">\n <img src="${o.default}" alt="Down Payment icon"/>\n <div class="title">Down Payment</div>\n </div>\n <img class="info-icon" src="${m.default}" alt="Info icon" data-tooltip="Your initial payment towards the property"/>\n </div>\n <div class="input-field">\n <div class="downpayment-percentage-wrapper">\n <input type="text" value="$ 100,000" data-previous-value="100000" class="value-input">\n <input type="text" value="20%" data-previous-value="20" class="percentage-value-input">\n </div>\n <input type="range" min="5" max="40" value="20" class="slider">\n <div class="range-label">\n <span>5%</span>\n <span>40%</span>\n </div>\n </div>\n </div>\n\n <div class="calculator-input interest-rate">\n <div class="header">\n <div class="title-wrapper">\n <img src="${a.default}" alt="Interest Rate icon"/>\n <div class="title">Interest Rate</div>\n </div>\n <div class="fixed-variable-selector">\n <div class="selector">Fixed</div>\n <div class="selector active">Variable</div>\n </div>\n </div>\n <div class="input-field">\n <input type="text" value="6.00%" data-previous-value="6.00" class="value-input">\n <input type="range" min="0.1" max="40" value="6" step="0.1" class="slider">\n <div class="range-label">\n <span>0.1%</span>\n <span>40%</span>\n </div>\n </div>\n </div>\n\n <div class="calculator-input amortization-period">\n <div class="header">\n <div class="title-wrapper">\n <img src="${c.default}" alt="Amortization Period icon"/>\n <div class="title">Amortization Period</div>\n </div>\n <img class="info-icon" src="${m.default}" alt="Info icon" data-tooltip="The total length of time to pay off your mortgage"/>\n </div>\n <div class="dropdown">\n <div class="dropdown-field">\n <span>25 years</span>\n <img class="info-icon" src="${l.default}" alt="Dropdown icon"/> \n </div>\n <div class="dropdown-opts">\n <div class="dropdown-opt">5 years</div>\n <div class="dropdown-opt">10 years</div>\n <div class="dropdown-opt">15 years</div>\n <div class="dropdown-opt">20 years</div>\n <div class="dropdown-opt">25 years</div>\n <div class="dropdown-opt">30 years</div>\n </div>\n </div>\n </div>\n\n <div class="calculator-input term-length">\n <div class="header">\n <div class="title-wrapper">\n <img src="${u.default}" alt="Term Length icon"/>\n <div class="title">Term Length</div>\n </div>\n <img class="info-icon" src="${m.default}" alt="Info icon" data-tooltip="The length of your mortgage term"/>\n </div>\n <div class="dropdown">\n <div class="dropdown-field">\n <span>5 years</span>\n <img class="info-icon" src="${l.default}" alt="Dropdown icon"/> \n </div>\n <div class="dropdown-opts">\n <div class="dropdown-opt">1 year</div>\n <div class="dropdown-opt">2 years</div>\n <div class="dropdown-opt">3 years</div>\n <div class="dropdown-opt">4 years</div>\n <div class="dropdown-opt">5 years</div>\n <div class="dropdown-opt">7 years</div>\n <div class="dropdown-opt">10 years</div>\n </div>\n </div>\n </div>\n\n <div class="calculator-input payment-frequency">\n <div class="header">\n <div class="title-wrapper">\n <img src="${h.default}" alt="Payment Frequency icon"/>\n <div class="title">Payment Frequency</div>\n </div>\n <img class="info-icon" src="${m.default}" alt="Info icon" data-tooltip="How often you make mortgage payments"/>\n </div>\n <div class="dropdown">\n <div class="dropdown-field">\n <span>Monthly</span>\n <img class="info-icon" src="${l.default}" alt="Dropdown icon"/> \n </div>\n <div class="dropdown-opts">\n <div class="dropdown-opt">Monthly</div>\n <div class="dropdown-opt">Semi-Monthly</div>\n <div class="dropdown-opt">Bi-Weekly</div>\n <div class="dropdown-opt">Accelerated Bi-Weekly</div>\n <div class="dropdown-opt">Weekly</div>\n <div class="dropdown-opt">Accelerated Weekly</div>\n </div>\n </div>\n </div>\n\n `,r=`\n <div class="calculator-input term-length">\n <div class="header">\n <div class="title-wrapper">\n <img src="${u.default}" alt="Term Length icon"/>\n <div class="title">Term Length</div>\n </div>\n <img class="info-icon" src="${m.default}" alt="Info icon" data-tooltip="The length of your mortgage contract"/>\n </div>\n <div class="dropdown">\n <div class="dropdown-field">\n <span>5 years</span>\n <img class="info-icon" src="${l.default}" alt="Dropdown icon"/> \n </div>\n <div class="dropdown-opts">\n <div class="dropdown-opt">1 year</div>\n <div class="dropdown-opt">2 years</div>\n <div class="dropdown-opt">3 years</div>\n <div class="dropdown-opt">4 years</div>\n <div class="dropdown-opt">5 years</div>\n <div class="dropdown-opt">7 years</div>\n <div class="dropdown-opt">10 years</div>\n </div>\n </div>\n </div>\n\n <div class="calculator-input property-taxes">\n <div class="header">\n <div class="title-wrapper">\n <img src="${d.default}" alt="Property Taxes icon"/>\n <div class="title">Property Taxes</div>\n </div>\n <img class="info-icon" src="${m.default}" alt="Info icon" data-tooltip="Annual property taxes"/>\n </div>\n <div class="input-field">\n <input type="text" value="$ 9,600" data-previous-value="9600" class="value-input">\n <input type="range" min="0" max="10000" value="9600" class="slider">\n <div class="range-label">\n <span>$0</span>\n <span>$10,000</span>\n </div>\n </div>\n </div>\n\n <div class="calculator-input heating-costs">\n <div class="header">\n <div class="title-wrapper">\n <img src="${f.default}" alt="Heating Costs icon"/>\n <div class="title">Heating Costs</div>\n </div>\n <img class="info-icon" src="${m.default}" alt="Info icon" data-tooltip="Annual heating costs"/>\n </div>\n <div class="input-field">\n <input type="text" value="$ 2,400" data-previous-value="2400" class="value-input">\n <input type="range" min="0" max="3000" value="2400" class="slider">\n <div class="range-label">\n <span>$0</span>\n <span>$3,000</span>\n </div>\n </div>\n </div>\n\n <div class="calculator-input condo-fees">\n <div class="header">\n <div class="title-wrapper">\n <img src="${p.default}" alt="Condo Fees icon"/>\n <div class="title">Condo Fees</div>\n </div>\n <img class="info-icon" src="${m.default}" alt="Info icon" data-tooltip="Monthly condo maintenance fees"/>\n </div>\n <div class="input-field">\n <input type="text" value="$ 250" data-previous-value="250" class="value-input">\n <input type="range" min="0" max="1000" value="250" class="slider">\n <div class="range-label">\n <span>$0</span>\n <span>$1,000</span>\n </div>\n </div>\n </div>\n\n <div class="calculator-input extra-payments">\n <div class="header">\n <div class="title-wrapper">\n <img src="${g.default}" alt="Extra Payments icon"/>\n <div class="title">Extra Payments</div>\n </div>\n <div class="extra-payment-selectors">\n <span class="selector">None</span>\n <span class="selector active">One-Time</span>\n <span class="selector">Recurring</span>\n </div>\n </div>\n <div class="input-field"><input type="text" value="$ 0" data-previous-value="0" class="value-input"></div>\n <div class="dropdown">\n <div class="dropdown-field">\n <span>Monthly</span>\n <img class="info-icon" src="${l.default}" alt="Dropdown icon"/> \n </div>\n <div class="dropdown-opts">\n <div class="dropdown-opt">Monthly</div>\n <div class="dropdown-opt">Yearly</div>\n <div class="dropdown-opt">One-time</div>\n </div>\n </div>\n </div>\n\n `;e.innerHTML=`\n <div class="mortgage-calculator">\n <div class="section-heading">Mortgage Calculator</div>\n <div class="tab-layout">\n <div class="tab-headers">\n <div class="tab-header active">Standard</div>\n <div class="tab-header">Advanced</div>\n </div>\n <div class="tab-content active">\n <div class="calculator-inputs">\n ${n}\n </div>\n <div class="calculator-results">\n \n <div class="mortgage-payment">\n <div class="mortgage-payment-wrapper">\n <div class="label">Mortgage Payment</div>\n <div class="value">$2,902</div>\n <div class="frequency">Monthly Payment</div>\n </div>\n <div class="mortgage-amount-insurance">\n <div class="mortgage-amount">\n <div class="label">Mortgage Amount</div>\n <div class="value">$440,000</div>\n </div>\n <div class="mortgage-insurance">\n <div class="label">Mortgage Insurance</div>\n <div class="value">$13,640</div>\n </div>\n </div>\n </div>\n\n <div class="payment-breakdown">\n <div class="section-label">Payment Breakdown</div>\n <div class="section-wrapper">\n <div class="principal">\n <div class="label">Principal</div>\n <div class="value">$662</div>\n </div>\n <div class="interest">\n <div class="label">Interest</div>\n <div class="value">$2,240</div>\n </div>\n </div>\n </div>\n\n <div class="term-calculations">\n <div class="section-label">Term Calculations (<span>5 years</span>)</div>\n <div class="section-wrapper">\n <div class="calculation-row">\n <div class="label">Total Payments over Term</div>\n <div class="value">$174,145</div>\n </div>\n <div class="calculation-row">\n <div class="label">Principal Paid during Term</div>\n <div class="value">$46,105</div>\n </div>\n <div class="calculation-row">\n <div class="label">Interest Paid during Term</div>\n <div class="value">$128,040</div>\n </div>\n <div class="calculation-row">\n <div class="label">Balance Remaining after Term</div>\n <div class="value">$407,535</div>\n </div>\n <div class="calculation-row">\n <input type="range" min="1" max="100" value="10" step="1" class="slider principal-slider" disabled>\n <div class="range-label">\n <span>Principal Paid (10%)</span>\n <span>Remaining Balance</span>\n </div>\n </div>\n </div>\n </div>\n\n <div class="total-mortgage">\n <div class="section-label">Total Mortgage (<span>25 years</span>)</div>\n <div class="section-wrapper">\n <div class="calculation-row">\n <div class="label">Total Mortgage + Interest</div>\n <div class="value">$870,726</div>\n </div>\n <div class="calculation-row">\n <div class="label">Total Interest Paid</div>\n <div class="value">$417,086</div>\n </div>\n <div class="calculation-row">\n <div class="label">Interest/Principal Ratio</div>\n <div class="value">92%</div>\n </div>\n <div class="calculation-row">\n <div class="calculation-row-label">Amortization</div>\n <input type="range" min="1" max="100" value="92" step="1" class="slider amortization-result-slider" disabled>\n <div class="range-label">\n <span>Principal</span>\n <span>Interest</span>\n </div>\n </div>\n </div>\n </div>\n\n \n </div>\n </div>\n <div class="tab-content">\n <div class="calculator-inputs">\n ${r}\n </div>\n <div class="calculator-results">\n \n <div class="total-mortgage-payment">\n <div class="mortgage-payment-wrapper">\n <div class="label">Total Mortgage Payment</div>\n <div class="value">$3,902</div>\n <div class="frequency">Including all selected costs</div>\n </div>\n <div class="mortgage-amount-insurance">\n <div class="mortgage-amount advanced-mortgage-payment">\n <div class="label">Mortgage Payment</div>\n <div class="value">$2,902</div>\n </div>\n <div class="mortgage-insurance property-taxes">\n <div class="label">Property Taxes</div>\n <div class="value">$800</div>\n </div>\n <div class="mortgage-amount heating-costs">\n <div class="label">Heating Costs</div>\n <div class="value">$200</div>\n </div>\n <div class="mortgage-insurance condo-fees">\n <div class="label">Condo Fees</div>\n <div class="value">$0</div>\n </div>\n </div>\n </div>\n\n <div class="extra-payment-impacts">\n <div class="section-label">Impact of Extra Payments</div>\n <div class="section-wrapper">\n <div class="principal years-saved">\n <div class="label">Years Saved</div>\n <div class="value">0 years</div>\n </div>\n <div class="interest interest-saved">\n <div class="label">Interest Saved</div>\n <div class="value">$0</div>\n </div>\n </div>\n </div>\n\n <div class="mortgage-stress-test">\n <div class="section-label">Mortgage Stress Test</div>\n <div class="section-wrapper">\n <div class="calculation-row">\n <div class="label">Qualifying Rate</div>\n <div class="value">8.00%</div>\n </div>\n <div class="calculation-row">\n <div class="label">Stress Test Payment</div>\n <div class="value">$3,358</div>\n </div>\n <div class="calculation-row">\n <div class="label">Income Required</div>\n <div class="value">$163,430</div>\n </div>\n </div>\n </div>\n\n \n </div>\n </div>\n </div>\n </div>\n `;const v=document.querySelector(".purchase-price .value-input"),y=document.querySelector(".purchase-price .slider"),w=document.querySelector(".down-payment .value-input"),b=document.querySelector(".down-payment .percentage-value-input"),_=document.querySelector(".down-payment .slider"),I=document.querySelector(".interest-rate .value-input"),E=document.querySelector(".interest-rate .slider"),S=document.querySelector(".term-calculations .principal-slider"),T=document.querySelector(".total-mortgage .amortization-result-slider"),x=document.querySelectorAll(".tab-header"),C=document.querySelectorAll(".tab-content"),D=document.querySelector(".property-taxes .value-input"),A=document.querySelector(".property-taxes .slider"),k=document.querySelector(".heating-costs .value-input"),N=document.querySelector(".heating-costs .slider"),L=document.querySelector(".condo-fees .value-input"),M=document.querySelector(".condo-fees .slider"),P=document.querySelector(".extra-payments .value-input"),O=document.querySelector(".amortization-period .dropdown-field span"),R=document.querySelector(".payment-frequency .dropdown-field span"),F=document.querySelector(".term-length .dropdown-field span"),V=document.querySelector(".extra-payments .dropdown-field span"),q=document.querySelector(".calculator-results .mortgage-payment-wrapper .value"),$=document.querySelector(".calculator-results .mortgage-amount-insurance .mortgage-amount .value"),B=document.querySelector(".calculator-results .mortgage-amount-insurance .mortgage-insurance .value"),U=document.querySelector(".calculator-results .payment-breakdown .principal .value"),j=document.querySelector(".calculator-results .payment-breakdown .interest .value"),z=document.querySelector(".term-calculations .section-wrapper .calculation-row:nth-child(1) .value"),G=document.querySelector(".term-calculations .section-wrapper .calculation-row:nth-child(2) .value"),K=document.querySelector(".term-calculations .section-wrapper .calculation-row:nth-child(3) .value"),H=document.querySelector(".term-calculations .section-wrapper .calculation-row:nth-child(4) .value"),Q=document.querySelector(".total-mortgage .section-wrapper .calculation-row:nth-child(1) .value"),W=document.querySelector(".total-mortgage .section-wrapper .calculation-row:nth-child(2) .value"),J=document.querySelector(".total-mortgage .section-wrapper .calculation-row:nth-child(3) .value"),Y=document.querySelector(".term-calculations .section-label span"),X=document.querySelector(".total-mortgage .section-label span"),Z=document.querySelector(".calculator-results .total-mortgage-payment .mortgage-payment-wrapper .value"),ee=document.querySelector(".calculator-results .total-mortgage-payment .mortgage-amount-insurance .advanced-mortgage-payment .value"),te=document.querySelector(".calculator-results .total-mortgage-payment .mortgage-amount-insurance .property-taxes .value"),ne=document.querySelector(".calculator-results .total-mortgage-payment .mortgage-amount-insurance .heating-costs .value"),re=document.querySelector(".calculator-results .total-mortgage-payment .mortgage-amount-insurance .condo-fees .value"),ie=document.querySelector(".calculator-results .extra-payment-impacts .years-saved .value"),se=document.querySelector(".calculator-results .extra-payment-impacts .interest-saved .value"),oe=document.querySelector(".calculator-results .mortgage-stress-test .section-wrapper .calculation-row:nth-child(1) .value"),ae=document.querySelector(".calculator-results .mortgage-stress-test .section-wrapper .calculation-row:nth-child(2) .value"),ce=document.querySelector(".calculator-results .mortgage-stress-test .section-wrapper .calculation-row:nth-child(3) .value"),le=document.querySelectorAll(".fixed-variable-selector .selector"),ue=document.querySelectorAll(".extra-payment-selectors .selector"),he=document.querySelectorAll("[data-tooltip]");function de(e){const t=Number(e.value),n=Number(e.min),r=(t-n)/(Number(e.max)-n)*100;e.style.background=`linear-gradient(to right, #5f758a ${r}%, #5f758a2f ${r}%)`}document.querySelectorAll(".dropdown-opt").forEach((e=>{e.addEventListener("click",(()=>{var t,n;const r=null===(t=e.parentElement)||void 0===t?void 0:t.previousElementSibling,i=null==r?void 0:r.querySelector("span");i&&(i.textContent=e.textContent),null===(n=e.parentElement)||void 0===n||n.classList.remove("expanded"),ge()}))})),document.querySelectorAll(".dropdown-field").forEach((e=>{e.addEventListener("click",(t=>{document.querySelectorAll(".dropdown-opts.expanded").forEach((e=>{e.classList.remove("expanded")}));const n=e.nextElementSibling;null==n||n.classList.toggle("expanded"),t.stopPropagation()}))})),document.addEventListener("click",(e=>{e.target.closest(".dropdown")||document.querySelectorAll(".dropdown-opts.expanded").forEach((e=>{e.classList.remove("expanded")}))})),x.forEach(((e,t)=>{e.addEventListener("click",(()=>{x.forEach((e=>e.classList.remove("active"))),C.forEach((e=>e.classList.remove("active"))),e.classList.add("active"),C[t].classList.add("active"),ge()}))})),le.forEach(((e,t)=>{e.addEventListener("click",(()=>{le.forEach((e=>e.classList.remove("active"))),e.classList.add("active"),ge()}))})),ue.forEach(((e,t)=>{e.addEventListener("click",(()=>{var t,n,r,i,s,o;ue.forEach((e=>e.classList.remove("active"))),e.classList.add("active");const a=null===(n=null===(t=e.parentElement)||void 0===t?void 0:t.parentElement)||void 0===n?void 0:n.nextElementSibling,c=null===(s=null===(i=null===(r=e.parentElement)||void 0===r?void 0:r.parentElement)||void 0===i?void 0:i.nextElementSibling)||void 0===s?void 0:s.nextElementSibling;"none"===(null===(o=e.textContent)||void 0===o?void 0:o.toLowerCase())?(null==a||a.classList.add("disabled"),null==c||c.classList.add("disabled")):(null==a||a.classList.remove("disabled"),null==c||c.classList.remove("disabled")),ge()}))})),he.forEach((e=>{const t=e.getAttribute("data-tooltip"),n=document.createElement("div");n.className="custom-tooltip",n.textContent=t,document.body.appendChild(n),e.addEventListener("mousemove",(e=>{const t=e;n.style.top=`${t.pageY+20}px`,n.style.left=t.pageX-n.clientWidth/2+"px"})),e.addEventListener("mouseenter",(e=>{n.style.opacity="1",n.style.pointerEvents="none"})),e.addEventListener("mouseleave",(()=>{n.style.opacity="0"}))})),y.addEventListener("input",(()=>{const e=y.value.replace(/[^0-9.]/g,"");v.value=e?`$ ${parseInt(e).toLocaleString("en-US")}`:"",v.dataset.previousValue=e,de(y),fe(),ge()})),_.addEventListener("input",(()=>{var e;let t=null===(e=v.dataset.previousValue)||void 0===e?void 0:e.replace(/[^0-9.]/g,"");const n=t?parseInt(t):0,r=_.value.replace(/[^0-9.]/g,"");b.value=r?`${parseInt(r).toLocaleString("en-US")}%`:"",b.dataset.previousValue=r;const i=n&&r?n*(.01*parseInt(r)):0;w.value=`$ ${i.toLocaleString("en-US")}`,w.dataset.previousValue=i.toString(),de(_),ge()})),E.addEventListener("input",(()=>{const e=E.value.replace(/[^0-9.]/g,"");I.value=e?`${parseFloat(e).toFixed(2)}%`:"",I.dataset.previousValue=e,de(E),ge()})),A.addEventListener("input",(()=>{const e=A.value.replace(/[^0-9.]/g,"");D.value=e?`$ ${parseInt(e).toLocaleString("en-US")}`:"",D.dataset.previousValue=e,de(A),ge()})),N.addEventListener("input",(()=>{const e=N.value.replace(/[^0-9.]/g,"");k.value=e?`$ ${parseInt(e).toLocaleString("en-US")}`:"",k.dataset.previousValue=e,de(N),ge()})),M.addEventListener("input",(()=>{const e=M.value.replace(/[^0-9.]/g,"");L.value=e?`$ ${parseInt(e).toLocaleString("en-US")}`:"",L.dataset.previousValue=e,de(M),ge()}));const fe=()=>{var e,t;let n=null===(e=v.dataset.previousValue)||void 0===e?void 0:e.replace(/[^0-9.]/g,"");const r=n?parseInt(n):0,i=parseInt(null!==(t=w.dataset.previousValue)&&void 0!==t?t:"0")/r*100;_.value=i.toString(),de(_),b.value=`${i.toLocaleString("en-US")}%`,b.dataset.previousValue=i.toString()},pe=(e,t,n)=>{e.addEventListener("input",(e=>{var r,i;const s=e.target;if(s){let e=s.value;e=e.replace(/[^0-9.]/g,"");const o=e?parseInt(e):0;switch(n){case"purchase-price":0<=o&&o<=2e6?(y.value=o.toString(),de(y),s.value=`${t} ${parseInt(e).toLocaleString("en-US")}`,s.dataset.previousValue=e):s.dataset.previousValue&&(s.value=`${t} ${parseInt(s.dataset.previousValue).toLocaleString("en-US")}`),fe();break;case"downpayment":let n=null===(r=v.dataset.previousValue)||void 0===r?void 0:r.replace(/[^0-9.]/g,"");const a=n?parseInt(n):0;if(o<=.4*a){const n=o/a*100;_.value=n.toString(),de(_),b.value=`${n.toLocaleString("en-US")}%`,b.dataset.previousValue=n.toString(),s.value=`${t} ${parseInt(e).toLocaleString("en-US")}`,s.dataset.previousValue=e}else s.dataset.previousValue&&(s.value=`${t} ${s.dataset.previousValue}`);break;case"downpayment-percentage":if(1<=o&&o<=40){_.value=o.toString(),de(_),s.value=`${e}${t}`,s.dataset.previousValue=e;let n=null===(i=v.dataset.previousValue)||void 0===i?void 0:i.replace(/[^0-9.]/g,"");const r=n?parseInt(n):0,a=r?r*(.01*o):0;w.value=`$ ${a.toLocaleString("en-US")}`,w.dataset.previousValue=a.toString()}else s.dataset.previousValue&&(s.value=`${s.dataset.previousValue}${t}`);break;case"interest-rate":const c=e?parseFloat(e):0;.1<=c&&c<=40?(E.value=c.toFixed(2),de(E),s.value=`${c.toFixed(2)}%`,s.dataset.previousValue=c.toFixed(2)):s.dataset.previousValue&&(s.value=`${parseFloat(s.dataset.previousValue).toFixed(2)}%`);break;case"property-taxes":0<=o&&o<=1e4?(A.value=o.toString(),de(A),s.value=`${t} ${parseInt(e).toLocaleString("en-US")}`,s.dataset.previousValue=e):s.dataset.previousValue&&(s.value=`${t} ${parseInt(s.dataset.previousValue).toLocaleString("en-US")}`);break;case"heating-costs":0<=o&&o<=3e3?(N.value=o.toString(),de(N),s.value=`${t} ${parseInt(e).toLocaleString("en-US")}`,s.dataset.previousValue=e):s.dataset.previousValue&&(s.value=`${t} ${parseInt(s.dataset.previousValue).toLocaleString("en-US")}`);break;case"condo-fees":0<=o&&o<=1e3?(M.value=o.toString(),de(M),s.value=`${t} ${parseInt(e).toLocaleString("en-US")}`,s.dataset.previousValue=e):s.dataset.previousValue&&(s.value=`${t} ${parseInt(s.dataset.previousValue).toLocaleString("en-US")}`);break;case"extra-payments":0<=o?(s.value=`${t} ${parseInt(e).toLocaleString("en-US")}`,s.dataset.previousValue=e):s.dataset.previousValue&&(s.value=`${t} ${parseInt(s.dataset.previousValue).toLocaleString("en-US")}`)}ge()}}))},ge=()=>{var e;const t=document.querySelector(".mortgage-calculator .tab-headers .active"),n=document.querySelector(".interest-rate .fixed-variable-selector .active"),r=document.querySelector(".extra-payments .extra-payment-selectors .active"),s=null===(e=t.textContent)||void 0===e?void 0:e.toLowerCase(),o={purchasePrice:v.dataset.previousValue?parseInt(v.dataset.previousValue):0,downPaymentAmount:w.dataset.previousValue?parseInt(w.dataset.previousValue):0,downPaymentPercentage:b.dataset.previousValue?parseInt(b.dataset.previousValue):0,interestRate:I.dataset.previousValue?parseFloat(parseFloat(I.dataset.previousValue).toFixed(2)):0,amortizationPeriod:O.textContent?parseInt(O.textContent.replace(" years","")):5,paymentFrequency:R.textContent?R.textContent.toLowerCase():"monthly",rateType:n.textContent?n.textContent.toLowerCase():"fixed",termLength:F.textContent?parseInt(F.textContent.replace(" years","").replace(" year","")):5,propertyTaxes:D.dataset.previousValue?parseInt(D.dataset.previousValue):0,heatingCosts:k.dataset.previousValue?parseInt(k.dataset.previousValue):0,condoFees:L.dataset.previousValue?parseInt(L.dataset.previousValue):0,extraPaymentType:r.textContent?r.textContent.toLowerCase():"none",extraPaymentAmount:P.dataset.previousValue?parseInt(P.dataset.previousValue):0,extraPaymentFrequency:V.textContent?V.textContent.toLowerCase():"monthly"},a=(0,i.calculateMortgage)(o),c=(0,i.calculateAdvancedResults)(o);"standard"===s?(q.textContent=`$${a.monthlyPayment.toLocaleString()}`,$.textContent=`$${a.mortgageAmount.toLocaleString()}`,B.textContent=`$${a.mortgageInsurance.toLocaleString()}`,U.textContent=`$${a.principal.toLocaleString()}`,j.textContent=`$${a.interest.toLocaleString()}`,z.textContent=`$${a.termPayments.toLocaleString()}`,G.textContent=`$${a.termPrincipalPaid.toLocaleString()}`,K.textContent=`$${a.termInterestPaid.toLocaleString()}`,H.textContent=`$${a.remainingPrincipalAtEndOfTerm.toLocaleString()}`,S.value=Math.round(a.termPrincipalPaid/a.mortgageAmount*100).toString(),de(S),Q.textContent=`$${a.totalMortgagePlusInterest.toLocaleString()}`,W.textContent=`$${a.totalInterestPaid.toLocaleString()}`,J.textContent=`${a.interestPrincipalRatio}%`,T.value=(100-a.interestPrincipalRatio).toString(),de(T),Y.textContent=F.textContent,X.textContent=O.textContent):(Z.textContent=`$${c.totalMonthlyPayment.toLocaleString()}`,ee.textContent=`$${c.mortgagePayment.toLocaleString()}`,te.textContent=`$${c.propertyTaxesMonthly.toLocaleString()}`,ne.textContent=`$${c.heatingCostsMonthly.toLocaleString()}`,re.textContent=`$${c.condoFeesMonthly.toLocaleString()}`,ie.textContent=`${c.yearsSaved} years`,se.textContent=`$${c.interestSaved.toLocaleString()}`,oe.textContent=`${c.qualifyingRate.toFixed(2)}%`,ae.textContent=`$${c.stressTestPayment.toLocaleString()}`,ce.textContent=`$${c.incomeRequired.toLocaleString()}`)};pe(v,"$","purchase-price"),de(y),pe(b,"%","downpayment-percentage"),pe(w,"$","downpayment"),de(_),pe(I,"%","interest-rate"),de(E),de(S),de(T),pe(D,"$","property-taxes"),de(A),pe(k,"$","heating-costs"),de(N),pe(L,"$","condo-fees"),de(M),pe(P,"$","extra-payments"),ge()};const i=n(185),s=r(n(450)),o=r(n(790)),a=r(n(636)),c=r(n(904)),l=r(n(38)),u=r(n(706)),h=r(n(490)),d=r(n(552)),f=r(n(378)),p=r(n(800)),g=r(n(877)),m=r(n(947))},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")),l=r.filter((e=>"housing-indicators"===e.id))[0];let u="";for(let e of l.stats)u+=`\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=u,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">×</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),l="educational_videos",u=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,l),(0,o.orderBy)("date","desc"),(0,o.limit)(u));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(!l){const{getFirestore:e}=yield Promise.resolve().then((()=>s(n(815)))),t=(0,a.initializeApp)(c);l=e(t)}return l}))},t.getFirebaseFunctions=function(){return o(this,void 0,void 0,(function*(){if(!u){const{getFunctions:e}=yield Promise.resolve().then((()=>s(n(619)))),t=(0,a.initializeApp)(c);u=e(t)}return u}))};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 l=null,u=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"),l=e.querySelector(".free-guides-form .name-field"),u=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=l.value,t=u.value;e&&t&&p(t)?d.classList.remove("disabled"):d.classList.add("disabled")})),p=e=>/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(e);l.addEventListener("change",(e=>{f()})),u.addEventListener("change",(e=>{f()})),h.addEventListener("change",(e=>{f()})),d.addEventListener("click",(e=>r(this,void 0,void 0,(function*(){const e=l.value.trim(),t=u.value.trim(),r=h.checked;try{d.textContent="Processing...",d.disabled=!0,d.classList.toggle("disabled");const a=yield(0,o.getFirebaseFunctions)(),l=(0,s.httpsCallable)(a,"sendGuideEmail"),u=(yield l({name:e,email:t,consent:r,file:"test-1.pdf"})).data;if(u.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=u.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">×</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),l="market_trend_videos",u=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,l),(0,o.orderBy)("date","desc"),(0,o.limit)(u));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"),u=n.textContent?n.textContent:"",l=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 l=null,u="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));u&&(r=(0,s.query)(r,(0,s.where)("category","==",u))),l&&(r=(0,s.query)(r,(0,s.startAfter)(l)));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,l,h,d;const f=e.data(),p=document.createElement("div");p.classList.add("calendar-event"),t.classList.remove("show","three-col-layout"),"Interest Rate"===u?(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 ',p.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"===u?(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 ',p.classList.add("three-col-layout"),p.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"===u&&(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 ',p.classList.add("three-col-layout"),p.innerHTML=`\n <div class="calendar-event-col">${null===(l=f.title)||void 0===l?void 0:l.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(p)})),l=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,l),(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 u=Object.keys(c);let h="";u.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)),l="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)),l="mortgage_news",u=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,l),(0,o.orderBy)("date","desc"),(0,o.limit)(u));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;u(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 u(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 l=null;function u(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));l&&(n=(0,s.query)(n,(0,s.startAfter)(l)));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)})),l=r.docs[r.docs.length-1],!0)}catch(e){return console.error("Error loading research articles:",e),!1}}))}},185:(e,t)=>{"use strict";function n(e){const t=e.purchasePrice-e.downPaymentAmount;let n=0;if(e.downPaymentPercentage<20){let r=0;e.downPaymentPercentage>=15?r=.028:e.downPaymentPercentage>=10?r=.031:e.downPaymentPercentage>=5&&(r=.04),n=t*r}const r=t+n,i=e.interestRate/100/2,s=Math.pow(1+i,2/12)-1,o=12*e.amortizationPeriod,a=12*e.termLength,c=r*(s*Math.pow(1+s,o))/(Math.pow(1+s,o)-1),l=c*o,u=l-r,h=r*s,d=c-h,f=Math.round(u/r*100),p=c*a,g=function(e,t,n,r){return e*Math.pow(1+t,r)-n*(Math.pow(1+t,r)-1)/t}(r,s,c,a),m=r-g,v=p-m;return{monthlyPayment:Math.round(c),mortgageAmount:Math.round(t),mortgageInsurance:Math.round(n),principal:Math.round(d),interest:Math.round(h),totalMortgagePlusInterest:Math.round(l),totalInterestPaid:Math.round(u),interestPrincipalRatio:f,termPayments:Math.round(p),termPrincipalPaid:Math.round(m),termInterestPaid:Math.round(v),remainingPrincipalAtEndOfTerm:Math.round(g)}}Object.defineProperty(t,"__esModule",{value:!0}),t.defaultMortgageData=void 0,t.calculateMortgage=n,t.calculateAdvancedResults=function(e){const t=n(e),r=Math.round(e.propertyTaxes/12),i=Math.round(e.heatingCosts/12),s=e.condoFees,o=t.monthlyPayment+r+i+s;let a=0,c=0;if("none"!==e.extraPaymentType&&e.extraPaymentAmount>0){const n="monthly"===e.extraPaymentFrequency?12*e.extraPaymentAmount:e.extraPaymentAmount;a=Math.min(Math.round(n*e.amortizationPeriod/t.mortgageAmount),e.amortizationPeriod-1),c=Math.round(12*a*t.interest)}const l=Math.max(e.interestRate+2,5.25),u=l/100/2,h=Math.pow(1+u,2/12)-1,d=12*e.amortizationPeriod,f=(e.purchasePrice-e.downPaymentAmount)*(h*Math.pow(1+h,d))/(Math.pow(1+h,d)-1),p=12*f+e.propertyTaxes+e.heatingCosts+12*e.condoFees,g=Math.round(p/.32);return{totalMonthlyPayment:Math.round(o),mortgagePayment:t.monthlyPayment,propertyTaxesMonthly:r,heatingCostsMonthly:i,condoFeesMonthly:s,yearsSaved:a,interestSaved:c,qualifyingRate:l,stressTestPayment:Math.round(f),incomeRequired:g}},t.formatDate=function(e){const t=new Date(e);return new Intl.DateTimeFormat("en-US",{month:"long",day:"numeric",year:"numeric"}).format(t)},t.defaultMortgageData={purchasePrice:5e5,downPaymentAmount:1e5,downPaymentPercentage:20,interestRate:4.75,amortizationPeriod:25,paymentFrequency:"monthly",rateType:"fixed",termLength:5,propertyTaxes:3600,heatingCosts:1200,condoFees:0,extraPaymentType:"none",extraPaymentAmount:0,extraPaymentFrequency:"monthly"}},904:(e,t,n)=>{"use strict";e.exports=n.p+"0aedc236b853cf75f799.svg"},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"},800:(e,t,n)=>{"use strict";e.exports=n.p+"9494550fdfafc3ef2c95.svg"},790:(e,t,n)=>{"use strict";e.exports=n.p+"255c94be199eb8f10a50.svg"},38:(e,t,n)=>{"use strict";e.exports=n.p+"4cf66e75d98ed1b6111b.svg"},877:(e,t,n)=>{"use strict";e.exports=n.p+"1358c7e31687624f57e2.svg"},765:(e,t,n)=>{"use strict";e.exports=n.p+"d686a45650560ddaa773.svg"},378:(e,t,n)=>{"use strict";e.exports=n.p+"f788593ff71e33e36caf.svg"},947:(e,t,n)=>{"use strict";e.exports=n.p+"eed2bfb095ae763cb632.svg"},636:(e,t,n)=>{"use strict";e.exports=n.p+"f45122777360c8743959.svg"},490:(e,t,n)=>{"use strict";e.exports=n.p+"c0479e777ea346aaaa27.svg"},757:(e,t,n)=>{"use strict";e.exports=n.p+"dec0b8717bf0d582857b.svg"},552:(e,t,n)=>{"use strict";e.exports=n.p+"43c55608a5fb15ce54c5.svg"},450:(e,t,n)=>{"use strict";e.exports=n.p+"204629feb4301824d2a9.svg"},706:(e,t,n)=>{"use strict";e.exports=n.p+"7a6c5262adc1cd432101.svg"},148:(e,t,n)=>{"use strict";n.r(t),n.d(t,{deleteDB:()=>m,openDB:()=>g,unwrap:()=>p,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,l=new WeakMap,u=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(p(this),e),f(o.get(this))}:function(...e){return f(t.apply(p(this),e))}:function(e,...n){const r=t.call(p(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((()=>{})),u.set(t,e),t}(e);if(l.has(e))return l.get(e);const t=d(e);return t!==e&&(l.set(e,t),u.set(t,e)),t}const p=e=>u.get(e);function g(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 v=["get","getKey","getAll","getAllKeys","count"],y=["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=y.includes(n);if(!(n in(r?IDBIndex:IDBObjectStore).prototype)||!i&&!v.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,u.initCockpit)(r);break;case"educational-videos":(0,l.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),l=n(260),u=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",l="0.10.17",u=new i.Logger("@firebase/app"),d="@firebase/app-compat",h="@firebase/analytics-compat",f="@firebase/analytics",p="@firebase/app-check-compat",m="@firebase/app-check",g="@firebase/auth",v="@firebase/auth-compat",y="@firebase/database",w="@firebase/data-connect",b="@firebase/database-compat",_="@firebase/functions",I="@firebase/functions-compat",E="@firebase/installations",S="@firebase/installations-compat",T="@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",P="@firebase/firestore",M="@firebase/vertexai",R="@firebase/firestore-compat",O="firebase",F="[DEFAULT]",V={[c]:"fire-core",[d]:"fire-core-compat",[f]:"fire-analytics",[h]:"fire-analytics-compat",[m]:"fire-app-check",[p]:"fire-app-check-compat",[g]:"fire-auth",[v]:"fire-auth-compat",[y]:"fire-rtdb",[w]:"fire-data-connect",[b]:"fire-rtdb-compat",[_]:"fire-fn",[I]:"fire-fn-compat",[E]:"fire-iid",[S]:"fire-iid-compat",[T]:"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",[P]:"fire-fst",[R]:"fire-fst-compat",[M]:"fire-vertex","fire-js":"fire-js",[O]:"fire-js-all"},q=new Map,$=new Map,B=new Map;function U(e,t){try{e.container.addComponent(t)}catch(n){u.debug(`Component ${t.name} failed to register with FirebaseApp ${e.name}`,n)}}function j(e){const t=e.name;if(B.has(t))return u.debug(`There were multiple attempts to register component ${t}.`),!1;B.set(t,e);for(const t of q.values())U(t,e);for(const t of $.values())U(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 H{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 Q extends H{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,Y(c,l,"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 B.values())c.addComponent(e);const l=new H(n,i,c);return q.set(o,l),l}async function J(e){let t=!1;const n=e.name;q.has(n)?(t=!0,q.delete(n)):$.has(n)&&e.decRefCount()<=0&&($.delete(n),t=!0),t&&(await Promise.all(e.container.getProviders().map((e=>e.delete()))),e.isDeleted=!0)}function Y(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 u.warn(e.join(" "))}j(new r.Component(`${s}-version`,(()=>({library:s,version:t})),"VERSION"))}const X="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(X)}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(X,"readwrite"),r=n.objectStore(X);await r.put(t,ne(e)),await n.done}catch(e){if(e instanceof s.FirebaseError)u.warn(e.message);else{const t=K.create("idb-set",{originalErrorMessage:null==e?void 0:e.message});u.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){u.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 u.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(X),n=await t.objectStore(X).get(ne(e));return await t.done,n}catch(e){if(e instanceof s.FirebaseError)u.warn(e.message);else{const t=K.create("idb-get",{originalErrorMessage:null==e?void 0:e.message});u.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}j(new r.Component("platform-logger",(e=>new a(e)),"PRIVATE")),j(new r.Component("heartbeat",(e=>new re(e)),"PRIVATE")),Y(c,l,"node"),Y(c,l,"cjs2017"),Y("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=U,t._addOrOverwriteComponent=function(e,t){e.container.addOrOverwriteComponent(t)},t._apps=q,t._clearComponents=function(){B.clear()},t._components=B,t._getProvider=z,t._isFirebaseApp=G,t._isFirebaseServerApp=function(e){return void 0!==e.settings},t._registerComponent=j,t._removeServiceInstance=function(e,t,n=F){z(e,t).clearInstance(n)},t._serverApps=$,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=$.get(o);if(c)return c.incRefCount(t.releaseOnDeref),c;const l=new r.ComponentContainer(o);for(const e of B.values())l.addComponent(e);const u=new Q(n,t,o,l);return $.set(o,u),u},t.onLog=function(e,t){if(null!==e&&"function"!=typeof e)throw K.create("invalid-log-argument");i.setUserLogHandler(e,t)},t.registerVersion=Y,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 l="@firebase/firestore";class u{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}}u.UNAUTHENTICATED=new u(null),u.GOOGLE_CREDENTIALS=new u("google-credentials-uid"),u.FIRST_PARTY=new u("first-party-uid"),u.MOCK_USER=new u("mock-user");let d="11.0.2";const h=new s.Logger("@firebase/firestore");function f(){return h.logLevel}function p(e,...t){if(h.logLevel<=s.LogLevel.DEBUG){const n=t.map(v);h.debug(`Firestore (${d}): ${e}`,...n)}}function m(e,...t){if(h.logLevel<=s.LogLevel.ERROR){const n=t.map(v);h.error(`Firestore (${d}): ${e}`,...n)}}function g(e,...t){if(h.logLevel<=s.LogLevel.WARN){const n=t.map(v);h.warn(`Firestore (${d}): ${e}`,...n)}}function v(e){if("string"==typeof e)return e;try{return function(e){return JSON.stringify(e)}(e)}catch(t){return e}}function y(e="Unexpected state"){const t=`FIRESTORE (${d}) INTERNAL ASSERTION FAILED: `+e;throw m(t),new Error(t)}function w(e,t){e||y()}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 S{constructor(e,t){this.user=t,this.type="OAuth",this.headers=new Map,this.headers.set("Authorization",`Bearer ${e}`)}}class T{getToken(){return Promise.resolve(null)}invalidateToken(){}start(e,t){e.enqueueRetryable((()=>t(u.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=u.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=>{p("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):(p("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?(p("FirebaseAuthCredentialsProvider","getToken aborted due to token change."),this.getToken()):t?(w("string"==typeof t.accessToken),new S(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 u(e)}}class D{constructor(e,t,n){this.l=e,this.h=t,this.P=n,this.type="FirstParty",this.user=u.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(u.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&&p("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,p("FirebaseAppCheckTokenProvider",`Received ${n?"new":"existing"} token.`),n?t(e.token):Promise.resolve()};this.o=t=>{e.enqueueRetryable((()=>n(t)))};const r=e=>{p("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):p("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 P{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 O(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&&y(),void 0===n?n=e.length-t:n>e.length-t&&y(),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 $ extends q{construct(e,t,n){return new $(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 $(t)}static emptyPath(){return new $([])}}const B=/^[_a-zA-Z][_a-zA-Z0-9]*$/;class U extends q{construct(e,t,n){return new U(e,t,n)}static isValidIdentifier(e){return B.test(e)}canonicalString(){return this.toArray().map((e=>(e=e.replace(/\\/g,"\\\\").replace(/`/g,"\\`"),U.isValidIdentifier(e)||(e="`"+e+"`"),e))).join(".")}toString(){return this.canonicalString()}isKeyField(){return 1===this.length&&"__name__"===this.get(0)}static keyField(){return new U(["__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 U(t)}static emptyPath(){return new U([])}}class j{constructor(e){this.path=e}static fromPath(e){return new j($.fromString(e))}static fromName(e){return new j($.fromString(e).popFirst(5))}static empty(){return new j($.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===$.comparator(this.path,e.path)}toString(){return this.path.toString()}static comparator(e,t){return $.comparator(e.path,t.path)}static isDocumentKey(e){return e.length%2==0}static fromSegments(e){return new j(new $(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 H(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 Q{constructor(e,t){this.fieldPath=e,this.kind=t}}function W(e,t){const n=U.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 Y(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,j.empty(),t)}function X(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(),j.empty(),-1)}static max(){return new Z(V.max(),j.empty(),-1)}}function ee(e,t){let n=e.readTime.compareTo(t.readTime);return 0!==n?n:(n=j.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;p("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&&y(),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 le(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 le(e,t.error)):this.V.resolve()},this.transaction.onerror=t=>{const n=pe(t.target.error);this.V.reject(new le(e,n))}}get m(){return this.V.promise}abort(e){e&&this.V.reject(e),this.aborted||(p("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 de(t)}}class oe{static delete(e){return p("SimpleDb","Removing database:",e),he(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())&&m("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||(p("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 le(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 le(e,r))},r.onupgradeneeded=e=>{p("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((()=>{p("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(p("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 he(this.B.delete())}}class le extends I{constructor(e,t){super(_.UNAVAILABLE,`IndexedDB transaction '${e}' failed: ${t}`),this.name="IndexedDbTransactionError"}}function ue(e){return"IndexedDbTransactionError"===e.name}class de{constructor(e){this.store=e}put(e,t){let n;return void 0!==t?(p("SimpleDb","PUT",this.store.name,e,t),n=this.store.put(t,e)):(p("SimpleDb","PUT",this.store.name,"<auto-key>",e),n=this.store.put(e)),he(n)}add(e){return p("SimpleDb","ADD",this.store.name,e,e),he(this.store.add(e))}get(e){return he(this.store.get(e)).next((t=>(void 0===t&&(t=null),p("SimpleDb","GET",this.store.name,e,t),t)))}delete(e){return p("SimpleDb","DELETE",this.store.name,e),he(this.store.delete(e))}count(){return p("SimpleDb","COUNT",this.store.name),he(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){p("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=pe(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 he(e){return new ie(((t,n)=>{e.onsuccess=e=>{const n=e.target.result;t(n)},e.onerror=e=>{const t=pe(e.target.error);n(t)}}))}let fe=!1;function pe(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 me{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){p("IndexBackfiller",`Scheduled in ${e}ms`),this.task=this.asyncQueue.enqueueAfterDelay("index_backfill",e,(async()=>{this.task=null;try{p("IndexBackfiller",`Documents written: ${await this.Z.ee()}`)}catch(e){ue(e)?p("IndexBackfiller","Ignoring IndexedDB error during index backfill: ",e):await re(e)}await this.X(6e4)}))}}class ge{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 p("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=>(p("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=X(t);ee(r,n)>0&&(n=r)})),new Z(n.readTime,n.documentKey,Math.max(t.batchId,e.largestBatchId))}}class ve{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 ye(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 Se(e){const t=e.length;if(w(t>=2),2===t)return w(""===e.charAt(0)&&""===e.charAt(1)),$.emptyPath();const n=t-2,r=[];let i="";for(let s=0;s<t;){const t=e.indexOf("",s);switch((t<0||t>n)&&y(),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:y()}s=t+2}return new $(r)}ve.oe=-1;const Te=["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"],Pe=["targetId","path"],Me=["path","targetId"],Re=["collectionId","parent"],Oe=["indexId","uid"],Fe=["uid","sequenceNumber"],Ve=["indexId","uid","arrayValue","directionalValue","orderedDocumentKey","documentKey"],qe=["indexId","uid","orderedDocumentKey"],$e=["userId","collectionPath","documentId"],Be=["userId","collectionPath","largestBatchId"],Ue=["userId","collectionGroup","largestBatchId"],je=["mutationQueues","mutations","documentMutations","remoteDocuments","targets","owner","targetGlobal","targetDocuments","clientMetadata","remoteDocumentGlobal","collectionParents","bundles","namedQueries"],ze=[...je,"documentOverlays"],Ge=["mutationQueues","mutations","documentMutations","remoteDocumentsV14","targets","owner","targetGlobal","targetDocuments","clientMetadata","remoteDocumentGlobal","collectionParents","bundles","namedQueries","documentOverlays"],Ke=Ge,He=[...Ke,"indexConfiguration","indexState","indexEntries"],Qe=He,We=[...He,"globals"];class Je extends ne{constructor(e,t){super(),this._e=e,this.currentSequenceNumber=t}}function Ye(e,t){const n=b(e);return oe.C(n._e,t)}function Xe(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 y();if(this.right.isRed())throw y();const e=this.left.check();if(e!==this.right.check())throw y();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 y()}get value(){throw y()}get color(){throw y()}get left(){throw y()}get right(){throw y()}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(U.comparator)}static empty(){return new ct([])}unionWith(e){let t=new st(U.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 lt extends Error{constructor(){super(...arguments),this.name="Base64DecodeError"}}class ut{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 lt("Invalid base64 string: "+e):e}}(e);return new ut(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 ut(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}}ut.EMPTY_BYTE_STRING=new ut("");const dt=new RegExp(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.(\d+))?Z$/);function ht(e){if(w(!!e),"string"==typeof e){let t=0;const n=dt.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 pt(e){return"string"==typeof e?ut.fromBase64String(e):ut.fromUint8Array(e)}function mt(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 gt(e){const t=e.mapValue.fields.__previous_value__;return mt(t)?gt(t):t}function vt(e){const t=ht(e.mapValue.fields.__local_write_time__.timestampValue);return new F(t.seconds,t.nanos)}class yt{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?mt(e)?4:qt(e)?9007199254740991:Ft(e)?10:11:y()}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 vt(e).isEqual(vt(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=ht(e.timestampValue),r=ht(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 pt(e.bytesValue).isEqual(pt(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(Xe(n)!==Xe(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 y()}}function St(e,t){return void 0!==(e.values||[]).find((e=>Et(e,t)))}function Tt(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(vt(e),vt(t));case 5:return M(e.stringValue,t.stringValue);case 6:return function(e,t){const n=pt(e),r=pt(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,l=null===(r=a.value)||void 0===r?void 0:r.arrayValue,u=M((null===(i=null==c?void 0:c.values)||void 0===i?void 0:i.length)||0,(null===(s=null==l?void 0:l.values)||void 0===s?void 0:s.length)||0);return 0!==u?u:Ct(c,l)}(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=Tt(n[r[e]],i[s[e]]);if(0!==o)return o}return M(r.length,s.length)}(e.mapValue,t.mapValue);default:throw y()}}function xt(e,t){if("string"==typeof e&&"string"==typeof t&&e.length===t.length)return M(e,t);const n=ht(e),r=ht(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=Tt(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=ht(e);return`time(${t.seconds},${t.nanos})`}(e.timestampValue):"stringValue"in e?e.stringValue:"bytesValue"in e?function(e){return pt(e).toBase64()}(e.bytesValue):"referenceValue"in e?function(e){return j.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):y()}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=gt(e);return t?16+kt(t):16;case 5:return 2*e.stringValue.length;case 6:return pt(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 y()}}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 Pt(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 Ot(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 $t={mapValue:{fields:{__type__:{stringValue:"__vector__"},value:{arrayValue:{}}}}};function Bt(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(),j.empty()):"geoPointValue"in e?{geoPointValue:{latitude:-90,longitude:-180}}:"arrayValue"in e?{arrayValue:{}}:"mapValue"in e?Ft(e)?$t:{mapValue:{}}:y()}function Ut(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(),j.empty()):"referenceValue"in e?{geoPointValue:{latitude:-90,longitude:-180}}:"geoPointValue"in e?{arrayValue:{}}:"arrayValue"in e?$t:"mapValue"in e?Ft(e)?{mapValue:{}}:bt:y()}function jt(e,t){const n=Tt(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=Tt(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)],!Ot(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=U.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());Ot(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)];Ot(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 U([e]);if(Ot(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 Ht{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 Ht(e,0,V.min(),V.min(),V.min(),Gt.empty(),0)}static newFoundDocument(e,t,n,r){return new Ht(e,1,t,V.min(),n,r,0)}static newNoDocument(e,t){return new Ht(e,2,t,V.min(),V.min(),Gt.empty(),0)}static newUnknownDocument(e,t){return new Ht(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 Ht&&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 Ht(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 Qt{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()?j.comparator(j.fromName(o.referenceValue),n.key):Tt(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 Yt{constructor(e,t="asc"){this.field=e,this.dir=t}}function Xt(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 dn(e,t,n):"array-contains"===t?new mn(e,n):"in"===t?new gn(e,n):"not-in"===t?new vn(e,n):"array-contains-any"===t?new yn(e,n):new en(e,t,n)}static createKeyFieldInFilter(e,t,n){return"in"===t?new hn(e,n):new fn(e,n)}matches(e){const t=e.data.field(this.field);return"!="===this.op?null!==t&&this.matchesComparison(Tt(t,this.value)):null!==t&&It(this.value)===It(t)&&this.matchesComparison(Tt(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 y()}}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 y()}function ln(e,t){const n=e.filters.concat(t);return tn.create(n,e.op)}function un(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(un).join(" ,")+"}"}(e):"Filter"}class dn extends en{constructor(e,t,n){super(e,t,n),this.key=j.fromName(n.referenceValue)}matches(e){const t=j.comparator(e.key,this.key);return this.matchesComparison(t)}}class hn extends en{constructor(e,t){super(e,"in",t),this.keys=pn(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=pn(0,t)}matches(e){return!this.keys.some((t=>t.isEqual(e.key)))}}function pn(e,t){var n;return((null===(n=t.arrayValue)||void 0===n?void 0:n.values)||[]).map((e=>j.fromName(e.referenceValue)))}class mn extends en{constructor(e,t){super(e,"array-contains",t)}matches(e){const t=e.data.field(this.field);return Pt(t)&&St(t.arrayValue,this.value)}}class gn extends en{constructor(e,t){super(e,"in",t)}matches(e){const t=e.data.field(this.field);return null!==t&&St(this.value.arrayValue,t)}}class vn extends en{constructor(e,t){super(e,"not-in",t)}matches(e){if(St(this.value.arrayValue,{nullValue:"NULL_VALUE"}))return!1;const t=e.data.field(this.field);return null!==t&&!St(this.value.arrayValue,t)}}class yn extends en{constructor(e,t){super(e,"array-contains-any",t)}matches(e){const t=e.data.field(this.field);return!(!Pt(t)||!t.arrayValue.values)&&t.arrayValue.values.some((e=>St(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(","),ye(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(!Xt(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 j.isDocumentKey(e.path)&&null===e.collectionGroup&&0===e.filters.length}function Sn(e,t){return e.filters.filter((e=>e instanceof en&&e.field.isEqual(t)))}function Tn(e,t,n){let r=_t,i=!0;for(const n of Sn(e,t)){let e=_t,t=!0;switch(n.op){case"<":case"<=":e=Bt(n.value);break;case"==":case"in":case">=":e=n.value;break;case">":e=n.value,t=!1;break;case"!=":case"not-in":e=_t}jt({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];jt({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 Sn(e,t)){let e=bt,t=!0;switch(n.op){case">=":case">":e=Ut(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(U.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 Yt(r,n))})),e.has(U.keyField().canonicalString())||t.ce.push(new Yt(U.keyField(),n))}return t.ce}function Pn(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 Yt(e.field,t)}));const n=e.endAt?new Qt(e.endAt.position,e.endAt.inclusive):null,r=e.startAt?new Qt(e.startAt.position,e.startAt.inclusive):null;return bn(e.path,e.collectionGroup,t,e.filters,e.limit,n,r)}}function On(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(Pn(e),Pn(t))&&e.limitType===t.limitType}function qn(e){return`${_n(Pn(e))}|lt:${e.limitType}`}function $n(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=>un(e))).join(", ")}]`),ye(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})`}(Pn(e))}; limitType=${e.limitType})`}function Bn(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):j.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 Un(e){return e.collectionGroup||(e.path.length%2==1?e.path.lastSegment():e.path.get(e.path.length-2))}function jn(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()?j.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?Tt(r,i):y()}(e.field,t,n);switch(e.dir){case"asc":return r;case"desc":return-1*r;default:return y()}}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(j.comparator);function Hn(){return Kn}const Qn=new nt(j.comparator);function Wn(...e){let t=Qn;for(const n of e)t=t.insert(n.key,n);return t}function Jn(e){let t=Qn;return e.forEach(((e,n)=>t=t.insert(e,n.overlayedDocument))),t}function Yn(){return Zn()}function Xn(){return Zn()}function Zn(){return new Gn((e=>e.toString()),((e,t)=>e.isEqual(t)))}const er=new nt(j.comparator),tr=new st(j.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 lr(e,t,n){return e instanceof hr?function(e,t){const n={fields:{__type__:{stringValue:"server_timestamp"},__local_write_time__:{timestampValue:{seconds:e.seconds,nanos:e.nanoseconds}}}};return t&&mt(t)&&(t=gt(t)),t&&(n.fields.__previous_value__=t),{mapValue:n}}(n,t):e instanceof fr?pr(e,t):e instanceof mr?gr(e,t):function(e,t){const n=dr(e,t),r=yr(n)+yr(e.Pe);return Lt(n)&&Lt(e.Pe)?or(r):sr(e.serializer,r)}(e,t)}function ur(e,t,n){return e instanceof fr?pr(e,t):e instanceof mr?gr(e,t):n}function dr(e,t){return e instanceof vr?function(e){return Lt(e)||function(e){return!!e&&"doubleValue"in e}(e)}(t)?t:{integerValue:0}:null}class hr extends cr{}class fr extends cr{constructor(e){super(),this.elements=e}}function pr(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 mr extends cr{constructor(e){super(),this.elements=e}}function gr(e,t){let n=wr(t);for(const t of e.elements)n=n.filter((e=>!Et(e,t)));return{arrayValue:{values:n}}}class vr extends cr{constructor(e,t){super(),this.serializer=e,this.Pe=t}}function yr(e){return ft(e.integerValue||e.doubleValue)}function wr(e){return Pt(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 Sr{}function Tr(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(U.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=Pr(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=Pr(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=dr(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 mr&&t instanceof mr?R(e.elements,t.elements,Et):e instanceof vr&&t instanceof vr?Et(e.Pe,t.Pe):e instanceof hr&&t instanceof hr}(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 Sr{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 Sr{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 Pr(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,ur(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,lr(e,s,t))}return r}class Rr extends Sr{constructor(e,t){super(),this.key=e,this.precondition=t,this.type=2,this.fieldTransforms=[]}getFieldMask(){return null}}class Or extends Sr{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=Xn();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=Tr(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 $r{constructor(e,t,n){this.alias=e,this.aggregateType=t,this.fieldPath=n}}class Br{constructor(e,t){this.count=e,this.unchangedNames=t}}var Ur,jr;function zr(e){switch(e){default:return y();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 m("GRPC error has no .code"),_.UNKNOWN;switch(e){case Ur.OK:return _.OK;case Ur.CANCELLED:return _.CANCELLED;case Ur.UNKNOWN:return _.UNKNOWN;case Ur.DEADLINE_EXCEEDED:return _.DEADLINE_EXCEEDED;case Ur.RESOURCE_EXHAUSTED:return _.RESOURCE_EXHAUSTED;case Ur.INTERNAL:return _.INTERNAL;case Ur.UNAVAILABLE:return _.UNAVAILABLE;case Ur.UNAUTHENTICATED:return _.UNAUTHENTICATED;case Ur.INVALID_ARGUMENT:return _.INVALID_ARGUMENT;case Ur.NOT_FOUND:return _.NOT_FOUND;case Ur.ALREADY_EXISTS:return _.ALREADY_EXISTS;case Ur.PERMISSION_DENIED:return _.PERMISSION_DENIED;case Ur.FAILED_PRECONDITION:return _.FAILED_PRECONDITION;case Ur.ABORTED:return _.ABORTED;case Ur.OUT_OF_RANGE:return _.OUT_OF_RANGE;case Ur.UNIMPLEMENTED:return _.UNIMPLEMENTED;case Ur.DATA_LOSS:return _.DATA_LOSS;default:return y()}}(jr=Ur||(Ur={}))[jr.OK=0]="OK",jr[jr.CANCELLED=1]="CANCELLED",jr[jr.UNKNOWN=2]="UNKNOWN",jr[jr.INVALID_ARGUMENT=3]="INVALID_ARGUMENT",jr[jr.DEADLINE_EXCEEDED=4]="DEADLINE_EXCEEDED",jr[jr.NOT_FOUND=5]="NOT_FOUND",jr[jr.ALREADY_EXISTS=6]="ALREADY_EXISTS",jr[jr.PERMISSION_DENIED=7]="PERMISSION_DENIED",jr[jr.UNAUTHENTICATED=16]="UNAUTHENTICATED",jr[jr.RESOURCE_EXHAUSTED=8]="RESOURCE_EXHAUSTED",jr[jr.FAILED_PRECONDITION=9]="FAILED_PRECONDITION",jr[jr.ABORTED=10]="ABORTED",jr[jr.OUT_OF_RANGE=11]="OUT_OF_RANGE",jr[jr.UNIMPLEMENTED=12]="UNIMPLEMENTED",jr[jr.INTERNAL=13]="INTERNAL",jr[jr.UNAVAILABLE=14]="UNAVAILABLE",jr[jr.DATA_LOSS=15]="DATA_LOSS";let Kr=null;function Hr(){return new TextEncoder}const Qr=new a.Integer([4294967295,4294967295],0);function Wr(e){const t=Hr().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 Yr{constructor(e,t,n){if(this.bitmap=e,this.padding=t,this.hashCount=n,t<0||t>=8)throw new Xr(`Invalid padding: ${t}`);if(n<0)throw new Xr(`Invalid hash count: ${n}`);if(e.length>0&&0===this.hashCount)throw new Xr(`Invalid hash count: ${n}`);if(0===e.length&&0!==t)throw new Xr(`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(Qr)&&(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 Yr(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 Xr 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),Hn(),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=ut.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=ut.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:y()}})),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=Hn(),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:y()}}))}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 j(i.path);this.We(t,e,Ht.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,l,u;const d={localCacheCount:e,existenceFilterCount:t.count,databaseId:n.database,projectId:n.projectId},h=t.unchangedNames;return h&&(d.bloomFilter={applied:0===i,hashCount:null!==(s=null==h?void 0:h.hashCount)&&void 0!==s?s:0,bitmapLength:null!==(c=null===(a=null===(o=null==h?void 0:h.bits)||void 0===o?void 0:o.bitmap)||void 0===a?void 0:a.length)&&void 0!==c?c:0,padding:null!==(u=null===(l=null==h?void 0:h.bits)||void 0===l?void 0:l.padding)&&void 0!==u?u:0,mightContain:e=>{var t;return null!==(t=null==r?void 0:r.mightContain(e))&&void 0!==t&&t}}),d}(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=pt(n).toUint8Array()}catch(e){if(e instanceof lt)return g("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 Yr(s,r,i)}catch(e){return g(e instanceof Xr?"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 j(i.target.path);this.st(t).has(r)||this.ot(r,t)||this.We(r,t,Ht.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=Hn(),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||p("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(j.comparator)}function ai(){return new nt(j.comparator)}const ci={asc:"ASCENDING",desc:"DESCENDING"},li={"<":"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"},ui={and:"AND",or:"OR"};class di{constructor(e,t){this.databaseId=e,this.useProto3Json=t}}function hi(e,t){return e.useProto3Json||ye(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 pi(e,t){return e.useProto3Json?t.toBase64():t.toUint8Array()}function mi(e,t){return fi(e,t.toTimestamp())}function gi(e){return w(!!e),V.fromTimestamp(function(e){const t=ht(e);return new F(t.seconds,t.nanos)}(e))}function vi(e,t){return yi(e,t).canonicalString()}function yi(e,t){const n=function(e){return new $(["projects",e.projectId,"databases",e.database])}(e).child("documents");return void 0===t?n:n.child(t)}function wi(e){const t=$.fromString(e);return w(Ui(t)),t}function bi(e,t){return vi(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 j(Ti(n))}function Ii(e,t){return vi(e.databaseId,t)}function Ei(e){const t=wi(e);return 4===t.length?$.emptyPath():Ti(t)}function Si(e){return new $(["projects",e.databaseId.projectId,"databases",e.databaseId.database]).canonicalString()}function Ti(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=gi(t.updateTime),s=t.createTime?gi(t.createTime):V.min(),o=new Gt({mapValue:{fields:t.fields}}),a=Ht.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:Bi(t.fieldMask)};else{if(!(t instanceof Or))return y();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 hr)return{fieldPath:t.field.canonicalString(),setToServerValue:"REQUEST_TIME"};if(n instanceof fr)return{fieldPath:t.field.canonicalString(),appendMissingElements:{values:n.elements}};if(n instanceof mr)return{fieldPath:t.field.canonicalString(),removeAllFromArray:{values:n.elements}};if(n instanceof vr)return{fieldPath:t.field.canonicalString(),increment:n.Pe};throw y()}(0,e)))),t.precondition.isNone||(n.currentDocument=function(e,t){return void 0!==t.updateTime?{updateTime:mi(e,t.updateTime)}:void 0!==t.exists?{exists:t.exists}:y()}(e,t.precondition)),n}function Ai(e,t){const n=t.currentDocument?function(e){return void 0!==e.updateTime?Ir.updateTime(gi(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 hr;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 mr(e)}else"increment"in t?n=new vr(e,t.increment):y();const r=U.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=>U.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 Or(r,n)}return y()}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 $i(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=hi(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 Pi(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 Yt(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,ye(t)?null:t}(n.limit));let c=null;n.startAt&&(c=function(e){const t=!!e.before,n=e.values||[];return new Qt(n,t)}(n.startAt));let l=null;return n.endAt&&(l=function(e){const t=!e.before,n=e.values||[];return new Qt(n,t)}(n.endAt)),Dn(t,i,o,s,a,"F",c,l)}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 y()}}(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 y()}}(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 y()}}(e.compositeFilter.op))}(e):y()}function Ri(e){return ci[e]}function Oi(e){return li[e]}function Fi(e){return ui[e]}function Vi(e){return{fieldPath:e.canonicalString()}}function qi(e){return U.fromServerFormat(e.fieldPath)}function $i(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:Oi(e.op),value:e.value}}}(e):e instanceof tn?function(e){const t=e.getFilters().map((e=>$i(e)));return 1===t.length?t[0]:{compositeFilter:{op:Fi(e.op),filters:t}}}(e):y()}function Bi(e){const t=[];return e.fields.forEach((e=>t.push(e.canonicalString()))),{fieldPaths:t}}function Ui(e){return e.length>=4&&"projects"===e.get(0)&&"databases"===e.get(2)}class ji{constructor(e,t,n,r,i=V.min(),s=V.min(),o=ut.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 ji(this.target,this.targetId,this.purpose,e,this.snapshotVersion,this.lastLimboFreeSnapshotVersion,this.resumeToken,this.expectedCount)}withResumeToken(e,t){return new ji(this.target,this.targetId,this.purpose,this.sequenceNumber,t,this.lastLimboFreeSnapshotVersion,e,null)}withExpectedCount(e){return new ji(this.target,this.targetId,this.purpose,this.sequenceNumber,this.snapshotVersion,this.lastLimboFreeSnapshotVersion,this.resumeToken,e)}withLastLimboFreeSnapshotVersion(e){return new ji(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:Hi(t.version)};else{if(!t.isUnknownDocument())return y();r.unknownDocument={path:n.path.toArray(),version:Hi(t.version)}}return r}function Ki(e){const t=e.toTimestamp();return[t.seconds,t.nanoseconds]}function Hi(e){const t=e.toTimestamp();return{seconds:t.seconds,nanoseconds:t.nanoseconds}}function Qi(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=Qi(e.readTime),n=void 0!==e.lastLimboFreeSnapshotVersion?Qi(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),Pn(An(Ei(e.documents[0])))}(e.query):function(e){return Pn(Pi(e))}(e.query),new ji(r,e.targetId,"TargetPurposeListen",e.lastListenSequenceNumber,t,n,ut.fromBase64String(e.resumeToken))}function Yi(e,t){const n=Hi(t.snapshotVersion),r=Hi(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 Xi(e){const t=Pi({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:Hi(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:Qi(e.createTime),version:e.version}}(e)}))}saveBundleMetadata(e,t){return rs(e).put(function(e){return{bundleId:e.id,createTime:Hi(gi(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:Xi(e.bundledQuery),readTime:Qi(e.readTime)}}(e)}))}saveNamedQuery(e,t){return is(e).put(function(e){return{name:e.name,readTime:Hi(gi(e.readTime)),bundledQuery:e.bundledQuery}}(t))}}function rs(e){return Ye(e,"bundles")}function is(e){return Ye(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=Yn();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=Yn(),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=Yn();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 Ye(e,"documentOverlays")}class as{It(e){return Ye(e,"globals")}getSessionToken(e){return this.It(e).get("sessionToken").next((e=>{const t=null==e?void 0:e.value;return t?ut.fromUint8Array(t):ut.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=ht(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(pt(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)):y()}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),j.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 ls(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 us(e){const t=64-function(e){let t=0;for(let n=0;n<8;++n){const r=ls(255&e[n]);if(t+=r,8!==r)break}return t}(e);return Math.ceil(t/8)}cs.Ft=new cs;class ds{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=us(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=us(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 hs{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 ps{constructor(){this.Jt=new ds,this.Yt=new hs(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 ms{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 ms(this.indexId,this.documentKey,this.arrayValue,n)}}function gs(e,t){let n=e.indexId-t.indexId;return 0!==n?n:(n=vs(e.arrayValue,t.arrayValue),0!==n?n:(n=vs(e.directionalValue,t.directionalValue),0!==n?n:j.comparator(e.documentKey,t.documentKey)))}function vs(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 ys{constructor(e){this.tn=new st(((e,t)=>U.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(U.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 Q(n.field,2));else{if(e.has(n.field))continue;e=e.add(n.field),t.push(new Q(n.field,0))}for(const n of this.nn)n.field.isKeyField()||e.has(n.field)||(e=e.add(n.field),t.push(new Q(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 gn){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=Ss(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 Ss(e){if(w(e instanceof en||e instanceof tn),e instanceof en)return e;if(1===e.filters.length)return Ss(e.filters[0]);const t=e.filters.map((e=>Ss(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)=>Ts(e,t))))}function Ts(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 ln(e,t.getFilters());const n=rn(e)?e:t,r=rn(e)?t:e,i=n.filters.map((e=>Ts(e,r)));return tn.create(i,"or")}(e,t),Cs(n)}function xs(e,t){if(nn(t))return ln(t,e.getFilters());{const n=t.filters.map((t=>Ts(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($.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($.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,""],[O(t),""],!1,!0);return Ls(e).U(r).next((e=>{for(const r of e){if(r.collectionId!==t)break;n.push(Se(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=Ps(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=Ps(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 ys(t).cn();if(null!=n)return this.addFieldIndex(e,n)}}))))}getDocumentsMatchingTarget(e,t){const n=Ps(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)=>{p("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 Sn(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 Sn(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?Tn(e,i.fieldPath,e.startAt):xn(e,i.fieldPath,e.startAt);n.push(t.value),r&&(r=t.inclusive)}return new Qt(n,r)}(s,i),l=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):Tn(e,i.fieldPath,e.endAt);n.push(t.value),r&&(r=t.inclusive)}return new Qt(n,r)}(s,i),u=this.En(i,s,c),d=this.En(i,s,l),h=this.dn(i,s,a),f=this.An(i.indexId,o,u,c.inclusive,d,l.inclusive,h);return ie.forEach(f,(i=>n.G(i,t.limit).next((t=>{t.forEach((t=>{const n=j.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),l=[];for(let u=0;u<a;++u){const a=t?this.Rn(t[u/c]):ks,d=this.Vn(e,a,n[u%c],r),h=this.mn(e,a,i[u%c],s),f=o.map((t=>this.Vn(e,a,t,!0)));l.push(...this.createRange(d,h,f))}return l}Vn(e,t,n,r){const i=new ms(e,j.empty(),t,n);return r?i:i.en()}mn(e,t,n,r){const i=new ms(e,j.empty(),t,n);return r?i.en():i}In(e,t){const n=new ys(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(U.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 ps;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 ps;return cs.Ft.Et(e,t.Xt(0)),t.Ht()}gn(e,t){const n=new ps;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 ps);let i=0;for(const s of K(e)){const e=n[i++];for(const n of r)if(this.pn(t,s.fieldPath)&&Pt(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 ps;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(Qi(t.readTime),new j(Se(t.documentKey)),t.largestBatchId)):J.empty(),r=e.fields.map((([e,t])=>new Q(U.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 Ps(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 Ps(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=Ps(e);let i=new st(gs);return r.J({index:"documentKeyIndex",range:IDBKeyRange.only([n.indexId,this.uid,this.gn(n,t)])},((e,r)=>{i=i.add(new ms(n.indexId,t,r.arrayValue,r.directionalValue))})).next((()=>i))}Dn(e,t){let n=new st(gs);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(Pt(s))for(const i of s.arrayValue.values||[])n=n.add(new ms(t.indexId,e.key,this.Rn(i),r))}else n=n.add(new ms(t.indexId,e.key,ks,r));return n}vn(e,t,n,r,i){p("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,gs,(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)=>gs(e,t))).filter(((e,t,n)=>!t||0!==gs(e,n[t-1])));const r=[];r.push(e);for(const i of n){const n=gs(i,e),s=gs(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 gs(e,t)>0}getMinOffsetFromCollectionGroup(e,t){return this.getFieldIndexes(e,t).next(Os)}getMinOffset(e,t){return ie.mapArray(this.Tn(t),(t=>this.In(e,t).next((e=>e||y())))).next(Os)}}function Ls(e){return Ye(e,"collectionParents")}function Ps(e){return Ye(e,"indexEntries")}function Ms(e){return Ye(e,"indexConfiguration")}function Rs(e){return Ye(e,"indexState")}function Os(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 l=[];for(const e of n.mutations){const r=Ce(t,e.key.path,n.batchId);s.push(i.delete(r)),l.push(e.key)}return ie.waitFor(s).next((()=>l))}function $s(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 y();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 Bs{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 Bs(i,t,n,r)}checkEmpty(e){let t=!0;const n=IDBKeyRange.bound([this.userId,Number.NEGATIVE_INFINITY],[this.userId,Number.POSITIVE_INFINITY]);return js(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=js(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),l=[];let u=new st(((e,t)=>M(e.canonicalString(),t.canonicalString())));for(const e of r){const t=Ce(this.userId,e.key.path,o);u=u.add(e.key.path.popLast()),l.push(s.put(c)),l.push(i.put(t,De))}return u.forEach((t=>{l.push(this.indexManager.addToCollectionParentIndex(e,t))})),e.addOnCommittedListener((()=>{this.xn[o]=a.keys()})),ie.waitFor(l).next((()=>a))}))}lookupMutationBatch(e,t){return js(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 js(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 js(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 js(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,l=Se(a);if(o===this.userId&&t.path.isEqual(l))return js(e).get(c).next((e=>{if(!e)throw y();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=Se(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,l=Se(a);s===this.userId&&n.isPrefixOf(l)?l.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(js(e).get(t).next((e=>{if(null===e)throw y();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=Se(e[1]);r.push(t)}else n.done()})).next((()=>{w(0===r.length)}))}))}containsKey(e,t){return Us(e,this.userId,t)}Bn(e){return Gs(e).get(this.userId).next((e=>e||{userId:this.userId,lastAcknowledgedBatchId:-1,lastStreamToken:""}))}}function Us(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 js(e){return Ye(e,"mutations")}function zs(e){return Ye(e,"documentMutations")}function Gs(e){return Ye(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 Hs{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((()=>Qs(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 Qs(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 Qs(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 Qs(e).put(Yi(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 Qs(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=Se(e[1]),s=new j(r);i=i.add(s)})).next((()=>i))}containsKey(e,t){const n=_e(t.path),r=IDBKeyRange.bound([n],[O(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 Qs(e).get(t).next((e=>e?Ji(e):null))}}function Qs(e){return Ye(e,"targets")}function Ws(e){return Ye(e,"targetGlobal")}function Js(e){return Ye(e,"targetDocuments")}function Ys([e,t],[n,r]){const i=M(e,n);return 0===i?M(t,r):i}class Xs{constructor(e){this.Gn=e,this.buffer=new st(Ys),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();Ys(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){p("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){ue(e)?p("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(ve.oe);const n=new Xs(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?(p("LruGarbageCollector","Garbage collection skipped; disabled"),ie.resolve(Fs)):this.getCacheSize(e).next((n=>n<this.params.cacheSizeCollectionThreshold?(p("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,l;const u=Date.now();return this.calculateTargetCount(e,this.params.percentileToCollect).next((t=>(t>this.params.maximumSequenceNumbersToCollect?(p("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=>(l=Date.now(),f()<=s.LogLevel.DEBUG&&p("LruGarbageCollector",`LRU Garbage Collection\n\tCounted targets in ${o-u}ms\n\tDetermined least recently used ${r} in `+(a-o)+"ms\n"+`\tRemoved ${i} targets in `+(c-a)+"ms\n"+`\tRemoved ${e} documents in `+(l-c)+"ms\n"+`Total Duration: ${l-u}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=>Us(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=ve.oe;return n.J({index:"documentTargetsIndex"},(([e,n],{path:s,sequenceNumber:o})=>{0===e?(i!==ve.oe&&t(new j(Se(r)),i),i=o,r=s):i=ve.oe})).next((()=>{i!==ve.oe&&t(new j(Se(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,Ht.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 lo(e).put(n)}removeEntry(e,t,n){return lo(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=Ht.newInvalidDocument(t);return lo(e).J({index:"documentKeyIndex",range:IDBKeyRange.only(uo(t))},((e,r)=>{n=this._r(t,r)})).next((()=>n))}ar(e,t){let n={size:0,document:Ht.newInvalidDocument(t)};return lo(e).J({index:"documentKeyIndex",range:IDBKeyRange.only(uo(t))},((e,r)=>{n={document:this._r(t,r),size:$s(r)}})).next((()=>n))}getEntries(e,t){let n=Hn();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=Hn(),r=new nt(j.comparator);return this.ur(e,t,((e,t)=>{const i=this._r(e,t);n=n.insert(e,i),r=r.insert(e,$s(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(uo(r.first()),uo(r.last())),s=r.getIterator();let o=s.getNext();return lo(e).J({index:"documentKeyIndex",range:i},((e,t,r)=>{const i=j.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.$(uo(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 lo(e).U(IDBKeyRange.bound(o,a,!0)).next((e=>{null==i||i.incrementDocumentReadCount(e.length);let n=Hn();for(const i of e){const e=this._r(j.fromSegments(i.prefixPath.concat(i.collectionGroup,i.documentId)),i);e.isFoundDocument()&&(Bn(t,e)||r.has(e.key))&&(n=n.insert(e.key,e))}return n}))}getAllFromCollectionGroup(e,t,n,r){let i=Hn();const s=ho(t,n),o=ho(t,Z.max());return lo(e).J({index:"collectionGroupIndex",range:IDBKeyRange.bound(s,o,!0)},((e,t,n)=>{const s=this._r(j.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=j.fromSegments(t.noDocument.path),r=Qi(t.noDocument.readTime);n=Ht.newNoDocument(e,r),t.hasCommittedMutations&&n.setHasCommittedMutations()}else{if(!t.unknownDocument)return y();{const e=j.fromSegments(t.unknownDocument.path),r=Qi(t.unknownDocument.version);n=Ht.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 Ht.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=$s(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 Ye(e,"remoteDocumentGlobal")}function lo(e){return Ye(e,"remoteDocumentsV14")}function uo(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 po{constructor(e,t){this.overlayedDocument=e,this.mutatedFields=t}}class mo{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=Yn();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=Yn();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=Hn();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 po(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,l=Xn();c.forEach((e=>{if(!i.has(e)){const r=Tr(t.get(e),n.get(e));null!==r&&l.set(e,r),i=i.add(e)}})),s.push(this.documentOverlayCache.saveOverlays(e,a,l))}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 j.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(Yn());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 j(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,Ht.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()),Bn(t,r)&&(n=n.insert(e,r))})),n}))}}class go{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:gi(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:Xi(e.bundledQuery),readTime:gi(e.readTime)}}(t)),ie.resolve()}}class vo{constructor(){this.overlays=new nt(j.comparator),this.Er=new Map}getOverlay(e,t){return ie.resolve(this.overlays.get(t))}getOverlays(e,t){const n=Yn();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=Yn(),i=t.length+1,s=new j(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=Yn(),i=i.insert(e.largestBatchId,t)),t.set(e.getKey(),e)}}const o=Yn(),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 yo{constructor(){this.sessionToken=ut.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 j(new $([])),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 j(new $([])),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 j.comparator(e.key,t.key)||M(e.br,t.br)}static Vr(e,t){return M(e.br,t.br)||j.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;j.isDocumentKey(i)||(i=i.child(""));const s=new bo(new j(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(j.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():Ht.newInvalidDocument(t))}getEntries(e,t){let n=Hn();return t.forEach((e=>{const t=this.docs.get(e);n=n.insert(e,t?t.document.mutableCopy():Ht.newInvalidDocument(e))})),ie.resolve(n)}getDocumentsMatchingQuery(e,t,n,r){let i=Hn();const s=t.path,o=new j(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(X(o),n)<=0||(r.has(o.key)||Bn(t,o))&&(i=i.insert(o.key,o.mutableCopy()))}return ie.resolve(i)}getAllFromCollectionGroup(e,t,n,r){y()}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 So{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 To{constructor(e,t){this.Kr={},this.overlays={},this.$r=new ve(0),this.Ur=!1,this.Ur=!0,this.Wr=new yo,this.referenceDelegate=e(this),this.Gr=new So(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 go(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 vo,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){p("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 y()}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=j.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",Te,{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",Te,{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:$e});t.createIndex("collectionPathOverlayIndex",Be,{unique:!1}),t.createIndex("collectionGroupOverlayIndex",Ue,{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:Oe}).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+=$s(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 $(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 $(e);return i(n.popLast())})).next((()=>t.store("documentMutations").J({H:!0},(([e,t,n],r)=>{const s=Se(t);return i(s.popLast())}))))}ai(e){const t=e.store("targets");return t.J(((e,n)=>{const r=Ji(n),i=Yi(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 j($.fromString(e.document.name).popFirst(5)):e.noDocument?j.fromSegments(e.noDocument.path):e.unknownDocument?j.fromSegments(e.unknownDocument.path):y()}(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 To(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 u(n),o=ss.Pt(this.serializer,s),a=i.getIndexManager(s),c=Bs.Pt(s,this.serializer,a,i.referenceDelegate);return new mo(r,c,o,a).recalculateAndSaveOverlaysForDocumentKeys(new Je(t,ve.oe),e).next()}))}))}}function ko(e){e.createObjectStore("targetDocuments",{keyPath:Pe}).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,l,u=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=l,this.Ti=u,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 Hs(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===l&&m("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 ve(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(ue(e))return p("IndexedDbPersistence","Failed to extend owner lease: ",e),this.isPrimary;if(!this.allowTabSynchronization)throw e;return p("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 Po(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=Ye(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):Po(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&&p("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,ve.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 Bs.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){p("IndexedDbPersistence","Starting transaction:",e);const r="readonly"===t?"readonly":"readwrite",i=function(e){return 17===e?We:16===e?Qe:15===e?He:14===e?Ke:13===e?Ge:12===e?ze:11===e?je:void y()}(this.Ti);let s;return this.mi.runTransaction(e,r,i,(r=>(s=new Je(r,this.$r?this.$r.next():ve.oe),"readwrite-primary"===t?this.bi(s).next((e=>!!e||this.Di(s))).next((t=>{if(!t)throw m(`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 Po(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 Po(e).put("owner",t)}static p(){return oe.p()}vi(e){const t=Po(e);return t.get("owner").next((e=>this.Fi(e)?(p("IndexedDbPersistence","Releasing primary lease."),t.delete("owner")):ie.resolve()))}Oi(e,t){const n=Date.now();return!(e<n-t||e>n&&(m(`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 p("IndexedDbPersistence",`Client '${e}' ${n?"is":"is not"} zombied in LocalStorage`),n}catch(e){return m("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){m("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 Po(e){return Ye(e,"owner")}function Mo(e){return Ye(e,"clientMetadata")}function Ro(e,t){let n=e.projectId;return e.isDefaultDatabase||(n+="."+e.database),"firestore/"+t+"/"+n+"/"}class Oo{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 Oo(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&&p("QueryEngine","SDK will not create cache indexes for query:",$n(t),"since it only creates cache indexes for collection contains","more than or equal to",this.Ji,"documents"),ie.resolve()):(f()<=s.LogLevel.DEBUG&&p("QueryEngine","Query:",$n(t),"scans",n.documentReadCount,"local documents and returns",r,"documents as results."),n.documentReadCount>this.Yi*r?(f()<=s.LogLevel.DEBUG&&p("QueryEngine","The SDK decides to create cache indexes for query:",$n(t),"as using cache indexes may help improve performance."),this.indexManager.createTargetIndexes(e,Pn(t))):ie.resolve())}Xi(e,t){if(kn(t))return ie.resolve(null);let n=Pn(t);return this.indexManager.getIndexType(e,n).next((r=>0===r?null:(null!==t.limit&&1===r&&(t=Fn(t,null,"F"),n=Pn(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&&p("QueryEngine","Re-using previous result from %s to execute query: %s",r.toString(),$n(t)),this.os(e,o,t,Y(r,-1)).next((e=>e)))}))}rs(e,t){let n=new st(jn(e));return t.forEach(((t,r)=>{Bn(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&&p("QueryEngine","Using full collection scan to execute query:",$n(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 mo(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 $o(e,t,n,r){return new qo(e,t,n,r)}async function Bo(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 Uo(e){const t=b(e);return t.persistence.runTransaction("Get last remote snapshot version","readonly",(e=>t.Gr.getLastRemoteSnapshotVersion(e)))}function jo(e,t,n){let r=nr(),i=nr();return n.forEach((e=>r=r.add(e))),t.getEntries(e,r).next((e=>{let r=Hn();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)):p("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 ji(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(!ue(e))throw e;p("LocalStore",`Failed to update sequence numbers for target ${t}: ${e}`)}r.us=r.us.remove(t),r.cs.delete(i.target)}function Ho(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,Pn(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,Un(t),e),{documents:e,ds:s})))))}function Qo(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,Y(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 Yo(e,t,n=nr()){const r=await Go(e,Pn(Xi(t.bundledQuery))),i=b(e);return i.persistence.runTransaction("Save named query","readwrite",(e=>{const s=gi(t.readTime);if(r.snapshotVersion.compareTo(s)>=0)return i.jr.saveNamedQuery(e,t);const o=r.withResumeToken(ut.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 Xo(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):(m("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):(m("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):(m("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):(m("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=Xo(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(Xo(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 p("SharedClientState","READ",e,t),t}setItem(e,t){p("SharedClientState","SET",e,t),this.storage.setItem(e,t)}removeItem(e){p("SharedClientState","REMOVE",e),this.storage.removeItem(e)}bs(e){const t=e;if(t.storageArea===this.storage){if(p("SharedClientState","EVENT",t.key,t.newValue),t.key===this.Cs)return void m("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=ve.oe;if(null!=e)try{const n=JSON.parse(e);w("number"==typeof n),t=n}catch(e){m("SharedClientState","Failed to read sequence number from WebStorage",e)}return t}(t.newValue);e!==ve.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 u(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);p("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 la{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(){p("ConnectivityMonitor","Network connectivity changed: AVAILABLE");for(const e of this.To)e(0)}Po(){p("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 ua=null;function da(){return null===ua?ua=268435456+Math.round(2147483648*Math.random()):ua++,"0x"+ua.toString(16)}const ha={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 pa="WebChannelConnection";class ma 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=da(),o=this.No(e,t.toUriEncodedString());p("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=>(p("RestConnection",`Received RPC '${e}' ${s}: `,t),t)),(t=>{throw g("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/"+d,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=ha[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=da();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();p(pa,`XHR for RPC '${e}' ${i} received:`,JSON.stringify(t)),s(t);break;case c.ErrorCode.TIMEOUT:p(pa,`RPC '${e}' ${i} timed out`),o(new I(_.DEADLINE_EXCEEDED,"Request time out"));break;case c.ErrorCode.HTTP_ERROR:const n=a.getStatus();if(p(pa,`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:y()}}finally{p(pa,`RPC '${e}' ${i} completed.`)}}));const l=JSON.stringify(r);p(pa,`RPC '${e}' ${i} sending request:`,r),a.send(t,"POST",l,n,15)}))}qo(e,t,n){const r=da(),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},l=this.longPollingOptions.timeoutSeconds;void 0!==l&&(a.longPollingTimeout=Math.round(1e3*l)),this.useFetchStreams&&(a.useFetchStreams=!0),this.Lo(a.initMessageHeaders,t,n),a.encodeInitMessageHeaders=!0;const u=i.join("");p(pa,`Creating RPC '${e}' stream ${r}: ${u}`,a);const d=s.createWebChannel(u,a);let h=!1,f=!1;const m=new fa({Eo:t=>{f?p(pa,`Not sending because RPC '${e}' stream ${r} is closed:`,t):(h||(p(pa,`Opening RPC '${e}' stream ${r} transport.`),d.open(),h=!0),p(pa,`RPC '${e}' stream ${r} sending:`,t),d.send(t))},Ao:()=>d.close()}),v=(e,t,n)=>{e.listen(t,(e=>{try{n(e)}catch(e){setTimeout((()=>{throw e}),0)}}))};return v(d,c.WebChannel.EventType.OPEN,(()=>{f||(p(pa,`RPC '${e}' stream ${r} transport opened.`),m.So())})),v(d,c.WebChannel.EventType.CLOSE,(()=>{f||(f=!0,p(pa,`RPC '${e}' stream ${r} transport closed`),m.Do())})),v(d,c.WebChannel.EventType.ERROR,(t=>{f||(f=!0,g(pa,`RPC '${e}' stream ${r} transport errored:`,t),m.Do(new I(_.UNAVAILABLE,"The operation could not be completed")))})),v(d,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){p(pa,`RPC '${e}' stream ${r} received error:`,o);const t=o.status;let n=function(e){const t=Ur[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,m.Do(new I(n,i)),d.close()}else p(pa,`RPC '${e}' stream ${r} received:`,i),m.vo(i)}})),v(o,c.Event.STAT_EVENT,(t=>{t.stat===c.Stat.PROXY?p(pa,`RPC '${e}' stream ${r} detected buffering proxy`):t.stat===c.Stat.NOPROXY&&p(pa,`RPC '${e}' stream ${r} detected no buffering proxy`)})),setTimeout((()=>{m.bo()}),0),m}}function ga(){return"undefined"!=typeof window?window:null}function va(){return"undefined"!=typeof document?document:null}function ya(e){return new di(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&&p("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?(m(t.toString()),m("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 p("PersistentStream",`close with error: ${e}`),this.stream=null,this.close(4,e)}T_(e){return t=>{this.li.enqueueAndForget((()=>this.Xo===e?t():(p("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:y()}(t.targetChange.targetChangeType||"NO_CHANGE"),i=t.targetChange.targetIds||[],s=function(e,t){return e.useProto3Json?(w(void 0===t||"string"==typeof t),ut.fromBase64String(t||"")):(w(void 0===t||t instanceof Buffer||t instanceof Uint8Array),ut.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=gi(r.document.updateTime),o=r.document.createTime?gi(r.document.createTime):V.min(),a=new Gt({mapValue:{fields:r.document.fields}}),c=Ht.newFoundDocument(i,s,o,a),l=r.targetIds||[],u=r.removedTargetIds||[];n=new ti(l,u,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?gi(r.readTime):V.min(),o=Ht.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 y();{t.filter;const e=t.filter;e.targetId;const{count:r=0,unchangedNames:i}=e,s=new Br(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?gi(t.readTime):V.min()}(e);return this.listener.R_(t,n)}V_(e){const t={};t.database=Si(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=pi(e,t.resumeToken);const r=hi(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=hi(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 y()}}(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=Si(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?gi(e.updateTime):gi(t);return n.isEqual(V.min())&&(n=gi(t)),new _r(n,e.transformResults||[])}(e,t)))):[]}(e.writeResults,e.commitTime),n=gi(e.commitTime);return this.listener.y_(n,t)}w_(){const e={};e.database=Si(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,yi(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,yi(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 Sa{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_?(m(t),this.C_=!1):p("OnlineStateTracker",t)}N_(){null!==this.v_&&(this.v_.cancel(),this.v_=null)}}class Ta{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)&&(p("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 Sa(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),Pa(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 Pa(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 Oa(e){e.K_.set("Online")}async function Fa(e){e.B_.forEach(((t,n)=>{ka(e,t)}))}async function Va(e,t){Ra(e),Pa(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){p("RemoteStore","Failed to remove targets %s: %s ",t.targetIds.join(","),n),await $a(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 Uo(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(ut.EMPTY_BYTE_STRING,r.snapshotVersion)),Na(e,t);const i=new ji(r.target,t,n,r.sequenceNumber);ka(e,i)})),e.remoteSyncer.applyRemoteEvent(n)}(e,n)}catch(t){p("RemoteStore","Failed to raise snapshot:",t),await $a(e,t)}}async function $a(e,t,n){if(!ue(t))throw t;e.k_.add(1),await Ca(e),e.K_.set("Offline"),n||(n=()=>Uo(e.localStore)),e.asyncQueue.enqueueRetryable((async()=>{p("RemoteStore","Retrying IndexedDB access"),await n(),e.k_.delete(1),await xa(e)}))}function Ba(e,t){return t().catch((n=>$a(e,n,t)))}async function Ua(e){const t=b(e),n=ec(t);let r=t.L_.length>0?t.L_[t.L_.length-1].batchId:-1;for(;ja(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 $a(t,e)}Ga(t)&&Ka(t)}function ja(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 Ha(e){ec(e).w_()}async function Qa(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 Ba(e,(()=>e.remoteSyncer.applySuccessfulWrite(i))),await Ua(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 Ba(e,(()=>e.remoteSyncer.rejectFailedWrite(n.batchId,t))),await Ua(e)}}(e,t),Ga(e)&&Ka(e)}async function Ya(e,t){const n=b(e);n.asyncQueue.verifyOperationInProgress(),p("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 Xa(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:Oa.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_.__(),Pa(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:Ha.bind(null,e),po:Ja.bind(null,e),p_:Qa.bind(null,e),y_:Wa.bind(null,e)}),e.q_.push((async t=>{t?(e.G_.__(),await Ua(e)):(await e.G_.stop(),e.L_.length>0&&(p("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(m("AsyncQueue",`${t}: ${e}`),ue(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)||j.comparator(t.key,n.key):(e,t)=>j.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(j.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}):y():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 lc(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 '${$n(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 uc(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 dc(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 hc(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 pc,mc;(mc=pc||(pc={})).na="default",mc.Cache="cache";class gc{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!==pc.Cache}}class vc{constructor(e,t){this.ca=e,this.byteLength=t}la(){return"metadata"in this.ca}}class yc{constructor(e){this.serializer=e}As(e){return _i(this.serializer,e)}Rs(e){return e.metadata.exists?Ci(this.serializer,e.document,!1):Ht.newNoDocument(this.As(e.metadata.name),this.Vs(e.metadata.readTime))}Vs(e){return gi(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=$.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 yc(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=Hn();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 Pn(An($.fromString(`__bundle__/docs/${e}`)))}(r));return i.persistence.runTransaction("Apply bundle documents","readwrite",(e=>jo(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 yc(this.serializer),this.documents,this.ha.id),t=this.Ta(this.documents);for(const e of this.queries)await Yo(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=jn(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 l=r.get(e),u=Bn(this.query,t)?t:null,d=!!l&&this.mutatedKeys.has(l.key),h=!!u&&(u.hasLocalMutations||this.mutatedKeys.has(u.key)&&u.hasCommittedMutations);let f=!1;l&&u?l.data.isEqual(u.data)?d!==h&&(n.track({type:3,doc:u}),f=!0):this.ya(l,u)||(n.track({type:2,doc:u}),f=!0,(a&&this.Va(u,a)>0||c&&this.Va(u,c)<0)&&(o=!0)):!l&&u?(n.track({type:0,doc:u}),f=!0):l&&!u&&(n.track({type:1,doc:l}),f=!0,(a||c)&&(o=!0)),f&&(u?(s=s.add(u),i=h?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 y()}};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 Sc{constructor(e,t,n){this.query=e,this.targetId=t,this.view=n}}class Tc{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(j.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=nl(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=nl(e);await Ac(n,t,!0,!1)}async function Ac(e,t,n,r){const i=await Go(e.localStore,Pn(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 Ho(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 Uc(e,t.targetId,a.ba),a.snapshot}(e,t,n,r);const s=await Ho(e.localStore,t,!0),o=new Ec(t,s.ds),a=o.ga(s.documents),c=ei.createSynthesizedTargetChangeForCurrentChange(n,r&&"Offline"!==e.onlineState,i),l=o.applyChanges(a,e.isPrimaryClient,c);Uc(e,n,l.ba);const u=new Sc(t,n,o);return e.xa.set(t,u),e.Oa.has(n)?e.Oa.get(n).push(t):e.Oa.set(n,[t]),l.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),$c(r,i.targetId)})).catch(re)):($c(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 Pc(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 l=c.withSequenceNumber(e.currentSequenceNumber);null!==t.targetMismatches.get(a)?l=l.withResumeToken(ut.EMPTY_BYTE_STRING,V.min()).withLastLimboFreeSnapshotVersion(V.min()):s.resumeToken.approximateByteSize()>0&&(l=l.withResumeToken(s.resumeToken,r)),i=i.insert(a,l),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,l,s)&&o.push(n.Gr.updateTargetData(e,l))}));let a=Hn(),c=nr();if(t.documentUpdates.forEach((r=>{t.resolvedLimboDocuments.has(r)&&o.push(n.persistence.referenceDelegate.updateLimboDocument(e,r))})),o.push(jo(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(j.comparator);e=e.insert(s,Ht.newNoDocument(s,V.min()));const n=nr().add(s),i=new Zr(V.min(),new Map,new nt(M),e,n);await Pc(r,i),r.La=r.La.remove(s),r.Ba.delete(t),zc(r)}else await Ko(r.localStore,t,!1).then((()=>$c(r,t,n))).catch(re)}async function Oc(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 $c(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)||Bc(e,t)}))}function Bc(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 Uc(e,t,n){for(const r of n)r instanceof _c?(e.ka.addReference(r.key,t),jc(e,r)):r instanceof Ic?(p("SyncEngine","Document no longer in limbo: "+r.key),e.ka.removeReference(r.key,t),e.ka.containsKey(r.key)||Bc(e,r.key)):y()}function jc(e,t){const n=t.key,r=n.path.canonicalString();e.La.get(n)||e.Na.has(r)||(p("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 j($.fromString(t)),r=e.Ka.next();e.Ba.set(r,new Tc(n)),e.La=e.La.insert(n,r),Da(e.remoteStore,new ji(Pn(An(n.path)),r,"TargetPurposeLimboResolution",ve.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=Oo.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(!ue(e))throw e;p("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)){p("SyncEngine","User change. New user:",t.toKey());const e=await Bo(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 Hc(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 Qc(e,t){const n=b(e),r=await Ho(n.localStore,t.query,!0),i=t.view.va(r);return n.isPrimaryClient&&Uc(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 Ua(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)):y(),await Gc(i,s)):p("SyncEngine","Cannot apply mutation batch with id: "+t)}async function Yc(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,Pn(n[0]));for(const e of n){const t=r.xa.get(e),n=await Qc(r,t);n.snapshot&&s.push(n.snapshot)}}else{const n=await Qo(r.localStore,e);t=await Go(r.localStore,n),await kc(r,Xc(n),e,!1,t.resumeToken)}i.push(t)}return r.Ma.R_(s),i}function Xc(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 el(e,t,n,r){const i=b(e);if(i.$a)return void p("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,Un(s[0])),r=Zr.createSynthesizedRemoteEventForCurrentChange(t,"current"===n,ut.EMPTY_BYTE_STRING);await Gc(i,e,r);break}case"rejected":await Ko(i.localStore,t,!0),$c(i,t,r);break;default:y()}}async function tl(e,t,n){const r=nl(e);if(r.$a){for(const e of t){if(r.Oa.has(e)&&r.sharedClientState.isActiveQueryTarget(e)){p("SyncEngine","Adding an already active target "+e);continue}const t=await Qo(r.localStore,e),n=await Go(r.localStore,t);await kc(r,Xc(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),$c(r,e)})).catch(re)}}function nl(e){const t=b(e);return t.remoteStore.remoteSyncer.applyRemoteEvent=Pc.bind(null,t),t.remoteStore.remoteSyncer.getRemoteKeysForTarget=Hc.bind(null,t),t.remoteStore.remoteSyncer.rejectListen=Rc.bind(null,t),t.Ma.R_=dc.bind(null,t.eventManager),t.Ma.Wa=hc.bind(null,t.eventManager),t}function rl(e){const t=b(e);return t.remoteStore.remoteSyncer.applySuccessfulWrite=Oc.bind(null,t),t.remoteStore.remoteSyncer.rejectFailedWrite=Fc.bind(null,t),t}class il{constructor(){this.kind="memory",this.synchronizeTabs=!1}async initialize(e){this.serializer=ya(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 $o(this.persistence,new Vo,e.initialUser,this.serializer)}ja(e){return new To(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()}}il.provider={build:()=>new il};class sl extends il{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 To((e=>Do.ei(e,t)),this.serializer)}}class ol extends il{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 rl(this.Za.syncEngine),await Ua(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 $o(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 ge(t,this.persistence);return new me(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,ga(),va(),this.serializer,this.sharedClientState,!!this.forceOwnership)}za(e){return new aa}}class al extends ol{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:el.bind(null,t),oo:tl.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(nl(n),rl(n),!0===t&&!0!==n.$a){const e=n.sharedClientState.getAllActiveQueryTargets(),t=await Yc(n,e.toArray());n.$a=!0,await Xa(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((()=>($c(n,i),Ko(n.localStore,i,!0)))),Aa(n.remoteStore,i)})),await t,await Yc(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(j.comparator)}(n),n.$a=!1,await Xa(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=ga();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 cl{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 Xa(this.remoteStore,this.syncEngine.isPrimaryClient))}createEventManager(e){return new ac}createDatastore(e){const t=ya(e.databaseInfo.databaseId),n=function(e){return new ma(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 Ta(e,t,n,r,i)}(this.localStore,this.datastore,e.asyncQueue,(e=>Mc(this.syncEngine,e,0)),la.p()?new la: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);p("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 ll(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()}}cl.provider={build:()=>new cl};class ul{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):m("Uncaught Error in snapshot listener:",e.toString()))}eu(){this.muted=!0}Xa(e,t){setTimeout((()=>{this.muted||e(t)}),0)}}class dl{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 vc(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 hl{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,$.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=gi(t.found.updateTime),i=t.found.createTime?gi(t.found.createTime):V.min(),s=new Gt({mapValue:{fields:t.found.fields}});return Ht.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=gi(t.readTime);return Ht.newNoDocument(n,r)}(e,t):y()}(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=j.fromPath(t);this.mutations.push(new Or(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,$.emptyPath(),r)}(this.datastore,this.mutations),this.committed=!0}recordVersion(e){let t;if(e.isFoundDocument())t=e.version;else{if(!e.isNoDocument())throw y();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 fl{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 hl(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!ye(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 pl{constructor(e,t,n,r,i){this.authCredentials=e,this.appCheckCredentials=t,this.asyncQueue=n,this.databaseInfo=r,this.user=u.UNAUTHENTICATED,this.clientId=P.newId(),this.authCredentialListener=()=>Promise.resolve(),this.appCheckCredentialListener=()=>Promise.resolve(),this._uninitializedComponentsProvider=i,this.authCredentials.start(n,(async e=>{p("FirestoreClient","Received user=",e.uid),await this.authCredentialListener(e),this.user=e})),this.appCheckCredentials.start(n,(e=>(p("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 ml(e,t){e.asyncQueue.verifyOperationInProgress(),p("FirestoreClient","Initializing OfflineComponentProvider");const n=e.configuration;await t.initialize(n);let r=n.initialUser;e.setCredentialChangeListener((async e=>{r.isEqual(e)||(await Bo(t.localStore,e),r=e)})),t.persistence.setDatabaseDeletedListener((()=>e.terminate())),e._offlineComponents=t}async function gl(e,t){e.asyncQueue.verifyOperationInProgress();const n=await vl(e);p("FirestoreClient","Initializing OnlineComponentProvider"),await t.initialize(n,e.configuration),e.setCredentialChangeListener((e=>Ya(t.remoteStore,e))),e.setAppCheckTokenChangeListener(((e,n)=>Ya(t.remoteStore,n))),e._onlineComponents=t}async function vl(e){if(!e._offlineComponents)if(e._uninitializedComponentsProvider){p("FirestoreClient","Using user provided OfflineComponentProvider");try{await ml(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;g("Error using user provided cache. Falling back to memory cache: "+n),await ml(e,new il)}}else p("FirestoreClient","Using default OfflineComponentProvider"),await ml(e,new sl(void 0));return e._offlineComponents}async function yl(e){return e._onlineComponents||(e._uninitializedComponentsProvider?(p("FirestoreClient","Using user provided OnlineComponentProvider"),await gl(e,e._uninitializedComponentsProvider._online)):(p("FirestoreClient","Using default OnlineComponentProvider"),await gl(e,new cl))),e._onlineComponents}function wl(e){return vl(e).then((e=>e.persistence))}function bl(e){return vl(e).then((e=>e.localStore))}function _l(e){return yl(e).then((e=>e.remoteStore))}function Il(e){return yl(e).then((e=>e.syncEngine))}function El(e){return yl(e).then((e=>e.datastore))}async function Sl(e){const t=await yl(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 Tl(e,t,n={}){const r=new E;return e.asyncQueue.enqueueAndForget((async()=>function(e,t,n,r,i){const s=new ul({next:a=>{s.eu(),t.enqueueAndForget((()=>uc(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 gc(An(n.path),s,{includeMetadataChanges:!0,ua:!0});return lc(e,o)}(await Sl(e),e.asyncQueue,t,n,r))),r.promise}function xl(e,t,n={}){const r=new E;return e.asyncQueue.enqueueAndForget((async()=>function(e,t,n,r,i){const s=new ul({next:n=>{s.eu(),t.enqueueAndForget((()=>uc(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 gc(n,s,{includeMetadataChanges:!0,ua:!0});return lc(e,o)}(await Sl(e),e.asyncQueue,t,n,r))),r.promise}function Cl(e){const t={};return void 0!==e.timeoutSeconds&&(t.timeoutSeconds=e.timeoutSeconds),t}const Dl=new Map;function Al(e,t,n){if(!n)throw new I(_.INVALID_ARGUMENT,`Function ${e}() cannot be called with an empty ${t}.`)}function kl(e,t,n,r){if(!0===t&&!0===r)throw new I(_.INVALID_ARGUMENT,`${e} and ${n} cannot be used together.`)}function Nl(e){if(!j.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 Ll(e){if(j.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 Pl(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":y()}function Ml(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=Pl(e);throw new I(_.INVALID_ARGUMENT,`Expected type '${t.name}', but it was: ${n}`)}}return e}function Rl(e,t){if(t<=0)throw new I(_.INVALID_ARGUMENT,`Function ${e}() requires a positive number, but it was: ${t}.`)}class Ol{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}kl("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=Cl(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 Fl{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 Ol({}),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 Ol(e),void 0!==e.credentials&&(this._authCredentials=function(e){if(!e)return new T;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=Dl.get(e);t&&(p("ComponentProvider","Removing Datastore"),Dl.delete(e),t.terminate())}(this),Promise.resolve()}}function Vl(e,t,n,r={}){var i;const s=(e=Ml(e,Fl))._getSettings(),a=`${t}:${n}`;if("firestore.googleapis.com"!==s.host&&s.host!==a&&g("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=u.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 u(s)}e._authCredentials=new x(new S(t,n))}}class ql{constructor(e,t,n){this.converter=t,this._query=n,this.type="query",this.firestore=e}withConverter(e){return new ql(this.firestore,e,this._query)}}class $l{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 Bl(this.firestore,this.converter,this._key.path.popLast())}withConverter(e){return new $l(this.firestore,e,this._key)}}class Bl extends ql{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 $l(this.firestore,null,new j(e))}withConverter(e){return new Bl(this.firestore,e,this._path)}}function Ul(e,t,...n){if(e=o.getModularInstance(e),1===arguments.length&&(t=P.newId()),Al("doc","path",t),e instanceof Fl){const r=$.fromString(t,...n);return Nl(r),new $l(e,null,new j(r))}{if(!(e instanceof $l||e instanceof Bl))throw new I(_.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");const r=e._path.child($.fromString(t,...n));return Nl(r),new $l(e.firestore,e instanceof Bl?e.converter:null,new j(r))}}function jl(e,t){return e=o.getModularInstance(e),t=o.getModularInstance(t),e instanceof ql&&t instanceof ql&&e.firestore===t.firestore&&Vn(e._query,t._query)&&e.converter===t.converter}class zl{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=va();e&&p("AsyncQueue","Visibility state changed to "+e.visibilityState),this.r_.Jo()},this.gu=e;const t=va();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=va();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(!ue(e))throw e;p("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 m("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&&y()}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 Gl(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 Kl{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 Hl extends Fl{constructor(e,t,n,r){super(e,t,n,r),this.type="firestore",this._queue=new zl,this._persistenceKey=(null==r?void 0:r.name)||"[DEFAULT]"}async _terminate(){if(this._firestoreClient){const e=this._firestoreClient.terminate();this._queue=new zl(e),this._firestoreClient=void 0,await e}}}function Ql(e){if(e._terminated)throw new I(_.FAILED_PRECONDITION,"The client has already been terminated.");return e._firestoreClient||Wl(e),e._firestoreClient}function Wl(e){var t,n,r;const i=e._freezeSettings(),s=function(e,t,n,r){return new yt(e,t,n,r.host,r.ssl,r.experimentalForceLongPolling,r.experimentalAutoDetectLongPolling,Cl(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 pl(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 Jl(e,t,n){if((e=Ml(e,Hl))._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},Wl(e)}class Yl{constructor(e="count",t){this._internalFieldPath=t,this.type="AggregateField",this.aggregateType=e}}class Xl{constructor(e,t,n){this._userDataWriter=t,this._data=n,this.type="AggregateQuerySnapshot",this.query=e}data(){return this._userDataWriter.convertObjectMap(this._data)}}class Zl{constructor(e){this._byteString=e}static fromBase64String(e){try{return new Zl(ut.fromBase64String(e))}catch(e){throw new I(_.INVALID_ARGUMENT,"Failed to construct data from Base64 string: "+e)}}static fromUint8Array(e){return new Zl(ut.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 eu{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 U(e)}isEqual(e){return this._internalPath.isEqual(e._internalPath)}}class tu{constructor(e){this._methodName=e}}class nu{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 ru{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 iu=/^__.*__$/;class su{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 ou{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 au(e){switch(e){case 0:case 2:case 1:return!0;case 3:case 4:return!1;default:throw y()}}class cu{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 cu(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 Du(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(au(this.Mu)&&iu.test(e))throw this.qu('Document fields cannot begin and end with "__"')}}class lu{constructor(e,t,n){this.databaseId=e,this.ignoreUndefinedProperties=t,this.serializer=n||ya(e)}$u(e,t,n,r=!1){return new cu({Mu:e,methodName:t,Ku:n,path:U.emptyPath(),Nu:!1,Qu:r},this.databaseId,this.serializer,this.ignoreUndefinedProperties)}}function uu(e){const t=e._freezeSettings(),n=ya(e._databaseId);return new lu(e._databaseId,!!t.ignoreUndefinedProperties,n)}function du(e,t,n,r,i,s={}){const o=e.$u(s.merge||s.mergeFields?2:0,t,n,i);Su("Data must be an object, but it was:",o,r);const a=Iu(r,o);let c,l;if(s.merge)c=new ct(o.fieldMask),l=o.fieldTransforms;else if(s.mergeFields){const e=[];for(const r of s.mergeFields){const i=Tu(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.`);Au(e,i)||e.push(i)}c=new ct(e),l=o.fieldTransforms.filter((e=>c.covers(e.field)))}else c=null,l=o.fieldTransforms;return new su(new Gt(a),c,l)}class hu extends tu{_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 hu}}function fu(e,t,n){return new cu({Mu:3,Ku:t.settings.Ku,methodName:e._methodName,Nu:n},t.databaseId,t.serializer,t.ignoreUndefinedProperties)}class pu extends tu{_toFieldTransform(e){return new br(e.path,new hr)}isEqual(e){return e instanceof pu}}class mu extends tu{constructor(e,t){super(e),this.Uu=t}_toFieldTransform(e){const t=fu(this,e,!0),n=this.Uu.map((e=>_u(e,t))),r=new fr(n);return new br(e.path,r)}isEqual(e){return e instanceof mu&&o.deepEqual(this.Uu,e.Uu)}}class gu extends tu{constructor(e,t){super(e),this.Uu=t}_toFieldTransform(e){const t=fu(this,e,!0),n=this.Uu.map((e=>_u(e,t))),r=new mr(n);return new br(e.path,r)}isEqual(e){return e instanceof gu&&o.deepEqual(this.Uu,e.Uu)}}class vu extends tu{constructor(e,t){super(e),this.Wu=t}_toFieldTransform(e){const t=new vr(e.serializer,ar(e.serializer,this.Wu));return new br(e.path,t)}isEqual(e){return e instanceof vu&&this.Wu===e.Wu}}function yu(e,t,n,r){const i=e.$u(1,t,n);Su("Data must be an object, but it was:",i,r);const s=[],a=Gt.empty();Ze(r,((e,r)=>{const c=Cu(t,e,n);r=o.getModularInstance(r);const l=i.Bu(c);if(r instanceof hu)s.push(c);else{const e=_u(r,l);null!=e&&(s.push(c),a.set(c,e))}}));const c=new ct(s);return new ou(a,c,i.fieldTransforms)}function wu(e,t,n,r,i,s){const a=e.$u(1,t,n),c=[Tu(t,r,n)],l=[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(Tu(t,s[e])),l.push(s[e+1]);const u=[],d=Gt.empty();for(let e=c.length-1;e>=0;--e)if(!Au(u,c[e])){const t=c[e];let n=l[e];n=o.getModularInstance(n);const r=a.Bu(t);if(n instanceof hu)u.push(t);else{const e=_u(n,r);null!=e&&(u.push(t),d.set(t,e))}}const h=new ct(u);return new ou(d,h,a.fieldTransforms)}function bu(e,t,n,r=!1){return _u(n,e.$u(r?4:3,t))}function _u(e,t){if(Eu(e=o.getModularInstance(e)))return Su("Unsupported field value:",t,e),Iu(e,t);if(e instanceof tu)return function(e,t){if(!au(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=_u(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 nu)return{geoPointValue:{latitude:e.latitude,longitude:e.longitude}};if(e instanceof Zl)return{bytesValue:pi(t.serializer,e._byteString)};if(e instanceof $l){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:vi(e.firestore._databaseId||t.databaseId,e._key.path)}}if(e instanceof ru)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: ${Pl(e)}`)}(e,t)}function Iu(e,t){const n={};return tt(e)?t.path&&t.path.length>0&&t.fieldMask.push(t.path):Ze(e,((e,r)=>{const i=_u(r,t.Ou(e));null!=i&&(n[e]=i)})),{mapValue:{fields:n}}}function Eu(e){return!("object"!=typeof e||null===e||e instanceof Array||e instanceof Date||e instanceof F||e instanceof nu||e instanceof Zl||e instanceof $l||e instanceof tu||e instanceof ru)}function Su(e,t,n){if(!Eu(n)||!function(e){return"object"==typeof e&&null!==e&&(Object.getPrototypeOf(e)===Object.prototype||null===Object.getPrototypeOf(e))}(n)){const r=Pl(n);throw"an object"===r?t.qu(e+" a custom object"):t.qu(e+" "+r)}}function Tu(e,t,n){if((t=o.getModularInstance(t))instanceof eu)return t._internalPath;if("string"==typeof t)return Cu(e,t);throw Du("Field path arguments must be of type string or ",e,!1,void 0,n)}const xu=new RegExp("[~\\*/\\[\\]]");function Cu(e,t,n){if(t.search(xu)>=0)throw Du(`Invalid field path (${t}). Paths must not contain '~', '*', '/', '[', or ']'`,e,!1,void 0,n);try{return new eu(...t.split("."))._internalPath}catch(r){throw Du(`Invalid field path (${t}). Paths must not be empty, begin with '.', end with '.', or contain '..'`,e,!1,void 0,n)}}function Du(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 Au(e,t){return e.some((e=>e.isEqual(t)))}class ku{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 $l(this._firestore,this._converter,this._key)}exists(){return null!==this._document}data(){if(this._document){if(this._converter){const e=new Nu(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(Lu("DocumentSnapshot.get",e));if(null!==t)return this._userDataWriter.convertValue(t)}}}class Nu extends ku{data(){return super.data()}}function Lu(e,t){return"string"==typeof t?Cu(e,t):t instanceof eu?t._internalPath:t._delegate._internalPath}function Pu(e){if("L"===e.limitType&&0===e.explicitOrderBy.length)throw new I(_.UNIMPLEMENTED,"limitToLast() queries require specifying at least one orderBy() clause")}class Mu{}class Ru extends Mu{}class Ou extends Ru{constructor(e,t,n){super(),this._field=e,this._op=t,this._value=n,this.type="where"}static _create(e,t,n){return new Ou(e,t,n)}_apply(e){const t=this._parse(e);return Gu(e._query,t),new ql(e.firestore,e.converter,On(e._query,t))}_parse(e){const t=uu(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){zu(o,s);const t=[];for(const n of o)t.push(ju(r,e,n));a={arrayValue:{values:t}}}else a=ju(r,e,o)}else"in"!==s&&"not-in"!==s&&"array-contains-any"!==s||zu(o,s),a=bu(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 Fu extends Mu{constructor(e,t){super(),this.type=e,this._queryConstraints=t}static _create(e,t){return new Fu(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)Gu(n,e),n=On(n,e)}(e._query,t),new ql(e.firestore,e.converter,On(e._query,t)))}_getQueryConstraints(){return this._queryConstraints}_getOperator(){return"and"===this.type?"and":"or"}}class Vu extends Ru{constructor(e,t){super(),this._field=e,this._direction=t,this.type="orderBy"}static _create(e,t){return new Vu(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 Yt(t,n)}(e._query,this._field,this._direction);return new ql(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 qu extends Ru{constructor(e,t,n){super(),this.type=e,this._limit=t,this._limitType=n}static _create(e,t,n){return new qu(e,t,n)}_apply(e){return new ql(e.firestore,e.converter,Fn(e._query,this._limit,this._limitType))}}class $u extends Ru{constructor(e,t,n){super(),this.type=e,this._docOrFields=t,this._inclusive=n}static _create(e,t,n){return new $u(e,t,n)}_apply(e){const t=Uu(e,this.type,this._docOrFields,this._inclusive);return new ql(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 Bu extends Ru{constructor(e,t,n){super(),this.type=e,this._docOrFields=t,this._inclusive=n}static _create(e,t,n){return new Bu(e,t,n)}_apply(e){const t=Uu(e,this.type,this._docOrFields,this._inclusive);return new ql(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 Uu(e,t,n,r){if(n[0]=o.getModularInstance(n[0]),n[0]instanceof ku)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(mt(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 Qt(s,i)}(e._query,e.firestore._databaseId,t,n[0]._document,r);{const i=uu(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($.fromString(c));if(!j.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 j(n);a.push(Nt(t,i))}else{const e=bu(n,r,c);a.push(e)}}return new Qt(a,s)}(e._query,e.firestore._databaseId,i,t,n,r)}}function ju(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($.fromString(n));if(!j.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 j(r))}if(n instanceof $l)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: ${Pl(n)}.`)}function zu(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 Gu(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 Ku(e,t){if(!(t instanceof Ou||t instanceof Fu))throw new I(_.INVALID_ARGUMENT,`Function ${e}() requires AppliableConstraints created with a call to 'where(...)', 'or(...)', or 'and(...)'.`)}class Hu{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(pt(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 y()}}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 ru(i)}convertGeoPoint(e){return new nu(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=gt(e);return null==n?null:this.convertValue(n,t);case"estimate":return this.convertTimestamp(vt(e));default:return null}}convertTimestamp(e){const t=ht(e);return new F(t.seconds,t.nanos)}convertDocumentKey(e,t){const n=$.fromString(e);w(Ui(n));const r=new wt(n.get(1),n.get(3)),i=new j(n.popFirst(5));return r.isEqual(t)||m(`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 Qu(e,t,n){let r;return r=e?n&&(n.merge||n.mergeFields)?e.toFirestore(t,n):e.toFirestore(t):t,r}class Wu extends Hu{constructor(e){super(),this.firestore=e}convertBytes(e){return new Zl(e)}convertReference(e){const t=this.convertDocumentKey(e,this.firestore._databaseId);return new $l(this.firestore,null,t)}}function Ju(){return new Yl("count")}class Yu{constructor(e,t){this.hasPendingWrites=e,this.fromCache=t}isEqual(e){return this.hasPendingWrites===e.hasPendingWrites&&this.fromCache===e.fromCache}}class Xu extends ku{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 Zu(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(Lu("DocumentSnapshot.get",e));if(null!==n)return this._userDataWriter.convertValue(n,t.serverTimestamps)}}}class Zu extends Xu{data(e={}){return super.data(e)}}class ed{constructor(e,t,n,r){this._firestore=e,this._userDataWriter=t,this._snapshot=r,this.metadata=new Yu(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 Zu(this._firestore,this._userDataWriter,n.key,n,new Yu(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 Zu(e._firestore,e._userDataWriter,n.doc.key,n.doc,new Yu(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 Zu(e._firestore,e._userDataWriter,t.doc.key,t.doc,new Yu(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:td(t.type),doc:r,oldIndex:i,newIndex:s}}))}}(this,t),this._cachedChangesIncludeMetadataChanges=t),this._cachedChanges}}function td(e){switch(e){case 0:return"added";case 2:case 3:return"modified";case 1:return"removed";default:return y()}}class nd extends Hu{constructor(e){super(),this.firestore=e}convertBytes(e){return new Zl(e)}convertReference(e){const t=this.convertDocumentKey(e,this.firestore._databaseId);return new $l(this.firestore,null,t)}}function rd(e,t){return function(e,t){const n=new E;return e.asyncQueue.enqueueAndForget((async()=>async function(e,t,n){const r=rl(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=Hn(),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 Ua(r.remoteStore)}catch(e){const t=nc(e,"Failed to persist write");n.reject(t)}}(await Il(e),t,n))),n.promise}(Ql(e),t)}function id(e,t,n){const r=n.docs.get(t._key),i=new nd(e);return new Xu(e,i,t._key,r,new Yu(n.hasPendingWrites,n.fromCache),t.converter)}function sd(e,t){const n=Ml(e.firestore,Hl),r=Ql(n),i=et(t,((e,t)=>new $r(t,e.aggregateType,e._internalFieldPath)));return function(e,t,n){const r=new E;return e.asyncQueue.enqueueAndForget((async()=>{try{const i=await El(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 l=null===(r=c[0].result)||void 0===r?void 0:r.aggregateFields;return Object.keys(l).reduce(((e,t)=>(e[o[t]]=l[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 nd(e);return new Xl(t,r,n)}(n,e,t)))}class od{constructor(e){this.kind="memory",this._onlineComponentProvider=cl.provider,(null==e?void 0:e.garbageCollector)?this._offlineComponentProvider=e.garbageCollector._offlineComponentProvider:this._offlineComponentProvider={build:()=>new sl(void 0)}}toJSON(){return{kind:this.kind}}}class ad{constructor(e){let t;this.kind="persistent",(null==e?void 0:e.tabManager)?(e.tabManager._initialize(e),t=e.tabManager):(t=hd(void 0),t._initialize(e)),this._onlineComponentProvider=t._onlineComponentProvider,this._offlineComponentProvider=t._offlineComponentProvider}toJSON(){return{kind:this.kind}}}class cd{constructor(){this.kind="memoryEager",this._offlineComponentProvider=il.provider}toJSON(){return{kind:this.kind}}}class ld{constructor(e){this.kind="memoryLru",this._offlineComponentProvider={build:()=>new sl(e)}}toJSON(){return{kind:this.kind}}}class ud{constructor(e){this.forceOwnership=e,this.kind="persistentSingleTab"}toJSON(){return{kind:this.kind}}_initialize(e){this._onlineComponentProvider=cl.provider,this._offlineComponentProvider={build:t=>new ol(t,null==e?void 0:e.cacheSizeBytes,this.forceOwnership)}}}class dd{constructor(){this.kind="PersistentMultipleTab"}toJSON(){return{kind:this.kind}}_initialize(e){this._onlineComponentProvider=cl.provider,this._offlineComponentProvider={build:t=>new al(t,null==e?void 0:e.cacheSizeBytes)}}}function hd(e){return new ud(null==e?void 0:e.forceOwnership)}const fd={maxAttempts:5};class pd{constructor(e,t){this._firestore=e,this._commitHandler=t,this._mutations=[],this._committed=!1,this._dataReader=uu(e)}set(e,t,n){this._verifyNotCommitted();const r=md(e,this._firestore),i=Qu(r.converter,t,n),s=du(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=md(e,this._firestore);let s;return s="string"==typeof(t=o.getModularInstance(t))||t instanceof eu?wu(this._dataReader,"WriteBatch.update",i._key,t,n,r):yu(this._dataReader,"WriteBatch.update",i._key,t),this._mutations.push(s.toMutation(i._key,Ir.exists(!0))),this}delete(e){this._verifyNotCommitted();const t=md(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 md(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 gd extends class{constructor(e,t){this._firestore=e,this._transaction=t,this._dataReader=uu(e)}get(e){const t=md(e,this._firestore),n=new Wu(this._firestore);return this._transaction.lookup([t._key]).then((e=>{if(!e||1!==e.length)return y();const r=e[0];if(r.isFoundDocument())return new ku(this._firestore,n,r.key,r,t.converter);if(r.isNoDocument())return new ku(this._firestore,n,t._key,null,t.converter);throw y()}))}set(e,t,n){const r=md(e,this._firestore),i=Qu(r.converter,t,n),s=du(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=md(e,this._firestore);let s;return s="string"==typeof(t=o.getModularInstance(t))||t instanceof eu?wu(this._dataReader,"Transaction.update",i._key,t,n,r):yu(this._dataReader,"Transaction.update",i._key,t),this._transaction.update(i._key,s),this}delete(e){const t=md(e,this._firestore);return this._transaction.delete(t._key),this}}{constructor(e,t){super(e,t),this._firestore=e}get(e){const t=md(e,this._firestore),n=new nd(this._firestore);return super.get(e).then((e=>new Xu(this._firestore,n,t._key,e._document,new Yu(!1,!1),t.converter)))}}function vd(e,t){if("string"!=typeof e[t])throw new I(_.INVALID_ARGUMENT,"Missing string value for: "+t);return e[t]}class yd{constructor(e){this._firestore=e,this.type="PersistentCacheIndexManager"}}function wd(e,t){(function(e,t){return e.asyncQueue.enqueue((async()=>function(e,t){b(e)._s.Hi=t}(await bl(e),t)))})(Ql(e._firestore),t).then((e=>p(`setting persistent cache index auto creation isEnabled=${t} succeeded`))).catch((e=>g(`setting persistent cache index auto creation isEnabled=${t} failed`,e)))}const bd=new WeakMap;class _d{constructor(){this.Gu=new Map}static get instance(){return Id||(Id=new _d,function(e){if(Kr)throw new Error("a TestingHooksSpi instance is already set");Kr=e}(Id)),Id}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 Id=null;!function(e,t=!0){!function(e){d=e}(r.SDK_VERSION),r._registerComponent(new i.Component("firestore",((e,{instanceIdentifier:n,options:r})=>{const i=e.getProvider("app").getImmediate(),s=new Hl(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(l,"4.7.5",e),r.registerVersion(l,"4.7.5","cjs2017")}(),t.AbstractUserDataWriter=Hu,t.AggregateField=Yl,t.AggregateQuerySnapshot=Xl,t.Bytes=Zl,t.CACHE_SIZE_UNLIMITED=-1,t.CollectionReference=Bl,t.DocumentReference=$l,t.DocumentSnapshot=Xu,t.FieldPath=eu,t.FieldValue=tu,t.Firestore=Hl,t.FirestoreError=I,t.GeoPoint=nu,t.LoadBundleTask=Kl,t.PersistentCacheIndexManager=yd,t.Query=ql,t.QueryCompositeFilterConstraint=Fu,t.QueryConstraint=Ru,t.QueryDocumentSnapshot=Zu,t.QueryEndAtConstraint=Bu,t.QueryFieldFilterConstraint=Ou,t.QueryLimitConstraint=qu,t.QueryOrderByConstraint=Vu,t.QuerySnapshot=ed,t.QueryStartAtConstraint=$u,t.SnapshotMetadata=Yu,t.Timestamp=F,t.Transaction=gd,t.VectorValue=ru,t.WriteBatch=pd,t._AutoId=P,t._ByteString=ut,t._DatabaseId=wt,t._DocumentKey=j,t._EmptyAppCheckTokenProvider=class{getToken(){return Promise.resolve(new k(""))}invalidateToken(){}start(e,t){}shutdown(){}},t._EmptyAuthCredentialsProvider=T,t._FieldPath=U,t._TestingHooks=class{constructor(){throw new Error("instances of this class should not be created")}static onExistenceFilterMismatch(e){return _d.instance.onExistenceFilterMismatch(e)}},t._cast=Ml,t._debugAssert=function(e,t){e||y()},t._internalAggregationQueryToProtoRunAggregationQueryRequest=function(e,t){var n;const r=et(t,((e,t)=>new $r(t,e.aggregateType,e._internalFieldPath))),i=null===(n=Ql(Ml(e.firestore,Hl))._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=Ql(Ml(e.firestore,Hl))._onlineComponents)||void 0===t?void 0:t.datastore.serializer;return void 0===n?null:Ni(n,Pn(e._query)).ct},t._isBase64Available=function(){return"undefined"!=typeof atob},t._logWarn=g,t._validateIsNotUsedTogether=kl,t.addDoc=function(e,t){const n=Ml(e.firestore,Hl),r=Ul(e),i=Qu(e.converter,t);return rd(n,[du(uu(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 Yl&&t instanceof Yl&&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 jl(e.query,t.query)&&o.deepEqual(e.data(),t.data())},t.and=function(...e){return e.forEach((e=>Ku("and",e))),Fu._create("and",e)},t.arrayRemove=function(...e){return new gu("arrayRemove",e)},t.arrayUnion=function(...e){return new mu("arrayUnion",e)},t.average=function(e){return new Yl("avg",Tu("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),Al("collection","path",t),e instanceof Fl){const r=$.fromString(t,...n);return Ll(r),new Bl(e,null,r)}{if(!(e instanceof $l||e instanceof Bl))throw new I(_.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");const r=e._path.child($.fromString(t,...n));return Ll(r),new Bl(e.firestore,null,r)}},t.collectionGroup=function(e,t){if(e=Ml(e,Fl),Al("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 ql(e,null,function(e){return new Cn($.emptyPath(),e)}(t))},t.connectFirestoreEmulator=Vl,t.count=Ju,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 bl(e))))})(Ql(e._firestore)).then((e=>p("deleting all persistent cache indexes succeeded"))).catch((e=>g("deleting all persistent cache indexes failed",e)))},t.deleteDoc=function(e){return rd(Ml(e.firestore,Hl),[new Rr(e._key,Ir.none())])},t.deleteField=function(){return new hu("deleteField")},t.disableNetwork=function(e){return function(e){return e.asyncQueue.enqueue((async()=>{const t=await wl(e),n=await _l(e);return t.setNetworkEnabled(!1),async function(e){const t=b(e);t.k_.add(0),await Ca(t),t.K_.set("Offline")}(n)}))}(Ql(e=Ml(e,Hl)))},t.disablePersistentCacheIndexAutoCreation=function(e){wd(e,!1)},t.doc=Ul,t.documentId=function(){return new eu("__name__")},t.enableIndexedDbPersistence=function(e,t){g("enableIndexedDbPersistence() will be deprecated in the future, you can use `FirestoreSettings.cache` instead.");const n=e._freezeSettings();return Jl(e,cl.provider,{build:e=>new ol(e,n.cacheSizeBytes,null==t?void 0:t.forceOwnership)}),Promise.resolve()},t.enableMultiTabIndexedDbPersistence=async function(e){g("enableMultiTabIndexedDbPersistence() will be deprecated in the future, you can use `FirestoreSettings.cache` instead.");const t=e._freezeSettings();Jl(e,cl.provider,{build:e=>new al(e,t.cacheSizeBytes)})},t.enableNetwork=function(e){return function(e){return e.asyncQueue.enqueue((async()=>{const t=await wl(e),n=await _l(e);return t.setNetworkEnabled(!0),function(e){const t=b(e);return t.k_.delete(0),xa(t)}(n)}))}(Ql(e=Ml(e,Hl)))},t.enablePersistentCacheIndexAutoCreation=function(e){wd(e,!0)},t.endAt=function(...e){return Bu._create("endAt",e,!0)},t.endBefore=function(...e){return Bu._create("endBefore",e,!1)},t.ensureFirestoreConfigured=Ql,t.executeWrite=rd,t.getAggregateFromServer=sd,t.getCountFromServer=function(e){return sd(e,{count:Ju()})},t.getDoc=function(e){e=Ml(e,$l);const t=Ml(e.firestore,Hl);return Tl(Ql(t),e._key).then((n=>id(t,e,n)))},t.getDocFromCache=function(e){e=Ml(e,$l);const t=Ml(e.firestore,Hl),n=Ql(t),r=new nd(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 bl(e),t,n))),n.promise}(n,e._key).then((n=>new Xu(t,r,e._key,n,new Yu(null!==n&&n.hasLocalMutations,!0),e.converter)))},t.getDocFromServer=function(e){e=Ml(e,$l);const t=Ml(e.firestore,Hl);return Tl(Ql(t),e._key,{source:"server"}).then((n=>id(t,e,n)))},t.getDocs=function(e){e=Ml(e,ql);const t=Ml(e.firestore,Hl),n=Ql(t),r=new nd(t);return Pu(e._query),xl(n,e._query).then((n=>new ed(t,r,e,n)))},t.getDocsFromCache=function(e){e=Ml(e,ql);const t=Ml(e.firestore,Hl),n=Ql(t),r=new nd(t);return function(e,t){const n=new E;return e.asyncQueue.enqueueAndForget((async()=>async function(e,t,n){try{const r=await Ho(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 bl(e),t,n))),n.promise}(n,e._query).then((n=>new ed(t,r,e,n)))},t.getDocsFromServer=function(e){e=Ml(e,ql);const t=Ml(e.firestore,Hl),n=Ql(t),r=new nd(t);return xl(n,e._query,{source:"server"}).then((n=>new ed(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&&Vl(s,...e)}return s},t.getPersistentCacheIndexManager=function(e){var t;e=Ml(e,Hl);const n=bd.get(e);if(n)return n;if("persistent"!==(null===(t=Ql(e)._uninitializedComponentsProvider)||void 0===t?void 0:t._offline.kind))return null;const r=new yd(e);return bd.set(e,r),r},t.increment=function(e){return new vu("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 Rl("limit",e),qu._create("limit",e,"F")},t.limitToLast=function(e){return Rl("limitToLast",e),qu._create("limitToLast",e,"L")},t.loadBundle=function(e,t){const n=Ql(e=Ml(e,Hl)),r=new Kl;return function(e,t,n,r){const i=function(e,t){let n;return n="string"==typeof e?Hr().encode(e):e,function(e,t){return new dl(e,t)}(function(e,t){if(e instanceof Uint8Array)return ll(e,t);if(e instanceof ArrayBuffer)return ll(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,ya(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=gi(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 g("SyncEngine",`Loading bundle failed with ${e}`),n._failWith(e),Promise.resolve(new Set)}})(r,t,n).then((e=>{r.sharedClientState.notifyBundleLoaded(e)}))}(await Il(e),i,r)}))}(n,e._databaseId,t,r),r},t.memoryEagerGarbageCollector=function(){return new cd},t.memoryLocalCache=function(e){return new od(e)},t.memoryLruGarbageCollector=function(e){return new ld(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 bl(e),t)))}(Ql(e=Ml(e,Hl)),t).then((t=>t?new ql(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]||Gl(t[a])||(s=t[a],a++);const c={includeMetadataChanges:s.includeMetadataChanges,source:s.source};if(Gl(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 l,u,d;if(e instanceof $l)u=Ml(e.firestore,Hl),d=An(e._key.path),l={next:n=>{t[a]&&t[a](id(u,e,n))},error:t[a+1],complete:t[a+2]};else{const n=Ml(e,ql);u=Ml(n.firestore,Hl),d=n._query;const r=new nd(u);l={next:e=>{t[a]&&t[a](new ed(u,r,n,e))},error:t[a+1],complete:t[a+2]},Pu(e._query)}return function(e,t,n,r){const i=new ul(r),s=new gc(t,i,n);return e.asyncQueue.enqueueAndForget((async()=>lc(await Sl(e),s))),()=>{i.eu(),e.asyncQueue.enqueueAndForget((async()=>uc(await Sl(e),s)))}}(Ql(u),d,c,l)},t.onSnapshotsInSync=function(e,t){return function(e,t){const n=new ul(t);return e.asyncQueue.enqueueAndForget((async()=>function(e,t){b(e).X_.add(t),t.next()}(await Sl(e),n))),()=>{n.eu(),e.asyncQueue.enqueueAndForget((async()=>function(e,t){b(e).X_.delete(t)}(await Sl(e),n)))}}(Ql(e=Ml(e,Hl)),Gl(t)?t:{next:t})},t.or=function(...e){return e.forEach((e=>Ku("or",e))),Fu._create("or",e)},t.orderBy=function(e,t="asc"){const n=t,r=Lu("orderBy",e);return Vu._create(r,n)},t.persistentLocalCache=function(e){return new ad(e)},t.persistentMultipleTabManager=function(){return new dd},t.persistentSingleTabManager=hd,t.query=function(e,t,...n){let r=[];t instanceof Mu&&r.push(t),r=r.concat(n),function(e){const t=e.filter((e=>e instanceof Fu)).length,n=e.filter((e=>e instanceof Ou)).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=jl,t.refEqual=function(e,t){return e=o.getModularInstance(e),t=o.getModularInstance(t),(e instanceof $l||e instanceof Bl)&&(t instanceof $l||t instanceof Bl)&&e.firestore===t.firestore&&e.path===t.path&&e.converter===t.converter},t.runTransaction=function(e,t,n){e=Ml(e,Hl);const r=Object.assign(Object.assign({},fd),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 El(e);new fl(e.asyncQueue,i,n,t,r).cu()})),r.promise}(Ql(e),(n=>t(new gd(e,n))),r)},t.serverTimestamp=function(){return new pu("serverTimestamp")},t.setDoc=function(e,t,n){e=Ml(e,$l);const r=Ml(e.firestore,Hl),i=Qu(e.converter,t,n);return rd(r,[du(uu(r),"setDoc",e._key,i,null!==e.converter,n).toMutation(e._key,Ir.none())])},t.setIndexConfiguration=function(e,t){const n=Ql(e=Ml(e,Hl));if(!n._uninitializedComponentsProvider||"memory"===n._uninitializedComponentsProvider._offline.kind)return g("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=vd(e,"collectionGroup"),r=[];if(Array.isArray(e.fields))for(const t of e.fields){const e=Cu("setIndexConfiguration",vd(t,"fieldPath"));"CONTAINS"===t.arrayConfig?r.push(new Q(e,2)):"ASCENDING"===t.order?r.push(new Q(e,0)):"DESCENDING"===t.order&&r.push(new Q(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,H,(t=>{i.push(r.addFieldIndex(e,t))}),(t=>{i.push(r.deleteFieldIndex(e,t))})))).next((()=>ie.waitFor(i)))))}(await bl(e),t)))}(n,r)},t.setLogLevel=function(e){h.setLogLevel(e)},t.snapshotEqual=function(e,t){return e instanceof Xu&&t instanceof Xu?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 ed&&t instanceof ed&&e._firestore===t._firestore&&jl(e.query,t.query)&&e.metadata.isEqual(t.metadata)&&e._snapshot.isEqual(t._snapshot)},t.startAfter=function(...e){return $u._create("startAfter",e,!1)},t.startAt=function(...e){return $u._create("startAt",e,!0)},t.sum=function(e){return new Yl("sum",Tu("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=Ml(e,$l);const i=Ml(e.firestore,Hl),s=uu(i);let a;return a="string"==typeof(t=o.getModularInstance(t))||t instanceof eu?wu(s,"updateDoc",e._key,t,n,r):yu(s,"updateDoc",e._key,t),rd(i,[a.toMutation(e._key,Ir.exists(!0))])},t.vector=function(e){return new ru(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)||p("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 Il(e),t))),t.promise}(Ql(e=Ml(e,Hl)))},t.where=function(e,t,n){const r=t,i=Lu("where",e);return Ou._create(i,r,n)},t.writeBatch=function(e){return Ql(e=Ml(e,Hl)),new pd(e,(t=>rd(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 l="functions",u={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 d extends i.FirebaseError{constructor(e,t,n){super(`${l}/${e}`,t||""),this.details=n,Object.setPrototypeOf(this,d.prototype)}}function h(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(!u[t])return new d("internal","internal");r=u[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 d(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 p="us-central1",m=/^data: (.*?)(?:\n|$)/;class g{constructor(e,t,n,r,i=p,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=p}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 v(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 y(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 y(e,r),o=function(e){let t=null;return{promise:new Promise(((n,r)=>{t=setTimeout((()=>{r(new d("deadline-exceeded","deadline-exceeded"))}),e)})),cancel:()=>{t&&clearTimeout(t)}}}(r.timeout||7e4),l=await Promise.race([v(t,i,s,e.fetchImpl),o.promise,e.cancelAllRequests]);if(o.cancel(),!l)throw new d("cancelled","Firebase Functions instance was deleted.");const u=h(l.status,l.json);if(u)throw u;if(!l.json)throw new d("internal","Response is not valid JSON object.");let f=l.json.data;if(void 0===f&&(f=l.json.result),void 0===f)throw new d("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 y(e,r);let l,u,f;o["Content-Type"]="application/json",o.Accept="text/event-stream";try{l=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 d("cancelled","Request was cancelled.");return{data:Promise.reject(e),stream:{[Symbol.asyncIterator]:()=>({next:()=>Promise.reject(e)})}}}const t=h(0,null);return{data:Promise.reject(t),stream:{[Symbol.asyncIterator]:()=>({next:()=>Promise.reject(t)})}}}const p=new Promise(((e,t)=>{u=e,f=t}));null===(i=null==r?void 0:r.signal)||void 0===i||i.addEventListener("abort",(()=>{const e=new d("cancelled","Request was cancelled.");f(e)}));const g=function(e,t,n,r){const i=(e,r)=>{const i=e.match(m);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=h(0,e);return r.error(t),void n(t)}}catch(e){if(e instanceof d)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 d("cancelled","Request was cancelled");return t.error(e),n(e),Promise.resolve()}try{const{value:c,done:l}=await e.read();if(l)return o.trim()&&i(o.trim(),t),void t.close();if(null==r?void 0:r.aborted){const r=new d("cancelled","Request was cancelled");return t.error(r),n(r),void await e.cancel()}o+=s.decode(c,{stream:!0});const u=o.split("\n");o=u.pop()||"";for(const e of u)e.trim()&&i(e.trim(),t);return a()}catch(e){const r=e instanceof d?e:h(0,null);t.error(r),n(r)}}()},cancel:()=>e.cancel()})}(l.body.getReader(),u,f,null==r?void 0:r.signal);return{stream:{[Symbol.asyncIterator](){const e=g.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:p}}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(l,((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 g(n,r,i,s,t)}),"PUBLIC").setMultipleInstances(!0)),r.registerVersion(_,I,undefined),r.registerVersion(_,I,"cjs2017"),t.FunctionsError=d,t.connectFunctionsEmulator=E,t.getFunctions=function(e=r.getApp(),t=p){const n=r._getProvider(i.getModularInstance(e),l).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,l=i>>2,u=(3&i)<<4|o>>4;let d=(15&o)<<2|c>>6,h=63&c;a||(h=64,s||(d=64)),r.push(n[l],n[u],n[d],n[h])}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 l=i<<2|s>>4;if(r.push(l),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 l=function(e){const t=o(e);return a.encodeByteArray(t,!0)},u=function(e){return l(e).replace(/\./g,"")},d=function(e){try{return a.decodeString(e,!0)}catch(e){console.error("base64Decode failed: ",e)}return null};function h(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]=h(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 p=()=>{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&&d(e[1]);return t&&JSON.parse(t)})()}catch(e){return void console.info(`Unable to get __FIREBASE_DEFAULTS__ due to: ${e}`)}},m=e=>{var t,n;return null===(n=null===(t=p())||void 0===t?void 0:t.emulatorHosts)||void 0===n?void 0:n[e]};class g{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 v(){return"undefined"!=typeof navigator&&"string"==typeof navigator.userAgent?navigator.userAgent:""}function y(){var e;const t=null===(e=p())||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 S=function(e){let t={},n={},r={},i="";try{const s=e.split(".");t=E(d(s[0])||""),n=E(d(s[1])||""),i=s[2],r=n.d||{},delete n.d}catch(e){}return{header:t,claims:n,data:r,signature:i}};function T(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=g,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],l=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+l+i+n[e]&4294967295;l=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]+l&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=d,t.base64Encode=l,t.base64urlEncodeWithoutPadding=u,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[u(JSON.stringify({alg:"none",type:"JWT"})),u(JSON.stringify(s)),""].join(".")},t.createSubscribe=function(e,t){const n=new x(e,t);return n.subscribe.bind(n)},t.decode=S,t.deepCopy=function(e){return h(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(T(r)&&T(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=h,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=p())||void 0===e?void 0:e.config},t.getDefaultEmulatorHost=m,t.getDefaultEmulatorHostnameAndPort=e=>{const t=m(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=p,t.getExperimentalSetting=e=>{var t;return null===(t=p())||void 0===t?void 0:t[`_${e}`]},t.getGlobal=f,t.getModularInstance=function(e){return e&&e._delegate?e._delegate:e},t.getUA=v,t.isAdmin=function(e){const t=S(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 v().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=v();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(v())},t.isNode=y,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!y()&&!!navigator.userAgent&&navigator.userAgent.includes("Safari")&&!navigator.userAgent.includes("Chrome")},t.isUWP=function(){return v().indexOf("MSAppHost/")>=0},t.isValidFormat=function(e){const t=S(e).claims;return!!t&&"object"==typeof t&&t.hasOwnProperty("iat")},t.isValidTimestamp=function(e){const t=S(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=S(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 g;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),l=o(1),u=o(16777216);function d(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 h(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(l)}function p(e,t){return e.add(f(t))}function m(e,t){for(;(65535&e[t])!=e[t];)e[t+1]+=e[t]>>>16,e[t]&=65535,t++}function g(e,t){this.g=e,this.h=t}function v(e,t){if(d(t))throw Error("division by zero");if(d(e))return new g(c,c);if(h(e))return t=v(f(e),t),new g(f(t.g),f(t.h));if(h(t))return t=v(e,f(t)),new g(f(t.g),t.h);if(30<e.g.length){if(h(e)||h(t))throw Error("slowDivide_ only works with positive integers.");for(var n=l,r=t;0>=r.l(e);)n=y(n),r=y(r);var i=w(n,1),s=w(r,1);for(r=w(r,2),n=w(n,2);!d(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=p(e,i.j(t)),new g(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);h(o)||0<o.l(e);)o=(s=a(n-=r)).j(t);d(s)&&(s=l),i=i.add(s),e=p(e,o)}return new g(i,e)}function y(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(h(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(d(this))return"0";if(h(this))return"-"+f(this).toString(e);for(var t=a(Math.pow(e,6)),n=this,r="";;){var i=v(n,t).g,s=((0<(n=p(n,i.j(t))).g.length?n.g[0]:n.h)>>>0).toString(e);if(d(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 h(e=p(this,e))?-1:d(e)?0:1},t.abs=function(){return h(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(d(this)||d(e))return c;if(h(this))return h(e)?f(this).j(f(e)):f(f(this).j(e));if(h(e))return f(this.j(f(e)));if(0>this.l(u)&&0>e.l(u))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,l=65535&this.i(r),p=e.i(s)>>>16,g=65535&e.i(s);n[2*r+2*s]+=l*g,m(n,2*r+2*s),n[2*r+2*s+1]+=o*g,m(n,2*r+2*s+1),n[2*r+2*s+1]+=l*p,m(n,2*r+2*s+1),n[2*r+2*s+2]+=o*p,m(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 v(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),l=parseInt(t.substring(s,s+o),n);8>o?(o=a(Math.pow(n,o)),i=i.j(o).add(a(l))):i=(i=i.j(r)).add(a(l))}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 l(e,t,n){return e.call.apply(e.bind,arguments)}function u(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 d(e,t,n){return(d=Function.prototype.bind&&-1!=Function.prototype.bind.toString().indexOf("native code")?l:u).apply(null,arguments)}function h(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 p(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 m(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 g(e){return/^[\s\xa0]*$/.test(e)}function v(){var e=o.navigator;return e&&(e=e.userAgent)?e:""}function y(e){return y[" "](e),e}y[" "]=function(){};var w=!(-1==v().indexOf("Gecko")||-1!=v().toLowerCase().indexOf("webkit")&&-1==v().indexOf("Edge")||-1!=v().indexOf("Trident")||-1!=v().indexOf("MSIE")||-1!=v().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 S(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 T(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(P)}};var P=()=>{for(var e;e=x();){try{e.h.call(e.g)}catch(e){T(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 O=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{y(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),$=0;function B(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=++$,this.da=this.fa=!1}function U(e){e.da=!0,e.listener=null,e.proxy=null,e.src=null,e.ha=null}function j(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&&(U(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}j.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 B(t,this.src,s,!!r,i)).fa=n,e.push(t)),t};var K="closure_lm_"+(1e6*Math.random()|0),H={};function Q(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++)Q(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 j(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)O||(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 Y(e,t,n,r,i){if(Array.isArray(t))for(var s=0;s<t.length;s++)Y(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))&&(U(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)&&X(n))}function X(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)):U(e)}}}function Z(e){return e in H?H[e]:H[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&&X(e),e=n.call(r,t)}return e}function te(e){return(e=e[K])instanceof j?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 j(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=d(e,n));else{if(!e||"function"!=typeof e.handleEvent)throw Error("Invalid listener argument");e=d(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){Y(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++)U(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 le 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 ue(e){M.call(this),this.h=e,this.g={}}f(ue,M);var de=[];function he(e){b(e.g,(function(e,t){this.g.hasOwnProperty(t)&&X(e)}),e),e.g={}}ue.prototype.N=function(){ue.aa.N.call(this),he(this)},ue.prototype.handleEvent=function(){throw Error("EventHandler.handleEvent not implemented")};var fe=o.JSON.stringify,pe=o.JSON.parse,me=class{stringify(e){return o.JSON.stringify(e,void 0)}parse(e){return o.JSON.parse(e,void 0)}};function ge(){}function ve(e){return e.h||(e.h=e.i())}function ye(){}ge.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 Se(){return Ee=Ee||new ie}function Te(e){R.call(this,Ie.La,e)}function xe(e){const t=Se();se(t,new Te(t,e))}function Ce(e,t){R.call(this,Ie.STAT_EVENT,e),this.stat=t}function De(e){const t=Se();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(Te,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 Pe,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 Oe(){}function Fe(e,t,n,r){this.j=e,this.i=t,this.l=n,this.R=r||1,this.U=new ue(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(Oe,ge),Oe.prototype.g=function(){return new XMLHttpRequest},Oe.prototype.i=function(){return{}},Pe=new Oe;var qe={},$e={};function Be(e,t,n){e.L=1,e.v=ft(ct(t)),e.m=n,e.P=!0,Ue(e,null)}function Ue(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=mn(e.j,n?t:null,!e.m),0<e.O&&(e.M=new le(d(e.Y,e,e.g),e.O)),t=e.U,n=e.g,r=e.ca;var i="readystatechange";Array.isArray(i)||(i&&(de[0]=i.toString()),i=de);for(var s=0;s<i.length;s++){var o=Q(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 l=a[c].split("=");if(1<l.length){var u=l[0];l=l[1];var d=u.split("_");o=2<=d.length&&"type"==d[1]?o+(u+"=")+l+"&":o+(u+"=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 je(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?$e:(n=Number(t.substring(n,r)),isNaN(n)?qe:(r+=1)+n>t.length?$e:(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(d(e.ba,e),t)}function He(e){e.B&&(o.clearTimeout(e.B),e.B=null)}function Qe(e){0==e.j.G||e.J||un(e.j,e)}function We(e){He(e);var t=e.M;t&&"function"==typeof t.ma&&t.ma(),e.M=null,he(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;ln(n),Xt(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(d(n.Za,n),6e3));if(1>=et(n.h)&&n.ca){try{n.ca()}catch(e){}n.ca=void 0}}else hn(n,11)}else if((e.K||n.g==e)&&ln(n),!g(t))for(i=n.Da.g.parse(t),t=0;t<i.length;t++){let l=i[t];if(n.T=l[0],l=l[1],2==n.G)if("c"==l[0]){n.K=l[1],n.ia=l[2];const t=l[3];null!=t&&(n.la=t,n.j.info("VER="+n.la));const i=l[4];null!=i&&(n.Aa=i,n.j.info("SVER="+n.Aa));const u=l[5];null!=u&&"number"==typeof u&&0<u&&(r=1.5*u,n.L=r,n.j.info("backChannelRequestTimeoutMs_="+r)),r=n;const d=e.g;if(d){const e=d.g?d.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=d.g?d.g.getResponseHeader("X-HTTP-Session-Id"):null;e&&(r.ya=e,ht(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=pn(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&&(He(a),Ge(a)),r.g=o}else sn(r);0<n.i.length&&en(n)}else"stop"!=l[0]&&"close"!=l[0]||hn(n,7);else 3==n.G&&("stop"==l[0]||"close"==l[0]?"stop"==l[0]?hn(n,7):Yt(n):"noop"!=l[0]&&n.l&&n.l.ta(l),n.v=0)}xe(4)}catch(e){}}Fe.prototype.ca=function(e){e=e.target;const t=this.M;t&&3==Ht(e)?t.j():this.Y(e)},Fe.prototype.Y=function(e){try{if(e==this.g)e:{const h=Ht(this.g);var t=this.g.Ba();const f=this.g.Z();if(!(3>h)&&(3!=h||this.g&&(this.h.h||this.g.oa()||Qt(this.g)))){this.J||4!=h||7==t||xe(8==t||0>=f?3:2),He(this);var n=this.g.Z();this.X=n;t:if(je(this)){var r=Qt(this.g);e="";var i=r.length,s=4==Ht(this.g);if(!this.h.i){if("undefined"==typeof TextDecoder){We(this),Qe(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,h,n),this.o){if(this.T&&!this.K){t:{if(this.g){var c,l=this.g;if((c=l.g?l.g.getResponseHeader("X-HTTP-Initial-Response"):null)&&!g(c)){var u=c;break t}}u=null}if(!(n=u)){this.o=!1,this.s=3,De(12),We(this),Qe(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==$e){4==h&&(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(je(this)&&0!=this.C&&(this.h.g=this.h.g.slice(this.C),this.C=0),4!=h||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 d=this.j;d.g==this&&d.ba&&!d.M&&(d.j.info("Great, no buffering proxy detected. Bytes received: "+a.length),an(d),d.M=!0,De(11))}}else Le(this.i,this.l,a,"[Invalid Chunked Response]"),We(this),Qe(this)}else Le(this.i,this.l,a,null),Je(this,a);4==h&&We(this),this.o&&!this.J&&(4==h?un(this.j,this):(this.o=!1,Ge(this)))}else(function(e){const t={};e=(e.g&&2<=Ht(e)&&e.g.getAllResponseHeaders()||"").split("\r\n");for(let r=0;r<e.length;r++){if(g(e[r]))continue;var n=S(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),Qe(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,Qe(this)):Ke(this,this.S-e)};var Ye=class{constructor(e,t){this.g=e,this.map=t}};function Xe(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 p(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)}Xe.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,lt(this,e.j),this.o=e.o,this.g=e.g,ut(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),dt(this,n),this.m=e.m}else e&&(t=String(e).match(ot))?(this.h=!1,lt(this,t[1]||"",!0),this.o=pt(t[2]||""),this.g=pt(t[3]||"",!0),ut(this,t[4]),this.l=pt(t[5]||"",!0),dt(this,t[6]||"",!0),this.m=pt(t[7]||"")):(this.h=!1,this.i=new Et(null,this.h))}function ct(e){return new at(e)}function lt(e,t,n){e.j=n?pt(t,!0):t,e.j&&(e.j=e.j.replace(/:$/,""))}function ut(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 dt(e,t,n){t instanceof Et?(e.i=t,function(e,t){t&&!e.j&&(St(e),e.i=null,e.g.forEach((function(e,t){var n=t.toLowerCase();t!=n&&(Tt(this,t),Ct(this,n,e))}),e)),e.j=t}(e.i,e.h)):(n||(t=mt(t,_t)),e.i=new Et(t,e.h))}function ht(e,t,n){e.i.set(t,n)}function ft(e){return ht(e,"zx",Math.floor(2147483648*Math.random()).toString(36)+Math.abs(Math.floor(2147483648*Math.random())^Date.now()).toString(36)),e}function pt(e,t){return e?t?decodeURI(e.replace(/%25/g,"%2525")):decodeURIComponent(e):""}function mt(e,t,n){return"string"==typeof e?(e=encodeURI(e).replace(t,gt),n&&(e=e.replace(/%25([0-9a-fA-F]{2})/g,"%$1")),e):null}function gt(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(mt(t,yt,!0),":");var n=this.g;return(n||"file"==t)&&(e.push("//"),(t=this.o)&&e.push(mt(t,yt,!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(mt(n,"/"==n.charAt(0)?bt:wt,!0))),(n=this.i.toString())&&e.push("?",n),(n=this.m)&&e.push("#",mt(n,It)),e.join("")};var vt,yt=/[#\/\?@]/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 St(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 Tt(e,t){St(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 St(e),t=Dt(e,t),e.g.has(t)}function Ct(e,t,n){Tt(e,t),0<n.length&&(e.i=null,e.g.set(Dt(e,t),p(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 me}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 Pt(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,Ot(e)}function Ot(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))):ht(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){St(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){St(this),this.g.forEach((function(n,r){n.forEach((function(n){e.call(t,n,r,this)}),this)}),this)},t.na=function(){St(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){St(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 St(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,ge),Lt.prototype.g=function(){return new Pt(this.l,this.j)},Lt.prototype.i=(vt={},function(){return vt}),f(Pt,ie),(t=Pt.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,Ot(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,Ot(this)),this.g&&(this.readyState=3,Ot(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):Ot(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(Pt.prototype,"withCredentials",{get:function(){return"include"===this.m},set:function(e){this.m=e?"include":"same-origin"}}),f(qt,ie);var $t=/^https?$/i,Bt=["POST","PUT"];function Ut(e,t){e.h=!1,e.g&&(e.j=!0,e.g.abort(),e.j=!1),e.l=t,e.m=5,jt(e),Gt(e)}function jt(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!=Ht(e)||2!=e.Z()))if(e.u&&4==Ht(e))ae(e.Ea,0,e);else if(se(e,"readystatechange"),4==Ht(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=!$t.test(i?i.toLowerCase():"")}n=r}if(n)se(e,"complete"),se(e,"success");else{e.m=6;try{var a=2<Ht(e)?e.g.statusText:""}catch(e){a=""}e.l=a+" ["+e.Z()+"]",jt(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 Ht(e){return e.g?e.g.readyState:0}function Qt(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 Xe(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 Yt(e){if(Zt(e),3==e.G){var t=e.U++,n=ct(e.I);if(ht(n,"SID",e.K),ht(n,"RID",t),ht(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=mn(t.j,null),t.g.ea(t.v)),t.F=Date.now(),Ge(t)}fn(e)}function Xt(e){e.g&&(an(e),e.g.cancel(),e.g=null)}function Zt(e){Xt(e),e.u&&(o.clearTimeout(e.u),e.u=null),ln(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);ht(r,"SID",e.K),ht(r,"RID",n),ht(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),Be(n,r,t)}function nn(e,t){e.H&&b(e.H,(function(e,n){ht(t,n,e)})),e.l&&st({},(function(e,n){ht(t,n,e)}))}function rn(e,t,n){n=Math.min(e.i.length,n);var r=e.l?d(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(d(e.Fa,e),dn(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);ht(t,"RID","rpc"),ht(t,"SID",e.K),ht(t,"AID",e.T),ht(t,"CI",e.F?"0":"1"),!e.F&&e.ja&&ht(t,"TO",e.ja),ht(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,Ue(n,e)}function ln(e){null!=e.C&&(o.clearTimeout(e.C),e.C=null)}function un(e,t){var n=null;if(e.g==t){ln(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=Se(),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(d(e.Ga,e,t),dn(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:hn(e,5);break;case 4:hn(e,10);break;case 3:hn(e,6);break;default:hn(e,2)}}function dn(e,t){let n=e.Ta+Math.floor(Math.random()*e.cb);return e.isActive()||(n*=2),n*t}function hn(e,t){if(e.j.info("Error code "+t),2==t){var n=d(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||lt(r,"https"),ft(r),t?function(e,t){const n=new Ne;if(o.Image){const r=new Image;r.onload=h(At,n,"TestLoadImage: loaded",!0,t,r),r.onerror=h(At,n,"TestLoadImage: error",!1,t,r),r.onabort=h(At,n,"TestLoadImage: abort",!1,t,r),r.ontimeout=h(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||(m(e.ka,t),m(e.ka,e.i),e.h.i.length=0,p(e.i),e.i.length=0),e.l.ra()}}function pn(e,t,n){var r=n instanceof at?ct(n):new at(n);if(""!=r.g)t&&(r.g=t+"."+r.g),ut(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&<(s,r),t&&(s.g=t),i&&ut(s,i),n&&(s.l=n),r=s}return n=e.D,t=e.ya,n&&t&&ht(r,n,t),ht(r,"VER",e.la),nn(e,r),r}function mn(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 gn(){}function vn(){}function yn(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)&&!g(e)&&(this.g.m=e),this.v=t&&t.supportsCrossDomainXhr||!1,this.u=t&&t.sendRawJson||!1,(t=t&&t.httpSessionIdParam)&&!g(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():Pe.g(),this.v=this.o?ve(this.o):ve(Pe),this.g.onreadystatechange=d(this.Ea,this);try{this.B=!0,this.g.open(t,String(e),!0),this.B=!1}catch(e){return void Ut(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(Bt,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){Ut(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<Ht(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)),pe(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=pn(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),ht(n=ct(this.I),"RID",e),ht(n,"CVER",22),this.D&&ht(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&&ht(n,"TYPE","init"),this.P?(ht(n,"$req",t),ht(n,"SID","null"),i.T=!0,Be(i,n,null)):Be(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(d(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),Xt(this),cn(this))},t.Za=function(){null!=this.C&&(this.C=null,Xt(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=gn.prototype).ua=function(){},t.ta=function(){},t.sa=function(){},t.ra=function(){},t.isActive=function(){return!0},t.Na=function(){},vn.prototype.g=function(e,t){return new yn(e,t)},f(yn,ie),yn.prototype.m=function(){this.g.l=this.j,this.v&&(this.g.J=!0),this.g.connect(this.l,this.h||void 0)},yn.prototype.close=function(){Yt(this.g)},yn.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 Ye(t.Ya++,e)),3==t.G&&en(t)},yn.prototype.N=function(){this.g.l=null,delete this.j,Yt(this.g),delete this.g,yn.aa.N.call(this)},f(wn,be),f(bn,_e),f(_n,gn),_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")},vn.prototype.createWebChannel=vn.prototype.g,yn.prototype.send=yn.prototype.o,yn.prototype.open=yn.prototype.m,yn.prototype.close=yn.prototype.close,e.exports.createWebChannelTransport=function(){return new vn},e.exports.getStatEventTarget=function(){return Se()},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,ye.EventType=we,we.OPEN="a",we.CLOSE="b",we.ERROR="c",we.MESSAGE="d",ie.prototype.listen=ie.prototype.K,e.exports.WebChannel=ye,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:function(e,t,n){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.initCalculator=function(e,t){const n=`\n <div class="calculator-input purchase-price">\n <div class="header">\n <div class="title-wrapper">\n <img src="${s.default}" alt="Purchase Price icon"/>\n <div class="title">Purchase Price</div>\n </div>\n <img class="info-icon" src="${g.default}" alt="Info icon" data-tooltip="The total purchase price of the property"/>\n </div>\n <div class="input-field">\n <input type="text" value="$ 500,000" data-previous-value="500000" class="value-input">\n <input type="range" min="0" max="2000000" value="500000" class="slider">\n <div class="range-label">\n <span>$0</span>\n <span>$2M</span>\n </div>\n </div>\n </div>\n\n <div class="calculator-input down-payment">\n <div class="header">\n <div class="title-wrapper">\n <img src="${o.default}" alt="Down Payment icon"/>\n <div class="title">Down Payment</div>\n </div>\n <img class="info-icon" src="${g.default}" alt="Info icon" data-tooltip="Your initial payment towards the property"/>\n </div>\n <div class="input-field">\n <div class="downpayment-percentage-wrapper">\n <input type="text" value="$ 100,000" data-previous-value="100000" class="value-input">\n <input type="text" value="20%" data-previous-value="20" class="percentage-value-input">\n </div>\n <input type="range" min="5" max="40" value="20" class="slider">\n <div class="range-label">\n <span>5%</span>\n <span>40%</span>\n </div>\n </div>\n </div>\n\n <div class="calculator-input interest-rate">\n <div class="header">\n <div class="title-wrapper">\n <img src="${a.default}" alt="Interest Rate icon"/>\n <div class="title">Interest Rate</div>\n </div>\n <div class="fixed-variable-selector">\n <div class="selector">Fixed</div>\n <div class="selector active">Variable</div>\n </div>\n </div>\n <div class="input-field">\n <input type="text" value="6.00%" data-previous-value="6.00" class="value-input">\n <input type="range" min="0.1" max="40" value="6" step="0.1" class="slider">\n <div class="range-label">\n <span>0.1%</span>\n <span>40%</span>\n </div>\n </div>\n </div>\n\n <div class="calculator-input amortization-period">\n <div class="header">\n <div class="title-wrapper">\n <img src="${c.default}" alt="Amortization Period icon"/>\n <div class="title">Amortization Period</div>\n </div>\n <img class="info-icon" src="${g.default}" alt="Info icon" data-tooltip="The total length of time to pay off your mortgage"/>\n </div>\n <div class="dropdown">\n <div class="dropdown-field">\n <span>25 years</span>\n <img class="info-icon" src="${l.default}" alt="Dropdown icon"/> \n </div>\n <div class="dropdown-opts">\n <div class="dropdown-opt">5 years</div>\n <div class="dropdown-opt">10 years</div>\n <div class="dropdown-opt">15 years</div>\n <div class="dropdown-opt">20 years</div>\n <div class="dropdown-opt">25 years</div>\n <div class="dropdown-opt">30 years</div>\n </div>\n </div>\n </div>\n\n <div class="calculator-input term-length">\n <div class="header">\n <div class="title-wrapper">\n <img src="${u.default}" alt="Term Length icon"/>\n <div class="title">Term Length</div>\n </div>\n <img class="info-icon" src="${g.default}" alt="Info icon" data-tooltip="The length of your mortgage term"/>\n </div>\n <div class="dropdown">\n <div class="dropdown-field">\n <span>5 years</span>\n <img class="info-icon" src="${l.default}" alt="Dropdown icon"/> \n </div>\n <div class="dropdown-opts">\n <div class="dropdown-opt">1 year</div>\n <div class="dropdown-opt">2 years</div>\n <div class="dropdown-opt">3 years</div>\n <div class="dropdown-opt">4 years</div>\n <div class="dropdown-opt">5 years</div>\n <div class="dropdown-opt">7 years</div>\n <div class="dropdown-opt">10 years</div>\n </div>\n </div>\n </div>\n\n <div class="calculator-input payment-frequency">\n <div class="header">\n <div class="title-wrapper">\n <img src="${d.default}" alt="Payment Frequency icon"/>\n <div class="title">Payment Frequency</div>\n </div>\n <img class="info-icon" src="${g.default}" alt="Info icon" data-tooltip="How often you make mortgage payments"/>\n </div>\n <div class="dropdown">\n <div class="dropdown-field">\n <span>Monthly</span>\n <img class="info-icon" src="${l.default}" alt="Dropdown icon"/> \n </div>\n <div class="dropdown-opts">\n <div class="dropdown-opt">Monthly</div>\n <div class="dropdown-opt">Semi-Monthly</div>\n <div class="dropdown-opt">Bi-Weekly</div>\n <div class="dropdown-opt">Accelerated Bi-Weekly</div>\n <div class="dropdown-opt">Weekly</div>\n <div class="dropdown-opt">Accelerated Weekly</div>\n </div>\n </div>\n </div>\n\n `,r=`\n <div class="calculator-input property-taxes">\n <div class="header">\n <div class="title-wrapper">\n <img src="${h.default}" alt="Property Taxes icon"/>\n <div class="title">Property Taxes</div>\n </div>\n <img class="info-icon" src="${g.default}" alt="Info icon" data-tooltip="Annual property taxes"/>\n </div>\n <div class="input-field">\n <input type="text" value="$ 9,600" data-previous-value="9600" class="value-input">\n <input type="range" min="0" max="100000" value="9600" class="slider">\n <div class="range-label">\n <span>$0</span>\n <span>$100,000</span>\n </div>\n </div>\n </div>\n\n <div class="calculator-input heating-costs">\n <div class="header">\n <div class="title-wrapper">\n <img src="${f.default}" alt="Heating Costs icon"/>\n <div class="title">Heating Costs</div>\n </div>\n <img class="info-icon" src="${g.default}" alt="Info icon" data-tooltip="Annual heating costs"/>\n </div>\n <div class="input-field">\n <input type="text" value="$ 2,400" data-previous-value="2400" class="value-input">\n <input type="range" min="0" max="5000" value="2400" class="slider">\n <div class="range-label">\n <span>$0</span>\n <span>$5,000</span>\n </div>\n </div>\n </div>\n\n <div class="calculator-input condo-fees">\n <div class="header">\n <div class="title-wrapper">\n <img src="${p.default}" alt="Condo Fees icon"/>\n <div class="title">Condo Fees</div>\n </div>\n <img class="info-icon" src="${g.default}" alt="Info icon" data-tooltip="Monthly condo maintenance fees"/>\n </div>\n <div class="input-field">\n <input type="text" value="$ 250" data-previous-value="250" class="value-input">\n <input type="range" min="0" max="1500" value="250" class="slider">\n <div class="range-label">\n <span>$0</span>\n <span>$1,500</span>\n </div>\n </div>\n </div>\n\n <div class="calculator-input extra-payments">\n <div class="header">\n <div class="title-wrapper">\n <img src="${m.default}" alt="Extra Payments icon"/>\n <div class="title">Extra Payments</div>\n </div>\n <div class="extra-payment-selectors">\n <span class="selector">None</span>\n <span class="selector active">One-Time</span>\n <span class="selector">Recurring</span>\n </div>\n </div>\n <div class="input-field"><input type="text" value="$ 0" data-previous-value="0" class="value-input"></div>\n <div class="dropdown">\n <div class="dropdown-field">\n <span>Monthly</span>\n <img class="info-icon" src="${l.default}" alt="Dropdown icon"/> \n </div>\n <div class="dropdown-opts">\n <div class="dropdown-opt">Monthly</div>\n <div class="dropdown-opt">Yearly</div>\n <div class="dropdown-opt">One-time</div>\n </div>\n </div>\n </div>\n\n `;e.innerHTML=`\n <div class="mortgage-calculator">\n <div class="section-heading">Purchase Calculator</div>\n <div class="tab-layout">\n <div class="tab-headers">\n <div class="tab-header active">Standard</div>\n <div class="tab-header">Advanced</div>\n </div>\n <div class="tab-content active">\n <div class="calculator-inputs">\n ${n}\n </div>\n <div class="calculator-results">\n \n <div class="mortgage-payment">\n <div class="mortgage-payment-wrapper">\n <div class="label">Mortgage Payment</div>\n <div class="value">$2,902</div>\n <div class="frequency">Monthly Payment</div>\n </div>\n <div class="mortgage-amount-insurance">\n <div class="mortgage-amount">\n <div class="label">Mortgage Amount</div>\n <div class="value">$440,000</div>\n </div>\n <div class="mortgage-insurance">\n <div class="label">Mortgage Insurance</div>\n <div class="value">$13,640</div>\n </div>\n </div>\n </div>\n\n <div class="payment-breakdown">\n <div class="section-label">Payment Breakdown</div>\n <div class="section-wrapper">\n <div class="principal">\n <div class="label">Principal</div>\n <div class="value">$662</div>\n </div>\n <div class="interest">\n <div class="label">Interest</div>\n <div class="value">$2,240</div>\n </div>\n </div>\n </div>\n\n <div class="term-calculations">\n <div class="section-label">Term Calculations (<span>5 years</span>)</div>\n <div class="section-wrapper">\n <div class="calculation-row">\n <div class="label">Total Payments over Term</div>\n <div class="value">$174,145</div>\n </div>\n <div class="calculation-row">\n <div class="label">Principal Paid during Term</div>\n <div class="value">$46,105</div>\n </div>\n <div class="calculation-row">\n <div class="label">Interest Paid during Term</div>\n <div class="value">$128,040</div>\n </div>\n <div class="calculation-row">\n <div class="label">Balance Remaining after Term</div>\n <div class="value">$407,535</div>\n </div>\n <div class="calculation-row">\n <input type="range" min="1" max="100" value="10" step="1" class="slider principal-slider" disabled>\n <div class="range-label">\n <span>Principal Paid (10%)</span>\n <span>Remaining Balance</span>\n </div>\n </div>\n </div>\n </div>\n\n <div class="total-mortgage">\n <div class="section-label">Total Mortgage (<span>25 years</span>)</div>\n <div class="section-wrapper">\n <div class="calculation-row">\n <div class="label">Total Mortgage + Interest</div>\n <div class="value">$870,726</div>\n </div>\n <div class="calculation-row">\n <div class="label">Total Interest Paid</div>\n <div class="value">$417,086</div>\n </div>\n <div class="calculation-row">\n <div class="label">Interest/Principal Ratio</div>\n <div class="value">92%</div>\n </div>\n <div class="calculation-row">\n <div class="calculation-row-label">Amortization</div>\n <input type="range" min="1" max="100" value="92" step="1" class="slider amortization-result-slider" disabled>\n <div class="range-label">\n <span>Principal</span>\n <span>Interest</span>\n </div>\n </div>\n </div>\n </div>\n\n \n </div>\n </div>\n <div class="tab-content">\n <div class="calculator-inputs">\n ${r}\n </div>\n <div class="calculator-results">\n \n <div class="total-mortgage-payment">\n <div class="mortgage-payment-wrapper">\n <div class="label">Total Mortgage Payment</div>\n <div class="value">$3,902</div>\n <div class="frequency">Including all selected costs</div>\n </div>\n <div class="mortgage-amount-insurance">\n <div class="mortgage-amount advanced-mortgage-payment">\n <div class="label">Mortgage Payment</div>\n <div class="value">$2,902</div>\n </div>\n <div class="mortgage-insurance property-taxes">\n <div class="label">Property Taxes</div>\n <div class="value">$800</div>\n </div>\n <div class="mortgage-amount heating-costs">\n <div class="label">Heating Costs</div>\n <div class="value">$200</div>\n </div>\n <div class="mortgage-insurance condo-fees">\n <div class="label">Condo Fees</div>\n <div class="value">$0</div>\n </div>\n </div>\n </div>\n\n <div class="extra-payment-impacts">\n <div class="section-label">Impact of Extra Payments</div>\n <div class="section-wrapper">\n <div class="principal years-saved">\n <div class="label">Years Saved</div>\n <div class="value">0 years</div>\n </div>\n <div class="interest interest-saved">\n <div class="label">Interest Saved</div>\n <div class="value">$0</div>\n </div>\n </div>\n </div>\n\n <div class="mortgage-stress-test">\n <div class="section-label">Mortgage Stress Test</div>\n <div class="section-wrapper">\n <div class="calculation-row">\n <div class="label">Qualifying Rate</div>\n <div class="value">8.00%</div>\n </div>\n <div class="calculation-row">\n <div class="label">Stress Test Payment</div>\n <div class="value">$3,358</div>\n </div>\n <div class="calculation-row">\n <div class="label">Income Required</div>\n <div class="value">$163,430</div>\n </div>\n </div>\n </div>\n\n \n </div>\n </div>\n </div>\n </div>\n `;const v=document.querySelector(".purchase-price .value-input"),y=document.querySelector(".purchase-price .slider"),w=document.querySelector(".down-payment .value-input"),b=document.querySelector(".down-payment .percentage-value-input"),_=document.querySelector(".down-payment .slider"),I=document.querySelector(".interest-rate .value-input"),E=document.querySelector(".interest-rate .slider"),S=document.querySelector(".term-calculations .principal-slider"),T=document.querySelector(".total-mortgage .amortization-result-slider"),x=document.querySelectorAll(".tab-header"),C=document.querySelectorAll(".tab-content"),D=document.querySelector(".property-taxes .value-input"),A=document.querySelector(".property-taxes .slider"),k=document.querySelector(".heating-costs .value-input"),N=document.querySelector(".heating-costs .slider"),L=document.querySelector(".condo-fees .value-input"),P=document.querySelector(".condo-fees .slider"),M=document.querySelector(".extra-payments .value-input"),R=document.querySelector(".amortization-period .dropdown-field span"),O=document.querySelector(".payment-frequency .dropdown-field span"),F=document.querySelector(".term-length .dropdown-field span"),V=document.querySelector(".extra-payments .dropdown-field span"),q=document.querySelector(".calculator-results .mortgage-payment-wrapper .value"),$=document.querySelector(".calculator-results .mortgage-amount-insurance .mortgage-amount .value"),B=document.querySelector(".calculator-results .mortgage-amount-insurance .mortgage-insurance .value"),U=document.querySelector(".calculator-results .payment-breakdown .principal .value"),j=document.querySelector(".calculator-results .payment-breakdown .interest .value"),z=document.querySelector(".term-calculations .section-wrapper .calculation-row:nth-child(1) .value"),G=document.querySelector(".term-calculations .section-wrapper .calculation-row:nth-child(2) .value"),K=document.querySelector(".term-calculations .section-wrapper .calculation-row:nth-child(3) .value"),H=document.querySelector(".term-calculations .section-wrapper .calculation-row:nth-child(4) .value"),Q=document.querySelector(".total-mortgage .section-wrapper .calculation-row:nth-child(1) .value"),W=document.querySelector(".total-mortgage .section-wrapper .calculation-row:nth-child(2) .value"),J=document.querySelector(".total-mortgage .section-wrapper .calculation-row:nth-child(3) .value"),Y=document.querySelector(".term-calculations .section-label span"),X=document.querySelector(".total-mortgage .section-label span"),Z=document.querySelector(".calculator-results .total-mortgage-payment .mortgage-payment-wrapper .value"),ee=document.querySelector(".calculator-results .total-mortgage-payment .mortgage-amount-insurance .advanced-mortgage-payment .value"),te=document.querySelector(".calculator-results .total-mortgage-payment .mortgage-amount-insurance .property-taxes .value"),ne=document.querySelector(".calculator-results .total-mortgage-payment .mortgage-amount-insurance .heating-costs .value"),re=document.querySelector(".calculator-results .total-mortgage-payment .mortgage-amount-insurance .condo-fees .value"),ie=document.querySelector(".calculator-results .extra-payment-impacts .years-saved .value"),se=document.querySelector(".calculator-results .extra-payment-impacts .interest-saved .value"),oe=document.querySelector(".calculator-results .mortgage-stress-test .section-wrapper .calculation-row:nth-child(1) .value"),ae=document.querySelector(".calculator-results .mortgage-stress-test .section-wrapper .calculation-row:nth-child(2) .value"),ce=document.querySelector(".calculator-results .mortgage-stress-test .section-wrapper .calculation-row:nth-child(3) .value"),le=document.querySelectorAll(".fixed-variable-selector .selector"),ue=document.querySelectorAll(".extra-payment-selectors .selector"),de=document.querySelectorAll("[data-tooltip]");function he(e){const t=Number(e.value),n=Number(e.min),r=(t-n)/(Number(e.max)-n)*100;e.style.background=`linear-gradient(to right, #1A4383 ${r}%, #1A43832f ${r}%)`}document.querySelectorAll(".dropdown-opt").forEach((e=>{e.addEventListener("click",(()=>{var t,n;const r=null===(t=e.parentElement)||void 0===t?void 0:t.previousElementSibling,i=null==r?void 0:r.querySelector("span");i&&(i.textContent=e.textContent),null===(n=e.parentElement)||void 0===n||n.classList.remove("expanded"),me()}))})),document.querySelectorAll(".dropdown-field").forEach((e=>{e.addEventListener("click",(t=>{document.querySelectorAll(".dropdown-opts.expanded").forEach((e=>{e.classList.remove("expanded")}));const n=e.nextElementSibling;null==n||n.classList.toggle("expanded"),t.stopPropagation()}))})),document.addEventListener("click",(e=>{e.target.closest(".dropdown")||document.querySelectorAll(".dropdown-opts.expanded").forEach((e=>{e.classList.remove("expanded")}))})),x.forEach(((e,t)=>{e.addEventListener("click",(()=>{x.forEach((e=>e.classList.remove("active"))),C.forEach((e=>e.classList.remove("active"))),e.classList.add("active"),C[t].classList.add("active"),me()}))})),le.forEach(((e,t)=>{e.addEventListener("click",(()=>{le.forEach((e=>e.classList.remove("active"))),e.classList.add("active"),me()}))})),ue.forEach(((e,t)=>{e.addEventListener("click",(()=>{var t,n,r,i,s,o;ue.forEach((e=>e.classList.remove("active"))),e.classList.add("active");const a=null===(n=null===(t=e.parentElement)||void 0===t?void 0:t.parentElement)||void 0===n?void 0:n.nextElementSibling,c=null===(s=null===(i=null===(r=e.parentElement)||void 0===r?void 0:r.parentElement)||void 0===i?void 0:i.nextElementSibling)||void 0===s?void 0:s.nextElementSibling;"none"===(null===(o=e.textContent)||void 0===o?void 0:o.toLowerCase())?(null==a||a.classList.add("disabled"),null==c||c.classList.add("disabled")):(null==a||a.classList.remove("disabled"),null==c||c.classList.remove("disabled")),me()}))})),de.forEach((e=>{const t=e.getAttribute("data-tooltip"),n=document.createElement("div");n.className="custom-tooltip",n.textContent=t,document.body.appendChild(n),e.addEventListener("mousemove",(e=>{const t=e;n.style.top=`${t.pageY+20}px`,n.style.left=t.pageX-n.clientWidth/2+"px"})),e.addEventListener("mouseenter",(e=>{n.style.opacity="1",n.style.pointerEvents="none"})),e.addEventListener("mouseleave",(()=>{n.style.opacity="0"}))})),y.addEventListener("input",(()=>{const e=y.value.replace(/[^0-9.]/g,"");v.value=e?`$ ${parseInt(e).toLocaleString("en-US")}`:"",v.dataset.previousValue=e,he(y),fe(),me()})),_.addEventListener("input",(()=>{var e;let t=null===(e=v.dataset.previousValue)||void 0===e?void 0:e.replace(/[^0-9.]/g,"");const n=t?parseInt(t):0,r=_.value.replace(/[^0-9.]/g,"");b.value=r?`${parseInt(r).toLocaleString("en-US")}%`:"",b.dataset.previousValue=r;const i=n&&r?n*(.01*parseInt(r)):0;w.value=`$ ${i.toLocaleString("en-US")}`,w.dataset.previousValue=i.toString(),he(_),me()})),E.addEventListener("input",(()=>{const e=E.value.replace(/[^0-9.]/g,"");I.value=e?`${parseFloat(e).toFixed(2)}%`:"",I.dataset.previousValue=e,he(E),me()})),A.addEventListener("input",(()=>{const e=A.value.replace(/[^0-9.]/g,"");D.value=e?`$ ${parseInt(e).toLocaleString("en-US")}`:"",D.dataset.previousValue=e,he(A),me()})),N.addEventListener("input",(()=>{const e=N.value.replace(/[^0-9.]/g,"");k.value=e?`$ ${parseInt(e).toLocaleString("en-US")}`:"",k.dataset.previousValue=e,he(N),me()})),P.addEventListener("input",(()=>{const e=P.value.replace(/[^0-9.]/g,"");L.value=e?`$ ${parseInt(e).toLocaleString("en-US")}`:"",L.dataset.previousValue=e,he(P),me()}));const fe=()=>{var e,t;let n=null===(e=v.dataset.previousValue)||void 0===e?void 0:e.replace(/[^0-9.]/g,"");const r=n?parseInt(n):0,i=parseInt(null!==(t=w.dataset.previousValue)&&void 0!==t?t:"0")/r*100;_.value=i.toString(),he(_),b.value=`${i.toLocaleString("en-US")}%`,b.dataset.previousValue=i.toString()},pe=(e,t,n)=>{e.addEventListener("input",(e=>{var r,i;const s=e.target;if(s){let e=s.value;e=e.replace(/[^0-9.]/g,"");const o=e?parseInt(e):0;switch(n){case"purchase-price":0<=o&&o<=2e6?(y.value=o.toString(),he(y),s.value=`${t} ${parseInt(e).toLocaleString("en-US")}`,s.dataset.previousValue=e):s.dataset.previousValue&&(s.value=`${t} ${parseInt(s.dataset.previousValue).toLocaleString("en-US")}`),fe();break;case"downpayment":let n=null===(r=v.dataset.previousValue)||void 0===r?void 0:r.replace(/[^0-9.]/g,"");const a=n?parseInt(n):0;if(o<=.4*a){const n=o/a*100;_.value=n.toString(),he(_),b.value=`${n.toLocaleString("en-US")}%`,b.dataset.previousValue=n.toString(),s.value=`${t} ${parseInt(e).toLocaleString("en-US")}`,s.dataset.previousValue=e}else s.dataset.previousValue&&(s.value=`${t} ${s.dataset.previousValue}`);break;case"downpayment-percentage":if(1<=o&&o<=40){_.value=o.toString(),he(_),s.value=`${e}${t}`,s.dataset.previousValue=e;let n=null===(i=v.dataset.previousValue)||void 0===i?void 0:i.replace(/[^0-9.]/g,"");const r=n?parseInt(n):0,a=r?r*(.01*o):0;w.value=`$ ${a.toLocaleString("en-US")}`,w.dataset.previousValue=a.toString()}else s.dataset.previousValue&&(s.value=`${s.dataset.previousValue}${t}`);break;case"interest-rate":const c=e?parseFloat(e):0;.1<=c&&c<=40?(E.value=c.toFixed(2),he(E),s.value=`${c.toFixed(2)}%`,s.dataset.previousValue=c.toFixed(2)):s.dataset.previousValue&&(s.value=`${parseFloat(s.dataset.previousValue).toFixed(2)}%`);break;case"property-taxes":0<=o&&o<=1e5?(A.value=o.toString(),he(A),s.value=`${t} ${parseInt(e).toLocaleString("en-US")}`,s.dataset.previousValue=e):s.dataset.previousValue&&(s.value=`${t} ${parseInt(s.dataset.previousValue).toLocaleString("en-US")}`);break;case"heating-costs":0<=o&&o<=5e3?(N.value=o.toString(),he(N),s.value=`${t} ${parseInt(e).toLocaleString("en-US")}`,s.dataset.previousValue=e):s.dataset.previousValue&&(s.value=`${t} ${parseInt(s.dataset.previousValue).toLocaleString("en-US")}`);break;case"condo-fees":0<=o&&o<=1500?(P.value=o.toString(),he(P),s.value=`${t} ${parseInt(e).toLocaleString("en-US")}`,s.dataset.previousValue=e):s.dataset.previousValue&&(s.value=`${t} ${parseInt(s.dataset.previousValue).toLocaleString("en-US")}`);break;case"extra-payments":0<=o?(s.value=`${t} ${parseInt(e).toLocaleString("en-US")}`,s.dataset.previousValue=e):s.dataset.previousValue&&(s.value=`${t} ${parseInt(s.dataset.previousValue).toLocaleString("en-US")}`)}me()}}))},me=()=>{var e;const t=document.querySelector(".mortgage-calculator .tab-headers .active"),n=document.querySelector(".interest-rate .fixed-variable-selector .active"),r=document.querySelector(".extra-payments .extra-payment-selectors .active"),s=null===(e=t.textContent)||void 0===e?void 0:e.toLowerCase(),o={purchasePrice:v.dataset.previousValue?parseInt(v.dataset.previousValue):0,downPaymentAmount:w.dataset.previousValue?parseInt(w.dataset.previousValue):0,downPaymentPercentage:b.dataset.previousValue?parseInt(b.dataset.previousValue):0,interestRate:I.dataset.previousValue?parseFloat(parseFloat(I.dataset.previousValue).toFixed(2)):0,amortizationPeriod:R.textContent?parseInt(R.textContent.replace(" years","")):5,paymentFrequency:O.textContent?O.textContent.toLowerCase():"monthly",rateType:n.textContent?n.textContent.toLowerCase():"fixed",termLength:F.textContent?parseInt(F.textContent.replace(" years","").replace(" year","")):5,propertyTaxes:D.dataset.previousValue?parseInt(D.dataset.previousValue):0,heatingCosts:k.dataset.previousValue?parseInt(k.dataset.previousValue):0,condoFees:L.dataset.previousValue?parseInt(L.dataset.previousValue):0,extraPaymentType:r.textContent?r.textContent.toLowerCase():"none",extraPaymentAmount:M.dataset.previousValue?parseInt(M.dataset.previousValue):0,extraPaymentFrequency:V.textContent?V.textContent.toLowerCase():"monthly"},a=(0,i.calculateMortgage)(o),c=(0,i.calculateAdvancedResults)(o);"standard"===s?(q.textContent=`$${a.monthlyPayment.toLocaleString()}`,$.textContent=`$${a.mortgageAmount.toLocaleString()}`,B.textContent=`$${a.mortgageInsurance.toLocaleString()}`,U.textContent=`$${a.principal.toLocaleString()}`,j.textContent=`$${a.interest.toLocaleString()}`,z.textContent=`$${a.termPayments.toLocaleString()}`,G.textContent=`$${a.termPrincipalPaid.toLocaleString()}`,K.textContent=`$${a.termInterestPaid.toLocaleString()}`,H.textContent=`$${a.remainingPrincipalAtEndOfTerm.toLocaleString()}`,S.value=Math.round(a.termPrincipalPaid/a.mortgageAmount*100).toString(),he(S),Q.textContent=`$${a.totalMortgagePlusInterest.toLocaleString()}`,W.textContent=`$${a.totalInterestPaid.toLocaleString()}`,J.textContent=`${a.interestPrincipalRatio}%`,T.value=(100-a.interestPrincipalRatio).toString(),he(T),Y.textContent=F.textContent,X.textContent=R.textContent):(Z.textContent=`$${c.totalMonthlyPayment.toLocaleString()}`,ee.textContent=`$${c.mortgagePayment.toLocaleString()}`,te.textContent=`$${c.propertyTaxesMonthly.toLocaleString()}`,ne.textContent=`$${c.heatingCostsMonthly.toLocaleString()}`,re.textContent=`$${c.condoFeesMonthly.toLocaleString()}`,ie.textContent=`${c.yearsSaved} years`,se.textContent=`$${c.interestSaved.toLocaleString()}`,oe.textContent=`${c.qualifyingRate.toFixed(2)}%`,ae.textContent=`$${c.stressTestPayment.toLocaleString()}`,ce.textContent=`$${c.incomeRequired.toLocaleString()}`)};pe(v,"$","purchase-price"),he(y),pe(b,"%","downpayment-percentage"),pe(w,"$","downpayment"),he(_),pe(I,"%","interest-rate"),he(E),he(S),he(T),pe(D,"$","property-taxes"),he(A),pe(k,"$","heating-costs"),he(N),pe(L,"$","condo-fees"),he(P),pe(M,"$","extra-payments"),me()};const i=n(185),s=r(n(450)),o=r(n(790)),a=r(n(636)),c=r(n(904)),l=r(n(38)),u=r(n(706)),d=r(n(490)),h=r(n(552)),f=r(n(378)),p=r(n(800)),m=r(n(877)),g=r(n(947))},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")),l=r.filter((e=>"housing-indicators"===e.id))[0];let u="";for(let e of l.stats)u+=`\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=u,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">×</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;h=t||"",d=null,s.innerHTML="",f(e)}}))};const s=n(487),o=n(815),a=i(n(757)),c=n(185),l="educational_videos",u=9;let d=null,h="";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,l),(0,o.orderBy)("date","desc"),(0,o.limit)(u));h&&(n=(0,o.query)(n,(0,o.where)("category","==",h))),d&&(n=(0,o.query)(n,(0,o.startAfter)(d)));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)}}})),d=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(!l){const{getFirestore:e}=yield Promise.resolve().then((()=>s(n(815)))),t=(0,a.initializeApp)(c);l=e(t)}return l}))},t.getFirebaseFunctions=function(){return o(this,void 0,void 0,(function*(){if(!u){const{getFunctions:e}=yield Promise.resolve().then((()=>s(n(619)))),t=(0,a.initializeApp)(c);u=e(t)}return u}))};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 l=null,u=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"),l=e.querySelector(".free-guides-form .name-field"),u=e.querySelector(".free-guides-form .email-field"),d=e.querySelector(".free-guides-form #consent-checkbox"),h=e.querySelector(".free-guides-form .submit-button"),f=()=>r(this,void 0,void 0,(function*(){const e=l.value,t=u.value;e&&t&&p(t)?h.classList.remove("disabled"):h.classList.add("disabled")})),p=e=>/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(e);l.addEventListener("change",(e=>{f()})),u.addEventListener("change",(e=>{f()})),d.addEventListener("change",(e=>{f()})),h.addEventListener("click",(e=>r(this,void 0,void 0,(function*(){const e=l.value.trim(),t=u.value.trim(),r=d.checked;try{h.textContent="Processing...",h.disabled=!0,h.classList.toggle("disabled");const a=yield(0,o.getFirebaseFunctions)(),l=(0,s.httpsCallable)(a,"sendGuideEmail"),u=(yield l({name:e,email:t,consent:r,file:"test-1.pdf"})).data;if(u.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{h.textContent="Yes, I want this",h.disabled=!1,h.classList.toggle("disabled");const e=document.createElement("div");e.classList.add("status"),e.classList.add("error"),e.textContent=u.message,n.appendChild(e)}}catch(e){h.textContent="Yes, I want this",h.disabled=!1,h.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">×</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;h(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 h(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),l="market_trend_videos",u=9;let d=null;function h(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,l),(0,o.orderBy)("date","desc"),(0,o.limit)(u));d&&(n=(0,o.query)(n,(0,o.startAfter)(d)));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)}}})),d=r.docs[r.docs.length-1],!0)}catch(e){return console.error("Error loading trending videos:",e),!1}}))}},117:function(e,t,n){"use strict";var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.initMortgageCalculator=function(e,t){const n=`\n <div class="calculator-input mortgage-calculator-input">\n <div class="header">\n <div class="title-wrapper">\n <div class="title">Mortgage Calculator</div>\n </div>\n </div>\n <div class="input-fields">\n <div class="input-field purchase-price">\n <div class="field-label">Mortgage Amount</div>\n <input type="text" value="$ 500,000" data-previous-value="500000" class="value-input">\n <input type="range" min="0" max="2000000" value="500000" step="10000" class="slider">\n </div>\n <div class="dropdown inline payment-frequency">\n <div class="dropdown-field inline-label">\n <div class="field-label">Payment Frequency</div>\n <span>Monthly</span>\n <img class="info-icon" src="${c.default}" alt="Dropdown icon"/>\n </div>\n <div class="dropdown-opts payment-frequency-dd">\n <div class="dropdown-opt">Monthly</div>\n <div class="dropdown-opt">Bi-Weekly</div>\n <div class="dropdown-opt">Weekly</div>\n </div>\n </div>\n </div>\n </div>\n\n \n <div class="calculator-input mortgage-calculator-input">\n <div class="header stacked">\n <div class="title-wrapper">\n <img src="${s.default}" alt="Rate icon"/>\n <div class="title">Rate</div>\n </div>\n <div class="mortgage-calculator-info">Your mortgage interest rate can either be Fixed for the term or Variable (which changes with the prime rate). The Rate Term is the contract length with a lender.</div>\n </div>\n <div class="input-fields">\n <div class="input-field interest-rate">\n <div class="title-selector-wrapper">\n <div class="field-label">Rate</div>\n <div class="fixed-variable-selector">\n <div class="selector">Fixed</div>\n <div class="selector active">Variable</div>\n </div>\n </div>\n <input type="text" value="6.00%" data-previous-value="6.00" class="value-input">\n <input type="range" min="1" max="10" value="6" step="0.1" class="slider">\n </div>\n <div class="dropdown inline term-length">\n <div class="dropdown-field inline-label">\n <div class="field-label">Rate Term</div>\n <span>5 years</span>\n <img class="info-icon" src="${c.default}" alt="Dropdown icon"/> \n </div>\n <div class="dropdown-opts">\n <div class="dropdown-opt">1 year</div>\n <div class="dropdown-opt">2 years</div>\n <div class="dropdown-opt">3 years</div>\n <div class="dropdown-opt">4 years</div>\n <div class="dropdown-opt">5 years</div>\n <div class="dropdown-opt">7 years</div>\n <div class="dropdown-opt">10 years</div>\n </div>\n </div>\n </div>\n </div>\n\n <div class="calculator-input mortgage-calculator-input">\n <div class="header stacked">\n <div class="title-wrapper">\n <img src="${a.default}" alt="Amortization icon"/>\n <div class="title">Amortization</div>\n </div>\n <div class="mortgage-calculator-info">Amortization is the total time it takes to pay off your mortgage in full. New mortgages usually start with an amortization of 25 years or 30 years in Canada.</div>\n </div>\n <div class="input-fields single-field">\n <div class="input-field amortization">\n <div class="field-label">Amortization</div>\n <input type="text" value="25 Years" data-previous-value="25" class="value-input">\n <input type="range" min="1" max="40" value="25" step="1" class="slider">\n </div>\n </div>\n </div>\n\n <div class="calculator-input mortgage-calculator-input">\n <div class="header stacked">\n <div class="title-wrapper">\n <img src="${o.default}" alt="Pay your mortgage faster icon"/>\n <div class="title">Pay your mortgage faster</div>\n </div>\n <div class="mortgage-calculator-info">Increasing your mortgage payments or paying a lump sum towards your principal have a huge impact. You'll pay off your mortgage much sooner and save tons of interest.</div>\n </div>\n <div class="input-fields single-field">\n <div class="input-field payment-increase">\n <div class="field-label">Payment Increase</div>\n <div class="downpayment-percentage-wrapper">\n <input type="text" value="$ 400" data-previous-value="400" class="value-input">\n <input type="text" value="20%" data-previous-value="20" class="percentage-value-input" disabled>\n </div>\n <input type="range" min="0" max="2000" value="400" step="25" class="slider">\n </div>\n <div class="input-field one-time-pre-payment">\n <div class="field-label">One time Pre-Payment</div>\n <input type="text" value="$ 1000" data-previous-value="1000" class="value-input">\n <input type="range" min="0" max="100000" value="1000" step="1000" class="slider">\n </div>\n </div>\n </div>\n `;e.innerHTML=`\n <div class="mortgage-calculator">\n <div class="section-heading">Mortgage Calculator</div>\n <div class="tab-layout">\n <div class="tab-content active">\n <div class="calculator-inputs">\n ${n}\n </div>\n <div class="calculator-results mortgage-calculator-results">\n \n <div class="mortgage-payment">\n <div class="mortgage-payment-wrapper">\n <div class="label">Mortgage Payment</div>\n <div class="value">$2,902</div>\n <div class="frequency">Monthly Payment</div>\n </div>\n </div>\n\n <div class="payment-breakdown">\n <div class="section-label">Payment Breakdown</div>\n <div class="section-wrapper">\n <div class="breakdown-details">\n <div class="breakdown-detail">\n <div class="breakdown-bar-container">\n <div class="breakdown-bar-principal"></div>\n <div class="breakdown-bar-interest"></div>\n </div>\n <div class="principal-paid">\n <div class="icon-name-wrapper">\n <div class="detail-icon principal"></div>\n <div class="detail-name">Principal Paid</div>\n </div>\n <div class="value">$698.59</div>\n </div>\n <div class="interest-paid">\n <div class="icon-name-wrapper">\n <div class="detail-icon interest"></div>\n <div class="detail-name">Interest Paid</div>\n </div>\n <div class="value">$2,587.14</div>\n </div>\n </div>\n <div class="breakdown-total-payment">\n <div class="label">Total payment</div>\n <div class="value">$3,285.72</div>\n </div>\n </div>\n </div>\n </div>\n\n <div class="balance-amortization">\n <div class="section-wrapper">\n <div class="info-row balance">\n <div class="label">Balance end of Term</div>\n <div class="value">$450,996.52</div>\n </div>\n <div class="info-row amortization">\n <div class="label">Effective Amortization</div>\n <div class="value">IO Years 9 Months</div>\n </div>\n <div class="info-row duration">\n <div class="tag">3 MONTHS FASTER</div>\n </div>\n </div>\n </div>\n\n <div class="five-year-breakdown">\n <div class="section-wrapper">\n <div class="sec-heading">Breakdown Over 5 Years</div>\n <div class="info-row">\n <div class="label">Total Paid</div>\n <div class="value">$481,277</div>\n </div>\n <div class="info-row">\n <div class="label">Interest Paid</div>\n <div class="value">$160,562</div>\n </div>\n <div class="info-row">\n <div class="label">Principal Paid</div>\n <div class="value">$320,715</div>\n </div>\n <div class="info-row">\n <div class="label">Balance Remaining</div>\n <div class="value">$479,285</div>\n </div>\n </div>\n </div>\n\n <div class="total-breakdown">\n <div class="section-wrapper">\n <div class="sec-heading">Total Breakdown</div>\n <div class="info-row">\n <div class="label">Total Principal Paid</div>\n <div class="value">$232,688</div>\n </div>\n <div class="info-row">\n <div class="label">Total Interest Paid</div>\n <div class="value">$1,032,688</div>\n </div>\n <div class="info-row">\n <div class="label">Total Cost</div>\n <div class="value">$1,032,688</div>\n </div>\n </div>\n </div>\n\n <div class="savings-with-accelerated-payments">\n <div class="section-wrapper">\n <div class="sec-heading">Total Savings with Accelerated Payments</div>\n <div class="info-wrapper">\n <div class="info-row">\n <div class="label">Interest Savings</div>\n <div class="value">$53,765</div>\n </div>\n <div class="info-row">\n <div class="label">Time Saved</div>\n <div class="value">3 YEARS, 8 MONTHS FASTER</div>\n </div>\n <div class="total-money-saved">\n <div class="btn-label">Total Money Saved</div>\n <div class="btn-value">$6,321</div>\n </div>\n </div>\n </div>\n </div>\n \n </div>\n </div>\n </div>\n </div>\n `;const r=document.querySelector(".purchase-price .value-input"),l=document.querySelector(".purchase-price .slider"),u=document.querySelector(".interest-rate .value-input"),d=document.querySelector(".interest-rate .slider"),h=document.querySelector(".amortization .value-input"),f=document.querySelector(".amortization .slider"),p=document.querySelector(".payment-increase .value-input"),m=document.querySelector(".payment-increase .slider"),g=document.querySelector(".one-time-pre-payment .value-input"),v=document.querySelector(".one-time-pre-payment .slider"),y=document.querySelector(".payment-frequency .dropdown-field span"),w=document.querySelector(".term-length .dropdown-field span"),b=document.querySelector(".mortgage-calculator-results .mortgage-payment .value"),_=document.querySelector(".mortgage-calculator-results .payment-breakdown .principal-paid .value"),I=document.querySelector(".mortgage-calculator-results .payment-breakdown .interest-paid .value"),E=document.querySelector(".mortgage-calculator-results .payment-breakdown .breakdown-total-payment .value"),S=document.querySelector(".mortgage-calculator-results .payment-breakdown .breakdown-bar-principal"),T=document.querySelector(".mortgage-calculator-results .payment-breakdown .breakdown-bar-interest"),x=document.querySelector(".mortgage-calculator-results .balance-amortization .balance .value"),C=document.querySelector(".mortgage-calculator-results .balance-amortization .amortization .value"),D=document.querySelector(".mortgage-calculator-results .balance-amortization .duration .tag"),A=document.querySelector(".mortgage-calculator-results .five-year-breakdown .info-row:nth-of-type(2) .value"),k=document.querySelector(".mortgage-calculator-results .five-year-breakdown .info-row:nth-of-type(3) .value"),N=document.querySelector(".mortgage-calculator-results .five-year-breakdown .info-row:nth-of-type(4) .value"),L=document.querySelector(".mortgage-calculator-results .five-year-breakdown .info-row:nth-of-type(5) .value"),P=document.querySelector(".mortgage-calculator-results .total-breakdown .info-row:nth-of-type(2) .value"),M=document.querySelector(".mortgage-calculator-results .total-breakdown .info-row:nth-of-type(3) .value"),R=document.querySelector(".mortgage-calculator-results .total-breakdown .info-row:nth-of-type(4) .value"),O=document.querySelector(".savings-with-accelerated-payments"),F=document.querySelector(".mortgage-calculator-results .savings-with-accelerated-payments .info-row:nth-of-type(1) .value"),V=document.querySelector(".mortgage-calculator-results .savings-with-accelerated-payments .info-row:nth-of-type(2) .value"),q=document.querySelector(".mortgage-calculator-results .savings-with-accelerated-payments .total-money-saved .btn-value"),$=document.querySelector(".mortgage-calculator-input .payment-increase .percentage-value-input"),B=document.querySelectorAll(".fixed-variable-selector .selector"),U=document.querySelectorAll("[data-tooltip]");function j(e){const t=Number(e.value),n=Number(e.min),r=(t-n)/(Number(e.max)-n)*100;e.style.background=`linear-gradient(to right, #1A4383 ${r}%, #1A43832f ${r}%)`}document.querySelectorAll(".dropdown-opt").forEach((e=>{e.addEventListener("click",(()=>{var t,n;const r=null===(t=e.parentElement)||void 0===t?void 0:t.previousElementSibling,i=null==r?void 0:r.querySelector("span");i&&(i.textContent=e.textContent),null===(n=e.parentElement)||void 0===n||n.classList.remove("expanded"),G()}))})),document.querySelectorAll(".dropdown-field").forEach((e=>{e.addEventListener("click",(t=>{document.querySelectorAll(".dropdown-opts.expanded").forEach((e=>{e.classList.remove("expanded")}));const n=e.nextElementSibling;null==n||n.classList.toggle("expanded"),t.stopPropagation()}))})),document.addEventListener("click",(e=>{e.target.closest(".dropdown")||document.querySelectorAll(".dropdown-opts.expanded").forEach((e=>{e.classList.remove("expanded")}))})),B.forEach(((e,t)=>{e.addEventListener("click",(()=>{B.forEach((e=>e.classList.remove("active"))),e.classList.add("active"),G()}))})),U.forEach((e=>{const t=e.getAttribute("data-tooltip"),n=document.createElement("div");n.className="custom-tooltip",n.textContent=t,document.body.appendChild(n),e.addEventListener("mousemove",(e=>{const t=e;n.style.top=`${t.pageY+20}px`,n.style.left=t.pageX-n.clientWidth/2+"px"})),e.addEventListener("mouseenter",(e=>{n.style.opacity="1",n.style.pointerEvents="none"})),e.addEventListener("mouseleave",(()=>{n.style.opacity="0"}))})),l.addEventListener("input",(()=>{const e=l.value.replace(/[^0-9.]/g,"");r.value=e?`$ ${parseInt(e).toLocaleString("en-US")}`:"",r.dataset.previousValue=e,j(l),G()})),d.addEventListener("input",(()=>{const e=d.value.replace(/[^0-9.]/g,"");u.value=e?`${parseFloat(e).toFixed(2)}%`:"",u.dataset.previousValue=e,j(d),G()})),f.addEventListener("input",(()=>{const e=f.value.replace(/[^0-9.]/g,"");h.value=e?`${parseInt(e).toLocaleString("en-US")} Years`:"",h.dataset.previousValue=e,j(f),G()})),m.addEventListener("input",(()=>{const e=m.value.replace(/[^0-9.]/g,"");p.value=e?`$ ${parseInt(e).toLocaleString("en-US")}`:"",p.dataset.previousValue=e,j(m),G()})),v.addEventListener("input",(()=>{const e=v.value.replace(/[^0-9.]/g,"");g.value=e?`$ ${parseInt(e).toLocaleString("en-US")}`:"",g.dataset.previousValue=e,j(v),G()}));const z=(e,t,n)=>{e.addEventListener("input",(e=>{const r=e.target;if(r){let e=r.value;e=e.replace(/[^0-9.]/g,"");const i=e?parseInt(e):0;switch(n){case"purchase-price":0<=i&&i<=2e6?(l.value=i.toString(),j(l),r.value=`${t} ${parseInt(e).toLocaleString("en-US")}`,r.dataset.previousValue=e):r.dataset.previousValue&&(r.value=`${t} ${parseInt(r.dataset.previousValue).toLocaleString("en-US")}`);break;case"interest-rate":const n=e?parseFloat(e):0;.1<=n&&n<=10?(d.value=n.toFixed(2),j(d),r.value=`${n.toFixed(2)}%`,r.dataset.previousValue=n.toFixed(2)):r.dataset.previousValue&&(r.value=`${parseFloat(r.dataset.previousValue).toFixed(2)}%`);break;case"amortization-period":1<=i&&i<=40?(f.value=i.toString(),j(f),r.value=`${parseInt(e).toLocaleString("en-US")} ${t}`,r.dataset.previousValue=e):r.dataset.previousValue&&(r.value=`${parseInt(r.dataset.previousValue).toLocaleString("en-US")} ${t}`);break;case"payment-increase":0<=i&&i<=2e3?(m.value=i.toString(),j(m),r.value=`${t} ${parseInt(e).toLocaleString("en-US")}`,r.dataset.previousValue=e):r.dataset.previousValue&&(r.value=`${t} ${parseInt(r.dataset.previousValue).toLocaleString("en-US")}`);break;case"one-time-pre-payment":0<=i&&i<=1e5?(v.value=i.toString(),j(v),r.value=`${t} ${parseInt(e).toLocaleString("en-US")}`,r.dataset.previousValue=e):r.dataset.previousValue&&(r.value=`${t} ${parseInt(r.dataset.previousValue).toLocaleString("en-US")}`)}G()}}))},G=()=>{const e=r.dataset.previousValue?parseInt(r.dataset.previousValue):0,t=u.dataset.previousValue?parseFloat(parseFloat(u.dataset.previousValue).toFixed(2)):0,n=h.dataset.previousValue?parseInt(h.dataset.previousValue):1,s=y.textContent?y.textContent.toLowerCase():"monthly",o=p.dataset.previousValue?parseInt(p.dataset.previousValue):0;if(0===o)return 0;const a=t/100,c=a/12,l=12*n;let d;if("monthly"===s)d=e*(c*Math.pow(1+c,l))/(Math.pow(1+c,l)-1);else if("biweekly"===s){const t=a/26,r=26*n;d=e*(t*Math.pow(1+t,r))/(Math.pow(1+t,r)-1)}else{const t=a/52,r=52*n;d=e*(t*Math.pow(1+t,r))/(Math.pow(1+t,r)-1)}const f=o/d*100;$.value=`${f.toFixed(2)}%`,$.dataset.previousValue=f.toFixed(2).toString();const m={loanAmount:e,interestRate:t,rateTerm:w.textContent?parseInt(w.textContent.replace(" years","").replace(" year","")):5,amortization:n,paymentFrequency:s,loanType:"regular",compounding:"semi-annual",paymentIncrease:o,paymentIncreaseType:"dollar",oneTimePrePayment:g.dataset.previousValue?parseInt(g.dataset.previousValue):0,annualPrePayment:0},v=(0,i.calculateMortgage)(m),B=v.principal/v.mortgagePayment*100,U=100-B;b.textContent=v.acceleratedResults?(0,i.formatCurrency)(v.acceleratedResults.adjustedPayment):(0,i.formatCurrency)(v.mortgagePayment),_.textContent=(0,i.formatCurrency)(v.principal),I.textContent=(0,i.formatCurrency)(v.interest),E.textContent=v.acceleratedResults?(0,i.formatCurrency)(v.acceleratedResults.adjustedPayment):(0,i.formatCurrency)(v.mortgagePayment),S.style.width=`${B.toString()}%`,T.style.width=`${U.toString()}%`,x.textContent=(0,i.formatCurrency)(v.balanceEndOfTerm),C.textContent=v.acceleratedResults?`${Math.floor(v.acceleratedResults.payoffYears)} Years ${Math.round(12*(v.acceleratedResults.payoffYears-Math.floor(v.acceleratedResults.payoffYears)))} Months`:`${n||25} Years`,v.acceleratedResults?(D.textContent=v.acceleratedResults.timeSaved,D.style.display="unset"):D.style.display="none",A.textContent=(0,i.formatCurrency)(v.fiveYearBreakdown.totalPaid),k.textContent=(0,i.formatCurrency)(v.fiveYearBreakdown.interestPaid),N.textContent=(0,i.formatCurrency)(v.fiveYearBreakdown.principalPaid),L.textContent=(0,i.formatCurrency)(v.fiveYearBreakdown.balanceRemaining),P.textContent=(0,i.formatCurrency)(v.loanAmount),M.textContent=(0,i.formatCurrency)(v.totalInterest),R.textContent=(0,i.formatCurrency)(v.totalCost),v.acceleratedResults?(F.textContent=(0,i.formatCurrency)(v.acceleratedResults.totalInterestSaved),V.textContent=v.acceleratedResults.timeSaved,q.textContent=(0,i.formatCurrency)(v.acceleratedResults.totalInterestSaved),O.style.display="unset"):O.style.display="none"};z(r,"$","purchase-price"),j(l),z(u,"%","interest-rate"),j(d),z(h,"Years","amortization-period"),j(f),z(p,"$","payment-increase"),j(m),z(g,"$","one-time-pre-payment"),j(v),G()};const i=n(485),s=r(n(953)),o=r(n(92)),a=r(n(904)),c=r(n(38))},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;d(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 d(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"),u=n.textContent?n.textContent:"",l=null,o.classList.remove("show","three-col-layout"),s.innerHTML="",o.innerHTML="",d(e))}))};const i=n(487),s=n(815),o=n(185),a="mortgage_calender",c=9;let l=null,u="Interest Rate";function d(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));u&&(r=(0,s.query)(r,(0,s.where)("category","==",u))),l&&(r=(0,s.query)(r,(0,s.startAfter)(l)));const d=yield(0,s.getDocs)(r);return d.empty?(console.log("No more calendar events to load"),!1):(d.forEach((e=>{var r,i,s,a,c,l,d,h;const f=e.data(),p=document.createElement("div");p.classList.add("calendar-event"),t.classList.remove("show","three-col-layout"),"Interest Rate"===u?(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 ',p.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"===u?(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 ',p.classList.add("three-col-layout"),p.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"===u&&(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 ',p.classList.add("three-col-layout"),p.innerHTML=`\n <div class="calendar-event-col">${null===(l=f.title)||void 0===l?void 0:l.trim()}</div>\n <div class="calendar-event-col date">${(0,o.formatDate)(null===(d=f.release_date)||void 0===d?void 0:d.trim())}</div>\n <div class="calendar-event-col date">${(0,o.formatDate)(null===(h=f.last_published_date)||void 0===h?void 0:h.trim())}</div>\n `),n.appendChild(p)})),l=d.docs[d.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,l),(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 u=Object.keys(c);let d="";u.forEach((e=>{d+=`<div class="alphabet">${e}</div>`})),r.innerHTML=d,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)),l="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;h(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 h(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)),l="mortgage_news",u=9;let d=null;function h(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,l),(0,o.orderBy)("date","desc"),(0,o.limit)(u));d&&(n=(0,o.query)(n,(0,o.startAfter)(d)));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)})),d=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;u(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 u(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 l=null;function u(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));l&&(n=(0,s.query)(n,(0,s.startAfter)(l)));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)})),l=r.docs[r.docs.length-1],!0)}catch(e){return console.error("Error loading research articles:",e),!1}}))}},485:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.formatCurrency=function(e){return new Intl.NumberFormat("en-CA",{style:"currency",currency:"CAD",minimumFractionDigits:0,maximumFractionDigits:0}).format(e)},t.formatCurrencyDecimal=function(e){return new Intl.NumberFormat("en-CA",{style:"currency",currency:"CAD",minimumFractionDigits:2,maximumFractionDigits:2}).format(e)},t.formatNumber=function(e){return new Intl.NumberFormat("en-CA").format(e)},t.parseCurrency=function(e){return parseFloat(e.replace(/[,$]/g,""))||0},t.calculateMortgage=function(e){const t=e.loanAmount;let n;const r=e.interestRate/100;switch(e.compounding){case"semi-annual":default:n=Math.pow(1+r/2,1/6)-1;break;case"monthly":n=r/12;break;case"quarterly":n=Math.pow(1+r/4,1/3)-1;break;case"daily":n=Math.pow(1+r/365,365/12)-1;break;case"weekly":n=Math.pow(1+r/52,52/12)-1;break;case"bi-weekly":n=Math.pow(1+r/26,26/12)-1}const i=12*e.amortization;let s;s="interest-only"===e.loanType?t*n:0===n?t/i:t*(n*Math.pow(1+n,i))/(Math.pow(1+n,i)-1);const o=t*n,a=s-o;let c=t;const l=12*e.rateTerm;for(let e=0;e<l;e++){const e=s-c*n;if(c=Math.max(0,c-e),c<=0)break}let u=t,d=0,h=0;const f=Math.min(60,i);for(let e=0;e<f;e++){const e=u*n,t=s-e;if(u=Math.max(0,u-t),d+=e,h+=t,u<=0)break}const p=d+h,m=s*i-t,g=t+m;let v;if(e.paymentIncrease>0||e.oneTimePrePayment>0||e.annualPrePayment>0){const r=s+e.paymentIncrease;let o=t,a=0,c=0,u=!1;for(;o>.01&&c<2*i;){c++;const t=o*n;let i=r;if(!u&&c<=12&&e.oneTimePrePayment>0&&(i+=e.oneTimePrePayment,u=!0),c%12==0&&c>=12&&e.annualPrePayment>0&&(i+=e.annualPrePayment),o-=Math.min(i-t,o),a+=t,o<=0)break}const d=c/12,h=e.amortization-d,f=Math.floor(h),p=Math.round(12*(h-f)),g=m-a,y=[],w=(new Date).getFullYear();let b=t,_=t,I=0,E=0,S=!1;for(let t=0;t<=25;t+=5){const i=12*t;for(;I<i&&b>.01;){const e=s-b*n;b=Math.max(0,b-e),I++}for(;E<i&&_>.01;){E++;const t=_*n;let i=r;!S&&E<=12&&e.oneTimePrePayment>0&&(i+=e.oneTimePrePayment,S=!0),E%12==0&&e.annualPrePayment>0&&(i+=e.annualPrePayment);const s=Math.min(i-t,_);_=Math.max(0,_-s)}y.push({year:w+t,regularBalance:b,acceleratedBalance:_})}let T=t,x=0,C=0,D=0,A=!1;for(let t=0;t<Math.min(60,i);t++){const i=T*n;let s=r;!A&&t<12&&e.oneTimePrePayment>0&&(s+=e.oneTimePrePayment,A=!0),(t+1)%12==0&&t+1>=12&&e.annualPrePayment>0&&(s+=e.annualPrePayment);const o=Math.min(s-i,T);if(T=Math.max(0,T-o),x+=i,C+=o,D+=s,T<=0)break}let k=t,N=!1;for(let t=0;t<l;t++){const i=k*n;let s=r;!N&&t<12&&e.oneTimePrePayment>0&&(s+=e.oneTimePrePayment,N=!0),(t+1)%12==0&&t+1>=12&&e.annualPrePayment>0&&(s+=e.annualPrePayment);const o=Math.min(s-i,k);if(k=Math.max(0,k-o),k<=0)break}v={adjustedPayment:r,payoffYears:d,totalInterestSaved:g,timeSaved:f>0?`${f} YEARS, ${p} MONTHS FASTER`:`${p} MONTHS FASTER`,balanceComparison:y};const L=t*n;return{mortgagePayment:r,principal:r-L,interest:L,totalInterest:a,totalCost:t+a,loanAmount:t,balanceEndOfTerm:k,fiveYearBreakdown:{totalPaid:D,interestPaid:x,principalPaid:C,balanceRemaining:T},acceleratedResults:v}}return{mortgagePayment:s,principal:a,interest:o,totalInterest:m,totalCost:g,loanAmount:t,balanceEndOfTerm:c,fiveYearBreakdown:{totalPaid:p,interestPaid:d,principalPaid:h,balanceRemaining:u},acceleratedResults:v}}},185:(e,t)=>{"use strict";function n(e){const t=e.purchasePrice-e.downPaymentAmount;let n=0;if(e.downPaymentPercentage<20){let r=0;e.downPaymentPercentage>=15?r=.028:e.downPaymentPercentage>=10?r=.031:e.downPaymentPercentage>=5&&(r=.04),n=t*r}const r=t+n,i=e.interestRate/100/2,s=Math.pow(1+i,2/12)-1,o=12*e.amortizationPeriod,a=12*e.termLength,c=r*(s*Math.pow(1+s,o))/(Math.pow(1+s,o)-1),l=c*o,u=l-r,d=r*s,h=c-d,f=Math.round(u/r*100),p=c*a,m=function(e,t,n,r){return e*Math.pow(1+t,r)-n*(Math.pow(1+t,r)-1)/t}(r,s,c,a),g=r-m,v=p-g;return{monthlyPayment:Math.round(c),mortgageAmount:Math.round(t),mortgageInsurance:Math.round(n),principal:Math.round(h),interest:Math.round(d),totalMortgagePlusInterest:Math.round(l),totalInterestPaid:Math.round(u),interestPrincipalRatio:f,termPayments:Math.round(p),termPrincipalPaid:Math.round(g),termInterestPaid:Math.round(v),remainingPrincipalAtEndOfTerm:Math.round(m)}}Object.defineProperty(t,"__esModule",{value:!0}),t.defaultMortgageData=void 0,t.calculateMortgage=n,t.calculateAdvancedResults=function(e){const t=n(e),r=Math.round(e.propertyTaxes/12),i=Math.round(e.heatingCosts/12),s=e.condoFees,o=t.monthlyPayment+r+i+s;let a=0,c=0;if("none"!==e.extraPaymentType&&e.extraPaymentAmount>0){const n="monthly"===e.extraPaymentFrequency?12*e.extraPaymentAmount:e.extraPaymentAmount;a=Math.min(Math.round(n*e.amortizationPeriod/t.mortgageAmount),e.amortizationPeriod-1),c=Math.round(12*a*t.interest)}const l=Math.max(e.interestRate+2,5.25),u=l/100/2,d=Math.pow(1+u,2/12)-1,h=12*e.amortizationPeriod,f=(e.purchasePrice-e.downPaymentAmount)*(d*Math.pow(1+d,h))/(Math.pow(1+d,h)-1),p=12*f+e.propertyTaxes+e.heatingCosts+12*e.condoFees,m=Math.round(p/.32);return{totalMonthlyPayment:Math.round(o),mortgagePayment:t.monthlyPayment,propertyTaxesMonthly:r,heatingCostsMonthly:i,condoFeesMonthly:s,yearsSaved:a,interestSaved:c,qualifyingRate:l,stressTestPayment:Math.round(f),incomeRequired:m}},t.formatDate=function(e){const t=new Date(e);return new Intl.DateTimeFormat("en-US",{month:"long",day:"numeric",year:"numeric"}).format(t)},t.defaultMortgageData={purchasePrice:5e5,downPaymentAmount:1e5,downPaymentPercentage:20,interestRate:4.75,amortizationPeriod:25,paymentFrequency:"monthly",rateType:"fixed",termLength:5,propertyTaxes:3600,heatingCosts:1200,condoFees:0,extraPaymentType:"none",extraPaymentAmount:0,extraPaymentFrequency:"monthly"}},904:(e,t,n)=>{"use strict";e.exports=n.p+"ec59ff28ecbf77d31249.svg"},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"},800:(e,t,n)=>{"use strict";e.exports=n.p+"ec67e568eccf383cda9e.svg"},790:(e,t,n)=>{"use strict";e.exports=n.p+"81149ed26f2beeb606db.svg"},38:(e,t,n)=>{"use strict";e.exports=n.p+"1d67c5fb9d42f53718b2.svg"},877:(e,t,n)=>{"use strict";e.exports=n.p+"bd4ffa72a63f585acc95.svg"},765:(e,t,n)=>{"use strict";e.exports=n.p+"d686a45650560ddaa773.svg"},378:(e,t,n)=>{"use strict";e.exports=n.p+"a630985df1564d70133d.svg"},947:(e,t,n)=>{"use strict";e.exports=n.p+"1405b9b234fc3159c8f5.svg"},636:(e,t,n)=>{"use strict";e.exports=n.p+"a5f2f91315fae21adce3.svg"},92:(e,t,n)=>{"use strict";e.exports=n.p+"6f14f50227dba9b6de9c.svg"},490:(e,t,n)=>{"use strict";e.exports=n.p+"30b99c60fafb65be19cd.svg"},757:(e,t,n)=>{"use strict";e.exports=n.p+"dec0b8717bf0d582857b.svg"},552:(e,t,n)=>{"use strict";e.exports=n.p+"e3ef864cb6d9c860c30e.svg"},450:(e,t,n)=>{"use strict";e.exports=n.p+"91153cd53d2ed08a0a2e.svg"},953:(e,t,n)=>{"use strict";e.exports=n.p+"3e74f701b4efddab859b.svg"},706:(e,t,n)=>{"use strict";e.exports=n.p+"dafac920656692f6c6be.svg"},148:(e,t,n)=>{"use strict";n.r(t),n.d(t,{deleteDB:()=>g,openDB:()=>m,unwrap:()=>p,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,l=new WeakMap,u=new WeakMap;let d={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 h(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(p(this),e),f(o.get(this))}:function(...e){return f(t.apply(p(this),e))}:function(e,...n){const r=t.call(p(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,d):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((()=>{})),u.set(t,e),t}(e);if(l.has(e))return l.get(e);const t=h(e);return t!==e&&(l.set(e,t),u.set(t,e)),t}const p=e=>u.get(e);function m(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 g(e,{blocked:t}={}){const n=indexedDB.deleteDatabase(e);return t&&n.addEventListener("blocked",(e=>t(e.oldVersion,e))),f(n).then((()=>{}))}const v=["get","getKey","getAll","getAllKeys","count"],y=["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=y.includes(n);if(!(n in(r?IDBIndex:IDBObjectStore).prototype)||!i&&!v.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 _;_=d,d={..._,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,r;const p=document.getElementById(e.containerId);if(p)switch(e.product){case"calculator":(0,t.initCalculator)(p,(null===(n=e.options)||void 0===n?void 0:n.applyUrl)||"");break;case"mortgage-calculator":(0,i.initMortgageCalculator)(p,(null===(r=e.options)||void 0===r?void 0:r.applyUrl)||"");break;case"cockpit":(0,d.initCockpit)(p);break;case"educational-videos":(0,u.initEducationalVideos)(p);break;case"faqs":(0,o.initFaqs)(p);break;case"free-guides":(0,h.initFreeGuides)(p);break;case"market-trend-videos":(0,s.initMarketTrendVideos)(p);break;case"mortgage-calender":(0,f.initMortgageCalendar)(p);break;case"mortgage-glossary":(0,l.initMortgageGlossary)(p);break;case"mortgage-news":(0,c.initMortgageNews)(p);break;case"research-articles":(0,a.initResearchArticles)(p);break;default:console.error(`Unknown product: ${e.product}`)}else console.error("Container not found")},n(264);const t=n(846),i=n(117),s=n(137),o=n(987),a=n(659),c=n(242),l=n(533),u=n(260),d=n(958),h=n(536),f=n(0)})(),r})()));
|
3
3
|
//# sourceMappingURL=index.js.map
|