/**
 * Skipped minification because the original files appears to be already minified.
 * Original file: /npm/mortgage-calculator-package@2.7.1/dist/index.js
 *
 * Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files
 */
/*! For license information please see index.js.LICENSE.txt */
!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={6199:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(5319),s=n(5844),i=n(6336),a=n(6148);class o{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 l="@firebase/app",c="0.10.17",u=new s.Logger("@firebase/app"),d="@firebase/app-compat",h="@firebase/analytics-compat",p="@firebase/analytics",f="@firebase/app-check-compat",m="@firebase/app-check",v="@firebase/auth",g="@firebase/auth-compat",y="@firebase/database",w="@firebase/data-connect",b="@firebase/database-compat",S="@firebase/functions",x="@firebase/functions-compat",E="@firebase/installations",I="@firebase/installations-compat",_="@firebase/messaging",T="@firebase/messaging-compat",C="@firebase/performance",A="@firebase/performance-compat",D="@firebase/remote-config",k="@firebase/remote-config-compat",L="@firebase/storage",M="@firebase/storage-compat",N="@firebase/firestore",P="@firebase/vertexai",R="@firebase/firestore-compat",V="firebase",O="[DEFAULT]",$={[l]:"fire-core",[d]:"fire-core-compat",[p]:"fire-analytics",[h]:"fire-analytics-compat",[m]:"fire-app-check",[f]:"fire-app-check-compat",[v]:"fire-auth",[g]:"fire-auth-compat",[y]:"fire-rtdb",[w]:"fire-data-connect",[b]:"fire-rtdb-compat",[S]:"fire-fn",[x]:"fire-fn-compat",[E]:"fire-iid",[I]:"fire-iid-compat",[_]:"fire-fcm",[T]:"fire-fcm-compat",[C]:"fire-perf",[A]:"fire-perf-compat",[D]:"fire-rc",[k]:"fire-rc-compat",[L]:"fire-gcs",[M]:"fire-gcs-compat",[N]:"fire-fst",[R]:"fire-fst-compat",[P]:"fire-vertex","fire-js":"fire-js",[V]:"fire-js-all"},F=new Map,q=new Map,U=new Map;function B(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(U.has(t))return u.debug(`There were multiple attempts to register component ${t}.`),!1;U.set(t,e);for(const t of F.values())B(t,e);for(const t of q.values())B(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 i.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 s=void 0!==t.automaticDataCollectionEnabled&&t.automaticDataCollectionEnabled,i={name:n,automaticDataCollectionEnabled:s};void 0!==e.apiKey?super(e,i,r):super(e.options,i,r),this._serverConfig=Object.assign({automaticDataCollectionEnabled:s},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,J(l,c,"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(){Y(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 s=Object.assign({name:O,automaticDataCollectionEnabled:!1},t),a=s.name;if("string"!=typeof a||!a)throw K.create("bad-app-name",{appName:String(a)});if(n||(n=i.getDefaultAppConfig()),!n)throw K.create("no-options");const o=F.get(a);if(o){if(i.deepEqual(n,o.options)&&i.deepEqual(s,o.config))return o;throw K.create("duplicate-app",{appName:a})}const l=new r.ComponentContainer(a);for(const e of U.values())l.addComponent(e);const c=new H(n,s,l);return F.set(a,c),c}async function Y(e){let t=!1;const n=e.name;F.has(n)?(t=!0,F.delete(n)):q.has(n)&&e.decRefCount()<=0&&(q.delete(n),t=!0),t&&(await Promise.all(e.container.getProviders().map((e=>e.delete()))),e.isDeleted=!0)}function J(e,t,n){var s;let i=null!==(s=$[e])&&void 0!==s?s:e;n&&(i+=`-${n}`);const a=i.match(/\s|\//),o=t.match(/\s|\//);if(a||o){const e=[`Unable to register library "${i}" with version "${t}":`];return a&&e.push(`library name "${i}" contains illegal characters (whitespace or "/")`),a&&o&&e.push("and"),o&&e.push(`version name "${t}" contains illegal characters (whitespace or "/")`),void u.warn(e.join(" "))}j(new r.Component(`${i}-version`,(()=>({library:i,version:t})),"VERSION"))}const X="firebase-heartbeat-store";let Z=null;function ee(){return Z||(Z=a.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 i.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 ie(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=se();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=se(),{heartbeatsToSend:n,unsentEntries:r}=function(e,t=1024){const n=[];let r=e.slice();for(const s of e){const e=n.find((e=>e.agent===s.agent));if(e){if(e.dates.push(s.date),ae(n)>t){e.dates.pop();break}}else if(n.push({agent:s.agent,dates:[s.date]}),ae(n)>t){n.pop();break}r=r.slice(1)}return{heartbeatsToSend:n,unsentEntries:r}}(this._heartbeatsCache.heartbeats),s=i.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)),s}catch(e){return u.warn(e),""}}}function se(){return(new Date).toISOString().substring(0,10)}class ie{constructor(e){this.app=e,this._canUseIndexedDBPromise=this.runIndexedDBEnvironmentCheck()}async runIndexedDBEnvironmentCheck(){return!!i.isIndexedDBAvailable()&&i.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 i.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 ae(e){return i.base64urlEncodeWithoutPadding(JSON.stringify({version:2,heartbeats:e})).length}j(new r.Component("platform-logger",(e=>new o(e)),"PRIVATE")),j(new r.Component("heartbeat",(e=>new re(e)),"PRIVATE")),J(l,c,"node"),J(l,c,"cjs2017"),J("fire-js",""),Object.defineProperty(t,"FirebaseError",{enumerable:!0,get:function(){return i.FirebaseError}}),t.SDK_VERSION="11.1.0",t._DEFAULT_ENTRY_NAME=O,t._addComponent=B,t._addOrOverwriteComponent=function(e,t){e.container.addOrOverwriteComponent(t)},t._apps=F,t._clearComponents=function(){U.clear()},t._components=U,t._getProvider=z,t._isFirebaseApp=G,t._isFirebaseServerApp=function(e){return void 0!==e.settings},t._registerComponent=j,t._removeServiceInstance=function(e,t,n=O){z(e,t).clearInstance(n)},t._serverApps=q,t.deleteApp=Y,t.getApp=function(e=O){const t=F.get(e);if(!t&&e===O&&i.getDefaultAppConfig())return W();if(!t)throw K.create("no-app",{appName:e});return t},t.getApps=function(){return Array.from(F.values())},t.initializeApp=W,t.initializeServerApp=function(e,t){if(i.isBrowser()&&!i.isWebWorker())throw K.create("invalid-server-app-environment");let n;void 0===t.automaticDataCollectionEnabled&&(t.automaticDataCollectionEnabled=!1),n=G(e)?e.options:e;const s=Object.assign(Object.assign({},t),n);if(void 0!==s.releaseOnDeref&&delete s.releaseOnDeref,void 0!==t.releaseOnDeref&&"undefined"==typeof FinalizationRegistry)throw K.create("finalization-registry-not-supported",{});const a=""+(o=JSON.stringify(s),[...o].reduce(((e,t)=>Math.imul(31,e)+t.charCodeAt(0)|0),0));var o;const l=q.get(a);if(l)return l.incRefCount(t.releaseOnDeref),l;const c=new r.ComponentContainer(a);for(const e of U.values())c.addComponent(e);const u=new Q(n,t,a,c);return q.set(a,u),u},t.onLog=function(e,t){if(null!==e&&"function"!=typeof e)throw K.create("invalid-log-argument");s.setUserLogHandler(e,t)},t.registerVersion=J,t.setLogLevel=function(e){s.setLogLevel(e)}},5319:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(6336);const s="[DEFAULT]";class i{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:s})}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=s){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=s){return this.instances.has(e)}getOptions(e=s){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),s=null!==(n=this.onInitCallbacks.get(r))&&void 0!==n?n:new Set;s.add(e),this.onInitCallbacks.set(r,s);const i=this.instances.get(r);return i&&e(i,r),()=>{s.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===s?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=s){return this.component?this.component.multipleInstances?e:s: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 i(e,this);return this.providers.set(e,t),t}getProviders(){return Array.from(this.providers.values())}},t.Provider=i},1241:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(6199),s=n(5319),i=n(5844),a=n(6336),o=n(860),l=n(4832);const c="@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 i.Logger("@firebase/firestore");function p(){return h.logLevel}function f(e,...t){if(h.logLevel<=i.LogLevel.DEBUG){const n=t.map(g);h.debug(`Firestore (${d}): ${e}`,...n)}}function m(e,...t){if(h.logLevel<=i.LogLevel.ERROR){const n=t.map(g);h.error(`Firestore (${d}): ${e}`,...n)}}function v(e,...t){if(h.logLevel<=i.LogLevel.WARN){const n=t.map(g);h.warn(`Firestore (${d}): ${e}`,...n)}}function g(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 S={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 x extends a.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 I{constructor(e,t){this.user=t,this.type="OAuth",this.headers=new Map,this.headers.set("Authorization",`Bearer ${e}`)}}class _{getToken(){return Promise.resolve(null)}invalidateToken(){}start(e,t){e.enqueueRetryable((()=>t(u.UNAUTHENTICATED)))}shutdown(){}}class T{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 s=new E;this.o=()=>{this.i++,this.currentUser=this.u(),s.resolve(),s=new E,e.enqueueRetryable((()=>r(this.currentUser)))};const i=()=>{const t=s;e.enqueueRetryable((async()=>{await t.promise,await r(this.currentUser)}))},a=e=>{f("FirebaseAuthCredentialsProvider","Auth detected"),this.auth=e,this.o&&(this.auth.addAuthTokenListener(this.o),i())};this.t.onInit((e=>a(e))),setTimeout((()=>{if(!this.auth){const e=this.t.getImmediate({optional:!0});e?a(e):(f("FirebaseAuthCredentialsProvider","Auth not yet detected"),s.resolve(),s=new E)}}),0),i()}getToken(){const e=this.i,t=this.forceRefresh;return this.forceRefresh=!1,this.auth?this.auth.getToken(t).then((t=>this.i!==e?(f("FirebaseAuthCredentialsProvider","getToken aborted due to token change."),this.getToken()):t?(w("string"==typeof t.accessToken),new I(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 A{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 D{constructor(e,t,n){this.l=e,this.h=t,this.P=n}getToken(){return Promise.resolve(new A(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 L{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&&f("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,f("FirebaseAppCheckTokenProvider",`Received ${n?"new":"existing"} token.`),n?t(e.token):Promise.resolve()};this.o=t=>{e.enqueueRetryable((()=>n(t)))};const r=e=>{f("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):f("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 M(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 N{static newId(){const e=62*Math.floor(256/62);let t="";for(;t.length<20;){const n=M(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 R(e,t,n){return e.length===t.length&&e.every(((e,r)=>n(e,t[r])))}function V(e){return e+"\0"}class O{static now(){return O.fromMillis(Date.now())}static fromDate(e){return O.fromMillis(e.getTime())}static fromMillis(e){const t=Math.floor(e/1e3),n=Math.floor(1e6*(e-1e3*t));return new O(t,n)}constructor(e,t){if(this.seconds=e,this.nanoseconds=t,t<0)throw new x(S.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+t);if(t>=1e9)throw new x(S.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+t);if(e<-62135596800)throw new x(S.INVALID_ARGUMENT,"Timestamp seconds out of range: "+e);if(e>=253402300800)throw new x(S.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 ${static fromTimestamp(e){return new $(e)}static min(){return new $(new O(0,0))}static max(){return new $(new O(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 F{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===F.comparator(this,e)}child(e){const t=this.segments.slice(this.offset,this.limit());return e instanceof F?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),s=t.get(r);if(n<s)return-1;if(n>s)return 1}return e.length<t.length?-1:e.length>t.length?1:0}}class q extends F{construct(e,t,n){return new q(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 x(S.INVALID_ARGUMENT,`Invalid segment (${n}). Paths must not contain // in them.`);t.push(...n.split("/").filter((e=>e.length>0)))}return new q(t)}static emptyPath(){return new q([])}}const U=/^[_a-zA-Z][_a-zA-Z0-9]*$/;class B extends F{construct(e,t,n){return new B(e,t,n)}static isValidIdentifier(e){return U.test(e)}canonicalString(){return this.toArray().map((e=>(e=e.replace(/\\/g,"\\\\").replace(/`/g,"\\`"),B.isValidIdentifier(e)||(e="`"+e+"`"),e))).join(".")}toString(){return this.canonicalString()}isKeyField(){return 1===this.length&&"__name__"===this.get(0)}static keyField(){return new B(["__name__"])}static fromServerFormat(e){const t=[];let n="",r=0;const s=()=>{if(0===n.length)throw new x(S.INVALID_ARGUMENT,`Invalid field path (${e}). Paths must not be empty, begin with '.', end with '.', or contain '..'`);t.push(n),n=""};let i=!1;for(;r<e.length;){const t=e[r];if("\\"===t){if(r+1===e.length)throw new x(S.INVALID_ARGUMENT,"Path has trailing escape character: "+e);const t=e[r+1];if("\\"!==t&&"."!==t&&"`"!==t)throw new x(S.INVALID_ARGUMENT,"Path has invalid escape sequence: "+e);n+=t,r+=2}else"`"===t?(i=!i,r++):"."!==t||i?(n+=t,r++):(s(),r++)}if(s(),i)throw new x(S.INVALID_ARGUMENT,"Unterminated ` in path: "+e);return new B(t)}static emptyPath(){return new B([])}}class j{constructor(e){this.path=e}static fromPath(e){return new j(q.fromString(e))}static fromName(e){return new j(q.fromString(e).popFirst(5))}static empty(){return new j(q.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===q.comparator(this.path,e.path)}toString(){return this.path.toString()}static comparator(e,t){return q.comparator(e.path,t.path)}static isDocumentKey(e){return e.length%2==0}static fromSegments(e){return new j(new q(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=B.comparator(e.fieldPath,t.fieldPath);return 0!==n?n:P(e.kind,t.kind)}class Y{constructor(e,t){this.sequenceNumber=e,this.offset=t}static empty(){return new Y(0,Z.min())}}function J(e,t){const n=e.toTimestamp().seconds,r=e.toTimestamp().nanoseconds+1,s=$.fromTimestamp(1e9===r?new O(n+1,0):new O(n,r));return new Z(s,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($.min(),j.empty(),-1)}static max(){return new Z($.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!==S.FAILED_PRECONDITION||e.message!==te)throw e;f("LocalStore","Unexpectedly lost primary lease")}class se{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 se(((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 se?t:se.resolve(t)}catch(e){return se.reject(e)}}wrapSuccess(e,t){return e?this.wrapUserFunction((()=>e(t))):se.resolve(t)}wrapFailure(e,t){return e?this.wrapUserFunction((()=>e(t))):se.reject(t)}static resolve(e){return new se(((t,n)=>{t(e)}))}static reject(e){return new se(((t,n)=>{n(e)}))}static waitFor(e){return new se(((t,n)=>{let r=0,s=0,i=!1;e.forEach((e=>{++r,e.next((()=>{++s,i&&s===r&&t()}),(e=>n(e)))})),i=!0,s===r&&t()}))}static or(e){let t=se.resolve(!1);for(const n of e)t=t.next((e=>e?se.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 se(((n,r)=>{const s=e.length,i=new Array(s);let a=0;for(let o=0;o<s;o++){const l=o;t(e[l]).next((e=>{i[l]=e,++a,a===s&&n(i)}),(e=>r(e)))}}))}static doWhile(e,t){return new se(((n,r)=>{const s=()=>{!0===e()?t().next((()=>{s()}),r):n()};s()}))}}class ie{static open(e,t,n,r){try{return new ie(t,e.transaction(r,n))}catch(e){throw new ce(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 ce(e,t.error)):this.V.resolve()},this.transaction.onerror=t=>{const n=fe(t.target.error);this.V.reject(new ce(e,n))}}get m(){return this.V.promise}abort(e){e&&this.V.reject(e),this.aborted||(f("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 ae{static delete(e){return f("SimpleDb","Removing database:",e),he(window.indexedDB.deleteDatabase(e)).toPromise()}static p(){if(!a.isIndexedDBAvailable())return!1;if(ae.S())return!0;const e=a.getUA(),t=ae.D(e),n=0<t&&t<10,r=oe(e),s=0<r&&r<4.5;return!(e.indexOf("MSIE ")>0||e.indexOf("Trident/")>0||e.indexOf("Edge/")>0||n||s)}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===ae.D(a.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||(f("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 ce(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 x(S.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 x(S.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 ce(e,r))},r.onupgradeneeded=e=>{f("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((()=>{f("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 s="readonly"===t;let i=0;for(;;){++i;try{this.db=await this.M(e);const t=ie.open(this.db,e,s?"readonly":"readwrite",n),i=r(t).next((e=>(t.g(),e))).catch((e=>(t.abort(e),se.reject(e)))).toPromise();return i.catch((()=>{})),await t.m,i}catch(e){const t=e,n="FirebaseError"!==t.name&&i<3;if(f("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 oe(e){const t=e.match(/Android ([\d.]+)/i),n=t?t[1].split(".").slice(0,2).join("."):"-1";return Number(n)}class le{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 ce extends x{constructor(e,t){super(S.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?(f("SimpleDb","PUT",this.store.name,e,t),n=this.store.put(t,e)):(f("SimpleDb","PUT",this.store.name,"<auto-key>",e),n=this.store.put(e)),he(n)}add(e){return f("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),f("SimpleDb","GET",this.store.name,e,t),t)))}delete(e){return f("SimpleDb","DELETE",this.store.name,e),he(this.store.delete(e))}count(){return f("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 se(((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 se(((e,t)=>{n.onerror=e=>{t(e.target.error)},n.onsuccess=t=>{e(t.target.result)}}))}j(e,t){f("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 se(((n,r)=>{t.onerror=e=>{const t=fe(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 se(((r,s)=>{e.onerror=e=>{s(e.target.error)},e.onsuccess=e=>{const s=e.target.result;if(!s)return void r();const i=new le(s),a=t(s.primaryKey,s.value,i);if(a instanceof se){const e=a.catch((e=>(i.done(),se.reject(e))));n.push(e)}i.isDone?r():null===i.K?s.continue():s.continue(i.K)}})).next((()=>se.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 se(((t,n)=>{e.onsuccess=e=>{const n=e.target.result;t(n)},e.onerror=e=>{const t=fe(e.target.error);n(t)}}))}let pe=!1;function fe(e){const t=ae.D(a.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 x("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 pe||(pe=!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){f("IndexBackfiller",`Scheduled in ${e}ms`),this.task=this.asyncQueue.enqueueAfterDelay("index_backfill",e,(async()=>{this.task=null;try{f("IndexBackfiller",`Documents written: ${await this.Z.ee()}`)}catch(e){ue(e)?f("IndexBackfiller","Ignoring IndexedDB error during index backfill: ",e):await re(e)}await this.X(6e4)}))}}class ve{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,s=!0;return se.doWhile((()=>!0===s&&r>0),(()=>this.localStore.indexManager.getNextCollectionGroupToUpdate(e).next((t=>{if(null!==t&&!n.has(t))return f("IndexBackfiller",`Processing collection: ${t}`),this.ne(e,t,r).next((e=>{r-=e,n.add(t)}));s=!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 s=n.changes;return this.localStore.indexManager.updateIndexEntries(e,s).next((()=>this.re(r,n))).next((n=>(f("IndexBackfiller",`Updating offset: ${n}`),this.localStore.indexManager.updateCollectionGroup(e,t,n)))).next((()=>s.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 ge{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 Se(e){let t="";for(let n=0;n<e.length;n++)t.length>0&&(t=Ee(t)),t=xe(e.get(n),t);return Ee(t)}function xe(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 Ie(e){const t=e.length;if(w(t>=2),2===t)return w(""===e.charAt(0)&&""===e.charAt(1)),q.emptyPath();const n=t-2,r=[];let s="";for(let i=0;i<t;){const t=e.indexOf("",i);switch((t<0||t>n)&&y(),e.charAt(t+1)){case"":const n=e.substring(i,t);let a;0===s.length?a=n:(s+=n,a=s,s=""),r.push(a);break;case"":s+=e.substring(i,t),s+="\0";break;case"":s+=e.substring(i,t+1);break;default:y()}i=t+2}return new q(r)}ge.oe=-1;const _e=["userId","batchId"];function Te(e,t){return[e,Se(t)]}function Ce(e,t,n){return[e,Se(t),n]}const Ae={},De=["prefixPath","collectionGroup","readTime","documentId"],ke=["prefixPath","collectionGroup","documentId"],Le=["collectionGroup","readTime","prefixPath","documentId"],Me=["canonicalId","targetId"],Ne=["targetId","path"],Pe=["path","targetId"],Re=["collectionId","parent"],Ve=["indexId","uid"],Oe=["uid","sequenceNumber"],$e=["indexId","uid","arrayValue","directionalValue","orderedDocumentKey","documentKey"],Fe=["indexId","uid","orderedDocumentKey"],qe=["userId","collectionPath","documentId"],Ue=["userId","collectionPath","largestBatchId"],Be=["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 Ye extends ne{constructor(e,t){super(),this._e=e,this.currentSequenceNumber=t}}function Je(e,t){const n=b(e);return ae.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||st.EMPTY}insert(e,t){return new nt(this.comparator,this.root.insert(e,t,this.comparator).copy(null,null,st.BLACK,null,null))}remove(e){return new nt(this.comparator,this.root.remove(e,this.comparator).copy(null,null,st.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 s=1;for(;!e.isEmpty();)if(s=t?n(e.key,t):1,t&&r&&(s*=-1),s<0)e=this.isReverse?e.left:e.right;else{if(0===s){this.nodeStack.push(e);break}this.nodeStack.push(e),e=this.isReverse?e.right:e.left}}getNext(){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 st{constructor(e,t,n,r,s){this.key=e,this.value=t,this.color=null!=n?n:st.RED,this.left=null!=r?r:st.EMPTY,this.right=null!=s?s:st.EMPTY,this.size=this.left.size+1+this.right.size}copy(e,t,n,r,s){return new st(null!=e?e:this.key,null!=t?t:this.value,null!=n?n:this.color,null!=r?r:this.left,null!=s?s: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 s=n(e,r.key);return r=s<0?r.copy(null,null,null,r.left.insert(e,t,n),null):0===s?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 st.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 st.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,st.RED,null,this.right.left);return this.right.copy(null,null,this.color,e,null)}rotateRight(){const e=this.copy(null,null,st.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)}}st.EMPTY=null,st.RED=!0,st.BLACK=!1,st.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,s){return this}insert(e,t,n){return new st(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 it{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 at(this.data.getIterator())}getIteratorFrom(e){return new at(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 it))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 it(this.comparator);return t.data=e,t}}class at{constructor(e){this.iter=e}getNext(){return this.iter.getNext().key}hasNext(){return this.iter.hasNext()}}function ot(e){return e.hasNext()?e.getNext():void 0}class lt{constructor(e){this.fields=e,e.sort(B.comparator)}static empty(){return new lt([])}unionWith(e){let t=new it(B.comparator);for(const e of this.fields)t=t.add(e);for(const n of e)t=t.add(n);return new lt(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 ct 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 ct("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 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:pt(e.seconds),nanos:pt(e.nanos)}}function pt(e){return"number"==typeof e?e:"string"==typeof e?Number(e):0}function ft(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 vt(e){const t=e.mapValue.fields.__previous_value__;return mt(t)?vt(t):t}function gt(e){const t=ht(e.mapValue.fields.__local_write_time__.timestampValue);return new O(t.seconds,t.nanos)}class yt{constructor(e,t,n,r,s,i,a,o,l){this.databaseId=e,this.appId=t,this.persistenceKey=n,this.host=r,this.ssl=s,this.forceLongPolling=i,this.autoDetectLongPolling=a,this.longPollingOptions=o,this.useFetchStreams=l}}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__"}}}},St={nullValue:"NULL_VALUE"};function xt(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:Ft(e)?9007199254740991:Ot(e)?10:11:y()}function Et(e,t){if(e===t)return!0;const n=xt(e);if(n!==xt(t))return!1;switch(n){case 0:case 9007199254740991:return!0;case 1:return e.booleanValue===t.booleanValue;case 4:return gt(e).isEqual(gt(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 ft(e.bytesValue).isEqual(ft(t.bytesValue))}(e,t);case 7:return e.referenceValue===t.referenceValue;case 8:return function(e,t){return pt(e.geoPointValue.latitude)===pt(t.geoPointValue.latitude)&&pt(e.geoPointValue.longitude)===pt(t.geoPointValue.longitude)}(e,t);case 2:return function(e,t){if("integerValue"in e&&"integerValue"in t)return pt(e.integerValue)===pt(t.integerValue);if("doubleValue"in e&&"doubleValue"in t){const n=pt(e.doubleValue),r=pt(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 It(e,t){return void 0!==(e.values||[]).find((e=>Et(e,t)))}function _t(e,t){if(e===t)return 0;const n=xt(e),r=xt(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=pt(e.integerValue||e.doubleValue),r=pt(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 Tt(e.timestampValue,t.timestampValue);case 4:return Tt(gt(e),gt(t));case 5:return P(e.stringValue,t.stringValue);case 6:return function(e,t){const n=ft(e),r=ft(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(pt(e.latitude),pt(t.latitude));return 0!==n?n:P(pt(e.longitude),pt(t.longitude))}(e.geoPointValue,t.geoPointValue);case 9:return Ct(e.arrayValue,t.arrayValue);case 10:return function(e,t){var n,r,s,i;const a=e.fields||{},o=t.fields||{},l=null===(n=a.value)||void 0===n?void 0:n.arrayValue,c=null===(r=o.value)||void 0===r?void 0:r.arrayValue,u=P((null===(s=null==l?void 0:l.values)||void 0===s?void 0:s.length)||0,(null===(i=null==c?void 0:c.values)||void 0===i?void 0:i.length)||0);return 0!==u?u:Ct(l,c)}(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),s=t.fields||{},i=Object.keys(s);r.sort(),i.sort();for(let e=0;e<r.length&&e<i.length;++e){const t=P(r[e],i[e]);if(0!==t)return t;const a=_t(n[r[e]],s[i[e]]);if(0!==a)return a}return P(r.length,i.length)}(e.mapValue,t.mapValue);default:throw y()}}function Tt(e,t){if("string"==typeof e&&"string"==typeof t&&e.length===t.length)return P(e,t);const n=ht(e),r=ht(t),s=P(n.seconds,r.seconds);return 0!==s?s: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=_t(n[e],r[e]);if(t)return t}return P(n.length,r.length)}function At(e){return Dt(e)}function Dt(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 ft(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+=Dt(r);return t+"]"}(e.arrayValue):"mapValue"in e?function(e){const t=Object.keys(e.fields||{}).sort();let n="{",r=!0;for(const s of t)r?r=!1:n+=",",n+=`${s}:${Dt(e.fields[s])}`;return n+"}"}(e.mapValue):y()}function kt(e){switch(xt(e)){case 0:case 1:return 4;case 2:return 8;case 3:case 8:return 16;case 4:const t=vt(e);return t?16+kt(t):16;case 5:return 2*e.stringValue.length;case 6:return ft(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 Lt(e,t){return{referenceValue:`projects/${e.projectId}/databases/${e.database}/documents/${t.path.canonicalString()}`}}function Mt(e){return!!e&&"integerValue"in e}function Nt(e){return!!e&&"arrayValue"in e}function Pt(e){return!!e&&"nullValue"in e}function Rt(e){return!!e&&"doubleValue"in e&&isNaN(Number(e.doubleValue))}function Vt(e){return!!e&&"mapValue"in e}function Ot(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 $t(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]=$t(n))),t}if(e.arrayValue){const t={arrayValue:{values:[]}};for(let n=0;n<(e.arrayValue.values||[]).length;++n)t.arrayValue.values[n]=$t(e.arrayValue.values[n]);return t}return Object.assign({},e)}function Ft(e){return"__max__"===(((e.mapValue||{}).fields||{}).__type__||{}).stringValue}const qt={mapValue:{fields:{__type__:{stringValue:"__vector__"},value:{arrayValue:{}}}}};function Ut(e){return"nullValue"in e?St:"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?Lt(wt.empty(),j.empty()):"geoPointValue"in e?{geoPointValue:{latitude:-90,longitude:-180}}:"arrayValue"in e?{arrayValue:{}}:"mapValue"in e?Ot(e)?qt:{mapValue:{}}:y()}function Bt(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?Lt(wt.empty(),j.empty()):"referenceValue"in e?{geoPointValue:{latitude:-90,longitude:-180}}:"geoPointValue"in e?{arrayValue:{}}:"arrayValue"in e?qt:"mapValue"in e?Ot(e)?{mapValue:{}}:bt:y()}function jt(e,t){const n=_t(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=_t(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)],!Vt(t))return null;return t=(t.mapValue.fields||{})[e.lastSegment()],t||null}}set(e,t){this.getFieldsMap(e.popLast())[e.lastSegment()]=$t(t)}setAll(e){let t=B.emptyPath(),n={},r=[];e.forEach(((e,s)=>{if(!t.isImmediateParentOf(s)){const e=this.getFieldsMap(t);this.applyChanges(e,n,r),n={},r=[],t=s.popLast()}e?n[s.lastSegment()]=$t(e):r.push(s.lastSegment())}));const s=this.getFieldsMap(t);this.applyChanges(s,n,r)}delete(e){const t=this.field(e.popLast());Vt(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)];Vt(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($t(this.value))}}function Kt(e){const t=[];return Ze(e.fields,((e,n)=>{const r=new B([e]);if(Vt(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 lt(t)}class Ht{constructor(e,t,n,r,s,i,a){this.key=e,this.documentType=t,this.version=n,this.readTime=r,this.createTime=s,this.data=i,this.documentState=a}static newInvalidDocument(e){return new Ht(e,0,$.min(),$.min(),$.min(),Gt.empty(),0)}static newFoundDocument(e,t,n,r){return new Ht(e,1,t,$.min(),n,r,0)}static newNoDocument(e,t){return new Ht(e,2,t,$.min(),$.min(),Gt.empty(),0)}static newUnknownDocument(e,t){return new Ht(e,3,t,$.min(),$.min(),Gt.empty(),2)}convertToFoundDocument(e,t){return!this.createTime.isEqual($.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=$.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 s=0;s<e.position.length;s++){const i=t[s],a=e.position[s];if(r=i.field.isKeyField()?j.comparator(j.fromName(a.referenceValue),n.key):_t(a,n.data.field(i.field)),"desc"===i.dir&&(r*=-1),0!==r)break}return r}function Yt(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 Jt{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 vn(e,n):"not-in"===t?new gn(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 pn(e,n)}matches(e){const t=e.data.field(this.field);return"!="===this.op?null!==t&&this.matchesComparison(_t(t,this.value)):null!==t&&xt(this.value)===xt(t)&&this.matchesComparison(_t(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 an(e)&&nn(e)}function an(e){for(const t of e.filters)if(t instanceof tn)return!1;return!0}function on(e){if(e instanceof en)return e.field.canonicalString()+e.op.toString()+At(e.value);if(sn(e))return e.filters.map((e=>on(e))).join(",");{const t=e.filters.map((e=>on(e))).join(",");return`${e.op}(${t})`}}function ln(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&&ln(n,t.filters[r])),!0)}(e,t):void y()}function cn(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} ${At(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=fn(0,t)}matches(e){return this.keys.some((t=>t.isEqual(e.key)))}}class pn extends en{constructor(e,t){super(e,"not-in",t),this.keys=fn(0,t)}matches(e){return!this.keys.some((t=>t.isEqual(e.key)))}}function fn(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 Nt(t)&&It(t.arrayValue,this.value)}}class vn extends en{constructor(e,t){super(e,"in",t)}matches(e){const t=e.data.field(this.field);return null!==t&&It(this.value.arrayValue,t)}}class gn extends en{constructor(e,t){super(e,"not-in",t)}matches(e){if(It(this.value.arrayValue,{nullValue:"NULL_VALUE"}))return!1;const t=e.data.field(this.field);return null!==t&&!It(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!(!Nt(t)||!t.arrayValue.values)&&t.arrayValue.values.some((e=>It(this.value.arrayValue,e)))}}class wn{constructor(e,t=null,n=[],r=[],s=null,i=null,a=null){this.path=e,this.collectionGroup=t,this.orderBy=n,this.filters=r,this.limit=s,this.startAt=i,this.endAt=a,this.ue=null}}function bn(e,t=null,n=[],r=[],s=null,i=null,a=null){return new wn(e,t,n,r,s,i,a)}function Sn(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=>on(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=>At(e))).join(",")),t.endAt&&(e+="|ub:",e+=t.endAt.inclusive?"a:":"b:",e+=t.endAt.position.map((e=>At(e))).join(",")),t.ue=e}return t.ue}function xn(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(!ln(e.filters[n],t.filters[n]))return!1;return e.collectionGroup===t.collectionGroup&&!!e.path.isEqual(t.path)&&!!Yt(e.startAt,t.startAt)&&Yt(e.endAt,t.endAt)}function En(e){return j.isDocumentKey(e.path)&&null===e.collectionGroup&&0===e.filters.length}function In(e,t){return e.filters.filter((e=>e instanceof en&&e.field.isEqual(t)))}function _n(e,t,n){let r=St,s=!0;for(const n of In(e,t)){let e=St,t=!0;switch(n.op){case"<":case"<=":e=Ut(n.value);break;case"==":case"in":case">=":e=n.value;break;case">":e=n.value,t=!1;break;case"!=":case"not-in":e=St}jt({value:r,inclusive:s},{value:e,inclusive:t})<0&&(r=e,s=t)}if(null!==n)for(let i=0;i<e.orderBy.length;++i)if(e.orderBy[i].field.isEqual(t)){const e=n.position[i];jt({value:r,inclusive:s},{value:e,inclusive:n.inclusive})<0&&(r=e,s=n.inclusive);break}return{value:r,inclusive:s}}function Tn(e,t,n){let r=bt,s=!0;for(const n of In(e,t)){let e=bt,t=!0;switch(n.op){case">=":case">":e=Bt(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:s},{value:e,inclusive:t})>0&&(r=e,s=t)}if(null!==n)for(let i=0;i<e.orderBy.length;++i)if(e.orderBy[i].field.isEqual(t)){const e=n.position[i];zt({value:r,inclusive:s},{value:e,inclusive:n.inclusive})>0&&(r=e,s=n.inclusive);break}return{value:r,inclusive:s}}class Cn{constructor(e,t=null,n=[],r=[],s=null,i="F",a=null,o=null){this.path=e,this.collectionGroup=t,this.explicitOrderBy=n,this.filters=r,this.limit=s,this.limitType=i,this.startAt=a,this.endAt=o,this.ce=null,this.le=null,this.he=null,this.startAt,this.endAt}}function An(e,t,n,r,s,i,a,o){return new Cn(e,t,n,r,s,i,a,o)}function Dn(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 Ln(e){return null!==e.collectionGroup}function Mn(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 it(B.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 Jt(r,n))})),e.has(B.keyField().canonicalString())||t.ce.push(new Jt(B.keyField(),n))}return t.ce}function Nn(e){const t=b(e);return t.le||(t.le=Rn(t,Mn(e))),t.le}function Pn(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 Jt(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 Vn(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 On(e,t,n){return new Cn(e.path,e.collectionGroup,e.explicitOrderBy.slice(),e.filters.slice(),t,n,e.startAt,e.endAt)}function $n(e,t){return xn(Nn(e),Nn(t))&&e.limitType===t.limitType}function Fn(e){return`${Sn(Nn(e))}|lt:${e.limitType}`}function qn(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=>At(e))).join(",")),e.endAt&&(t+=", endAt: ",t+=e.endAt.inclusive?"a:":"b:",t+=e.endAt.position.map((e=>At(e))).join(",")),`Target(${t})`}(Nn(e))}; limitType=${e.limitType})`}function Un(e,t){return t.isFoundDocument()&&function(e,t){const n=t.key.path;return null!==e.collectionGroup?t.key.hasCollectionId(e.collectionGroup)&&e.path.isPrefixOf(n):j.isDocumentKey(e.path)?e.path.isEqual(n):e.path.isImmediateParentOf(n)}(e,t)&&function(e,t){for(const n of Mn(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,Mn(e),t)||e.endAt&&!function(e,t,n){const r=Wt(e,t,n);return e.inclusive?r>=0:r>0}(e.endAt,Mn(e),t))}(e,t)}function Bn(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 s of Mn(e)){const e=zn(s,t,n);if(0!==e)return e;r=r||s.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),s=n.data.field(e);return null!==r&&null!==s?_t(r,s):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 Yn(e){let t=Qn;return e.forEach(((e,n)=>t=t.insert(e,n.overlayedDocument))),t}function Jn(){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 it(j.comparator);function nr(...e){let t=tr;for(const n of e)t=t.add(n);return t}const rr=new it(P);function sr(){return rr}function ir(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 ar(e){return{integerValue:""+e}}function or(e,t){return be(t)?ar(t):ir(e,t)}class lr{constructor(){this._=void 0}}function cr(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=vt(t)),t&&(n.fields.__previous_value__=t),{mapValue:n}}(n,t):e instanceof pr?fr(e,t):e instanceof mr?vr(e,t):function(e,t){const n=dr(e,t),r=yr(n)+yr(e.Pe);return Mt(n)&&Mt(e.Pe)?ar(r):ir(e.serializer,r)}(e,t)}function ur(e,t,n){return e instanceof pr?fr(e,t):e instanceof mr?vr(e,t):n}function dr(e,t){return e instanceof gr?function(e){return Mt(e)||function(e){return!!e&&"doubleValue"in e}(e)}(t)?t:{integerValue:0}:null}class hr extends lr{}class pr extends lr{constructor(e){super(),this.elements=e}}function fr(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 lr{constructor(e){super(),this.elements=e}}function vr(e,t){let n=wr(t);for(const t of e.elements)n=n.filter((e=>!Et(e,t)));return{arrayValue:{values:n}}}class gr extends lr{constructor(e,t){super(),this.serializer=e,this.Pe=t}}function yr(e){return pt(e.integerValue||e.doubleValue)}function wr(e){return Nt(e)&&e.arrayValue.values?e.arrayValue.values.slice():[]}class br{constructor(e,t){this.field=e,this.transform=t}}class Sr{constructor(e,t){this.version=e,this.transformResults=t}}class xr{constructor(e,t){this.updateTime=e,this.exists=t}static none(){return new xr}static exists(e){return new xr(void 0,e)}static updateTime(e){return new xr(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 Ir{}function _r(e,t){if(!e.hasLocalMutations||t&&0===t.fields.length)return null;if(null===t)return e.isNoDocument()?new Rr(e.key,xr.none()):new kr(e.key,e.data,xr.none());{const n=e.data,r=Gt.empty();let s=new it(B.comparator);for(let e of t.fields)if(!s.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),s=s.add(e)}return new Lr(e.key,r,new lt(s.toArray()),xr.none())}}function Tr(e,t,n){e instanceof kr?function(e,t,n){const r=e.value.clone(),s=Nr(e.fieldTransforms,t,n.transformResults);r.setAll(s),t.convertToFoundDocument(n.version,r).setHasCommittedMutations()}(e,t,n):e instanceof Lr?function(e,t,n){if(!Er(e.precondition,t))return void t.convertToUnknownDocument(n.version);const r=Nr(e.fieldTransforms,t,n.transformResults),s=t.data;s.setAll(Mr(e)),s.setAll(r),t.convertToFoundDocument(n.version,s).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 s=e.value.clone(),i=Pr(e.fieldTransforms,r,t);return s.setAll(i),t.convertToFoundDocument(t.version,s).setHasLocalMutations(),null}(e,t,n,r):e instanceof Lr?function(e,t,n,r){if(!Er(e.precondition,t))return n;const s=Pr(e.fieldTransforms,r,t),i=t.data;return i.setAll(Mr(e)),i.setAll(s),t.convertToFoundDocument(t.version,i).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 Ar(e,t){let n=null;for(const r of e.fieldTransforms){const e=t.data.field(r.field),s=dr(r.transform,e||null);null!=s&&(null===n&&(n=Gt.empty()),n.set(r.field,s))}return n||null}function Dr(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 pr&&t instanceof pr||e instanceof mr&&t instanceof mr?R(e.elements,t.elements,Et):e instanceof gr&&t instanceof gr?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 Ir{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 Lr extends Ir{constructor(e,t,n,r,s=[]){super(),this.key=e,this.data=t,this.fieldMask=n,this.precondition=r,this.fieldTransforms=s,this.type=1}getFieldMask(){return this.fieldMask}}function Mr(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 Nr(e,t,n){const r=new Map;w(e.length===n.length);for(let s=0;s<n.length;s++){const i=e[s],a=i.transform,o=t.data.field(i.field);r.set(i.field,ur(a,o,n[s]))}return r}function Pr(e,t,n){const r=new Map;for(const s of e){const e=s.transform,i=n.data.field(s.field);r.set(s.field,cr(e,i,t))}return r}class Rr extends Ir{constructor(e,t){super(),this.key=e,this.precondition=t,this.type=2,this.fieldTransforms=[]}getFieldMask(){return null}}class Vr extends Ir{constructor(e,t){super(),this.key=e,this.precondition=t,this.type=3,this.fieldTransforms=[]}getFieldMask(){return null}}class Or{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)&&Tr(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 s=e.get(r.key),i=s.overlayedDocument;let a=this.applyToLocalView(i,s.mutatedFields);a=t.has(r.key)?null:a;const o=_r(i,a);null!==o&&n.set(r.key,o),i.isValidDocument()||i.convertToNoDocument($.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)=>Dr(e,t)))&&R(this.baseMutations,e.baseMutations,((e,t)=>Dr(e,t)))}}class $r{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 s=e.mutations;for(let e=0;e<s.length;e++)r=r.insert(s[e].key,n[e].version);return new $r(e,t,n,r)}}class Fr{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 qr{constructor(e,t,n){this.alias=e,this.aggregateType=t,this.fieldPath=n}}class Ur{constructor(e,t){this.count=e,this.unchangedNames=t}}var Br,jr;function zr(e){switch(e){default:return y();case S.CANCELLED:case S.UNKNOWN:case S.DEADLINE_EXCEEDED:case S.RESOURCE_EXHAUSTED:case S.INTERNAL:case S.UNAVAILABLE:case S.UNAUTHENTICATED:return!1;case S.INVALID_ARGUMENT:case S.NOT_FOUND:case S.ALREADY_EXISTS:case S.PERMISSION_DENIED:case S.FAILED_PRECONDITION:case S.ABORTED:case S.OUT_OF_RANGE:case S.UNIMPLEMENTED:case S.DATA_LOSS:return!0}}function Gr(e){if(void 0===e)return m("GRPC error has no .code"),S.UNKNOWN;switch(e){case Br.OK:return S.OK;case Br.CANCELLED:return S.CANCELLED;case Br.UNKNOWN:return S.UNKNOWN;case Br.DEADLINE_EXCEEDED:return S.DEADLINE_EXCEEDED;case Br.RESOURCE_EXHAUSTED:return S.RESOURCE_EXHAUSTED;case Br.INTERNAL:return S.INTERNAL;case Br.UNAVAILABLE:return S.UNAVAILABLE;case Br.UNAUTHENTICATED:return S.UNAUTHENTICATED;case Br.INVALID_ARGUMENT:return S.INVALID_ARGUMENT;case Br.NOT_FOUND:return S.NOT_FOUND;case Br.ALREADY_EXISTS:return S.ALREADY_EXISTS;case Br.PERMISSION_DENIED:return S.PERMISSION_DENIED;case Br.FAILED_PRECONDITION:return S.FAILED_PRECONDITION;case Br.ABORTED:return S.ABORTED;case Br.OUT_OF_RANGE:return S.OUT_OF_RANGE;case Br.UNIMPLEMENTED:return S.UNIMPLEMENTED;case Br.DATA_LOSS:return S.DATA_LOSS;default:return y()}}(jr=Br||(Br={}))[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 o.Integer([4294967295,4294967295],0);function Wr(e){const t=Hr().encode(e),n=new o.Md5;return n.update(t),new Uint8Array(n.digest())}function Yr(e){const t=new DataView(e.buffer),n=t.getUint32(0,!0),r=t.getUint32(4,!0),s=t.getUint32(8,!0),i=t.getUint32(12,!0);return[new o.Integer([n,r],0),new o.Integer([s,i],0)]}class Jr{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=o.Integer.fromNumber(this.Te)}Ee(e,t,n){let r=e.add(t.multiply(o.Integer.fromNumber(n)));return 1===r.compare(Qr)&&(r=new o.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]=Yr(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,s=new Uint8Array(Math.ceil(e/8)),i=new Jr(s,r,t);return n.forEach((e=>i.insert(e))),i}insert(e){if(0===this.Te)return;const t=Wr(e),[n,r]=Yr(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,s){this.snapshotVersion=e,this.targetChanges=t,this.targetMismatches=n,this.documentUpdates=r,this.resolvedLimboDocuments=s}static createSynthesizedRemoteEventForCurrentChange(e,t,n){const r=new Map;return r.set(e,es.createSynthesizedTargetChangeForCurrentChange(e,t,n)),new Zr($.min(),r,new nt(P),Hn(),nr())}}class es{constructor(e,t,n,r,s){this.resumeToken=e,this.current=t,this.addedDocuments=n,this.modifiedDocuments=r,this.removedDocuments=s}static createSynthesizedTargetChangeForCurrentChange(e,t,n){return new es(n,t,nr(),nr(),nr())}}class ts{constructor(e,t,n,r){this.Re=e,this.removedTargetIds=t,this.key=n,this.Ve=r}}class ns{constructor(e,t){this.targetId=e,this.me=t}}class rs{constructor(e,t,n=ut.EMPTY_BYTE_STRING,r=null){this.state=e,this.targetIds=t,this.resumeToken=n,this.cause=r}}class ss{constructor(){this.fe=0,this.ge=os(),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,s)=>{switch(s){case 0:e=e.add(r);break;case 2:t=t.add(r);break;case 1:n=n.add(r);break;default:y()}})),new es(this.pe,this.ye,e,t,n)}Ce(){this.we=!1,this.ge=os()}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 is{constructor(e){this.Le=e,this.Be=new Map,this.ke=Hn(),this.qe=as(),this.Qe=as(),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 s=r.target;if(En(s))if(0===n){const e=new j(s.path);this.We(t,e,Ht.newNoDocument(e,$.min()))}else w(1===n);else{const r=this.Ze(t);if(r!==n){const n=this.Xe(e),s=n?this.et(n,e,r):1;if(0!==s){this.He(t);const e=2===s?"TargetPurposeExistenceFilterMismatchBloom":"TargetPurposeExistenceFilterMismatch";this.Ke=this.Ke.insert(t,e)}null==Kr||Kr.tt(function(e,t,n,r,s){var i,a,o,l,c,u;const d={localCacheCount:e,existenceFilterCount:t.count,databaseId:n.database,projectId:n.projectId},h=t.unchangedNames;return h&&(d.bloomFilter={applied:0===s,hashCount:null!==(i=null==h?void 0:h.hashCount)&&void 0!==i?i:0,bitmapLength:null!==(l=null===(o=null===(a=null==h?void 0:h.bits)||void 0===a?void 0:a.bitmap)||void 0===o?void 0:o.length)&&void 0!==l?l:0,padding:null!==(u=null===(c=null==h?void 0:h.bits)||void 0===c?void 0:c.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,s))}}}}Xe(e){const t=e.me.unchangedNames;if(!t||!t.bits)return null;const{bits:{bitmap:n="",padding:r=0},hashCount:s=0}=t;let i,a;try{i=ft(n).toUint8Array()}catch(e){if(e instanceof ct)return v("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{a=new Jr(i,r,s)}catch(e){return v(e instanceof Xr?"BloomFilter error: ":"Applying bloom filter failed: ",e),null}return 0===a.Te?null:a}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 s=this.Le.nt(),i=`projects/${s.projectId}/databases/${s.database}/documents/${n.path.canonicalString()}`;e.mightContain(i)||(this.We(t,n,null),r++)})),r}it(e){const t=new Map;this.Be.forEach(((n,r)=>{const s=this.Ye(r);if(s){if(n.current&&En(s.target)){const t=new j(s.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=as(),this.Qe=as(),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 ss,this.Be.set(e,t)),t}_t(e){let t=this.Qe.get(e);return t||(t=new it(P),this.Qe=this.Qe.insert(e,t)),t}st(e){let t=this.qe.get(e);return t||(t=new it(P),this.qe=this.qe.insert(e,t)),t}je(e){const t=null!==this.Ye(e);return t||f("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 ss),this.Le.getRemoteKeysForTarget(e).forEach((t=>{this.We(e,t,null)}))}ot(e,t){return this.Le.getRemoteKeysForTarget(e).has(t)}}function as(){return new nt(j.comparator)}function os(){return new nt(j.comparator)}const ls={asc:"ASCENDING",desc:"DESCENDING"},cs={"<":"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"},us={and:"AND",or:"OR"};class ds{constructor(e,t){this.databaseId=e,this.useProto3Json=t}}function hs(e,t){return e.useProto3Json||ye(t)?t:{value:t}}function ps(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 fs(e,t){return e.useProto3Json?t.toBase64():t.toUint8Array()}function ms(e,t){return ps(e,t.toTimestamp())}function vs(e){return w(!!e),$.fromTimestamp(function(e){const t=ht(e);return new O(t.seconds,t.nanos)}(e))}function gs(e,t){return ys(e,t).canonicalString()}function ys(e,t){const n=function(e){return new q(["projects",e.projectId,"databases",e.database])}(e).child("documents");return void 0===t?n:n.child(t)}function ws(e){const t=q.fromString(e);return w(Bs(t)),t}function bs(e,t){return gs(e.databaseId,t.path)}function Ss(e,t){const n=ws(t);if(n.get(1)!==e.databaseId.projectId)throw new x(S.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 x(S.INVALID_ARGUMENT,"Tried to deserialize key from different database: "+n.get(3)+" vs "+e.databaseId.database);return new j(_s(n))}function xs(e,t){return gs(e.databaseId,t)}function Es(e){const t=ws(e);return 4===t.length?q.emptyPath():_s(t)}function Is(e){return new q(["projects",e.databaseId.projectId,"databases",e.databaseId.database]).canonicalString()}function _s(e){return w(e.length>4&&"documents"===e.get(4)),e.popFirst(5)}function Ts(e,t,n){return{name:bs(e,t),fields:n.value.mapValue.fields}}function Cs(e,t,n){const r=Ss(e,t.name),s=vs(t.updateTime),i=t.createTime?vs(t.createTime):$.min(),a=new Gt({mapValue:{fields:t.fields}}),o=Ht.newFoundDocument(r,s,i,a);return n&&o.setHasCommittedMutations(),n?o.setHasCommittedMutations():o}function As(e,t){let n;if(t instanceof kr)n={update:Ts(e,t.key,t.value)};else if(t instanceof Rr)n={delete:bs(e,t.key)};else if(t instanceof Lr)n={update:Ts(e,t.key,t.data),updateMask:Us(t.fieldMask)};else{if(!(t instanceof Vr))return y();n={verify:bs(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 pr)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 gr)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:ms(e,t.updateTime)}:void 0!==t.exists?{exists:t.exists}:y()}(e,t.precondition)),n}function Ds(e,t){const n=t.currentDocument?function(e){return void 0!==e.updateTime?xr.updateTime(vs(e.updateTime)):void 0!==e.exists?xr.exists(e.exists):xr.none()}(t.currentDocument):xr.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 pr(e)}else if("removeAllFromArray"in t){const e=t.removeAllFromArray.values||[];n=new mr(e)}else"increment"in t?n=new gr(e,t.increment):y();const r=B.fromServerFormat(t.fieldPath);return new br(r,n)}(e,t))):[];if(t.update){t.update.name;const s=Ss(e,t.update.name),i=new Gt({mapValue:{fields:t.update.fields}});if(t.updateMask){const e=function(e){const t=e.fieldPaths||[];return new lt(t.map((e=>B.fromServerFormat(e))))}(t.updateMask);return new Lr(s,i,e,n,r)}return new kr(s,i,n,r)}if(t.delete){const r=Ss(e,t.delete);return new Rr(r,n)}if(t.verify){const r=Ss(e,t.verify);return new Vr(r,n)}return y()}function ks(e,t){return{documents:[xs(e,t.path)]}}function Ls(e,t){const n={structuredQuery:{}},r=t.path;let s;null!==t.collectionGroup?(s=r,n.structuredQuery.from=[{collectionId:t.collectionGroup,allDescendants:!0}]):(s=r.popLast(),n.structuredQuery.from=[{collectionId:r.lastSegment()}]),n.parent=xs(e,s);const i=function(e){if(0!==e.length)return qs(tn.create(e,"and"))}(t.filters);i&&(n.structuredQuery.where=i);const a=function(e){if(0!==e.length)return e.map((e=>function(e){return{field:$s(e.field),direction:Rs(e.dir)}}(e)))}(t.orderBy);a&&(n.structuredQuery.orderBy=a);const o=hs(e,t.limit);return null!==o&&(n.structuredQuery.limit=o),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:s}}function Ms(e,t,n,r){const{ct:s,parent:i}=Ls(e,t),a={},o=[];let l=0;return n.forEach((e=>{const t=r?e.alias:"aggregate_"+l++;a[t]=e.alias,"count"===e.aggregateType?o.push({alias:t,count:{}}):"avg"===e.aggregateType?o.push({alias:t,avg:{field:$s(e.fieldPath)}}):"sum"===e.aggregateType&&o.push({alias:t,sum:{field:$s(e.fieldPath)}})})),{request:{structuredAggregationQuery:{aggregations:o,structuredQuery:s.structuredQuery},parent:s.parent},lt:a,parent:i}}function Ns(e){let t=Es(e.parent);const n=e.structuredQuery,r=n.from?n.from.length:0;let s=null;if(r>0){w(1===r);const e=n.from[0];e.allDescendants?s=e.collectionId:t=t.child(e.collectionId)}let i=[];n.where&&(i=function(e){const t=Ps(e);return t instanceof tn&&sn(t)?t.getFilters():[t]}(n.where));let a=[];n.orderBy&&(a=function(e){return e.map((e=>function(e){return new Jt(Fs(e.field),function(e){switch(e){case"ASCENDING":return"asc";case"DESCENDING":return"desc";default:return}}(e.direction))}(e)))}(n.orderBy));let o=null;n.limit&&(o=function(e){let t;return t="object"==typeof e?e.value:e,ye(t)?null:t}(n.limit));let l=null;n.startAt&&(l=function(e){const t=!!e.before,n=e.values||[];return new Qt(n,t)}(n.startAt));let c=null;return n.endAt&&(c=function(e){const t=!e.before,n=e.values||[];return new Qt(n,t)}(n.endAt)),An(t,s,a,i,o,"F",l,c)}function Ps(e){return void 0!==e.unaryFilter?function(e){switch(e.unaryFilter.op){case"IS_NAN":const t=Fs(e.unaryFilter.field);return en.create(t,"==",{doubleValue:NaN});case"IS_NULL":const n=Fs(e.unaryFilter.field);return en.create(n,"==",{nullValue:"NULL_VALUE"});case"IS_NOT_NAN":const r=Fs(e.unaryFilter.field);return en.create(r,"!=",{doubleValue:NaN});case"IS_NOT_NULL":const s=Fs(e.unaryFilter.field);return en.create(s,"!=",{nullValue:"NULL_VALUE"});default:return y()}}(e):void 0!==e.fieldFilter?function(e){return en.create(Fs(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=>Ps(e))),function(e){switch(e){case"AND":return"and";case"OR":return"or";default:return y()}}(e.compositeFilter.op))}(e):y()}function Rs(e){return ls[e]}function Vs(e){return cs[e]}function Os(e){return us[e]}function $s(e){return{fieldPath:e.canonicalString()}}function Fs(e){return B.fromServerFormat(e.fieldPath)}function qs(e){return e instanceof en?function(e){if("=="===e.op){if(Rt(e.value))return{unaryFilter:{field:$s(e.field),op:"IS_NAN"}};if(Pt(e.value))return{unaryFilter:{field:$s(e.field),op:"IS_NULL"}}}else if("!="===e.op){if(Rt(e.value))return{unaryFilter:{field:$s(e.field),op:"IS_NOT_NAN"}};if(Pt(e.value))return{unaryFilter:{field:$s(e.field),op:"IS_NOT_NULL"}}}return{fieldFilter:{field:$s(e.field),op:Vs(e.op),value:e.value}}}(e):e instanceof tn?function(e){const t=e.getFilters().map((e=>qs(e)));return 1===t.length?t[0]:{compositeFilter:{op:Os(e.op),filters:t}}}(e):y()}function Us(e){const t=[];return e.fields.forEach((e=>t.push(e.canonicalString()))),{fieldPaths:t}}function Bs(e){return e.length>=4&&"projects"===e.get(0)&&"databases"===e.get(2)}class js{constructor(e,t,n,r,s=$.min(),i=$.min(),a=ut.EMPTY_BYTE_STRING,o=null){this.target=e,this.targetId=t,this.purpose=n,this.sequenceNumber=r,this.snapshotVersion=s,this.lastLimboFreeSnapshotVersion=i,this.resumeToken=a,this.expectedCount=o}withSequenceNumber(e){return new js(this.target,this.targetId,this.purpose,e,this.snapshotVersion,this.lastLimboFreeSnapshotVersion,this.resumeToken,this.expectedCount)}withResumeToken(e,t){return new js(this.target,this.targetId,this.purpose,this.sequenceNumber,t,this.lastLimboFreeSnapshotVersion,e,null)}withExpectedCount(e){return new js(this.target,this.targetId,this.purpose,this.sequenceNumber,this.snapshotVersion,this.lastLimboFreeSnapshotVersion,this.resumeToken,e)}withLastLimboFreeSnapshotVersion(e){return new js(this.target,this.targetId,this.purpose,this.sequenceNumber,this.snapshotVersion,e,this.resumeToken,this.expectedCount)}}class zs{constructor(e){this.ht=e}}function Gs(e,t){const n=t.key,r={prefixPath:n.getCollectionPath().popLast().toArray(),collectionGroup:n.collectionGroup,documentId:n.path.lastSegment(),readTime:Ks(t.readTime),hasCommittedMutations:t.hasCommittedMutations};if(t.isFoundDocument())r.document=function(e,t){return{name:bs(e,t.key),fields:t.data.value.mapValue.fields,updateTime:ps(e,t.version.toTimestamp()),createTime:ps(e,t.createTime.toTimestamp())}}(e.ht,t);else if(t.isNoDocument())r.noDocument={path:n.path.toArray(),readTime:Hs(t.version)};else{if(!t.isUnknownDocument())return y();r.unknownDocument={path:n.path.toArray(),version:Hs(t.version)}}return r}function Ks(e){const t=e.toTimestamp();return[t.seconds,t.nanoseconds]}function Hs(e){const t=e.toTimestamp();return{seconds:t.seconds,nanoseconds:t.nanoseconds}}function Qs(e){const t=new O(e.seconds,e.nanoseconds);return $.fromTimestamp(t)}function Ws(e,t){const n=(t.baseMutations||[]).map((t=>Ds(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=>Ds(e.ht,t))),s=O.fromMillis(t.localWriteTimeMs);return new Or(t.batchId,s,n,r)}function Ys(e){const t=Qs(e.readTime),n=void 0!==e.lastLimboFreeSnapshotVersion?Qs(e.lastLimboFreeSnapshotVersion):$.min();let r;return r=function(e){return void 0!==e.documents}(e.query)?function(e){return w(1===e.documents.length),Nn(Dn(Es(e.documents[0])))}(e.query):function(e){return Nn(Ns(e))}(e.query),new js(r,e.targetId,"TargetPurposeListen",e.lastListenSequenceNumber,t,n,ut.fromBase64String(e.resumeToken))}function Js(e,t){const n=Hs(t.snapshotVersion),r=Hs(t.lastLimboFreeSnapshotVersion);let s;s=En(t.target)?ks(e.ht,t.target):Ls(e.ht,t.target).ct;const i=t.resumeToken.toBase64();return{targetId:t.targetId,canonicalId:Sn(t.target),readTime:n,resumeToken:i,lastListenSequenceNumber:t.sequenceNumber,lastLimboFreeSnapshotVersion:r,query:s}}function Xs(e){const t=Ns({parent:e.parent,structuredQuery:e.structuredQuery});return"LAST"===e.limitType?On(t,t.limit,"L"):t}function Zs(e,t){return new Fr(t.largestBatchId,Ds(e.ht,t.overlayMutation))}function ei(e,t){const n=t.path.lastSegment();return[e,Se(t.path.popLast()),n]}function ti(e,t,n,r){return{indexId:e,uid:t,sequenceNumber:n,readTime:Hs(r.readTime),documentKey:Se(r.documentKey.path),largestBatchId:r.largestBatchId}}class ni{getBundleMetadata(e,t){return ri(e).get(t).next((e=>{if(e)return function(e){return{id:e.bundleId,createTime:Qs(e.createTime),version:e.version}}(e)}))}saveBundleMetadata(e,t){return ri(e).put(function(e){return{bundleId:e.id,createTime:Hs(vs(e.createTime)),version:e.version}}(t))}getNamedQuery(e,t){return si(e).get(t).next((e=>{if(e)return function(e){return{name:e.name,query:Xs(e.bundledQuery),readTime:Qs(e.readTime)}}(e)}))}saveNamedQuery(e,t){return si(e).put(function(e){return{name:e.name,readTime:Hs(vs(e.readTime)),bundledQuery:e.bundledQuery}}(t))}}function ri(e){return Je(e,"bundles")}function si(e){return Je(e,"namedQueries")}class ii{constructor(e,t){this.serializer=e,this.userId=t}static Pt(e,t){const n=t.uid||"";return new ii(e,n)}getOverlay(e,t){return ai(e).get(ei(this.userId,t)).next((e=>e?Zs(this.serializer,e):null))}getOverlays(e,t){const n=Jn();return se.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,s)=>{const i=new Fr(t,s);r.push(this.Tt(e,i))})),se.waitFor(r)}removeOverlaysForBatchId(e,t,n){const r=new Set;t.forEach((e=>r.add(Se(e.getCollectionPath()))));const s=[];return r.forEach((t=>{const r=IDBKeyRange.bound([this.userId,t,n],[this.userId,t,n+1],!1,!0);s.push(ai(e).j("collectionPathOverlayIndex",r))})),se.waitFor(s)}getOverlaysForCollection(e,t,n){const r=Jn(),s=Se(t),i=IDBKeyRange.bound([this.userId,s,n],[this.userId,s,Number.POSITIVE_INFINITY],!0);return ai(e).U("collectionPathOverlayIndex",i).next((e=>{for(const t of e){const e=Zs(this.serializer,t);r.set(e.getKey(),e)}return r}))}getOverlaysForCollectionGroup(e,t,n,r){const s=Jn();let i;const a=IDBKeyRange.bound([this.userId,t,n],[this.userId,t,Number.POSITIVE_INFINITY],!0);return ai(e).J({index:"collectionGroupOverlayIndex",range:a},((e,t,n)=>{const a=Zs(this.serializer,t);s.size()<r||a.largestBatchId===i?(s.set(a.getKey(),a),i=a.largestBatchId):n.done()})).next((()=>s))}Tt(e,t){return ai(e).put(function(e,t,n){const[r,s,i]=ei(t,n.mutation.key);return{userId:t,collectionPath:s,documentId:i,collectionGroup:n.mutation.key.getCollectionGroup(),largestBatchId:n.largestBatchId,overlayMutation:As(e.ht,n.mutation)}}(this.serializer,this.userId,t))}}function ai(e){return Je(e,"documentOverlays")}class oi{It(e){return Je(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 li{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(pt(e.integerValue));else if("doubleValue"in e){const n=pt(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(ft(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?Ft(e)?this.Rt(t,Number.MAX_SAFE_INTEGER):Ot(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 s=e.fields||{};this.Rt(t,53);const i="value",a=(null===(r=null===(n=s[i].arrayValue)||void 0===n?void 0:n.values)||void 0===r?void 0:r.length)||0;this.Rt(t,15),t.Vt(pt(a)),this.gt(i,t),this.dt(s[i],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 ci(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 ui(e){const t=64-function(e){let t=0;for(let n=0;n<8;++n){const r=ci(255&e[n]);if(t+=r,8!==r)break}return t}(e);return Math.ceil(t/8)}li.Ft=new li;class di{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=ui(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=ui(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 hi{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 pi{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 fi{constructor(){this.Jt=new di,this.Yt=new hi(this.Jt),this.Zt=new pi(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 mi{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 mi(this.indexId,this.documentKey,this.arrayValue,n)}}function vi(e,t){let n=e.indexId-t.indexId;return 0!==n?n:(n=gi(e.arrayValue,t.arrayValue),0!==n?n:(n=gi(e.directionalValue,t.directionalValue),0!==n?n:j.comparator(e.documentKey,t.documentKey)))}function gi(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 yi{constructor(e){this.tn=new it(((e,t)=>B.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,s=0,i=0;for(;s<n.length&&this._n(n[s]);++s)r=r.add(n[s].fieldPath.canonicalString());if(s===n.length)return!0;if(this.tn.size>0){const e=this.tn.getIterator().getNext();if(!r.has(e.field.canonicalString())){const t=n[s];if(!this.an(e,t)||!this.un(this.nn[i++],t))return!1}++s}for(;s<n.length;++s){const e=n[s];if(i>=this.nn.length||!this.un(this.nn[i++],e))return!1}return!0}cn(){if(this.sn)return null;let e=new it(B.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,Y.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 wi(e){var t,n;if(w(e instanceof en||e instanceof tn),e instanceof en){if(e instanceof vn){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=>wi(e)));return tn.create(r,e.op)}function bi(e){if(0===e.getFilters().length)return[];const t=Ii(wi(e));return w(Ei(t)),Si(t)||xi(t)?[t]:t.getFilters()}function Si(e){return e instanceof en}function xi(e){return e instanceof tn&&sn(e)}function Ei(e){return Si(e)||xi(e)||function(e){if(e instanceof tn&&rn(e)){for(const t of e.getFilters())if(!Si(t)&&!xi(t))return!1;return!0}return!1}(e)}function Ii(e){if(w(e instanceof en||e instanceof tn),e instanceof en)return e;if(1===e.filters.length)return Ii(e.filters[0]);const t=e.filters.map((e=>Ii(e)));let n=tn.create(t,e.op);return n=Ci(n),Ei(n)?n:(w(n instanceof tn),w(nn(n)),w(n.filters.length>1),n.filters.reduce(((e,t)=>_i(e,t))))}function _i(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):Ti(e,t):t instanceof en?Ti(t,e):function(e,t){if(w(e.filters.length>0&&t.filters.length>0),nn(e)&&nn(t))return cn(e,t.getFilters());const n=rn(e)?e:t,r=rn(e)?t:e,s=n.filters.map((e=>_i(e,r)));return tn.create(s,"or")}(e,t),Ci(n)}function Ti(e,t){if(nn(t))return cn(t,e.getFilters());{const n=t.filters.map((t=>_i(e,t)));return tn.create(n,"or")}}function Ci(e){if(w(e instanceof en||e instanceof tn),e instanceof en)return e;const t=e.getFilters();if(1===t.length)return Ci(t[0]);if(an(e))return e;const n=t.map((e=>Ci(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 Ai{constructor(){this.ln=new Di}addToCollectionParentIndex(e,t){return this.ln.add(t),se.resolve()}getCollectionParents(e,t){return se.resolve(this.ln.getEntries(t))}addFieldIndex(e,t){return se.resolve()}deleteFieldIndex(e,t){return se.resolve()}deleteAllFieldIndexes(e){return se.resolve()}createTargetIndexes(e,t){return se.resolve()}getDocumentsMatchingTarget(e,t){return se.resolve(null)}getIndexType(e,t){return se.resolve(0)}getFieldIndexes(e,t){return se.resolve([])}getNextCollectionGroupToUpdate(e){return se.resolve(null)}getMinOffset(e,t){return se.resolve(Z.min())}getMinOffsetFromCollectionGroup(e,t){return se.resolve(Z.min())}updateCollectionGroup(e,t,n){return se.resolve()}updateIndexEntries(e,t){return se.resolve()}}class Di{constructor(){this.index={}}add(e){const t=e.lastSegment(),n=e.popLast(),r=this.index[t]||new it(q.comparator),s=!r.has(n);return this.index[t]=r.add(n),s}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 it(q.comparator)).toArray()}}const ki=new Uint8Array(0);class Li{constructor(e,t){this.databaseId=t,this.hn=new Di,this.Pn=new Gn((e=>Sn(e)),((e,t)=>xn(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 s={collectionId:n,parent:Se(r)};return Mi(e).put(s)}return se.resolve()}getCollectionParents(e,t){const n=[],r=IDBKeyRange.bound([t,""],[V(t),""],!1,!0);return Mi(e).U(r).next((e=>{for(const r of e){if(r.collectionId!==t)break;n.push(Ie(r.parent))}return n}))}addFieldIndex(e,t){const n=Pi(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 s=n.add(r);if(t.indexState){const n=Ri(e);return s.next((e=>{n.put(ti(e,this.uid,t.indexState.sequenceNumber,t.indexState.offset))}))}return s.next()}deleteFieldIndex(e,t){const n=Pi(e),r=Ri(e),s=Ni(e);return n.delete(t.indexId).next((()=>r.delete(IDBKeyRange.bound([t.indexId],[t.indexId+1],!1,!0)))).next((()=>s.delete(IDBKeyRange.bound([t.indexId],[t.indexId+1],!1,!0))))}deleteAllFieldIndexes(e){const t=Pi(e),n=Ni(e),r=Ri(e);return t.j().next((()=>n.j())).next((()=>r.j()))}createTargetIndexes(e,t){return se.forEach(this.Tn(t),(t=>this.getIndexType(e,t).next((n=>{if(0===n||1===n){const n=new yi(t).cn();if(null!=n)return this.addFieldIndex(e,n)}}))))}getDocumentsMatchingTarget(e,t){const n=Ni(e);let r=!0;const s=new Map;return se.forEach(this.Tn(t),(t=>this.In(e,t).next((e=>{r&&(r=!!e),s.set(t,e)})))).next((()=>{if(r){let e=nr();const r=[];return se.forEach(s,((s,i)=>{f("IndexedDbIndexManager",`Using index ${function(e){return`id=${e.indexId}|cg=${e.collectionGroup}|f=${e.fields.map((e=>`${e.fieldPath}:${e.kind}`)).join(",")}`}(s)} to execute ${Sn(t)}`);const a=function(e,t){const n=G(t);if(void 0===n)return null;for(const t of In(e,n.fieldPath))switch(t.op){case"array-contains-any":return t.value.arrayValue.values||[];case"array-contains":return[t.value]}return null}(i,s),o=function(e,t){const n=new Map;for(const r of K(t))for(const t of In(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}(i,s),l=function(e,t){const n=[];let r=!0;for(const s of K(t)){const t=0===s.kind?_n(e,s.fieldPath,e.startAt):Tn(e,s.fieldPath,e.startAt);n.push(t.value),r&&(r=t.inclusive)}return new Qt(n,r)}(i,s),c=function(e,t){const n=[];let r=!0;for(const s of K(t)){const t=0===s.kind?Tn(e,s.fieldPath,e.endAt):_n(e,s.fieldPath,e.endAt);n.push(t.value),r&&(r=t.inclusive)}return new Qt(n,r)}(i,s),u=this.En(s,i,l),d=this.En(s,i,c),h=this.dn(s,i,o),p=this.An(s.indexId,a,u,l.inclusive,d,c.inclusive,h);return se.forEach(p,(s=>n.G(s,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 se.resolve(null)}))}Tn(e){let t=this.Pn.get(e);return t||(t=0===e.filters.length?[e]:bi(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,s,i,a){const o=(null!=t?t.length:1)*Math.max(n.length,s.length),l=o/(null!=t?t.length:1),c=[];for(let u=0;u<o;++u){const o=t?this.Rn(t[u/l]):ki,d=this.Vn(e,o,n[u%l],r),h=this.mn(e,o,s[u%l],i),p=a.map((t=>this.Vn(e,o,t,!0)));c.push(...this.createRange(d,h,p))}return c}Vn(e,t,n,r){const s=new mi(e,j.empty(),t,n);return r?s:s.en()}mn(e,t,n,r){const s=new mi(e,j.empty(),t,n);return r?s.en():s}In(e,t){const n=new yi(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 se.forEach(r,(t=>this.In(e,t).next((e=>{e?0!==n&&e.fields.length<function(e){let t=new it(B.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 fi;for(const r of K(e)){const e=t.data.field(r.fieldPath);if(null==e)return null;const s=n.Xt(r.kind);li.Ft.Et(e,s)}return n.Ht()}Rn(e){const t=new fi;return li.Ft.Et(e,t.Xt(0)),t.Ht()}gn(e,t){const n=new fi;return li.Ft.Et(Lt(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 fi);let s=0;for(const i of K(e)){const e=n[s++];for(const n of r)if(this.pn(t,i.fieldPath)&&Nt(e))r=this.yn(r,i,e);else{const t=n.Xt(i.kind);li.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],s=[];for(const e of n.arrayValue.values||[])for(const n of r){const r=new fi;r.seed(n.Ht()),li.Ft.Et(e,r.Xt(t.kind)),s.push(r)}return s}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=Pi(e),r=Ri(e);return(t?n.U("collectionGroupIndex",IDBKeyRange.bound(t,t)):n.U()).next((e=>{const t=[];return se.forEach(e,(e=>r.get([e.indexId,this.uid]).next((n=>{t.push(function(e,t){const n=t?new Y(t.sequenceNumber,new Z(Qs(t.readTime),new j(Ie(t.documentKey)),t.largestBatchId)):Y.empty(),r=e.fields.map((([e,t])=>new Q(B.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=Pi(e),s=Ri(e);return this.Sn(e).next((e=>r.U("collectionGroupIndex",IDBKeyRange.bound(t,t)).next((t=>se.forEach(t,(t=>s.put(ti(t.indexId,this.uid,e,n))))))))}updateIndexEntries(e,t){const n=new Map;return se.forEach(t,((t,r)=>{const s=n.get(t.collectionGroup);return(s?se.resolve(s):this.getFieldIndexes(e,t.collectionGroup)).next((s=>(n.set(t.collectionGroup,s),se.forEach(s,(n=>this.bn(e,t,n).next((t=>{const s=this.Dn(r,n);return t.isEqual(s)?se.resolve():this.vn(e,r,n,t,s)})))))))}))}Cn(e,t,n,r){return Ni(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 Ni(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=Ni(e);let s=new it(vi);return r.J({index:"documentKeyIndex",range:IDBKeyRange.only([n.indexId,this.uid,this.gn(n,t)])},((e,r)=>{s=s.add(new mi(n.indexId,t,r.arrayValue,r.directionalValue))})).next((()=>s))}Dn(e,t){let n=new it(vi);const r=this.fn(t,e);if(null==r)return n;const s=G(t);if(null!=s){const i=e.data.field(s.fieldPath);if(Nt(i))for(const s of i.arrayValue.values||[])n=n.add(new mi(t.indexId,e.key,this.Rn(s),r))}else n=n.add(new mi(t.indexId,e.key,ki,r));return n}vn(e,t,n,r,s){f("IndexedDbIndexManager","Updating index entries for document '%s'",t.key);const i=[];return function(e,t,n,r,s){const i=e.getIterator(),a=t.getIterator();let o=ot(i),l=ot(a);for(;o||l;){let e=!1,t=!1;if(o&&l){const r=n(o,l);r<0?t=!0:r>0&&(e=!0)}else null!=o?t=!0:e=!0;e?(r(l),l=ot(a)):t?(s(o),o=ot(i)):(o=ot(i),l=ot(a))}}(r,s,vi,(r=>{i.push(this.Cn(e,t,n,r))}),(r=>{i.push(this.Fn(e,t,n,r))})),se.waitFor(i)}Sn(e){let t=1;return Ri(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)=>vi(e,t))).filter(((e,t,n)=>!t||0!==vi(e,n[t-1])));const r=[];r.push(e);for(const s of n){const n=vi(s,e),i=vi(s,t);if(0===n)r[0]=e.en();else if(n>0&&i<0)r.push(s),r.push(s.en());else if(i>0)break}r.push(t);const s=[];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,ki,[]],n=[r[e+1].indexId,this.uid,r[e+1].arrayValue,r[e+1].directionalValue,ki,[]];s.push(IDBKeyRange.bound(t,n))}return s}Mn(e,t){return vi(e,t)>0}getMinOffsetFromCollectionGroup(e,t){return this.getFieldIndexes(e,t).next(Vi)}getMinOffset(e,t){return se.mapArray(this.Tn(t),(t=>this.In(e,t).next((e=>e||y())))).next(Vi)}}function Mi(e){return Je(e,"collectionParents")}function Ni(e){return Je(e,"indexEntries")}function Pi(e){return Je(e,"indexConfiguration")}function Ri(e){return Je(e,"indexState")}function Vi(e){w(0!==e.length);let t=e[0].indexState.offset,n=t.largestBatchId;for(let r=1;r<e.length;r++){const s=e[r].indexState.offset;ee(s,t)<0&&(t=s),n<s.largestBatchId&&(n=s.largestBatchId)}return new Z(t.readTime,t.documentKey,n)}const Oi={didRun:!1,sequenceNumbersCollected:0,targetsRemoved:0,documentsRemoved:0};class $i{static withCacheSize(e){return new $i(e,$i.DEFAULT_COLLECTION_PERCENTILE,$i.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT)}constructor(e,t,n){this.cacheSizeCollectionThreshold=e,this.percentileToCollect=t,this.maximumSequenceNumbersToCollect=n}}function Fi(e,t,n){const r=e.store("mutations"),s=e.store("documentMutations"),i=[],a=IDBKeyRange.only(n.batchId);let o=0;const l=r.J({range:a},((e,t,n)=>(o++,n.delete())));i.push(l.next((()=>{w(1===o)})));const c=[];for(const e of n.mutations){const r=Ce(t,e.key.path,n.batchId);i.push(s.delete(r)),c.push(e.key)}return se.waitFor(i).next((()=>c))}function qi(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}$i.DEFAULT_COLLECTION_PERCENTILE=10,$i.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT=1e3,$i.DEFAULT=new $i(41943040,$i.DEFAULT_COLLECTION_PERCENTILE,$i.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT),$i.DISABLED=new $i(-1,0,0);class Ui{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 s=e.isAuthenticated()?e.uid:"";return new Ui(s,t,n,r)}checkEmpty(e){let t=!0;const n=IDBKeyRange.bound([this.userId,Number.NEGATIVE_INFINITY],[this.userId,Number.POSITIVE_INFINITY]);return ji(e).J({index:"userMutationsIndex",range:n},((e,n,r)=>{t=!1,r.done()})).next((()=>t))}addMutationBatch(e,t,n,r){const s=zi(e),i=ji(e);return i.add({}).next((a=>{w("number"==typeof a);const o=new Or(a,t,n,r),l=function(e,t,n){const r=n.baseMutations.map((t=>As(e.ht,t))),s=n.mutations.map((t=>As(e.ht,t)));return{userId:t,batchId:n.batchId,localWriteTimeMs:n.localWriteTime.toMillis(),baseMutations:r,mutations:s}}(this.serializer,this.userId,o),c=[];let u=new it(((e,t)=>P(e.canonicalString(),t.canonicalString())));for(const e of r){const t=Ce(this.userId,e.key.path,a);u=u.add(e.key.path.popLast()),c.push(i.put(l)),c.push(s.put(t,Ae))}return u.forEach((t=>{c.push(this.indexManager.addToCollectionParentIndex(e,t))})),e.addOnCommittedListener((()=>{this.xn[a]=o.keys()})),se.waitFor(c).next((()=>o))}))}lookupMutationBatch(e,t){return ji(e).get(t).next((e=>e?(w(e.userId===this.userId),Ws(this.serializer,e)):null))}On(e,t){return this.xn[t]?se.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 s=null;return ji(e).J({index:"userMutationsIndex",range:r},((e,t,r)=>{t.userId===this.userId&&(w(t.batchId>=n),s=Ws(this.serializer,t)),r.done()})).next((()=>s))}getHighestUnacknowledgedBatchId(e){const t=IDBKeyRange.upperBound([this.userId,Number.POSITIVE_INFINITY]);let n=-1;return ji(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 ji(e).U("userMutationsIndex",t).next((e=>e.map((e=>Ws(this.serializer,e)))))}getAllMutationBatchesAffectingDocumentKey(e,t){const n=Te(this.userId,t.path),r=IDBKeyRange.lowerBound(n),s=[];return zi(e).J({range:r},((n,r,i)=>{const[a,o,l]=n,c=Ie(o);if(a===this.userId&&t.path.isEqual(c))return ji(e).get(l).next((e=>{if(!e)throw y();w(e.userId===this.userId),s.push(Ws(this.serializer,e))}));i.done()})).next((()=>s))}getAllMutationBatchesAffectingDocumentKeys(e,t){let n=new it(P);const r=[];return t.forEach((t=>{const s=Te(this.userId,t.path),i=IDBKeyRange.lowerBound(s),a=zi(e).J({range:i},((e,r,s)=>{const[i,a,o]=e,l=Ie(a);i===this.userId&&t.path.isEqual(l)?n=n.add(o):s.done()}));r.push(a)})),se.waitFor(r).next((()=>this.Nn(e,n)))}getAllMutationBatchesAffectingQuery(e,t){const n=t.path,r=n.length+1,s=Te(this.userId,n),i=IDBKeyRange.lowerBound(s);let a=new it(P);return zi(e).J({range:i},((e,t,s)=>{const[i,o,l]=e,c=Ie(o);i===this.userId&&n.isPrefixOf(c)?c.length===r&&(a=a.add(l)):s.done()})).next((()=>this.Nn(e,a)))}Nn(e,t){const n=[],r=[];return t.forEach((t=>{r.push(ji(e).get(t).next((e=>{if(null===e)throw y();w(e.userId===this.userId),n.push(Ws(this.serializer,e))})))})),se.waitFor(r).next((()=>n))}removeMutationBatch(e,t){return Fi(e._e,this.userId,t).next((n=>(e.addOnCommittedListener((()=>{this.Ln(t.batchId)})),se.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 se.resolve();const n=IDBKeyRange.lowerBound(function(e){return[e]}(this.userId)),r=[];return zi(e).J({range:n},((e,t,n)=>{if(e[0]===this.userId){const t=Ie(e[1]);r.push(t)}else n.done()})).next((()=>{w(0===r.length)}))}))}containsKey(e,t){return Bi(e,this.userId,t)}Bn(e){return Gi(e).get(this.userId).next((e=>e||{userId:this.userId,lastAcknowledgedBatchId:-1,lastStreamToken:""}))}}function Bi(e,t,n){const r=Te(t,n.path),s=r[1],i=IDBKeyRange.lowerBound(r);let a=!1;return zi(e).J({range:i,H:!0},((e,n,r)=>{const[i,o,l]=e;i===t&&o===s&&(a=!0),r.done()})).next((()=>a))}function ji(e){return Je(e,"mutations")}function zi(e){return Je(e,"documentMutations")}function Gi(e){return Je(e,"mutationQueues")}class Ki{constructor(e){this.kn=e}next(){return this.kn+=2,this.kn}static qn(){return new Ki(0)}static Qn(){return new Ki(-1)}}class Hi{constructor(e,t){this.referenceDelegate=e,this.serializer=t}allocateTargetId(e){return this.Kn(e).next((t=>{const n=new Ki(t.highestTargetId);return t.highestTargetId=n.next(),this.$n(e,t).next((()=>t.highestTargetId))}))}getLastRemoteSnapshotVersion(e){return this.Kn(e).next((e=>$.fromTimestamp(new O(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((()=>Qi(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 s=[];return Qi(e).J(((i,a)=>{const o=Ys(a);o.sequenceNumber<=t&&null===n.get(o.targetId)&&(r++,s.push(this.removeTargetData(e,o)))})).next((()=>se.waitFor(s))).next((()=>r))}forEachTarget(e,t){return Qi(e).J(((e,n)=>{const r=Ys(n);t(r)}))}Kn(e){return Wi(e).get("targetGlobalKey").next((e=>(w(null!==e),e)))}$n(e,t){return Wi(e).put("targetGlobalKey",t)}Un(e,t){return Qi(e).put(Js(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=Sn(t),r=IDBKeyRange.bound([n,Number.NEGATIVE_INFINITY],[n,Number.POSITIVE_INFINITY]);let s=null;return Qi(e).J({range:r,index:"queryTargetsIndex"},((e,n,r)=>{const i=Ys(n);xn(t,i.target)&&(s=i,r.done())})).next((()=>s))}addMatchingKeys(e,t,n){const r=[],s=Yi(e);return t.forEach((t=>{const i=Se(t.path);r.push(s.put({targetId:n,path:i})),r.push(this.referenceDelegate.addReference(e,n,t))})),se.waitFor(r)}removeMatchingKeys(e,t,n){const r=Yi(e);return se.forEach(t,(t=>{const s=Se(t.path);return se.waitFor([r.delete([n,s]),this.referenceDelegate.removeReference(e,n,t)])}))}removeMatchingKeysForTargetId(e,t){const n=Yi(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=Yi(e);let s=nr();return r.J({range:n,H:!0},((e,t,n)=>{const r=Ie(e[1]),i=new j(r);s=s.add(i)})).next((()=>s))}containsKey(e,t){const n=Se(t.path),r=IDBKeyRange.bound([n],[V(n)],!1,!0);let s=0;return Yi(e).J({index:"documentTargetsIndex",H:!0,range:r},(([e,t],n,r)=>{0!==e&&(s++,r.done())})).next((()=>s>0))}ut(e,t){return Qi(e).get(t).next((e=>e?Ys(e):null))}}function Qi(e){return Je(e,"targets")}function Wi(e){return Je(e,"targetGlobal")}function Yi(e){return Je(e,"targetDocuments")}function Ji([e,t],[n,r]){const s=P(e,n);return 0===s?P(t,r):s}class Xi{constructor(e){this.Gn=e,this.buffer=new it(Ji),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();Ji(t,e)<0&&(this.buffer=this.buffer.delete(e).add(t))}}get maxValue(){return this.buffer.last()[0]}}class Zi{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){f("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)?f("LruGarbageCollector","Ignoring IndexedDB error during garbage collection: ",e):await re(e)}await this.Yn(3e5)}))}}class ea{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 se.resolve(ge.oe);const n=new Xi(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?(f("LruGarbageCollector","Garbage collection skipped; disabled"),se.resolve(Oi)):this.getCacheSize(e).next((n=>n<this.params.cacheSizeCollectionThreshold?(f("LruGarbageCollector",`Garbage collection skipped; Cache size ${n} is lower than threshold ${this.params.cacheSizeCollectionThreshold}`),Oi):this.tr(e,t)))}getCacheSize(e){return this.Zn.getCacheSize(e)}tr(e,t){let n,r,s,a,o,l,c;const u=Date.now();return this.calculateTargetCount(e,this.params.percentileToCollect).next((t=>(t>this.params.maximumSequenceNumbersToCollect?(f("LruGarbageCollector",`Capping sequence numbers to collect down to the maximum of ${this.params.maximumSequenceNumbersToCollect} from ${t}`),r=this.params.maximumSequenceNumbersToCollect):r=t,a=Date.now(),this.nthSequenceNumber(e,r)))).next((r=>(n=r,o=Date.now(),this.removeTargets(e,n,t)))).next((t=>(s=t,l=Date.now(),this.removeOrphanedDocuments(e,n)))).next((e=>(c=Date.now(),p()<=i.LogLevel.DEBUG&&f("LruGarbageCollector",`LRU Garbage Collection\n\tCounted targets in ${a-u}ms\n\tDetermined least recently used ${r} in `+(o-a)+"ms\n"+`\tRemoved ${s} targets in `+(l-o)+"ms\n"+`\tRemoved ${e} documents in `+(c-l)+"ms\n"+`Total Duration: ${c-u}ms`),se.resolve({didRun:!0,sequenceNumbersCollected:r,targetsRemoved:s,documentsRemoved:e}))))}}function ta(e,t){return new ea(e,t)}class na{constructor(e,t){this.db=e,this.garbageCollector=ta(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 ra(e,n)}removeReference(e,t,n){return ra(e,n)}removeTargets(e,t,n){return this.db.getTargetCache().removeTargets(e,t,n)}markPotentiallyOrphaned(e,t){return ra(e,t)}ir(e,t){return function(e,t){let n=!1;return Gi(e).Y((r=>Bi(e,r,t).next((e=>(e&&(n=!0),se.resolve(!e)))))).next((()=>n))}(e,t)}removeOrphanedDocuments(e,t){const n=this.db.getRemoteDocumentCache().newChangeBuffer(),r=[];let s=0;return this.rr(e,((i,a)=>{if(a<=t){const t=this.ir(e,i).next((t=>{if(!t)return s++,n.getEntry(e,i).next((()=>(n.removeEntry(i,$.min()),Yi(e).delete(function(e){return[0,Se(e.path)]}(i)))))}));r.push(t)}})).next((()=>se.waitFor(r))).next((()=>n.apply(e))).next((()=>s))}removeTarget(e,t){const n=t.withSequenceNumber(e.currentSequenceNumber);return this.db.getTargetCache().updateTargetData(e,n)}updateLimboDocument(e,t){return ra(e,t)}rr(e,t){const n=Yi(e);let r,s=ge.oe;return n.J({index:"documentTargetsIndex"},(([e,n],{path:i,sequenceNumber:a})=>{0===e?(s!==ge.oe&&t(new j(Ie(r)),s),s=a,r=i):s=ge.oe})).next((()=>{s!==ge.oe&&t(new j(Ie(r)),s)}))}getCacheSize(e){return this.db.getRemoteDocumentCache().getSize(e)}}function ra(e,t){return Yi(e).put(function(e,t){return{targetId:0,path:Se(e.path),sequenceNumber:t}}(t,e.currentSequenceNumber))}class sa{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?se.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 ia{constructor(e){this.serializer=e}setIndexManager(e){this.indexManager=e}addEntry(e,t,n){return ca(e).put(n)}removeEntry(e,t,n){return ca(e).delete(function(e,t){const n=e.path.toArray();return[n.slice(0,n.length-2),n[n.length-2],Ks(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 ca(e).J({index:"documentKeyIndex",range:IDBKeyRange.only(ua(t))},((e,r)=>{n=this._r(t,r)})).next((()=>n))}ar(e,t){let n={size:0,document:Ht.newInvalidDocument(t)};return ca(e).J({index:"documentKeyIndex",range:IDBKeyRange.only(ua(t))},((e,r)=>{n={document:this._r(t,r),size:qi(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 s=this._r(e,t);n=n.insert(e,s),r=r.insert(e,qi(t))})).next((()=>({documents:n,lr:r})))}ur(e,t,n){if(t.isEmpty())return se.resolve();let r=new it(ha);t.forEach((e=>r=r.add(e)));const s=IDBKeyRange.bound(ua(r.first()),ua(r.last())),i=r.getIterator();let a=i.getNext();return ca(e).J({index:"documentKeyIndex",range:s},((e,t,r)=>{const s=j.fromSegments([...t.prefixPath,t.collectionGroup,t.documentId]);for(;a&&ha(a,s)<0;)n(a,null),a=i.getNext();a&&a.isEqual(s)&&(n(a,t),a=i.hasNext()?i.getNext():null),a?r.$(ua(a)):r.done()})).next((()=>{for(;a;)n(a,null),a=i.hasNext()?i.getNext():null}))}getDocumentsMatchingQuery(e,t,n,r,s){const i=t.path,a=[i.popLast().toArray(),i.lastSegment(),Ks(n.readTime),n.documentKey.path.isEmpty()?"":n.documentKey.path.lastSegment()],o=[i.popLast().toArray(),i.lastSegment(),[Number.MAX_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],""];return ca(e).U(IDBKeyRange.bound(a,o,!0)).next((e=>{null==s||s.incrementDocumentReadCount(e.length);let n=Hn();for(const s of e){const e=this._r(j.fromSegments(s.prefixPath.concat(s.collectionGroup,s.documentId)),s);e.isFoundDocument()&&(Un(t,e)||r.has(e.key))&&(n=n.insert(e.key,e))}return n}))}getAllFromCollectionGroup(e,t,n,r){let s=Hn();const i=da(t,n),a=da(t,Z.max());return ca(e).J({index:"collectionGroupIndex",range:IDBKeyRange.bound(i,a,!0)},((e,t,n)=>{const i=this._r(j.fromSegments(t.prefixPath.concat(t.collectionGroup,t.documentId)),t);s=s.insert(i.key,i),s.size===r&&n.done()})).next((()=>s))}newChangeBuffer(e){return new oa(this,!!e&&e.trackRemovals)}getSize(e){return this.getMetadata(e).next((e=>e.byteSize))}getMetadata(e){return la(e).get("remoteDocumentGlobalKey").next((e=>(w(!!e),e)))}sr(e,t){return la(e).put("remoteDocumentGlobalKey",t)}_r(e,t){if(t){const e=function(e,t){let n;if(t.document)n=Cs(e.ht,t.document,!!t.hasCommittedMutations);else if(t.noDocument){const e=j.fromSegments(t.noDocument.path),r=Qs(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=Qs(t.unknownDocument.version);n=Ht.newUnknownDocument(e,r)}}return t.readTime&&n.setReadTime(function(e){const t=new O(e[0],e[1]);return $.fromTimestamp(t)}(t.readTime)),n}(this.serializer,t);if(!e.isNoDocument()||!e.version.isEqual($.min()))return e}return Ht.newInvalidDocument(e)}}function aa(e){return new ia(e)}class oa extends sa{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 it(((e,t)=>P(e.canonicalString(),t.canonicalString())));return this.changes.forEach(((s,i)=>{const a=this.Pr.get(s);if(t.push(this.hr.removeEntry(e,s,a.readTime)),i.isValidDocument()){const o=Gs(this.hr.serializer,i);r=r.add(s.path.popLast());const l=qi(o);n+=l-a.size,t.push(this.hr.addEntry(e,s,o))}else if(n-=a.size,this.trackRemovals){const n=Gs(this.hr.serializer,i.convertToNoDocument($.min()));t.push(this.hr.addEntry(e,s,n))}})),r.forEach((n=>{t.push(this.hr.indexManager.addToCollectionParentIndex(e,n))})),t.push(this.hr.updateMetadata(e,n)),se.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 la(e){return Je(e,"remoteDocumentGlobal")}function ca(e){return Je(e,"remoteDocumentsV14")}function ua(e){const t=e.path.toArray();return[t.slice(0,t.length-2),t[t.length-2],t[t.length-1]]}function da(e,t){const n=t.documentKey.path.toArray();return[e,Ks(t.readTime),n.slice(0,n.length-2),n.length>0?n[n.length-1]:""]}function ha(e,t){const n=e.path.toArray(),r=t.path.toArray();let s=0;for(let e=0;e<n.length-2&&e<r.length-2;++e)if(s=P(n[e],r[e]),s)return s;return s=P(n.length,r.length),s||(s=P(n[n.length-2],r[r.length-2]),s||P(n[n.length-1],r[r.length-1]))}class pa{constructor(e,t){this.overlayedDocument=e,this.mutatedFields=t}}class fa{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,lt.empty(),O.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=Jn();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=Jn();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 s=Hn();const i=Zn(),a=Zn();return t.forEach(((e,t)=>{const a=n.get(t.key);r.has(t.key)&&(void 0===a||a.mutation instanceof Lr)?s=s.insert(t.key,t):void 0!==a?(i.set(t.key,a.mutation.getFieldMask()),Cr(a.mutation,t,a.mutation.getFieldMask(),O.now())):i.set(t.key,lt.empty())})),this.recalculateAndSaveOverlays(e,s).next((e=>(e.forEach(((e,t)=>i.set(e,t))),t.forEach(((e,t)=>{var n;return a.set(e,new pa(t,null!==(n=i.get(e))&&void 0!==n?n:null))})),a)))}recalculateAndSaveOverlays(e,t){const n=Zn();let r=new nt(((e,t)=>e-t)),s=nr();return this.mutationQueue.getAllMutationBatchesAffectingDocumentKeys(e,t).next((e=>{for(const s of e)s.keys().forEach((e=>{const i=t.get(e);if(null===i)return;let a=n.get(e)||lt.empty();a=s.applyToLocalView(i,a),n.set(e,a);const o=(r.get(s.batchId)||nr()).add(e);r=r.insert(s.batchId,o)}))})).next((()=>{const i=[],a=r.getReverseIterator();for(;a.hasNext();){const r=a.getNext(),o=r.key,l=r.value,c=Xn();l.forEach((e=>{if(!s.has(e)){const r=_r(t.get(e),n.get(e));null!==r&&c.set(e,r),s=s.add(e)}})),i.push(this.documentOverlayCache.saveOverlays(e,o,c))}return se.waitFor(i)})).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):Ln(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((s=>{const i=r-s.size>0?this.documentOverlayCache.getOverlaysForCollectionGroup(e,t,n.largestBatchId,r-s.size):se.resolve(Jn());let a=-1,o=s;return i.next((t=>se.forEach(t,((t,n)=>(a<n.largestBatchId&&(a=n.largestBatchId),s.get(t)?se.resolve():this.remoteDocumentCache.getEntry(e,t).next((e=>{o=o.insert(t,e)}))))).next((()=>this.populateOverlays(e,t,s))).next((()=>this.computeViews(e,o,t,nr()))).next((e=>({batchId:a,changes:Yn(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 s=t.collectionGroup;let i=Wn();return this.indexManager.getCollectionParents(e,s).next((a=>se.forEach(a,(a=>{const o=function(e,t){return new Cn(t,null,e.explicitOrderBy.slice(),e.filters.slice(),e.limit,e.limitType,e.startAt,e.endAt)}(t,a.child(s));return this.getDocumentsMatchingCollectionQuery(e,o,n,r).next((e=>{e.forEach(((e,t)=>{i=i.insert(e,t)}))}))})).next((()=>i))))}getDocumentsMatchingCollectionQuery(e,t,n,r){let s;return this.documentOverlayCache.getOverlaysForCollection(e,t.path,n.largestBatchId).next((i=>(s=i,this.remoteDocumentCache.getDocumentsMatchingQuery(e,t,n,s,r)))).next((e=>{s.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 i=s.get(e);void 0!==i&&Cr(i.mutation,r,lt.empty(),O.now()),Un(t,r)&&(n=n.insert(e,r))})),n}))}}class ma{constructor(e){this.serializer=e,this.Tr=new Map,this.Ir=new Map}getBundleMetadata(e,t){return se.resolve(this.Tr.get(t))}saveBundleMetadata(e,t){return this.Tr.set(t.id,function(e){return{id:e.id,version:e.version,createTime:vs(e.createTime)}}(t)),se.resolve()}getNamedQuery(e,t){return se.resolve(this.Ir.get(t))}saveNamedQuery(e,t){return this.Ir.set(t.name,function(e){return{name:e.name,query:Xs(e.bundledQuery),readTime:vs(e.readTime)}}(t)),se.resolve()}}class va{constructor(){this.overlays=new nt(j.comparator),this.Er=new Map}getOverlay(e,t){return se.resolve(this.overlays.get(t))}getOverlays(e,t){const n=Jn();return se.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)})),se.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)),se.resolve()}getOverlaysForCollection(e,t,n){const r=Jn(),s=t.length+1,i=new j(t.child("")),a=this.overlays.getIteratorFrom(i);for(;a.hasNext();){const e=a.getNext().value,i=e.getKey();if(!t.isPrefixOf(i.path))break;i.path.length===s&&e.largestBatchId>n&&r.set(e.getKey(),e)}return se.resolve(r)}getOverlaysForCollectionGroup(e,t,n,r){let s=new nt(((e,t)=>e-t));const i=this.overlays.getIterator();for(;i.hasNext();){const e=i.getNext().value;if(e.getKey().getCollectionGroup()===t&&e.largestBatchId>n){let t=s.get(e.largestBatchId);null===t&&(t=Jn(),s=s.insert(e.largestBatchId,t)),t.set(e.getKey(),e)}}const a=Jn(),o=s.getIterator();for(;o.hasNext()&&(o.getNext().value.forEach(((e,t)=>a.set(e,t))),!(a.size()>=r)););return se.resolve(a)}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 Fr(t,n));let s=this.Er.get(t);void 0===s&&(s=nr(),this.Er.set(t,s)),this.Er.set(t,s.add(n.key))}}class ga{constructor(){this.sessionToken=ut.EMPTY_BYTE_STRING}getSessionToken(e){return se.resolve(this.sessionToken)}setSessionToken(e,t){return this.sessionToken=t,se.resolve()}}class ya{constructor(){this.dr=new it(wa.Ar),this.Rr=new it(wa.Vr)}isEmpty(){return this.dr.isEmpty()}addReference(e,t){const n=new wa(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 wa(e,t))}pr(e,t){e.forEach((e=>this.removeReference(e,t)))}yr(e){const t=new j(new q([])),n=new wa(t,e),r=new wa(t,e+1),s=[];return this.Rr.forEachInRange([n,r],(e=>{this.gr(e),s.push(e.key)})),s}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 q([])),n=new wa(t,e),r=new wa(t,e+1);let s=nr();return this.Rr.forEachInRange([n,r],(e=>{s=s.add(e.key)})),s}containsKey(e){const t=new wa(e,0),n=this.dr.firstAfterOrEqual(t);return null!==n&&e.isEqual(n.key)}}class wa{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 ba{constructor(e,t){this.indexManager=e,this.referenceDelegate=t,this.mutationQueue=[],this.Dr=1,this.vr=new it(wa.Ar)}checkEmpty(e){return se.resolve(0===this.mutationQueue.length)}addMutationBatch(e,t,n,r){const s=this.Dr;this.Dr++,this.mutationQueue.length>0&&this.mutationQueue[this.mutationQueue.length-1];const i=new Or(s,t,n,r);this.mutationQueue.push(i);for(const t of r)this.vr=this.vr.add(new wa(t.key,s)),this.indexManager.addToCollectionParentIndex(e,t.key.path.popLast());return se.resolve(i)}lookupMutationBatch(e,t){return se.resolve(this.Cr(t))}getNextMutationBatchAfterBatchId(e,t){const n=t+1,r=this.Fr(n),s=r<0?0:r;return se.resolve(this.mutationQueue.length>s?this.mutationQueue[s]:null)}getHighestUnacknowledgedBatchId(){return se.resolve(0===this.mutationQueue.length?-1:this.Dr-1)}getAllMutationBatches(e){return se.resolve(this.mutationQueue.slice())}getAllMutationBatchesAffectingDocumentKey(e,t){const n=new wa(t,0),r=new wa(t,Number.POSITIVE_INFINITY),s=[];return this.vr.forEachInRange([n,r],(e=>{const t=this.Cr(e.br);s.push(t)})),se.resolve(s)}getAllMutationBatchesAffectingDocumentKeys(e,t){let n=new it(P);return t.forEach((e=>{const t=new wa(e,0),r=new wa(e,Number.POSITIVE_INFINITY);this.vr.forEachInRange([t,r],(e=>{n=n.add(e.br)}))})),se.resolve(this.Mr(n))}getAllMutationBatchesAffectingQuery(e,t){const n=t.path,r=n.length+1;let s=n;j.isDocumentKey(s)||(s=s.child(""));const i=new wa(new j(s),0);let a=new it(P);return this.vr.forEachWhile((e=>{const t=e.key.path;return!!n.isPrefixOf(t)&&(t.length===r&&(a=a.add(e.br)),!0)}),i),se.resolve(this.Mr(a))}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 se.forEach(t.mutations,(r=>{const s=new wa(r.key,t.batchId);return n=n.delete(s),this.referenceDelegate.markPotentiallyOrphaned(e,r.key)})).next((()=>{this.vr=n}))}Ln(e){}containsKey(e,t){const n=new wa(t,0),r=this.vr.firstAfterOrEqual(n);return se.resolve(t.isEqual(r&&r.key))}performConsistencyCheck(e){return this.mutationQueue.length,se.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 Sa{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),s=r?r.size:0,i=this.Nr(t);return this.docs=this.docs.insert(n,{document:t.mutableCopy(),size:i}),this.size+=i-s,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 se.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))})),se.resolve(n)}getDocumentsMatchingQuery(e,t,n,r){let s=Hn();const i=t.path,a=new j(i.child("")),o=this.docs.getIteratorFrom(a);for(;o.hasNext();){const{key:e,value:{document:a}}=o.getNext();if(!i.isPrefixOf(e.path))break;e.path.length>i.length+1||ee(X(a),n)<=0||(r.has(a.key)||Un(t,a))&&(s=s.insert(a.key,a.mutableCopy()))}return se.resolve(s)}getAllFromCollectionGroup(e,t,n,r){y()}Lr(e,t){return se.forEach(this.docs,(e=>t(e)))}newChangeBuffer(e){return new xa(this)}getSize(e){return se.resolve(this.size)}}class xa extends sa{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)})),se.waitFor(t)}getFromCache(e,t){return this.hr.getEntry(e,t)}getAllFromCache(e,t){return this.hr.getEntries(e,t)}}class Ea{constructor(e){this.persistence=e,this.Br=new Gn((e=>Sn(e)),xn),this.lastRemoteSnapshotVersion=$.min(),this.highestTargetId=0,this.kr=0,this.qr=new ya,this.targetCount=0,this.Qr=Ki.qn()}forEachTarget(e,t){return this.Br.forEach(((e,n)=>t(n))),se.resolve()}getLastRemoteSnapshotVersion(e){return se.resolve(this.lastRemoteSnapshotVersion)}getHighestSequenceNumber(e){return se.resolve(this.kr)}allocateTargetId(e){return this.highestTargetId=this.Qr.next(),se.resolve(this.highestTargetId)}setTargetsMetadata(e,t,n){return n&&(this.lastRemoteSnapshotVersion=n),t>this.kr&&(this.kr=t),se.resolve()}Un(e){this.Br.set(e.target,e);const t=e.targetId;t>this.highestTargetId&&(this.Qr=new Ki(t),this.highestTargetId=t),e.sequenceNumber>this.kr&&(this.kr=e.sequenceNumber)}addTargetData(e,t){return this.Un(t),this.targetCount+=1,se.resolve()}updateTargetData(e,t){return this.Un(t),se.resolve()}removeTargetData(e,t){return this.Br.delete(t.target),this.qr.yr(t.targetId),this.targetCount-=1,se.resolve()}removeTargets(e,t,n){let r=0;const s=[];return this.Br.forEach(((i,a)=>{a.sequenceNumber<=t&&null===n.get(a.targetId)&&(this.Br.delete(i),s.push(this.removeMatchingKeysForTargetId(e,a.targetId)),r++)})),se.waitFor(s).next((()=>r))}getTargetCount(e){return se.resolve(this.targetCount)}getTargetData(e,t){const n=this.Br.get(t)||null;return se.resolve(n)}addMatchingKeys(e,t,n){return this.qr.mr(t,n),se.resolve()}removeMatchingKeys(e,t,n){this.qr.pr(t,n);const r=this.persistence.referenceDelegate,s=[];return r&&t.forEach((t=>{s.push(r.markPotentiallyOrphaned(e,t))})),se.waitFor(s)}removeMatchingKeysForTargetId(e,t){return this.qr.yr(t),se.resolve()}getMatchingKeysForTargetId(e,t){const n=this.qr.Sr(t);return se.resolve(n)}containsKey(e,t){return se.resolve(this.qr.containsKey(t))}}class Ia{constructor(e,t){this.Kr={},this.overlays={},this.$r=new ge(0),this.Ur=!1,this.Ur=!0,this.Wr=new ga,this.referenceDelegate=e(this),this.Gr=new Ea(this),this.indexManager=new Ai,this.remoteDocumentCache=function(e){return new Sa(e)}((e=>this.referenceDelegate.zr(e))),this.serializer=new zs(t),this.jr=new ma(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 va,this.overlays[e.toKey()]=t),t}getMutationQueue(e,t){let n=this.Kr[e.toKey()];return n||(n=new ba(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){f("MemoryPersistence","Starting transaction:",e);const r=new _a(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 se.or(Object.values(this.Kr).map((n=>()=>n.containsKey(e,t))))}}class _a extends ne{constructor(e){super(),this.currentSequenceNumber=e}}class Ta{constructor(e){this.persistence=e,this.Zr=new ya,this.Xr=null}static ei(e){return new Ta(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()),se.resolve()}removeReference(e,t,n){return this.Zr.removeReference(n,t),this.ti.add(n.toString()),se.resolve()}markPotentiallyOrphaned(e,t){return this.ti.add(t.toString()),se.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 se.forEach(this.ti,(n=>{const r=j.fromPath(n);return this.ni(e,r).next((e=>{e||t.removeEntry(r,$.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 se.or([()=>se.resolve(this.Zr.containsKey(t)),()=>this.persistence.getTargetCache().containsKey(e,t),()=>this.persistence.Yr(e,t)])}}class Ca{constructor(e,t){this.persistence=e,this.ri=new Gn((e=>Se(e.path)),((e,t)=>e.isEqual(t))),this.garbageCollector=ta(this,t)}static ei(e,t){return new Ca(e,t)}Hr(){}Jr(e){return se.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 se.forEach(this.ri,((n,r)=>this.ir(e,n,r).next((e=>e?se.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(),s=r.newChangeBuffer();return r.Lr(e,(r=>this.ir(e,r,t).next((e=>{e||(n++,s.removeEntry(r,$.min()))})))).next((()=>s.apply(e))).next((()=>n))}markPotentiallyOrphaned(e,t){return this.ri.set(t,e.currentSequenceNumber),se.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),se.resolve()}removeReference(e,t,n){return this.ri.set(n,e.currentSequenceNumber),se.resolve()}updateLimboDocument(e,t){return this.ri.set(t,e.currentSequenceNumber),se.resolve()}zr(e){let t=e.key.toString().length;return e.isFoundDocument()&&(t+=kt(e.data.value)),t}ir(e,t,n){return se.or([()=>this.persistence.Yr(e,t),()=>this.persistence.getTargetCache().containsKey(e,t),()=>{const e=this.ri.get(t);return se.resolve(void 0!==e&&e>n)}])}getCacheSize(e){return this.persistence.getRemoteDocumentCache().getSize(e)}}class Aa{constructor(e){this.serializer=e}O(e,t,n,r){const s=new ie("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",_e,{unique:!0}),e.createObjectStore("documentMutations")}(e),Da(e),function(e){e.createObjectStore("remoteDocuments")}(e));let i=se.resolve();return n<3&&r>=3&&(0!==n&&(function(e){e.deleteObjectStore("targetDocuments"),e.deleteObjectStore("targets"),e.deleteObjectStore("targetGlobal")}(e),Da(e)),i=i.next((()=>function(e){const t=e.store("targetGlobal"),n={highestTargetId:0,highestListenSequenceNumber:0,lastRemoteSnapshotVersion:$.min().toTimestamp(),targetCount:0};return t.put("targetGlobalKey",n)}(s)))),n<4&&r>=4&&(0!==n&&(i=i.next((()=>function(e,t){return t.store("mutations").U().next((n=>{e.deleteObjectStore("mutations"),e.createObjectStore("mutations",{keyPath:"batchId",autoIncrement:!0}).createIndex("userMutationsIndex",_e,{unique:!0});const r=t.store("mutations"),s=n.map((e=>r.put(e)));return se.waitFor(s)}))}(e,s)))),i=i.next((()=>{!function(e){e.createObjectStore("clientMetadata",{keyPath:"clientId"})}(e)}))),n<5&&r>=5&&(i=i.next((()=>this.ii(s)))),n<6&&r>=6&&(i=i.next((()=>(function(e){e.createObjectStore("remoteDocumentGlobal")}(e),this.si(s))))),n<7&&r>=7&&(i=i.next((()=>this.oi(s)))),n<8&&r>=8&&(i=i.next((()=>this._i(e,s)))),n<9&&r>=9&&(i=i.next((()=>{!function(e){e.objectStoreNames.contains("remoteDocumentChanges")&&e.deleteObjectStore("remoteDocumentChanges")}(e)}))),n<10&&r>=10&&(i=i.next((()=>this.ai(s)))),n<11&&r>=11&&(i=i.next((()=>{!function(e){e.createObjectStore("bundles",{keyPath:"bundleId"})}(e),function(e){e.createObjectStore("namedQueries",{keyPath:"name"})}(e)}))),n<12&&r>=12&&(i=i.next((()=>{!function(e){const t=e.createObjectStore("documentOverlays",{keyPath:qe});t.createIndex("collectionPathOverlayIndex",Ue,{unique:!1}),t.createIndex("collectionGroupOverlayIndex",Be,{unique:!1})}(e)}))),n<13&&r>=13&&(i=i.next((()=>function(e){const t=e.createObjectStore("remoteDocumentsV14",{keyPath:De});t.createIndex("documentKeyIndex",ke),t.createIndex("collectionGroupIndex",Le)}(e))).next((()=>this.ui(e,s))).next((()=>e.deleteObjectStore("remoteDocuments")))),n<14&&r>=14&&(i=i.next((()=>this.ci(e,s)))),n<15&&r>=15&&(i=i.next((()=>function(e){e.createObjectStore("indexConfiguration",{keyPath:"indexId",autoIncrement:!0}).createIndex("collectionGroupIndex","collectionGroup",{unique:!1}),e.createObjectStore("indexState",{keyPath:Ve}).createIndex("sequenceNumberIndex",Oe,{unique:!1}),e.createObjectStore("indexEntries",{keyPath:$e}).createIndex("documentKeyIndex",Fe,{unique:!1})}(e)))),n<16&&r>=16&&(i=i.next((()=>{t.objectStore("indexState").clear()})).next((()=>{t.objectStore("indexEntries").clear()}))),n<17&&r>=17&&(i=i.next((()=>{!function(e){e.createObjectStore("globals",{keyPath:"name"})}(e)}))),i}si(e){let t=0;return e.store("remoteDocuments").J(((e,n)=>{t+=qi(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=>se.forEach(t,(t=>{const r=IDBKeyRange.bound([t.userId,-1],[t.userId,t.lastAcknowledgedBatchId]);return n.U("userMutationsIndex",r).next((n=>se.forEach(n,(n=>{w(n.userId===t.userId);const r=Ws(this.serializer,n);return Fi(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,s)=>{const i=new q(n),a=function(e){return[0,Se(e)]}(i);r.push(t.get(a).next((n=>n?se.resolve():(n=>t.put({targetId:0,path:Se(n),sequenceNumber:e.highestListenSequenceNumber}))(i))))})).next((()=>se.waitFor(r)))}))}_i(e,t){e.createObjectStore("collectionParents",{keyPath:Re});const n=t.store("collectionParents"),r=new Di,s=e=>{if(r.add(e)){const t=e.lastSegment(),r=e.popLast();return n.put({collectionId:t,parent:Se(r)})}};return t.store("remoteDocuments").J({H:!0},((e,t)=>{const n=new q(e);return s(n.popLast())})).next((()=>t.store("documentMutations").J({H:!0},(([e,t,n],r)=>{const i=Ie(t);return s(i.popLast())}))))}ai(e){const t=e.store("targets");return t.J(((e,n)=>{const r=Ys(n),s=Js(this.serializer,r);return t.put(s)}))}ui(e,t){const n=t.store("remoteDocuments"),r=[];return n.J(((e,n)=>{const s=t.store("remoteDocumentsV14"),i=function(e){return e.document?new j(q.fromString(e.document.name).popFirst(5)):e.noDocument?j.fromSegments(e.noDocument.path):e.unknownDocument?j.fromSegments(e.unknownDocument.path):y()}(n).path.toArray(),a={prefixPath:i.slice(0,i.length-2),collectionGroup:i[i.length-2],documentId:i[i.length-1],readTime:n.readTime||[0,0],unknownDocument:n.unknownDocument,noDocument:n.noDocument,document:n.document,hasCommittedMutations:!!n.hasCommittedMutations};r.push(s.put(a))})).next((()=>se.waitFor(r)))}ci(e,t){const n=t.store("mutations"),r=aa(this.serializer),s=new Ia(Ta.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();Ws(this.serializer,e).keys().forEach((e=>r=r.add(e))),n.set(e.userId,r)})),se.forEach(n,((e,n)=>{const i=new u(n),a=ii.Pt(this.serializer,i),o=s.getIndexManager(i),l=Ui.Pt(i,this.serializer,o,s.referenceDelegate);return new fa(r,l,a,o).recalculateAndSaveOverlaysForDocumentKeys(new Ye(t,ge.oe),e).next()}))}))}}function Da(e){e.createObjectStore("targetDocuments",{keyPath:Ne}).createIndex("documentTargetsIndex",Pe,{unique:!0}),e.createObjectStore("targets",{keyPath:"targetId"}).createIndex("queryTargetsIndex",Me,{unique:!0}),e.createObjectStore("targetGlobal")}const ka="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 La{constructor(e,t,n,r,s,i,a,o,l,c,u=17){if(this.allowTabSynchronization=e,this.persistenceKey=t,this.clientId=n,this.li=s,this.window=i,this.document=a,this.hi=l,this.Pi=c,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(),!La.p())throw new x(S.UNIMPLEMENTED,"This platform is either missing IndexedDB or is known to have an incomplete implementation. Offline persistence has been disabled.");this.referenceDelegate=new na(this,r),this.Vi=t+"main",this.serializer=new zs(o),this.mi=new ae(this.Vi,this.Ti,new Aa(this.serializer)),this.Wr=new oi,this.Gr=new Hi(this.referenceDelegate,this.serializer),this.remoteDocumentCache=aa(this.serializer),this.jr=new ni,this.window&&this.window.localStorage?this.fi=this.window.localStorage:(this.fi=null,!1===c&&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 x(S.FAILED_PRECONDITION,ka);return this.pi(),this.yi(),this.wi(),this.runTransaction("getHighestListenSequenceNumber","readonly",(e=>this.Gr.getHighestSequenceNumber(e)))})).then((e=>{this.$r=new ge(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=>Na(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 f("IndexedDbPersistence","Failed to extend owner lease: ",e),this.isPrimary;if(!this.allowTabSynchronization)throw e;return f("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 Ma(e).get("owner").next((e=>se.resolve(this.Fi(e))))}Mi(e){return Na(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=Je(e,"clientMetadata");return t.U().next((e=>{const n=this.Ni(e,18e5),r=e.filter((e=>-1===n.indexOf(e)));return se.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?se.resolve(!0):Ma(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 x(S.FAILED_PRECONDITION,ka);return!1}}return!(!this.networkEnabled||!this.inForeground)||Na(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&&f("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 Ye(e,ge.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=>Na(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 Ui.Pt(e,this.serializer,t,this.referenceDelegate)}getTargetCache(){return this.Gr}getRemoteDocumentCache(){return this.remoteDocumentCache}getIndexManager(e){return new Li(e,this.serializer.ht.databaseId)}getDocumentOverlayCache(e){return ii.Pt(this.serializer,e)}getBundleCache(){return this.jr}runTransaction(e,t,n){f("IndexedDbPersistence","Starting transaction:",e);const r="readonly"===t?"readonly":"readwrite",s=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 i;return this.mi.runTransaction(e,r,s,(r=>(i=new Ye(r,this.$r?this.$r.next():ge.oe),"readwrite-primary"===t?this.bi(i).next((e=>!!e||this.Di(i))).next((t=>{if(!t)throw m(`Failed to obtain primary lease for action '${e}'.`),this.isPrimary=!1,this.li.enqueueRetryable((()=>this.Ri(!1))),new x(S.FAILED_PRECONDITION,te);return n(i)})).next((e=>this.Ci(i).next((()=>e)))):this.Ui(i).next((()=>n(i)))))).then((e=>(i.raiseOnCommittedEvent(),e)))}Ui(e){return Ma(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 x(S.FAILED_PRECONDITION,ka)}))}Ci(e){const t={ownerId:this.clientId,allowTabSynchronization:this.allowTabSynchronization,leaseTimestampMs:Date.now()};return Ma(e).put("owner",t)}static p(){return ae.p()}vi(e){const t=Ma(e);return t.get("owner").next((e=>this.Fi(e)?(f("IndexedDbPersistence","Releasing primary lease."),t.delete("owner")):se.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]/;a.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 f("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 Ma(e){return Je(e,"owner")}function Na(e){return Je(e,"clientMetadata")}function Pa(e,t){let n=e.projectId;return e.isDefaultDatabase||(n+="."+e.database),"firestore/"+t+"/"+n+"/"}class Ra{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 Ra(e,t.fromCache,n,r)}}class Va{constructor(){this._documentReadCount=0}get documentReadCount(){return this._documentReadCount}incrementDocumentReadCount(e){this._documentReadCount+=e}}class Oa{constructor(){this.ji=!1,this.Hi=!1,this.Ji=100,this.Yi=a.isSafari()?8:oe(a.getUA())>0?6:4}initialize(e,t){this.Zi=e,this.indexManager=t,this.ji=!0}getDocumentsMatchingQuery(e,t,n,r){const s={result:null};return this.Xi(e,t).next((e=>{s.result=e})).next((()=>{if(!s.result)return this.es(e,t,r,n).next((e=>{s.result=e}))})).next((()=>{if(s.result)return;const n=new Va;return this.ts(e,t,n).next((r=>{if(s.result=r,this.Hi)return this.ns(e,t,n,r.size)}))})).next((()=>s.result))}ns(e,t,n,r){return n.documentReadCount<this.Ji?(p()<=i.LogLevel.DEBUG&&f("QueryEngine","SDK will not create cache indexes for query:",qn(t),"since it only creates cache indexes for collection contains","more than or equal to",this.Ji,"documents"),se.resolve()):(p()<=i.LogLevel.DEBUG&&f("QueryEngine","Query:",qn(t),"scans",n.documentReadCount,"local documents and returns",r,"documents as results."),n.documentReadCount>this.Yi*r?(p()<=i.LogLevel.DEBUG&&f("QueryEngine","The SDK decides to create cache indexes for query:",qn(t),"as using cache indexes may help improve performance."),this.indexManager.createTargetIndexes(e,Nn(t))):se.resolve())}Xi(e,t){if(kn(t))return se.resolve(null);let n=Nn(t);return this.indexManager.getIndexType(e,n).next((r=>0===r?null:(null!==t.limit&&1===r&&(t=On(t,null,"F"),n=Nn(t)),this.indexManager.getDocumentsMatchingTarget(e,n).next((r=>{const s=nr(...r);return this.Zi.getDocuments(e,s).next((r=>this.indexManager.getMinOffset(e,n).next((n=>{const i=this.rs(t,r);return this.ss(t,i,s,n.readTime)?this.Xi(e,On(t,null,"F")):this.os(e,i,t,n)}))))})))))}es(e,t,n,r){return kn(t)||r.isEqual($.min())?se.resolve(null):this.Zi.getDocuments(e,n).next((s=>{const a=this.rs(t,s);return this.ss(t,a,n,r)?se.resolve(null):(p()<=i.LogLevel.DEBUG&&f("QueryEngine","Re-using previous result from %s to execute query: %s",r.toString(),qn(t)),this.os(e,a,t,J(r,-1)).next((e=>e)))}))}rs(e,t){let n=new it(jn(e));return t.forEach(((t,r)=>{Un(e,r)&&(n=n.add(r))})),n}ss(e,t,n,r){if(null===e.limit)return!1;if(n.size!==t.size)return!0;const s="F"===e.limitType?t.last():t.first();return!!s&&(s.hasPendingWrites||s.version.compareTo(r)>0)}ts(e,t,n){return p()<=i.LogLevel.DEBUG&&f("QueryEngine","Using full collection scan to execute query:",qn(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 $a{constructor(e,t,n,r){this.persistence=e,this._s=t,this.serializer=r,this.us=new nt(P),this.cs=new Gn((e=>Sn(e)),xn),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 fa(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 Fa(e,t,n,r){return new $a(e,t,n,r)}async function qa(e,t){const n=b(e);return await n.persistence.runTransaction("Handle user change","readonly",(e=>{let r;return n.mutationQueue.getAllMutationBatches(e).next((s=>(r=s,n.Ps(t),n.mutationQueue.getAllMutationBatches(e)))).next((t=>{const s=[],i=[];let a=nr();for(const e of r){s.push(e.batchId);for(const t of e.mutations)a=a.add(t.key)}for(const e of t){i.push(e.batchId);for(const t of e.mutations)a=a.add(t.key)}return n.localDocuments.getDocuments(e,a).next((e=>({Ts:e,removedBatchIds:s,addedBatchIds:i})))}))}))}function Ua(e){const t=b(e);return t.persistence.runTransaction("Get last remote snapshot version","readonly",(e=>t.Gr.getLastRemoteSnapshotVersion(e)))}function Ba(e,t,n){let r=nr(),s=nr();return n.forEach((e=>r=r.add(e))),t.getEntries(e,r).next((e=>{let r=Hn();return n.forEach(((n,i)=>{const a=e.get(n);i.isFoundDocument()!==a.isFoundDocument()&&(s=s.add(n)),i.isNoDocument()&&i.version.isEqual($.min())?(t.removeEntry(n,i.readTime),r=r.insert(n,i)):!a.isValidDocument()||i.version.compareTo(a.version)>0||0===i.version.compareTo(a.version)&&a.hasPendingWrites?(t.addEntry(i),r=r.insert(n,i)):f("LocalStore","Ignoring outdated watch update for ",n,". Current version:",a.version," Watch version:",i.version)})),{Is:r,Es:s}}))}function ja(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 za(e,t){const n=b(e);return n.persistence.runTransaction("Allocate target","readwrite",(e=>{let r;return n.Gr.getTargetData(e,t).next((s=>s?(r=s,se.resolve(r)):n.Gr.allocateTargetId(e).next((s=>(r=new js(t,s,"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 Ga(e,t,n){const r=b(e),s=r.us.get(t),i=n?"readwrite":"readwrite-primary";try{n||await r.persistence.runTransaction("Release target",i,(e=>r.persistence.referenceDelegate.removeTarget(e,s)))}catch(e){if(!ue(e))throw e;f("LocalStore",`Failed to update sequence numbers for target ${t}: ${e}`)}r.us=r.us.remove(t),r.cs.delete(s.target)}function Ka(e,t,n){const r=b(e);let s=$.min(),i=nr();return r.persistence.runTransaction("Execute query","readwrite",(e=>function(e,t,n){const r=b(e),s=r.cs.get(n);return void 0!==s?se.resolve(r.us.get(s)):r.Gr.getTargetData(t,n)}(r,e,Nn(t)).next((t=>{if(t)return s=t.lastLimboFreeSnapshotVersion,r.Gr.getMatchingKeysForTargetId(e,t.targetId).next((e=>{i=e}))})).next((()=>r._s.getDocumentsMatchingQuery(e,t,n?s:$.min(),n?i:nr()))).next((e=>(Wa(r,Bn(t),e),{documents:e,ds:i})))))}function Ha(e,t){const n=b(e),r=b(n.Gr),s=n.us.get(t);return s?Promise.resolve(s.target):n.persistence.runTransaction("Get target data","readonly",(e=>r.ut(e,t).next((e=>e?e.target:null))))}function Qa(e,t){const n=b(e),r=n.ls.get(t)||$.min();return n.persistence.runTransaction("Get new document changes","readonly",(e=>n.hs.getAllFromCollectionGroup(e,t,J(r,-1),Number.MAX_SAFE_INTEGER))).then((e=>(Wa(n,t,e),e)))}function Wa(e,t,n){let r=e.ls.get(t)||$.min();n.forEach(((e,t)=>{t.readTime.compareTo(r)>0&&(r=t.readTime)})),e.ls.set(t,r)}async function Ya(e,t,n=nr()){const r=await za(e,Nn(Xs(t.bundledQuery))),s=b(e);return s.persistence.runTransaction("Save named query","readwrite",(e=>{const i=vs(t.readTime);if(r.snapshotVersion.compareTo(i)>=0)return s.jr.saveNamedQuery(e,t);const a=r.withResumeToken(ut.EMPTY_BYTE_STRING,i);return s.us=s.us.insert(a.targetId,a),s.Gr.updateTargetData(e,a).next((()=>s.Gr.removeMatchingKeysForTargetId(e,r.targetId))).next((()=>s.Gr.addMatchingKeys(e,n,r.targetId))).next((()=>s.jr.saveNamedQuery(e,t)))}))}function Ja(e,t){return`firestore_clients_${e}_${t}`}function Xa(e,t,n){let r=`firestore_mutations_${e}_${n}`;return t.isAuthenticated()&&(r+=`_${t.uid}`),r}function Za(e,t){return`firestore_targets_${e}_${t}`}class eo{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 s,i="object"==typeof r&&-1!==["pending","acknowledged","rejected"].indexOf(r.state)&&(void 0===r.error||"object"==typeof r.error);return i&&r.error&&(i="string"==typeof r.error.message&&"string"==typeof r.error.code,i&&(s=new x(r.error.code,r.error.message))),i?new eo(e,t,r.state,s):(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 to{constructor(e,t,n){this.targetId=e,this.state=t,this.error=n}static fs(e,t){const n=JSON.parse(t);let r,s="object"==typeof n&&-1!==["not-current","current","rejected"].indexOf(n.state)&&(void 0===n.error||"object"==typeof n.error);return s&&n.error&&(s="string"==typeof n.error.message&&"string"==typeof n.error.code,s&&(r=new x(n.error.code,n.error.message))),s?new to(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 no{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,s=sr();for(let e=0;r&&e<n.activeTargetIds.length;++e)r=be(n.activeTargetIds[e]),s=s.add(n.activeTargetIds[e]);return r?new no(e,s):(m("SharedClientState",`Failed to parse client data for instance '${e}': ${t}`),null)}}class ro{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 ro(t.clientId,t.onlineState):(m("SharedClientState",`Failed to parse online state: ${e}`),null)}}class so{constructor(){this.activeTargetIds=sr()}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 io{constructor(e,t,n,r,s){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 i=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");this.storage=this.window.localStorage,this.currentUser=s,this.Cs=Ja(this.persistenceKey,this.ws),this.Fs=function(e){return`firestore_sequence_number_${e}`}(this.persistenceKey),this.Ds=this.Ds.insert(this.ws,new so),this.Ms=new RegExp(`^firestore_clients_${i}_([^_]*)$`),this.xs=new RegExp(`^firestore_mutations_${i}_(\\d+)(?:_(.*))?$`),this.Os=new RegExp(`^firestore_targets_${i}_(\\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(Ja(this.persistenceKey,t));if(e){const n=no.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(Za(this.persistenceKey,e));if(t){const r=to.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(Za(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 f("SharedClientState","READ",e,t),t}setItem(e,t){f("SharedClientState","SET",e,t),this.storage.setItem(e,t)}removeItem(e){f("SharedClientState","REMOVE",e),this.storage.removeItem(e)}bs(e){const t=e;if(t.storageArea===this.storage){if(f("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=ge.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!==ge.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 eo(this.currentUser,e,t,n),s=Xa(this.persistenceKey,this.currentUser,e);this.setItem(s,r.gs())}$s(e){const t=Xa(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=Za(this.persistenceKey,e),s=new to(e,t,n);this.setItem(r,s.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 no.fs(n,t)}Ys(e,t){const n=this.xs.exec(e),r=Number(n[1]),s=void 0!==n[2]?n[2]:null;return eo.fs(new u(s),r,t)}Xs(e,t){const n=this.Os.exec(e),r=Number(n[1]);return to.fs(r,t)}ks(e){return ro.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);f("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),s=this.Qs(n),i=[],a=[];return s.forEach((e=>{r.has(e)||i.push(e)})),r.forEach((e=>{s.has(e)||a.push(e)})),this.syncEngine.oo(i,a).then((()=>{this.Ds=n}))}qs(e){this.Ds.get(e.clientId)&&this.onlineStateHandler(e.onlineState)}Qs(e){let t=sr();return e.forEach(((e,n)=>{t=t.unionWith(n.activeTargetIds)})),t}}class ao{constructor(){this._o=new so,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 so,Promise.resolve()}handleUserChange(e,t,n){}setOnlineState(e){}shutdown(){}writeSequenceNumber(e){}notifyBundleLoaded(e){}}class oo{uo(e){}shutdown(){}}class lo{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(){f("ConnectivityMonitor","Network connectivity changed: AVAILABLE");for(const e of this.To)e(0)}Po(){f("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 co=null;function uo(){return null===co?co=268435456+Math.round(2147483648*Math.random()):co++,"0x"+co.toString(16)}const ho={BatchGetDocuments:"batchGet",Commit:"commit",RunQuery:"runQuery",RunAggregationQuery:"runAggregationQuery"};class po{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 fo="WebChannelConnection";class mo 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,s){const i=uo(),a=this.No(e,t.toUriEncodedString());f("RestConnection",`Sending RPC '${e}' ${i}:`,a,n);const o={"google-cloud-resource-prefix":this.Mo,"x-goog-request-params":this.xo};return this.Lo(o,r,s),this.Bo(e,a,o,n).then((t=>(f("RestConnection",`Received RPC '${e}' ${i}: `,t),t)),(t=>{throw v("RestConnection",`RPC '${e}' ${i} failed with error: `,t,"url: ",a,"request:",n),t}))}ko(e,t,n,r,s,i){return this.Oo(e,t,n,r,s)}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=ho[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 s=uo();return new Promise(((i,a)=>{const o=new l.XhrIo;o.setWithCredentials(!0),o.listenOnce(l.EventType.COMPLETE,(()=>{try{switch(o.getLastErrorCode()){case l.ErrorCode.NO_ERROR:const t=o.getResponseJson();f(fo,`XHR for RPC '${e}' ${s} received:`,JSON.stringify(t)),i(t);break;case l.ErrorCode.TIMEOUT:f(fo,`RPC '${e}' ${s} timed out`),a(new x(S.DEADLINE_EXCEEDED,"Request time out"));break;case l.ErrorCode.HTTP_ERROR:const n=o.getStatus();if(f(fo,`RPC '${e}' ${s} failed with status:`,n,"response text:",o.getResponseText()),n>0){let e=o.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(S).indexOf(t)>=0?t:S.UNKNOWN}(t.status);a(new x(e,t.message))}else a(new x(S.UNKNOWN,"Server responded with status "+o.getStatus()))}else a(new x(S.UNAVAILABLE,"Connection failed."));break;default:y()}}finally{f(fo,`RPC '${e}' ${s} completed.`)}}));const c=JSON.stringify(r);f(fo,`RPC '${e}' ${s} sending request:`,r),o.send(t,"POST",c,n,15)}))}qo(e,t,n){const r=uo(),s=[this.Fo,"/","google.firestore.v1.Firestore","/",e,"/channel"],i=l.createWebChannelTransport(),a=l.getStatEventTarget(),o={httpSessionIdParam:"gsessionid",initMessageHeaders:{},messageUrlParams:{database:`projects/${this.databaseId.projectId}/databases/${this.databaseId.database}`},sendRawJson:!0,supportsCrossDomainXhr:!0,internalChannelParams:{forwardChannelRequestTimeoutMs:6e5},forceLongPolling:this.forceLongPolling,detectBufferingProxy:this.autoDetectLongPolling},c=this.longPollingOptions.timeoutSeconds;void 0!==c&&(o.longPollingTimeout=Math.round(1e3*c)),this.useFetchStreams&&(o.useFetchStreams=!0),this.Lo(o.initMessageHeaders,t,n),o.encodeInitMessageHeaders=!0;const u=s.join("");f(fo,`Creating RPC '${e}' stream ${r}: ${u}`,o);const d=i.createWebChannel(u,o);let h=!1,p=!1;const m=new po({Eo:t=>{p?f(fo,`Not sending because RPC '${e}' stream ${r} is closed:`,t):(h||(f(fo,`Opening RPC '${e}' stream ${r} transport.`),d.open(),h=!0),f(fo,`RPC '${e}' stream ${r} sending:`,t),d.send(t))},Ao:()=>d.close()}),g=(e,t,n)=>{e.listen(t,(e=>{try{n(e)}catch(e){setTimeout((()=>{throw e}),0)}}))};return g(d,l.WebChannel.EventType.OPEN,(()=>{p||(f(fo,`RPC '${e}' stream ${r} transport opened.`),m.So())})),g(d,l.WebChannel.EventType.CLOSE,(()=>{p||(p=!0,f(fo,`RPC '${e}' stream ${r} transport closed`),m.Do())})),g(d,l.WebChannel.EventType.ERROR,(t=>{p||(p=!0,v(fo,`RPC '${e}' stream ${r} transport errored:`,t),m.Do(new x(S.UNAVAILABLE,"The operation could not be completed")))})),g(d,l.WebChannel.EventType.MESSAGE,(t=>{var n;if(!p){const s=t.data[0];w(!!s);const i=s,a=(null==i?void 0:i.error)||(null===(n=i[0])||void 0===n?void 0:n.error);if(a){f(fo,`RPC '${e}' stream ${r} received error:`,a);const t=a.status;let n=function(e){const t=Br[e];if(void 0!==t)return Gr(t)}(t),s=a.message;void 0===n&&(n=S.INTERNAL,s="Unknown error status: "+t+" with message "+a.message),p=!0,m.Do(new x(n,s)),d.close()}else f(fo,`RPC '${e}' stream ${r} received:`,s),m.vo(s)}})),g(a,l.Event.STAT_EVENT,(t=>{t.stat===l.Stat.PROXY?f(fo,`RPC '${e}' stream ${r} detected buffering proxy`):t.stat===l.Stat.NOPROXY&&f(fo,`RPC '${e}' stream ${r} detected no buffering proxy`)})),setTimeout((()=>{m.bo()}),0),m}}function vo(){return"undefined"!=typeof window?window:null}function go(){return"undefined"!=typeof document?document:null}function yo(e){return new ds(e,!0)}class wo{constructor(e,t,n=1e3,r=1.5,s=6e4){this.li=e,this.timerId=t,this.Qo=n,this.Ko=r,this.$o=s,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&&f("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 bo{constructor(e,t,n,r,s,i,a,o){this.li=e,this.Yo=n,this.Zo=r,this.connection=s,this.authCredentialsProvider=i,this.appCheckCredentialsProvider=a,this.listener=o,this.state=0,this.Xo=0,this.e_=null,this.t_=null,this.stream=null,this.n_=0,this.r_=new wo(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===S.RESOURCE_EXHAUSTED?(m(t.toString()),m("Using maximum backoff delay to prevent overloading the backend."),this.r_.zo()):t&&t.code===S.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 x(S.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 f("PersistentStream",`close with error: ${e}`),this.stream=null,this.close(4,e)}T_(e){return t=>{this.li.enqueueAndForget((()=>this.Xo===e?t():(f("PersistentStream","stream callback skipped by getCloseGuardedDispatcher."),Promise.resolve())))}}}class So extends bo{constructor(e,t,n,r,s,i){super(e,"listen_stream_connection_backoff","listen_stream_idle","health_check_timeout",t,n,r,i),this.serializer=s}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"),s=t.targetChange.targetIds||[],i=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),a=t.targetChange.cause,o=a&&function(e){const t=void 0===e.code?S.UNKNOWN:Gr(e.code);return new x(t,e.message||"")}(a);n=new rs(r,s,i,o||null)}else if("documentChange"in t){t.documentChange;const r=t.documentChange;r.document,r.document.name,r.document.updateTime;const s=Ss(e,r.document.name),i=vs(r.document.updateTime),a=r.document.createTime?vs(r.document.createTime):$.min(),o=new Gt({mapValue:{fields:r.document.fields}}),l=Ht.newFoundDocument(s,i,a,o),c=r.targetIds||[],u=r.removedTargetIds||[];n=new ts(c,u,l.key,l)}else if("documentDelete"in t){t.documentDelete;const r=t.documentDelete;r.document;const s=Ss(e,r.document),i=r.readTime?vs(r.readTime):$.min(),a=Ht.newNoDocument(s,i),o=r.removedTargetIds||[];n=new ts([],o,a.key,a)}else if("documentRemove"in t){t.documentRemove;const r=t.documentRemove;r.document;const s=Ss(e,r.document),i=r.removedTargetIds||[];n=new ts([],i,s,null)}else{if(!("filter"in t))return y();{t.filter;const e=t.filter;e.targetId;const{count:r=0,unchangedNames:s}=e,i=new Ur(r,s),a=e.targetId;n=new ns(a,i)}}return n}(this.serializer,e),n=function(e){if(!("targetChange"in e))return $.min();const t=e.targetChange;return t.targetIds&&t.targetIds.length?$.min():t.readTime?vs(t.readTime):$.min()}(e);return this.listener.R_(t,n)}V_(e){const t={};t.database=Is(this.serializer),t.addTarget=function(e,t){let n;const r=t.target;if(n=En(r)?{documents:ks(e,r)}:{query:Ls(e,r).ct},n.targetId=t.targetId,t.resumeToken.approximateByteSize()>0){n.resumeToken=fs(e,t.resumeToken);const r=hs(e,t.expectedCount);null!==r&&(n.expectedCount=r)}else if(t.snapshotVersion.compareTo($.min())>0){n.readTime=ps(e,t.snapshotVersion.toTimestamp());const r=hs(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=Is(this.serializer),t.removeTarget=e,this.c_(t)}}class xo extends bo{constructor(e,t,n,r,s,i){super(e,"write_stream_connection_backoff","write_stream_idle","health_check_timeout",t,n,r,i),this.serializer=s}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?vs(e.updateTime):vs(t);return n.isEqual($.min())&&(n=vs(t)),new Sr(n,e.transformResults||[])}(e,t)))):[]}(e.writeResults,e.commitTime),n=vs(e.commitTime);return this.listener.y_(n,t)}w_(){const e={};e.database=Is(this.serializer),this.c_(e)}g_(e){const t={streamToken:this.lastStreamToken,writes:e.map((e=>As(this.serializer,e)))};this.c_(t)}}class Eo 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 x(S.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((([s,i])=>this.connection.Oo(e,ys(t,n),r,s,i))).catch((e=>{throw"FirebaseError"===e.name?(e.code===S.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),e):new x(S.UNKNOWN,e.toString())}))}ko(e,t,n,r,s){return this.b_(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then((([i,a])=>this.connection.ko(e,ys(t,n),r,i,a,s))).catch((e=>{throw"FirebaseError"===e.name?(e.code===S.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),e):new x(S.UNKNOWN,e.toString())}))}terminate(){this.S_=!0,this.connection.terminate()}}class Io{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):f("OnlineStateTracker",t)}N_(){null!==this.v_&&(this.v_.cancel(),this.v_=null)}}class _o{constructor(e,t,n,r,s){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_=s,this.Q_.uo((e=>{n.enqueueAndForget((async()=>{Po(this)&&(f("RemoteStore","Restarting streams for network reachability change."),await async function(e){const t=b(e);t.k_.add(4),await Co(t),t.K_.set("Unknown"),t.k_.delete(4),await To(t)}(this))}))})),this.K_=new Io(n,r)}}async function To(e){if(Po(e))for(const t of e.q_)await t(!0)}async function Co(e){for(const t of e.q_)await t(!1)}function Ao(e,t){const n=b(e);n.B_.has(t.targetId)||(n.B_.set(t.targetId,t),No(n)?Mo(n):Zo(n).s_()&&ko(n,t))}function Do(e,t){const n=b(e),r=Zo(n);n.B_.delete(t),r.s_()&&Lo(n,t),0===n.B_.size&&(r.s_()?r.a_():Po(n)&&n.K_.set("Unknown"))}function ko(e,t){if(e.U_.xe(t.targetId),t.resumeToken.approximateByteSize()>0||t.snapshotVersion.compareTo($.min())>0){const n=e.remoteSyncer.getRemoteKeysForTarget(t.targetId).size;t=t.withExpectedCount(n)}Zo(e).V_(t)}function Lo(e,t){e.U_.xe(t),Zo(e).m_(t)}function Mo(e){e.U_=new is({getRemoteKeysForTarget:t=>e.remoteSyncer.getRemoteKeysForTarget(t),ut:t=>e.B_.get(t)||null,nt:()=>e.datastore.serializer.databaseId}),Zo(e).start(),e.K_.F_()}function No(e){return Po(e)&&!Zo(e).i_()&&e.B_.size>0}function Po(e){return 0===b(e).k_.size}function Ro(e){e.U_=void 0}async function Vo(e){e.K_.set("Online")}async function Oo(e){e.B_.forEach(((t,n)=>{ko(e,t)}))}async function $o(e,t){Ro(e),No(e)?(e.K_.O_(t),Mo(e)):e.K_.set("Unknown")}async function Fo(e,t,n){if(e.K_.set("Online"),t instanceof rs&&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){f("RemoteStore","Failed to remove targets %s: %s ",t.targetIds.join(","),n),await qo(e,n)}else if(t instanceof ts?e.U_.$e(t):t instanceof ns?e.U_.Je(t):e.U_.Ge(t),!n.isEqual($.min()))try{const t=await Ua(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 s=e.B_.get(r);s&&e.B_.set(r,s.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)),Lo(e,t);const s=new js(r.target,t,n,r.sequenceNumber);ko(e,s)})),e.remoteSyncer.applyRemoteEvent(n)}(e,n)}catch(t){f("RemoteStore","Failed to raise snapshot:",t),await qo(e,t)}}async function qo(e,t,n){if(!ue(t))throw t;e.k_.add(1),await Co(e),e.K_.set("Offline"),n||(n=()=>Ua(e.localStore)),e.asyncQueue.enqueueRetryable((async()=>{f("RemoteStore","Retrying IndexedDB access"),await n(),e.k_.delete(1),await To(e)}))}function Uo(e,t){return t().catch((n=>qo(e,n,t)))}async function Bo(e){const t=b(e),n=el(t);let r=t.L_.length>0?t.L_[t.L_.length-1].batchId:-1;for(;jo(t);)try{const e=await ja(t.localStore,r);if(null===e){0===t.L_.length&&n.a_();break}r=e.batchId,zo(t,e)}catch(e){await qo(t,e)}Go(t)&&Ko(t)}function jo(e){return Po(e)&&e.L_.length<10}function zo(e,t){e.L_.push(t);const n=el(e);n.s_()&&n.f_&&n.g_(t.mutations)}function Go(e){return Po(e)&&!el(e).i_()&&e.L_.length>0}function Ko(e){el(e).start()}async function Ho(e){el(e).w_()}async function Qo(e){const t=el(e);for(const n of e.L_)t.g_(n.mutations)}async function Wo(e,t,n){const r=e.L_.shift(),s=$r.from(r,t,n);await Uo(e,(()=>e.remoteSyncer.applySuccessfulWrite(s))),await Bo(e)}async function Yo(e,t){t&&el(e).f_&&await async function(e,t){if(function(e){return zr(e)&&e!==S.ABORTED}(t.code)){const n=e.L_.shift();el(e).__(),await Uo(e,(()=>e.remoteSyncer.rejectFailedWrite(n.batchId,t))),await Bo(e)}}(e,t),Go(e)&&Ko(e)}async function Jo(e,t){const n=b(e);n.asyncQueue.verifyOperationInProgress(),f("RemoteStore","RemoteStore received new credentials");const r=Po(n);n.k_.add(3),await Co(n),r&&n.K_.set("Unknown"),await n.remoteSyncer.handleCredentialChange(t),n.k_.delete(3),await To(n)}async function Xo(e,t){const n=b(e);t?(n.k_.delete(2),await To(n)):t||(n.k_.add(2),await Co(n),n.K_.set("Unknown"))}function Zo(e){return e.W_||(e.W_=function(e,t,n){const r=b(e);return r.b_(),new So(t,r.connection,r.authCredentials,r.appCheckCredentials,r.serializer,n)}(e.datastore,e.asyncQueue,{Ro:Vo.bind(null,e),mo:Oo.bind(null,e),po:$o.bind(null,e),R_:Fo.bind(null,e)}),e.q_.push((async t=>{t?(e.W_.__(),No(e)?Mo(e):e.K_.set("Unknown")):(await e.W_.stop(),Ro(e))}))),e.W_}function el(e){return e.G_||(e.G_=function(e,t,n){const r=b(e);return r.b_(),new xo(t,r.connection,r.authCredentials,r.appCheckCredentials,r.serializer,n)}(e.datastore,e.asyncQueue,{Ro:()=>Promise.resolve(),mo:Ho.bind(null,e),po:Yo.bind(null,e),p_:Qo.bind(null,e),y_:Wo.bind(null,e)}),e.q_.push((async t=>{t?(e.G_.__(),await Bo(e)):(await e.G_.stop(),e.L_.length>0&&(f("RemoteStore",`Stopping write stream with ${e.L_.length} pending writes`),e.L_=[]))}))),e.G_}class tl{constructor(e,t,n,r,s){this.asyncQueue=e,this.timerId=t,this.targetTimeMs=n,this.op=r,this.removalCallback=s,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,s){const i=Date.now()+n,a=new tl(e,t,i,r,s);return a.start(n),a}start(e){this.timerHandle=setTimeout((()=>this.handleDelayElapsed()),e)}skipDelay(){return this.handleDelayElapsed()}cancel(e){null!==this.timerHandle&&(this.clearTimeout(),this.deferred.reject(new x(S.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 nl(e,t){if(m("AsyncQueue",`${t}: ${e}`),ue(e))return new x(S.UNAVAILABLE,`${t}: ${e}`);throw e}class rl{static emptySet(e){return new rl(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 rl))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 rl;return n.comparator=this.comparator,n.keyedMap=e,n.sortedSet=t,n}}class sl{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 il{constructor(e,t,n,r,s,i,a,o,l){this.query=e,this.docs=t,this.oldDocs=n,this.docChanges=r,this.mutatedKeys=s,this.fromCache=i,this.syncStateChanged=a,this.excludesMetadataChanges=o,this.hasCachedResults=l}static fromInitialDocuments(e,t,n,r,s){const i=[];return t.forEach((e=>{i.push({type:0,doc:e})})),new il(e,t,rl.emptySet(t),i,n,r,!0,!1,s)}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)&&$n(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 al{constructor(){this.H_=void 0,this.J_=[]}Y_(){return this.J_.some((e=>e.Z_()))}}class ol{constructor(){this.queries=ll(),this.onlineState="Unknown",this.X_=new Set}terminate(){!function(e,t){const n=b(e),r=n.queries;n.queries=ll(),r.forEach(((e,n)=>{for(const e of n.J_)e.onError(t)}))}(this,new x(S.ABORTED,"Firestore shutting down"))}}function ll(){return new Gn((e=>Fn(e)),$n)}async function cl(e,t){const n=b(e);let r=3;const s=t.query;let i=n.queries.get(s);i?!i.Y_()&&t.Z_()&&(r=2):(i=new al,r=t.Z_()?0:1);try{switch(r){case 0:i.H_=await n.onListen(s,!0);break;case 1:i.H_=await n.onListen(s,!1);break;case 2:await n.onFirstRemoteStoreListen(s)}}catch(e){const n=nl(e,`Initialization of query '${qn(t.query)}' failed`);return void t.onError(n)}n.queries.set(s,i),i.J_.push(t),t.ea(n.onlineState),i.H_&&t.ta(i.H_)&&pl(n)}async function ul(e,t){const n=b(e),r=t.query;let s=3;const i=n.queries.get(r);if(i){const e=i.J_.indexOf(t);e>=0&&(i.J_.splice(e,1),0===i.J_.length?s=t.Z_()?0:1:!i.Y_()&&t.Z_()&&(s=2))}switch(s){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 dl(e,t){const n=b(e);let r=!1;for(const e of t){const t=e.query,s=n.queries.get(t);if(s){for(const t of s.J_)t.ta(e)&&(r=!0);s.H_=e}}r&&pl(n)}function hl(e,t,n){const r=b(e),s=r.queries.get(t);if(s)for(const e of s.J_)e.onError(n);r.queries.delete(t)}function pl(e){e.X_.forEach((e=>{e.next()}))}var fl,ml;(ml=fl||(fl={})).na="default",ml.Cache="cache";class vl{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 il(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=il.fromInitialDocuments(e.query,e.docs,e.mutatedKeys,e.fromCache,e.hasCachedResults),this.ia=!0,this.ra.next(e)}Z_(){return this.options.source!==fl.Cache}}class gl{constructor(e,t){this.ca=e,this.byteLength=t}la(){return"metadata"in this.ca}}class yl{constructor(e){this.serializer=e}As(e){return Ss(this.serializer,e)}Rs(e){return e.metadata.exists?Cs(this.serializer,e.document,!1):Ht.newNoDocument(this.As(e.metadata.name),this.Vs(e.metadata.readTime))}Vs(e){return vs(e)}}class wl{constructor(e,t,n){this.ha=e,this.localStore=t,this.serializer=n,this.queries=[],this.documents=[],this.collectionGroups=new Set,this.progress=bl(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=q.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 yl(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 s=b(e);let i=nr(),a=Hn();for(const e of n){const n=t.As(e.metadata.name);e.document&&(i=i.add(n));const r=t.Rs(e);r.setReadTime(t.Vs(e.metadata.readTime)),a=a.insert(n,r)}const o=s.hs.newChangeBuffer({trackRemovals:!0}),l=await za(s,function(e){return Nn(Dn(q.fromString(`__bundle__/docs/${e}`)))}(r));return s.persistence.runTransaction("Apply bundle documents","readwrite",(e=>Ba(e,o,a).next((t=>(o.apply(e),t))).next((t=>s.Gr.removeMatchingKeysForTargetId(e,l.targetId).next((()=>s.Gr.addMatchingKeys(e,i,l.targetId))).next((()=>s.localDocuments.getLocalViewOfDocuments(e,t.Is,t.Es))).next((()=>t.Is))))))}(this.localStore,new yl(this.serializer),this.documents,this.ha.id),t=this.Ta(this.documents);for(const e of this.queries)await Ya(this.localStore,e,t.get(e.name));return this.progress.taskState="Success",{progress:this.progress,Ia:this.collectionGroups,Ea:e}}}function bl(e){return{taskState:"Running",documentsLoaded:0,bytesLoaded:0,totalDocuments:e.totalDocuments,totalBytes:e.totalBytes}}class Sl{constructor(e){this.key=e}}class xl{constructor(e){this.key=e}}class El{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 rl(this.Va)}get fa(){return this.da}ga(e,t){const n=t?t.pa:new sl,r=t?t.ma:this.ma;let s=t?t.mutatedKeys:this.mutatedKeys,i=r,a=!1;const o="F"===this.query.limitType&&r.size===this.query.limit?r.last():null,l="L"===this.query.limitType&&r.size===this.query.limit?r.first():null;if(e.inorderTraversal(((e,t)=>{const c=r.get(e),u=Un(this.query,t)?t:null,d=!!c&&this.mutatedKeys.has(c.key),h=!!u&&(u.hasLocalMutations||this.mutatedKeys.has(u.key)&&u.hasCommittedMutations);let p=!1;c&&u?c.data.isEqual(u.data)?d!==h&&(n.track({type:3,doc:u}),p=!0):this.ya(c,u)||(n.track({type:2,doc:u}),p=!0,(o&&this.Va(u,o)>0||l&&this.Va(u,l)<0)&&(a=!0)):!c&&u?(n.track({type:0,doc:u}),p=!0):c&&!u&&(n.track({type:1,doc:c}),p=!0,(o||l)&&(a=!0)),p&&(u?(i=i.add(u),s=h?s.add(e):s.delete(e)):(i=i.delete(e),s=s.delete(e)))})),null!==this.query.limit)for(;i.size>this.query.limit;){const e="F"===this.query.limitType?i.last():i.first();i=i.delete(e.key),s=s.delete(e.key),n.track({type:1,doc:e})}return{ma:i,pa:n,ss:a,mutatedKeys:s}}ya(e,t){return e.hasLocalMutations&&t.hasCommittedMutations&&!t.hasLocalMutations}applyChanges(e,t,n,r){const s=this.ma;this.ma=e.ma,this.mutatedKeys=e.mutatedKeys;const i=e.pa.j_();i.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 a=t&&!r?this.Sa():[],o=0===this.Ra.size&&this.current&&!r?1:0,l=o!==this.Aa;return this.Aa=o,0!==i.length||l?{snapshot:new il(this.query,e.ma,s,i,e.mutatedKeys,0===o,l,!1,!!n&&n.resumeToken.approximateByteSize()>0),ba:a}:{ba:a}}ea(e){return this.current&&"Offline"===e?(this.current=!1,this.applyChanges({ma:this.ma,pa:new sl,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 xl(e))})),this.Ra.forEach((n=>{e.has(n)||t.push(new Sl(n))})),t}va(e){this.da=e.ds,this.Ra=nr();const t=this.ga(e.documents);return this.applyChanges(t,!0)}Ca(){return il.fromInitialDocuments(this.query,this.ma,this.mutatedKeys,0===this.Aa,this.hasCachedResults)}}class Il{constructor(e,t,n){this.query=e,this.targetId=t,this.view=n}}class _l{constructor(e){this.key=e,this.Fa=!1}}class Tl{constructor(e,t,n,r,s,i){this.localStore=e,this.remoteStore=t,this.eventManager=n,this.sharedClientState=r,this.currentUser=s,this.maxConcurrentLimboResolutions=i,this.Ma={},this.xa=new Gn((e=>Fn(e)),$n),this.Oa=new Map,this.Na=new Set,this.La=new nt(j.comparator),this.Ba=new Map,this.ka=new ya,this.qa={},this.Qa=new Map,this.Ka=Ki.Qn(),this.onlineState="Unknown",this.$a=void 0}get isPrimaryClient(){return!0===this.$a}}async function Cl(e,t,n=!0){const r=nc(e);let s;const i=r.xa.get(t);return i?(r.sharedClientState.addLocalQueryTarget(i.targetId),s=i.view.Ca()):s=await Dl(r,t,n,!0),s}async function Al(e,t){const n=nc(e);await Dl(n,t,!0,!1)}async function Dl(e,t,n,r){const s=await za(e.localStore,Nn(t)),i=s.targetId,a=e.sharedClientState.addLocalQueryTarget(i,n);let o;return r&&(o=await kl(e,t,i,"current"===a,s.resumeToken)),e.isPrimaryClient&&n&&Ao(e.remoteStore,s),o}async function kl(e,t,n,r,s){e.Ua=(t,n,r)=>async function(e,t,n,r){let s=t.view.ga(n);s.ss&&(s=await Ka(e.localStore,t.query,!1).then((({documents:e})=>t.view.ga(e,s))));const i=r&&r.targetChanges.get(t.targetId),a=r&&null!=r.targetMismatches.get(t.targetId),o=t.view.applyChanges(s,e.isPrimaryClient,i,a);return Bl(e,t.targetId,o.ba),o.snapshot}(e,t,n,r);const i=await Ka(e.localStore,t,!0),a=new El(t,i.ds),o=a.ga(i.documents),l=es.createSynthesizedTargetChangeForCurrentChange(n,r&&"Offline"!==e.onlineState,s),c=a.applyChanges(o,e.isPrimaryClient,l);Bl(e,n,c.ba);const u=new Il(t,n,a);return e.xa.set(t,u),e.Oa.has(n)?e.Oa.get(n).push(t):e.Oa.set(n,[t]),c.snapshot}async function Ll(e,t,n){const r=b(e),s=r.xa.get(t),i=r.Oa.get(s.targetId);if(i.length>1)return r.Oa.set(s.targetId,i.filter((e=>!$n(e,t)))),void r.xa.delete(t);r.isPrimaryClient?(r.sharedClientState.removeLocalQueryTarget(s.targetId),r.sharedClientState.isActiveQueryTarget(s.targetId)||await Ga(r.localStore,s.targetId,!1).then((()=>{r.sharedClientState.clearQueryState(s.targetId),n&&Do(r.remoteStore,s.targetId),ql(r,s.targetId)})).catch(re)):(ql(r,s.targetId),await Ga(r.localStore,s.targetId,!0))}async function Ml(e,t){const n=b(e),r=n.xa.get(t),s=n.Oa.get(r.targetId);n.isPrimaryClient&&1===s.length&&(n.sharedClientState.removeLocalQueryTarget(r.targetId),Do(n.remoteStore,r.targetId))}async function Nl(e,t){const n=b(e);try{const e=await function(e,t){const n=b(e),r=t.snapshotVersion;let s=n.us;return n.persistence.runTransaction("Apply remote event","readwrite-primary",(e=>{const i=n.hs.newChangeBuffer({trackRemovals:!0});s=n.us;const a=[];t.targetChanges.forEach(((i,o)=>{const l=s.get(o);if(!l)return;a.push(n.Gr.removeMatchingKeys(e,i.removedDocuments,o).next((()=>n.Gr.addMatchingKeys(e,i.addedDocuments,o))));let c=l.withSequenceNumber(e.currentSequenceNumber);null!==t.targetMismatches.get(o)?c=c.withResumeToken(ut.EMPTY_BYTE_STRING,$.min()).withLastLimboFreeSnapshotVersion($.min()):i.resumeToken.approximateByteSize()>0&&(c=c.withResumeToken(i.resumeToken,r)),s=s.insert(o,c),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}(l,c,i)&&a.push(n.Gr.updateTargetData(e,c))}));let o=Hn(),l=nr();if(t.documentUpdates.forEach((r=>{t.resolvedLimboDocuments.has(r)&&a.push(n.persistence.referenceDelegate.updateLimboDocument(e,r))})),a.push(Ba(e,i,t.documentUpdates).next((e=>{o=e.Is,l=e.Es}))),!r.isEqual($.min())){const t=n.Gr.getLastRemoteSnapshotVersion(e).next((t=>n.Gr.setTargetsMetadata(e,e.currentSequenceNumber,r)));a.push(t)}return se.waitFor(a).next((()=>i.apply(e))).next((()=>n.localDocuments.getLocalViewOfDocuments(e,o,l))).next((()=>o))})).then((e=>(n.us=s,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 Gl(n,e,t)}catch(e){await re(e)}}function Pl(e,t,n){const r=b(e);if(r.isPrimaryClient&&0===n||!r.isPrimaryClient&&1===n){const e=[];r.xa.forEach(((n,r)=>{const s=r.view.ea(t);s.snapshot&&e.push(s.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&&pl(n)}(r.eventManager,t),e.length&&r.Ma.R_(e),r.onlineState=t,r.isPrimaryClient&&r.sharedClientState.setOnlineState(t)}}async function Rl(e,t,n){const r=b(e);r.sharedClientState.updateQueryState(t,"rejected",n);const s=r.Ba.get(t),i=s&&s.key;if(i){let e=new nt(j.comparator);e=e.insert(i,Ht.newNoDocument(i,$.min()));const n=nr().add(i),s=new Zr($.min(),new Map,new nt(P),e,n);await Nl(r,s),r.La=r.La.remove(i),r.Ba.delete(t),zl(r)}else await Ga(r.localStore,t,!1).then((()=>ql(r,t,n))).catch(re)}async function Vl(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(),s=n.hs.newChangeBuffer({trackRemovals:!0});return function(e,t,n,r){const s=n.batch,i=s.keys();let a=se.resolve();return i.forEach((e=>{a=a.next((()=>r.getEntry(t,e))).next((t=>{const i=n.docVersions.get(e);w(null!==i),t.version.compareTo(i)<0&&(s.applyToRemoteDocument(t,n),t.isValidDocument()&&(t.setReadTime(n.commitVersion),r.addEntry(t)))}))})),a.next((()=>e.mutationQueue.removeMutationBatch(t,s)))}(n,e,t,s).next((()=>s.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);Fl(n,r,null),$l(n,r),n.sharedClientState.updateMutationState(r,"acknowledged"),await Gl(n,e)}catch(e){await re(e)}}async function Ol(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);Fl(r,t,n),$l(r,t),r.sharedClientState.updateMutationState(t,"rejected",n),await Gl(r,e)}catch(n){await re(n)}}function $l(e,t){(e.Qa.get(t)||[]).forEach((e=>{e.resolve()})),e.Qa.delete(t)}function Fl(e,t,n){const r=b(e);let s=r.qa[r.currentUser.toKey()];if(s){const e=s.get(t);e&&(n?e.reject(n):e.resolve(),s=s.remove(t)),r.qa[r.currentUser.toKey()]=s}}function ql(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)||Ul(e,t)}))}function Ul(e,t){e.Na.delete(t.path.canonicalString());const n=e.La.get(t);null!==n&&(Do(e.remoteStore,n),e.La=e.La.remove(t),e.Ba.delete(n),zl(e))}function Bl(e,t,n){for(const r of n)r instanceof Sl?(e.ka.addReference(r.key,t),jl(e,r)):r instanceof xl?(f("SyncEngine","Document no longer in limbo: "+r.key),e.ka.removeReference(r.key,t),e.ka.containsKey(r.key)||Ul(e,r.key)):y()}function jl(e,t){const n=t.key,r=n.path.canonicalString();e.La.get(n)||e.Na.has(r)||(f("SyncEngine","New document in limbo: "+n),e.Na.add(r),zl(e))}function zl(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(q.fromString(t)),r=e.Ka.next();e.Ba.set(r,new _l(n)),e.La=e.La.insert(n,r),Ao(e.remoteStore,new js(Nn(Dn(n.path)),r,"TargetPurposeLimboResolution",ge.oe))}}async function Gl(e,t,n){const r=b(e),s=[],i=[],a=[];r.xa.isEmpty()||(r.xa.forEach(((e,o)=>{a.push(r.Ua(o,t,n).then((e=>{var t;if((e||n)&&r.isPrimaryClient){const s=e?!e.fromCache:null===(t=null==n?void 0:n.targetChanges.get(o.targetId))||void 0===t?void 0:t.current;r.sharedClientState.updateQueryState(o.targetId,s?"current":"not-current")}if(e){s.push(e);const t=Ra.zi(o.targetId,e);i.push(t)}})))})),await Promise.all(a),r.Ma.R_(s),await async function(e,t){const n=b(e);try{await n.persistence.runTransaction("notifyLocalViewChanges","readwrite",(e=>se.forEach(t,(t=>se.forEach(t.Wi,(r=>n.persistence.referenceDelegate.addReference(e,t.targetId,r))).next((()=>se.forEach(t.Gi,(r=>n.persistence.referenceDelegate.removeReference(e,t.targetId,r)))))))))}catch(e){if(!ue(e))throw e;f("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,s=e.withLastLimboFreeSnapshotVersion(r);n.us=n.us.insert(t,s)}}}(r.localStore,i))}async function Kl(e,t){const n=b(e);if(!n.currentUser.isEqual(t)){f("SyncEngine","User change. New user:",t.toKey());const e=await qa(n.localStore,t);n.currentUser=t,function(e){e.Qa.forEach((e=>{e.forEach((e=>{e.reject(new x(S.CANCELLED,"'waitForPendingWrites' promise is rejected due to a user change."))}))})),e.Qa.clear()}(n),n.sharedClientState.handleUserChange(t,e.removedBatchIds,e.addedBatchIds),await Gl(n,e.Ts)}}function Hl(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 Ql(e,t){const n=b(e),r=await Ka(n.localStore,t.query,!0),s=t.view.va(r);return n.isPrimaryClient&&Bl(n,t.targetId,s.ba),s}async function Wl(e,t){const n=b(e);return Qa(n.localStore,t).then((e=>Gl(n,e)))}async function Yl(e,t,n,r){const s=b(e),i=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):se.resolve(null)))))}(s.localStore,t);null!==i?("pending"===n?await Bo(s.remoteStore):"acknowledged"===n||"rejected"===n?(Fl(s,t,r||null),$l(s,t),function(e,t){b(b(e).mutationQueue).Ln(t)}(s.localStore,t)):y(),await Gl(s,i)):f("SyncEngine","Cannot apply mutation batch with id: "+t)}async function Jl(e,t,n){const r=b(e),s=[],i=[];for(const e of t){let t;const n=r.Oa.get(e);if(n&&0!==n.length){t=await za(r.localStore,Nn(n[0]));for(const e of n){const t=r.xa.get(e),n=await Ql(r,t);n.snapshot&&i.push(n.snapshot)}}else{const n=await Ha(r.localStore,e);t=await za(r.localStore,n),await kl(r,Xl(n),e,!1,t.resumeToken)}s.push(t)}return r.Ma.R_(i),s}function Xl(e){return An(e.path,e.collectionGroup,e.orderBy,e.filters,e.limit,"F",e.startAt,e.endAt)}function Zl(e){return function(e){return b(b(e).persistence).$i()}(b(e).localStore)}async function ec(e,t,n,r){const s=b(e);if(s.$a)return void f("SyncEngine","Ignoring unexpected query state notification.");const i=s.Oa.get(t);if(i&&i.length>0)switch(n){case"current":case"not-current":{const e=await Qa(s.localStore,Bn(i[0])),r=Zr.createSynthesizedRemoteEventForCurrentChange(t,"current"===n,ut.EMPTY_BYTE_STRING);await Gl(s,e,r);break}case"rejected":await Ga(s.localStore,t,!0),ql(s,t,r);break;default:y()}}async function tc(e,t,n){const r=nc(e);if(r.$a){for(const e of t){if(r.Oa.has(e)&&r.sharedClientState.isActiveQueryTarget(e)){f("SyncEngine","Adding an already active target "+e);continue}const t=await Ha(r.localStore,e),n=await za(r.localStore,t);await kl(r,Xl(t),n.targetId,!1,n.resumeToken),Ao(r.remoteStore,n)}for(const e of n)r.Oa.has(e)&&await Ga(r.localStore,e,!1).then((()=>{Do(r.remoteStore,e),ql(r,e)})).catch(re)}}function nc(e){const t=b(e);return t.remoteStore.remoteSyncer.applyRemoteEvent=Nl.bind(null,t),t.remoteStore.remoteSyncer.getRemoteKeysForTarget=Hl.bind(null,t),t.remoteStore.remoteSyncer.rejectListen=Rl.bind(null,t),t.Ma.R_=dl.bind(null,t.eventManager),t.Ma.Wa=hl.bind(null,t.eventManager),t}function rc(e){const t=b(e);return t.remoteStore.remoteSyncer.applySuccessfulWrite=Vl.bind(null,t),t.remoteStore.remoteSyncer.rejectFailedWrite=Ol.bind(null,t),t}class sc{constructor(){this.kind="memory",this.synchronizeTabs=!1}async initialize(e){this.serializer=yo(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 Fa(this.persistence,new Oa,e.initialUser,this.serializer)}ja(e){return new Ia(Ta.ei,this.serializer)}za(e){return new ao}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()}}sc.provider={build:()=>new sc};class ic extends sc{constructor(e){super(),this.cacheSizeBytes=e}Ja(e,t){w(this.persistence.referenceDelegate instanceof Ca);const n=this.persistence.referenceDelegate.garbageCollector;return new Zi(n,e.asyncQueue,t)}ja(e){const t=void 0!==this.cacheSizeBytes?$i.withCacheSize(this.cacheSizeBytes):$i.DEFAULT;return new Ia((e=>Ca.ei(e,t)),this.serializer)}}class ac extends sc{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 rc(this.Za.syncEngine),await Bo(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 Fa(this.persistence,new Oa,e.initialUser,this.serializer)}Ja(e,t){const n=this.persistence.referenceDelegate.garbageCollector;return new Zi(n,e.asyncQueue,t)}Ya(e,t){const n=new ve(t,this.persistence);return new me(e.asyncQueue,n)}ja(e){const t=Pa(e.databaseInfo.databaseId,e.databaseInfo.persistenceKey),n=void 0!==this.cacheSizeBytes?$i.withCacheSize(this.cacheSizeBytes):$i.DEFAULT;return new La(this.synchronizeTabs,t,e.clientId,n,e.asyncQueue,vo(),go(),this.serializer,this.sharedClientState,!!this.forceOwnership)}za(e){return new ao}}class oc extends ac{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 io&&(this.sharedClientState.syncEngine={io:Yl.bind(null,t),so:ec.bind(null,t),oo:tc.bind(null,t),$i:Zl.bind(null,t),ro:Wl.bind(null,t)},await this.sharedClientState.start()),await this.persistence.Si((async e=>{await async function(e,t){const n=b(e);if(nc(n),rc(n),!0===t&&!0!==n.$a){const e=n.sharedClientState.getAllActiveQueryTargets(),t=await Jl(n,e.toArray());n.$a=!0,await Xo(n.remoteStore,!0);for(const e of t)Ao(n.remoteStore,e)}else if(!1===t&&!1!==n.$a){const e=[];let t=Promise.resolve();n.Oa.forEach(((r,s)=>{n.sharedClientState.isLocalQueryTarget(s)?e.push(s):t=t.then((()=>(ql(n,s),Ga(n.localStore,s,!0)))),Do(n.remoteStore,s)})),await t,await Jl(n,e),function(e){const t=b(e);t.Ba.forEach(((e,n)=>{Do(t.remoteStore,n)})),t.ka.wr(),t.Ba=new Map,t.La=new nt(j.comparator)}(n),n.$a=!1,await Xo(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=vo();if(!io.p(t))throw new x(S.UNIMPLEMENTED,"IndexedDB persistence is only available on platforms that support LocalStorage.");const n=Pa(e.databaseInfo.databaseId,e.databaseInfo.persistenceKey);return new io(t,e.asyncQueue,n,e.clientId,e.initialUser)}}class lc{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=>Pl(this.syncEngine,e,1),this.remoteStore.remoteSyncer.handleCredentialChange=Kl.bind(null,this.syncEngine),await Xo(this.remoteStore,this.syncEngine.isPrimaryClient))}createEventManager(e){return new ol}createDatastore(e){const t=yo(e.databaseInfo.databaseId),n=function(e){return new mo(e)}(e.databaseInfo);return function(e,t,n,r){return new Eo(e,t,n,r)}(e.authCredentials,e.appCheckCredentials,n,t)}createRemoteStore(e){return function(e,t,n,r,s){return new _o(e,t,n,r,s)}(this.localStore,this.datastore,e.asyncQueue,(e=>Pl(this.syncEngine,e,0)),lo.p()?new lo:new oo)}createSyncEngine(e,t){return function(e,t,n,r,s,i,a){const o=new Tl(e,t,n,r,s,i);return a&&(o.$a=!0),o}(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);f("RemoteStore","RemoteStore shutting down."),t.k_.add(5),await Co(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 cc(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()}}lc.provider={build:()=>new lc};class uc{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 dc{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 gl(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 hc{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 x(S.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=>bs(n.serializer,e)))},s=await n.ko("BatchGetDocuments",n.serializer.databaseId,q.emptyPath(),r,t.length),i=new Map;s.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=Ss(e,t.found.name),r=vs(t.found.updateTime),s=t.found.createTime?vs(t.found.createTime):$.min(),i=new Gt({mapValue:{fields:t.found.fields}});return Ht.newFoundDocument(n,r,s,i)}(e,t):"missing"in t?function(e,t){w(!!t.missing),w(!!t.readTime);const n=Ss(e,t.missing),r=vs(t.readTime);return Ht.newNoDocument(n,r)}(e,t):y()}(n.serializer,e);i.set(t.key.toString(),t)}));const a=[];return t.forEach((e=>{const t=i.get(e.toString());w(!!t),a.push(t)})),a}(this.datastore,e);return t.forEach((e=>this.recordVersion(e))),t}set(e,t){this.write(t.toMutation(e,this.precondition(e))),this.writtenDocs.add(e.toString())}update(e,t){try{this.write(t.toMutation(e,this.preconditionForUpdate(e)))}catch(e){this.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 Vr(n,this.precondition(n)))})),await async function(e,t){const n=b(e),r={writes:t.map((e=>As(n.serializer,e)))};await n.Oo("Commit",n.serializer.databaseId,q.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=$.min()}const n=this.readVersions.get(e.key.toString());if(n){if(!t.isEqual(n))throw new x(S.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($.min())?xr.exists(!1):xr.updateTime(t):xr.none()}preconditionForUpdate(e){const t=this.readVersions.get(e.toString());if(!this.writtenDocs.has(e.toString())&&t){if(t.isEqual($.min()))throw new x(S.INVALID_ARGUMENT,"Can't update a document that doesn't exist.");return xr.updateTime(t)}return xr.exists(!0)}write(e){this.ensureCommitNotCalled(),this.mutations.push(e)}ensureCommitNotCalled(){}}class pc{constructor(e,t,n,r,s){this.asyncQueue=e,this.datastore=t,this.options=n,this.updateFunction=r,this.deferred=s,this.uu=n.maxAttempts,this.r_=new wo(this.asyncQueue,"transaction_retry")}cu(){this.uu-=1,this.lu()}lu(){this.r_.jo((async()=>{const e=new hc(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 fc{constructor(e,t,n,r,s){this.authCredentials=e,this.appCheckCredentials=t,this.asyncQueue=n,this.databaseInfo=r,this.user=u.UNAUTHENTICATED,this.clientId=N.newId(),this.authCredentialListener=()=>Promise.resolve(),this.appCheckCredentialListener=()=>Promise.resolve(),this._uninitializedComponentsProvider=s,this.authCredentials.start(n,(async e=>{f("FirestoreClient","Received user=",e.uid),await this.authCredentialListener(e),this.user=e})),this.appCheckCredentials.start(n,(e=>(f("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=nl(t,"Failed to shutdown persistence");e.reject(n)}})),e.promise}}async function mc(e,t){e.asyncQueue.verifyOperationInProgress(),f("FirestoreClient","Initializing OfflineComponentProvider");const n=e.configuration;await t.initialize(n);let r=n.initialUser;e.setCredentialChangeListener((async e=>{r.isEqual(e)||(await qa(t.localStore,e),r=e)})),t.persistence.setDatabaseDeletedListener((()=>e.terminate())),e._offlineComponents=t}async function vc(e,t){e.asyncQueue.verifyOperationInProgress();const n=await gc(e);f("FirestoreClient","Initializing OnlineComponentProvider"),await t.initialize(n,e.configuration),e.setCredentialChangeListener((e=>Jo(t.remoteStore,e))),e.setAppCheckTokenChangeListener(((e,n)=>Jo(t.remoteStore,n))),e._onlineComponents=t}async function gc(e){if(!e._offlineComponents)if(e._uninitializedComponentsProvider){f("FirestoreClient","Using user provided OfflineComponentProvider");try{await mc(e,e._uninitializedComponentsProvider._offline)}catch(t){const n=t;if(!function(e){return"FirebaseError"===e.name?e.code===S.FAILED_PRECONDITION||e.code===S.UNIMPLEMENTED:!("undefined"!=typeof DOMException&&e instanceof DOMException)||22===e.code||20===e.code||11===e.code}(n))throw n;v("Error using user provided cache. Falling back to memory cache: "+n),await mc(e,new sc)}}else f("FirestoreClient","Using default OfflineComponentProvider"),await mc(e,new ic(void 0));return e._offlineComponents}async function yc(e){return e._onlineComponents||(e._uninitializedComponentsProvider?(f("FirestoreClient","Using user provided OnlineComponentProvider"),await vc(e,e._uninitializedComponentsProvider._online)):(f("FirestoreClient","Using default OnlineComponentProvider"),await vc(e,new lc))),e._onlineComponents}function wc(e){return gc(e).then((e=>e.persistence))}function bc(e){return gc(e).then((e=>e.localStore))}function Sc(e){return yc(e).then((e=>e.remoteStore))}function xc(e){return yc(e).then((e=>e.syncEngine))}function Ec(e){return yc(e).then((e=>e.datastore))}async function Ic(e){const t=await yc(e),n=t.eventManager;return n.onListen=Cl.bind(null,t.syncEngine),n.onUnlisten=Ll.bind(null,t.syncEngine),n.onFirstRemoteStoreListen=Al.bind(null,t.syncEngine),n.onLastRemoteStoreUnlisten=Ml.bind(null,t.syncEngine),n}function _c(e,t,n={}){const r=new E;return e.asyncQueue.enqueueAndForget((async()=>function(e,t,n,r,s){const i=new uc({next:o=>{i.eu(),t.enqueueAndForget((()=>ul(e,a)));const l=o.docs.has(n);!l&&o.fromCache?s.reject(new x(S.UNAVAILABLE,"Failed to get document because the client is offline.")):l&&o.fromCache&&r&&"server"===r.source?s.reject(new x(S.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.)')):s.resolve(o)},error:e=>s.reject(e)}),a=new vl(Dn(n.path),i,{includeMetadataChanges:!0,ua:!0});return cl(e,a)}(await Ic(e),e.asyncQueue,t,n,r))),r.promise}function Tc(e,t,n={}){const r=new E;return e.asyncQueue.enqueueAndForget((async()=>function(e,t,n,r,s){const i=new uc({next:n=>{i.eu(),t.enqueueAndForget((()=>ul(e,a))),n.fromCache&&"server"===r.source?s.reject(new x(S.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.)')):s.resolve(n)},error:e=>s.reject(e)}),a=new vl(n,i,{includeMetadataChanges:!0,ua:!0});return cl(e,a)}(await Ic(e),e.asyncQueue,t,n,r))),r.promise}function Cc(e){const t={};return void 0!==e.timeoutSeconds&&(t.timeoutSeconds=e.timeoutSeconds),t}const Ac=new Map;function Dc(e,t,n){if(!n)throw new x(S.INVALID_ARGUMENT,`Function ${e}() cannot be called with an empty ${t}.`)}function kc(e,t,n,r){if(!0===t&&!0===r)throw new x(S.INVALID_ARGUMENT,`${e} and ${n} cannot be used together.`)}function Lc(e){if(!j.isDocumentKey(e))throw new x(S.INVALID_ARGUMENT,`Invalid document reference. Document references must have an even number of segments, but ${e} has ${e.length}.`)}function Mc(e){if(j.isDocumentKey(e))throw new x(S.INVALID_ARGUMENT,`Invalid collection reference. Collection references must have an odd number of segments, but ${e} has ${e.length}.`)}function Nc(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 Pc(e,t){if("_delegate"in e&&(e=e._delegate),!(e instanceof t)){if(t.name===e.constructor.name)throw new x(S.INVALID_ARGUMENT,"Type does not match the expected instance. Did you pass a reference from a different Firestore SDK?");{const n=Nc(e);throw new x(S.INVALID_ARGUMENT,`Expected type '${t.name}', but it was: ${n}`)}}return e}function Rc(e,t){if(t<=0)throw new x(S.INVALID_ARGUMENT,`Function ${e}() requires a positive number, but it was: ${t}.`)}class Vc{constructor(e){var t,n;if(void 0===e.host){if(void 0!==e.ssl)throw new x(S.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 x(S.INVALID_ARGUMENT,"cacheSizeBytes must be at least 1048576");this.cacheSizeBytes=e.cacheSizeBytes}kc("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=Cc(null!==(n=e.experimentalLongPollingOptions)&&void 0!==n?n:{}),function(e){if(void 0!==e.timeoutSeconds){if(isNaN(e.timeoutSeconds))throw new x(S.INVALID_ARGUMENT,`invalid long polling timeout: ${e.timeoutSeconds} (must not be NaN)`);if(e.timeoutSeconds<5)throw new x(S.INVALID_ARGUMENT,`invalid long polling timeout: ${e.timeoutSeconds} (minimum allowed value is 5)`);if(e.timeoutSeconds>30)throw new x(S.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 Oc{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 Vc({}),this._settingsFrozen=!1,this._terminateTask="notTerminated"}get app(){if(!this._app)throw new x(S.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 x(S.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 Vc(e),void 0!==e.credentials&&(this._authCredentials=function(e){if(!e)return new _;switch(e.type){case"firstParty":return new D(e.sessionIndex||"0",e.iamToken||null,e.authTokenFactory||null);case"provider":return e.client;default:throw new x(S.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=Ac.get(e);t&&(f("ComponentProvider","Removing Datastore"),Ac.delete(e),t.terminate())}(this),Promise.resolve()}}function $c(e,t,n,r={}){var s;const i=(e=Pc(e,Oc))._getSettings(),o=`${t}:${n}`;if("firestore.googleapis.com"!==i.host&&i.host!==o&&v("Host has been set in both settings() and connectFirestoreEmulator(), emulator host will be used."),e._setSettings(Object.assign(Object.assign({},i),{host:o,ssl:!1})),r.mockUserToken){let t,n;if("string"==typeof r.mockUserToken)t=r.mockUserToken,n=u.MOCK_USER;else{t=a.createMockUserToken(r.mockUserToken,null===(s=e._app)||void 0===s?void 0:s.options.projectId);const i=r.mockUserToken.sub||r.mockUserToken.user_id;if(!i)throw new x(S.INVALID_ARGUMENT,"mockUserToken must contain 'sub' or 'user_id' field!");n=new u(i)}e._authCredentials=new T(new I(t,n))}}class Fc{constructor(e,t,n){this.converter=t,this._query=n,this.type="query",this.firestore=e}withConverter(e){return new Fc(this.firestore,e,this._query)}}class qc{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 Uc(this.firestore,this.converter,this._key.path.popLast())}withConverter(e){return new qc(this.firestore,e,this._key)}}class Uc extends Fc{constructor(e,t,n){super(e,t,Dn(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 qc(this.firestore,null,new j(e))}withConverter(e){return new Uc(this.firestore,e,this._path)}}function Bc(e,t,...n){if(e=a.getModularInstance(e),1===arguments.length&&(t=N.newId()),Dc("doc","path",t),e instanceof Oc){const r=q.fromString(t,...n);return Lc(r),new qc(e,null,new j(r))}{if(!(e instanceof qc||e instanceof Uc))throw new x(S.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");const r=e._path.child(q.fromString(t,...n));return Lc(r),new qc(e.firestore,e instanceof Uc?e.converter:null,new j(r))}}function jc(e,t){return e=a.getModularInstance(e),t=a.getModularInstance(t),e instanceof Fc&&t instanceof Fc&&e.firestore===t.firestore&&$n(e._query,t._query)&&e.converter===t.converter}class zc{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 wo(this,"async_queue_retry"),this.fu=()=>{const e=go();e&&f("AsyncQueue","Visibility state changed to "+e.visibilityState),this.r_.Jo()},this.gu=e;const t=go();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=go();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;f("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=tl.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 Gc(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 Kc{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 Hc extends Oc{constructor(e,t,n,r){super(e,t,n,r),this.type="firestore",this._queue=new zc,this._persistenceKey=(null==r?void 0:r.name)||"[DEFAULT]"}async _terminate(){if(this._firestoreClient){const e=this._firestoreClient.terminate();this._queue=new zc(e),this._firestoreClient=void 0,await e}}}function Qc(e){if(e._terminated)throw new x(S.FAILED_PRECONDITION,"The client has already been terminated.");return e._firestoreClient||Wc(e),e._firestoreClient}function Wc(e){var t,n,r;const s=e._freezeSettings(),i=function(e,t,n,r){return new yt(e,t,n,r.host,r.ssl,r.experimentalForceLongPolling,r.experimentalAutoDetectLongPolling,Cc(r.experimentalLongPollingOptions),r.useFetchStreams)}(e._databaseId,(null===(t=e._app)||void 0===t?void 0:t.options.appId)||"",e._persistenceKey,s);e._componentsProvider||(null===(n=s.localCache)||void 0===n?void 0:n._offlineComponentProvider)&&(null===(r=s.localCache)||void 0===r?void 0:r._onlineComponentProvider)&&(e._componentsProvider={_offline:s.localCache._offlineComponentProvider,_online:s.localCache._onlineComponentProvider}),e._firestoreClient=new fc(e._authCredentials,e._appCheckCredentials,e._queue,i,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 Yc(e,t,n){if((e=Pc(e,Hc))._firestoreClient||e._terminated)throw new x(S.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 x(S.FAILED_PRECONDITION,"SDK cache is already specified.");e._componentsProvider={_online:t,_offline:n},Wc(e)}class Jc{constructor(e="count",t){this._internalFieldPath=t,this.type="AggregateField",this.aggregateType=e}}class Xc{constructor(e,t,n){this._userDataWriter=t,this._data=n,this.type="AggregateQuerySnapshot",this.query=e}data(){return this._userDataWriter.convertObjectMap(this._data)}}class Zc{constructor(e){this._byteString=e}static fromBase64String(e){try{return new Zc(ut.fromBase64String(e))}catch(e){throw new x(S.INVALID_ARGUMENT,"Failed to construct data from Base64 string: "+e)}}static fromUint8Array(e){return new Zc(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 x(S.INVALID_ARGUMENT,"Invalid field name at argument $(i + 1). Field names must not be empty.");this._internalPath=new B(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 x(S.INVALID_ARGUMENT,"Latitude must be a number between -90 and 90, but was: "+e);if(!isFinite(t)||t<-180||t>180)throw new x(S.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 su=/^__.*__$/;class iu{constructor(e,t,n){this.data=e,this.fieldMask=t,this.fieldTransforms=n}toMutation(e,t){return null!==this.fieldMask?new Lr(e,this.data,this.fieldMask,t,this.fieldTransforms):new kr(e,this.data,t,this.fieldTransforms)}}class au{constructor(e,t,n){this.data=e,this.fieldMask=t,this.fieldTransforms=n}toMutation(e,t){return new Lr(e,this.data,this.fieldMask,t,this.fieldTransforms)}}function ou(e){switch(e){case 0:case 2:case 1:return!0;case 3:case 4:return!1;default:throw y()}}class lu{constructor(e,t,n,r,s,i){this.settings=e,this.databaseId=t,this.serializer=n,this.ignoreUndefinedProperties=r,void 0===s&&this.Fu(),this.fieldTransforms=s||[],this.fieldMask=i||[]}get path(){return this.settings.path}get Mu(){return this.settings.Mu}xu(e){return new lu(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 Au(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(ou(this.Mu)&&su.test(e))throw this.qu('Document fields cannot begin and end with "__"')}}class cu{constructor(e,t,n){this.databaseId=e,this.ignoreUndefinedProperties=t,this.serializer=n||yo(e)}$u(e,t,n,r=!1){return new lu({Mu:e,methodName:t,Ku:n,path:B.emptyPath(),Nu:!1,Qu:r},this.databaseId,this.serializer,this.ignoreUndefinedProperties)}}function uu(e){const t=e._freezeSettings(),n=yo(e._databaseId);return new cu(e._databaseId,!!t.ignoreUndefinedProperties,n)}function du(e,t,n,r,s,i={}){const a=e.$u(i.merge||i.mergeFields?2:0,t,n,s);Iu("Data must be an object, but it was:",a,r);const o=xu(r,a);let l,c;if(i.merge)l=new lt(a.fieldMask),c=a.fieldTransforms;else if(i.mergeFields){const e=[];for(const r of i.mergeFields){const s=_u(t,r,n);if(!a.contains(s))throw new x(S.INVALID_ARGUMENT,`Field '${s}' is specified in your field mask but missing from your input data.`);Du(e,s)||e.push(s)}l=new lt(e),c=a.fieldTransforms.filter((e=>l.covers(e.field)))}else l=null,c=a.fieldTransforms;return new iu(new Gt(o),l,c)}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 pu(e,t,n){return new lu({Mu:3,Ku:t.settings.Ku,methodName:e._methodName,Nu:n},t.databaseId,t.serializer,t.ignoreUndefinedProperties)}class fu extends tu{_toFieldTransform(e){return new br(e.path,new hr)}isEqual(e){return e instanceof fu}}class mu extends tu{constructor(e,t){super(e),this.Uu=t}_toFieldTransform(e){const t=pu(this,e,!0),n=this.Uu.map((e=>Su(e,t))),r=new pr(n);return new br(e.path,r)}isEqual(e){return e instanceof mu&&a.deepEqual(this.Uu,e.Uu)}}class vu extends tu{constructor(e,t){super(e),this.Uu=t}_toFieldTransform(e){const t=pu(this,e,!0),n=this.Uu.map((e=>Su(e,t))),r=new mr(n);return new br(e.path,r)}isEqual(e){return e instanceof vu&&a.deepEqual(this.Uu,e.Uu)}}class gu extends tu{constructor(e,t){super(e),this.Wu=t}_toFieldTransform(e){const t=new gr(e.serializer,or(e.serializer,this.Wu));return new br(e.path,t)}isEqual(e){return e instanceof gu&&this.Wu===e.Wu}}function yu(e,t,n,r){const s=e.$u(1,t,n);Iu("Data must be an object, but it was:",s,r);const i=[],o=Gt.empty();Ze(r,((e,r)=>{const l=Cu(t,e,n);r=a.getModularInstance(r);const c=s.Bu(l);if(r instanceof hu)i.push(l);else{const e=Su(r,c);null!=e&&(i.push(l),o.set(l,e))}}));const l=new lt(i);return new au(o,l,s.fieldTransforms)}function wu(e,t,n,r,s,i){const o=e.$u(1,t,n),l=[_u(t,r,n)],c=[s];if(i.length%2!=0)throw new x(S.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<i.length;e+=2)l.push(_u(t,i[e])),c.push(i[e+1]);const u=[],d=Gt.empty();for(let e=l.length-1;e>=0;--e)if(!Du(u,l[e])){const t=l[e];let n=c[e];n=a.getModularInstance(n);const r=o.Bu(t);if(n instanceof hu)u.push(t);else{const e=Su(n,r);null!=e&&(u.push(t),d.set(t,e))}}const h=new lt(u);return new au(d,h,o.fieldTransforms)}function bu(e,t,n,r=!1){return Su(n,e.$u(r?4:3,t))}function Su(e,t){if(Eu(e=a.getModularInstance(e)))return Iu("Unsupported field value:",t,e),xu(e,t);if(e instanceof tu)return function(e,t){if(!ou(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 s of e){let e=Su(s,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=a.getModularInstance(e)))return{nullValue:"NULL_VALUE"};if("number"==typeof e)return or(t.serializer,e);if("boolean"==typeof e)return{booleanValue:e};if("string"==typeof e)return{stringValue:e};if(e instanceof Date){const n=O.fromDate(e);return{timestampValue:ps(t.serializer,n)}}if(e instanceof O){const n=new O(e.seconds,1e3*Math.floor(e.nanoseconds/1e3));return{timestampValue:ps(t.serializer,n)}}if(e instanceof nu)return{geoPointValue:{latitude:e.latitude,longitude:e.longitude}};if(e instanceof Zc)return{bytesValue:fs(t.serializer,e._byteString)};if(e instanceof qc){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:gs(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 ir(t.serializer,e)}))}}}}}}(e,t);throw t.qu(`Unsupported field value: ${Nc(e)}`)}(e,t)}function xu(e,t){const n={};return tt(e)?t.path&&t.path.length>0&&t.fieldMask.push(t.path):Ze(e,((e,r)=>{const s=Su(r,t.Ou(e));null!=s&&(n[e]=s)})),{mapValue:{fields:n}}}function Eu(e){return!("object"!=typeof e||null===e||e instanceof Array||e instanceof Date||e instanceof O||e instanceof nu||e instanceof Zc||e instanceof qc||e instanceof tu||e instanceof ru)}function Iu(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=Nc(n);throw"an object"===r?t.qu(e+" a custom object"):t.qu(e+" "+r)}}function _u(e,t,n){if((t=a.getModularInstance(t))instanceof eu)return t._internalPath;if("string"==typeof t)return Cu(e,t);throw Au("Field path arguments must be of type string or ",e,!1,void 0,n)}const Tu=new RegExp("[~\\*/\\[\\]]");function Cu(e,t,n){if(t.search(Tu)>=0)throw Au(`Invalid field path (${t}). Paths must not contain '~', '*', '/', '[', or ']'`,e,!1,void 0,n);try{return new eu(...t.split("."))._internalPath}catch(r){throw Au(`Invalid field path (${t}). Paths must not be empty, begin with '.', end with '.', or contain '..'`,e,!1,void 0,n)}}function Au(e,t,n,r,s){const i=r&&!r.isEmpty(),a=void 0!==s;let o=`Function ${t}() called with invalid data`;n&&(o+=" (via `toFirestore()`)"),o+=". ";let l="";return(i||a)&&(l+=" (found",i&&(l+=` in field ${r}`),a&&(l+=` in document ${s}`),l+=")"),new x(S.INVALID_ARGUMENT,o+e+l)}function Du(e,t){return e.some((e=>e.isEqual(t)))}class ku{constructor(e,t,n,r,s){this._firestore=e,this._userDataWriter=t,this._key=n,this._document=r,this._converter=s}get id(){return this._key.path.lastSegment()}get ref(){return new qc(this._firestore,this._converter,this._key)}exists(){return null!==this._document}data(){if(this._document){if(this._converter){const e=new Lu(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(Mu("DocumentSnapshot.get",e));if(null!==t)return this._userDataWriter.convertValue(t)}}}class Lu extends ku{data(){return super.data()}}function Mu(e,t){return"string"==typeof t?Cu(e,t):t instanceof eu?t._internalPath:t._delegate._internalPath}function Nu(e){if("L"===e.limitType&&0===e.explicitOrderBy.length)throw new x(S.UNIMPLEMENTED,"limitToLast() queries require specifying at least one orderBy() clause")}class Pu{}class Ru extends Pu{}class Vu 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 Vu(e,t,n)}_apply(e){const t=this._parse(e);return Gu(e._query,t),new Fc(e.firestore,e.converter,Vn(e._query,t))}_parse(e){const t=uu(e.firestore),n=function(e,t,n,r,s,i,a){let o;if(s.isKeyField()){if("array-contains"===i||"array-contains-any"===i)throw new x(S.INVALID_ARGUMENT,`Invalid Query. You can't perform '${i}' queries on documentId().`);if("in"===i||"not-in"===i){zu(a,i);const t=[];for(const n of a)t.push(ju(r,e,n));o={arrayValue:{values:t}}}else o=ju(r,e,a)}else"in"!==i&&"not-in"!==i&&"array-contains-any"!==i||zu(a,i),o=bu(n,"where",a,"in"===i||"not-in"===i);return en.create(s,i,o)}(e._query,0,t,e.firestore._databaseId,this._field,this._op,this._value);return n}}class Ou extends Pu{constructor(e,t){super(),this.type=e,this._queryConstraints=t}static _create(e,t){return new Ou(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=Vn(n,e)}(e._query,t),new Fc(e.firestore,e.converter,Vn(e._query,t)))}_getQueryConstraints(){return this._queryConstraints}_getOperator(){return"and"===this.type?"and":"or"}}class $u extends Ru{constructor(e,t){super(),this._field=e,this._direction=t,this.type="orderBy"}static _create(e,t){return new $u(e,t)}_apply(e){const t=function(e,t,n){if(null!==e.startAt)throw new x(S.INVALID_ARGUMENT,"Invalid query. You must not call startAt() or startAfter() before calling orderBy().");if(null!==e.endAt)throw new x(S.INVALID_ARGUMENT,"Invalid query. You must not call endAt() or endBefore() before calling orderBy().");return new Jt(t,n)}(e._query,this._field,this._direction);return new Fc(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 Fu extends Ru{constructor(e,t,n){super(),this.type=e,this._limit=t,this._limitType=n}static _create(e,t,n){return new Fu(e,t,n)}_apply(e){return new Fc(e.firestore,e.converter,On(e._query,this._limit,this._limitType))}}class qu extends Ru{constructor(e,t,n){super(),this.type=e,this._docOrFields=t,this._inclusive=n}static _create(e,t,n){return new qu(e,t,n)}_apply(e){const t=Bu(e,this.type,this._docOrFields,this._inclusive);return new Fc(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 Uu extends Ru{constructor(e,t,n){super(),this.type=e,this._docOrFields=t,this._inclusive=n}static _create(e,t,n){return new Uu(e,t,n)}_apply(e){const t=Bu(e,this.type,this._docOrFields,this._inclusive);return new Fc(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 Bu(e,t,n,r){if(n[0]=a.getModularInstance(n[0]),n[0]instanceof ku)return function(e,t,n,r,s){if(!r)throw new x(S.NOT_FOUND,`Can't use a DocumentSnapshot that doesn't exist for ${n}().`);const i=[];for(const n of Mn(e))if(n.field.isKeyField())i.push(Lt(t,r.key));else{const e=r.data.field(n.field);if(mt(e))throw new x(S.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 x(S.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.`)}i.push(e)}return new Qt(i,s)}(e._query,e.firestore._databaseId,t,n[0]._document,r);{const s=uu(e.firestore);return function(e,t,n,r,s,i){const a=e.explicitOrderBy;if(s.length>a.length)throw new x(S.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 o=[];for(let i=0;i<s.length;i++){const l=s[i];if(a[i].field.isKeyField()){if("string"!=typeof l)throw new x(S.INVALID_ARGUMENT,`Invalid query. Expected a string for document ID in ${r}(), but got a ${typeof l}`);if(!Ln(e)&&-1!==l.indexOf("/"))throw new x(S.INVALID_ARGUMENT,`Invalid query. When querying a collection and ordering by documentId(), the value passed to ${r}() must be a plain document ID, but '${l}' contains a slash.`);const n=e.path.child(q.fromString(l));if(!j.isDocumentKey(n))throw new x(S.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 s=new j(n);o.push(Lt(t,s))}else{const e=bu(n,r,l);o.push(e)}}return new Qt(o,i)}(e._query,e.firestore._databaseId,s,t,n,r)}}function ju(e,t,n){if("string"==typeof(n=a.getModularInstance(n))){if(""===n)throw new x(S.INVALID_ARGUMENT,"Invalid query. When querying with documentId(), you must provide a valid document ID, but it was an empty string.");if(!Ln(t)&&-1!==n.indexOf("/"))throw new x(S.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(q.fromString(n));if(!j.isDocumentKey(r))throw new x(S.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 Lt(e,new j(r))}if(n instanceof qc)return Lt(e,n._key);throw new x(S.INVALID_ARGUMENT,`Invalid query. When querying with documentId(), you must provide a valid string or a DocumentReference, but it was: ${Nc(n)}.`)}function zu(e,t){if(!Array.isArray(e)||0===e.length)throw new x(S.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 x(S.INVALID_ARGUMENT,`Invalid query. You cannot use more than one '${t.op.toString()}' filter.`):new x(S.INVALID_ARGUMENT,`Invalid query. You cannot use '${t.op.toString()}' filters with '${n.toString()}' filters.`)}function Ku(e,t){if(!(t instanceof Vu||t instanceof Ou))throw new x(S.INVALID_ARGUMENT,`Function ${e}() requires AppliableConstraints created with a call to 'where(...)', 'or(...)', or 'and(...)'.`)}class Hu{convertValue(e,t="none"){switch(xt(e)){case 0:return null;case 1:return e.booleanValue;case 2:return pt(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(ft(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 s=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=>pt(e.doubleValue)));return new ru(s)}convertGeoPoint(e){return new nu(pt(e.latitude),pt(e.longitude))}convertArray(e,t){return(e.values||[]).map((e=>this.convertValue(e,t)))}convertServerTimestamp(e,t){switch(t){case"previous":const n=vt(e);return null==n?null:this.convertValue(n,t);case"estimate":return this.convertTimestamp(gt(e));default:return null}}convertTimestamp(e){const t=ht(e);return new O(t.seconds,t.nanos)}convertDocumentKey(e,t){const n=q.fromString(e);w(Bs(n));const r=new wt(n.get(1),n.get(3)),s=new j(n.popFirst(5));return r.isEqual(t)||m(`Document ${s} 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.`),s}}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 Zc(e)}convertReference(e){const t=this.convertDocumentKey(e,this.firestore._databaseId);return new qc(this.firestore,null,t)}}function Yu(){return new Jc("count")}class Ju{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,s,i){super(e,t,n,r,i),this._firestore=e,this._firestoreImpl=e,this.metadata=s}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(Mu("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 Ju(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 Ju(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 x(S.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 Ju(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 Ju(e._snapshot.mutatedKeys.has(t.doc.key),e._snapshot.fromCache),e.query.converter);let s=-1,i=-1;return 0!==t.type&&(s=n.indexOf(t.doc.key),n=n.delete(t.doc.key)),1!==t.type&&(n=n.add(t.doc),i=n.indexOf(t.doc.key)),{type:td(t.type),doc:r,oldIndex:s,newIndex:i}}))}}(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 Zc(e)}convertReference(e){const t=this.convertDocumentKey(e,this.firestore._databaseId);return new qc(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=rc(e);try{const e=await function(e,t){const n=b(e),r=O.now(),s=t.reduce(((e,t)=>e.add(t.key)),nr());let i,a;return n.persistence.runTransaction("Locally write mutations","readwrite",(e=>{let o=Hn(),l=nr();return n.hs.getEntries(e,s).next((e=>{o=e,o.forEach(((e,t)=>{t.isValidDocument()||(l=l.add(e))}))})).next((()=>n.localDocuments.getOverlayedDocuments(e,o))).next((s=>{i=s;const a=[];for(const e of t){const t=Ar(e,i.get(e.key).overlayedDocument);null!=t&&a.push(new Lr(e.key,t,Kt(t.value.mapValue),xr.exists(!0)))}return n.mutationQueue.addMutationBatch(e,r,a,t)})).next((t=>{a=t;const r=t.applyToLocalDocumentSet(i,l);return n.documentOverlayCache.saveOverlays(e,t.batchId,r)}))})).then((()=>({batchId:a.batchId,changes:Yn(i)})))}(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 Gl(r,e.changes),await Bo(r.remoteStore)}catch(e){const t=nl(e,"Failed to persist write");n.reject(t)}}(await xc(e),t,n))),n.promise}(Qc(e),t)}function sd(e,t,n){const r=n.docs.get(t._key),s=new nd(e);return new Xu(e,s,t._key,r,new Ju(n.hasPendingWrites,n.fromCache),t.converter)}function id(e,t){const n=Pc(e.firestore,Hc),r=Qc(n),s=et(t,((e,t)=>new qr(t,e.aggregateType,e._internalFieldPath)));return function(e,t,n){const r=new E;return e.asyncQueue.enqueueAndForget((async()=>{try{const s=await Ec(e);r.resolve(async function(e,t,n){var r;const s=b(e),{request:i,lt:a,parent:o}=Ms(s.serializer,Pn(t),n);s.connection.Co||delete i.parent;const l=(await s.ko("RunAggregationQuery",s.serializer.databaseId,o,i,1)).filter((e=>!!e.result));w(1===l.length);const c=null===(r=l[0].result)||void 0===r?void 0:r.aggregateFields;return Object.keys(c).reduce(((e,t)=>(e[a[t]]=c[t],e)),{})}(s,t,n))}catch(e){r.reject(e)}})),r.promise}(r,e._query,s).then((t=>function(e,t,n){const r=new nd(e);return new Xc(t,r,n)}(n,e,t)))}class ad{constructor(e){this.kind="memory",this._onlineComponentProvider=lc.provider,(null==e?void 0:e.garbageCollector)?this._offlineComponentProvider=e.garbageCollector._offlineComponentProvider:this._offlineComponentProvider={build:()=>new ic(void 0)}}toJSON(){return{kind:this.kind}}}class od{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 ld{constructor(){this.kind="memoryEager",this._offlineComponentProvider=sc.provider}toJSON(){return{kind:this.kind}}}class cd{constructor(e){this.kind="memoryLru",this._offlineComponentProvider={build:()=>new ic(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=lc.provider,this._offlineComponentProvider={build:t=>new ac(t,null==e?void 0:e.cacheSizeBytes,this.forceOwnership)}}}class dd{constructor(){this.kind="PersistentMultipleTab"}toJSON(){return{kind:this.kind}}_initialize(e){this._onlineComponentProvider=lc.provider,this._offlineComponentProvider={build:t=>new oc(t,null==e?void 0:e.cacheSizeBytes)}}}function hd(e){return new ud(null==e?void 0:e.forceOwnership)}const pd={maxAttempts:5};class fd{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),s=Qu(r.converter,t,n),i=du(this._dataReader,"WriteBatch.set",r._key,s,null!==r.converter,n);return this._mutations.push(i.toMutation(r._key,xr.none())),this}update(e,t,n,...r){this._verifyNotCommitted();const s=md(e,this._firestore);let i;return i="string"==typeof(t=a.getModularInstance(t))||t instanceof eu?wu(this._dataReader,"WriteBatch.update",s._key,t,n,r):yu(this._dataReader,"WriteBatch.update",s._key,t),this._mutations.push(i.toMutation(s._key,xr.exists(!0))),this}delete(e){this._verifyNotCommitted();const t=md(e,this._firestore);return this._mutations=this._mutations.concat(new Rr(t._key,xr.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 x(S.FAILED_PRECONDITION,"A write batch can no longer be used after commit() has been called.")}}function md(e,t){if((e=a.getModularInstance(e)).firestore!==t)throw new x(S.INVALID_ARGUMENT,"Provided document reference is from a different Firestore instance.");return e}class vd 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),s=Qu(r.converter,t,n),i=du(this._dataReader,"Transaction.set",r._key,s,null!==r.converter,n);return this._transaction.set(r._key,i),this}update(e,t,n,...r){const s=md(e,this._firestore);let i;return i="string"==typeof(t=a.getModularInstance(t))||t instanceof eu?wu(this._dataReader,"Transaction.update",s._key,t,n,r):yu(this._dataReader,"Transaction.update",s._key,t),this._transaction.update(s._key,i),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 Ju(!1,!1),t.converter)))}}function gd(e,t){if("string"!=typeof e[t])throw new x(S.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 bc(e),t)))})(Qc(e._firestore),t).then((e=>f(`setting persistent cache index auto creation isEnabled=${t} succeeded`))).catch((e=>v(`setting persistent cache index auto creation isEnabled=${t} failed`,e)))}const bd=new WeakMap;class Sd{constructor(){this.Gu=new Map}static get instance(){return xd||(xd=new Sd,function(e){if(Kr)throw new Error("a TestingHooksSpi instance is already set");Kr=e}(xd)),xd}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 xd=null;!function(e,t=!0){!function(e){d=e}(r.SDK_VERSION),r._registerComponent(new s.Component("firestore",((e,{instanceIdentifier:n,options:r})=>{const s=e.getProvider("app").getImmediate(),i=new Hc(new C(e.getProvider("auth-internal")),new L(e.getProvider("app-check-internal")),function(e,t){if(!Object.prototype.hasOwnProperty.apply(e.options,["projectId"]))throw new x(S.INVALID_ARGUMENT,'"projectId" not provided in firebase.initializeApp.');return new wt(e.options.projectId,t)}(s,n),s);return r=Object.assign({useFetchStreams:t},r),i._setSettings(r),i}),"PUBLIC").setMultipleInstances(!0)),r.registerVersion(c,"4.7.5",e),r.registerVersion(c,"4.7.5","cjs2017")}(),t.AbstractUserDataWriter=Hu,t.AggregateField=Jc,t.AggregateQuerySnapshot=Xc,t.Bytes=Zc,t.CACHE_SIZE_UNLIMITED=-1,t.CollectionReference=Uc,t.DocumentReference=qc,t.DocumentSnapshot=Xu,t.FieldPath=eu,t.FieldValue=tu,t.Firestore=Hc,t.FirestoreError=x,t.GeoPoint=nu,t.LoadBundleTask=Kc,t.PersistentCacheIndexManager=yd,t.Query=Fc,t.QueryCompositeFilterConstraint=Ou,t.QueryConstraint=Ru,t.QueryDocumentSnapshot=Zu,t.QueryEndAtConstraint=Uu,t.QueryFieldFilterConstraint=Vu,t.QueryLimitConstraint=Fu,t.QueryOrderByConstraint=$u,t.QuerySnapshot=ed,t.QueryStartAtConstraint=qu,t.SnapshotMetadata=Ju,t.Timestamp=O,t.Transaction=vd,t.VectorValue=ru,t.WriteBatch=fd,t._AutoId=N,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._FieldPath=B,t._TestingHooks=class{constructor(){throw new Error("instances of this class should not be created")}static onExistenceFilterMismatch(e){return Sd.instance.onExistenceFilterMismatch(e)}},t._cast=Pc,t._debugAssert=function(e,t){e||y()},t._internalAggregationQueryToProtoRunAggregationQueryRequest=function(e,t){var n;const r=et(t,((e,t)=>new qr(t,e.aggregateType,e._internalFieldPath))),s=null===(n=Qc(Pc(e.firestore,Hc))._onlineComponents)||void 0===n?void 0:n.datastore.serializer;return void 0===s?null:Ms(s,Pn(e._query),r,!0).request},t._internalQueryToProtoQueryTarget=function(e){var t;const n=null===(t=Qc(Pc(e.firestore,Hc))._onlineComponents)||void 0===t?void 0:t.datastore.serializer;return void 0===n?null:Ls(n,Nn(e._query)).ct},t._isBase64Available=function(){return"undefined"!=typeof atob},t._logWarn=v,t._validateIsNotUsedTogether=kc,t.addDoc=function(e,t){const n=Pc(e.firestore,Hc),r=Bc(e),s=Qu(e.converter,t);return rd(n,[du(uu(e.firestore),"addDoc",r._key,s,null!==e.converter,{}).toMutation(r._key,xr.exists(!1))]).then((()=>r))},t.aggregateFieldEqual=function(e,t){var n,r;return e instanceof Jc&&t instanceof Jc&&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 jc(e.query,t.query)&&a.deepEqual(e.data(),t.data())},t.and=function(...e){return e.forEach((e=>Ku("and",e))),Ou._create("and",e)},t.arrayRemove=function(...e){return new vu("arrayRemove",e)},t.arrayUnion=function(...e){return new mu("arrayUnion",e)},t.average=function(e){return new Jc("avg",_u("average",e))},t.clearIndexedDbPersistence=function(e){if(e._initialized&&!e._terminated)throw new x(S.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(!ae.p())return Promise.resolve();const t=e+"main";await ae.delete(t)}(Pa(e._databaseId,e._persistenceKey)),t.resolve()}catch(e){t.reject(e)}})),t.promise},t.collection=function(e,t,...n){if(e=a.getModularInstance(e),Dc("collection","path",t),e instanceof Oc){const r=q.fromString(t,...n);return Mc(r),new Uc(e,null,r)}{if(!(e instanceof qc||e instanceof Uc))throw new x(S.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");const r=e._path.child(q.fromString(t,...n));return Mc(r),new Uc(e.firestore,null,r)}},t.collectionGroup=function(e,t){if(e=Pc(e,Oc),Dc("collectionGroup","collection id",t),t.indexOf("/")>=0)throw new x(S.INVALID_ARGUMENT,`Invalid collection ID '${t}' passed to function collectionGroup(). Collection IDs must not contain '/'.`);return new Fc(e,null,function(e){return new Cn(q.emptyPath(),e)}(t))},t.connectFirestoreEmulator=$c,t.count=Yu,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 bc(e))))})(Qc(e._firestore)).then((e=>f("deleting all persistent cache indexes succeeded"))).catch((e=>v("deleting all persistent cache indexes failed",e)))},t.deleteDoc=function(e){return rd(Pc(e.firestore,Hc),[new Rr(e._key,xr.none())])},t.deleteField=function(){return new hu("deleteField")},t.disableNetwork=function(e){return function(e){return e.asyncQueue.enqueue((async()=>{const t=await wc(e),n=await Sc(e);return t.setNetworkEnabled(!1),async function(e){const t=b(e);t.k_.add(0),await Co(t),t.K_.set("Offline")}(n)}))}(Qc(e=Pc(e,Hc)))},t.disablePersistentCacheIndexAutoCreation=function(e){wd(e,!1)},t.doc=Bc,t.documentId=function(){return new eu("__name__")},t.enableIndexedDbPersistence=function(e,t){v("enableIndexedDbPersistence() will be deprecated in the future, you can use `FirestoreSettings.cache` instead.");const n=e._freezeSettings();return Yc(e,lc.provider,{build:e=>new ac(e,n.cacheSizeBytes,null==t?void 0:t.forceOwnership)}),Promise.resolve()},t.enableMultiTabIndexedDbPersistence=async function(e){v("enableMultiTabIndexedDbPersistence() will be deprecated in the future, you can use `FirestoreSettings.cache` instead.");const t=e._freezeSettings();Yc(e,lc.provider,{build:e=>new oc(e,t.cacheSizeBytes)})},t.enableNetwork=function(e){return function(e){return e.asyncQueue.enqueue((async()=>{const t=await wc(e),n=await Sc(e);return t.setNetworkEnabled(!0),function(e){const t=b(e);return t.k_.delete(0),To(t)}(n)}))}(Qc(e=Pc(e,Hc)))},t.enablePersistentCacheIndexAutoCreation=function(e){wd(e,!0)},t.endAt=function(...e){return Uu._create("endAt",e,!0)},t.endBefore=function(...e){return Uu._create("endBefore",e,!1)},t.ensureFirestoreConfigured=Qc,t.executeWrite=rd,t.getAggregateFromServer=id,t.getCountFromServer=function(e){return id(e,{count:Yu()})},t.getDoc=function(e){e=Pc(e,qc);const t=Pc(e.firestore,Hc);return _c(Qc(t),e._key).then((n=>sd(t,e,n)))},t.getDocFromCache=function(e){e=Pc(e,qc);const t=Pc(e.firestore,Hc),n=Qc(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 x(S.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=nl(e,`Failed to get document '${t} from cache`);n.reject(r)}}(await bc(e),t,n))),n.promise}(n,e._key).then((n=>new Xu(t,r,e._key,n,new Ju(null!==n&&n.hasLocalMutations,!0),e.converter)))},t.getDocFromServer=function(e){e=Pc(e,qc);const t=Pc(e.firestore,Hc);return _c(Qc(t),e._key,{source:"server"}).then((n=>sd(t,e,n)))},t.getDocs=function(e){e=Pc(e,Fc);const t=Pc(e.firestore,Hc),n=Qc(t),r=new nd(t);return Nu(e._query),Tc(n,e._query).then((n=>new ed(t,r,e,n)))},t.getDocsFromCache=function(e){e=Pc(e,Fc);const t=Pc(e.firestore,Hc),n=Qc(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 Ka(e,t,!0),s=new El(t,r.ds),i=s.ga(r.documents),a=s.applyChanges(i,!1);n.resolve(a.snapshot)}catch(e){const r=nl(e,`Failed to execute query '${t} against cache`);n.reject(r)}}(await bc(e),t,n))),n.promise}(n,e._query).then((n=>new ed(t,r,e,n)))},t.getDocsFromServer=function(e){e=Pc(e,Fc);const t=Pc(e.firestore,Hc),n=Qc(t),r=new nd(t);return Tc(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(),s="string"==typeof e?e:t||"(default)",i=r._getProvider(n,"firestore").getImmediate({identifier:s});if(!i._initialized){const e=a.getDefaultEmulatorHostnameAndPort("firestore");e&&$c(i,...e)}return i},t.getPersistentCacheIndexManager=function(e){var t;e=Pc(e,Hc);const n=bd.get(e);if(n)return n;if("persistent"!==(null===(t=Qc(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 gu("increment",e)},t.initializeFirestore=function(e,t,n){n||(n="(default)");const s=r._getProvider(e,"firestore");if(s.isInitialized(n)){const e=s.getImmediate({identifier:n}),r=s.getOptions(n);if(a.deepEqual(r,t))return e;throw new x(S.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 x(S.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 x(S.INVALID_ARGUMENT,"cacheSizeBytes must be at least 1048576");return s.initialize({options:t,instanceIdentifier:n})},t.limit=function(e){return Rc("limit",e),Fu._create("limit",e,"F")},t.limitToLast=function(e){return Rc("limitToLast",e),Fu._create("limitToLast",e,"L")},t.loadBundle=function(e,t){const n=Qc(e=Pc(e,Hc)),r=new Kc;return function(e,t,n,r){const s=function(e,t){let n;return n="string"==typeof e?Hr().encode(e):e,function(e,t){return new dc(e,t)}(function(e,t){if(e instanceof Uint8Array)return cc(e,t);if(e instanceof ArrayBuffer)return cc(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,yo(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=vs(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(bl(r));const s=new wl(r,e.localStore,t.serializer);let i=await t.Ga();for(;i;){const e=await s.Pa(i);e&&n._updateProgress(e),i=await t.Ga()}const a=await s.complete();return await Gl(e,a.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(a.progress),Promise.resolve(a.Ia)}catch(e){return v("SyncEngine",`Loading bundle failed with ${e}`),n._failWith(e),Promise.resolve(new Set)}})(r,t,n).then((e=>{r.sharedClientState.notifyBundleLoaded(e)}))}(await xc(e),s,r)}))}(n,e._databaseId,t,r),r},t.memoryEagerGarbageCollector=function(){return new ld},t.memoryLocalCache=function(e){return new ad(e)},t.memoryLruGarbageCollector=function(e){return new cd(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 bc(e),t)))}(Qc(e=Pc(e,Hc)),t).then((t=>t?new Fc(e,null,t.query):null))},t.onSnapshot=function(e,...t){var n,r,s;e=a.getModularInstance(e);let i={includeMetadataChanges:!1,source:"default"},o=0;"object"!=typeof t[o]||Gc(t[o])||(i=t[o],o++);const l={includeMetadataChanges:i.includeMetadataChanges,source:i.source};if(Gc(t[o])){const e=t[o];t[o]=null===(n=e.next)||void 0===n?void 0:n.bind(e),t[o+1]=null===(r=e.error)||void 0===r?void 0:r.bind(e),t[o+2]=null===(s=e.complete)||void 0===s?void 0:s.bind(e)}let c,u,d;if(e instanceof qc)u=Pc(e.firestore,Hc),d=Dn(e._key.path),c={next:n=>{t[o]&&t[o](sd(u,e,n))},error:t[o+1],complete:t[o+2]};else{const n=Pc(e,Fc);u=Pc(n.firestore,Hc),d=n._query;const r=new nd(u);c={next:e=>{t[o]&&t[o](new ed(u,r,n,e))},error:t[o+1],complete:t[o+2]},Nu(e._query)}return function(e,t,n,r){const s=new uc(r),i=new vl(t,s,n);return e.asyncQueue.enqueueAndForget((async()=>cl(await Ic(e),i))),()=>{s.eu(),e.asyncQueue.enqueueAndForget((async()=>ul(await Ic(e),i)))}}(Qc(u),d,l,c)},t.onSnapshotsInSync=function(e,t){return function(e,t){const n=new uc(t);return e.asyncQueue.enqueueAndForget((async()=>function(e,t){b(e).X_.add(t),t.next()}(await Ic(e),n))),()=>{n.eu(),e.asyncQueue.enqueueAndForget((async()=>function(e,t){b(e).X_.delete(t)}(await Ic(e),n)))}}(Qc(e=Pc(e,Hc)),Gc(t)?t:{next:t})},t.or=function(...e){return e.forEach((e=>Ku("or",e))),Ou._create("or",e)},t.orderBy=function(e,t="asc"){const n=t,r=Mu("orderBy",e);return $u._create(r,n)},t.persistentLocalCache=function(e){return new od(e)},t.persistentMultipleTabManager=function(){return new dd},t.persistentSingleTabManager=hd,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 Ou)).length,n=e.filter((e=>e instanceof Vu)).length;if(t>1||t>0&&n>0)throw new x(S.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=jc,t.refEqual=function(e,t){return e=a.getModularInstance(e),t=a.getModularInstance(t),(e instanceof qc||e instanceof Uc)&&(t instanceof qc||t instanceof Uc)&&e.firestore===t.firestore&&e.path===t.path&&e.converter===t.converter},t.runTransaction=function(e,t,n){e=Pc(e,Hc);const r=Object.assign(Object.assign({},pd),n);return function(e){if(e.maxAttempts<1)throw new x(S.INVALID_ARGUMENT,"Max attempts must be at least 1")}(r),function(e,t,n){const r=new E;return e.asyncQueue.enqueueAndForget((async()=>{const s=await Ec(e);new pc(e.asyncQueue,s,n,t,r).cu()})),r.promise}(Qc(e),(n=>t(new vd(e,n))),r)},t.serverTimestamp=function(){return new fu("serverTimestamp")},t.setDoc=function(e,t,n){e=Pc(e,qc);const r=Pc(e.firestore,Hc),s=Qu(e.converter,t,n);return rd(r,[du(uu(r),"setDoc",e._key,s,null!==e.converter,n).toMutation(e._key,xr.none())])},t.setIndexConfiguration=function(e,t){const n=Qc(e=Pc(e,Hc));if(!n._uninitializedComponentsProvider||"memory"===n._uninitializedComponentsProvider._offline.kind)return v("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 x(S.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=gd(e,"collectionGroup"),r=[];if(Array.isArray(e.fields))for(const t of e.fields){const e=Cu("setIndexConfiguration",gd(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,Y.empty()))}return n}(t);return function(e,t){return e.asyncQueue.enqueue((async()=>async function(e,t){const n=b(e),r=n.indexManager,s=[];return n.persistence.runTransaction("Configure indexes","readwrite",(e=>r.getFieldIndexes(e).next((n=>function(e,t,n,r,s){e=[...e],t=[...t],e.sort(n),t.sort(n);const i=e.length,a=t.length;let o=0,l=0;for(;o<a&&l<i;){const i=n(e[l],t[o]);i<0?s(e[l++]):i>0?r(t[o++]):(o++,l++)}for(;o<a;)r(t[o++]);for(;l<i;)s(e[l++])}(n,t,H,(t=>{s.push(r.addFieldIndex(e,t))}),(t=>{s.push(r.deleteFieldIndex(e,t))})))).next((()=>se.waitFor(s)))))}(await bc(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&&jc(e.query,t.query)&&e.metadata.isEqual(t.metadata)&&e._snapshot.isEqual(t._snapshot)},t.startAfter=function(...e){return qu._create("startAfter",e,!1)},t.startAt=function(...e){return qu._create("startAt",e,!0)},t.sum=function(e){return new Jc("sum",_u("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=Pc(e,qc);const s=Pc(e.firestore,Hc),i=uu(s);let o;return o="string"==typeof(t=a.getModularInstance(t))||t instanceof eu?wu(i,"updateDoc",e._key,t,n,r):yu(i,"updateDoc",e._key,t),rd(s,[o.toMutation(e._key,xr.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);Po(n.remoteStore)||f("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=nl(e,"Initialization of waitForPendingWrites() operation failed");t.reject(n)}}(await xc(e),t))),t.promise}(Qc(e=Pc(e,Hc)))},t.where=function(e,t,n){const r=t,s=Mu("where",e);return Vu._create(s,r,n)},t.writeBatch=function(e){return Qc(e=Pc(e,Hc)),new fd(e,(t=>rd(e,t)))}},249:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(6199),s=n(6336),i=n(5319);function a(e,t){const n={};for(const r in e)e.hasOwnProperty(r)&&(n[r]=t(e[r]));return n}function o(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=>o(e)));if("function"==typeof e||"object"==typeof e)return a(e,(e=>o(e)));throw new Error("Data cannot be encoded in JSON: "+e)}function l(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=>l(e))):"function"==typeof e||"object"==typeof e?a(e,(e=>l(e))):e}const c="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 s.FirebaseError{constructor(e,t,n){super(`${c}/${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),s=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],s=t}const i=e.message;"string"==typeof i&&(s=i),n=e.details,void 0!==n&&(n=l(n))}}catch(e){}return"ok"===r?null:new d(r,s,n)}class p{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 f="us-central1",m=/^data: (.*?)(?:\n|$)/;class v{constructor(e,t,n,r,s=f,i=(...e)=>fetch(...e)){this.app=e,this.fetchImpl=i,this.emulatorOrigin=null,this.contextProvider=new p(t,n,r),this.cancelAllRequests=new Promise((e=>{this.deleteService=()=>Promise.resolve(e())}));try{const e=new URL(s);this.customDomain=e.origin+("/"===e.pathname?"":e.pathname),this.region=f}catch(e){this.customDomain=null,this.region=s}}_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 g(e,t,n,r){let s;n["Content-Type"]="application/json";try{s=await r(e,{method:"POST",body:JSON.stringify(t),headers:n})}catch(e){return{status:0,json:null}}let i=null;try{i=await s.json()}catch(e){}return{status:s.status,json:i}}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 s={data:n=o(n)},i=await y(e,r),a=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),c=await Promise.race([g(t,s,i,e.fetchImpl),a.promise,e.cancelAllRequests]);if(a.cancel(),!c)throw new d("cancelled","Firebase Functions instance was deleted.");const u=h(c.status,c.json);if(u)throw u;if(!c.json)throw new d("internal","Response is not valid JSON object.");let p=c.json.data;if(void 0===p&&(p=c.json.result),void 0===p)throw new d("internal","Response is missing data field.");return{data:l(p)}}async function b(e,t,n,r){var s;const i={data:n=o(n)},a=await y(e,r);let c,u,p;a["Content-Type"]="application/json",a.Accept="text/event-stream";try{c=await e.fetchImpl(t,{method:"POST",body:JSON.stringify(i),headers:a,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 f=new Promise(((e,t)=>{u=e,p=t}));null===(s=null==r?void 0:r.signal)||void 0===s||s.addEventListener("abort",(()=>{const e=new d("cancelled","Request was cancelled.");p(e)}));const v=function(e,t,n,r){const s=(e,r)=>{const s=e.match(m);if(!s)return;const i=s[1];try{const e=JSON.parse(i);if("result"in e)return void t(l(e.result));if("message"in e)return void r.enqueue(l(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)}},i=new TextDecoder;return new ReadableStream({start(t){let a="";return async function o(){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:l,done:c}=await e.read();if(c)return a.trim()&&s(a.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()}a+=i.decode(l,{stream:!0});const u=a.split("\n");a=u.pop()||"";for(const e of u)e.trim()&&s(e.trim(),t);return o()}catch(e){const r=e instanceof d?e:h(0,null);t.error(r),n(r)}}()},cancel:()=>e.cancel()})}(c.body.getReader(),u,p,null==r?void 0:r.signal);return{stream:{[Symbol.asyncIterator](){const e=v.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:f}}const S="@firebase/functions",x="0.12.0";function E(e,t,n){!function(e,t,n){e.emulatorOrigin=`http://${t}:${n}`}(s.getModularInstance(e),t,n)}r._registerComponent(new i.Component(c,((e,{instanceIdentifier:t})=>{const n=e.getProvider("app").getImmediate(),r=e.getProvider("auth-internal"),s=e.getProvider("messaging-internal"),i=e.getProvider("app-check-internal");return new v(n,r,s,i,t)}),"PUBLIC").setMultipleInstances(!0)),r.registerVersion(S,x,undefined),r.registerVersion(S,x,"cjs2017"),t.FunctionsError=d,t.connectFunctionsEmulator=E,t.getFunctions=function(e=r.getApp(),t=f){const n=r._getProvider(s.getModularInstance(e),c).getImmediate({identifier:t}),i=s.getDefaultEmulatorHostnameAndPort("functions");return i&&E(n,...i),n},t.httpsCallable=function(e,t,n){return function(e,t,n){const r=r=>function(e,t,n,r){const s=e._url(t);return w(e,s,n,r)}(e,t,r,n||{});return r.stream=(n,r)=>function(e,t,n,r){const s=e._url(t);return b(e,s,n,r||{})}(e,t,n,r),r}(s.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}(s.getModularInstance(e),t,n)}},5844:(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 s={debug:t.LogLevel.DEBUG,verbose:t.LogLevel.VERBOSE,info:t.LogLevel.INFO,warn:t.LogLevel.WARN,error:t.LogLevel.ERROR,silent:t.LogLevel.SILENT},i=t.LogLevel.INFO,a={[t.LogLevel.DEBUG]:"log",[t.LogLevel.VERBOSE]:"log",[t.LogLevel.INFO]:"info",[t.LogLevel.WARN]:"warn",[t.LogLevel.ERROR]:"error"},o=(e,t,...n)=>{if(t<e.logLevel)return;const r=(new Date).toISOString(),s=a[t];if(!s)throw new Error(`Attempted to log a message with an invalid logType (value: ${t})`);console[s](`[${r}]  ${e.name}:`,...n)};t.Logger=class{constructor(e){this.name=e,this._logLevel=i,this._logHandler=o,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?s[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 i of n){let n=null;r&&r.level&&(n=s[r.level]),i.userLogHandler=null===e?null:(r,s,...i)=>{const a=i.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(" ");s>=(null!=n?n:r.logLevel)&&e({level:t.LogLevel[s].toLowerCase(),message:a,args:i,type:r.name})}}}},6336:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});const r={NODE_CLIENT:!1,NODE_ADMIN:!1,SDK_VERSION:"${JSCORE_VERSION}"},s=function(e,t){if(!e)throw i(t)},i=function(e){return new Error("Firebase Database ("+r.SDK_VERSION+") INTERNAL ASSERT FAILED: "+e)},a=function(e){const t=[];let n=0;for(let r=0;r<e.length;r++){let s=e.charCodeAt(r);s<128?t[n++]=s:s<2048?(t[n++]=s>>6|192,t[n++]=63&s|128):55296==(64512&s)&&r+1<e.length&&56320==(64512&e.charCodeAt(r+1))?(s=65536+((1023&s)<<10)+(1023&e.charCodeAt(++r)),t[n++]=s>>18|240,t[n++]=s>>12&63|128,t[n++]=s>>6&63|128,t[n++]=63&s|128):(t[n++]=s>>12|224,t[n++]=s>>6&63|128,t[n++]=63&s|128)}return t},o={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 s=e[t],i=t+1<e.length,a=i?e[t+1]:0,o=t+2<e.length,l=o?e[t+2]:0,c=s>>2,u=(3&s)<<4|a>>4;let d=(15&a)<<2|l>>6,h=63&l;o||(h=64,i||(d=64)),r.push(n[c],n[u],n[d],n[h])}return r.join("")},encodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?btoa(e):this.encodeByteArray(a(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 s=e[n++];if(s<128)t[r++]=String.fromCharCode(s);else if(s>191&&s<224){const i=e[n++];t[r++]=String.fromCharCode((31&s)<<6|63&i)}else if(s>239&&s<365){const i=((7&s)<<18|(63&e[n++])<<12|(63&e[n++])<<6|63&e[n++])-65536;t[r++]=String.fromCharCode(55296+(i>>10)),t[r++]=String.fromCharCode(56320+(1023&i))}else{const i=e[n++],a=e[n++];t[r++]=String.fromCharCode((15&s)<<12|(63&i)<<6|63&a)}}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 s=n[e.charAt(t++)],i=t<e.length?n[e.charAt(t)]:0;++t;const a=t<e.length?n[e.charAt(t)]:64;++t;const o=t<e.length?n[e.charAt(t)]:64;if(++t,null==s||null==i||null==a||null==o)throw new l;const c=s<<2|i>>4;if(r.push(c),64!==a){const e=i<<4&240|a>>2;if(r.push(e),64!==o){const e=a<<6&192|o;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 l extends Error{constructor(){super(...arguments),this.name="DecodeBase64StringError"}}const c=function(e){const t=a(e);return o.encodeByteArray(t,!0)},u=function(e){return c(e).replace(/\./g,"")},d=function(e){try{return o.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 p(){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 f=()=>{try{return p().__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=f())||void 0===t?void 0:t.emulatorHosts)||void 0===n?void 0:n[e]};class v{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 g(){return"undefined"!=typeof navigator&&"string"==typeof navigator.userAgent?navigator.userAgent:""}function y(){var e;const t=null===(e=f())||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,S.prototype.create)}}class S{constructor(e,t,n){this.service=e,this.serviceName=t,this.errors=n}create(e,...t){const n=t[0]||{},r=`${this.service}/${e}`,s=this.errors[e],i=s?function(e,t){return e.replace(x,((e,n)=>{const r=t[n];return null!=r?String(r):`<${n}?>`}))}(s,n):"Error",a=`${this.serviceName}: ${i} (${r}).`;return new b(r,a,n)}}const x=/\{\$([^}]+)}/g;function E(e){return JSON.parse(e)}const I=function(e){let t={},n={},r={},s="";try{const i=e.split(".");t=E(d(i[0])||""),n=E(d(i[1])||""),s=i[2],r=n.d||{},delete n.d}catch(e){}return{header:t,claims:n,data:r,signature:s}};function _(e){return null!==e&&"object"==typeof e}class T{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 s=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),s}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 A(e,t){return`${e} failed: ${t} argument `}const D=144e5;t.CONSTANTS=r,t.DecodeBase64StringError=l,t.Deferred=v,t.ErrorFactory=S,t.FirebaseError=b,t.MAX_VALUE_MILLIS=D,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,s,i=this.chain_[0],a=this.chain_[1],o=this.chain_[2],l=this.chain_[3],c=this.chain_[4];for(let e=0;e<80;e++){e<40?e<20?(r=l^a&(o^l),s=1518500249):(r=a^o^l,s=1859775393):e<60?(r=a&o|l&(a|o),s=2400959708):(r=a^o^l,s=3395469782);const t=(i<<5|i>>>27)+r+c+s+n[e]&4294967295;c=l,l=o,o=4294967295&(a<<30|a>>>2),a=i,i=t}this.chain_[0]=this.chain_[0]+i&4294967295,this.chain_[1]=this.chain_[1]+a&4294967295,this.chain_[2]=this.chain_[2]+o&4294967295,this.chain_[3]=this.chain_[3]+l&4294967295,this.chain_[4]=this.chain_[4]+c&4294967295}update(e,t){if(null==e)return;void 0===t&&(t=e.length);const n=t-this.blockSize;let r=0;const s=this.buf_;let i=this.inbuf_;for(;r<t;){if(0===i)for(;r<=n;)this.compress_(e,r),r+=this.blockSize;if("string"==typeof e){for(;r<t;)if(s[i]=e.charCodeAt(r),++i,++r,i===this.blockSize){this.compress_(s),i=0;break}}else for(;r<t;)if(s[i]=e[r],++i,++r,i===this.blockSize){this.compress_(s),i=0;break}}this.inbuf_=i,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=s,t.assertionError=i,t.async=function(e,t){return(...n)=>{Promise.resolve(!0).then((()=>{e(...n)})).catch((e=>{t&&t(e)}))}},t.base64=o,t.base64Decode=d,t.base64Encode=c,t.base64urlEncodeWithoutPadding=u,t.calculateBackoffMillis=function(e,t=1e3,n=2){const r=t*Math.pow(n,e),s=Math.round(.5*r*(Math.random()-.5)*2);return Math.min(D,r+s)},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,s=e.sub||e.user_id;if(!s)throw new Error("mockUserToken must contain 'sub' or 'user_id' field!");const i=Object.assign({iss:`https://securetoken.google.com/${n}`,aud:n,iat:r,exp:r+3600,auth_time:r,sub:s,user_id:s,firebase:{sign_in_provider:"custom",identities:{}}},e);return[u(JSON.stringify({alg:"none",type:"JWT"})),u(JSON.stringify(i)),""].join(".")},t.createSubscribe=function(e,t){const n=new T(e,t);return n.subscribe.bind(n)},t.decode=I,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),s=Object.keys(n);for(const i of r){if(!s.includes(i))return!1;const r=t[i],a=n[i];if(_(r)&&_(a)){if(!e(r,a))return!1}else if(r!==a)return!1}for(const e of s)if(!r.includes(e))return!1;return!0},t.deepExtend=h,t.errorPrefix=A,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=f())||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=f,t.getExperimentalSetting=e=>{var t;return null===(t=f())||void 0===t?void 0:t[`_${e}`]},t.getGlobal=p,t.getModularInstance=function(e){return e&&e._delegate?e._delegate:e},t.getUA=g,t.isAdmin=function(e){const t=I(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 g().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=g();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(g())},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 g().indexOf("MSAppHost/")>=0},t.isValidFormat=function(e){const t=I(e).claims;return!!t&&"object"==typeof t&&t.hasOwnProperty("iat")},t.isValidTimestamp=function(e){const t=I(e).claims,n=Math.floor((new Date).getTime()/1e3);let r=0,s=0;return"object"==typeof t&&(t.hasOwnProperty("nbf")?r=t.nbf:t.hasOwnProperty("iat")&&(r=t.iat),s=t.hasOwnProperty("exp")?t.exp:r+86400),!!n&&!!r&&!!s&&n>=r&&n<=s},t.isWebWorker=w,t.issuedAtTime=function(e){const t=I(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 s in e)Object.prototype.hasOwnProperty.call(e,s)&&(r[s]=t.call(n,e[s],s,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 v;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 i=e.charCodeAt(r);if(i>=55296&&i<=56319){const t=i-55296;r++,s(r<e.length,"Surrogate pair missing trail surrogate."),i=65536+(t<<10)+(e.charCodeAt(r)-56320)}i<128?t[n++]=i:i<2048?(t[n++]=i>>6|192,t[n++]=63&i|128):i<65536?(t[n++]=i>>12|224,t[n++]=i>>6&63|128,t[n++]=63&i|128):(t[n++]=i>>18|240,t[n++]=i>>12&63|128,t[n++]=i>>6&63|128,t[n++]=63&i|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 s;if(r<t?s="at least "+t:r>n&&(s=0===n?"none":"no more than "+n),s)throw new Error(e+" failed: Was called with "+r+(1===r?" argument.":" arguments.")+" Expects "+s+".")},t.validateCallback=function(e,t,n,r){if((!r||n)&&"function"!=typeof n)throw new Error(A(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(A(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",s=self.indexedDB.open(r);s.onsuccess=()=>{s.result.close(),n||self.indexedDB.deleteDatabase(r),e(!0)},s.onupgradeneeded=()=>{n=!1},s.onerror=()=>{var e;t((null===(e=s.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(A(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 s=0;16>s;++s)r[s]=t.charCodeAt(n++)|t.charCodeAt(n++)<<8|t.charCodeAt(n++)<<16|t.charCodeAt(n++)<<24;else for(s=0;16>s;++s)r[s]=t[n++]|t[n++]<<8|t[n++]<<16|t[n++]<<24;t=e.g[0],n=e.g[1],s=e.g[2];var i=e.g[3],a=t+(i^n&(s^i))+r[0]+3614090360&4294967295;a=(n=(s=(i=(t=(n=(s=(i=(t=(n=(s=(i=(t=(n=(s=(i=(t=(n=(s=(i=(t=(n=(s=(i=(t=(n=(s=(i=(t=(n=(s=(i=(t=(n=(s=(i=(t=(n=(s=(i=(t=(n=(s=(i=(t=(n=(s=(i=(t=(n=(s=(i=(t=(n=(s=(i=(t=(n=(s=(i=(t=n+(a<<7&4294967295|a>>>25))+((a=i+(s^t&(n^s))+r[1]+3905402710&4294967295)<<12&4294967295|a>>>20))+((a=s+(n^i&(t^n))+r[2]+606105819&4294967295)<<17&4294967295|a>>>15))+((a=n+(t^s&(i^t))+r[3]+3250441966&4294967295)<<22&4294967295|a>>>10))+((a=t+(i^n&(s^i))+r[4]+4118548399&4294967295)<<7&4294967295|a>>>25))+((a=i+(s^t&(n^s))+r[5]+1200080426&4294967295)<<12&4294967295|a>>>20))+((a=s+(n^i&(t^n))+r[6]+2821735955&4294967295)<<17&4294967295|a>>>15))+((a=n+(t^s&(i^t))+r[7]+4249261313&4294967295)<<22&4294967295|a>>>10))+((a=t+(i^n&(s^i))+r[8]+1770035416&4294967295)<<7&4294967295|a>>>25))+((a=i+(s^t&(n^s))+r[9]+2336552879&4294967295)<<12&4294967295|a>>>20))+((a=s+(n^i&(t^n))+r[10]+4294925233&4294967295)<<17&4294967295|a>>>15))+((a=n+(t^s&(i^t))+r[11]+2304563134&4294967295)<<22&4294967295|a>>>10))+((a=t+(i^n&(s^i))+r[12]+1804603682&4294967295)<<7&4294967295|a>>>25))+((a=i+(s^t&(n^s))+r[13]+4254626195&4294967295)<<12&4294967295|a>>>20))+((a=s+(n^i&(t^n))+r[14]+2792965006&4294967295)<<17&4294967295|a>>>15))+((a=n+(t^s&(i^t))+r[15]+1236535329&4294967295)<<22&4294967295|a>>>10))+((a=t+(s^i&(n^s))+r[1]+4129170786&4294967295)<<5&4294967295|a>>>27))+((a=i+(n^s&(t^n))+r[6]+3225465664&4294967295)<<9&4294967295|a>>>23))+((a=s+(t^n&(i^t))+r[11]+643717713&4294967295)<<14&4294967295|a>>>18))+((a=n+(i^t&(s^i))+r[0]+3921069994&4294967295)<<20&4294967295|a>>>12))+((a=t+(s^i&(n^s))+r[5]+3593408605&4294967295)<<5&4294967295|a>>>27))+((a=i+(n^s&(t^n))+r[10]+38016083&4294967295)<<9&4294967295|a>>>23))+((a=s+(t^n&(i^t))+r[15]+3634488961&4294967295)<<14&4294967295|a>>>18))+((a=n+(i^t&(s^i))+r[4]+3889429448&4294967295)<<20&4294967295|a>>>12))+((a=t+(s^i&(n^s))+r[9]+568446438&4294967295)<<5&4294967295|a>>>27))+((a=i+(n^s&(t^n))+r[14]+3275163606&4294967295)<<9&4294967295|a>>>23))+((a=s+(t^n&(i^t))+r[3]+4107603335&4294967295)<<14&4294967295|a>>>18))+((a=n+(i^t&(s^i))+r[8]+1163531501&4294967295)<<20&4294967295|a>>>12))+((a=t+(s^i&(n^s))+r[13]+2850285829&4294967295)<<5&4294967295|a>>>27))+((a=i+(n^s&(t^n))+r[2]+4243563512&4294967295)<<9&4294967295|a>>>23))+((a=s+(t^n&(i^t))+r[7]+1735328473&4294967295)<<14&4294967295|a>>>18))+((a=n+(i^t&(s^i))+r[12]+2368359562&4294967295)<<20&4294967295|a>>>12))+((a=t+(n^s^i)+r[5]+4294588738&4294967295)<<4&4294967295|a>>>28))+((a=i+(t^n^s)+r[8]+2272392833&4294967295)<<11&4294967295|a>>>21))+((a=s+(i^t^n)+r[11]+1839030562&4294967295)<<16&4294967295|a>>>16))+((a=n+(s^i^t)+r[14]+4259657740&4294967295)<<23&4294967295|a>>>9))+((a=t+(n^s^i)+r[1]+2763975236&4294967295)<<4&4294967295|a>>>28))+((a=i+(t^n^s)+r[4]+1272893353&4294967295)<<11&4294967295|a>>>21))+((a=s+(i^t^n)+r[7]+4139469664&4294967295)<<16&4294967295|a>>>16))+((a=n+(s^i^t)+r[10]+3200236656&4294967295)<<23&4294967295|a>>>9))+((a=t+(n^s^i)+r[13]+681279174&4294967295)<<4&4294967295|a>>>28))+((a=i+(t^n^s)+r[0]+3936430074&4294967295)<<11&4294967295|a>>>21))+((a=s+(i^t^n)+r[3]+3572445317&4294967295)<<16&4294967295|a>>>16))+((a=n+(s^i^t)+r[6]+76029189&4294967295)<<23&4294967295|a>>>9))+((a=t+(n^s^i)+r[9]+3654602809&4294967295)<<4&4294967295|a>>>28))+((a=i+(t^n^s)+r[12]+3873151461&4294967295)<<11&4294967295|a>>>21))+((a=s+(i^t^n)+r[15]+530742520&4294967295)<<16&4294967295|a>>>16))+((a=n+(s^i^t)+r[2]+3299628645&4294967295)<<23&4294967295|a>>>9))+((a=t+(s^(n|~i))+r[0]+4096336452&4294967295)<<6&4294967295|a>>>26))+((a=i+(n^(t|~s))+r[7]+1126891415&4294967295)<<10&4294967295|a>>>22))+((a=s+(t^(i|~n))+r[14]+2878612391&4294967295)<<15&4294967295|a>>>17))+((a=n+(i^(s|~t))+r[5]+4237533241&4294967295)<<21&4294967295|a>>>11))+((a=t+(s^(n|~i))+r[12]+1700485571&4294967295)<<6&4294967295|a>>>26))+((a=i+(n^(t|~s))+r[3]+2399980690&4294967295)<<10&4294967295|a>>>22))+((a=s+(t^(i|~n))+r[10]+4293915773&4294967295)<<15&4294967295|a>>>17))+((a=n+(i^(s|~t))+r[1]+2240044497&4294967295)<<21&4294967295|a>>>11))+((a=t+(s^(n|~i))+r[8]+1873313359&4294967295)<<6&4294967295|a>>>26))+((a=i+(n^(t|~s))+r[15]+4264355552&4294967295)<<10&4294967295|a>>>22))+((a=s+(t^(i|~n))+r[6]+2734768916&4294967295)<<15&4294967295|a>>>17))+((a=n+(i^(s|~t))+r[13]+1309151649&4294967295)<<21&4294967295|a>>>11))+((i=(t=n+((a=t+(s^(n|~i))+r[4]+4149444226&4294967295)<<6&4294967295|a>>>26))+((a=i+(n^(t|~s))+r[11]+3174756917&4294967295)<<10&4294967295|a>>>22))^((s=i+((a=s+(t^(i|~n))+r[2]+718787259&4294967295)<<15&4294967295|a>>>17))|~t))+r[9]+3951481745&4294967295,e.g[0]=e.g[0]+t&4294967295,e.g[1]=e.g[1]+(s+(a<<21&4294967295|a>>>11))&4294967295,e.g[2]=e.g[2]+s&4294967295,e.g[3]=e.g[3]+i&4294967295}function s(e,t){this.h=t;for(var n=[],r=!0,s=e.length-1;0<=s;s--){var i=0|e[s];r&&i==t||(n[s]=i,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 s=Array(arguments.length-2),i=2;i<arguments.length;i++)s[i-2]=arguments[i];return t.prototype[n].apply(e,s)}}(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,s=this.B,i=this.h,a=0;a<t;){if(0==i)for(;a<=n;)r(this,e,a),a+=this.blockSize;if("string"==typeof e){for(;a<t;)if(s[i++]=e.charCodeAt(a++),i==this.blockSize){r(this,s),i=0;break}}else for(;a<t;)if(s[i++]=e[a++],i==this.blockSize){r(this,s),i=0;break}}this.h=i,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 i={};function a(e){return-128<=e&&128>e?function(e){var t=i;return Object.prototype.hasOwnProperty.call(t,e)?t[e]:t[e]=function(e){return new s([0|e],0>e?-1:0)}(e)}(e):new s([0|e],0>e?-1:0)}function o(e){if(isNaN(e)||!isFinite(e))return l;if(0>e)return p(o(-e));for(var t=[],n=1,r=0;e>=n;r++)t[r]=e/n|0,n*=4294967296;return new s(t,0)}var l=a(0),c=a(1),u=a(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 p(e){for(var t=e.g.length,n=[],r=0;r<t;r++)n[r]=~e.g[r];return new s(n,~e.h).add(c)}function f(e,t){return e.add(p(t))}function m(e,t){for(;(65535&e[t])!=e[t];)e[t+1]+=e[t]>>>16,e[t]&=65535,t++}function v(e,t){this.g=e,this.h=t}function g(e,t){if(d(t))throw Error("division by zero");if(d(e))return new v(l,l);if(h(e))return t=g(p(e),t),new v(p(t.g),p(t.h));if(h(t))return t=g(e,p(t)),new v(p(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=c,r=t;0>=r.l(e);)n=y(n),r=y(r);var s=w(n,1),i=w(r,1);for(r=w(r,2),n=w(n,2);!d(r);){var a=i.add(r);0>=a.l(e)&&(s=s.add(n),i=a),r=w(r,1),n=w(n,1)}return t=f(e,s.j(t)),new v(s,t)}for(s=l;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),a=(i=o(n)).j(t);h(a)||0<a.l(e);)a=(i=o(n-=r)).j(t);d(i)&&(i=c),s=s.add(i),e=f(e,a)}return new v(s,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 s(n,e.h)}function w(e,t){var n=t>>5;t%=32;for(var r=e.g.length-n,i=[],a=0;a<r;a++)i[a]=0<t?e.i(a+n)>>>t|e.i(a+n+1)<<32-t:e.i(a+n);return new s(i,e.h)}(t=s.prototype).m=function(){if(h(this))return-p(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"-"+p(this).toString(e);for(var t=o(Math.pow(e,6)),n=this,r="";;){var s=g(n,t).g,i=((0<(n=f(n,s.j(t))).g.length?n.g[0]:n.h)>>>0).toString(e);if(d(n=s))return i+r;for(;6>i.length;)i="0"+i;r=i+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=f(this,e))?-1:d(e)?0:1},t.abs=function(){return h(this)?p(this):this},t.add=function(e){for(var t=Math.max(this.g.length,e.g.length),n=[],r=0,i=0;i<=t;i++){var a=r+(65535&this.i(i))+(65535&e.i(i)),o=(a>>>16)+(this.i(i)>>>16)+(e.i(i)>>>16);r=o>>>16,a&=65535,o&=65535,n[i]=o<<16|a}return new s(n,-2147483648&n[n.length-1]?-1:0)},t.j=function(e){if(d(this)||d(e))return l;if(h(this))return h(e)?p(this).j(p(e)):p(p(this).j(e));if(h(e))return p(this.j(p(e)));if(0>this.l(u)&&0>e.l(u))return o(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 i=0;i<e.g.length;i++){var a=this.i(r)>>>16,c=65535&this.i(r),f=e.i(i)>>>16,v=65535&e.i(i);n[2*r+2*i]+=c*v,m(n,2*r+2*i),n[2*r+2*i+1]+=a*v,m(n,2*r+2*i+1),n[2*r+2*i+1]+=c*f,m(n,2*r+2*i+1),n[2*r+2*i+2]+=a*f,m(n,2*r+2*i+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 s(n,0)},t.A=function(e){return g(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 s(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 s(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 s(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,s.prototype.add=s.prototype.add,s.prototype.multiply=s.prototype.j,s.prototype.modulo=s.prototype.A,s.prototype.compare=s.prototype.l,s.prototype.toNumber=s.prototype.m,s.prototype.toString=s.prototype.toString,s.prototype.getBits=s.prototype.i,s.fromNumber=o,s.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 p(e(t.substring(1),n));if(0<=t.indexOf("-"))throw Error('number format error: interior "-" character');for(var r=o(Math.pow(n,8)),s=l,i=0;i<t.length;i+=8){var a=Math.min(8,t.length-i),c=parseInt(t.substring(i,i+a),n);8>a?(a=o(Math.pow(n,a)),s=s.j(a).add(o(c))):s=(s=s.j(r)).add(o(c))}return s},e.exports.Integer=s}).apply(void 0!==n.g?n.g:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},4832:(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},s=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=s;e=e.split(".");for(var i=0;i<e.length-1;i++){var a=e[i];if(!(a in n))break e;n=n[a]}(t=t(i=n[e=e[e.length-1]]))!=i&&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,s={next:function(){if(!r&&n<e.length){var s=n++;return{value:t(0,e[s]),done:!1}}return r=!0,{done:!0,value:void 0}}};return s[Symbol.iterator]=function(){return s},s}(this,(function(e,t){return t}))}}));var i=i||{},a=this||self;function o(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 l(e){var t=typeof e;return"object"==t&&null!=e||"function"==t}function c(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")?c: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 p(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 s=Array(arguments.length-2),i=2;i<arguments.length;i++)s[i-2]=arguments[i];return t.prototype[n].apply(e,s)}}function f(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(o(n)){const t=e.length||0,r=n.length||0;e.length=t+r;for(let s=0;s<r;s++)e[t+s]=n[s]}else e.push(n)}}function v(e){return/^[\s\xa0]*$/.test(e)}function g(){var e=a.navigator;return e&&(e=e.userAgent)?e:""}function y(e){return y[" "](e),e}y[" "]=function(){};var w=!(-1==g().indexOf("Gecko")||-1!=g().toLowerCase().indexOf("webkit")&&-1==g().indexOf("Edge")||-1!=g().indexOf("Trident")||-1!=g().indexOf("MSIE")||-1!=g().indexOf("Edge"));function b(e,t,n){for(const r in e)t.call(n,e[r],r,e)}function S(e){const t={};for(const n in e)t[n]=e[n];return t}const x="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<x.length;t++)n=x[t],Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}}function I(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 _(e){a.setTimeout((()=>{throw e}),0)}function T(){var e=L;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 A),(e=>e.reset()));class A{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 D,k=!1,L=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}},M=()=>{const e=a.Promise.resolve(void 0);D=()=>{e.then(N)}};var N=()=>{for(var e;e=T();){try{e.h.call(e.g)}catch(e){_(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 R(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()()},R.prototype.h=function(){this.defaultPrevented=!0};var V=function(){if(!a.addEventListener||!Object.defineProperty)return!1;var e=!1,t=Object.defineProperty({},"passive",{get:function(){e=!0}});try{const e=()=>{};a.addEventListener("test",e,t),a.removeEventListener("test",e,t)}catch(e){}return e}();function O(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 s=!0;break e}catch(e){}s=!1}s||(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:$[e.pointerType]||"",this.state=e.state,this.i=e,e.defaultPrevented&&O.aa.h.call(this)}}p(O,R);var $={2:"touch",3:"pen",4:"mouse"};O.prototype.h=function(){O.aa.h.call(this);var e=this.i;e.preventDefault?e.preventDefault():e.returnValue=!1};var F="closure_listenable_"+(1e6*Math.random()|0),q=0;function U(e,t,n,r,s){this.listener=e,this.proxy=null,this.src=t,this.type=n,this.capture=!!r,this.ha=s,this.key=++q,this.da=this.fa=!1}function B(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,s=e.g[n],i=Array.prototype.indexOf.call(s,t,void 0);(r=0<=i)&&Array.prototype.splice.call(s,i,1),r&&(B(t),0==e.g[n].length&&(delete e.g[n],e.h--))}}function G(e,t,n,r){for(var s=0;s<e.length;++s){var i=e[s];if(!i.da&&i.listener==t&&i.capture==!!n&&i.ha==r)return s}return-1}j.prototype.add=function(e,t,n,r,s){var i=e.toString();(e=this.g[i])||(e=this.g[i]=[],this.h++);var a=G(e,t,r,s);return-1<a?(t=e[a],n||(t.fa=!1)):((t=new U(t,this.src,i,!!r,s)).fa=n,e.push(t)),t};var K="closure_lm_"+(1e6*Math.random()|0),H={};function Q(e,t,n,r,s){if(r&&r.once)return Y(e,t,n,r,s);if(Array.isArray(t)){for(var i=0;i<t.length;i++)Q(e,t[i],n,r,s);return null}return n=re(n),e&&e[F]?e.K(t,n,l(r)?!!r.capture:!!r,s):W(e,t,n,!1,r,s)}function W(e,t,n,r,s,i){if(!t)throw Error("Invalid event type");var a=l(s)?!!s.capture:!!s,o=te(e);if(o||(e[K]=o=new j(e)),(n=o.add(t,n,r,a,i)).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)V||(s=a),void 0===s&&(s=!1),e.addEventListener(t.toString(),r,s);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 Y(e,t,n,r,s){if(Array.isArray(t)){for(var i=0;i<t.length;i++)Y(e,t[i],n,r,s);return null}return n=re(n),e&&e[F]?e.L(t,n,l(r)?!!r.capture:!!r,s):W(e,t,n,!0,r,s)}function J(e,t,n,r,s){if(Array.isArray(t))for(var i=0;i<t.length;i++)J(e,t[i],n,r,s);else r=l(r)?!!r.capture:!!r,n=re(n),e&&e[F]?(e=e.i,(t=String(t).toString())in e.g&&-1<(n=G(i=e.g[t],n,r,s))&&(B(i[n]),Array.prototype.splice.call(i,n,1),0==i.length&&(delete e.g[t],e.h--))):e&&(e=te(e))&&(t=e.g[t.toString()],e=-1,t&&(e=G(t,n,r,s)),(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[F])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)):B(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 O(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 se(){P.call(this),this.i=new j(this),this.M=this,this.F=null}function ie(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 s=t;E(t=new R(r,e),s)}if(s=!0,n)for(var i=n.length-1;0<=i;i--){var a=t.g=n[i];s=ae(a,r,!0,t)&&s}if(s=ae(a=t.g=e,r,!0,t)&&s,s=ae(a,r,!1,t)&&s,n)for(i=0;i<n.length;i++)s=ae(a=t.g=n[i],r,!1,t)&&s}function ae(e,t,n,r){if(!(t=e.i.g[String(t)]))return!0;t=t.concat();for(var s=!0,i=0;i<t.length;++i){var a=t[i];if(a&&!a.da&&a.capture==n){var o=a.listener,l=a.ha||a.src;a.fa&&z(e.i,a),s=!1!==o.call(l,r)&&s}}return s&&!r.defaultPrevented}function oe(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:a.setTimeout(e,t||0)}function le(e){e.g=oe((()=>{e.g=null,e.i&&(e.i=!1,le(e))}),e.l);const t=e.h;e.h=null,e.m.apply(null,t)}p(se,P),se.prototype[F]=!0,se.prototype.removeEventListener=function(e,t,n,r){J(this,e,t,n,r)},se.prototype.N=function(){if(se.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++)B(n[r]);delete t.g[e],t.h--}}this.F=null},se.prototype.K=function(e,t,n,r){return this.i.add(String(e),t,!1,n,r)},se.prototype.L=function(e,t,n,r){return this.i.add(String(e),t,!0,n,r)};class ce 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:le(this)}N(){super.N(),this.g&&(a.clearTimeout(this.g),this.g=null,this.i=!1,this.h=null)}}function ue(e){P.call(this),this.h=e,this.g={}}p(ue,P);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 pe=a.JSON.stringify,fe=a.JSON.parse,me=class{stringify(e){return a.JSON.stringify(e,void 0)}parse(e){return a.JSON.parse(e,void 0)}};function ve(){}function ge(e){return e.h||(e.h=e.i())}function ye(){}ve.prototype.h=null;var we={OPEN:"a",kb:"b",Ja:"c",wb:"d"};function be(){R.call(this,"d")}function Se(){R.call(this,"c")}p(be,R),p(Se,R);var xe={},Ee=null;function Ie(){return Ee=Ee||new se}function _e(e){R.call(this,xe.La,e)}function Te(e){const t=Ie();ie(t,new _e(t,e))}function Ce(e,t){R.call(this,xe.STAT_EVENT,e),this.stat=t}function Ae(e){const t=Ie();ie(t,new Ce(t,e))}function De(e,t){R.call(this,xe.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 a.setTimeout((function(){e()}),t)}function Le(){this.g=!0}function Me(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 s=r[1];if(Array.isArray(s)&&!(1>s.length)){var i=s[0];if("noop"!=i&&"stop"!=i&&"close"!=i)for(var a=1;a<s.length;a++)s[a]=""}}}return pe(n)}catch(e){return t}}(e,n)+(r?" "+r:"")}))}xe.La="serverreachability",p(_e,R),xe.STAT_EVENT="statevent",p(Ce,R),xe.Ma="timingevent",p(De,R),Le.prototype.xa=function(){this.g=!1},Le.prototype.info=function(){};var Ne,Pe={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 Ve(){}function Oe(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 $e}function $e(){this.i=null,this.g="",this.h=!1}p(Ve,ve),Ve.prototype.g=function(){return new XMLHttpRequest},Ve.prototype.i=function(){return{}},Ne=new Ve;var Fe={},qe={};function Ue(e,t,n){e.L=1,e.v=pt(lt(t)),e.m=n,e.P=!0,Be(e,null)}function Be(e,t){e.F=Date.now(),Ge(e),e.A=lt(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 $e,e.g=mn(e.j,n?t:null,!e.m),0<e.O&&(e.M=new ce(d(e.Y,e,e.g),e.O)),t=e.U,n=e.g,r=e.ca;var s="readystatechange";Array.isArray(s)||(s&&(de[0]=s.toString()),s=de);for(var i=0;i<s.length;i++){var a=Q(n,s[i],r||t.handleEvent,!1,t.h||t);if(!a)break;t.g[a.key]=a}t=e.H?S(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)),Te(1),function(e,t,n,r,s,i){e.info((function(){if(e.g)if(i)for(var a="",o=i.split("&"),l=0;l<o.length;l++){var c=o[l].split("=");if(1<c.length){var u=c[0];c=c[1];var d=u.split("_");a=2<=d.length&&"type"==d[1]?a+(u+"=")+c+"&":a+(u+"=redacted&")}}else a=null;else a=i;return"XMLHTTP REQ ("+r+") [attempt "+s+"]: "+t+"\n"+n+"\n"+a}))}(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?qe:(n=Number(t.substring(n,r)),isNaN(n)?Fe:(r+=1)+n>t.length?qe:(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&&(a.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 Ye(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 s=r;if(0==s[0]){e:if(!n.u){if(n.g){if(!(n.g.F+3e3<e.F))break e;cn(n),Xt(n)}an(n),Ae(18)}}else n.za=s[1],0<n.za-n.T&&37500>s[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)&&cn(n),!v(t))for(s=n.Da.g.parse(t),t=0;t<s.length;t++){let c=s[t];if(n.T=c[0],c=c[1],2==n.G)if("c"==c[0]){n.K=c[1],n.ia=c[2];const t=c[3];null!=t&&(n.la=t,n.j.info("VER="+n.la));const s=c[4];null!=s&&(n.Aa=s,n.j.info("SVER="+n.Aa));const u=c[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 i=r.h;i.g||-1==e.indexOf("spdy")&&-1==e.indexOf("quic")&&-1==e.indexOf("h2")||(i.j=i.l,i.g=new Set,i.h&&(nt(i,i.h),i.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 a=e;if((r=n).qa=fn(r,r.J?r.ia:null,r.W),a.K){rt(r.h,a);var o=a,l=r.L;l&&(o.I=l),o.B&&(He(o),Ge(o)),r.g=a}else sn(r);0<n.i.length&&en(n)}else"stop"!=c[0]&&"close"!=c[0]||hn(n,7);else 3==n.G&&("stop"==c[0]||"close"==c[0]?"stop"==c[0]?hn(n,7):Jt(n):"noop"!=c[0]&&n.l&&n.l.ta(c),n.v=0)}Te(4)}catch(e){}}Oe.prototype.ca=function(e){e=e.target;const t=this.M;t&&3==Ht(e)?t.j():this.Y(e)},Oe.prototype.Y=function(e){try{if(e==this.g)e:{const h=Ht(this.g);var t=this.g.Ba();const p=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||Te(8==t||0>=p?3:2),He(this);var n=this.g.Z();this.X=n;t:if(je(this)){var r=Qt(this.g);e="";var s=r.length,i=4==Ht(this.g);if(!this.h.i){if("undefined"==typeof TextDecoder){We(this),Qe(this);var o="";break t}this.h.i=new a.TextDecoder}for(t=0;t<s;t++)this.h.h=!0,e+=this.h.i.decode(r[t],{stream:!(i&&t==s-1)});r.length=0,this.h.g+=e,this.C=0,o=this.h.g}else o=this.g.oa();if(this.o=200==n,function(e,t,n,r,s,i,a){e.info((function(){return"XMLHTTP RESP ("+r+") [ attempt "+s+"]: "+t+"\n"+n+"\n"+i+" "+a}))}(this.i,this.u,this.A,this.l,this.R,h,n),this.o){if(this.T&&!this.K){t:{if(this.g){var l,c=this.g;if((l=c.g?c.g.getResponseHeader("X-HTTP-Initial-Response"):null)&&!v(l)){var u=l;break t}}u=null}if(!(n=u)){this.o=!1,this.s=3,Ae(12),We(this),Qe(this);break e}Me(this.i,this.l,n,"Initial handshake response via X-HTTP-Initial-Response"),this.K=!0,Ye(this,n)}if(this.P){let e;for(n=!0;!this.J&&this.C<o.length;){if(e=ze(this,o),e==qe){4==h&&(this.s=4,Ae(14),n=!1),Me(this.i,this.l,null,"[Incomplete Response]");break}if(e==Fe){this.s=4,Ae(15),Me(this.i,this.l,o,"[Invalid Chunk]"),n=!1;break}Me(this.i,this.l,e,null),Ye(this,e)}if(je(this)&&0!=this.C&&(this.h.g=this.h.g.slice(this.C),this.C=0),4!=h||0!=o.length||this.h.h||(this.s=1,Ae(16),n=!1),this.o=this.o&&n,n){if(0<o.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: "+o.length),on(d),d.M=!0,Ae(11))}}else Me(this.i,this.l,o,"[Invalid Chunked Response]"),We(this),Qe(this)}else Me(this.i,this.l,o,null),Ye(this,o);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(v(e[r]))continue;var n=I(e[r]);const s=n[0];if("string"!=typeof(n=n[1]))continue;n=n.trim();const i=t[s]||[];t[s]=i,i.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<o.indexOf("Unknown SID")?(this.s=3,Ae(12)):(this.s=0,Ae(13)),We(this),Qe(this)}}}catch(e){}},Oe.prototype.cancel=function(){this.J=!0,We(this)},Oe.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&&(Te(3),Ae(17)),We(this),this.s=2,Qe(this)):Ke(this,this.S-e)};var Je=class{constructor(e,t){this.g=e,this.map=t}};function Xe(e){this.l=e||10,e=a.PerformanceNavigationTiming?0<(e=a.performance.getEntriesByType("navigation")).length&&("hq"==e[0].nextHopProtocol||"h2"==e[0].nextHopProtocol):!!(a.chrome&&a.chrome.loadTimes&&a.chrome.loadTimes()&&a.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 st(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 f(e.i)}function it(e,t){if(e.forEach&&"function"==typeof e.forEach)e.forEach(t,void 0);else if(o(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(o(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(o(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),s=r.length,i=0;i<s;i++)t.call(void 0,r[i],n&&n[i],e)}Xe.prototype.cancel=function(){if(this.i=st(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 at=RegExp("^(?:([^:/?#.]+):)?(?://(?:([^\\\\/?#]*)@)?([^\\\\/?#]*?)(?::([0-9]+))?(?=[\\\\/?#]|$))?([^?#]+)?(?:\\?([^#]*))?(?:#([\\s\\S]*))?$");function ot(e){if(this.g=this.o=this.j="",this.s=null,this.m=this.l="",this.h=!1,e instanceof ot){this.h=e.h,ct(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(at))?(this.h=!1,ct(this,t[1]||"",!0),this.o=ft(t[2]||""),this.g=ft(t[3]||"",!0),ut(this,t[4]),this.l=ft(t[5]||"",!0),dt(this,t[6]||"",!0),this.m=ft(t[7]||"")):(this.h=!1,this.i=new Et(null,this.h))}function lt(e){return new ot(e)}function ct(e,t,n){e.j=n?ft(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&&(It(e),e.i=null,e.g.forEach((function(e,t){var n=t.toLowerCase();t!=n&&(_t(this,t),Ct(this,n,e))}),e)),e.j=t}(e.i,e.h)):(n||(t=mt(t,St)),e.i=new Et(t,e.h))}function ht(e,t,n){e.i.set(t,n)}function pt(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 ft(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,vt),n&&(e=e.replace(/%25([0-9a-fA-F]{2})/g,"%$1")),e):null}function vt(e){return"%"+((e=e.charCodeAt(0))>>4&15).toString(16)+(15&e).toString(16)}ot.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,xt)),e.join("")};var gt,yt=/[#\/\?@]/g,wt=/[#\?:]/g,bt=/[#\?]/g,St=/[#\?@]/g,xt=/#/g;function Et(e,t){this.h=this.g=null,this.i=e||null,this.j=!!t}function It(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("="),s=null;if(0<=r){var i=e[n].substring(0,r);s=e[n].substring(r+1)}else i=e[n];t(i,s?decodeURIComponent(s.replace(/\+/g," ")):"")}}}(e.i,(function(t,n){e.add(decodeURIComponent(t.replace(/\+/g," ")),n)})))}function _t(e,t){It(e),t=At(e,t),e.g.has(t)&&(e.i=null,e.h-=e.g.get(t).length,e.g.delete(t))}function Tt(e,t){return It(e),t=At(e,t),e.g.has(t)}function Ct(e,t,n){_t(e,t),0<n.length&&(e.i=null,e.g.set(At(e,t),f(n)),e.h+=n.length)}function At(e,t){return t=String(t),e.j&&(t=t.toLowerCase()),t}function Dt(e,t,n,r,s){try{s&&(s.onload=null,s.onerror=null,s.onabort=null,s.ontimeout=null),r(n)}catch(e){}}function kt(){this.g=new me}function Lt(e,t,n){const r=n||"";try{it(e,(function(e,n){let s=e;l(e)&&(s=pe(e)),t.push(r+n+"="+encodeURIComponent(s))}))}catch(e){throw t.push(r+"type="+encodeURIComponent("_badmap")),e}}function Mt(e){this.l=e.Ub||null,this.j=e.eb||!1}function Nt(e,t){se.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 Rt(e){e.readyState=4,e.l=null,e.j=null,e.v=null,Vt(e)}function Vt(e){e.onreadystatechange&&e.onreadystatechange.call(e)}function Ot(e){let t="";return b(e,(function(e,n){t+=n,t+=":",t+=e,t+="\r\n"})),t}function $t(e,t,n){e:{for(r in n){var r=!1;break e}r=!0}r||(n=Ot(n),"string"==typeof e?(encodeURIComponent(String(t)),null!=n&&encodeURIComponent(String(n))):ht(e,t,n))}function Ft(e){se.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){It(this),this.i=null,e=At(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){It(this),this.g.forEach((function(n,r){n.forEach((function(n){e.call(t,n,r,this)}),this)}),this)},t.na=function(){It(this);const e=Array.from(this.g.values()),t=Array.from(this.g.keys()),n=[];for(let r=0;r<t.length;r++){const s=e[r];for(let e=0;e<s.length;e++)n.push(t[r])}return n},t.V=function(e){It(this);let t=[];if("string"==typeof e)Tt(this,e)&&(t=t.concat(this.g.get(At(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 It(this),this.i=null,Tt(this,e=At(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 i=encodeURIComponent(String(r)),a=this.V(r);for(r=0;r<a.length;r++){var s=i;""!==a[r]&&(s+="="+encodeURIComponent(String(a[r]))),e.push(s)}}return this.i=e.join("&")},p(Mt,ve),Mt.prototype.g=function(){return new Nt(this.l,this.j)},Mt.prototype.i=(gt={},function(){return gt}),p(Nt,se),(t=Nt.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,Vt(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||a).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,Vt(this)),this.g&&(this.readyState=3,Vt(this),this.g)))if("arraybuffer"===this.responseType)e.arrayBuffer().then(this.Qa.bind(this),this.ga.bind(this));else if(void 0!==a.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?Rt(this):Vt(this),3==this.readyState&&Pt(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(Nt.prototype,"withCredentials",{get:function(){return"include"===this.m},set:function(e){this.m=e?"include":"same-origin"}}),p(Ft,se);var qt=/^https?$/i,Ut=["POST","PUT"];function Bt(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,ie(e,"complete"),ie(e,"error"))}function zt(e){if(e.h&&void 0!==i&&(!e.v[1]||4!=Ht(e)||2!=e.Z()))if(e.u&&4==Ht(e))oe(e.Ea,0,e);else if(ie(e,"readystatechange"),4==Ht(e)){e.h=!1;try{const i=e.Z();e:switch(i){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===i){var s=String(e.D).match(at)[1]||null;!s&&a.self&&a.self.location&&(s=a.self.location.protocol.slice(0,-1)),r=!qt.test(s?s.toLowerCase():"")}n=r}if(n)ie(e,"complete"),ie(e,"success");else{e.m=6;try{var o=2<Ht(e)?e.g.statusText:""}catch(e){o=""}e.l=o+" ["+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||ie(e,"ready");try{n.onreadystatechange=r}catch(e){}}}function Kt(e){e.I&&(a.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 Yt(e){this.Aa=0,this.i=[],this.j=new Le,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 Jt(e){if(Zt(e),3==e.G){var t=e.U++,n=lt(e.I);if(ht(n,"SID",e.K),ht(n,"RID",t),ht(n,"TYPE","terminate"),nn(e,n),(t=new Oe(e,e.j,t)).L=2,t.v=pt(lt(n)),n=!1,a.navigator&&a.navigator.sendBeacon)try{n=a.navigator.sendBeacon(t.v.toString(),"")}catch(e){}!n&&a.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)}pn(e)}function Xt(e){e.g&&(on(e),e.g.cancel(),e.g=null)}function Zt(e){Xt(e),e.u&&(a.clearTimeout(e.u),e.u=null),cn(e),e.h.cancel(),e.s&&("number"==typeof e.s&&a.clearTimeout(e.s),e.s=null)}function en(e){if(!Ze(e.h)&&!e.s){e.s=!0;var t=e.Ga;D||M(),k||(D(),k=!0),L.add(t,e),e.B=0}}function tn(e,t){var n;n=t?t.l:e.U++;const r=lt(e.I);ht(r,"SID",e.K),ht(r,"RID",n),ht(r,"AID",e.T),nn(e,r),e.m&&e.o&&$t(r,e.m,e.o),n=new Oe(e,e.j,n,e.B+1),null===e.m&&(n.H=e.o),t&&(e.i=t.D.concat(e.i)),t=rn(e,n,1e3),n.I=Math.round(.5*e.wa)+Math.round(.5*e.wa*Math.random()),nt(e.h,n),Ue(n,r,t)}function nn(e,t){e.H&&b(e.H,(function(e,n){ht(t,n,e)})),e.l&&it({},(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 s=e.i;let t=-1;for(;;){const e=["count="+n];-1==t?0<n?(t=s[0].g,e.push("ofs="+t)):t=0:e.push("ofs="+t);let i=!0;for(let a=0;a<n;a++){let n=s[a].g;const o=s[a].map;if(n-=t,0>n)t=Math.max(0,s[a].g-100),i=!1;else try{Lt(o,e,"req"+n+"_")}catch(e){r&&r(o)}}if(i){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;D||M(),k||(D(),k=!0),L.add(t,e),e.v=0}}function an(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 on(e){null!=e.A&&(a.clearTimeout(e.A),e.A=null)}function ln(e){e.g=new Oe(e,e.j,"rpc",e.Y),null===e.m&&(e.g.H=e.o),e.g.O=0;var t=lt(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&&$t(t,e.m,e.o),e.L&&(e.g.I=e.L);var n=e.g;e=e.ia,n.L=1,n.v=pt(lt(t)),n.m=null,n.P=!0,Be(n,e)}function cn(e){null!=e.C&&(a.clearTimeout(e.C),e.C=null)}function un(e,t){var n=null;if(e.g==t){cn(e),on(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 s=e.B;ie(r=Ie(),new De(r,n,t,s)),en(e)}else sn(e);else if(3==(s=t.s)||0==s&&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&&an(e)))switch(n&&0<n.length&&(t=e.h,t.i=t.i.concat(n)),s){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 ot(r||"//www.google.com/images/cleardot.gif"),a.location&&"http"==a.location.protocol||ct(r,"https"),pt(r),t?function(e,t){const n=new Le;if(a.Image){const r=new Image;r.onload=h(Dt,n,"TestLoadImage: loaded",!0,t,r),r.onerror=h(Dt,n,"TestLoadImage: error",!1,t,r),r.onabort=h(Dt,n,"TestLoadImage: abort",!1,t,r),r.ontimeout=h(Dt,n,"TestLoadImage: timeout",!1,t,r),a.setTimeout((function(){r.ontimeout&&r.ontimeout()}),1e4),r.src=e}else t(!1)}(r.toString(),n):function(e,t){new Le;const n=new AbortController,r=setTimeout((()=>{n.abort(),Dt(0,0,!1,t)}),1e4);fetch(e,{signal:n.signal}).then((e=>{clearTimeout(r),e.ok?Dt(0,0,!0,t):Dt(0,0,!1,t)})).catch((()=>{clearTimeout(r),Dt(0,0,!1,t)}))}(r.toString(),n)}else Ae(2);e.G=0,e.l&&e.l.sa(t),pn(e),Zt(e)}function pn(e){if(e.G=0,e.ka=[],e.l){const t=st(e.h);0==t.length&&0==e.i.length||(m(e.ka,t),m(e.ka,e.i),e.h.i.length=0,f(e.i),e.i.length=0),e.l.ra()}}function fn(e,t,n){var r=n instanceof ot?lt(n):new ot(n);if(""!=r.g)t&&(r.g=t+"."+r.g),ut(r,r.s);else{var s=a.location;r=s.protocol,t=t?t+"."+s.hostname:s.hostname,s=+s.port;var i=new ot(null);r&&ct(i,r),t&&(i.g=t),s&&ut(i,s),n&&(i.l=n),r=i}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 Ft(new Mt({eb:n})):new Ft(e.pa)).Ha(e.J),t}function vn(){}function gn(){}function yn(e,t){se.call(this),this.g=new Yt(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)&&!v(e)&&(this.g.m=e),this.v=t&&t.supportsCrossDomainXhr||!1,this.u=t&&t.sendRawJson||!1,(t=t&&t.httpSessionIdParam)&&!v(t)&&(this.g.D=t,null!==(e=this.h)&&t in e&&t in(e=this.h)&&delete e[t]),this.j=new Sn(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(){Se.call(this),this.status=1}function Sn(e){this.g=e}(t=Ft.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():Ne.g(),this.v=this.o?ge(this.o):ge(Ne),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 Bt(this,e)}if(e=n||"",n=new Map(this.headers),r)if(Object.getPrototypeOf(r)===Object.prototype)for(var s in r)n.set(s,r[s]);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())),s=a.FormData&&e instanceof a.FormData,!(0<=Array.prototype.indexOf.call(Ut,t,void 0))||r||s||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){Bt(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,ie(this,"complete"),ie(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)),Ft.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)),fe(t)}},t.Ba=function(){return this.m},t.Ka=function(){return"string"==typeof this.l?this.l:String(this.l)},(t=Yt.prototype).la=8,t.G=1,t.connect=function(e,t,n,r){Ae(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=fn(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 s=new Oe(this,this.j,e);let i=this.o;if(this.S&&(i?(i=S(i),E(i,this.S)):i=this.S),null!==this.m||this.O||(s.H=i,i=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,s,t),ht(n=lt(this.I),"RID",e),ht(n,"CVER",22),this.D&&ht(n,"X-HTTP-Session-Id",this.D),nn(this,n),i&&(this.O?t="headers="+encodeURIComponent(String(Ot(i)))+"&"+t:this.m&&$t(n,this.m,i)),nt(this.h,s),this.Ua&&ht(n,"TYPE","init"),this.P?(ht(n,"$req",t),ht(n,"SID","null"),s.T=!0,Ue(s,n,null)):Ue(s,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,ln(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,Ae(10),Xt(this),ln(this))},t.Za=function(){null!=this.C&&(this.C=null,Xt(this),an(this),Ae(19))},t.fb=function(e){e?(this.j.info("Successfully pinged google.com"),Ae(2)):(this.j.info("Failed to ping google.com"),Ae(1))},t.isActive=function(){return!!this.l&&this.l.isActive(this)},(t=vn.prototype).ua=function(){},t.ta=function(){},t.sa=function(){},t.ra=function(){},t.isActive=function(){return!0},t.Na=function(){},gn.prototype.g=function(e,t){return new yn(e,t)},p(yn,se),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(){Jt(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__=pe(e),e=n);t.i.push(new Je(t.Ya++,e)),3==t.G&&en(t)},yn.prototype.N=function(){this.g.l=null,delete this.j,Jt(this.g),delete this.g,yn.aa.N.call(this)},p(wn,be),p(bn,Se),p(Sn,vn),Sn.prototype.ua=function(){ie(this.g,"a")},Sn.prototype.ta=function(e){ie(this.g,new wn(e))},Sn.prototype.sa=function(e){ie(this.g,new bn(e))},Sn.prototype.ra=function(){ie(this.g,"b")},gn.prototype.createWebChannel=gn.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 gn},e.exports.getStatEventTarget=function(){return Ie()},e.exports.Event=xe,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,Re.COMPLETE="complete",e.exports.EventType=Re,ye.EventType=we,we.OPEN="a",we.CLOSE="b",we.ERROR="c",we.MESSAGE="d",se.prototype.listen=se.prototype.K,e.exports.WebChannel=ye,e.exports.FetchXmlHttpFactory=Mt,Ft.prototype.listenOnce=Ft.prototype.L,Ft.prototype.getLastError=Ft.prototype.Ka,Ft.prototype.getLastErrorCode=Ft.prototype.Ba,Ft.prototype.getStatus=Ft.prototype.Z,Ft.prototype.getResponseJson=Ft.prototype.Oa,Ft.prototype.getResponseText=Ft.prototype.oa,Ft.prototype.send=Ft.prototype.ea,Ft.prototype.setWithCredentials=Ft.prototype.Ha,e.exports.XhrIo=Ft}).apply(void 0!==n.g?n.g:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},5577:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(6199);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]}})}))},9815:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(1241);Object.keys(r).forEach((function(e){"default"===e||t.hasOwnProperty(e)||Object.defineProperty(t,e,{enumerable:!0,get:function(){return r[e]}})}))},5619:(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]}})}))},2264:(e,t,n)=>{"use strict";n.r(t)},3846: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){const t=`\n    <div class="calculator-input purchase-price">\n      <div class="header stacked">\n        <div class="title-wrapper">\n          <img src="${i.default}" alt="Purchase Price icon"/>\n          <div class="title">Purchase Price</div>\n        </div>\n        <div class="mortgage-calculator-info">The total purchase price of the property</div>\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" step="10000" 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 stacked">\n        <div class="title-wrapper">\n          <img src="${a.default}" alt="Down Payment icon"/>\n          <div class="title">Down Payment</div>\n        </div>\n        <div class="mortgage-calculator-info">Your initial payment towards the property</div>\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="${o.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="1" max="15" value="6" step="0.1" class="slider">\n        <div class="range-label">\n          <span>1%</span>\n          <span>15%+</span>\n        </div>\n      </div>\n    </div>\n\n    <div class="calculator-input amortization-period">\n      <div class="header stacked">\n        <div class="title-wrapper">\n          <img src="${l.default}" alt="Amortization Period icon"/>\n          <div class="title">Amortization Period</div>\n        </div>\n        <div class="mortgage-calculator-info">The total length of time to pay off your mortgage</div>\n      </div>\n      <div class="dropdown">\n        <div class="dropdown-field">\n          <span>25 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">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 stacked">\n        <div class="title-wrapper">\n          <img src="${u.default}" alt="Term Length icon"/>\n          <div class="title">Term Length</div>\n        </div>\n        <div class="mortgage-calculator-info">The length of your mortgage term</div>\n      </div>\n      <div class="dropdown">\n        <div class="dropdown-field">\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\n    <div class="calculator-input payment-frequency">\n      <div class="header stacked">\n        <div class="title-wrapper">\n          <img src="${d.default}" alt="Payment Frequency icon"/>\n          <div class="title">Payment Frequency</div>\n        </div>\n        <div class="mortgage-calculator-info">How often you make mortgage payments</div>\n      </div>\n      <div class="dropdown">\n        <div class="dropdown-field">\n          <span>Monthly</span>\n          <img class="info-icon" src="${c.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  `,n=`\n    <div class="calculator-input property-taxes">\n      <div class="header stacked">\n        <div class="title-wrapper">\n          <img src="${h.default}" alt="Property Taxes icon"/>\n          <div class="title">Property Taxes</div>\n        </div>\n        <div class="mortgage-calculator-info">Annual property taxes</div>\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" step="2000" 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 stacked">\n        <div class="title-wrapper">\n          <img src="${p.default}" alt="Heating Costs icon"/>\n          <div class="title">Heating Costs</div>\n        </div>\n        <div class="mortgage-calculator-info">Annual heating costs</div>\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" step="100" 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 stacked">\n        <div class="title-wrapper">\n          <img src="${f.default}" alt="Condo Fees icon"/>\n          <div class="title">Condo Fees</div>\n        </div>\n        <div class="mortgage-calculator-info">Monthly condo maintenance fees</div>\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" step="50" 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="${c.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              ${t}\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              ${n}\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 r=document.querySelector(".purchase-price .value-input"),v=document.querySelector(".purchase-price .slider"),g=document.querySelector(".down-payment .value-input"),y=document.querySelector(".down-payment .percentage-value-input"),w=document.querySelector(".down-payment .slider"),b=document.querySelector(".interest-rate .value-input"),S=document.querySelector(".interest-rate .slider"),x=document.querySelector(".term-calculations .principal-slider"),E=document.querySelector(".total-mortgage .amortization-result-slider"),I=document.querySelectorAll(".tab-header"),_=document.querySelectorAll(".tab-content"),T=document.querySelector(".property-taxes .value-input"),C=document.querySelector(".property-taxes .slider"),A=document.querySelector(".heating-costs .value-input"),D=document.querySelector(".heating-costs .slider"),k=document.querySelector(".condo-fees .value-input"),L=document.querySelector(".condo-fees .slider"),M=document.querySelector(".extra-payments .value-input"),N=document.querySelector(".amortization-period .dropdown-field span"),P=document.querySelector(".payment-frequency .dropdown-field span"),R=document.querySelector(".term-length .dropdown-field span"),V=document.querySelector(".extra-payments .dropdown-field span"),O=document.querySelector(".calculator-results .mortgage-payment-wrapper .value"),$=document.querySelector(".calculator-results .mortgage-amount-insurance .mortgage-amount .value"),F=document.querySelector(".calculator-results .mortgage-amount-insurance .mortgage-insurance .value"),q=document.querySelector(".calculator-results .payment-breakdown .principal .value"),U=document.querySelector(".calculator-results .payment-breakdown .interest .value"),B=document.querySelector(".term-calculations .section-wrapper .calculation-row:nth-child(1) .value"),j=document.querySelector(".term-calculations .section-wrapper .calculation-row:nth-child(2) .value"),z=document.querySelector(".term-calculations .section-wrapper .calculation-row:nth-child(3) .value"),G=document.querySelector(".term-calculations .section-wrapper .calculation-row:nth-child(4) .value"),K=document.querySelector(".total-mortgage .section-wrapper .calculation-row:nth-child(1) .value"),H=document.querySelector(".total-mortgage .section-wrapper .calculation-row:nth-child(2) .value"),Q=document.querySelector(".total-mortgage .section-wrapper .calculation-row:nth-child(3) .value"),W=document.querySelector(".term-calculations .section-label span"),Y=document.querySelector(".total-mortgage .section-label span"),J=document.querySelector(".calculator-results .total-mortgage-payment .mortgage-payment-wrapper .value"),X=document.querySelector(".calculator-results .total-mortgage-payment .mortgage-amount-insurance .advanced-mortgage-payment .value"),Z=document.querySelector(".calculator-results .total-mortgage-payment .mortgage-amount-insurance .property-taxes .value"),ee=document.querySelector(".calculator-results .total-mortgage-payment .mortgage-amount-insurance .heating-costs .value"),te=document.querySelector(".calculator-results .total-mortgage-payment .mortgage-amount-insurance .condo-fees .value"),ne=document.querySelector(".calculator-results .extra-payment-impacts .years-saved .value"),re=document.querySelector(".calculator-results .extra-payment-impacts .interest-saved .value"),se=document.querySelector(".calculator-results .mortgage-stress-test .section-wrapper .calculation-row:nth-child(1) .value"),ie=document.querySelector(".calculator-results .mortgage-stress-test .section-wrapper .calculation-row:nth-child(2) .value"),ae=document.querySelector(".calculator-results .mortgage-stress-test .section-wrapper .calculation-row:nth-child(3) .value"),oe=document.querySelectorAll(".fixed-variable-selector .selector"),le=document.querySelectorAll(".extra-payment-selectors .selector"),ce=document.querySelectorAll("[data-tooltip]");function ue(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,s=null==r?void 0:r.querySelector("span");s&&(s.textContent=e.textContent),null===(n=e.parentElement)||void 0===n||n.classList.remove("expanded"),null==r||r.classList.remove("dropdown-expanded"),pe()}))})),document.querySelectorAll(".dropdown-field").forEach((e=>{e.addEventListener("click",(t=>{var n;if(t.stopPropagation(),null===(n=t.target)||void 0===n?void 0:n.closest(".dropdown-expanded"))document.querySelectorAll(".dropdown-opts.expanded").forEach((e=>{var t;null===(t=e.previousElementSibling)||void 0===t||t.classList.remove("dropdown-expanded"),e.classList.remove("expanded")}));else{document.querySelectorAll(".dropdown-field.dropdown-expanded").forEach((e=>{e.classList.remove("dropdown-expanded")})),document.querySelectorAll(".dropdown-opts.expanded").forEach((e=>{e.classList.remove("expanded")}));const t=e.nextElementSibling;null==t||t.classList.toggle("expanded"),(null==t?void 0:t.classList.contains("expanded"))&&t.previousElementSibling&&(t.style.top=`${t.previousElementSibling.clientHeight+5}px`,e.classList.add("dropdown-expanded"))}}))})),document.addEventListener("click",(e=>{e.target.closest(".dropdown")||document.querySelectorAll(".dropdown-opts.expanded").forEach((e=>{var t;null===(t=e.previousElementSibling)||void 0===t||t.classList.remove("dropdown-expanded"),e.classList.remove("expanded")}))})),I.forEach(((e,t)=>{e.addEventListener("click",(()=>{I.forEach((e=>e.classList.remove("active"))),_.forEach((e=>e.classList.remove("active"))),e.classList.add("active"),_[t].classList.add("active"),pe()}))})),oe.forEach(((e,t)=>{e.addEventListener("click",(()=>{oe.forEach((e=>e.classList.remove("active"))),e.classList.add("active"),pe()}))})),le.forEach(((e,t)=>{e.addEventListener("click",(()=>{var t,n,r,s,i,a;le.forEach((e=>e.classList.remove("active"))),e.classList.add("active");const o=null===(n=null===(t=e.parentElement)||void 0===t?void 0:t.parentElement)||void 0===n?void 0:n.nextElementSibling,l=null===(i=null===(s=null===(r=e.parentElement)||void 0===r?void 0:r.parentElement)||void 0===s?void 0:s.nextElementSibling)||void 0===i?void 0:i.nextElementSibling;"none"===(null===(a=e.textContent)||void 0===a?void 0:a.toLowerCase())?(null==o||o.classList.add("disabled"),null==l||l.classList.add("disabled")):(null==o||o.classList.remove("disabled"),null==l||l.classList.remove("disabled")),pe()}))})),ce.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"}))})),v.addEventListener("input",(()=>{const e=v.value.replace(/[^0-9.]/g,"");r.value=e?`$  ${parseInt(e).toLocaleString("en-US")}`:"",r.dataset.previousValue=e,ue(v),de(),pe()})),w.addEventListener("input",(()=>{var e;let t=null===(e=r.dataset.previousValue)||void 0===e?void 0:e.replace(/[^0-9.]/g,"");const n=t?parseInt(t):0,s=w.value.replace(/[^0-9.]/g,"");y.value=s?`${parseInt(s).toLocaleString("en-US")}%`:"",y.dataset.previousValue=s;const i=n&&s?n*(.01*parseInt(s)):0;g.value=`$  ${i.toLocaleString("en-US")}`,g.dataset.previousValue=i.toString(),ue(w),pe()})),S.addEventListener("input",(()=>{const e=S.value.replace(/[^0-9.]/g,"");b.value=e?`${parseFloat(e).toFixed(2)}%`:"",b.dataset.previousValue=e,ue(S),pe()})),C.addEventListener("input",(()=>{const e=C.value.replace(/[^0-9.]/g,"");T.value=e?`$  ${parseInt(e).toLocaleString("en-US")}`:"",T.dataset.previousValue=e,ue(C),pe()})),D.addEventListener("input",(()=>{const e=D.value.replace(/[^0-9.]/g,"");A.value=e?`$  ${parseInt(e).toLocaleString("en-US")}`:"",A.dataset.previousValue=e,ue(D),pe()})),L.addEventListener("input",(()=>{const e=L.value.replace(/[^0-9.]/g,"");k.value=e?`$  ${parseInt(e).toLocaleString("en-US")}`:"",k.dataset.previousValue=e,ue(L),pe()}));const de=()=>{var e,t;let n=null===(e=r.dataset.previousValue)||void 0===e?void 0:e.replace(/[^0-9.]/g,"");const s=n?parseInt(n):0,i=parseInt(null!==(t=g.dataset.previousValue)&&void 0!==t?t:"0")/s*100;w.value=i.toString(),ue(w),y.value=`${i.toLocaleString("en-US")}%`,y.dataset.previousValue=i.toString()},he=(e,t,n)=>{e.addEventListener("change",(e=>{var s,i;const a=e.target;if(a){let e=a.value;e=e.replace(/[^0-9.]/g,"");const o=e?parseInt(e):0;switch(n){case"purchase-price":0<=o?(v.value=o.toString(),ue(v),a.value=`${t}  ${parseInt(e).toLocaleString("en-US")}`,a.dataset.previousValue=e):a.dataset.previousValue&&(a.value=`${t}  ${parseInt(a.dataset.previousValue).toLocaleString("en-US")}`),de();break;case"downpayment":let n=null===(s=r.dataset.previousValue)||void 0===s?void 0:s.replace(/[^0-9.]/g,"");const l=n?parseInt(n):0;if(o<=.4*l){const n=o/l*100;w.value=n.toString(),ue(w),y.value=`${n.toLocaleString("en-US")}%`,y.dataset.previousValue=n.toString(),a.value=`${t}  ${parseInt(e).toLocaleString("en-US")}`,a.dataset.previousValue=e}else a.dataset.previousValue&&(a.value=`${t}  ${a.dataset.previousValue}`);break;case"downpayment-percentage":if(1<=o&&o<=40){w.value=o.toString(),ue(w),a.value=`${e}${t}`,a.dataset.previousValue=e;let n=null===(i=r.dataset.previousValue)||void 0===i?void 0:i.replace(/[^0-9.]/g,"");const s=n?parseInt(n):0,l=s?s*(.01*o):0;g.value=`$  ${l.toLocaleString("en-US")}`,g.dataset.previousValue=l.toString()}else a.dataset.previousValue&&(a.value=`${a.dataset.previousValue}${t}`);break;case"interest-rate":const c=e?parseFloat(e):0;1<=c?(S.value=c.toFixed(2),ue(S),a.value=`${c.toFixed(2)}%`,a.dataset.previousValue=c.toFixed(2)):a.dataset.previousValue&&(a.value=`${parseFloat(a.dataset.previousValue).toFixed(2)}%`);break;case"property-taxes":0<=o?(C.value=o.toString(),ue(C),a.value=`${t}  ${parseInt(e).toLocaleString("en-US")}`,a.dataset.previousValue=e):a.dataset.previousValue&&(a.value=`${t}  ${parseInt(a.dataset.previousValue).toLocaleString("en-US")}`);break;case"heating-costs":0<=o?(D.value=o.toString(),ue(D),a.value=`${t}  ${parseInt(e).toLocaleString("en-US")}`,a.dataset.previousValue=e):a.dataset.previousValue&&(a.value=`${t}  ${parseInt(a.dataset.previousValue).toLocaleString("en-US")}`);break;case"condo-fees":0<=o?(L.value=o.toString(),ue(L),a.value=`${t}  ${parseInt(e).toLocaleString("en-US")}`,a.dataset.previousValue=e):a.dataset.previousValue&&(a.value=`${t}  ${parseInt(a.dataset.previousValue).toLocaleString("en-US")}`);break;case"extra-payments":0<=o?(a.value=`${t}  ${parseInt(e).toLocaleString("en-US")}`,a.dataset.previousValue=e):a.dataset.previousValue&&(a.value=`${t}  ${parseInt(a.dataset.previousValue).toLocaleString("en-US")}`)}pe()}}))},pe=()=>{var e;const t=document.querySelector(".mortgage-calculator .tab-headers .active"),n=document.querySelector(".interest-rate .fixed-variable-selector .active"),i=document.querySelector(".extra-payments .extra-payment-selectors .active"),a=null===(e=t.textContent)||void 0===e?void 0:e.toLowerCase(),o={purchasePrice:r.dataset.previousValue?parseInt(r.dataset.previousValue):0,downPaymentAmount:g.dataset.previousValue?parseInt(g.dataset.previousValue):0,downPaymentPercentage:y.dataset.previousValue?parseInt(y.dataset.previousValue):0,interestRate:b.dataset.previousValue?parseFloat(parseFloat(b.dataset.previousValue).toFixed(2)):0,amortizationPeriod:N.textContent?parseInt(N.textContent.replace(" years","")):5,paymentFrequency:P.textContent?P.textContent.toLowerCase():"monthly",rateType:n.textContent?n.textContent.toLowerCase():"fixed",termLength:R.textContent?parseInt(R.textContent.replace(" years","").replace(" year","")):5,propertyTaxes:T.dataset.previousValue?parseInt(T.dataset.previousValue):0,heatingCosts:A.dataset.previousValue?parseInt(A.dataset.previousValue):0,condoFees:k.dataset.previousValue?parseInt(k.dataset.previousValue):0,extraPaymentType:i.textContent?i.textContent.toLowerCase():"none",extraPaymentAmount:M.dataset.previousValue?parseInt(M.dataset.previousValue):0,extraPaymentFrequency:V.textContent?V.textContent.toLowerCase():"monthly"},l=(0,s.calculateMortgage)(o),c=(0,s.calculateAdvancedResults)(o);"standard"===a?(O.textContent=`$${l.monthlyPayment.toLocaleString()}`,$.textContent=`$${l.mortgageAmount.toLocaleString()}`,F.textContent=`$${l.mortgageInsurance.toLocaleString()}`,q.textContent=`$${l.principal.toLocaleString()}`,U.textContent=`$${l.interest.toLocaleString()}`,B.textContent=`$${l.termPayments.toLocaleString()}`,j.textContent=`$${l.termPrincipalPaid.toLocaleString()}`,z.textContent=`$${l.termInterestPaid.toLocaleString()}`,G.textContent=`$${l.remainingPrincipalAtEndOfTerm.toLocaleString()}`,x.value=Math.round(l.termPrincipalPaid/l.mortgageAmount*100).toString(),ue(x),K.textContent=`$${l.totalMortgagePlusInterest.toLocaleString()}`,H.textContent=`$${l.totalInterestPaid.toLocaleString()}`,Q.textContent=`${l.interestPrincipalRatio}%`,E.value=(100-l.interestPrincipalRatio).toString(),ue(E),W.textContent=R.textContent,Y.textContent=N.textContent):(J.textContent=`$${c.totalMonthlyPayment.toLocaleString()}`,X.textContent=`$${c.mortgagePayment.toLocaleString()}`,Z.textContent=`$${c.propertyTaxesMonthly.toLocaleString()}`,ee.textContent=`$${c.heatingCostsMonthly.toLocaleString()}`,te.textContent=`$${c.condoFeesMonthly.toLocaleString()}`,ne.textContent=`${c.yearsSaved} years`,re.textContent=`$${c.interestSaved.toLocaleString()}`,se.textContent=`${c.qualifyingRate.toFixed(2)}%`,ie.textContent=`$${c.stressTestPayment.toLocaleString()}`,ae.textContent=`$${c.incomeRequired.toLocaleString()}`)};he(r,"$","purchase-price"),ue(v),he(y,"%","downpayment-percentage"),he(g,"$","downpayment"),ue(w),he(b,"%","interest-rate"),ue(S),ue(x),ue(E),he(T,"$","property-taxes"),ue(C),he(A,"$","heating-costs"),ue(D),he(k,"$","condo-fees"),ue(L),he(M,"$","extra-payments"),pe()};const s=n(6185),i=r(n(1450)),a=r(n(790)),o=r(n(636)),l=r(n(6904)),c=r(n(38)),u=r(n(8706)),d=r(n(1490)),h=r(n(2552)),p=r(n(3378)),f=r(n(4800)),m=r(n(9877))},577:(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 s='\n      <div class="cockpit">\n        <div class="header-wrapper">\n            <div class="tab-selectors">\n            ',i=0;for(let e of r)s+=`<div class="tab-selector ${0===i?"selected":""}" data-tab-id="${e.id}">${e.name}</div>`,i++;s+="\n            </div>",i=0;for(let e of r)s+=`\n            <div id="tab-content-${e.id}" class="tab-content ${0===i?"selected":""}">\n                <div class="title">${e.name}</div>\n                <div class="description">${e.description}</div>\n            </div>`,i++;s+='\n        </div>\n        <div class="stats"></div>\n      </div>\n    ',e.innerHTML=s;const a=e.querySelector(".cockpit"),o=e.querySelector(".tab-selectors"),l=(e.querySelector(".header-wrapper"),e.querySelector(".stats")),c=r.filter((e=>"housing-indicators"===e.id))[0];let u="";for(let e of c.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        `;l.innerHTML=u,a.addEventListener("click",(e=>{var t,n;const s=e.target;if(s.closest(".tab-selector")){null===(t=o.querySelector(".selected"))||void 0===t||t.classList.remove("selected"),s.classList.add("selected"),a.querySelectorAll(".tab-content").forEach((e=>{e.classList.remove("selected")})),null===(n=document.getElementById(`tab-content-${s.dataset.tabId}`))||void 0===n||n.classList.add("selected");const e=r.filter((e=>e.id===s.dataset.tabId))[0];let i="";for(let t of e.stats)i+=`\n                    <div class="stat">\n                        <div class="title">${t.title}</div>\n                        <div class="stat-graph">${t.embed_code}</div>\n                    </div>\n                `;l.innerHTML=i}}))}},2186: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.initDebtServiceCalculator=function(e){const t=`\n    <div class="calculator-input mortgage-calculator-input">\n      <div class="header stacked">\n        <div class="title-wrapper">\n          <img src="${a.default}" alt="Mortgage Amount icon"/>\n          <div class="title">Mortgage Amount</div>\n        </div>\n      </div>\n      <div class="input-fields single-field">\n        <div class="input-field load-amount">\n          <div class="field-label">Loan Amount</div>\n          <input type="text" value="$  500,000" data-previous-value="500000" class="value-input">\n          <input type="range" min="0" max="1500000" value="500000" step="10000" class="slider">\n          <div class="range-label">\n            <span>$0</span>\n            <span>$1,500,000+</span>\n          </div>\n        </div>\n      </div>\n      <div class="input-fields half-width-fields">\n        <div class="input-field gross-annual-income">\n          <div class="field-label">Gross Annual Income</div>\n          <input type="text" value="$  150,000" data-previous-value="150000" class="value-input">\n          <input type="range" min="0" max="500000" value="150000" step="10000" class="slider">\n          <div class="range-label">\n            <span>$0</span>\n            <span>$500,000+</span>\n          </div>\n        </div>\n        <div class="input-field monthly-debt-payments">\n          <div class="field-label">Monthly Debt Payments</div>\n          <input type="text" value="$  300" data-previous-value="300" class="value-input">\n          <input type="range" min="0" max="5000" value="300" step="100" class="slider">\n          <div class="range-label">\n            <span>$0</span>\n            <span>$5,000+</span>\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="${u.default}" alt="Home Expenses icon"/>\n          <div class="title">Home Expenses</div>\n        </div>\n        <div class="mortgage-calculator-info">To budget better and calculate a more realistic total monthly cost, enter the additional home expenses here.</div>\n      </div>\n      <div class="input-fields half-width-fields">\n        <div class="input-field home-expense-monthly">\n          <div class="field-label">Property Tax (Monthly)</div>\n          <input type="text" value="$  200" data-previous-value="200" class="value-input">\n        </div>\n        <div class="input-field home-expense-yearly">\n          <div class="field-label">Property Tax (Yearly)</div>\n          <input type="text" value="$  2,400" data-previous-value="2400" class="value-input">\n        </div>\n      </div>\n      <div class="input-fields half-width-fields">\n        <div class="input-field home-expense-condo-fees">\n          <div class="field-label">Condo fees (Monthly)</div>\n          <input type="text" value="$  200" data-previous-value="200" class="value-input">\n        </div>\n        <div class="input-field home-expense-heat">\n          <div class="field-label">Heat (Monthly)</div>\n          <input type="text" value="$  200" data-previous-value="200" class="value-input">\n        </div>\n      </div>\n    </div>\n\n    <div class="calculator-input mortgage-calculator-input debt-service-rate">\n      <div class="header">\n        <div class="title-wrapper">\n          <img src="${c.default}" alt="Rate icon"/>\n          <div class="title">Rate</div>\n        </div>\n        <div class="btn-group-selector">\n          <div class="selector active">Regular</div>\n          <div class="selector">Interest Only</div>\n        </div>\n        <div class="mortgage-calculator-info full-row-width">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 single-field">\n        <div class="dropdown inline compounding">\n          <div class="dropdown-field inline-label">\n            <div class="field-label">Compounding</div>\n            <span>Semi-Annual</span>\n            <img class="info-icon" src="${h.default}" alt="Dropdown icon"/>  \n          </div>\n          <div class="dropdown-opts">\n            <div class="dropdown-opt">Daily</div>\n            <div class="dropdown-opt">Weekly</div>\n            <div class="dropdown-opt">Bi-Weekly</div>\n            <div class="dropdown-opt">Monthly</div>\n            <div class="dropdown-opt">Quarterly</div>\n            <div class="dropdown-opt">Semi-Annual</div>\n          </div>\n        </div>\n      </div>\n      <div class="input-fields">\n        <div class="input-field rate">\n          <div class="field-label">Rate</div>\n          <input type="text" value="6.29%" data-previous-value="6.29" class="value-input">\n          <input type="range" min="0" max="10" value="6.29" step="0.05" class="slider">\n        </div>\n        <div class="dropdown inline rate-term">\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="${h.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="${d.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="5" max="30" value="25" step="1" class="slider">\n          <div class="range-label">\n            <span>5 Year</span>\n            <span>30 Years</span>\n          </div>\n        </div>\n      </div>\n    </div>\n\n    <div class="calculator-input mortgage-calculator-input add-rental-income">\n      <div class="header stacked">\n        <div class="title-toggle-wrapper">\n          <div class="title-wrapper">\n            <img src="${l.default}" alt="Add Rental Income icon"/>\n            <div class="title">Add Rental Income</div>\n          </div>\n          <div class="toggle">\n            <div class="opt off selected" data-value="off"></div>\n            <div class="opt on" data-value="on"></div>\n          </div>\n        </div>\n        <div class="mortgage-calculator-info">If you plan to rent out part of your home, enter the rent amount here to reduce your total monthly cost.</div>\n      </div>\n\n      <div class="input-fields half-width-fields expandable">\n        <div class="input-field add-rental-income-monthly">\n          <div class="field-label">Monthly</div>\n          <input type="text" value="$  200" data-previous-value="200" class="value-input">\n        </div>\n        <div class="input-field add-rental-income-yearly">\n          <div class="field-label">Yearly</div>\n          <input type="text" value="$  2,400" data-previous-value="2400" class="value-input">\n        </div>\n      </div>\n    </div>\n\n    <div class="calculator-input mortgage-calculator-input stress-test-rule">\n      <div class="header">\n        <div class="title-wrapper">\n          <img src="${i.default}" alt="Stress Test Rule icon"/>\n          <div class="title">Stress Test Rule</div>\n        </div>\n        <div class="btn-group-selector">\n          <div class="selector">Contract</div>\n          <div class="selector active">B20</div>\n        </div>\n      </div>\n      <div class="input-fields single-field">\n        <div class="dropdown inline condo-fee-inclusion-rate">\n          <div class="dropdown-field inline-label">\n            <div class="field-label">Condo Fee Inclusion Rate</div>\n            <span>50%</span>\n            <img class="info-icon" src="${h.default}" alt="Dropdown icon"/>  \n          </div>\n          <div class="dropdown-opts">\n            <div class="dropdown-opt">0%</div>\n            <div class="dropdown-opt">50%</div>\n            <div class="dropdown-opt">100%</div>\n          </div>\n        </div>\n      </div>\n    </div>\n\n    <div class="calculator-input mortgage-calculator-input rental-income-rule">\n      <div class="header">\n        <div class="title-wrapper">\n          <img src="${o.default}" alt="Rental Income Rule icon"/>\n          <div class="title">Rental Income Rule</div>\n        </div>\n        <div class="btn-group-selector">\n          <div class="selector">Add Back</div>\n          <div class="selector active">Offset</div>\n        </div>\n      </div>\n      <div class="input-fields single-field">\n        <div class="dropdown inline rental-income-portion">\n          <div class="dropdown-field inline-label">\n            <div class="field-label">Rental Income Portion</div>\n            <span>50%</span>\n            <img class="info-icon" src="${h.default}" alt="Dropdown icon"/>  \n          </div>\n          <div class="dropdown-opts">\n            <div class="dropdown-opt">25%</div>\n            <div class="dropdown-opt">50%</div>\n            <div class="dropdown-opt">75%</div>\n            <div class="dropdown-opt">100%</div>\n          </div>\n        </div>\n      </div>\n    </div>\n  `;e.innerHTML=`\n    <div class="mortgage-calculator">\n        <div class="section-heading">Debt Service Calculator</div>\n        <div class="tab-layout">\n          <div class="tab-content active">\n            <div class="calculator-inputs">\n              ${t}\n            </div>\n            <div class="calculator-results debt-service-calculator-results">\n              \n    <div class="debt-service-ratios">\n      <div class="label">Debt Service Ratios</div>\n      <div class="ratios">\n        <div class="ratio">\n          <div class="value">28.546%</div>\n          <div class="value-label">GDS</div>\n        </div>\n        <div class="ratio">\n          <div class="value">30.946%</div>\n          <div class="value-label">TDS</div>\n        </div>\n      </div>\n      <div class="details">\n        <div class="st-rate">\n          <div class="st-rate-label">Stress Test Rate (<span>CONTRACT</span>)</div>\n          <div class="st-rate-value">6.29%</div>\n        </div>\n        <div class="ratio-tags">\n          <div class="ratio-tag ratio-tag-32">32%/40%</div>\n          <div class="ratio-tag ratio-tag-35">35%/42%</div>\n          <div class="ratio-tag ratio-tag-39">39%/44%</div>\n        </div>\n        <div class="debt-service-details">\n          <div class="service-detail monthly-mortgage">\n            <div class="service-detail-icon"></div>\n            <div class="service-detail-name">Monthly Mortgage</div>\n            <div class="service-detail-value">$2,934.93</div>\n          </div>\n          <div class="service-detail debt-payment">\n            <div class="service-detail-icon"></div>\n            <div class="service-detail-name">Debt Payment</div>\n            <div class="service-detail-value">$300.00</div>\n          </div>\n          <div class="service-detail home-expenses">\n            <div class="service-detail-icon"></div>\n            <div class="service-detail-name">Home Expenses <span>(incl. rental offset)</span></div>\n            <div class="service-detail-value">$1,233.33</div>\n          </div>\n          <div class="service-detail cash-left">\n            <div class="service-detail-icon"></div>\n            <div class="service-detail-name">Cash Left (Gross)</div>\n            <div class="service-detail-value">$8,531.74</div>\n          </div>\n        </div>\n      </div>\n    </div>\n  \n            </div>\n          </div>\n        </div>\n    </div>\n  `;const n=document.querySelector(".load-amount .value-input"),r=document.querySelector(".load-amount .slider"),p=document.querySelector(".gross-annual-income .value-input"),f=document.querySelector(".gross-annual-income .slider"),m=document.querySelector(".monthly-debt-payments .value-input"),v=document.querySelector(".monthly-debt-payments .slider"),g=document.querySelector(".home-expense-monthly .value-input"),y=document.querySelector(".home-expense-yearly .value-input"),w=document.querySelector(".home-expense-condo-fees .value-input"),b=document.querySelector(".home-expense-heat .value-input"),S=document.querySelector(".add-rental-income .expandable"),x=document.querySelector(".add-rental-income-monthly .value-input"),E=document.querySelector(".add-rental-income-yearly .value-input"),I=document.querySelector(".rate .value-input"),_=document.querySelector(".rate .slider"),T=document.querySelector(".compounding .dropdown-field span"),C=document.querySelector(".condo-fee-inclusion-rate .dropdown-field span"),A=document.querySelector(".rental-income-portion .dropdown-field span"),D=document.querySelector(".amortization .value-input"),k=document.querySelector(".amortization .slider"),L=document.querySelector(".debt-service-calculator-results .debt-service-ratios .ratios .ratio:nth-of-type(1) .value"),M=document.querySelector(".debt-service-calculator-results .debt-service-ratios .ratios .ratio:nth-of-type(2) .value"),N=document.querySelector(".debt-service-calculator-results .debt-service-ratios .details .st-rate .st-rate-label span"),P=document.querySelector(".debt-service-calculator-results .debt-service-ratios .details .st-rate .st-rate-value"),R=document.querySelectorAll(".debt-service-calculator-results .debt-service-ratios .details .ratio-tags .ratio-tag"),V=document.querySelector(".debt-service-calculator-results .debt-service-ratios .details .debt-service-details .monthly-mortgage .service-detail-value"),O=document.querySelector(".debt-service-calculator-results .debt-service-ratios .details .debt-service-details .debt-payment .service-detail-value"),$=document.querySelector(".debt-service-calculator-results .debt-service-ratios .details .debt-service-details .home-expenses .service-detail-name span"),F=document.querySelector(".debt-service-calculator-results .debt-service-ratios .details .debt-service-details .home-expenses .service-detail-value"),q=document.querySelector(".debt-service-calculator-results .debt-service-ratios .details .debt-service-details .cash-left .service-detail-value"),U=document.querySelectorAll(".debt-service-rate .btn-group-selector .selector"),B=document.querySelectorAll(".stress-test-rule .btn-group-selector .selector"),j=document.querySelectorAll(".rental-income-rule .btn-group-selector .selector"),z=document.querySelectorAll(".add-rental-income .opt"),G=document.querySelectorAll("[data-tooltip]");function K(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,s=null==r?void 0:r.querySelector("span");s&&(s.textContent=e.textContent),null===(n=e.parentElement)||void 0===n||n.classList.remove("expanded"),null==r||r.classList.remove("dropdown-expanded"),Y()}))})),document.querySelectorAll(".dropdown-field").forEach((e=>{e.addEventListener("click",(t=>{var n;if(t.stopPropagation(),null===(n=t.target)||void 0===n?void 0:n.closest(".dropdown-expanded"))document.querySelectorAll(".dropdown-opts.expanded").forEach((e=>{var t;null===(t=e.previousElementSibling)||void 0===t||t.classList.remove("dropdown-expanded"),e.classList.remove("expanded")}));else{document.querySelectorAll(".dropdown-field.dropdown-expanded").forEach((e=>{e.classList.remove("dropdown-expanded")})),document.querySelectorAll(".dropdown-opts.expanded").forEach((e=>{e.classList.remove("expanded")}));const t=e.nextElementSibling;null==t||t.classList.toggle("expanded"),(null==t?void 0:t.classList.contains("expanded"))&&t.previousElementSibling&&(t.style.top=`${t.previousElementSibling.clientHeight+5}px`,e.classList.add("dropdown-expanded"))}}))})),document.addEventListener("click",(e=>{e.target.closest(".dropdown")||document.querySelectorAll(".dropdown-opts.expanded").forEach((e=>{var t;null===(t=e.previousElementSibling)||void 0===t||t.classList.remove("dropdown-expanded"),e.classList.remove("expanded")}))})),U.forEach(((e,t)=>{e.addEventListener("click",(()=>{U.forEach((e=>e.classList.remove("active"))),e.classList.add("active"),Y()}))})),B.forEach(((e,t)=>{e.addEventListener("click",(()=>{B.forEach((e=>e.classList.remove("active"))),e.classList.add("active"),Y()}))})),j.forEach(((e,t)=>{e.addEventListener("click",(()=>{j.forEach((e=>e.classList.remove("active"))),e.classList.add("active"),Y()}))})),z.forEach(((e,t)=>{e.addEventListener("click",(()=>{var t,n,r,s,i,a,o,l,c,u,d,h;const p="off"===(null===(n=null===(t=document.querySelector(".title-toggle-wrapper .toggle .selected"))||void 0===t?void 0:t.dataset)||void 0===n?void 0:n.value)?"on":"off";z.forEach((e=>e.classList.remove("selected"))),"on"===p?document.querySelector(".title-toggle-wrapper .toggle .on").classList.add("selected"):document.querySelector(".title-toggle-wrapper .toggle .off").classList.add("selected"),null===(r=e.parentElement)||void 0===r||r.classList.remove("switched-on"),null===(o=null===(a=null===(i=null===(s=e.parentElement)||void 0===s?void 0:s.parentElement)||void 0===i?void 0:i.parentElement)||void 0===a?void 0:a.nextElementSibling)||void 0===o||o.classList.remove("expanded"),"on"===p?(null===(l=e.parentElement)||void 0===l||l.classList.add("switched-on"),null===(h=null===(d=null===(u=null===(c=e.parentElement)||void 0===c?void 0:c.parentElement)||void 0===u?void 0:u.parentElement)||void 0===d?void 0:d.nextElementSibling)||void 0===h||h.classList.add("expanded")):(x.value="$  0",x.dataset.previousValue="0",E.value="$  0",E.dataset.previousValue="0"),Y()}))})),R.forEach((e=>{e.addEventListener("click",(e=>{var t,i;const a=e.target;let o=32;a.classList.contains("ratio-tag-35")?o=35:a.classList.contains("ratio-tag-39")&&(o=39);const l=n.dataset.previousValue?parseInt(n.dataset.previousValue):0,c=p.dataset.previousValue?parseInt(p.dataset.previousValue):0,u=m.dataset.previousValue?parseInt(m.dataset.previousValue):0,d=g.dataset.previousValue?parseFloat(parseFloat(g.dataset.previousValue).toFixed(2)):0,h=w.dataset.previousValue?parseInt(w.dataset.previousValue):0,f=b.dataset.previousValue?parseInt(b.dataset.previousValue):0,v=I.dataset.previousValue?parseFloat(parseFloat(I.dataset.previousValue).toFixed(2)):0,y=D.dataset.previousValue?parseInt(D.dataset.previousValue):5,E=x.dataset.previousValue?parseInt(x.dataset.previousValue):0,_=T.textContent?T.textContent.toLowerCase():"semi-annual",C=document.querySelector(".stress-test-rule .btn-group-selector .active"),A=document.querySelector(".rental-income-rule .btn-group-selector .active"),k=(null===(t=C.textContent)||void 0===t?void 0:t.toLowerCase())||"contract",L=Q(k)?k:"contract",M=(null===(i=A.textContent)||void 0===i?void 0:i.toLowerCase().replace(" ","-"))||"offset",N=W(M)?M:"offset",P={mortgageAmount:l,grossAnnualIncome:c,monthlyDebtPayments:u,propertyTaxMonthly:d,condoFees:h,heatingCost:f,interestRate:v,amortizationYears:y,isRentalIncomeEnabled:S.classList.contains("expanded"),rentalIncomeMonthly:E},R=(0,s.calculateIdealMortgageAmount)(o,P,_,50,50,L,N);if(R>0&&R<=15e5){const e=Math.round(R);r.value=e.toString(),n.value=e?`$  ${e.toLocaleString("en-US")}`:"",n.dataset.previousValue=e.toString(),K(r),Y()}}))})),G.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"}))})),r.addEventListener("input",(()=>{const e=r.value.replace(/[^0-9.]/g,"");n.value=e?`$  ${parseInt(e).toLocaleString("en-US")}`:"",n.dataset.previousValue=e,K(r),Y()})),f.addEventListener("input",(()=>{const e=f.value.replace(/[^0-9.]/g,"");p.value=e?`$  ${parseInt(e).toLocaleString("en-US")}`:"",p.dataset.previousValue=e,K(f),Y()})),v.addEventListener("input",(()=>{const e=v.value.replace(/[^0-9.]/g,"");m.value=e?`$  ${parseInt(e).toLocaleString("en-US")}`:"",m.dataset.previousValue=e,K(v),Y()})),_.addEventListener("input",(()=>{const e=_.value.replace(/[^0-9.]/g,"");I.value=e?`${parseFloat(e).toFixed(2)}%`:"",I.dataset.previousValue=e,K(_),Y()})),k.addEventListener("input",(()=>{const e=k.value.replace(/[^0-9.]/g,"");D.value=e?`${parseInt(e).toLocaleString("en-US")} Years`:"",D.dataset.previousValue=e,K(k),Y()}));const H=(e,t,n)=>{e.addEventListener("change",(e=>{const s=e.target;if(s){let e=s.value;e=e.replace(/[^0-9.]/g,"");const i=e?parseInt(e):0;switch(n){case"loan-amount":0<=i?(r.value=i.toString(),K(r),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"gross-annual-income":0<=i?(f.value=i.toString(),K(f),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"monthly-debt-payments":0<=i?(v.value=i.toString(),K(v),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"home-expense-monthly":case"home-expense-yearly":case"home-expense-condo-fees":case"home-expense-heat":case"add-rental-income-monthly":case"add-rental-income-yearly":if(0<=i?(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")}`),"home-expense-monthly"===n){const e=s.dataset.previousValue,n=12*(e?parseInt(e):0);y.value=`${t} ${n.toLocaleString("en-US")}`,y.dataset.previousValue=n.toString()}else if("home-expense-yearly"===n){const e=s.dataset.previousValue,n=(e?parseInt(e):0)/12;g.value=`${t} ${n.toLocaleString("en-US")}`,g.dataset.previousValue=n.toString()}else if("add-rental-income-monthly"===n){const e=s.dataset.previousValue,n=12*(e?parseInt(e):0);E.value=`${t} ${n.toLocaleString("en-US")}`,E.dataset.previousValue=n.toString()}else if("add-rental-income-yearly"===n){const e=s.dataset.previousValue,n=(e?parseInt(e):0)/12;x.value=`${t} ${n.toLocaleString("en-US")}`,x.dataset.previousValue=n.toString()}break;case"interest-rate":const a=e?parseFloat(e):0;.1<=a&&a<=10?(_.value=a.toFixed(2),K(_),s.value=`${a.toFixed(2)}%`,s.dataset.previousValue=a.toFixed(2)):s.dataset.previousValue&&(s.value=`${parseFloat(s.dataset.previousValue).toFixed(2)}%`);break;case"amortization-period":5<=i&&i<=30?(k.value=i.toString(),K(k),s.value=`${parseInt(e).toLocaleString("en-US")} ${t}`,s.dataset.previousValue=e):s.dataset.previousValue&&(s.value=`${parseInt(s.dataset.previousValue).toLocaleString("en-US")} ${t}`)}Y()}}))};function Q(e){return"contract"===e||"b20"===e}function W(e){return"offset"===e||"add-back"===e}const Y=()=>{var e,t;const r=n.dataset.previousValue?parseInt(n.dataset.previousValue):0,i=p.dataset.previousValue?parseInt(p.dataset.previousValue):0,a=m.dataset.previousValue?parseInt(m.dataset.previousValue):0,o=g.dataset.previousValue?parseFloat(parseFloat(g.dataset.previousValue).toFixed(2)):0,l=w.dataset.previousValue?parseInt(w.dataset.previousValue):0,c=b.dataset.previousValue?parseInt(b.dataset.previousValue):0,u=I.dataset.previousValue?parseFloat(parseFloat(I.dataset.previousValue).toFixed(2)):0,d=D.dataset.previousValue?parseInt(D.dataset.previousValue):5,h=x.dataset.previousValue?parseInt(x.dataset.previousValue):0,f=T.textContent?T.textContent.toLowerCase():"semi-annual",v=C.textContent?parseInt(C.textContent.replace("%","")):50,y=A.textContent?parseInt(A.textContent.replace("%","")):50,E=document.querySelector(".stress-test-rule .btn-group-selector .active"),_=document.querySelector(".rental-income-rule .btn-group-selector .active"),k=(null===(e=E.textContent)||void 0===e?void 0:e.toLowerCase())||"contract",R=Q(k)?k:"contract",U=(null===(t=_.textContent)||void 0===t?void 0:t.toLowerCase().replace(" ","-"))||"offset",B=W(U)?U:"offset",j={mortgageAmount:r,grossAnnualIncome:i,monthlyDebtPayments:a,propertyTaxMonthly:o,condoFees:l,heatingCost:c,interestRate:u,amortizationYears:d,isRentalIncomeEnabled:S.classList.contains("expanded"),rentalIncomeMonthly:h},z=(0,s.calculateAllRatios)(j,f,5.25,v,y,R,B);L.textContent="b20"===R?`${z.stressTestGDS.toFixed(3)}%`:`${z.gdsRatio.toFixed(3)}%`,M.textContent="b20"===R?`${z.stressTestTDS.toFixed(3)}%`:`${z.tdsRatio.toFixed(3)}%`,N.textContent=R.toUpperCase(),P.textContent=`${z.stressTestRate.toFixed(2)}%`,V.textContent=(0,s.formatCurrencyDetailed)(z.monthlyMortgagePayment),O.textContent=(0,s.formatCurrencyDetailed)(j.monthlyDebtPayments),$.style.display="offset"===B.toLowerCase()?"unset":"none",F.textContent=(0,s.formatCurrencyDetailed)(z.monthlyHomeExpenses),q.textContent=(0,s.formatCurrencyDetailed)(z.cashLeftGross)};H(n,"$","loan-amount"),K(r),H(p,"$","gross-annual-income"),K(f),H(m,"$","monthly-debt-payments"),K(v),H(g,"$","home-expense-monthly"),H(y,"$","home-expense-yearly"),H(w,"$","home-expense-condo-fees"),H(b,"$","home-expense-heat"),H(x,"$","add-rental-income-monthly"),H(E,"$","add-rental-income-yearly"),H(I,"%","interest-rate"),K(_),H(D,"Years","amortization-period"),K(k),Y()};const s=n(4250),i=r(n(9875)),a=r(n(1804)),o=r(n(2950)),l=r(n(1341)),c=r(n(6421)),u=r(n(3725)),d=r(n(5858)),h=r(n(38))},8260:function(e,t,n){"use strict";var r=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(s,i){function a(e){try{l(r.next(e))}catch(e){i(e)}}function o(e){try{l(r.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(a,o)}l((r=r.apply(e,t||[])).next())}))},s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.initEducationalVideos=function(e){e.innerHTML='\n      <div class="educational-videos">\n        <div class="section-heading">Educational Videos</div>\n        <div class="filters">\n            <div class="filter selected">All Videos</div>\n            <div class="filter">First time home buyers in Canada</div>\n            <div class="filter">Mortgage Fundamentals</div>\n            <div class="filter">Renewal</div>\n            <div class="filter">Mortgage Repayment</div>\n        </div>\n        <div class="videos"></div>\n        <div id="video-player" class="modal" style="display: none;">\n            <div class="modal-content">\n                <span class="close">&times;</span>\n                <iframe id="video-frame" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>\n            </div>\n        </div>\n      </div>\n    ';const t=e.querySelector(".educational-videos"),n=e.querySelector(".section-heading"),s=e.querySelector(".filters"),i=e.querySelector(".videos");if(!t||!n||!i)return;p(e);let a=!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(!a&&o&&t){a=!0;try{const t=yield p(e);o=t}catch(e){console.error("Error loading educational videos:",e)}finally{a=!1}}}))))),s.addEventListener("click",(t=>{const n=t.target;if(n.closest(".filter")){s.querySelectorAll(".filter").forEach((e=>{e.classList.remove("selected")})),n.classList.add("selected");const t="All Videos"===n.textContent?"":n.textContent;h=t||"",d=null,i.innerHTML="",p(e)}}))};const i=n(9487),a=n(9815),o=s(n(757)),l=n(6185),c="educational_videos",u=9;let d=null,h="";function p(e){return r(this,void 0,void 0,(function*(){const t=e.querySelector(".videos");if(!t)return!1;try{const e=yield(0,i.getFirestoreInstance)();let n=(0,a.query)((0,a.collection)(e,c),(0,a.orderBy)("date","desc"),(0,a.limit)(u));h&&(n=(0,a.query)(n,(0,a.where)("category","==",h))),d&&(n=(0,a.query)(n,(0,a.startAfter)(d)));const r=yield(0,a.getDocs)(n);return r.empty?(console.log("No more videos to load"),!1):(r.forEach((e=>{var n,r,s;const i=e.data(),a=document.createElement("div");a.classList.add("video"),a.setAttribute("data-video-url",i.video_link),a.innerHTML=`\n                <div class="thumbnail" style="background-image: url('${i.img_link}');">\n                    <div class="thumbnail-overlay" style="">\n                        <div class="play-icon">\n                            <img src="${o.default}" alt="Play Video" />\n                        </div>\n                    </div>\n                </div>\n                <div class="date">${(0,l.formatDate)(null===(n=i.date)||void 0===n?void 0:n.trim())}</div>\n                <div class="title">${null===(r=i.headline)||void 0===r?void 0:r.trim()}</div>\n                <div class="source">Source: <span>${null===(s=i.source)||void 0===s?void 0:s.trim()}</span></div>\n            `,t.appendChild(a)})),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}}))}},3987:function(e,t,n){"use strict";var r=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(s,i){function a(e){try{l(r.next(e))}catch(e){i(e)}}function o(e){try{l(r.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(a,o)}l((r=r.apply(e,t||[])).next())}))},s=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="filters">\n            <div class="filter selected">All</div>\n            <div class="filter">Basic</div>\n            <div class="filter">First time home buyer</div>\n            <div class="filter">HELOC</div>\n            <div class="filter">Refinance</div>\n            <div class="filter">Renewal</div>\n        </div>\n        <div class="faq-list"></div>\n      </div>\n    ';const t=e.querySelector(".faqs"),n=e.querySelector(".section-heading"),r=e.querySelector(".filters"),s=e.querySelector(".faq-list");t&&n&&s&&(u(e),r.addEventListener("click",(t=>{const n=t.target;if(n.closest(".filter")){r.querySelectorAll(".filter").forEach((e=>{e.classList.remove("selected")})),n.classList.add("selected");const t="All"===n.textContent?"":n.textContent;c=t||"",s.innerHTML="",u(e)}})))};const i=n(9487),a=n(9815),o=s(n(9573)),l="faqs";let c="";function u(e){return r(this,void 0,void 0,(function*(){const t=e.querySelector(".faq-list");if(t)try{const e=yield(0,i.getFirestoreInstance)();let n=(0,a.query)((0,a.collection)(e,l),(0,a.orderBy)("question","asc"));c&&(n=(0,a.query)(n,(0,a.where)("category","==",c)));const r=yield(0,a.getDocs)(n);if(r.empty)return void console.log("No FAQs available");r.forEach((e=>{var n,r;const s=e.data();console.log("faqData - ",s);const i=document.createElement("div");i.classList.add("faq"),i.innerHTML=`\n                <div class="content-wrapper">\n                    <div class="question">${null===(n=s.question)||void 0===n?void 0:n.trim()}</div>\n                    <div class="answer">${null===(r=s.answer)||void 0===r?void 0:r.trim()}</div>\n                </div>\n                <div class="expand-collapse-wrapper">\n                    <img src="${o.default}" alt="Expand/Collapse" />\n                </div>\n            `,t.appendChild(i)})),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)}}))}},9487:function(e,t,n){"use strict";var r=this&&this.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n);var s=Object.getOwnPropertyDescriptor(t,n);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,s)}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),i=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 s(t,e),t},a=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(s,i){function a(e){try{l(r.next(e))}catch(e){i(e)}}function o(e){try{l(r.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(a,o)}l((r=r.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.getFirestoreInstance=function(){return a(this,void 0,void 0,(function*(){if(!c){const{getFirestore:e}=yield Promise.resolve().then((()=>i(n(9815)))),t=(0,o.initializeApp)(l);c=e(t)}return c}))},t.getFirebaseFunctions=function(){return a(this,void 0,void 0,(function*(){if(!u){const{getFunctions:e}=yield Promise.resolve().then((()=>i(n(5619)))),t=(0,o.initializeApp)(l);u=e(t)}return u}))};const o=n(5577),l={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 c=null,u=null},6536:function(e,t,n){"use strict";var r=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(s,i){function a(e){try{l(r.next(e))}catch(e){i(e)}}function o(e){try{l(r.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(a,o)}l((r=r.apply(e,t||[])).next())}))},s=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="${o.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"),s=e.querySelector(".free-guides-form .fields"),l=e.querySelector(".free-guides-form .consent-wrapper"),c=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"),p=()=>r(this,void 0,void 0,(function*(){const e=c.value,t=u.value;e&&t&&f(t)?h.classList.remove("disabled"):h.classList.add("disabled")})),f=e=>/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(e);c.addEventListener("change",(e=>{p()})),u.addEventListener("change",(e=>{p()})),d.addEventListener("change",(e=>{p()})),h.addEventListener("click",(e=>r(this,void 0,void 0,(function*(){const e=c.value.trim(),t=u.value.trim(),r=d.checked;try{h.textContent="Processing...",h.disabled=!0,h.classList.toggle("disabled");const o=yield(0,a.getFirebaseFunctions)(),c=(0,i.httpsCallable)(o,"sendGuideEmail"),u=(yield c({name:e,email:t,consent:r,file:"test-1.pdf"})).data;if(u.success){s.remove(),l.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 i=n(5619),a=n(9487),o=s(n(3765))},6137:function(e,t,n){"use strict";var r=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(s,i){function a(e){try{l(r.next(e))}catch(e){i(e)}}function o(e){try{l(r.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(a,o)}l((r=r.apply(e,t||[])).next())}))},s=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="filters">\n            <div class="filter selected">All Videos</div>\n            <div class="filter">First time home buyer</div>\n            <div class="filter">General</div>\n            <div class="filter">HELOC</div>\n            <div class="filter">Renewal</div>\n        </div>\n        <div class="videos"></div>\n        <div id="video-player" class="modal" style="display: none;">\n            <div class="modal-content">\n                <span class="close">&times;</span>\n                <iframe id="video-frame" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>\n            </div>\n        </div>\n      </div>\n    ';const t=e.querySelector(".market-trend-videos"),n=e.querySelector(".section-heading"),s=e.querySelector(".filters"),i=e.querySelector(".videos");if(!t||!n||!i)return;p(e);let a=!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(!a&&o&&t){a=!0;try{const t=yield p(e);o=t}catch(e){console.error("Error loading market trend videos:",e)}finally{a=!1}}}))))),s.addEventListener("click",(t=>{const n=t.target;if(n.closest(".filter")){s.querySelectorAll(".filter").forEach((e=>{e.classList.remove("selected")})),n.classList.add("selected");const t="All Videos"===n.textContent?"":n.textContent;h=t||"",d=null,i.innerHTML="",p(e)}}))};const i=n(9487),a=n(9815),o=s(n(757)),l=n(6185),c="market_trend_videos",u=9;let d=null,h="";function p(e){return r(this,void 0,void 0,(function*(){const t=e.querySelector(".videos");if(!t)return!1;try{const e=yield(0,i.getFirestoreInstance)();let n=(0,a.query)((0,a.collection)(e,c),(0,a.orderBy)("date","desc"),(0,a.limit)(u));h&&(n=(0,a.query)(n,(0,a.where)("category","==",h))),d&&(n=(0,a.query)(n,(0,a.startAfter)(d)));const r=yield(0,a.getDocs)(n);return r.empty?(console.log("No more videos to load"),!1):(r.forEach((e=>{var n,r,s;const i=e.data(),a=document.createElement("div");a.classList.add("video"),a.setAttribute("data-video-url",i.video_link),a.innerHTML=`\n                <div class="thumbnail" style="background-image: url('${i.img_link}');">\n                    <div class="thumbnail-overlay" style="">\n                        <div class="play-icon">\n                            <img src="${o.default}" alt="Play Video" />\n                        </div>\n                    </div>\n                </div>\n                <div class="date">${(0,l.formatDate)(null===(n=i.date)||void 0===n?void 0:n.trim())}</div>\n                <div class="title">${null===(r=i.headline)||void 0===r?void 0:r.trim()}</div>\n                <div class="source">Source: <span>${null===(s=i.source)||void 0===s?void 0:s.trim()}</span></div>\n            `,t.appendChild(a)})),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}}))}},4526: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.initMaxMortgageCalculator=function(e){const t=`\n    <div class="calculator-input mortgage-calculator-input">\n      <div class="header stacked">\n        <div class="title-wrapper">\n          <img src="${a.default}" alt="Maximum Mortgage icon"/>\n          <div class="title">Maximum Mortgage</div>\n        </div>\n      </div>\n      <div class="input-fields single-field">\n        <div class="input-field gross-annual-income">\n          <div class="field-label">Gross Annual Income</div>\n          <input type="text" value="$  150,000" data-previous-value="150000" class="value-input">\n          <input type="range" min="0" max="500000" value="150000" step="10000" class="slider">\n          <div class="range-label">\n            <span>$0</span>\n            <span>$500,000+</span>\n          </div>\n        </div>\n      </div>\n      <div class="input-fields single-field">\n        <div class="input-field monthly-debt-payments">\n          <div class="field-label">Monthly Debt Payments</div>\n          <input type="text" value="$  300" data-previous-value="300" class="value-input">\n          <input type="range" min="0" max="5000" value="300" step="100" class="slider">\n          <div class="range-label">\n            <span>$0</span>\n            <span>$5,000+</span>\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="${u.default}" alt="Home Expenses icon"/>\n          <div class="title">Home Expenses</div>\n        </div>\n        <div class="mortgage-calculator-info">To budget better and calculate a more realistic total monthly cost, enter the additional home expenses here.</div>\n      </div>\n      <div class="input-fields half-width-fields">\n        <div class="input-field home-expense-monthly">\n          <div class="field-label">Property Tax (Monthly)</div>\n          <input type="text" value="$  200" data-previous-value="200" class="value-input">\n        </div>\n        <div class="input-field home-expense-yearly">\n          <div class="field-label">Property Tax (Yearly)</div>\n          <input type="text" value="$  2,400" data-previous-value="2400" class="value-input">\n        </div>\n      </div>\n      <div class="input-fields half-width-fields">\n        <div class="input-field home-expense-condo-fees">\n          <div class="field-label">Condo fees (Monthly)</div>\n          <input type="text" value="$  200" data-previous-value="200" class="value-input">\n          <input type="range" min="0" max="2000" value="200" step="100" class="slider">\n          <div class="range-label">\n            <span>$0</span>\n            <span>$2,000+</span>\n          </div>\n        </div>\n        <div class="input-field home-expense-heat">\n          <div class="field-label">Heat (Monthly)</div>\n          <input type="text" value="$  200" data-previous-value="200" class="value-input">\n          <input type="range" min="0" max="300" value="200" step="10" class="slider">\n          <div class="range-label">\n            <span>$0</span>\n            <span>$300+</span>\n          </div>\n        </div>\n      </div>\n    </div>\n\n    <div class="calculator-input mortgage-calculator-input affordability-level">\n      <div class="header">\n        <div class="title-wrapper">\n          <img src="${c.default}" alt="Affordability Level icon"/>\n          <div class="title">Affordability Level</div>\n        </div>\n        <div class="mortgage-calculator-info full-row-width">This affordability slider helps you decides how much of your disposable income is allocated to mortgage payments, home expenses and monthly debt payments.</div>\n      </div>\n      <div class="input-fields half-width-fields">\n        <div class="input-field affordability-level-gds">\n          <div class="field-label">Property Tax (GDS)</div>\n          <input type="text" value="35%" data-previous-value="35" class="value-input">\n        </div>\n        <div class="input-field affordability-level-tds">\n          <div class="field-label">Property Tax (TDS)</div>\n          <input type="text" value="42%" data-previous-value="42" class="value-input">\n        </div>\n      </div>\n      <div class="btn-group-selector full-width">\n        <div class="selector active">Baseline</div>\n        <div class="selector">Standard</div>\n      </div>\n      <div class="current-calculated-ratios">\n        <div class="label">Current Calculated Ratios</div>\n        <div class="value">GDS: <span>35.00%</span> / TDS: <span>42.00%</span></div>\n      </div>\n    </div>\n\n    <div class="calculator-input mortgage-calculator-input debt-service-rate">\n      <div class="header">\n        <div class="title-wrapper">\n          <img src="${l.default}" alt="Rate icon"/>\n          <div class="title">Rate</div>\n        </div>\n        <div class="btn-group-selector">\n          <div class="selector active">Regular</div>\n          <div class="selector">Interest Only</div>\n        </div>\n        <div class="mortgage-calculator-info full-row-width">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 single-field">\n        <div class="dropdown inline compounding">\n          <div class="dropdown-field inline-label">\n            <div class="field-label">Compounding</div>\n            <span>Semi-Annual</span>\n            <img class="info-icon" src="${h.default}" alt="Dropdown icon"/>  \n          </div>\n          <div class="dropdown-opts">\n            <div class="dropdown-opt">Daily</div>\n            <div class="dropdown-opt">Weekly</div>\n            <div class="dropdown-opt">Bi-Weekly</div>\n            <div class="dropdown-opt">Monthly</div>\n            <div class="dropdown-opt">Quarterly</div>\n            <div class="dropdown-opt">Semi-Annual</div>\n          </div>\n        </div>\n      </div>\n      <div class="input-fields">\n        <div class="input-field rate">\n          <div class="field-label">Rate</div>\n          <input type="text" value="6.50%" data-previous-value="6.50" class="value-input">\n          <input type="range" min="0" max="10" value="6.50" step="0.5" class="slider">\n        </div>\n        <div class="dropdown inline rate-term">\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="${h.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="${d.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="5" max="30" value="25" step="1" class="slider">\n          <div class="range-label">\n            <span>5 Year</span>\n            <span>30 Years</span>\n          </div>\n        </div>\n      </div>\n    </div>\n\n    <div class="calculator-input mortgage-calculator-input add-rental-income">\n      <div class="header stacked">\n        <div class="title-toggle-wrapper">\n          <div class="title-wrapper">\n            <img src="${o.default}" alt="Add Rental Income icon"/>\n            <div class="title">Add Rental Income</div>\n          </div>\n          <div class="toggle">\n            <div class="opt off selected" data-value="off"></div>\n            <div class="opt on" data-value="on"></div>\n          </div>\n        </div>\n        <div class="mortgage-calculator-info">If you plan to rent out part of your home, enter the rent amount here to reduce your total monthly cost.</div>\n      </div>\n\n      <div class="input-fields half-width-fields expandable">\n        <div class="input-field add-rental-income-monthly">\n          <div class="field-label">Monthly</div>\n          <input type="text" value="$  200" data-previous-value="200" class="value-input">\n        </div>\n        <div class="input-field add-rental-income-yearly">\n          <div class="field-label">Yearly</div>\n          <input type="text" value="$  2,400" data-previous-value="2400" class="value-input">\n        </div>\n      </div>\n    </div>\n\n    <div class="calculator-input mortgage-calculator-input calculation-rules">\n      <div class="header">\n        <div class="title-wrapper">\n          <img src="${i.default}" alt="Calculation Rules icon"/>\n          <div class="title">Calculation Rules</div>\n        </div>\n      </div>\n      <div class="sub-header stress-test-rule">\n        <div class="title">Stress Test Rule</div>\n        <div class="btn-group-selector">\n          <div class="selector">Contract</div>\n          <div class="selector active">B20</div>\n        </div>\n      </div>\n      <div class="input-fields single-field">\n        <div class="dropdown inline condo-fee-inclusion-rate">\n          <div class="dropdown-field inline-label">\n            <div class="field-label">Condo Fee Inclusion Rate</div>\n            <span>50%</span>\n            <img class="info-icon" src="${h.default}" alt="Dropdown icon"/>  \n          </div>\n          <div class="dropdown-opts">\n            <div class="dropdown-opt">0%</div>\n            <div class="dropdown-opt">50%</div>\n            <div class="dropdown-opt">100%</div>\n          </div>\n        </div>\n      </div>\n      <div class="sub-header rental-income-rule">\n        <div class="title">Rental Income Rule</div>\n        <div class="btn-group-selector">\n          <div class="selector">Add Back</div>\n          <div class="selector active">Offset</div>\n        </div>\n      </div>\n      <div class="input-fields single-field">\n        <div class="dropdown inline rental-income-portion">\n          <div class="dropdown-field inline-label">\n            <div class="field-label">Rental Income Portion</div>\n            <span>50%</span>\n            <img class="info-icon" src="${h.default}" alt="Dropdown icon"/>  \n          </div>\n          <div class="dropdown-opts">\n            <div class="dropdown-opt">25%</div>\n            <div class="dropdown-opt">50%</div>\n            <div class="dropdown-opt">75%</div>\n            <div class="dropdown-opt">100%</div>\n          </div>\n        </div>\n      </div>\n      <div class="foot-notes">\n        <div class="foot-note">\n          <span>Stress Test:</span> CONTRACT uses your actual rate, 820 uses higher of 5.25% or contract rate + 2%\n        </div>\n        <div class="foot-note">\n          <span>Rental Income:</span> ADO BACK adds income to qualify, OFFSET reduces housing costs\n        </div>\n      </div>\n    </div>\n  `;e.innerHTML=`\n    <div class="mortgage-calculator">\n        <div class="section-heading">Maximum Mortgage Calculator</div>\n        <div class="tab-layout">\n          <div class="tab-content active">\n            <div class="calculator-inputs">\n              ${t}\n            </div>\n            <div class="calculator-results max-mortgage-calculator-results">\n              \n    <div class="max-mortgage-results">\n      <div class="label">Maximum Mortgage Amount</div>\n      <div class="max-mortgage-amount">\n        <div class="amount">$427,432</div>\n      </div>\n      <div class="ratios-wrapper">\n        <div class="item">\n          <div class="item-label">Stress Test Rate</div>\n          <div class="item-value">8.29%</div>\n        </div>\n        <div class="item">\n          <div class="item-label">GDS / TDS</div>\n          <div class="item-value">35.00% / 42.00%</div>\n        </div>\n      </div>\n      <div class="details">\n        <div class="breakdown-bar-container">\n          <div class="breakdown-bar-monthly-mortgage"></div>\n          <div class="breakdown-bar-debt-payment"></div>\n          <div class="breakdown-bar-home-expenses"></div>\n          <div class="breakdown-bar-cash-left"></div>\n        </div>\n        <div class="debt-service-details">\n          <div class="service-detail monthly-mortgage">\n            <div class="service-detail-icon"></div>\n            <div class="service-detail-name">Monthly Mortgage</div>\n            <div class="service-detail-value">$2,934.93</div>\n          </div>\n          <div class="service-detail debt-payment">\n            <div class="service-detail-icon"></div>\n            <div class="service-detail-name">Debt Payment</div>\n            <div class="service-detail-value">$300.00</div>\n          </div>\n          <div class="service-detail home-expenses">\n            <div class="service-detail-icon"></div>\n            <div class="service-detail-name">Home Expenses <span>(incl. rental offset)</span></div>\n            <div class="service-detail-value">$1,233.33</div>\n          </div>\n          <div class="service-detail cash-left">\n            <div class="service-detail-icon"></div>\n            <div class="service-detail-name">Cash Left (Gross)</div>\n            <div class="service-detail-value">$8,531.74</div>\n          </div>\n        </div>\n      </div>\n    </div>\n  \n            </div>\n          </div>\n        </div>\n    </div>\n  `;const n=document.querySelector(".gross-annual-income .value-input"),r=document.querySelector(".gross-annual-income .slider"),p=document.querySelector(".monthly-debt-payments .value-input"),f=document.querySelector(".monthly-debt-payments .slider"),m=document.querySelector(".home-expense-monthly .value-input"),v=document.querySelector(".home-expense-yearly .value-input"),g=document.querySelector(".home-expense-condo-fees .value-input"),y=document.querySelector(".home-expense-condo-fees .slider"),w=document.querySelector(".home-expense-heat .value-input"),b=document.querySelector(".home-expense-heat .slider"),S=document.querySelector(".affordability-level-gds .value-input"),x=document.querySelector(".affordability-level-tds .value-input"),E=document.querySelector(".affordability-level .current-calculated-ratios .value span:nth-of-type(1)"),I=document.querySelector(".affordability-level .current-calculated-ratios .value span:nth-of-type(2)"),_=document.querySelector(".add-rental-income .expandable"),T=document.querySelector(".add-rental-income-monthly .value-input"),C=document.querySelector(".add-rental-income-yearly .value-input"),A=document.querySelector(".rate .value-input"),D=document.querySelector(".rate .slider"),k=document.querySelector(".compounding .dropdown-field span"),L=document.querySelector(".condo-fee-inclusion-rate .dropdown-field span"),M=document.querySelector(".rental-income-portion .dropdown-field span"),N=document.querySelector(".amortization .value-input"),P=document.querySelector(".amortization .slider"),R=document.querySelector(".max-mortgage-calculator-results .max-mortgage-amount .amount"),V=document.querySelector(".max-mortgage-calculator-results .ratios-wrapper .item:nth-of-type(1) .item-value"),O=document.querySelector(".max-mortgage-calculator-results .ratios-wrapper .item:nth-of-type(2) .item-value"),$=document.querySelector(".max-mortgage-calculator-results .max-mortgage-results .details .debt-service-details .monthly-mortgage .service-detail-value"),F=document.querySelector(".max-mortgage-calculator-results .max-mortgage-results .details .debt-service-details .debt-payment .service-detail-value"),q=document.querySelector(".max-mortgage-calculator-results .max-mortgage-results .details .debt-service-details .home-expenses .service-detail-name span"),U=document.querySelector(".max-mortgage-calculator-results .max-mortgage-results .details .debt-service-details .home-expenses .service-detail-value"),B=document.querySelector(".max-mortgage-calculator-results .max-mortgage-results .details .debt-service-details .cash-left .service-detail-value"),j=document.querySelector(".max-mortgage-calculator-results .max-mortgage-results .details .breakdown-bar-container .breakdown-bar-monthly-mortgage"),z=document.querySelector(".max-mortgage-calculator-results .max-mortgage-results .details .breakdown-bar-container .breakdown-bar-debt-payment"),G=document.querySelector(".max-mortgage-calculator-results .max-mortgage-results .details .breakdown-bar-container .breakdown-bar-home-expenses"),K=document.querySelector(".max-mortgage-calculator-results .max-mortgage-results .details .breakdown-bar-container .breakdown-bar-cash-left"),H=document.querySelectorAll(".debt-service-rate .btn-group-selector .selector"),Q=document.querySelectorAll(".stress-test-rule .btn-group-selector .selector"),W=document.querySelectorAll(".rental-income-rule .btn-group-selector .selector"),Y=document.querySelectorAll(".affordability-level .btn-group-selector .selector"),J=document.querySelectorAll(".add-rental-income .opt"),X=document.querySelectorAll("[data-tooltip]");function Z(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,s=null==r?void 0:r.querySelector("span");s&&(s.textContent=e.textContent),null===(n=e.parentElement)||void 0===n||n.classList.remove("expanded"),null==r||r.classList.remove("dropdown-expanded"),te()}))})),document.querySelectorAll(".dropdown-field").forEach((e=>{e.addEventListener("click",(t=>{var n;if(t.stopPropagation(),null===(n=t.target)||void 0===n?void 0:n.closest(".dropdown-expanded"))document.querySelectorAll(".dropdown-opts.expanded").forEach((e=>{var t;null===(t=e.previousElementSibling)||void 0===t||t.classList.remove("dropdown-expanded"),e.classList.remove("expanded")}));else{document.querySelectorAll(".dropdown-field.dropdown-expanded").forEach((e=>{e.classList.remove("dropdown-expanded")})),document.querySelectorAll(".dropdown-opts.expanded").forEach((e=>{e.classList.remove("expanded")}));const t=e.nextElementSibling;null==t||t.classList.toggle("expanded"),(null==t?void 0:t.classList.contains("expanded"))&&t.previousElementSibling&&(t.style.top=`${t.previousElementSibling.clientHeight+5}px`,e.classList.add("dropdown-expanded"))}}))})),document.addEventListener("click",(e=>{e.target.closest(".dropdown")||document.querySelectorAll(".dropdown-opts.expanded").forEach((e=>{var t;null===(t=e.previousElementSibling)||void 0===t||t.classList.remove("dropdown-expanded"),e.classList.remove("expanded")}))})),H.forEach(((e,t)=>{e.addEventListener("click",(()=>{H.forEach((e=>e.classList.remove("active"))),e.classList.add("active"),te()}))})),Q.forEach(((e,t)=>{e.addEventListener("click",(()=>{Q.forEach((e=>e.classList.remove("active"))),e.classList.add("active"),te()}))})),W.forEach(((e,t)=>{e.addEventListener("click",(()=>{W.forEach((e=>e.classList.remove("active"))),e.classList.add("active"),te()}))})),Y.forEach(((e,t)=>{e.addEventListener("click",(()=>{var t;Y.forEach((e=>e.classList.remove("active"))),e.classList.add("active");const n=null===(t=e.textContent)||void 0===t?void 0:t.toLowerCase(),r="baseline"===n?35:39,s="baseline"===n?42:44;S.value=`${r.toLocaleString("en-US")}%`,S.dataset.previousValue=r.toString(),x.value=`${s.toLocaleString("en-US")}%`,x.dataset.previousValue=s.toString(),te()}))})),J.forEach(((e,t)=>{e.addEventListener("click",(()=>{var t,n,r,s,i,a,o,l,c,u,d,h;const p="off"===(null===(n=null===(t=document.querySelector(".title-toggle-wrapper .toggle .selected"))||void 0===t?void 0:t.dataset)||void 0===n?void 0:n.value)?"on":"off";J.forEach((e=>e.classList.remove("selected"))),"on"===p?document.querySelector(".title-toggle-wrapper .toggle .on").classList.add("selected"):document.querySelector(".title-toggle-wrapper .toggle .off").classList.add("selected"),null===(r=e.parentElement)||void 0===r||r.classList.remove("switched-on"),null===(o=null===(a=null===(i=null===(s=e.parentElement)||void 0===s?void 0:s.parentElement)||void 0===i?void 0:i.parentElement)||void 0===a?void 0:a.nextElementSibling)||void 0===o||o.classList.remove("expanded"),"on"===p?(null===(l=e.parentElement)||void 0===l||l.classList.add("switched-on"),null===(h=null===(d=null===(u=null===(c=e.parentElement)||void 0===c?void 0:c.parentElement)||void 0===u?void 0:u.parentElement)||void 0===d?void 0:d.nextElementSibling)||void 0===h||h.classList.add("expanded")):(T.value="$  0",T.dataset.previousValue="0",C.value="$  0",C.dataset.previousValue="0"),te()}))})),X.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"}))})),r.addEventListener("input",(()=>{const e=r.value.replace(/[^0-9.]/g,"");n.value=e?`$  ${parseInt(e).toLocaleString("en-US")}`:"",n.dataset.previousValue=e,Z(r),te()})),f.addEventListener("input",(()=>{const e=f.value.replace(/[^0-9.]/g,"");p.value=e?`$  ${parseInt(e).toLocaleString("en-US")}`:"",p.dataset.previousValue=e,Z(f),te()})),y.addEventListener("input",(()=>{const e=y.value.replace(/[^0-9.]/g,"");g.value=e?`$  ${parseInt(e).toLocaleString("en-US")}`:"",g.dataset.previousValue=e,Z(y),te()})),b.addEventListener("input",(()=>{const e=b.value.replace(/[^0-9.]/g,"");w.value=e?`$  ${parseInt(e).toLocaleString("en-US")}`:"",w.dataset.previousValue=e,Z(b),te()})),D.addEventListener("input",(()=>{const e=D.value.replace(/[^0-9.]/g,"");A.value=e?`${parseFloat(e).toFixed(2)}%`:"",A.dataset.previousValue=e,Z(D),te()})),P.addEventListener("input",(()=>{const e=P.value.replace(/[^0-9.]/g,"");N.value=e?`${parseInt(e).toLocaleString("en-US")} Years`:"",N.dataset.previousValue=e,Z(P),te()}));const ee=(e,t,n)=>{e.addEventListener("change",(e=>{const s=e.target;if(s){let e=s.value;e=e.replace(/[^0-9.]/g,"");const i=e?parseInt(e):0;switch(n){case"affordability-level-gds":case"affordability-level-tds":0<=i&&i<=100?(s.value=`${parseInt(e).toLocaleString("en-US")}${t}`,s.dataset.previousValue=e,"affordability-level-gds"===n?E.textContent=`${parseFloat(parseFloat(e).toFixed(2)).toLocaleString("en-US")}${t}`:"affordability-level-tds"===n&&(I.textContent=`${parseFloat(parseFloat(e).toFixed(2)).toLocaleString("en-US")}${t}`)):s.dataset.previousValue&&(s.value=`${parseInt(s.dataset.previousValue).toLocaleString("en-US")}${t}`);break;case"gross-annual-income":0<=i?(r.value=i.toString(),Z(r),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"monthly-debt-payments":0<=i?(f.value=i.toString(),Z(f),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"home-expense-condo-fees":0<=i?(y.value=i.toString(),Z(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")}`);break;case"home-expense-heat":0<=i?(b.value=i.toString(),Z(b),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"home-expense-monthly":case"home-expense-yearly":case"add-rental-income-monthly":case"add-rental-income-yearly":if(0<=i?(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")}`),"home-expense-monthly"===n){const e=s.dataset.previousValue,n=12*(e?parseInt(e):0);v.value=`${t} ${n.toLocaleString("en-US")}`,v.dataset.previousValue=n.toString()}else if("home-expense-yearly"===n){const e=s.dataset.previousValue,n=(e?parseInt(e):0)/12;m.value=`${t} ${n.toLocaleString("en-US")}`,m.dataset.previousValue=n.toString()}else if("add-rental-income-monthly"===n){const e=s.dataset.previousValue,n=12*(e?parseInt(e):0);C.value=`${t} ${n.toLocaleString("en-US")}`,C.dataset.previousValue=n.toString()}else if("add-rental-income-yearly"===n){const e=s.dataset.previousValue,n=(e?parseInt(e):0)/12;T.value=`${t} ${n.toLocaleString("en-US")}`,T.dataset.previousValue=n.toString()}break;case"interest-rate":const a=e?parseFloat(e):0;.1<=a&&a<=10?(D.value=a.toFixed(2),Z(D),s.value=`${a.toFixed(2)}%`,s.dataset.previousValue=a.toFixed(2)):s.dataset.previousValue&&(s.value=`${parseFloat(s.dataset.previousValue).toFixed(2)}%`);break;case"amortization-period":5<=i&&i<=30?(P.value=i.toString(),Z(P),s.value=`${parseInt(e).toLocaleString("en-US")} ${t}`,s.dataset.previousValue=e):s.dataset.previousValue&&(s.value=`${parseInt(s.dataset.previousValue).toLocaleString("en-US")} ${t}`)}te()}}))},te=()=>{var e,t;const r=n.dataset.previousValue?parseFloat(n.dataset.previousValue):0,i=p.dataset.previousValue?parseFloat(p.dataset.previousValue):0,a=m.dataset.previousValue?parseFloat(parseFloat(m.dataset.previousValue).toFixed(2)):0,o=g.dataset.previousValue?parseFloat(g.dataset.previousValue):0,l=w.dataset.previousValue?parseFloat(w.dataset.previousValue):0,c=A.dataset.previousValue?parseFloat(parseFloat(A.dataset.previousValue).toFixed(2)):0,u=N.dataset.previousValue?parseInt(N.dataset.previousValue):5,d=T.dataset.previousValue?parseFloat(T.dataset.previousValue):0,h=S.dataset.previousValue?parseFloat(S.dataset.previousValue):0,f=x.dataset.previousValue?parseFloat(x.dataset.previousValue):0,v=k.textContent?k.textContent.toLowerCase():"semi-annual",y=L.textContent?parseInt(L.textContent.replace("%","")):50,b=M.textContent?parseInt(M.textContent.replace("%","")):50,E=document.querySelector(".stress-test-rule .btn-group-selector .active"),I=document.querySelector(".rental-income-rule .btn-group-selector .active"),C=(null===(e=E.textContent)||void 0===e?void 0:e.toLowerCase())||"contract",D="contract"===(P=C)||"b20"===P?C:"contract";var P;const H=(null===(t=I.textContent)||void 0===t?void 0:t.toLowerCase().replace(" ","-"))||"offset",Q=function(e){return"offset"===e||"add-back"===e}(H)?H:"offset",W=(document.querySelector(".debt-service-rate .btn-group-selector .active"),(0,s.calculateMaxMortgage)({grossAnnualIncome:r,monthlyDebtPayments:i,propertyTaxMonthly:a,condoFees:o,heatCosts:l,interestRate:c,amortizationYears:u,amortizationMonths:0,affordabilityLevel:0,customGdsRatio:h,customTdsRatio:f,rentalIncomeMonthly:d,includeRentalIncome:_.classList.contains("expanded"),stressTestRule:D.toUpperCase(),condoFeeInclusionRate:y,rentalIncomeRule:Q.toUpperCase(),rentalIncomePortion:b,loanType:"REGULAR",compounding:v}));R.textContent=(0,s.formatCurrency)(W.maxMortgageAmount),V.textContent=(0,s.formatPercentage)(W.stressTestRate),O.textContent=`${(0,s.formatPercentage)(W.gdsRatio)} / ${(0,s.formatPercentage)(W.tdsRatio)}`,$.textContent=(0,s.formatCurrency)(W.monthlyMortgagePayment,!0);const Y=W.totalMonthlyDebtCosts-W.totalMonthlyHousingCosts,J=W.homeExpenses,X=W.monthlyMortgagePayment+Math.max(Y,0)+J+W.cashLeftGross,Z=W.monthlyMortgagePayment/X*100,ee=Math.max(Y,0)/X*100,te=J/X*100,ne=W.cashLeftGross/X*100;j.style.width=`${Z.toString()}%`,z.style.width=`${ee.toString()}%`,G.style.width=`${te.toString()}%`,K.style.width=`${ne.toString()}%`,F.textContent=(0,s.formatCurrency)(Math.max(Y,0),!0),q.style.display="offset"===Q.toLowerCase()?"unset":"none",U.textContent=(0,s.formatCurrency)(J,!0),B.textContent=(0,s.formatCurrency)(W.cashLeftGross,!0)};ee(n,"$","gross-annual-income"),Z(r),ee(p,"$","monthly-debt-payments"),Z(f),ee(m,"$","home-expense-monthly"),ee(v,"$","home-expense-yearly"),ee(S,"%","affordability-level-gds"),ee(x,"%","affordability-level-tds"),ee(g,"$","home-expense-condo-fees"),Z(y),ee(w,"$","home-expense-heat"),Z(b),ee(T,"$","add-rental-income-monthly"),ee(C,"$","add-rental-income-yearly"),ee(A,"%","interest-rate"),Z(D),ee(N,"Years","amortization-period"),Z(P),te()};const s=n(7422),i=r(n(9875)),a=r(n(1804)),o=r(n(1341)),l=r(n(6421)),c=r(n(5464)),u=r(n(3725)),d=r(n(5858)),h=r(n(38))},3117: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){const t=`\n    <div class="calculator-input mortgage-calculator-input">\n      <div class="header stacked">\n        <div class="title-wrapper">\n          <img src="${a.default}" alt="Loan Details icon"/>\n          <div class="title">Loan Details</div>\n        </div>\n      </div>\n      <div class="input-fields">\n        <div class="input-field purchase-price">\n          <div class="field-label">Loan Amount</div>\n          <input type="text" value="$  500,000" data-previous-value="500000" class="value-input">\n          <input type="range" min="100000" max="2000000" value="500000" step="10000" class="slider">\n          <div class="range-label">\n            <span>$100K</span>\n            <span>$2M+</span>\n          </div>\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="${u.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="${i.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-wrapper">\n            <div class="field-label">Rate</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 class="range-label">\n            <span>1%</span>\n            <span>10%</span>\n          </div>\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="${u.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="${c.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 class="range-label">\n            <span>1 Year</span>\n            <span>40 Years</span>\n          </div>\n        </div>\n      </div>\n    </div>\n\n    <div class="calculator-input mortgage-calculator-input calculator-settings">\n      <div class="header">\n        <div class="title-wrapper">\n          <img src="${o.default}" alt="Calculator Settings icon"/>\n          <div class="title">Calculator Settings</div>\n        </div>\n        <div class="btn-group-selector">\n          <div class="selector active">Regular</div>\n          <div class="selector">Interest Only</div>\n        </div>\n      </div>\n      <div class="input-fields single-field">\n        <div class="dropdown inline term-length">\n          <div class="dropdown-field inline-label">\n            <div class="field-label">Compounding</div>\n            <span>Semi-Annual</span>\n            <img class="info-icon" src="${u.default}" alt="Dropdown icon"/>  \n          </div>\n          <div class="dropdown-opts">\n            <div class="dropdown-opt">Daily</div>\n            <div class="dropdown-opt">Weekly</div>\n            <div class="dropdown-opt">Bi-Weekly</div>\n            <div class="dropdown-opt">Monthly</div>\n            <div class="dropdown-opt">Quarterly</div>\n            <div class="dropdown-opt">Semi-Annual</div>\n          </div>\n        </div>\n      </div>\n    </div>\n\n    <div class="calculator-input mortgage-calculator-input pay-mortgage-faster">\n      <div class="header stacked">\n        <div class="title-toggle-wrapper">\n          <div class="title-wrapper">\n            <img src="${l.default}" alt="Pay your mortgage faster icon"/>\n            <div class="title">Pay your mortgage faster</div>\n          </div>\n          <div class="toggle">\n            <div class="opt off selected" data-value="off"></div>\n            <div class="opt on" data-value="on"></div>\n          </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 expandable">\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="$  0" data-previous-value="0" class="value-input">\n            <input type="text" value="0%" data-previous-value="0" class="percentage-value-input" disabled>\n          </div>\n          <input type="range" min="0" max="2000" value="0" step="25" class="slider">\n          <div class="range-label">\n            <span>$0</span>\n            <span>$2,000+</span>\n          </div>\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="$  0" data-previous-value="0" class="value-input">\n          <input type="range" min="0" max="100000" value="0" step="1000" class="slider">\n          <div class="range-label">\n            <span>$0</span>\n            <span>$100K+</span>\n          </div>\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              ${t}\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 n=document.querySelector(".purchase-price .value-input"),r=document.querySelector(".purchase-price .slider"),d=document.querySelector(".interest-rate .value-input"),h=document.querySelector(".interest-rate .slider"),p=document.querySelector(".amortization .value-input"),f=document.querySelector(".amortization .slider"),m=document.querySelector(".payment-increase .value-input"),v=document.querySelector(".payment-increase .slider"),g=document.querySelector(".one-time-pre-payment .value-input"),y=document.querySelector(".one-time-pre-payment .slider"),w=document.querySelector(".payment-frequency .dropdown-field span"),b=document.querySelector(".term-length .dropdown-field span"),S=document.querySelector(".mortgage-calculator-results .mortgage-payment .value"),x=document.querySelector(".mortgage-calculator-results .payment-breakdown .principal-paid .value"),E=document.querySelector(".mortgage-calculator-results .payment-breakdown .interest-paid .value"),I=document.querySelector(".mortgage-calculator-results .payment-breakdown .breakdown-total-payment .value"),_=document.querySelector(".mortgage-calculator-results .payment-breakdown .breakdown-bar-principal"),T=document.querySelector(".mortgage-calculator-results .payment-breakdown .breakdown-bar-interest"),C=document.querySelector(".mortgage-calculator-results .balance-amortization .balance .value"),A=document.querySelector(".mortgage-calculator-results .balance-amortization .amortization .value"),D=document.querySelector(".mortgage-calculator-results .balance-amortization .duration .tag"),k=document.querySelector(".mortgage-calculator-results .five-year-breakdown .info-row:nth-of-type(2) .value"),L=document.querySelector(".mortgage-calculator-results .five-year-breakdown .info-row:nth-of-type(3) .value"),M=document.querySelector(".mortgage-calculator-results .five-year-breakdown .info-row:nth-of-type(4) .value"),N=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"),R=document.querySelector(".mortgage-calculator-results .total-breakdown .info-row:nth-of-type(3) .value"),V=document.querySelector(".mortgage-calculator-results .total-breakdown .info-row:nth-of-type(4) .value"),O=document.querySelector(".savings-with-accelerated-payments"),$=document.querySelector(".mortgage-calculator-results .savings-with-accelerated-payments .info-row:nth-of-type(1) .value"),F=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"),U=document.querySelector(".mortgage-calculator-input .payment-increase .percentage-value-input"),B=document.querySelectorAll(".calculator-settings .btn-group-selector .selector"),j=document.querySelector(".calculator-settings .dropdown-field span"),z=document.querySelectorAll(".pay-mortgage-faster .opt"),G=document.querySelectorAll("[data-tooltip]");function K(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,s=null==r?void 0:r.querySelector("span");s&&(s.textContent=e.textContent),null===(n=e.parentElement)||void 0===n||n.classList.remove("expanded"),null==r||r.classList.remove("dropdown-expanded"),Q()}))})),document.querySelectorAll(".dropdown-field").forEach((e=>{e.addEventListener("click",(t=>{var n;if(t.stopPropagation(),null===(n=t.target)||void 0===n?void 0:n.closest(".dropdown-expanded"))document.querySelectorAll(".dropdown-opts.expanded").forEach((e=>{var t;null===(t=e.previousElementSibling)||void 0===t||t.classList.remove("dropdown-expanded"),e.classList.remove("expanded")}));else{document.querySelectorAll(".dropdown-field.dropdown-expanded").forEach((e=>{e.classList.remove("dropdown-expanded")})),document.querySelectorAll(".dropdown-opts.expanded").forEach((e=>{e.classList.remove("expanded")}));const t=e.nextElementSibling;null==t||t.classList.toggle("expanded"),(null==t?void 0:t.classList.contains("expanded"))&&t.previousElementSibling&&(t.style.top=`${t.previousElementSibling.clientHeight+5}px`,e.classList.add("dropdown-expanded"))}}))})),document.addEventListener("click",(e=>{e.target.closest(".dropdown")||document.querySelectorAll(".dropdown-opts.expanded").forEach((e=>{var t;null===(t=e.previousElementSibling)||void 0===t||t.classList.remove("dropdown-expanded"),e.classList.remove("expanded")}))})),B.forEach(((e,t)=>{e.addEventListener("click",(()=>{B.forEach((e=>e.classList.remove("active"))),e.classList.add("active"),Q()}))})),z.forEach(((e,t)=>{e.addEventListener("click",(()=>{var t,n,r,s,i,a,o,l,c,u,d,h;const p="off"===(null===(n=null===(t=document.querySelector(".title-toggle-wrapper .toggle .selected"))||void 0===t?void 0:t.dataset)||void 0===n?void 0:n.value)?"on":"off";z.forEach((e=>e.classList.remove("selected"))),"on"===p?document.querySelector(".title-toggle-wrapper .toggle .on").classList.add("selected"):document.querySelector(".title-toggle-wrapper .toggle .off").classList.add("selected"),null===(r=e.parentElement)||void 0===r||r.classList.remove("switched-on"),null===(o=null===(a=null===(i=null===(s=e.parentElement)||void 0===s?void 0:s.parentElement)||void 0===i?void 0:i.parentElement)||void 0===a?void 0:a.nextElementSibling)||void 0===o||o.classList.remove("expanded"),"on"===p?(null===(l=e.parentElement)||void 0===l||l.classList.add("switched-on"),null===(h=null===(d=null===(u=null===(c=e.parentElement)||void 0===c?void 0:c.parentElement)||void 0===u?void 0:u.parentElement)||void 0===d?void 0:d.nextElementSibling)||void 0===h||h.classList.add("expanded")):(m.value="$  0",m.dataset.previousValue="0",v.value="0",K(v),g.value="$  0",g.dataset.previousValue="0",y.value="0",K(y)),Q()}))})),G.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"}))})),r.addEventListener("input",(()=>{const e=r.value.replace(/[^0-9.]/g,"");n.value=e?`$  ${parseInt(e).toLocaleString("en-US")}`:"",n.dataset.previousValue=e,K(r),Q()})),h.addEventListener("input",(()=>{const e=h.value.replace(/[^0-9.]/g,"");d.value=e?`${parseFloat(e).toFixed(2)}%`:"",d.dataset.previousValue=e,K(h),Q()})),f.addEventListener("input",(()=>{const e=f.value.replace(/[^0-9.]/g,"");p.value=e?`${parseInt(e).toLocaleString("en-US")} Years`:"",p.dataset.previousValue=e,K(f),Q()})),v.addEventListener("input",(()=>{const e=v.value.replace(/[^0-9.]/g,"");m.value=e?`$  ${parseInt(e).toLocaleString("en-US")}`:"",m.dataset.previousValue=e,K(v),Q()})),y.addEventListener("input",(()=>{const e=y.value.replace(/[^0-9.]/g,"");g.value=e?`$  ${parseInt(e).toLocaleString("en-US")}`:"",g.dataset.previousValue=e,K(y),Q()}));const H=(e,t,n)=>{e.addEventListener("change",(e=>{const s=e.target;if(s){let e=s.value;e=e.replace(/[^0-9.]/g,"");const i=e?parseInt(e):0;switch(n){case"purchase-price":1e5<=i?(r.value=i.toString(),K(r),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"interest-rate":const n=e?parseFloat(e):0;.1<=n&&n<=10?(h.value=n.toFixed(2),K(h),s.value=`${n.toFixed(2)}%`,s.dataset.previousValue=n.toFixed(2)):s.dataset.previousValue&&(s.value=`${parseFloat(s.dataset.previousValue).toFixed(2)}%`);break;case"amortization-period":1<=i&&i<=40?(f.value=i.toString(),K(f),s.value=`${parseInt(e).toLocaleString("en-US")} ${t}`,s.dataset.previousValue=e):s.dataset.previousValue&&(s.value=`${parseInt(s.dataset.previousValue).toLocaleString("en-US")} ${t}`);break;case"payment-increase":0<=i?(v.value=i.toString(),K(v),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"one-time-pre-payment":0<=i?(y.value=i.toString(),K(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")}`)}Q()}}))},Q=()=>{var e;const t=n.dataset.previousValue?parseInt(n.dataset.previousValue):0,r=d.dataset.previousValue?parseFloat(parseFloat(d.dataset.previousValue).toFixed(2)):0,i=p.dataset.previousValue?parseInt(p.dataset.previousValue):1,a=w.textContent?w.textContent.toLowerCase():"monthly",o=m.dataset.previousValue?parseInt(m.dataset.previousValue):0,l=document.querySelector(".calculator-settings .btn-group-selector .selector.active"),c=r/100,u=c/12,h=12*i;let f;if("monthly"===a)f=t*(u*Math.pow(1+u,h))/(Math.pow(1+u,h)-1);else if("biweekly"===a){const e=c/26,n=26*i;f=t*(e*Math.pow(1+e,n))/(Math.pow(1+e,n)-1)}else{const e=c/52,n=52*i;f=t*(e*Math.pow(1+e,n))/(Math.pow(1+e,n)-1)}const v=o/f*100;U.value=`${v.toFixed(2)}%`,U.dataset.previousValue=v.toFixed(2).toString();const y={loanAmount:t,interestRate:r,rateTerm:b.textContent?parseInt(b.textContent.replace(" years","").replace(" year","")):5,amortization:i,paymentFrequency:a,loanType:null===(e=null==l?void 0:l.textContent)||void 0===e?void 0:e.toLowerCase(),compounding:j.textContent?j.textContent.toLocaleLowerCase():"semi-annual",paymentIncrease:o,paymentIncreaseType:"dollar",oneTimePrePayment:g.dataset.previousValue?parseInt(g.dataset.previousValue):0,annualPrePayment:0},B=(0,s.calculateMortgage)(y),z=B.principal/B.mortgagePayment*100,G=100-z;S.textContent=B.acceleratedResults?(0,s.formatCurrency)(B.acceleratedResults.adjustedPayment):(0,s.formatCurrency)(B.mortgagePayment),x.textContent=(0,s.formatCurrency)(B.principal),E.textContent=(0,s.formatCurrency)(B.interest),I.textContent=B.acceleratedResults?(0,s.formatCurrency)(B.acceleratedResults.adjustedPayment):(0,s.formatCurrency)(B.mortgagePayment),_.style.width=`${z.toString()}%`,T.style.width=`${G.toString()}%`,C.textContent=(0,s.formatCurrency)(B.balanceEndOfTerm),A.textContent=B.acceleratedResults?`${Math.floor(B.acceleratedResults.payoffYears)} Years ${Math.round(12*(B.acceleratedResults.payoffYears-Math.floor(B.acceleratedResults.payoffYears)))} Months`:`${i||25} Years`,B.acceleratedResults?(D.textContent=B.acceleratedResults.timeSaved,D.style.display="unset"):D.style.display="none",k.textContent=(0,s.formatCurrency)(B.fiveYearBreakdown.totalPaid),L.textContent=(0,s.formatCurrency)(B.fiveYearBreakdown.interestPaid),M.textContent=(0,s.formatCurrency)(B.fiveYearBreakdown.principalPaid),N.textContent=(0,s.formatCurrency)(B.fiveYearBreakdown.balanceRemaining),P.textContent=(0,s.formatCurrency)(B.loanAmount),R.textContent=(0,s.formatCurrency)(B.totalInterest),V.textContent=(0,s.formatCurrency)(B.totalCost),B.acceleratedResults?($.textContent=(0,s.formatCurrency)(B.acceleratedResults.totalInterestSaved),F.textContent=B.acceleratedResults.timeSaved,q.textContent=(0,s.formatCurrency)(B.acceleratedResults.totalInterestSaved),O.style.display="unset"):O.style.display="none"};H(n,"$","purchase-price"),K(r),H(d,"%","interest-rate"),K(h),H(p,"Years","amortization-period"),K(f),H(m,"$","payment-increase"),K(v),H(g,"$","one-time-pre-payment"),K(y),Q()};const s=n(9485),i=r(n(1953)),a=r(n(1804)),o=r(n(515)),l=r(n(3092)),c=r(n(6904)),u=r(n(38))},9619:function(e,t,n){"use strict";var r=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(s,i){function a(e){try{l(r.next(e))}catch(e){i(e)}}function o(e){try{l(r.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(a,o)}l((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"),s=e.querySelector(".filters"),i=e.querySelector(".calendar-events"),a=e.querySelector(".calendar-header");if(!t||!n||!i)return;d(e);let o=!1,l=!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(!o&&l&&t){o=!0;try{l=yield d(e)}catch(e){console.error("Error loading mortgage calendar events:",e)}finally{o=!1}}}))))),s.addEventListener("click",(t=>{const n=t.target;n.closest(".filter")&&(s.querySelectorAll(".filter").forEach((e=>{e.classList.remove("selected")})),n.classList.add("selected"),u=n.textContent?n.textContent:"",c=null,a.classList.remove("show","three-col-layout"),i.innerHTML="",a.innerHTML="",d(e))}))};const s=n(9487),i=n(9815),a=n(6185),o="mortgage_calender",l=9;let c=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,s.getFirestoreInstance)();let r=(0,i.query)((0,i.collection)(e,o),(0,i.orderBy)("schedule_date","asc"),(0,i.limit)(l));u&&(r=(0,i.query)(r,(0,i.where)("category","==",u))),c&&(r=(0,i.query)(r,(0,i.startAfter)(c)));const d=yield(0,i.getDocs)(r);return d.empty?(console.log("No more calendar events to load"),!1):(d.forEach((e=>{var r,s,i,o,l,c,d,h;const p=e.data(),f=document.createElement("div");f.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                ',f.innerHTML=`\n                    <div class="calendar-event-col">${null===(r=p.title)||void 0===r?void 0:r.trim()}</div>\n                    <div class="calendar-event-col date">${(0,a.formatDate)(null===(s=p.schedule_date)||void 0===s?void 0:s.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                ',f.classList.add("three-col-layout"),f.innerHTML=`\n                    <div class="calendar-event-col">${null===(i=p.title)||void 0===i?void 0:i.trim()}</div>\n                    <div class="calendar-event-col date">${(0,a.formatDate)(null===(o=p.release_date)||void 0===o?void 0:o.trim())}</div>\n                    <div class="calendar-event-col date">${(0,a.formatDate)(null===(l=p.reference_period)||void 0===l?void 0:l.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                ',f.classList.add("three-col-layout"),f.innerHTML=`\n                    <div class="calendar-event-col">${null===(c=p.title)||void 0===c?void 0:c.trim()}</div>\n                    <div class="calendar-event-col date">${(0,a.formatDate)(null===(d=p.release_date)||void 0===d?void 0:d.trim())}</div>\n                    <div class="calendar-event-col date">${(0,a.formatDate)(null===(h=p.last_published_date)||void 0===h?void 0:h.trim())}</div>\n                `),n.appendChild(f)})),c=d.docs[d.docs.length-1],!0)}catch(e){return console.error("Error loading mortgage calendar events:",e),!1}}))}},9533:function(e,t,n){"use strict";var r=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(s,i){function a(e){try{l(r.next(e))}catch(e){i(e)}}function o(e){try{l(r.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(a,o)}l((r=r.apply(e,t||[])).next())}))},s=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="${o.default}" alt="Expand/Collapse" /></div>\n                <div class="alphabets"></div>\n                <div class="arrow-right"><img src="${l.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"),s=e.querySelector(".glossary-list");t&&n&&s&&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,i.getFirestoreInstance)();let s=(0,a.query)((0,a.collection)(e,c),(0,a.orderBy)("term","asc"));const o=yield(0,a.getDocs)(s);if(o.empty)return void console.log("No mortgage glossary available");let l={};o.forEach((e=>{var t,r;const s=e.data(),i=s.term.charAt(0).toUpperCase();let a=!1;l[i]||(l[i]=[],a=!0),l[i].push(s);const o=document.createElement("div");o.classList.add("glossary-item"),a&&o.setAttribute("data-glosssary-control-letter",i),o.innerHTML=`\n                <div class="term">${null===(t=s.term)||void 0===t?void 0:t.trim()}</div>\n                <div class="definition">${null===(r=s.definition)||void 0===r?void 0:r.trim()}</div>\n            `,n.appendChild(o)})),console.log(l," - groupedGlossary");const u=Object.keys(l);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 i=n(9487),a=n(9815),o=s(n(5648)),l=s(n(6415)),c="mortgage_glossary"},9242:function(e,t,n){"use strict";var r=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(s,i){function a(e){try{l(r.next(e))}catch(e){i(e)}}function o(e){try{l(r.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(a,o)}l((r=r.apply(e,t||[])).next())}))},s=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"),s=e.querySelector(".mortgage-news-list");if(!t||!n||!s)return;h(e);let i=!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(!i&&a&&t){i=!0;try{const t=yield h(e);a=t}catch(e){console.error("Error loading mortgage news:",e)}finally{i=!1}}})))))};const i=n(9487),a=n(9815),o=n(6185),l=s(n(9501)),c="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,i.getFirestoreInstance)();let n=(0,a.query)((0,a.collection)(e,c),(0,a.orderBy)("date","desc"),(0,a.limit)(u));d&&(n=(0,a.query)(n,(0,a.startAfter)(d)));const r=yield(0,a.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,o.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="${l.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}}))}},3659:function(e,t,n){"use strict";var r=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(s,i){function a(e){try{l(r.next(e))}catch(e){i(e)}}function o(e){try{l(r.throw(e))}catch(e){i(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(a,o)}l((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="filters">\n            <div class="filter selected">All Articles</div>\n            <div class="filter">First time home buyer</div>\n            <div class="filter">General</div>\n            <div class="filter">HELOC</div>\n            <div class="filter">Refinance</div>\n            <div class="filter">Renewal</div>\n        </div>\n        <div class="research-articles-list"></div>\n      </div>\n    ';const t=e.querySelector(".research-articles"),n=e.querySelector(".section-heading"),s=e.querySelector(".filters"),i=e.querySelector(".research-articles-list");if(!t||!n||!i)return;d(e);let a=!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(!a&&o&&t){a=!0;try{const t=yield d(e);o=t}catch(e){console.error("Error loading research articles:",e)}finally{a=!1}}}))))),s.addEventListener("click",(t=>{const n=t.target;if(n.closest(".filter")){s.querySelectorAll(".filter").forEach((e=>{e.classList.remove("selected")})),n.classList.add("selected");const t="All Articles"===n.textContent?"":n.textContent;u=t||"",c=null,i.innerHTML="",d(e)}}))};const s=n(9487),i=n(9815),a=n(6185),o="research_articles",l=9;let c=null,u="";function d(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,s.getFirestoreInstance)();let n=(0,i.query)((0,i.collection)(e,o),(0,i.orderBy)("date","desc"),(0,i.limit)(l));u&&(n=(0,i.query)(n,(0,i.where)("category","==",u))),c&&(n=(0,i.query)(n,(0,i.startAfter)(c)));const r=yield(0,i.getDocs)(n);return r.empty?(console.log("No more research articles to load"),!1):(r.forEach((e=>{var n,r;const s=e.data(),i=document.createElement("div");i.classList.add("research-article"),i.innerHTML=`\n                <div class="thumbnail" style="background-image: url('${s.img_link}');"></div>\n                <div class="date">${(0,a.formatDate)(s.date)}</div>\n                <div class="title">${null===(n=s.headline)||void 0===n?void 0:n.trim()}</div>\n                <div class="description">${null===(r=s.description)||void 0===r?void 0:r.trim()}</div>\n                <a class="read-more-link" href="${s.source}" target="_blank">Read More</a>\n            `,t.appendChild(i)})),c=r.docs[r.docs.length-1],!0)}catch(e){return console.error("Error loading research articles:",e),!1}}))}},4250:(e,t)=>{"use strict";function n(e,t,n,r="semi-annual"){if(e<=0||t<=0||n<=0)return 0;const s=t/100;let i;if("monthly"===r)i=s/12;else if("semi-annual"===r){const e=s/2,t=Math.pow(1+e,2)-1;i=Math.pow(1+t,1/12)-1}else i=Math.pow(1+s,1/12)-1;const a=12*n;return 0===i?e/a:e*(i*Math.pow(1+i,a))/(Math.pow(1+i,a)-1)}function r(e,t,n,r,s,i=50){return(e+t+n+r*(i/100))/s*100}function s(e,t,n){return(e+t)/n*100}Object.defineProperty(t,"__esModule",{value:!0}),t.calculateMonthlyMortgagePayment=n,t.calculateGDSRatio=r,t.calculateTDSRatio=s,t.getStressTestRate=function(e){return Math.max(e+2,5.2)},t.calculateAllRatios=function(e,t="semi-annual",i=5.25,a=50,o=50,l="contract",c="offset"){const u=e.grossAnnualIncome/12;let d=u;e.isRentalIncomeEnabled&&"add-back"===c&&(d=u+e.rentalIncomeMonthly*(o/100));const h=n(e.mortgageAmount,e.interestRate,e.amortizationYears,t),p=e.propertyTaxMonthly+e.heatingCost+e.condoFees;let f=e.propertyTaxMonthly+e.heatingCost+e.condoFees;if(e.isRentalIncomeEnabled&&"offset"===c){const t=e.rentalIncomeMonthly*(o/100);f=Math.max(0,f-t)}const m=h+p;let v=e.propertyTaxMonthly,g=e.heatingCost,y=e.condoFees;if(e.isRentalIncomeEnabled&&"offset"===c){const t=e.rentalIncomeMonthly*(o/100),n=v+g+y*(a/100),r=n>0?(n-t)/n:1;v*=r,g*=r,y*=r}const w=r(h,v,g,y,d,a),b=s(h+v+g+y*(a/100),e.monthlyDebtPayments,d);let S;S="contract"===l?e.interestRate:Math.max(e.interestRate+2,i);const x=n(e.mortgageAmount,S,e.amortizationYears,t),E=r(x,v,g,y,d,a),I=s(x+v+g+y*(a/100),e.monthlyDebtPayments,d);let _=u,T=h+p+e.monthlyDebtPayments;return e.isRentalIncomeEnabled&&(_=u+e.rentalIncomeMonthly),{monthlyMortgagePayment:h,monthlyHomeExpenses:p,monthlyIncome:d,gdsRatio:w,tdsRatio:b,stressTestRate:S,stressTestGDS:E,stressTestTDS:I,cashLeftGross:_-T,totalMonthlyHousingCosts:m}},t.calculateIdealMortgageAmount=function(e,t,n="semi-annual",r=50,s=50,i="contract",a="offset"){const o=t.grossAnnualIncome/12;let l=o;t.isRentalIncomeEnabled&&"add-back"===a&&(l=o+t.rentalIncomeMonthly*(s/100));let c,u=t.propertyTaxMonthly,d=t.heatingCost,h=t.condoFees;if(t.isRentalIncomeEnabled&&"offset"===a){const e=t.rentalIncomeMonthly*(s/100),n=u+d+h*(r/100),i=n>0?(n-e)/n:1;u*=i,d*=i,h*=i}c="contract"===i?t.interestRate:Math.max(t.interestRate+2,5.25);const p=l*(e/100)-(u+d+h*(r/100));if(p<=0)return 0;const f=12*t.amortizationYears;let m;const v=c/100;if("monthly"===n)m=v/12;else if("semi-annual"===n){const e=v/2,t=Math.pow(1+e,2)-1;m=Math.pow(1+t,1/12)-1}else m=Math.pow(1+v,1/12)-1;if(0===m)return p*f;const g=p*((1-Math.pow(1+m,-f))/m);return Math.max(0,g)},t.getStressTestStatus=function(e,t){return e<=32&&t<=40?{level:"excellent",color:"text-green-600",message:"Excellent - Well within qualification guidelines"}:e<=35&&t<=42?{level:"good",color:"text-yellow-600",message:"Good - May qualify with strong credit and down payment"}:e<=39&&t<=44?{level:"caution",color:"text-orange-600",message:"Caution - May face challenges qualifying"}:{level:"poor",color:"text-red-600",message:"High risk - Unlikely to qualify without changes"}},t.formatCurrencyDetailed=function(e){return new Intl.NumberFormat("en-CA",{style:"currency",currency:"CAD",minimumFractionDigits:2,maximumFractionDigits:2}).format(e)}},7422:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.formatCurrency=function(e,t=!1){return new Intl.NumberFormat("en-CA",{style:"currency",currency:"CAD",minimumFractionDigits:t?2:0,maximumFractionDigits:t?2:0}).format(e)},t.formatPercentage=function(e,t=2){return`${e.toFixed(t)}%`},t.parseNumericValue=function(e){const t=e.replace(/[^\d.-]/g,"");return parseFloat(t)||0},t.formatNumericInput=function(e){return new Intl.NumberFormat("en-CA").format(e)},t.calculateMonthlyFromYearly=function(e){return e/12},t.calculateYearlyFromMonthly=function(e){return 12*e},t.getAffordabilityLabel=function(e){return e<=33?"Conservative":e<=66?"Baseline":"Standard"},t.getAffordabilityColor=function(e){return e<=33?"text-green-600":e<=66?"text-yellow-600":"text-red-600"},t.calculateMaxMortgage=function(e){const{grossAnnualIncome:t,monthlyDebtPayments:n,propertyTaxMonthly:r,condoFees:s,heatCosts:i,interestRate:a,amortizationYears:o,amortizationMonths:l,affordabilityLevel:c,rentalIncomeMonthly:u,includeRentalIncome:d,stressTestRule:h,condoFeeInclusionRate:p,rentalIncomeRule:f,rentalIncomePortion:m,loanType:v,compounding:g}=e,y=t/12,w=12*o+l;let b;b="CONTRACT"===h?a:Math.max(5.25,a+2);let S=0,x=0;if(d){const e=u*(m/100);"ADD-BACK"===f?S=e:x=e}const E=y+S,I=e.customGdsRatio||35,_=e.customTdsRatio||42,T=I/100,C=_/100,A=E*T,D=E*C,k=s*(p/100),L=r+k+i,M=Math.min(A-L+x,D-n-L+x);let N=0;if(M>0){let e;const t=b/100;switch(g){case"monthly":e=t/12;break;case"semi-annual":default:e=Math.pow(1+t/2,2/12)-1;break;case"annual":e=Math.pow(1+t,1/12)-1}if(e>0){const t=e*Math.pow(1+e,w);N=M*((Math.pow(1+e,w)-1)/t)}else N=M*w}const P=function(e,t,n,r="Semi-Annual"){if(0===t)return e/n;let s;const i=t/100;switch(r){case"Monthly":s=i/12;break;case"Semi-Annual":default:s=Math.pow(1+i/2,2/12)-1;break;case"Annual":s=Math.pow(1+i,1/12)-1}return e*(s*Math.pow(1+s,n)/(Math.pow(1+s,n)-1))}(N,a,w,g),R=P+L,V=R+n,O=y+(d?u:0)-(P+(r+s+i)+n),$=R/E*100<=100*T&&V/E*100<=100*C;return{maxMortgageAmount:Math.round(N),monthlyMortgagePayment:Math.round(100*P)/100,stressTestRate:Math.round(100*b)/100,gdsRatio:Math.round(100*I)/100,tdsRatio:Math.round(100*_)/100,monthlyGrossIncome:Math.round(100*E)/100,totalMonthlyHousingCosts:Math.round(100*R)/100,totalMonthlyDebtCosts:Math.round(100*V)/100,homeExpenses:Math.round(100*(r+s+i))/100,includedCondoFees:Math.round(100*k)/100,cashLeftGross:Math.round(100*O)/100,isQualified:$}}},9485:(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 s=12*e.amortization;let i;i="interest only"===e.loanType?t*n:0===n?t/s:t*(n*Math.pow(1+n,s))/(Math.pow(1+n,s)-1);const a=t*n,o=i-a;let l=t;const c=12*e.rateTerm;for(let e=0;e<c;e++){const e=i-l*n;if(l=Math.max(0,l-e),l<=0)break}let u=t,d=0,h=0;const p=Math.min(60,s);for(let e=0;e<p;e++){const e=u*n,t=i-e;if(u=Math.max(0,u-t),d+=e,h+=t,u<=0)break}const f=d+h,m=i*s-t,v=t+m;let g;if(e.paymentIncrease>0||e.oneTimePrePayment>0||e.annualPrePayment>0){const r=i+e.paymentIncrease;let a=t,o=0,l=0,u=!1;for(;a>.01&&l<2*s;){l++;const t=a*n;let s=r;if(!u&&l<=12&&e.oneTimePrePayment>0&&(s+=e.oneTimePrePayment,u=!0),l%12==0&&l>=12&&e.annualPrePayment>0&&(s+=e.annualPrePayment),a-=Math.min(s-t,a),o+=t,a<=0)break}const d=l/12,h=e.amortization-d,p=Math.floor(h),f=Math.round(12*(h-p)),v=m-o,y=[],w=(new Date).getFullYear();let b=t,S=t,x=0,E=0,I=!1;for(let t=0;t<=25;t+=5){const s=12*t;for(;x<s&&b>.01;){const e=i-b*n;b=Math.max(0,b-e),x++}for(;E<s&&S>.01;){E++;const t=S*n;let s=r;!I&&E<=12&&e.oneTimePrePayment>0&&(s+=e.oneTimePrePayment,I=!0),E%12==0&&e.annualPrePayment>0&&(s+=e.annualPrePayment);const i=Math.min(s-t,S);S=Math.max(0,S-i)}y.push({year:w+t,regularBalance:b,acceleratedBalance:S})}let _=t,T=0,C=0,A=0,D=!1;for(let t=0;t<Math.min(60,s);t++){const s=_*n;let i=r;!D&&t<12&&e.oneTimePrePayment>0&&(i+=e.oneTimePrePayment,D=!0),(t+1)%12==0&&t+1>=12&&e.annualPrePayment>0&&(i+=e.annualPrePayment);const a=Math.min(i-s,_);if(_=Math.max(0,_-a),T+=s,C+=a,A+=i,_<=0)break}let k=t,L=!1;for(let t=0;t<c;t++){const s=k*n;let i=r;!L&&t<12&&e.oneTimePrePayment>0&&(i+=e.oneTimePrePayment,L=!0),(t+1)%12==0&&t+1>=12&&e.annualPrePayment>0&&(i+=e.annualPrePayment);const a=Math.min(i-s,k);if(k=Math.max(0,k-a),k<=0)break}g={adjustedPayment:r,payoffYears:d,totalInterestSaved:v,timeSaved:p>0?`${p} YEARS, ${f} MONTHS FASTER`:`${f} MONTHS FASTER`,balanceComparison:y};const M=t*n;return{mortgagePayment:r,principal:r-M,interest:M,totalInterest:o,totalCost:t+o,loanAmount:t,balanceEndOfTerm:k,fiveYearBreakdown:{totalPaid:A,interestPaid:T,principalPaid:C,balanceRemaining:_},acceleratedResults:g}}return{mortgagePayment:i,principal:o,interest:a,totalInterest:m,totalCost:v,loanAmount:t,balanceEndOfTerm:l,fiveYearBreakdown:{totalPaid:f,interestPaid:d,principalPaid:h,balanceRemaining:u},acceleratedResults:g}}},6185:(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,s=e.interestRate/100/2,i=Math.pow(1+s,2/12)-1,a=12*e.amortizationPeriod,o=12*e.termLength,l=r*(i*Math.pow(1+i,a))/(Math.pow(1+i,a)-1),c=l*a,u=c-r,d=r*i,h=l-d,p=Math.round(u/r*100),f=l*o,m=function(e,t,n,r){return e*Math.pow(1+t,r)-n*(Math.pow(1+t,r)-1)/t}(r,i,l,o),v=r-m,g=f-v;return{monthlyPayment:Math.round(l),mortgageAmount:Math.round(t),mortgageInsurance:Math.round(n),principal:Math.round(h),interest:Math.round(d),totalMortgagePlusInterest:Math.round(c),totalInterestPaid:Math.round(u),interestPrincipalRatio:p,termPayments:Math.round(f),termPrincipalPaid:Math.round(v),termInterestPaid:Math.round(g),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),s=Math.round(e.heatingCosts/12),i=e.condoFees,a=t.monthlyPayment+r+s+i;let o=0,l=0;if("none"!==e.extraPaymentType&&e.extraPaymentAmount>0){const n="monthly"===e.extraPaymentFrequency?12*e.extraPaymentAmount:e.extraPaymentAmount;o=Math.min(Math.round(n*e.amortizationPeriod/t.mortgageAmount),e.amortizationPeriod-1),l=Math.round(12*o*t.interest)}const c=Math.max(e.interestRate+2,5.25),u=c/100/2,d=Math.pow(1+u,2/12)-1,h=12*e.amortizationPeriod,p=(e.purchasePrice-e.downPaymentAmount)*(d*Math.pow(1+d,h))/(Math.pow(1+d,h)-1),f=12*p+e.propertyTaxes+e.heatingCosts+12*e.condoFees,m=Math.round(f/.32);return{totalMonthlyPayment:Math.round(a),mortgagePayment:t.monthlyPayment,propertyTaxesMonthly:r,heatingCostsMonthly:s,condoFeesMonthly:i,yearsSaved:o,interestSaved:l,qualifyingRate:c,stressTestPayment:Math.round(p),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"}},1341:(e,t,n)=>{"use strict";e.exports=n.p+"809f4354f8eac0cacf15.svg"},5464:(e,t,n)=>{"use strict";e.exports=n.p+"adce9f33c499587ea45d.svg"},6904:(e,t,n)=>{"use strict";e.exports=n.p+"ec59ff28ecbf77d31249.svg"},5858:(e,t,n)=>{"use strict";e.exports=n.p+"7f6c93e73d43a4571832.svg"},5648:(e,t,n)=>{"use strict";e.exports=n.p+"94d7adc1c3f7df08c5dc.svg"},6415:(e,t,n)=>{"use strict";e.exports=n.p+"0134ef940feb41dedc27.svg"},515:(e,t,n)=>{"use strict";e.exports=n.p+"fd3ab491ffdea43f77b4.svg"},9573:(e,t,n)=>{"use strict";e.exports=n.p+"05e0aac3f5f644c344d6.svg"},9501:(e,t,n)=>{"use strict";e.exports=n.p+"7acafcdacd8c7574dbdc.svg"},4800:(e,t,n)=>{"use strict";e.exports=n.p+"ec67e568eccf383cda9e.svg"},6421:(e,t,n)=>{"use strict";e.exports=n.p+"ee762419a9ed6107b289.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"},9877:(e,t,n)=>{"use strict";e.exports=n.p+"bd4ffa72a63f585acc95.svg"},3765:(e,t,n)=>{"use strict";e.exports=n.p+"d686a45650560ddaa773.svg"},3378:(e,t,n)=>{"use strict";e.exports=n.p+"a630985df1564d70133d.svg"},3725:(e,t,n)=>{"use strict";e.exports=n.p+"f228177f75e9c61b1941.svg"},636:(e,t,n)=>{"use strict";e.exports=n.p+"a5f2f91315fae21adce3.svg"},1804:(e,t,n)=>{"use strict";e.exports=n.p+"fe00e61ce8c64a156494.svg"},3092:(e,t,n)=>{"use strict";e.exports=n.p+"6f14f50227dba9b6de9c.svg"},1490:(e,t,n)=>{"use strict";e.exports=n.p+"30b99c60fafb65be19cd.svg"},757:(e,t,n)=>{"use strict";e.exports=n.p+"dec0b8717bf0d582857b.svg"},2552:(e,t,n)=>{"use strict";e.exports=n.p+"e3ef864cb6d9c860c30e.svg"},1450:(e,t,n)=>{"use strict";e.exports=n.p+"91153cd53d2ed08a0a2e.svg"},1953:(e,t,n)=>{"use strict";e.exports=n.p+"3e74f701b4efddab859b.svg"},2950:(e,t,n)=>{"use strict";e.exports=n.p+"4cb7068e83798f5794cc.svg"},9875:(e,t,n)=>{"use strict";e.exports=n.p+"c9a8c5682e1b6ada3690.svg"},8706:(e,t,n)=>{"use strict";e.exports=n.p+"dafac920656692f6c6be.svg"},6148:(e,t,n)=>{"use strict";n.r(t),n.d(t,{deleteDB:()=>v,openDB:()=>m,unwrap:()=>f,wrap:()=>p});const r=(e,t)=>t.some((t=>e instanceof t));let s,i;const a=new WeakMap,o=new WeakMap,l=new WeakMap,c=new WeakMap,u=new WeakMap;let d={get(e,t,n){if(e instanceof IDBTransaction){if("done"===t)return o.get(e);if("objectStoreNames"===t)return e.objectStoreNames||l.get(e);if("store"===t)return n.objectStoreNames[1]?void 0:n.objectStore(n.objectStoreNames[0])}return p(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?(i||(i=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])).includes(t)?function(...e){return t.apply(f(this),e),p(a.get(this))}:function(...e){return p(t.apply(f(this),e))}:function(e,...n){const r=t.call(f(this),e,...n);return l.set(r,e.sort?e.sort():[e]),p(r)}:(e instanceof IDBTransaction&&function(e){if(o.has(e))return;const t=new Promise(((t,n)=>{const r=()=>{e.removeEventListener("complete",s),e.removeEventListener("error",i),e.removeEventListener("abort",i)},s=()=>{t(),r()},i=()=>{n(e.error||new DOMException("AbortError","AbortError")),r()};e.addEventListener("complete",s),e.addEventListener("error",i),e.addEventListener("abort",i)}));o.set(e,t)}(e),r(e,s||(s=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction]))?new Proxy(e,d):e);var t}function p(e){if(e instanceof IDBRequest)return function(e){const t=new Promise(((t,n)=>{const r=()=>{e.removeEventListener("success",s),e.removeEventListener("error",i)},s=()=>{t(p(e.result)),r()},i=()=>{n(e.error),r()};e.addEventListener("success",s),e.addEventListener("error",i)}));return t.then((t=>{t instanceof IDBCursor&&a.set(t,e)})).catch((()=>{})),u.set(t,e),t}(e);if(c.has(e))return c.get(e);const t=h(e);return t!==e&&(c.set(e,t),u.set(t,e)),t}const f=e=>u.get(e);function m(e,t,{blocked:n,upgrade:r,blocking:s,terminated:i}={}){const a=indexedDB.open(e,t),o=p(a);return r&&a.addEventListener("upgradeneeded",(e=>{r(p(a.result),e.oldVersion,e.newVersion,p(a.transaction),e)})),n&&a.addEventListener("blocked",(e=>n(e.oldVersion,e.newVersion,e))),o.then((e=>{i&&e.addEventListener("close",(()=>i())),s&&e.addEventListener("versionchange",(e=>s(e.oldVersion,e.newVersion,e)))})).catch((()=>{})),o}function v(e,{blocked:t}={}){const n=indexedDB.deleteDatabase(e);return t&&n.addEventListener("blocked",(e=>t(e.oldVersion,e))),p(n).then((()=>{}))}const g=["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,s=y.includes(n);if(!(n in(r?IDBIndex:IDBObjectStore).prototype)||!s&&!g.includes(n))return;const i=async function(e,...t){const i=this.transaction(e,s?"readwrite":"readonly");let a=i.store;return r&&(a=a.index(t.shift())),(await Promise.all([a[n](...t),s&&i.done]))[0]};return w.set(t,i),i}var S;S=d,d={...S,get:(e,t,n)=>b(e,t)||S.get(e,t,n),has:(e,t)=>!!b(e,t)||S.has(e,t)}}},t={};function n(r){var s=t[r];if(void 0!==s)return s.exports;var i=t[r]={exports:{}};return e[r].call(i.exports,i,i.exports,n),i.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 s=r.length-1;s>-1&&(!e||!/^http(s?):/.test(e));)e=r[s--].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){const n=document.getElementById(e.containerId);if(n)switch(e.product){case"calculator":(0,t.initCalculator)(n);break;case"mortgage-calculator":(0,s.initMortgageCalculator)(n);break;case"debt-service-calculator":(0,i.initDebtServiceCalculator)(n);break;case"max-mortgage-calculator":(0,a.initMaxMortgageCalculator)(n);break;case"cockpit":(0,p.initCockpit)(n);break;case"educational-videos":(0,h.initEducationalVideos)(n);break;case"faqs":(0,l.initFaqs)(n);break;case"free-guides":(0,f.initFreeGuides)(n);break;case"market-trend-videos":(0,o.initMarketTrendVideos)(n);break;case"mortgage-calender":(0,m.initMortgageCalendar)(n);break;case"mortgage-glossary":(0,d.initMortgageGlossary)(n);break;case"mortgage-news":(0,u.initMortgageNews)(n);break;case"research-articles":(0,c.initResearchArticles)(n);break;default:console.error(`Unknown product: ${e.product}`)}else console.error("Container not found")},n(2264);const t=n(3846),s=n(3117),i=n(2186),a=n(4526),o=n(6137),l=n(3987),c=n(3659),u=n(9242),d=n(9533),h=n(8260),p=n(577),f=n(6536),m=n(9619)})(),r})()));
//# sourceMappingURL=index.js.map