1(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[636],{92:(e,t,r)=>{(window.__NEXT_P=window.__NEXT_P||[]).push(["/_app",function(){return r(62e3)}])},825:(e,t,r)=>{"use strict";r.d(t,{Au:()=>i,G3:()=>a,S_:()=>s,WE:()=>n,jX:()=>o});let n=["dashboard.view","profile.view","users.view","users.create","users.edit","users.delete","users.approve","users.suspend","users.manage_roles","audit.view","audit.export","settings.view","settings.edit","reports.view","reports.export","stock.view","stock.receive","stock.qc","stock.issue","stock.transfer","stock.adjust","stock.count","stock.approve","stock.post","stock.manage","stock.export","procurement.view","procurement.create","procurement.edit","procurement.approve","procurement.manage","procurement.export","rental.view","service.view","service.request","service.triage","service.assign","service.work","service.review","service.complete","service.cancel","service.admin","crm.view","customer.view","customer.manage","asset.view","asset.manage","customer.import.review","dealer.view","sites.view","devices.view","finance.view","marketing.view","hr.view","knowledge.view","workflow.view","integrations.view","iot.view","alerts.view","map.view","sales.view","assets.view","chatbot.view"],i=["products.view","products.create","products.edit","products.approve","products.manage"],s=["workflow.products.master.create","workflow.products.master.edit","workflow.products.master.activate","workflow.products.master.deactivate","workflow.products.master.manageTracking","workflow.products.master.import","workflow.products.master.manageCost"],a=[...n,...i,"workflow.service.assignment.view","workflow.service.assignment.assign","workflow.service.assignment.requestSelf","workflow.service.assignment.approve","workflow.service.assignment.reject","workflow.service.work.start","workflow.service.work.submitReview","workflow.service.work.approveComplete","workflow.stock.document.create","workflow.stock.document.editDraft","workflow.stock.document.submit","workflow.stock.assignment.assign","workflow.stock.assignment.requestSelf","workflow.stock.assignment.approve","workflow.stock.assignment.reject","workflow.stock.qc.inspect","workflow.stock.qc.decide","workflow.stock.document.approve","workflow.stock.document.reject","workflow.stock.document.post","workflow.stock.adjustment.approve","workflow.stock.adjustment.post","workflow.stock.count.record","workflow.stock.count.approve","workflow.procurement.pr.create","workflow.procurement.pr.editDraft","workflow.procurement.pr.submit","workflow.procurement.pr.approve","workflow.procurement.pr.reject","workflow.procurement.pr.cancel","workflow.procurement.pr.convert","workflow.procurement.po.create","workflow.procurement.po.editDraft","workflow.procurement.po.submit","workflow.procurement.po.approveWithinLimit","workflow.procurement.po.approveAnyAmount","workflow.procurement.po.reject","workflow.procurement.po.cancel","workflow.procurement.po.receiveHandoff",...s],o=new Set([...a,"workflow.engineering.authority.manage","workflow.engineering.report.verify","workflow.engineering.report.revoke"])},15137:(e,t,r)=>{"use strict";r.d(t,{ig:()=>g,jR:()=>m,T5:()=>p,_m:()=>d,GY:()=>h,SP:()=>c});var n=r(54476),i=r(825);let s=JSON.parse('{"i0":["*"],"KC":["*"],"u":["dashboard.view","profile.view","reports.view","customer.view","customer.manage","asset.view","asset.manage"],"Fo":["dashboard.view","profile.view"],"IN":["profile.view"],"b$":["profile.view"]}'),a=["PENDING","ACTIVE","SUSPENDED","DISABLED"],o=["SUPER_ADMIN","ADMIN","MANAGER","STAFF","DEALER","CUSTOMER"],l=i.WE,u={SUPER_ADMIN:s.i0.includes("*")?l:s.i0,ADMIN:s.KC.includes("*")?l:s.KC,MANAGER:s.u,STAFF:s.Fo,DEALER:s.IN,CUSTOMER:s.b$};function h(e,t){if("string"==typeof e&&o.includes(e))return e;if(Array.isArray(t)){let e=o.filter(e=>t.includes(e));if(1===e.length)return e[0]}return"STAFF"}function c(e){return"string"==typeof e&&a.includes(e)?e:"PENDING"}function d(e,t){if(!e||"ACTIVE"!==e.status)return!1;if(2===e.accessModelVersion)return(0,n.Kt)(e).permissions.includes(t);if(void 0!==e.accessModelVersion)return!1;let r=new Set(u[e.role]);
1return e.permissions?.forEach(e=>r.add(e)),Object.entries(e.permissionOverrides||{}).forEach(([e,t])=>{t?r.add(e):r.delete(e)}),r.has(t)}let f=["SUPER_ADMIN","ADMIN","STAFF"];function p(e){return null!==e&&f.includes(e.role)&&d(e,"users.approve")}function m(e,t){return!!e&&e.uid!==t.uid&&!!d(e,"users.edit")&&"SUPER_ADMIN"!==t.role&&("SUPER_ADMIN"===e.role||"ADMIN"===e.role&&"ADMIN"!==t.role)}function g(e,t){return!!d(e,"users.manage_roles")&&(e?.role==="SUPER_ADMIN"||e?.role==="ADMIN"&&"ADMIN"!==t&&"SUPER_ADMIN"!==t)}},16042:(e,t,r)=>{"use strict";r.d(t,{Dk:()=>n.Dk,Sx:()=>n.Sx,Wp:()=>n.Wp,g:()=>n.g});var n=r(36672);(0,n.KO)("firebase","12.12.1","app")},21610:(e,t,r)=>{"use strict";r.d(t,{h1:()=>o,uA:()=>i});var n=r(76653);class i{constructor(e,t,r){this.name=e,this.instanceFactory=t,this.type=r,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}}let s="[DEFAULT]";class a{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){let t=this.normalizeInstanceIdentifier(e);if(!this.instancesDeferred.has(t)){let e=new n.cY;if(this.instancesDeferred.set(t,e),this.isInitialized(t)||this.shouldAutoInitialize())try{let r=this.getOrInitializeService({instanceIdentifier:t});r&&e.resolve(r)}catch(e){}}return this.instancesDeferred.get(t).promise}getImmediate(e){let t=this.normalizeInstanceIdentifier(e?.identifier),r=e?.optional??!1;if(this.isInitialized(t)||this.shouldAutoInitialize())try{return this.getOrInitializeService({instanceIdentifier:t})}catch(e){if(r)return null;throw e}if(r)return null;throw Error(`Service ${this.name} is not available`)}getComponent(){return this.component}setComponent(e){if(e.name!==this.name)throw Error(`Mismatching Component ${e.name} for Provider ${this.name}.`);if(this.component)throw Error(`Component for ${this.name} has already been provided`);if(this.component=e,this.shouldAutoInitialize()){if("EAGER"===e.instantiationMode)try{this.getOrInitializeService({instanceIdentifier:s})}catch(e){}for(let[e,t]of this.instancesDeferred.entries()){let r=this.normalizeInstanceIdentifier(e);try{let e=this.getOrInitializeService({instanceIdentifier:r});t.resolve(e)}catch(e){}}}}clearInstance(e=s){this.instancesDeferred.delete(e),this.instancesOptions.delete(e),this.instances.delete(e)}async delete(){let 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={}){let{options:t={}}=e,r=this.normalizeInstanceIdentifier(e.instanceIdentifier);if(this.isInitialized(r))throw Error(`${this.name}(${r}) has already been initialized`);if(!this.isComponentSet())throw Error(`Component ${this.name} has not been registered yet`);let n=this.getOrInitializeService({instanceIdentifier:r,options:t});for(let[e,t]of this.instancesDeferred.entries())r===this.normalizeInstanceIdentifier(e)&&t.resolve(n);return n}onInit(e,t){let r=this.normalizeInstanceIdentifier(t),n=this.onInitCallbacks.get(r)??new Set;n.add(e),this.onInitCallbacks.set(r,n);let i=this.instances.get(r);return i&&e(i,r),()=>{n.delete(e)}}invokeOnInitCallbacks(e,t){let r=this.onInitCallbacks.get(t);if(r)for(let n of r)try{n(e,t)}catch{}}getOrInitializeService({instanceIdentifier:e,options:t={}}){var r;let n=this.instances.get(e);if(!n&&this.component&&(n=this.component.instanceFactory(this.container,{instanceIdentifier:(r=e)===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{}return n||null}normalizeInstanceIdentifier(e=s){return this.component?this.component.multipleInstances?e:s:e}shouldAutoInitialize(){return!!this.component&&"EXPLICIT"!==this.component.instantiationMode}}class o{constructor(e){this.name=e,this.providers=new Map}addComponent(e){let t=this.getProvider(e.name);if(t.isComponentSet())throw 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);let t=new a(e,this);return this.providers.set(e,t),t}getProviders(){return Array.from(this.providers.values())}}},27402:()=>{},29979:(e,t,r)=>{"use strict";var n,i;r.d(t,{$b:()=>n,Vy:()=>h});let s=[];(i=n||(n={}))[i.DEBUG=0]="DEBUG",i[i.VERBOSE=1]="VERBOSE",i[i.INFO=2]="INFO",i[i.WARN=3]="WARN",i[i.ERROR=4]="ERROR",i[i.SILENT=5]="SILENT";let a={debug:n.DEBUG,verbose:n.VERBOSE,info:n.INFO,warn:n.WARN,error:n.ERROR,silent:n.SILENT},o=n.INFO,l={[n.DEBUG]:"log",[n.VERBOSE]:"log",[n.INFO]:"info",[n.WARN]:"warn",[n.ERROR]:"error"},u=(e,t,...r)=>{if(t<e.logLevel)return;let n=new Date().toISOString(),i=l[t];if(i)console[i](`[${n}] ${e.name}:`,...r);
1else throw Error(`Attempted to log a message with an invalid logType (value: ${t})`)};class h{constructor(e){this.name=e,this._logLevel=o,this._logHandler=u,this._userLogHandler=null,s.push(this)}get logLevel(){return this._logLevel}set logLevel(e){if(!(e in n))throw TypeError(`Invalid value "${e}" assigned to \`logLevel\``);this._logLevel=e}setLogLevel(e){this._logLevel="string"==typeof e?a[e]:e}get logHandler(){return this._logHandler}set logHandler(e){if("function"!=typeof e)throw 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,n.DEBUG,...e),this._logHandler(this,n.DEBUG,...e)}log(...e){this._userLogHandler&&this._userLogHandler(this,n.VERBOSE,...e),this._logHandler(this,n.VERBOSE,...e)}info(...e){this._userLogHandler&&this._userLogHandler(this,n.INFO,...e),this._logHandler(this,n.INFO,...e)}warn(...e){this._userLogHandler&&this._userLogHandler(this,n.WARN,...e),this._logHandler(this,n.WARN,...e)}error(...e){this._userLogHandler&&this._userLogHandler(this,n.ERROR,...e),this._logHandler(this,n.ERROR,...e)}}},31620:()=>{},36672:(e,t,r)=>{"use strict";let n,i,s;r.d(t,{g:()=>l.g,MF:()=>M,j6:()=>O,xZ:()=>P,om:()=>D,Sx:()=>V,Dk:()=>F,Wp:()=>U,KO:()=>j});var a=r(21610),o=r(29979),l=r(76653);let u=new WeakMap,h=new WeakMap,c=new WeakMap,d=new WeakMap,f=new WeakMap,p={get(e,t,r){if(e instanceof IDBTransaction){if("done"===t)return h.get(e);if("objectStoreNames"===t)return e.objectStoreNames||c.get(e);if("store"===t)return r.objectStoreNames[1]?void 0:r.objectStore(r.objectStoreNames[0])}return m(e[t])},set:(e,t,r)=>(e[t]=r,!0),has:(e,t)=>e instanceof IDBTransaction&&("done"===t||"store"===t)||t in e};function m(e){if(e instanceof IDBRequest){let t;return(t=new Promise((t,r)=>{let n=()=>{e.removeEventListener("success",i),e.removeEventListener("error",s)},i=()=>{t(m(e.result)),n()},s=()=>{r(e.error),n()};e.addEventListener("success",i),e.addEventListener("error",s)})).then(t=>{t instanceof IDBCursor&&u.set(t,e)}).catch(()=>{}),f.set(t,e),t}if(d.has(e))return d.get(e);let t=function(e){if("function"==typeof e)return e!==IDBDatabase.prototype.transaction||"objectStoreNames"in IDBTransaction.prototype?(i||(i=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])).includes(e)?function(...t){return e.apply(g(this),t),m(u.get(this))}:function(...t){return m(e.apply(g(this),t))}:function(t,...r){let n=e.call(g(this),t,...r);return c.set(n,t.sort?t.sort():[t]),m(n)};return e instanceof IDBTransaction&&function(e){if(h.has(e))return;let t=new Promise((t,r)=>{let n=()=>{e.removeEventListener("complete",i),e.removeEventListener("error",s),e.removeEventListener("abort",s)},i=()=>{t(),n()},s=()=>{r(e.error||new DOMException("AbortError","AbortError")),n()};e.addEventListener("complete",i),e.addEventListener("error",s),e.addEventListener("abort",s)});h.set(e,t)}(e),(n||(n=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])).some(t=>e instanceof t)?new Proxy(e,p):e}(e);return t!==e&&(d.set(e,t),f.set(t,e)),t}let g=e=>f.get(e),y=["get","getKey","getAll","getAllKeys","count"],v=["put","add","delete","clear"],w=new Map;function E(e,t){if(!(e instanceof IDBDatabase&&!(t in e)&&"string"==typeof t))return;if(w.get(t))return w.get(t);let r=t.replace(/FromIndex$/,""),n=t!==r,i=v.includes(r);if(!(r in(n?IDBIndex:IDBObjectStore).prototype)||!(i||y.includes(r)))return;let s=async function(e,...t){let s=this.transaction(e,i?"readwrite":"readonly"),a=s.store;return n&&(a=a.index(t.shift())),(await Promise.all([a[r](...t),i&&s.done]))[0]};return w.set(t,s),s}p={...s=p,get:(e,t,r)=>E(e,t)||s.get(e,t,r),has:(e,t)=>!!E(e,t)||s.has(e,t)};class _{constructor(e){this.container=e}getPlatformInfoString(){return this.container.getProviders().map(e=>{let t;if(t=e.getComponent(),t?.type!=="VERSION")return null;{let t=e.getImmediate();return`${t.library}/${t.version}`}}).filter(e=>e).join(" ")}}let I="@firebase/app",T="0.14.11",b=new o.Vy("@firebase/app"),S="[DEFAULT]",A={[I
1]:"fire-core","@firebase/app-compat":"fire-core-compat","@firebase/analytics":"fire-analytics","@firebase/analytics-compat":"fire-analytics-compat","@firebase/app-check":"fire-app-check","@firebase/app-check-compat":"fire-app-check-compat","@firebase/auth":"fire-auth","@firebase/auth-compat":"fire-auth-compat","@firebase/database":"fire-rtdb","@firebase/data-connect":"fire-data-connect","@firebase/database-compat":"fire-rtdb-compat","@firebase/functions":"fire-fn","@firebase/functions-compat":"fire-fn-compat","@firebase/installations":"fire-iid","@firebase/installations-compat":"fire-iid-compat","@firebase/messaging":"fire-fcm","@firebase/messaging-compat":"fire-fcm-compat","@firebase/performance":"fire-perf","@firebase/performance-compat":"fire-perf-compat","@firebase/remote-config":"fire-rc","@firebase/remote-config-compat":"fire-rc-compat","@firebase/storage":"fire-gcs","@firebase/storage-compat":"fire-gcs-compat","@firebase/firestore":"fire-fst","@firebase/firestore-compat":"fire-fst-compat","@firebase/ai":"fire-vertex","fire-js":"fire-js",firebase:"fire-js-all"},C=new Map,k=new Map,N=new Map;function R(e,t){try{e.container.addComponent(t)}catch(r){b.debug(`Component ${t.name} failed to register with FirebaseApp ${e.name}`,r)}}function D(e){let t=e.name;if(N.has(t))return b.debug(`There were multiple attempts to register component ${t}.`),!1;for(let r of(N.set(t,e),C.values()))R(r,e);for(let t of k.values())R(t,e);return!0}function O(e,t){let r=e.container.getProvider("heartbeat").getImmediate({optional:!0});return r&&r.triggerHeartbeat(),e.container.getProvider(t)}function P(e){return null!=e&&void 0!==e.settings}let L=new l.FA("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.","invali
1d-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 x{constructor(e,t,r){this._isDeleted=!1,this._options={...e},this._config={...t},this._name=t.name,this._automaticDataCollectionEnabled=t.automaticDataCollectionEnabled,this._container=r,this.container.addComponent(new a.uA("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 L.create("app-deleted",{appName:this._name})}}let M="12.12.0";function U(e,t={}){let r=e;"object"!=typeof t&&(t={name:t});let n={name:S,automaticDataCollectionEnabled:!0,...t},i=n.name;if("string"!=typeof i||!i)throw L.create("bad-app-name",{appName:String(i)});if(r||(r=(0,l.T9)()),!r)throw L.create("no-options");let s=C.get(i);if(s)if((0,l.bD)(r,s.options)&&(0,l.bD)(n,s.config))return s;else throw L.create("duplicate-app",{appName:i});let o=new a.h1(i);for(let e of N.values())o.addComponent(e);let u=new x(r,n,o);return C.set(i,u),u}function V(e=S){let t=C.get(e);if(!t&&e===S&&(0,l.T9)())return U();if(!t)throw L.create("no-app",{appName:e});return t}function F(){return Array.from(C.values())}function j(e,t,r){let n=A[e]??e;r&&(n+=`-${r}`);let i=n.match(/\s|\//),s=t.match(/\s|\//);if(i||s){let e=[`Unable to register library "${n}" with version "${t}":`];i&&e.push(`library name "${n}" contains illegal characters (whitespace or "/")`),i&&s&&e.push("and"),s&&e.push(`version name "${t}" contains illegal characters (whitespace or "/")`),b.warn(e.join(" "));return}D(new a.uA(`${n}-version`,()=>({library:n,version:t}),"VERSION"))}let B="firebase-heartbeat-store",q=null;function $(){return q||(q=(function(e,{blocked:t,upgrade:r,blocking:n,terminated:i}={}){let s=indexedDB.open(e,1),a=m(s);return r&&s.addEventListener("upgradeneeded",e=>{r(m(s.result),e.oldVersion,e.newVersion,m(s.transaction),e)}),t&&s.addEventListener("blocked",e=>t(e.oldVersion,e.newVersion,e)),a.then(e=>{i&&e.addEventListener("close",()=>i()),n&&e.addEventListener("versionchange",e=>n(e.oldVersion,e.newVersion,e))}).catch(()=>{}),a})("firebase-heartbeat-database",{upgrade:(e,t)=>{if(0===t)try{e.createObjectStore(B)}catch(e){console.warn(e)}}}).catch(e=>{throw L.create("idb-open",{originalErrorMessage:e.message})})),q}async function z(e){try{let t=(await $()).transaction(B),r=await t.objectStore(B).get(H(e));return await t.done,r}catch(e){if(e instanceof l.g)b.warn(e.message);else{let t=L.create("idb-get",{originalErrorMessage:e?.message});b.warn(t.message)}}}async function K(e,t){try{let r=(await $()).transaction(B,"readwrite"),n=r.objectStore(B);await n.put(t,H(e)),await r.done}catch(e){if(e instanceof l.g)b.warn(e.message);else{let t=L.create("idb-set",{originalErrorMessage:e?.message});b.warn(t.message)}}}function H(e){return`${e.name}!${e.options.appId}`}class G{constructor(e){this.container=e,this._heartbeatsCache=null;const t=this.container.getProvider("app").getImmediate();this._storage=new Q(t),this._heartbeatsCachePromise=this._storage.read().then(e=>(this._heartbeatsCache=e,e))}async triggerHeartbeat(){try{let e=this.container.getProvider("platform-logger").getImmediate().getPlatformInfoString(),t=W();if(this._heartbeatsCache?.heartbeats==null&&(this._heartbeatsCache=await this._heartbeatsCachePromise,this._heartbeatsCache?.heartbeats==null)||this._heartbeatsCache.lastSentHeartbeatDate===t||this._heartbeatsCache.heartbeats.some(e=>e.date===t))return;if(this._heartbeatsCache.heartbeats.push({date:t,agent:e}),this._heartbeatsCache.heartbeats.length>30){let e=function(e){if(0===e.length)return -1;let t=0,r=e[0].date;for(let n=1;n<e.length;n++)e[n].date<r&&(r=e[n].date,t=n);return t}(this._heartbeatsCache.heartbeats);this._heartbeatsCache.heartbeats.splice(e,1)}return this._storage.overwrite(this._heartbeatsCache)}catch(e){b.warn(e)}}async getHeartbeatsHeader(){try{if(null===this._heartbeatsCache&&await this._heartbeatsCachePromise,this._heartbeatsCache?.heartbeats==null||0===this._heartbeatsCache.heartbeats.length)return"";let e=W(),{heartbeatsToSend:t,unsentEntries:r}=function(e,t=1024){let r=[],n=e.slice();for(let i of e){let e=r.find(e=>e.agent===i.agent);if(e){if(e.dates.push(i.date),J(r)>t){e.dates.pop();break}}else if(r.push({agent:i.agent,dates:[i.date]}),J(r)>t){r.pop();break}n=n.slice(1)}return{heartbeatsToSend:r,unsentEntries:n}}(this._heartbeatsCache.heartbeats),n=(0,l.Uj)(JSON.stringify({version:2,heartbeats:t}));return this._heartbeatsCache.lastSentHeartbeatDate=e,r.length>0?(this._heartbeatsCache.heartbeats=r,await this._storage.overwrite(this._heartbeatsCache)):(this._heartbeatsCache.heartbeats=[],this._storage.overwrite(this._heartbeatsCache)),n}catch(e){return b.warn(e),""}}}function W(){return new Date().toISOString().substring(0,10)}class Q{constructor(e){this.app=e,this._canUseIndexedDBPromise=this.runIndexedDBEnvironmentCheck()}async runIndexedDBEnvironmentCheck(){return!!(0,l.zW)()&&(0,l.eX)().then(()=>!0).catch(()=>!1)}async read(){if(!await this._canUseIndexedDBPromise)return{heartbeats:[]};{let e=await z(this.app);return e?.heartbeats?e:{heartbeats:[]}}}async overwrite(e){if(await this._canUseIndexedDBPromise){let t=await this.read();return K(this.app,{lastSentHeartbeatDate:e.lastSentHeartbeatDate??t.lastSentHeartbeatDate,heartbeats:e.heartbeats})}}async add(e){if(await this._canUseIndexedDBPromise){let t=await this.read();return K(this.app,{lastSentHeartbeatDate:e.lastSentHeartbeatDate??t.lastSentHeartbeatDate,heartbeats:[...t.heartbeats,...e.heartbeats]})}}}function J(e){return(0,l.Uj)(JSON.stringify({version:2,heartbeats:e})).length}D(new a.uA("platform-logger",e=>new _(e),"PRIVATE")),D(new a.uA("heartbeat",e=>new G(e),"PRIVATE")),j(I,T,""),j(I,T,"esm2020"),j("fire-js","")},39540:(e,t,r)=>{"use strict";r.d(t,{As:()=>v,OJ:()=>m});var n=r(37876),i=r(14232),s=r(16042),a=r(88036),o=r(55656),l=r(15137),u=r(54476),h=r(84317);let c=(0,i.createContext)({authUser:null,userProfile:null,user:null,loading:!0,error:null,isLoggedIn:!1,login:async()=>null,register:async()=>"auth/unknown",loginGoogle:async()=>"auth/unknown",resetPassword:async()=>"auth/unknown",changePassword:async()=>"auth/unknown",refreshProfile:async()=>{},logout:async()=>{}});async function d(e){var t;let r=await y((0,o.x7)((0,o.H9)(h.db,"users",e.uid)),1e4,"firestore/profile-timeout");if(!r.exists())throw Error("firestore/profile-missing");return t=r.data(),{...(0,u.$N)(t),id:e.uid,uid:e.uid,email:"string"==typeof t.email?t.email:e.email||"",displayName:"string"==typeof t.displayName?t.dis
1playName:e.displayName||e.email||"User",name:"string"==typeof t.displayName?t.displayName:e.displayName||e.email||"User",photoURL:"string"==typeof t.photoURL?t.photoURL:e.photoURL,status:(0,l.SP)(t.status),role:(0,l.GY)(t.role,t.roleCodes),permissions:Array.isArray(t.permissions)?t.permissions:void 0,permissionOverrides:t.permissionOverrides&&"object"==typeof t.permissionOverrides?t.permissionOverrides:void 0,departmentId:"string"==typeof t.departmentId?t.departmentId:null,positionId:"string"==typeof t.positionId?t.positionId:null,organizationId:"string"==typeof t.organizationId?t.organizationId:null,dealerId:"string"==typeof t.dealerId?t.dealerId:null,dealer:"string"==typeof t.dealerId?t.dealerId:"",siteName:"",siteIds:Array.isArray(t.siteIds)?t.siteIds.filter(e=>"string"==typeof e):[],createdAt:t.createdAt??null,updatedAt:t.updatedAt??null,approvedAt:t.approvedAt,approvedBy:"string"==typeof t.approvedBy?t.approvedBy:null,suspendedAt:t.suspendedAt,suspendedBy:"string"==typeof t.suspendedBy?t.suspendedBy:null,lastLoginAt:t.lastLoginAt}}async function f(e){await y((0,o.BN)((0,o.H9)(h.db,"users",e.uid),{uid:e.uid,email:e.email?.trim().toLowerCase()||"",displayName:e.displayName?.trim()||e.email||"User",photoURL:e.photoURL||null,status:"PENDING",role:"STAFF",departmentId:null,positionId:null,organizationId:null,permissions:[],permissionOverrides:{},siteIds:[],createdAt:(0,o.O5)(),createdBy:e.uid,updatedAt:(0,o.O5)(),updatedBy:e.uid}),15e3,"firestore/timeout")}function p(){return Object.assign(Error("The authenticated account changed during sign-in."),{code:"auth/account-switch-mismatch"})}function m({children:e}){let[t,r]=(0,i.useState)(null),[s,l]=(0,i.useState)(null),[u,v]=(0,i.useState)(!0),[w,E]=(0,i.useState)(null);(0,i.useEffect)(()=>{let e=!0,t=(0,a.hg)(h.j,async t=>{if(v(!0),E(null),!t){e&&!h.j.currentUser&&(r(null),l(null),v(!1));return}let n=()=>h.j.currentUser?.uid===t.uid;try{if(t.providerData.some(e=>"password"===e.providerId)&&!t.emailVerified)throw await (0,a.CI)(h.j),Error("auth/email-not-verified");let i=await d(t);e&&n()&&(r(t),l(i))}catch(i){e&&n()&&(r(t),l(null),E(i instanceof Error?i.message:"firestore/profile-error"))}finally{e&&n()&&v(!1)}});return()=>{e=!1,t()}},[]);let _=async(e,t)=>{v(!0),E(null);try{let n=await y((0,a.x9)(h.j,e.trim().toLowerCase(),t),15e3,"auth/timeout"),i=await d(n.user);if("ACTIVE"!==i.status)return await (0,a.CI)(h.j),i.status;if(!n.user.emailVerified)return await (0,a.gA)(n.user),await (0,a.CI)(h.j),"UNVERIFIED";return r(n.user),l(i),(0,o.mZ)((0,o.H9)(h.db,"users",n.user.uid),{lastLoginAt:(0,o.O5)()}).catch(()=>{}),"ACTIVE"}catch(t){let e=g(t);return E(e),e}finally{v(!1)}},I=async(e,t,r)=>{let n=null;try{return n=(await y((0,a.eJ)(h.j,t.trim().toLowerCase(),r),15e3,"auth/timeout")).user,await (0,a.r7)(n,{displayName:e.trim()}),await f(n),await (0,a.gA)(n),await (0,a.CI)(h.j),null}catch(e){if(n)try{await (0,a.hG)(n)}catch{}return g(e)}},T=async()=>{v(!0),E(null);try{let e,t=await (0,a.df)(h.j,h.h,a.hk),n=()=>h.j.currentUser?.uid===t.user.uid;if(!n())throw p();try{e=await d(t.user)}catch(r){if(!(r instanceof Error)||"firestore/profile-missing"!==r.message)throw r;if(!n()||(await f(t.user),!n()))throw p();e=await d(t.user)}if(!n())throw p();if("ACTIVE"!==e.status)return await (0,a.CI)(h.j),`account/${e.status.toLowerCase()}`;return r(t.user),l(e),null}catch(t){let e=g(t);return E(e),e}finally{v(!1)}},b=async()=>{v(!0);try{await (0,a.CI)(h.j)}finally{r(null),l(null),E(null),v(!1)}},S=async()=>{let e=h.j.currentUser;if(!e)return;let t=await d(e);h.j.currentUser?.uid===e.uid&&l(t)},A=async e=>{try{return await (0,a.J1)(h.j,e.trim().toLowerCase()),null}catch(t){let e=g(t);return"auth/invalid-email"===e?e:null}},C=async(e,t)=>{let r=h.j.currentUser;if(!r?.email||!r.providerData.some(e=>"password"===e.providerId))return"auth/requires-password-provider";try{let n=a.IX.credential(r.email,e);return await (0,a.kZ)(r,n),await (0,a.f3)(r,t),null}catch(e){return g(e)}},k=(0,i.useMemo)(()=>({authUser:t,userProfile:s,user:s,loading:u,error:w,isLoggedIn:s?.status==="ACTIVE",login:_,register:I,loginGoogle:T,resetPassword:A,changePassword:C,refreshProfile:S,logout:b}),[t,s,u,w]);return(0,n.jsx)(c.Provider,{value:k,children:e})}function g(e){return e&&"object"==typeof e&&"code"in e&&"string"==typeof e.code?e.code:e instanceof s.g?e.code:e instanceof Error?e.message:"auth/unknown"}
1function y(e,t,r){return Promise.race([e,new Promise((e,n)=>window.setTimeout(()=>n(Object.assign(Error(r),{code:r})),t))])}let v=()=>(0,i.useContext)(c)},46074:e=>{"use strict";let t=new Set(["/login","/register"]);function r(e,n="/"){if("string"!=typeof e||!e.startsWith("/")||e.startsWith("//")||/[\\\u0000-\u001f\u007f]/.test(e))return n;try{let r=new URL(e,"https://bes-os.invalid");if("https://bes-os.invalid"!==r.origin||t.has(r.pathname)||r.pathname.startsWith("/liff/"))return n;return`${r.pathname}${r.search}${r.hash}`}catch{return n}}e.exports={loginUrlForPath:function(e){let t=r(e);return`/login?next=${encodeURIComponent(t)}`},safeInternalRedirect:r}},50386:(e,t,r)=>{"use strict";r.d(t,{kL:()=>s});var n=r(15137);let i=[{path:"/",permission:"dashboard.view"},{path:"/profile",permission:"profile.view",navigation:!1},{path:"/users",permission:"users.view"},{path:"/website-access",permission:"users.approve",policy:"WEBSITE_ACCESS_MANAGEMENT"},{path:"/customer-approvals",permission:"users.approve",policy:"WEBSITE_ACCESS_MANAGEMENT"},{path:"/audit-logs",permission:"audit.view"},{path:"/settings",permission:"settings.view"},{path:"/reports",permission:"reports.view"},{path:"/stock",permission:"stock.view"},{path:"/stock/audit",permission:"stock.view",allOf:["stock.view","audit.view"]},{path:"/stock/qc",permission:"stock.qc"},{path:"/stock/approvals",permission:"stock.approve",anyOf:["stock.approve","stock.post"]},{path:"/stock/alerts",permission:"alerts.view"},{path:"/stock/reconciliation",permission:"stock.manage"},{path:"/purchasing",permission:"procurement.view"},{path:"/rental",permission:"rental.view"},{path:"/service",permission:"service.view"},{path:"/crm",permission:"crm.view"},{path:"/customers",permission:"customer.view"},{path:"/equipment",permission:"asset.view"},{path:"/product-mappings",permission:"customer.import.review"},{path:"/customer-import-review",permission:"customer.import.review"},{path:"/data-quality-review",permission:"customer.import.review",policy:"ADMIN_ONLY"},{path:"/dealer",permission:"dealer.view"},{path:"/sites",permission:"customer.view"},{path:"/site",permission:"customer.view",navigation:!1},{path:"/device",permission:"devices.view"},{path:"/finance",permission:"finance.view"},{path:"/erp",permission:"finance.view"},{path:"/revenue",permission:"finance.view"},{path:"/marketing-ai",permission:"marketing.view"},{path:"/hr",permission:"hr.view"},{path:"/knowledge",permission:"knowledge.view"},{path:"/workflow",permission:"workflow.view"},{path:"/integrations",permission:"integrations.view"},{path:"/iot",permission:"iot.view"},{path:"/alerts",permission:"alerts.view"},{path:"/map",permission:"map.view"},{path:"/sales-page",permission:"sales.view"},{path:"/assets",permission:"assets.view"},{path:"/chatbot",permission:"chatbot.view"}];function s(e,t){let r=i.filter(({path:e})=>"/"===e?"/"===t:t===e||t.startsWith(`${e}/`)).sort((e,t)=>t.path.length-e.path.length)[0]??null;return!!r&&("WEBSITE_ACCESS_MANAGEMENT"===r.policy?(0,n.T5)(e):"ADMIN_ONLY"===r.policy?!!(e&&("ADMIN"===e.role||"SUPER_ADMIN"===e.role)&&(0,n._m)(e,r.permission)):r.anyOf?r.anyOf.some(t=>(0,n._m)(e,t)):r.allOf?r.allOf.every(t=>(0,n._m)(e,t)):(0,n._m)(e,r.permission))}},51678:()=>{},54476:(e,t,r)=>{"use strict";r.d(t,{$N:()=>w,Kt:()=>v});var n=r(825);let i=["SERVICE","STOCK","PRODUCTS","FINANCE","SALES","MARKETING","MANAGEMENT"],s=["HEAD","STAFF"],a=["dashboard.view","profile.view"],o=[],l=n.S_.filter(e=>"workflow.products.master.manageCost"!==e),u={SERVICE:{HEAD:["service.view","service.request","service.triage","service.assign","service.work","service.review","service.complete","service.cancel","service.admin","workflow.service.assignment.view","workflow.service.assignment.assign","workflow.service.assignment.requestSelf","workflow.service.assignment.approve","workflow.service.assignment.reject","workflow.service.work.start","workflow.service.work.submitReview","workflow.service.work.approveComplete"],STAFF:["workflow.service.assignment.view","workflow.service.assignment.requestSelf","workflow.service.work.start","workflow.service.work.submitReview"]},STOCK:{HEAD:["stock.view","stock.receive","stock.qc","stock.issue","stock.transfer","stock.adjust","stock.count","stock.approve","stock.post","stock.manage","stock.export","workflow.stock.document.create","workflow.stock.document.editDraft","workflow.stock.document.submit","workflow.stock.assignment.assign","workflow.stock.assignment.requestSelf","workflow.stock.assignment.approve","workflow.stock.assignment.reject","workflow.stock.qc.inspect","workflow.stock.qc.decide","workflow.stock.document.approve","workflow.stock.document.reject","workflow.stock.document.post","workflow.stock.adjustment.approve","workflow.stock.adjustment.post","workflow.stock.count.record","workflow.stock.count.approve","workflow.procurement.pr.create","workflow.procurement.pr.editDraft","workflow.procurement.pr.submit","workflow.procurement.pr.approve","workflow.procurement.pr.reject","workflow.procurement.pr.cancel","workflow.procurement.pr.convert","workflow.procurement.po.create","workflow.procurement.po.editDraft","workflow.procurement.po.submit","workflow.procurement.po.approveWithinLim
1it","workflow.procurement.po.reject","workflow.procurement.po.cancel","workflow.procurement.po.receiveHandoff"],STAFF:["workflow.stock.document.create","workflow.stock.document.editDraft","workflow.stock.document.submit","workflow.stock.assignment.requestSelf","workflow.stock.count.record","workflow.procurement.pr.create","workflow.procurement.pr.editDraft","workflow.procurement.pr.submit","workflow.procurement.pr.cancel","workflow.procurement.pr.convert","workflow.procurement.po.create","workflow.procurement.po.editDraft","workflow.procurement.po.submit","workflow.procurement.po.cancel","workflow.procurement.po.receiveHandoff"]},PRODUCTS:{HEAD:[...n.Au,...l],STAFF:l},FINANCE:{HEAD:o,STAFF:o},SALES:{HEAD:o,STAFF:o},MARKETING:{HEAD:o,STAFF:o},MANAGEMENT:{HEAD:o,STAFF:o}},h=/^[A-Za-z0-9][A-Za-z0-9._-]{1,63}$/,c=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/,d=["INTERNAL","ADMIN","CUSTOMER"],f="ACTIVE";function p(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}function m(e){if("number"==typeof e)return Number.isFinite(e)?e:null;if("string"==typeof e){let t=Date.parse(e);return Number.isFinite(t)?t:null}if(e instanceof Date){let t=e.getTime();return Number.isFinite(t)?t:null}if(!p(e))return null;if("function"==typeof e.toMillis)try{let t=e.toMillis();return"number"==typeof t&&Number.isFinite(t)?t:null}catch{return null}if("number"==typeof e.seconds&&Number.isFinite(e.seconds)){let t="number"==typeof e.nanoseconds&&Number.isFinite(e.nanoseconds)?e.nanoseconds:0;return 1e3*e.seconds+t/1e6}return null}function g(e,t,r,n){let i=[...new Set(t)].sort(),s=[...r].sort((e,t)=>e.code.localeCompare(t.code)||e.path.localeCompare(t.path));return{valid:e,permissions:i,permissionHash:function(e){let t=0x811c9dc5,r=e.join("\n");for(let e=0;e<r.length;e+=1)t^=r.charCodeAt(e),t=Math.imul(t,0x1000193);return`fnv1a32:${(t>>>0).toString(16).padStart(8,"0")}`}(i),diagnostics:s,normalizedProfile:n}}function y(e,t,r){if(!Array.isArray(e)||e.length>r)return{valid:!1,values:[],duplicate:!1};let n=[];for(let r of e){if("string"!=typeof r||r!==r.trim()||!r||(t?!t.has(r):!c.test(r)))return{valid:!1,values:[],duplicate:!1};n.push(r)}let i=[...new Set(n)].sort();return{valid:!0,values:i,duplicate:i.length!==n.length}}function v(e,t={}){let r=[];if(!p(e))return g(!1,[],[{code:"PROFILE_NOT_OBJECT",path:"profile"}],null);if(2!==e.accessModelVersion)return g(!1,[],[{code:"UNSUPPORTED_ACCESS_MODEL_VERSION",path:"accessModelVersion"}],null);let o=e.status;"string"==typeof o&&["PENDING","ACTIVE","SUSPENDED","DISABLED"].includes(o)?o!==f&&r.push({code:"INACTIVE_STATUS",path:"status"}):r.push({code:"INVALID_STATUS",path:"status"});let l="string"==typeof e.principalType&&d.includes(e.principalType)?e.principalType:null;l||r.push({code:"INVALID_PRINCIPAL_TYPE",path:"principalType"});let c="string"==typeof e.organizationId&&e.organizationId===e.organizationId.trim()&&h.test(e.organizationId)?e.organizationId:null;c||r.push({code:"INVALID_ORGANIZATION",path:"organizationId"});let w="string"==typeof e.position&&s.includes(e.position)?e.position:null===e.position?null:void 0;void 0===w&&r.push({code:"INVALID_POSITION",path:"position"});let E=y(e.departments,new Set(i),i.length);E.valid||r.push({code:"INVALID_DEPARTMENTS",path:"departments"}),E.duplicate&&r.push({code:"DUPLICATE_DEPARTMENTS_NORMALIZED",path:"departments"});let _=y(e.authorizedCustomerIds,null,100);_.valid||r.push({code:"INVALID_CUSTOMER_SCOPE",path:"authorizedCustomerIds"}),_.duplicate&&r.push({code:"DUPLICATE_CUSTOMER_SCOPE_NORMALIZED",path:"authorizedCustomerIds"});let I="number"==typeof e.accessVersion&&Number.isSafeInteger(e.accessVersion)&&e.accessVersion>=1?e.accessVersion:null;null===I&&r.push({code:"INVALID_ACCESS_VERSION",path:"accessVersion"}),Array.isArray(e.permissionExceptions)||r.push({code:"INVALID_PERMISSION_EXCEPTION",path:"permissionExceptions"}),"INTERNAL"===l?(null===w||0===E.values.length||_.values.length>0)&&r.push({code:0===E.values.length?"EMPTY_INTERNAL_DEPARTMENTS":"PRINCIPAL_COMBINATION_INVALID",path:"principalType"}):("ADMIN"===l||"CUSTOMER"===l)&&(null!==w||E.values.length>0||"ADMIN"===l&&_.values.length>
10)&&r.push({code:"PRINCIPAL_COMBINATION_INVALID",path:"principalType"});let T=new Set(["INVALID_STATUS","INACTIVE_STATUS","INVALID_PRINCIPAL_TYPE","INVALID_ORGANIZATION","INVALID_POSITION","INVALID_DEPARTMENTS","EMPTY_INTERNAL_DEPARTMENTS","PRINCIPAL_COMBINATION_INVALID","INVALID_ACCESS_VERSION","INVALID_CUSTOMER_SCOPE"]);if(!l||!c||null===I||r.some(e=>T.has(e.code)))return g(!1,[],r,null);let b={accessModelVersion:2,principalType:l,position:w,departments:E.values,organizationId:c,authorizedCustomerIds:_.values,status:f,accessVersion:I},S=new Set;"ADMIN"===l?n.G3.forEach(e=>S.add(e)):"INTERNAL"===l&&(a.forEach(e=>S.add(e)),b.departments.forEach(e=>{u[e][b.position].forEach(e=>S.add(e))}));let A=t.now instanceof Date?t.now.getTime():t.now??Date.now();return!function(e,t,r,i,s){if(!Array.isArray(e))return i.push({code:"INVALID_PERMISSION_EXCEPTION",path:"permissionExceptions"});let a=e.length>20;a&&i.push({code:"TOO_MANY_PERMISSION_EXCEPTIONS",path:"permissionExceptions"});let o=e.map((e,t)=>({value:e,inputIndex:t})).sort((e,t)=>{let r=p(e.value)&&"string"==typeof e.value.id?e.value.id:"",n=p(t.value)&&"string"==typeof t.value.id?t.value.id:"";return r.localeCompare(n)||e.inputIndex-t.inputIndex}),l=new Map;o.forEach(({value:e})=>{p(e)&&"string"==typeof e.id&&e.id===e.id.trim()&&e.id.length>0&&l.set(e.id,(l.get(e.id)||0)+1)});let u=new Set;for(let{value:e,inputIndex:h}of o){let o=`permissionExceptions[${h}]`;if(!p(e)){i.push({code:"INVALID_PERMISSION_EXCEPTION",path:o});continue}let c="string"==typeof e.permission&&n.jX.has(e.permission)?e.permission:null;if(!c){i.push({code:"UNKNOWN_EXCEPTION_PERMISSION",path:`${o}.permission`});continue}let d="GRANT"===e.effect||"DENY"===e.effect?e.effect:null,f="string"==typeof e.id&&e.id===e.id.trim()&&e.id.length>0?e.id:null,g=null!==f&&(l.get(f)||0)>1;g&&i.push({code:"DUPLICATE_PERMISSION_EXCEPTION_ID",path:`${o}.id`});let y="string"==typeof e.reason&&e.reason.trim().length>0,v="string"==typeof e.approvedBy&&e.approvedBy.trim().length>0,w=m(e.approvedAt),E=m(e.expiresAt),_=null!==w&&null!==E&&E>w;if(!(!a&&null!==f&&!g&&null!==d&&y&&v&&_)){i.push({code:"INVALID_PERMISSION_EXCEPTION",path:o}),"DENY"===d&&u.add(c);continue}if(E<=s){i.push({code:"EXCEPTION_EXPIRED",path:o});continue}if(w>s){i.push({code:"EXCEPTION_NOT_ACTIVE",path:o});continue}if("DENY"===d){u.add(c);continue}if("CUSTOMER"===t){i.push({code:"CUSTOMER_INTERNAL_GRANT_REJECTED",path:o});continue}r.add(c)}u.forEach(e=>r.delete(e))}(e.permissionExceptions,l,S,r,A),0===r.length&&r.push({code:"ACCESS_V2_VALID",path:"profile"}),g(!0,S,r,b)}function w(e){let t={},r=r=>{Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r])};return r("accessModelVersion"),r("principalType"),r("position"),r("departments"),r("authorizedCustomerIds"),r("accessVersion"),r("permissionExceptions"),t}},55656:(e,t,r)=>{"use strict";r.d(t,{rJ:()=>sy,vN:()=>sf,H9:()=>sv,x7:()=>ai,GG:()=>as,aU:()=>sT,P:()=>s6,O5:()=>sJ,BN:()=>aa,mZ:()=>ao,_M:()=>s5});var n,i,s,a,o,l,u,h,c,d,f,p,m,g,y=r(36672),v=r(21610),w=r(76653),E="u">typeof globalThis?globalThis:"u">typeof window?window:"u">typeof global?global:"u">typeof self?self:{},_={};(function(){function e(){this.blockSize=-1,this.blockSize=64,this.g=[,,,,],this.C=Array(this.blockSize),this.o=this.h=0,this.u()}var t=function(){this.blockSize=-1};function r(){}function s(e,t,r){r||(r=0);let n=Array(16);if("string"==typeof t)for(var i=0;i<16;++i)n[i]=t.charCodeAt(r++)|t.charCodeAt(r++)<<8|t.charCodeAt(r++)<<16|t.charCodeAt(r++)<<24;else for(i=0;i<16;++i)n[i]=t[r++]|t[r++]<<8|t[r++]<<16|t[r++]<<24;t=e.g[0],r=e.g[1],i=e.g[2];let s=e.g[3],a;a=t+(s^r&(i^s))+n[0]+0xd76aa478|0,a=s+(i^(t=r+(a<<7|a>>>25))&(r^i))+n[1]+0xe8c7b756|0,a=i+(r^(s=t+(a<<12|a>>>20))&(t^r))+n[2]+0x242070db|0,a=r+(t^(i=s+(a<<17|a>>>15))&(s^t))+n[3]+0xc1bdceee|0,a=t+(s^(r=i+(a<<22|a>>>10))&(i^s))+n[4]+0xf57c0faf|0,a=s+(i^(t=r+(a<<7|a>>>25))&(r^i))+n[5]+0x4787c62a|0,a=i+(r^(s=t+(a<<12|a>>>20))&(t^r))+n[6]+0xa8304613|0,a=r+(t^(i=s+(a<<17|a>>>15))&(s^t))+n[7]+0xfd469501|0,a=t+(s^(r=i+(a<<22|a>>>10))&(i^s))+n[8]+0x698098d8|0,a=s+(i^(t=r+(a<<7|a>>>25))&(r^i))+n[9]+0x8b44f7af|0,a=i+(r^(s=t+(a<<12|a>>>20))&(t^r))+n[10]+0xffff5bb1|0,a=r+(t^(i=s+(a<<17|a>>>15))&(s^t))+n[11]+0x895cd7be|0,a=t+(s^(r=i+(a<<22|a>>>10))&(i^s))+n[12]+0x6b901122|0,a=s+(i^(t=r+(a<<7|a>>>25))&(r^i))+n[13]+0xfd987193|0,a=i+(r^(s=t+(a<<12|a>>>20))&(t^r))+n[14]+0xa679438e|0,a=r+(t^(i=s+(a<<17|a>>>15))&(s^t))+n[15]+0x49b40821|0,r=i+(a<<22|a>>>10),a=t+(i^s&(r^i))+n[1]+0xf61e2562|0,t=r+(a<<5|a>>>27),a=s+(r^i&(t^r))+n[6]+0xc040b340|0,s=t+(a<<9|a>>>23),a=i+(t^r&(s^t))+n[11]+0x265e5a51|0,i=s+(a<<14|a>>>18),a=r+(s^t&(i^s))+n[0]+0xe9b6c7aa|0,r=i+(a<<20|a>>>12),a=t+(i^s&(r^i))+n[5]+0xd62f105d|0,t=r+(a<<5|a>>>27),a=s+(r^i&(t^r))+n[10]+0x2441453|0,s=t+(a<<9|a>>>23),a=i+(t^r&(s^t))+n[15]+0xd8a1e681|0,i=s+(a<<14|a>>>18),a=r+(s^t&(i^s))+n[4]+0xe7d3fbc8|0,r=i+(a<<20|a>>>12),a=t+(i^s&(r^i))+n[9]+0x21e1cde6|0,t=r+(a<<5|a>>>27),a=s+(r^i&(t^r))+n[14]+0xc33707d6|0,s=t+(a<<9|a>>>23),a=i+(t^r&(s^t))+n[3]+0xf4d50d87|0,i=s+(a<<14|a>>>18),a=r+(s^t&(i^s))+n[8]+0x455a14ed|0,r=i+(a<<20|a>>>12),a=t+(i^s&(r^i))+n[13]+0xa9e3e905|0,t=r+(a<<5|a>>>27),a=s+(r^i&(t^r))+n[2]+0xfcefa3f8|0,s=t+(a<<9|a>>>23),a=i+(t^r&(s^t))+n[7]+0x676f02d9|0,i=s+(a<<14|a>>>18),a=r+(s^t&(i^s))+n[12]+0x8d2a4c8a|0,a=t+((r=i+(a<<20|a>>>
112))^i^s)+n[5]+0xfffa3942|0,a=s+((t=r+(a<<4|a>>>28))^r^i)+n[8]+0x8771f681|0,a=i+((s=t+(a<<11|a>>>21))^t^r)+n[11]+0x6d9d6122|0,a=r+((i=s+(a<<16|a>>>16))^s^t)+n[14]+0xfde5380c|0,a=t+((r=i+(a<<23|a>>>9))^i^s)+n[1]+0xa4beea44|0,a=s+((t=r+(a<<4|a>>>28))^r^i)+n[4]+0x4bdecfa9|0,a=i+((s=t+(a<<11|a>>>21))^t^r)+n[7]+0xf6bb4b60|0,a=r+((i=s+(a<<16|a>>>16))^s^t)+n[10]+0xbebfbc70|0,a=t+((r=i+(a<<23|a>>>9))^i^s)+n[13]+0x289b7ec6|0,a=s+((t=r+(a<<4|a>>>28))^r^i)+n[0]+0xeaa127fa|0,a=i+((s=t+(a<<11|a>>>21))^t^r)+n[3]+0xd4ef3085|0,a=r+((i=s+(a<<16|a>>>16))^s^t)+n[6]+0x4881d05|0,a=t+((r=i+(a<<23|a>>>9))^i^s)+n[9]+0xd9d4d039|0,a=s+((t=r+(a<<4|a>>>28))^r^i)+n[12]+0xe6db99e5|0,a=i+((s=t+(a<<11|a>>>21))^t^r)+n[15]+0x1fa27cf8|0,a=r+((i=s+(a<<16|a>>>16))^s^t)+n[2]+0xc4ac5665|0,r=i+(a<<23|a>>>9),a=t+(i^(r|~s))+n[0]+0xf4292244|0,t=r+(a<<6|a>>>26),a=s+(r^(t|~i))+n[7]+0x432aff97|0,s=t+(a<<10|a>>>22),a=i+(t^(s|~r))+n[14]+0xab9423a7|0,i=s+(a<<15|a>>>17),a=r+(s^(i|~t))+n[5]+0xfc93a039|0,r=i+(a<<21|a>>>11),a=t+(i^(r|~s))+n[12]+0x655b59c3|0,t=r+(a<<6|a>>>26),a=s+(r^(t|~i))+n[3]+0x8f0ccc92|0,s=t+(a<<10|a>>>22),a=i+(t^(s|~r))+n[10]+0xffeff47d|0,i=s+(a<<15|a>>>17),a=r+(s^(i|~t))+n[1]+0x85845dd1|0,r=i+(a<<21|a>>>11),a=t+(i^(r|~s))+n[8]+0x6fa87e4f|0,t=r+(a<<6|a>>>26),a=s+(r^(t|~i))+n[15]+0xfe2ce6e0|0,s=t+(a<<10|a>>>22),a=i+(t^(s|~r))+n[6]+0xa3014314|0,i=s+(a<<15|a>>>17),a=r+(s^(i|~t))+n[13]+0x4e0811a1|0,r=i+(a<<21|a>>>11),a=t+(i^(r|~s))+n[4]+0xf7537e82|0,t=r+(a<<6|a>>>26),a=s+(r^(t|~i))+n[11]+0xbd3af235|0,s=t+(a<<10|a>>>22),a=i+(t^(s|~r))+n[2]+0x2ad7d2bb|0,i=s+(a<<15|a>>>17),a=r+(s^(i|~t))+n[9]+0xeb86d391|0,e.g[0]=e.g[0]+t|0,e.g[1]=e.g[1]+(i+(a<<21|a>>>11))|0,e.g[2]=e.g[2]+i|0,e.g[3]=e.g[3]+s|0}function a(e,t){this.h=t;let r=[],n=!0;for(let i=e.length-1;i>=0;i--){let s=0|e[i];n&&s==t||(r[i]=s,n=!1)}this.g=r}r.prototype=t.prototype,e.F=t.prototype,e.prototype=new r,e.prototype.constructor=e,e.D=function(e,r,n){for(var i=Array(arguments.length-2),s=2;s<arguments.length;s++)i[s-2]=arguments[s];return t.prototype[r].apply(e,i)},e.prototype.u=function(){this.g[0]=0x67452301,this.g[1]=0xefcdab89,this.g[2]=0x98badcfe,this.g[3]=0x10325476,this.o=this.h=0},e.prototype.v=function(e,t){void 0===t&&(t=e.length);let r=t-this.blockSize,n=this.C,i=this.h,a=0;for(;a<t;){if(0==i)for(;a<=r;)s(this,e,a),a+=this.blockSize;if("string"==typeof e){for(;a<t;)if(n[i++]=e.charCodeAt(a++),i==this.blockSize){s(this,n),i=0;break}}else for(;a<t;)if(n[i++]=e[a++],i==this.blockSize){s(this,n),i=0;break}}this.h=i,this.o+=t},e.prototype.A=function(){var e=Array((this.h<56?this.blockSize:2*this.blockSize)-this.h);e[0]=128;for(var t=1;t<e.length-8;++t)e[t]=0;t=8*this.o;for(var r=e.length-8;r<e.length;++r)e[r]=255&t,t/=256;for(this.v(e),e=Array(16),t=0,r=0;r<4;++r)for(let n=0;n<32;n+=8)e[t++]=this.g[r]>>>n&255;return e};var o,l={};function u(e){var t;return -128<=e&&e<128?(t=function(e){return new a([0|e],e<0?-1:0)},Object.prototype.hasOwnProperty.call(l,e)?l[e]:l[e]=t(e)):new a([0|e],e<0?-1:0)}function h(e){if(isNaN(e)||!isFinite(e))return c;if(e<0)return g(h(-e));let t=[],r=1;for(let n=0;e>=r;n++)t[n]=e/r|0,r*=0x100000000;return new a(t,0)}var c=u(0),d=u(1),f=u(0x1000000);function p(e){if(0!=e.h)return!1;for(let t=0;t<e.g.length;t++)if(0!=e.g[t])return!1;return!0}function m(e){return -1==e.h}function g(e){let t=e.g.length,r=[];for(let n=0;n<t;n++)r[n]=~e.g[n];return new a(r,~e.h).add(d)}function y(e,t){return e.add(g(t))}function v(e,t){for(;(65535&e[t])!=e[t];)e[t+1]+=e[t]>>>16,e[t]&=65535,t++}function w(e,t){this.g=e,this.h=t}function E(e,t){if(p(t))throw Error("division by zero");if(p(e))return new w(c,c);if(m(e))return t=E(g(e),t),new w(g(t.g),g(t.h));if(m(t))return t=E(e,g(t)),new w(g(t.g),t.h);if(e.g.length>30){if(m(e)||m(t))throw Error("slowDivide_ only works with positive integers.");for(var r=d,n=t;0>=n.l(e);)r=I(r),n=I(n);var i=T(r,1),s=T(n,1);for(n=T(n,2),r=T(r,2);!p(n);){var a=s.add(n);0>=a.l(e)&&(i=i.add(r),s=a),n=T(n,1),r=T(r,1)}return t=y(e,i.j(t)),new w(i,t)}for(i=c;e.l(t)>=0;){for(n=(n=Math.ceil(Math.log(r=Math.max(1,Math.floor(e.m()/t.m())))/Math.LN2))<=48?1:Math.pow(2,n-48),a=(s=h(r)).j(t);m(a)||a.l(e)>0;)r-=n,a=(s=h(r)).j(t);p(s)&&(s=d),i=i.add(s),e=y(e,a)}return new w(i,e)}function I(e){let t=e.g.length+1,r=[];for(let n=0;n<t;n++)r[n]=e.i(n)<<1|e.i(n-1)>>>31;return new a(r,e.h)}function T(e,t){let r=t>>5;t%=32;let n=e.g.length-r,i=[];for(let s=0;s<n;s++)i[s]=t>0?e.i(s+r)>>>t|e.i(s+r+1)<<32-t:e.i(s+r);return new a(i,e.h)}(o=a.prototype).m=function(){if(m(this))return-g(this).m();let e=0,t=1;for(let r=0;r<this.g.length;r++){let n=this.i(r);e+=(n>=0?n:0x100000000+n)*t,t*=0x100000000}return e},o.toString=function(e){if((e=e||10)<2||36<e)throw Error("radix out of range: "+e);if(p(this))return"0";if(m(this))return"-"+g(this).toString(e);let t=h(Math.pow(e,6));var r=this;let n="";for(;;){let i=E(r,t).g,s=(((r=y(r,i.j(t))).g.length>0?r.g[0]:r.h)>>>0).toString(e);if(p(r=i))return s+n;for(;s.length<6;)s="0"+s;n=s+n}},o.i=function(e){return e<0?0:e<this.g.length?this.g[e]:this.h},o.l=function(e){return m(e=y(this,e))?-1:+!p(e)},o.abs=function(){return m(this)?g(this):this},o.add=function(e){let t=Math.max(this.g.length,e.g.length),r=[],n=0;for(let i=0;i<=t;i++){let t=n+(65535&this.i(i))+(65535&e.i(i)),s=(t>>>16)+(this.i(i)>>>16)+(e.i(i)>>>16);n=s>>>16,t&=65535,s&=65535,r[i]=s<<16|t}return new a(r,-0x80000000&r[r.length-1]?-1:0)},o.j=function(e){if(p(this)||p(e))return c;if(m(this))return m(e)?g(this).j(g(e)):g(g(this).j(e));if(m(e))return g(this.j(g(e)));if(0>this.l(f)&&0>e.l(f))return h(this.m()*e.m());let t=this.g.length+e.g.length,r=[];for(var n=0;n<2*t;n++)r[n]=0;for(n=0;n<this.g.length;n++)for(let t=0;t<e.g.length;t++){let i=this.i(n)>>>16,s=65535&this.i(n),a=e.i(t)>>>16,o=65535&e.i(t);r[2*n+2*t]+=s*o,v(r,2*n+2*t),r[2*n+2*t+1]+=i*o,v(r,2*n+2*t+1),r[2*n+2*t+1]+=s*a,v(r,2*n+2*t+1),r[2*n+2*t+2]+=i*a,v(r,2*n+2*t+2)}for(e=0;e<t;e++)r[e]=r[2*e+1]<<16|r[2*e];for(e=t;e<2*t;e++)r[e]=0;return new a(r,0)},o.B=function(e){return E(this,e).h},o.and=function(e){let t=Math.max(this.g.length,e.g.length),r=[];for(let n=0;n<t;n++)r[n]=this.i(n)&e.i(n);return new a(r,this.h&e.h)},o.or=function(e){let t=Math.max(this.g.length,e.g.length),r=[];for(let n=0;n<t;n++)r[n]=this.i(n)|e.i(n);return new a(r,this.h|e.h)},o.xor=function(e){let t=Math.max(this.g.length,e.g.length),r=[];for(let n=0;n<t;n++)r[n]=this.i(n)^e.i(n);return new a(r,this.h^e.h)},e.prototype.digest=e.prototype.A,e.prototype.reset=e.prototype.u,e.prototype.update=e.prototype.v,i=_.Md5=e,a.prototype.add=a.prototype.add,a.prototype.multiply=a.prototype.j,a.prototype.modulo=a.prototype.B,a.prototype.compare=a.prototype.l,a.prototype.toNumber=a.prototype.m,a.prototype.toString=a.prototype.toString,a.prototype.getBits=a.prototype.i,a.fromNumber=h,a.fromString=function e(t,r){if(0==t.length)throw Error("number format error: empty string");if((r=r||10)<2||36<r)throw Error("radix out of range: "+r);if("-"==t.charAt(0))return g(e(t.substring(1),r));if(t.indexOf("-")>=0)throw Error('number format error: interior "-" character');let n=h(Math.pow(r,8)),i=c;for(let e=0;e<t.length;e+=8){var s=Math.min(8,t.length-e);let a=parseInt(t.substring(e,e+s),r);s<8?(s=h(Math.pow(r,s)),i=i.j(s).add(h(a))):i=(i=i.j(n)).add(h(a))}return i},n=_.Integer=a}).apply(void 0!==E?E:"u">typeof self?self:"u">typeof window?window:{});var I=r(29979),T="u">typeof globalThis?globalThis:"u">typeof window?window:"u">typeof global?global:"u">typeof self?self:{},b={};(function(){var e,t,r=Object.defineProperty,n=function(e){e=["object"==typeof globalThis&&globalThis,e,"object"==typeof window&&window,"object"==typeof self&&self,"object"==typeof T&&T];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 i(e,t){if(t)e:{var i=n;e=e.split(".");for(var s=0;s<e.length-1;s++){var a=e[s];if(!(a in i))break e;i=i[a]}(t=t(s=i[e=e[e.length-1]]))!=s&&null!=t&&r(i,e,{configurable:!0,writable:!0,value:t})}}i("Symbol.dispose",function(e){return e||Symbol("Symbol.dispose")}),i("Array.prototype.values",function(e){return e||function(){return this[Symbol.iterator]()}}),i("Object.entries",function(e){return e||function(e){var t,r=[];for(t in e)Object.prototype.hasOwnProperty.call(e,t)&&r.push([t,e[t]]);return r}});var f=f||{},p=this||self;function m(e){var t=typeof e;return"object"==t&&null!=e||"function"==t}function g(e,t,r){return e.call.apply(e.bind,arguments)}function y(e,t,r){return(y=g).apply(null,arguments)}
1function v(e,t){var r=Array.prototype.slice.call(arguments,1);return function(){var t=r.slice();return t.push.apply(t,arguments),e.apply(this,t)}}function w(e,t){function r(){}r.prototype=t.prototype,e.Z=t.prototype,e.prototype=new r,e.prototype.constructor=e,e.Ob=function(e,r,n){for(var i=Array(arguments.length-2),s=2;s<arguments.length;s++)i[s-2]=arguments[s];return t.prototype[r].apply(e,i)}}var E="u">typeof AsyncContext&&"function"==typeof AsyncContext.Snapshot?e=>e&&AsyncContext.Snapshot.wrap(e):e=>e;function _(e){let t=e.length;if(t>0){let r=Array(t);for(let n=0;n<t;n++)r[n]=e[n];return r}return[]}function I(e,t){for(let t=1;t<arguments.length;t++){let n=arguments[t];var r=typeof n;if("array"==(r="object"!=r?r:n?Array.isArray(n)?"array":r:"null")||"object"==r&&"number"==typeof n.length){r=e.length||0;let t=n.length||0;e.length=r+t;for(let i=0;i<t;i++)e[r+i]=n[i]}else e.push(n)}}class S{constructor(e,t){this.i=e,this.j=t,this.h=0,this.g=null}get(){let e;return this.h>0?(this.h--,e=this.g,this.g=e.next,e.next=null):e=this.i(),e}}class A{constructor(){this.h=this.g=null}add(e,t){let r=C.get();r.set(e,t),this.h?this.h.next=r:this.g=r,this.h=r}}var C=new S(()=>new k,e=>e.reset());class k{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 N,R=!1,D=new A,O=()=>{let e=Promise.resolve(void 0);N=()=>{e.then(P)}};function P(){let e;for(var t;e=null,D.g&&(e=D.g,D.g=D.g.next,D.g||(D.h=null),e.next=null),t=e;){try{t.h.call(t.g)}catch(e){!function(e){p.setTimeout(()=>{throw e},0)}(e)}C.j(t),C.h<100&&(C.h++,t.next=C.g,C.g=t)}R=!1}function L(){this.u=this.u,this.C=this.C}function x(e,t){this.type=e,this.g=this.target=t,this.defaultPrevented=!1}L.prototype.u=!1,L.prototype.dispose=function(){this.u||(this.u=!0,this.N())},L.prototype[Symbol.dispose]=function(){this.dispose()},L.prototype.N=function(){if(this.C)for(;this.C.length;)this.C.shift()()},x.prototype.h=function(){this.defaultPrevented=!0};var M=function(){if(!p.addEventListener||!Object.defineProperty)return!1;var e=!1,t=Object.defineProperty({},"passive",{get:function(){e=!0}});try{let e=()=>{};p.addEventListener("test",e,t),p.removeEventListener("test",e,t)}catch(e){}return e}();function U(e){return/^[\s\xa0]*$/.test(e)}function V(e,t){x.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&&this.init(e,t)}w(V,x),V.prototype.init=function(e,t){let r=this.type=e.type,n=e.changedTouches&&e.changedTouches.length?e.changedTouches[0]:null;this.target=e.target||e.srcElement,this.g=t,(t=e.relatedTarget)||("mouseover"==r?t=e.fromElement:"mouseout"==r&&(t=e.toElement)),this.relatedTarget=t,n?(this.clientX=void 0!==n.clientX?n.clientX:n.pageX,this.clientY=void 0!==n.clientY?n.clientY:n.pageY,this.screenX=n.screenX||0,this.screenY=n.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=e.pointerType,this.state=e.state,this.i=e,e.defaultPrevented&&V.Z.h.call(this)},V.prototype.h=function(){V.Z.h.call(this);let e=this.i;e.preventDefault?e.preventDefault():e.returnValue=!1};var F="closure_listenable_"+(1e6*Math.random()|0),j=0;function B(e,t,r,n,i){this.listener=e,this.proxy=null,this.src=t,this.type=r,this.capture=!!n,this.ha=i,this.key=++j,this.da=this.fa=!1}function q(e){e.da=!0,e.listener=null,e.proxy=null,e.src=null,e.ha=null}function $(e,t,r){for(let n in e)t.call(r,e[n],n,e)}function z(e){let t={};for(let r in e)t[r]=e[r];return t}let K="constructor hasOwnProperty isPrototypeOf propertyIsEnumerable toLocaleString toString valueOf".split(" ");function H(e,t){let r,n;for(let t=1;t<arguments.length;t++){for(r in n=arguments[t])e[r]=n[r];for(let t=0;t<K.length;t++)r=K[t],Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}}function G(e){this.src=e,this.g={},this.h=0}function W(e,t){let r=t.type;if(r in e.g){var n,i=e.g[r],s=Array.prototype.indexOf.call(i,t,void 0);(n=s>=0)&&Array.prototype.splice.call(i,s,1),n&&(q(t),0==e.g[r].length&&(delete e.g[r],e.h--))}}function Q(e,t,r,n){for(let i=0;i<e.length;++i){let s=e[i];if(!s.da&&s.listener==t&&!!r==s.capture&&s.ha==n)return i}return -1}G.prototype.add=function(e,t,r,n,i){let s=e.toString();(e=this.g[s])||(e=this.g[s]=[],this.h++);let a=Q(e,t,n,i);return a>-1?(t=e[a],r||(t.fa=!1)):((t=new B(t,this.src,s,!!n,i)).fa=r,e.push(t)),t};var J="closure_lm_"+(1e6*Math.random()|0),X={};function Y(e,t,r,n,i,s){if(!t)throw Error("Invalid event type");let a=m(i)?!!i.capture:!!i,o=er(e);if(o||(e[J]=o=new G(e)),(r=o.add(t,r,n,a,s)).proxy)return r;if(n=function e(t){return et.call(e.src,e.listener,t)},r.proxy=n,n.src=e,n.listener=r,e.addEventListener)M||(i=a),void 0===i&&(i=!1),e.addEventListener(t.toString(),n,i);else if(e.attachEvent)e.attachEvent(ee(t.toString()),n);else if(e.addListener&&e.removeListener)e.addListener(n);else throw Error("addEventListener and attachEvent are unavailable.");return r}function Z(e){if("number"!=typeof e&&e&&!e.da){var t=e.src;if(t&&t[F])W(t.i,e);else{var r=e.type,n=e.proxy;t.removeEventListener?t.removeEventListener(r,n,e.capture):t.detachEvent?t.detachEvent(ee(r),n):t.addListener&&t.removeListener&&t.removeListener(n),(r=er(t))?(W(r,e),
10==r.h&&(r.src=null,t[J]=null)):q(e)}}}function ee(e){return e in X?X[e]:X[e]="on"+e}function et(e,t){if(e.da)e=!0;else{t=new V(t,this);let r=e.listener,n=e.ha||e.src;e.fa&&Z(e),e=r.call(n,t)}return e}function er(e){return(e=e[J])instanceof G?e:null}var en="__closure_events_fn_"+(1e9*Math.random()>>>0);function ei(e){return"function"==typeof e?e:(e[en]||(e[en]=function(t){return e.handleEvent(t)}),e[en])}function es(){L.call(this),this.i=new G(this),this.M=this,this.G=null}function ea(e,t){let r,n;var i,s=e.G;if(s)for(i=[];s;s=s.G)i.push(s);if(e=e.M,s=t.type||t,"string"==typeof t)t=new x(t,e);else if(t instanceof x)t.target=t.target||e;else{var a=t;H(t=new x(s,e),a)}if(a=!0,i)for(n=i.length-1;n>=0;n--)a=eo(r=t.g=i[n],s,!0,t)&&a;if(a=eo(r=t.g=e,s,!0,t)&&a,a=eo(r,s,!1,t)&&a,i)for(n=0;n<i.length;n++)a=eo(r=t.g=i[n],s,!1,t)&&a}function eo(e,t,r,n){if(!(t=e.i.g[String(t)]))return!0;t=t.concat();let i=!0;for(let s=0;s<t.length;++s){let a=t[s];if(a&&!a.da&&a.capture==r){let t=a.listener,r=a.ha||a.src;a.fa&&W(e.i,a),i=!1!==t.call(r,n)&&i}}return i&&!n.defaultPrevented}w(es,L),es.prototype[F]=!0,es.prototype.removeEventListener=function(e,t,r,n){!function e(t,r,n,i,s){if(Array.isArray(r))for(var a=0;a<r.length;a++)e(t,r[a],n,i,s);else(i=m(i)?!!i.capture:!!i,n=ei(n),t&&t[F])?(t=t.i,(a=String(r).toString())in t.g&&(n=Q(r=t.g[a],n,i,s))>-1&&(q(r[n]),Array.prototype.splice.call(r,n,1),0==r.length&&(delete t.g[a],t.h--))):t&&(t=er(t))&&(r=t.g[r.toString()],t=-1,r&&(t=Q(r,n,i,s)),(n=t>-1?r[t]:null)&&Z(n))}(this,e,t,r,n)},es.prototype.N=function(){if(es.Z.N.call(this),this.i){var e=this.i;for(let t in e.g){let r=e.g[t];for(let e=0;e<r.length;e++)q(r[e]);delete e.g[t],e.h--}}this.G=null},es.prototype.J=function(e,t,r,n){return this.i.add(String(e),t,!1,r,n)},es.prototype.K=function(e,t,r,n){return this.i.add(String(e),t,!0,r,n)};class el extends L{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:function e(t){t.g=function(e,t){if("function"!=typeof e)if(e&&"function"==typeof e.handleEvent)e=y(e.handleEvent,e);else throw Error("Invalid listener argument");return Number(t)>0x7fffffff?-1:p.setTimeout(e,t||0)}(()=>{t.g=null,t.i&&(t.i=!1,e(t))},t.l);let r=t.h;t.h=null,t.m.apply(null,r)}(this)}N(){super.N(),this.g&&(p.clearTimeout(this.g),this.g=null,this.i=!1,this.h=null)}}function eu(e){L.call(this),this.h=e,this.g={}}w(eu,L);var eh=[];function ec(e){$(e.g,function(e,t){this.g.hasOwnProperty(t)&&Z(e)},e),e.g={}}eu.prototype.N=function(){eu.Z.N.call(this),ec(this)},eu.prototype.handleEvent=function(){throw Error("EventHandler.handleEvent not implemented")};var ed=p.JSON.stringify,ef=p.JSON.parse,ep=class{stringify(e){return p.JSON.stringify(e,void 0)}parse(e){return p.JSON.parse(e,void 0)}};function em(){}function eg(){}var ey={OPEN:"a",hb:"b",ERROR:"c",tb:"d"};function ev(){x.call(this,"d")}function ew(){x.call(this,"c")}w(ev,x),w(ew,x);var eE={},e_=null;function eI(){return e_=e_||new es}function eT(e){x.call(this,eE.Ia,e)}function eb(e){let t=eI();ea(t,new eT(t))}function eS(e,t){x.call(this,eE.STAT_EVENT,e),this.stat=t}function eA(e){let t=eI();ea(t,new eS(t,e))}function eC(e,t){x.call(this,eE.Ja,e),this.size=t}function ek(e,t){if("function"!=typeof e)throw Error("Fn must not be null and must be a function");return p.setTimeout(function(){e()},t)}function eN(){this.g=!0}function eR(e,t,r,n){e.info(function(){return"XMLHTTP TEXT ("+t+"): "+function(e,t){if(!e.g)return t;if(!t)return null;try{let s=JSON.parse(t);if(s){for(e=0;e<s.length;e++)if(Array.isArray(s[e])){var r=s[e];if(!(r.length<2)){var n=r[1];if(Array.isArray(n)&&!(n.length<1)){var i=n[0];if("noop"!=i&&"stop"!=i&&"close"!=i)for(let e=1;e<n.length;e++)n[e]=""}}}}return ed(s)}catch(e){return t}}(e,r)+(n?" "+n:"")})}eE.Ia="serverreachability",w(eT,x),eE.STAT_EVENT="statevent",w(eS,x),eE.Ja="timingevent",w(eC,x),eN.prototype.ua=function(){this.g=!1},eN.prototype.info=function(){};var eD={NO_ERROR:0,cb:1,qb:2,pb:3,kb:4,ob:5,rb:6,Ga:7,TIMEOUT:8,ub:9},eO={ib:"complete",Fb:"success",ERROR:"error",Ga:"abort",xb:"ready",yb:"readystatechange",TIMEOUT:"timeout",sb:"incrementaldata",wb:"progress",lb:"downloadprogress",Nb:"uploadprogress"};function eP(){}function eL(e){return encodeURIComponent(String(e))}function ex(e,t,r,n){this.j=e,this.i=t,this.l=r,this.S=n||1,this.V=new eu(this),this.H=45e3,this.J=null,this.o=!1,this.u=this.B=this.A=this.M=this.F=this.T=this.D=null,this.G=[],this.g=null,this.C=0,this.m=this.v=null,this.X=-1,this.K=!1,this.P=0,this.O=null,this.W=this.L=this.U=this.R=!1,this.h=new eM}function eM(){this.i=null,this.g="",this.h=!1}w(eP,em),eP.prototype.g=function(){return new XMLHttpRequest},e=new eP;var eU={},eV={};function eF(e,t,r){e.M=1,e.A=e7(e3(t)),e.u=r,e.R=!0,ej(e,null)}
1function ej(e,t){e.F=Date.now(),eq(e),e.B=e3(e.A);var r,n,i,s,a,o,l=e.B,u=e.S;Array.isArray(u)||(u=[String(u)]),tf(l.i,"t",u),e.C=0,l=e.j.L,e.h=new eM,e.g=tZ(e.j,l?t:null,!e.u),e.P>0&&(e.O=new el(y(e.Y,e,e.g),e.P)),t=e.V,l=e.g,u=e.ba;var h="readystatechange";Array.isArray(h)||(h&&(eh[0]=h.toString()),h=eh);for(let e=0;e<h.length;e++){let r=function e(t,r,n,i,s){if(i&&i.once)return function e(t,r,n,i,s){if(Array.isArray(r)){for(let a=0;a<r.length;a++)e(t,r[a],n,i,s);return null}return n=ei(n),t&&t[F]?t.K(r,n,m(i)?!!i.capture:!!i,s):Y(t,r,n,!0,i,s)}(t,r,n,i,s);if(Array.isArray(r)){for(let a=0;a<r.length;a++)e(t,r[a],n,i,s);return null}return n=ei(n),t&&t[F]?t.J(r,n,m(i)?!!i.capture:!!i,s):Y(t,r,n,!1,i,s)}(l,h[e],u||t.handleEvent,!1,t.h||t);if(!r)break;t.g[r.key]=r}t=e.J?z(e.J):{},e.u?(e.v||(e.v="POST"),t["Content-Type"]="application/x-www-form-urlencoded",e.g.ea(e.B,e.v,e.u,t)):(e.v="GET",e.g.ea(e.B,e.v,null,t)),eb(),r=e.i,n=e.v,i=e.B,s=e.l,a=e.S,o=e.u,r.info(function(){if(r.g)if(o){var e="",t=o.split("&");for(let r=0;r<t.length;r++){var l=t[r].split("=");if(l.length>1){let t=l[0];l=l[1];let r=t.split("_");e=r.length>=2&&"type"==r[1]?e+(t+"=")+l+"&":e+(t+"=redacted&")}}}else e=null;else e=o;return"XMLHTTP REQ ("+s+") [attempt "+a+"]: "+n+"\n"+i+"\n"+e})}function eB(e){return!!e.g&&"GET"==e.v&&2!=e.M&&e.j.Aa}function eq(e){e.T=Date.now()+e.H,e$(e,e.H)}function e$(e,t){if(null!=e.D)throw Error("WatchDog timer not null");e.D=ek(y(e.aa,e),t)}function ez(e){e.D&&(p.clearTimeout(e.D),e.D=null)}function eK(e){0==e.j.I||e.K||tW(e.j,e)}function eH(e){ez(e);var t=e.O;t&&"function"==typeof t.dispose&&t.dispose(),e.O=null,ec(e.V),e.g&&(t=e.g,e.g=null,t.abort(),t.dispose())}function eG(e,t){try{var r=e.j;if(0!=r.I&&(r.g==e||eY(r.h,e))){if(!e.L&&eY(r.h,e)&&3==r.I){try{var n=r.Ba.g.parse(t)}catch(e){n=null}if(Array.isArray(n)&&3==n.length){var i=n;if(0==i[0]){e:if(!r.v){if(r.g)if(r.g.F+3e3<e.F)tG(r),tU(r);else break e;tz(r),eA(18)}}else r.xa=i[1],0<r.xa-r.K&&i[2]<37500&&r.F&&0==r.A&&!r.C&&(r.C=ek(y(r.Va,r),6e3));1>=eX(r.h)&&r.ta&&(r.ta=void 0)}else tJ(r,11)}else if((e.L||r.g==e)&&tG(r),!U(t))for(i=r.Ba.g.parse(t),t=0;t<i.length;t++){let o=i[t],l=o[0];if(!(l<=r.K))if(r.K=l,o=o[1],2==r.I)if("c"==o[0]){r.M=o[1],r.ba=o[2];let t=o[3];null!=t&&(r.ka=t,r.j.info("VER="+r.ka));let i=o[4];null!=i&&(r.za=i,r.j.info("SVER="+r.za));let l=o[5];null!=l&&"number"==typeof l&&l>0&&(r.O=n=1.5*l,r.j.info("backChannelRequestTimeoutMs_="+n)),n=r;let u=e.g;if(u){let e=u.g?u.g.getResponseHeader("X-Client-Wire-Protocol"):null;if(e){var s=n.h;s.g||-1==e.indexOf("spdy")&&-1==e.indexOf("quic")&&-1==e.indexOf("h2")||(s.j=s.l,s.g=new Set,s.h&&(eZ(s,s.h),s.h=null))}if(n.G){let e=u.g?u.g.getResponseHeader("X-HTTP-Session-Id"):null;e&&(n.wa=e,e9(n.J,n.G,e))}}if(r.I=3,r.l&&r.l.ra(),r.aa&&(r.T=Date.now()-e.F,r.j.info("Handshake RTT: "+r.T+"ms")),(n=r).na=tY(n,n.L?n.ba:null,n.W),e.L){e0(n.h,e);var a=n.O;a&&(e.H=a),e.D&&(ez(e),eq(e)),n.g=e}else t$(n);r.i.length>0&&tF(r)}else"stop"!=o[0]&&"close"!=o[0]||tJ(r,7);else 3==r.I&&("stop"==o[0]||"close"==o[0]?"stop"==o[0]?tJ(r,7):tM(r):"noop"!=o[0]&&r.l&&r.l.qa(o),r.A=0)}}eb(4)}catch(e){}}ex.prototype.ba=function(e){e=e.target;let t=this.O;t&&3==tO(e)?t.j():this.Y(e)},ex.prototype.Y=function(e){try{if(e==this.g)e:{let d=tO(this.g),f=this.g.ya(),m=this.g.ca();if(!(d<3)&&(3!=d||this.g&&(this.h.h||this.g.la()||tP(this.g)))){this.K||4!=d||7==f||(8==f||m<=0?eb(3):eb(2)),ez(this);var t=this.g.ca();this.X=t;var r=function(e){if(!eB(e))return e.g.la();let t=tP(e.g);if(""===t)return"";let r="",n=t.length,i=4==tO(e.g);if(!e.h.i){if("u"<typeof TextDecoder)return eH(e),eK(e),"";e.h.i=new p.TextDecoder}for(let s=0;s<n;s++)e.h.h=!0,r+=e.h.i.decode(t[s],{stream:!(i&&s==n-1)});return t.length=0,e.h.g+=r,e.C=0,e.h.g}(this);if(this.o=200==t,n=this.i,i=this.v,s=this.B,a=this.l,o=this.S,n.info(function(){return"XMLHTTP RESP ("+a+") [ attempt "+o+"]: "+i+"\n"+s+"\n"+d+" "+t}),this.o){if(this.U&&!this.L){t:{if(this.g){var n,i,s,a,o,l,u=this.g;if((l=u.g?u.g.getResponseHeader("X-HTTP-Initial-Response"):null)&&!U(l)){var h=l;break t}}h=null}if(e=h)eR(this.i,this.l,e,"Initial handshake response via X-HTTP-Initial-Response"),this.L=!0,eG(this,e);else{this.o=!1,this.m=3,eA(12),eH(this),eK(this);break e}}if(this.R){let t;for(e=!0;!this.K&&this.C<r.length;)if((t=function(e,t){var r=e.C,n=t.indexOf("\n",r);return -1==n?eV:isNaN(r=Number(t.substring(r,n)))?eU:(n+=1)+r>t.length?eV:(t=t.slice(n,n+r),e.C=n+r,t)}(this,r))==eV){4==d&&(this.m=4,eA(14),e=!1),eR(this.i,this.l,null,"[Incomplete Response]");break}
1else if(t==eU){this.m=4,eA(15),eR(this.i,this.l,r,"[Invalid Chunk]"),e=!1;break}else eR(this.i,this.l,t,null),eG(this,t);if(eB(this)&&0!=this.C&&(this.h.g=this.h.g.slice(this.C),this.C=0),4!=d||0!=r.length||this.h.h||(this.m=1,eA(16),e=!1),this.o=this.o&&e,e){if(r.length>0&&!this.W){this.W=!0;var c=this.j;c.g==this&&c.aa&&!c.P&&(c.j.info("Great, no buffering proxy detected. Bytes received: "+r.length),tK(c),c.P=!0,eA(11))}}else eR(this.i,this.l,r,"[Invalid Chunked Response]"),eH(this),eK(this)}else eR(this.i,this.l,r,null),eG(this,r);4==d&&eH(this),this.o&&!this.K&&(4==d?tW(this.j,this):(this.o=!1,eq(this)))}else(function(e){let t={};e=(e.g&&tO(e)>=2&&e.g.getAllResponseHeaders()||"").split("\r\n");for(let n=0;n<e.length;n++){if(U(e[n]))continue;var r=function(e){var t=1;e=e.split(":");let r=[];for(;t>0&&e.length;)r.push(e.shift()),t--;return e.length&&r.push(e.join(":")),r}(e[n]);let i=r[0];if("string"!=typeof(r=r[1]))continue;r=r.trim();let s=t[i]||[];t[i]=s,s.push(r)}var n=function(e){return e.join(", ")};for(let e in t)n.call(void 0,t[e],e,t)})(this.g),400==t&&r.indexOf("Unknown SID")>0?(this.m=3,eA(12)):(this.m=0,eA(13)),eH(this),eK(this)}}}catch(e){}finally{}},ex.prototype.cancel=function(){this.K=!0,eH(this)},ex.prototype.aa=function(){var e,t;this.D=null;let r=Date.now();r-this.T>=0?(e=this.i,t=this.B,e.info(function(){return"TIMEOUT: "+t}),2!=this.M&&(eb(),eA(17)),eH(this),this.m=2,eK(this)):e$(this,this.T-r)};var eW=class{constructor(e,t){this.g=e,this.map=t}};function eQ(e){this.l=e||10,e=p.PerformanceNavigationTiming?(e=p.performance.getEntriesByType("navigation")).length>0&&("hq"==e[0].nextHopProtocol||"h2"==e[0].nextHopProtocol):!!(p.chrome&&p.chrome.loadTimes&&p.chrome.loadTimes()&&p.chrome.loadTimes().wasFetchedViaSpdy),this.j=e?this.l:1,this.g=null,this.j>1&&(this.g=new Set),this.h=null,this.i=[]}function eJ(e){return!!e.h||!!e.g&&e.g.size>=e.j}function eX(e){return e.h?1:e.g?e.g.size:0}function eY(e,t){return e.h?e.h==t:!!e.g&&e.g.has(t)}function eZ(e,t){e.g?e.g.add(t):e.h=t}function e0(e,t){e.h&&e.h==t?e.h=null:e.g&&e.g.has(t)&&e.g.delete(t)}function e1(e){if(null!=e.h)return e.i.concat(e.h.G);if(null!=e.g&&0!==e.g.size){let t=e.i;for(let r of e.g.values())t=t.concat(r.G);return t}return _(e.i)}eQ.prototype.cancel=function(){if(this.i=e1(this),this.h)this.h.cancel(),this.h=null;else if(this.g&&0!==this.g.size){for(let e of this.g.values())e.cancel();this.g.clear()}};var e2=RegExp("^(?:([^:/?#.]+):)?(?://(?:([^\\\\/?#]*)@)?([^\\\\/?#]*?)(?::([0-9]+))?(?=[\\\\/?#]|$))?([^?#]+)?(?:\\?([^#]*))?(?:#([\\s\\S]*))?$");function e6(e){let t;this.g=this.o=this.j="",this.u=null,this.m=this.h="",this.l=!1,e instanceof e6?(this.l=e.l,e5(this,e.j),this.o=e.o,this.g=e.g,e8(this,e.u),this.h=e.h,e4(this,tp(e.i)),this.m=e.m):e&&(t=String(e).match(e2))?(this.l=!1,e5(this,t[1]||"",!0),this.o=te(t[2]||""),this.g=te(t[3]||"",!0),e8(this,t[4]),this.h=te(t[5]||"",!0),e4(this,t[6]||"",!0),this.m=te(t[7]||"")):(this.l=!1,this.i=new tl(null,this.l))}function e3(e){return new e6(e)}function e5(e,t,r){e.j=r?te(t,!0):t,e.j&&(e.j=e.j.replace(/:$/,""))}function e8(e,t){if(t){if(isNaN(t=Number(t))||t<0)throw Error("Bad port number "+t);e.u=t}else e.u=null}function e4(e,t,r){var n,i;t instanceof tl?(e.i=t,n=e.i,(i=e.l)&&!n.j&&(tu(n),n.i=null,n.g.forEach(function(e,t){let r=t.toLowerCase();t!=r&&(th(this,t),tf(this,r,e))},n)),n.j=i):(r||(t=tt(t,ta)),e.i=new tl(t,e.l))}function e9(e,t,r){e.i.set(t,r)}function e7(e){return e9(e,"zx",Math.floor(0x80000000*Math.random()).toString(36)+Math.abs(Math.floor(0x80000000*Math.random())^Date.now()).toString(36)),e}function te(e,t){return e?t?decodeURI(e.replace(/%25/g,"%2525")):decodeURIComponent(e):""}function tt(e,t,r){return"string"==typeof e?(e=encodeURI(e).replace(t,tr),r&&(e=e.replace(/%25([0-9a-fA-F]{2})/g,"%$1")),e):null}function tr(e){return"%"+((e=e.charCodeAt(0))>>4&15).toString(16)+(15&e).toString(16)}e6.prototype.toString=function(){let e=[];var t=this.j;t&&e.push(tt(t,tn,!0),":");var r=this.g;return(r||"file"==t)&&(e.push("//"),(t=this.o)&&e.push(tt(t,tn,!0),"@"),e.push(eL(r).replace(/%25([0-9a-fA-F]{2})/g,"%$1")),null!=(r=this.u)&&e.push(":",String(r))),(r=this.h)&&(this.g&&"/"!=r.charAt(0)&&e.push("/"),e.push(tt(r,"/"==r.charAt(0)?t
1s:ti,!0))),(r=this.i.toString())&&e.push("?",r),(r=this.m)&&e.push("#",tt(r,to)),e.join("")},e6.prototype.resolve=function(e){let t=e3(this),r=!!e.j;r?e5(t,e.j):r=!!e.o,r?t.o=e.o:r=!!e.g,r?t.g=e.g:r=null!=e.u;var n=e.h;if(r)e8(t,e.u);else if(r=!!e.h){if("/"!=n.charAt(0))if(this.g&&!this.h)n="/"+n;else{var i=t.h.lastIndexOf("/");-1!=i&&(n=t.h.slice(0,i+1)+n)}if(".."==(i=n)||"."==i)n="";else if(-1!=i.indexOf("./")||-1!=i.indexOf("/.")){n=0==i.lastIndexOf("/",0),i=i.split("/");let e=[];for(let t=0;t<i.length;){let r=i[t++];"."==r?n&&t==i.length&&e.push(""):".."==r?((e.length>1||1==e.length&&""!=e[0])&&e.pop(),n&&t==i.length&&e.push("")):(e.push(r),n=!0)}n=e.join("/")}else n=i}return r?t.h=n:r=""!==e.i.toString(),r?e4(t,tp(e.i)):r=!!e.m,r&&(t.m=e.m),t};var tn=/[#\/\?@]/g,ti=/[#\?:]/g,ts=/[#\?]/g,ta=/[#\?@]/g,to=/#/g;function tl(e,t){this.h=this.g=null,this.i=e||null,this.j=!!t}function tu(e){e.g||(e.g=new Map,e.h=0,e.i&&function(e,t){if(e){e=e.split("&");for(let r=0;r<e.length;r++){let n=e[r].indexOf("="),i,s=null;n>=0?(i=e[r].substring(0,n),s=e[r].substring(n+1)):i=e[r],t(i,s?decodeURIComponent(s.replace(/\+/g," ")):"")}}}(e.i,function(t,r){e.add(decodeURIComponent(t.replace(/\+/g," ")),r)}))}function th(e,t){tu(e),t=tm(e,t),e.g.has(t)&&(e.i=null,e.h-=e.g.get(t).length,e.g.delete(t))}function tc(e,t){return tu(e),t=tm(e,t),e.g.has(t)}function td(e,t){tu(e);let r=[];if("string"==typeof t)tc(e,t)&&(r=r.concat(e.g.get(tm(e,t))));else for(e=Array.from(e.g.values()),t=0;t<e.length;t++)r=r.concat(e[t]);return r}function tf(e,t,r){th(e,t),r.length>0&&(e.i=null,e.g.set(tm(e,t),_(r)),e.h+=r.length)}function tp(e){let t=new tl;return t.i=e.i,e.g&&(t.g=new Map(e.g),t.h=e.h),t}function tm(e,t){return t=String(t),e.j&&(t=t.toLowerCase()),t}function tg(e,t,r,n,i){try{i&&(i.onload=null,i.onerror=null,i.onabort=null,i.ontimeout=null),n(r)}catch(e){}}function ty(){this.g=new ep}function tv(e){this.i=e.Sb||null,this.h=e.ab||!1}function tw(e,t){es.call(this),this.H=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.A=new Headers,this.h=null,this.F="GET",this.D="",this.g=!1,this.B=this.j=this.l=null,this.v=new AbortController}function tE(e){e.j.read().then(e.Ma.bind(e)).catch(e.ga.bind(e))}function t_(e){e.readyState=4,e.l=null,e.j=null,e.B=null,tI(e)}function tI(e){e.onreadystatechange&&e.onreadystatechange.call(e)}function tT(e){let t="";return $(e,function(e,r){t+=r,t+=":",t+=e,t+="\r\n"}),t}function tb(e,t,r){e:{for(n in r){var n=!1;break e}n=!0}n||(r=tT(r),"string"==typeof e?null!=r&&eL(r):e9(e,t,r))}function tS(e){es.call(this),this.headers=new Map,this.L=e||null,this.h=!1,this.g=null,this.D="",this.o=0,this.l="",this.j=this.B=this.v=this.A=!1,this.m=null,this.F="",this.H=!1}(t=tl.prototype).add=function(e,t){tu(this),this.i=null,e=tm(this,e);let r=this.g.get(e);return r||this.g.set(e,r=[]),r.push(t),this.h+=1,this},t.forEach=function(e,t){tu(this),this.g.forEach(function(r,n){r.forEach(function(r){e.call(t,r,n,this)},this)},this)},t.set=function(e,t){return tu(this),this.i=null,tc(this,e=tm(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&&(e=td(this,e)).length>0?String(e[0]):t},t.toString=function(){if(this.i)return this.i;if(!this.g)return"";let e=[],t=Array.from(this.g.keys());for(let n=0;n<t.length;n++){var r=t[n];let i=eL(r);r=td(this,r);for(let t=0;t<r.length;t++){let n=i;""!==r[t]&&(n+="="+eL(r[t])),e.push(n)}}return this.i=e.join("&")},w(tv,em),tv.prototype.g=function(){return new tw(this.i,this.h)},w(tw,es),(t=tw.prototype).open=function(e,t){if(0!=this.readyState)throw this.abort(),Error("Error reopening a connection");this.F=e,this.D=t,this.readyState=1,tI(this)},t.send=function(e){if(1!=this.readyState)throw this.abort(),Error("need to call open() first. ");if(this.v.signal.aborted)throw this.abort(),Error("Request was aborted.");this.g=!0;let t={headers:this.A,method:this.F,credentials:this.m,cache:void 0,signal:this.v.signal};
1e&&(t.body=e),(this.H||p).fetch(new Request(this.D,t)).then(this.Pa.bind(this),this.ga.bind(this))},t.abort=function(){this.response=this.responseText="",this.A=new Headers,this.status=0,this.v.abort(),this.j&&this.j.cancel("Request was aborted.").catch(()=>{}),this.readyState>=1&&this.g&&4!=this.readyState&&(this.g=!1,t_(this)),this.readyState=0},t.Pa=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,tI(this)),this.g&&(this.readyState=3,tI(this),this.g)))if("arraybuffer"===this.responseType)e.arrayBuffer().then(this.Na.bind(this),this.ga.bind(this));else if(void 0!==p.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.B=new TextDecoder;tE(this)}else e.text().then(this.Oa.bind(this),this.ga.bind(this))},t.Ma=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.B.decode(t,{stream:!e.done}))&&(this.response=this.responseText+=t)}e.done?t_(this):tI(this),3==this.readyState&&tE(this)}},t.Oa=function(e){this.g&&(this.response=this.responseText=e,t_(this))},t.Na=function(e){this.g&&(this.response=e,t_(this))},t.ga=function(){this.g&&t_(this)},t.setRequestHeader=function(e,t){this.A.append(e,t)},t.getResponseHeader=function(e){return this.h&&this.h.get(e.toLowerCase())||""},t.getAllResponseHeaders=function(){if(!this.h)return"";let e=[],t=this.h.entries();for(var r=t.next();!r.done;)e.push((r=r.value)[0]+": "+r[1]),r=t.next();return e.join("\r\n")},Object.defineProperty(tw.prototype,"withCredentials",{get:function(){return"include"===this.m},set:function(e){this.m=e?"include":"same-origin"}}),w(tS,es);var tA=/^https?$/i,tC=["POST","PUT"];function tk(e,t){e.h=!1,e.g&&(e.j=!0,e.g.abort(),e.j=!1),e.l=t,e.o=5,tN(e),tD(e)}function tN(e){e.A||(e.A=!0,ea(e,"complete"),ea(e,"error"))}function tR(e){if(e.h&&void 0!==f){if(e.v&&4==tO(e))setTimeout(e.Ca.bind(e),0);else if(ea(e,"readystatechange"),4==tO(e)){e.h=!1;try{let s=e.ca();switch(s){case 200:case 201:case 202:case 204:case 206:case 304:case 1223:var t,r,n=!0;break;default:n=!1}if(!(t=n)){if(r=0===s){let t=String(e.D).match(e2)[1]||null;!t&&p.self&&p.self.location&&(t=p.self.location.protocol.slice(0,-1)),r=!tA.test(t?t.toLowerCase():"")}t=r}if(t)ea(e,"complete"),ea(e,"success");else{e.o=6;try{var i=tO(e)>2?e.g.statusText:""}catch(e){i=""}e.l=i+" ["+e.ca()+"]",tN(e)}}finally{tD(e)}}}}function tD(e,t){if(e.g){e.m&&(clearTimeout(e.m),e.m=null);let r=e.g;e.g=null,t||ea(e,"ready");try{r.onreadystatechange=null}catch(e){}}}function tO(e){return e.g?e.g.readyState:0}function tP(e){try{if(!e.g)return null;if("response"in e.g)return e.g.response;switch(e.F){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 tL(e,t,r){return r&&r.internalChannelParams&&r.internalChannelParams[e]||t}function tx(e){this.za=0,this.i=[],this.j=new eN,this.ba=this.na=this.J=this.W=this.g=this.wa=this.G=this.H=this.u=this.U=this.o=null,this.Ya=this.V=0,this.Sa=tL("failFast",!1,e),this.F=this.C=this.v=this.m=this.l=null,this.X=!0,this.xa=this.K=-1,this.Y=this.A=this.D=0,this.Qa=tL("baseRetryDelayMs",5e3,e),this.Za=tL("retryDelaySeedMs",1e4,e),this.Ta=tL("forwardChannelMaxRetries",2,e),this.va=tL("forwardChannelRequestTimeoutMs",2e4,e),this.ma=e&&e.xmlHttpFactory||void 0,this.Ua=e&&e.Rb||void 0,this.Aa=e&&e.useFetchStreams||!1,this.O=void 0,this.L=e&&e.supportsCrossDomainXhr||!1,this.M="",this.h=new eQ(e&&e.concurrentRequestLimit),this.Ba=new ty,this.S=e&&e.fastHandshake||!1,this.R=e&&e.encodeInitMessageHeaders||!1,this.S&&this.R&&(this.R=!1),this.Ra=e&&e.Pb||!1,e&&e.ua&&this.j.ua(),e&&e.forceLongPolling&&(this.X=!1),this.aa=!this.S&&this.X&&e&&e.detectBufferingProxy||!1,this.ia=void 0,e&&e.longPollingTimeout&&e.longPollingTimeout>0&&(this.ia=e.longPollingTimeout),this.ta=void 0,this.T=0,this.P=!1,this.ja=this.B=null}function tM(e){if(tV(e),3==e.I){var t=e.V++,r=e3(e.J);if(e9(r,"SID",e.M),e9(r,"RID",t),e9(r,"TYPE","terminate"),tB(e,r),(t=new ex(e,e.j,t)).M=2,t.A=e7(e3(r)),r=!1,p.navigator&&p.navigator.sendBeacon)try{r=p.navigator.sendBeacon(t.A.toString(),"")}catch(e){}!r&&p.Image&&((new Image).src=t.A,r=!0),r||(t.g=tZ(t.j,null),t.g.ea(t.A)),t.F=Date.now(),eq(t)}tX(e)}function tU(e){e.g&&(tK(e),e.g.cancel(),e.g=null)}function tV(e){tU(e),e.v&&(p.clearTimeout(e.v),e.v=null),tG(e),e.h.cancel(),e.m&&("number"==typeof e.m&&p.clearTimeout(e.m),e.m=null)}function tF(e){if(!eJ(e.h)&&!e.m){e.m=!0;var t=e.Ea;N||O(),R||(N(),R=!0),D.add(t,e),e.D=0}}function tj(e,t){var r;r=t?t.l:e.V++;let n=e3(e.J);e9(n,"SID",e.M),e9(n,"RID",r),e9(n,"AID",e.K),tB(e,n),e.u&&e.o&&tb(n,e.u,e.o),r=new ex(e,e.j,r,e.D+1),null===e.u&&(r.J=e.o),t&&(e.i=t.G.concat(e.i)),t=tq(e,r,1e3),r.H=Math.round(.5*e.va)+Math.round(.5*e.va*Math.random()),eZ(e.h,r),eF(r,n,t)}function tB(e,t){e.H&&$(e.H,function(e,r){e9(t,r,e)}),e.l&&$({},function(e,r){e9(t,r,e)})}function tq(e,t,r){r=Math.min(e.i.length,r);let n=e.l?y(e.l.Ka,e.l,e):null;e:{var i=e.i;let t=-1;for(;;){let e=["count="+r];-1==t?r>0?(t=i[0].g,e.push("ofs="+t)):t=0:e.push("ofs="+t);let o=!0;for(let l=0;l<r;l++){var s=i[l].g;let r=i[l].map;if((s-=t)<0)t=Math.max(0,i[l].g-100),o=!1;else try{s="req"+s+"_";try{var a=r instanceof Map?r:Object.entries(r);for(let[t,r]of a){let n=r;m(r)&&(n=ed(r)),e.push(s+t+"="+encodeURIComponent(n))}}catch(t){throw e.push(s+"type="+encodeURIComponent("_badmap")),t}}catch(e){n&&n(r)}}if(o){a=e.join("&");break e}}a=void 0}return t.G=e=e.i.splice(0,r),a}function t$(e){if(!e.g&&!e.v){e.Y=1;var t=e.Da;N||O(),R||(N(),R=!0),D.add(t,e),e.A=0}}function tz(e){return!e.g&&!e.v&&!(e.A>=3)&&(e.Y++,e.v=ek(y(e.Da,e),tQ(e,e.A)),e.A++,!0)}function tK(e){null!=e.B&&(p.clearTimeout(e.B),e.B=null)}function tH(e){e.g=new ex(e,e.j,"rpc",e.Y),null===e.u&&(e.g.J=e.o),e.g.P=0;var t=e3(e.na);e9(t,"RID","rpc"),e9(t,"SID",e.M),e9(t,"AID",e.K),e9(t,"CI",e.F?"0":"1"),!e.F&&e.ia&&e9(t,"TO",e.ia),e9(t,"TYPE","xmlhttp"),tB(e,t),e.u&&e.o&&tb(t,e.u,e.o),e.O&&(e.g.H=e.O);var r=e.g;e=e.ba,r.M=1,r.A=e7(e3(t)),r.u=null,r.R=!0,ej(r,e)}function tG(e){null!=e.C&&(p.clearTimeout(e.C),e.C=null)}function tW(e,t){var r,n=null;if(e.g==t){tG(e),tK(e),e.g=null;var i=2}else{if(!eY(e.h,t))return;n=t.G,e0(e.h,t),i=1}if(0!=e.I){if(t.o)if(1==i){n=t.u?t.u.length:0,t=Date.now()-t.F;var s=e.D;ea(i=eI(),new eC(i,n)),tF(e)}else t$(e);else if(3==(s=t.m)||0==s&&t.X>0||!(1==i&&(r=t,!(eX(e.h)>=e.h.j-!!e.m)&&(e.m?(e.i=r.G.concat(e.i),!0):1!=e.I&&2!=e.I&&!(e.D>=(e.Sa?0:e.Ta))&&(e.m=ek(y(e.Ea,e,r),tQ(e,e.D)),e.D++,!0)))||2==i&&tz(e)))switch(n&&n.length>0&&((t=e.h).i=t.i.concat(n)),s){case 1:tJ(e,5);break;case 4:tJ(e,10);break;case 3:tJ(e,6);break;default:tJ(e,2)}}}function tQ(e,t){let r=e.Qa+Math.floor(Math.random()*e.Za);return e.isActive()||(r*=2),r*t}function tJ(e,t){if(e.j.info("Error code "+t),2==t){let t,s,a;var r,n=y(e.bb,e),i=e.Ua;let o=!i;i=new e6(i||"//www.google.com/images/cleardot.gif"),p.location&&"http"==p.location.protocol||e5(i,"https"),e7(i),o?function(e,t){let r=new eN;if(p.Image){let n=new Image;n.onload=v(tg,r,"TestLoadImage: loaded",!0,t,n),n.onerror=v(tg,r,"TestLoadImage: error",!1,t,n),n.onabort=v(tg,r,"TestLoadImage: abort",!1,t,n),n.ontimeout=v(tg,r,"TestLoadImage: timeout",!1,t,n),p.setTimeout(function(){n.ontimeout&&n.ontimeout()},1e4),n.src=e}else t(!1)}(i.toString(),n):(r=i.toString(),t=new eN,s=new AbortController,a=setTimeout(()=>{s.abort(),tg(t,"TestPingServer: timeout",!1,n)},1e4),fetch(r,{signal:s.signal}).then(e=>{clearTimeout(a),e.ok?tg(t,"TestPingServer: ok",!0,n):tg(t,"TestPingServer: server error",!1,n)}).catch(()=>{clearTimeout(a),tg(t,"TestPingServer: error",!1,n)}))}else eA(2);e.I=0,e.l&&e.l.pa(t),tX(e),tV(e)}function tX(e){if(e.I=0,e.ja=[],e.l){let t=e1(e.h);(0!=t.length||0!=e.i.length)&&(I(e.ja,t),I(e.ja,e.i),e.h.i.length=0,_(e.i),e.i.length=0),e.l.oa()}}function tY(e,t,r){var n=r instanceof e6?e3(r):new e6(r);if(""!=n.g)t&&(n.g=t+"."+n.g),e8(n,n.u);else{var i=p.location;n=i.protocol,t=t?t+"."+i.hostname:i.hostname,i=+i.port;let e=new e6(null);n&&e5(e,n),t&&(e.g=t),i&&e8(e,i),r&&(e.h=r),n=e}return r=e.G,t=e.wa,r&&t&&e9(n,r,t),e9(n,"VER",e.ka),tB(e,n),n}function tZ(e,t,r){if(t&&!e.L)throw Error("Can't create secondary domain capable XhrIo object.");return(t=new tS(e.Aa&&!e.ma?new tv({ab:r}):e.ma)).Fa(e.L),t}function t0(){}function t1(){}function t2(e,t){es.call(this),this.g=new tx(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.sa&&(e?e["X-WebChannel-Client-Profile"]=t.sa:e={"X-WebChannel-Client-Profile":t.sa}),this.g.U=e,(e=t&&t.Qb)&&!U(e)&&(this.g.u=e),this.A=t&&t.supportsCrossDomainXhr||!1,this.v=t&&t.sendRawJson||!1,(t=t&&t.httpSessionIdParam)&&!U(t)&&(this.g.G=t,null!==(e=this.h)&&t in e&&t in(e=this.h)&&delete e[t]),this.j=new t5(this)}function t6(e){ev.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(let r in t){e=r;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 t3(){ew.call(this),this.status=1}function t5(e){this.g=e}(t=tS.prototype).Fa=function(e){this.H=e},t.ea=function(t,r,n,i){if(this.g)throw Error("[goog.net.XhrIo] Object is active with another request="+this.D+"; newUri="+t);r=r?r.toUpperCase():"GET",this.D=t,this.l="",this.o=0,this.A=!1,this.h=!0,this.g=this.L?this.L.g():e.g(),this.g.onreadystatechange=E(y(this.Ca,this));try{this.B=!0,this.g.open(r,String(t),!0),this.B=!1}catch(e){tk(this,e);return}if(t=n||"",n=new Map(this.headers),i)if(Object.getPrototypeOf(i)===Object.prototype)for(var s in i)n.set(s,i[s]);else if("function"==typeof i.keys&&"function"==typeof i.get)for(let e of i.keys())n.set(e,i.get(e));else throw Error("Unknown input type for opt_headers: "+String(i));for(let[e,a]of(i=Array.from(n.keys()).find(e=>"content-type"==e.toLowerCase()),s=p.FormData&&t instanceof p.FormData,!(Array.prototype.indexOf.call(tC,r,void 0)>=0)||i||s||n.set("Content-Type","application/x-www-form-urlencoded;charset=utf-8"),n))this.g.setRequestHeader(e,a);this.F&&(this.g.responseType=this.F),"withCredentials"in this.g&&this.g.withCredentials!==this.H&&(this.g.withCredentials=this.H);try{this.m&&(clearTimeout(this.m),this.m=null),this.v=!0,this.g.send(t),this.v=!1}catch(e){tk(this,e)}},t.abort=function(e){this.g&&this.h&&(this.h=!1,this.j=!0,this.g.abort(),this.j=!1,this.o=e||7,ea(this,"complete"),ea(this,"abort"),tD(this))},t.N=function(){this.g&&(this.h&&(this.h=!1,this.j=!0,this.g.abort(),this.j=!1),tD(this,!0)),tS.Z.N.call(this)},t.Ca=function(){this.u||(this.B||this.v||this.j?tR(this):this.Xa())},t.Xa=function(){tR(this)},t.isActive=function(){return!!this.g},t.ca=function(){try{return tO(this)>2?this.g.status:-1}catch(e){return -1}},t.la=function(){try{return this.g?this.g.responseText:""}catch(e){return""}},t.La=function(e){if(this.g){var t=this.g.responseText;
1return e&&0==t.indexOf(e)&&(t=t.substring(e.length)),ef(t)}},t.ya=function(){return this.o},t.Ha=function(){return"string"==typeof this.l?this.l:String(this.l)},(t=tx.prototype).ka=8,t.I=1,t.connect=function(e,t,r,n){eA(0),this.W=e,this.H=t||{},r&&void 0!==n&&(this.H.OSID=r,this.H.OAID=n),this.F=this.X,this.J=tY(this,null,this.W),tF(this)},t.Ea=function(e){if(this.m)if(this.m=null,1==this.I){if(!e){this.V=Math.floor(1e5*Math.random()),e=this.V++;let i=new ex(this,this.j,e),s=this.o;if(this.U&&(s?H(s=z(s),this.U):s=this.U),null!==this.u||this.R||(i.J=s,s=null),this.S)e:{for(var t=0,r=0;r<this.i.length;r++){t:{var n=this.i[r];if("__data__"in n.map&&"string"==typeof(n=n.map.__data__)){n=n.length;break t}n=void 0}if(void 0===n)break;if((t+=n)>4096){t=r;break e}if(4096===t||r===this.i.length-1){t=r+1;break e}}t=1e3}else t=1e3;t=tq(this,i,t),e9(r=e3(this.J),"RID",e),e9(r,"CVER",22),this.G&&e9(r,"X-HTTP-Session-Id",this.G),tB(this,r),s&&(this.R?t="headers="+eL(tT(s))+"&"+t:this.u&&tb(r,this.u,s)),eZ(this.h,i),this.Ra&&e9(r,"TYPE","init"),this.S?(e9(r,"$req",t),e9(r,"SID","null"),i.U=!0,eF(i,r,null)):eF(i,r,t),this.I=2}}else 3==this.I&&(e?tj(this,e):0==this.i.length||eJ(this.h)||tj(this))},t.Da=function(){if(this.v=null,tH(this),this.aa&&!(this.P||null==this.g||this.T<=0)){var e=4*this.T;this.j.info("BP detection timer enabled: "+e),this.B=ek(y(this.Wa,this),e)}},t.Wa=function(){this.B&&(this.B=null,this.j.info("BP detection timeout reached."),this.j.info("Buffering proxy detected and switch to long-polling!"),this.F=!1,this.P=!0,eA(10),tU(this),tH(this))},t.Va=function(){null!=this.C&&(this.C=null,tU(this),tz(this),eA(19))},t.bb=function(e){e?(this.j.info("Successfully pinged google.com"),eA(2)):(this.j.info("Failed to ping google.com"),eA(1))},t.isActive=function(){return!!this.l&&this.l.isActive(this)},(t=t0.prototype).ra=function(){},t.qa=function(){},t.pa=function(){},t.oa=function(){},t.isActive=function(){return!0},t.Ka=function(){},t1.prototype.g=function(e,t){return new t2(e,t)},w(t2,es),t2.prototype.m=function(){this.g.l=this.j,this.A&&(this.g.L=!0),this.g.connect(this.l,this.h||void 0)},t2.prototype.close=function(){tM(this.g)},t2.prototype.o=function(e){var t=this.g;if("string"==typeof e){var r={};r.__data__=e,e=r}else this.v&&((r={}).__data__=ed(e),e=r);t.i.push(new eW(t.Ya++,e)),3==t.I&&tF(t)},t2.prototype.N=function(){this.g.l=null,delete this.j,tM(this.g),delete this.g,t2.Z.N.call(this)},w(t6,ev),w(t3,ew),w(t5,t0),t5.prototype.ra=function(){ea(this.g,"a")},t5.prototype.qa=function(e){ea(this.g,new t6(e))},t5.prototype.pa=function(e){ea(this.g,new t3)},t5.prototype.oa=function(){ea(this.g,"b")},t1.prototype.createWebChannel=t1.prototype.g,t2.prototype.send=t2.prototype.o,t2.prototype.open=t2.prototype.m,t2.prototype.close=t2.prototype.close,d=b.createWebChannelTransport=function(){return new t1},c=b.getStatEventTarget=function(){return eI()},h=b.Event=eE,u=b.Stat={jb:0,mb:1,nb:2,Hb:3,Mb:4,Jb:5,Kb:6,Ib:7,Gb:8,Lb:9,PROXY:10,NOPROXY:11,Eb:12,Ab:13,Bb:14,zb:15,Cb:16,Db:17,fb:18,eb:19,gb:20},eD.NO_ERROR=0,eD.TIMEOUT=8,eD.HTTP_ERROR=6,l=b.ErrorCode=eD,eO.COMPLETE="complete",o=b.EventType=eO,eg.EventType=ey,ey.OPEN="a",ey.CLOSE="b",ey.ERROR="c",ey.MESSAGE="d",es.prototype.listen=es.prototype.J,a=b.WebChannel=eg,b.FetchXmlHttpFactory=tv,tS.prototype.listenOnce=tS.prototype.K,tS.prototype.getLastError=tS.prototype.Ha,tS.prototype.getLastErrorCode=tS.prototype.ya,tS.prototype.getStatus=tS.prototype.ca,tS.prototype.getResponseJson=tS.prototype.La,tS.prototype.getResponseText=tS.prototype.la,tS.prototype.send=tS.prototype.ea,tS.prototype.setWithCredentials=tS.prototype.Fa,s=b.XhrIo=tS}).apply(void 0!==T?T:"u">typeof self?self:"u">typeof window?window:{}),r(99742);var S=r(82909).hp;class A{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}}A.UNAUTHENTICATED=new A(null),A.GOOGLE_CREDENTIALS=new A("google-credentials-uid"),A.FIRST_PARTY=new A("first-party-uid"),A.MOCK_USER=new A("mock-user");let C="12.12.0",k=new I.Vy("@firebase/firestore");function N(){return k.logLevel}function R(e,...t){if(k.logLevel<=I.$b.DEBUG){let r=t.map(P);k.debug(`Firestore (${C}): ${e}`,...r)}}function D(e,...t){if(k.logLevel<=I.$b.ERROR){let r=t.map(P);k.error(`Firestore (${C}): ${e}`,...r)}}function O(e,...t){if(k.logLevel<=I.$b.WARN){let r=t.map(P);k.warn(`Firestore (${C}): ${e}`,...r)}}function P(e){if("string"==typeof e)return e;try{return JSON.stringify(e)}catch(t){return e}}function L(e,t,r){let n="Unexpected state";"string"==typeof t?n=t:r=t,x(e,n,r)}function x(e,t,r){let n=`FIRESTORE (${C}) INTERNAL ASSERTION FAILED: ${t} (ID: ${e.toString(16)})`;if(void 0!==r)try{n+=" CONTEXT: "+JSON.stringify(r)}catch(e){n+=" CONTEXT: "+r}throw D(n),Error(n)}function M(e,t,r,n){let i="Unexpected state";"string"==typeof r?i=r:n=r,e||x(t,i,n)}let 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",UNIMPLEMENT
1ED:"unimplemented",INTERNAL:"internal",UNAVAILABLE:"unavailable",DATA_LOSS:"data-loss"};class V extends w.g{constructor(e,t){super(e,t),this.code=e,this.message=t,this.toString=()=>`${this.name}: [code=${this.code}]: ${this.message}`}}class F{constructor(){this.promise=new Promise((e,t)=>{this.resolve=e,this.reject=t})}}class j{constructor(e,t){this.user=t,this.type="OAuth",this.headers=new Map,this.headers.set("Authorization",`Bearer ${e}`)}}class B{getToken(){return Promise.resolve(null)}invalidateToken(){}start(e,t){e.enqueueRetryable(()=>t(A.UNAUTHENTICATED))}shutdown(){}}class q{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 ${constructor(e){this.t=e,this.currentUser=A.UNAUTHENTICATED,this.i=0,this.forceRefresh=!1,this.auth=null}start(e,t){M(void 0===this.o,42304);let r=this.i,n=e=>this.i!==r?(r=this.i,t(e)):Promise.resolve(),i=new F;this.o=()=>{this.i++,this.currentUser=this.u(),i.resolve(),i=new F,e.enqueueRetryable(()=>n(this.currentUser))};let s=()=>{let t=i;e.enqueueRetryable(async()=>{await t.promise,await n(this.currentUser)})},a=e=>{R("FirebaseAuthCredentialsProvider","Auth detected"),this.auth=e,this.o&&(this.auth.addAuthTokenListener(this.o),s())};this.t.onInit(e=>a(e)),setTimeout(()=>{if(!this.auth){let e=this.t.getImmediate({optional:!0});e?a(e):(R("FirebaseAuthCredentialsProvider","Auth not yet detected"),i.resolve(),i=new F)}},0),s()}getToken(){let e=this.i,t=this.forceRefresh;return this.forceRefresh=!1,this.auth?this.auth.getToken(t).then(t=>this.i!==e?(R("FirebaseAuthCredentialsProvider","getToken aborted due to token change."),this.getToken()):t?(M("string"==typeof t.accessToken,31837,{l:t}),new j(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(){let e=this.auth&&this.auth.getUid();return M(null===e||"string"==typeof e,2055,{h:e}),new A(e)}}class z{constructor(e,t,r){this.P=e,this.T=t,this.I=r,this.type="FirstParty",this.user=A.FIRST_PARTY,this.R=new Map}A(){return this.I?this.I():null}get headers(){this.R.set("X-Goog-AuthUser",this.P);let e=this.A();return e&&this.R.set("Authorization",e),this.T&&this.R.set("X-Goog-Iam-Authorization-Token",this.T),this.R}}class K{constructor(e,t,r){this.P=e,this.T=t,this.I=r}getToken(){return Promise.resolve(new z(this.P,this.T,this.I))}start(e,t){e.enqueueRetryable(()=>t(A.FIRST_PARTY))}shutdown(){}invalidateToken(){}}class H{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 G{constructor(e,t){this.V=t,this.forceRefresh=!1,this.appCheck=null,this.m=null,this.p=null,(0,y.xZ)(e)&&e.settings.appCheckToken&&(this.p=e.settings.appCheckToken)}start(e,t){M(void 0===this.o,3512);let r=e=>{null!=e.error&&R("FirebaseAppCheckTokenProvider",`Error getting App Check token; using placeholder token instead. Error: ${e.error.message}`);let r=e.token!==this.m;return this.m=e.token,R("FirebaseAppCheckTokenProvider",`Received ${r?"new":"existing"} token.`),r?t(e.token):Promise.resolve()};this.o=t=>{e.enqueueRetryable(()=>r(t))};let n=e=>{R("FirebaseAppCheckTokenProvider","AppCheck detected"),this.appCheck=e,this.o&&this.appCheck.addTokenListener(this.o)};this.V.onInit(e=>n(e)),setTimeout(()=>{if(!this.appCheck){let e=this.V.getImmediate({optional:!0});e?n(e):R("FirebaseAppCheckTokenProvider","AppCheck not yet detected")}},0)}getToken(){if(this.p)return Promise.resolve(new H(this.p));let e=this.forceRefresh;return this.forceRefresh=!1,this.appCheck?this.appCheck.getToken(e).then(e=>e?(M("string"==typeof e.token,44558,{tokenResult:e}),this.m=e.token,new H(e.token)):null):Promise.resolve(null)}invalidateToken(){this.forceRefresh=!0}shutdown(){this.appCheck&&this.o&&this.appCheck.removeTokenListener(this.o),this.o=void 0}}class W{static newId(){let e=62*Math.floor(256/62),t="";for(;t.length<20;){let r=function(){let e="u">typeof self&&(self.crypto||self.msCrypto),t=new Uint8Array(40);if(e&&"function"==typeof e.getRandomValues)e.getRandomValues(t);else for(let e=0;e<40;
1e++)t[e]=Math.floor(256*Math.random());return t}();for(let n=0;n<r.length;++n)t.length<20&&r[n]<e&&(t+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".charAt(r[n]%62))}return t}}function Q(e,t){return e<t?-1:+(e>t)}function J(e,t){let r=Math.min(e.length,t.length);for(let n=0;n<r;n++){let r=e.charAt(n),i=t.charAt(n);if(r!==i)return X(r)===X(i)?Q(r,i):X(r)?1:-1}return Q(e.length,t.length)}function X(e){let t=e.charCodeAt(0);return t>=55296&&t<=57343}function Y(e,t,r){return e.length===t.length&&e.every((e,n)=>r(e,t[n]))}let Z="__name__";class ee{constructor(e,t,r){void 0===t?t=0:t>e.length&&L(637,{offset:t,range:e.length}),void 0===r?r=e.length-t:r>e.length-t&&L(1746,{length:r,range:e.length-t}),this.segments=e,this.offset=t,this.len=r}get length(){return this.len}isEqual(e){return 0===ee.comparator(this,e)}child(e){let t=this.segments.slice(this.offset,this.limit());return e instanceof ee?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,r=this.limit();t<r;t++)e(this.segments[t])}toArray(){return this.segments.slice(this.offset,this.limit())}static comparator(e,t){let r=Math.min(e.length,t.length);for(let n=0;n<r;n++){let r=ee.compareSegments(e.get(n),t.get(n));if(0!==r)return r}return Q(e.length,t.length)}static compareSegments(e,t){let r=ee.isNumericId(e),n=ee.isNumericId(t);return r&&!n?-1:!r&&n?1:r&&n?ee.extractNumericId(e).compare(ee.extractNumericId(t)):J(e,t)}static isNumericId(e){return e.startsWith("__id")&&e.endsWith("__")}static extractNumericId(e){return n.fromString(e.substring(4,e.length-2))}}class et extends ee{construct(e,t,r){return new et(e,t,r)}canonicalString(){return this.toArray().join("/")}toString(){return this.canonicalString()}toUriEncodedString(){return this.toArray().map(encodeURIComponent).join("/")}static fromString(...e){let t=[];for(let r of e){if(r.indexOf("//")>=0)throw new V(U.INVALID_ARGUMENT,`Invalid segment (${r}). Paths must not contain // in them.`);t.push(...r.split("/").filter(e=>e.length>0))}return new et(t)}static emptyPath(){return new et([])}}let er=/^[_a-zA-Z][_a-zA-Z0-9]*$/;class en extends ee{construct(e,t,r){return new en(e,t,r)}static isValidIdentifier(e){return er.test(e)}canonicalString(){return this.toArray().map(e=>(e=e.replace(/\\/g,"\\\\").replace(/`/g,"\\`"),en.isValidIdentifier(e)||(e="`"+e+"`"),e)).join(".")}toString(){return this.canonicalString()}isKeyField(){return 1===this.length&&this.get(0)===Z}static keyField(){return new en([Z])}static fromServerFormat(e){let t=[],r="",n=0,i=()=>{if(0===r.length)throw new V(U.INVALID_ARGUMENT,`Invalid field path (${e}). Paths must not be empty, begin with '.', end with '.', or contain '..'`);t.push(r),r=""},s=!1;for(;n<e.length;){let t=e[n];if("\\"===t){if(n+1===e.length)throw new V(U.INVALID_ARGUMENT,"Path has trailing escape character: "+e);let t=e[n+1];if("\\"!==t&&"."!==t&&"`"!==t)throw new V(U.INVALID_ARGUMENT,"Path has invalid escape sequence: "+e);r+=t,n+=2}else"`"===t?s=!s:"."!==t||s?r+=t:i(),n++}if(i(),s)throw new V(U.INVALID_ARGUMENT,"Unterminated ` in path: "+e);return new en(t)}static emptyPath(){return new en([])}}class ei{constructor(e){this.path=e}static fromPath(e){return new ei(et.fromString(e))}static fromName(e){return new ei(et.fromString(e).popFirst(5))}static empty(){return new ei(et.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===et.comparator(this.path,e.path)}toString(){return this.path.toString()}static comparator(e,t){return et.comparator(e.path,t.path)}static isDocumentKey(e){return e.length%2==0}static fromSegments(e){return new ei(new et(e.slice()))}}function es(e,t,r){if(!r)throw new V(U.INVALID_ARGUMENT,`Function ${e}() cannot be called with an empty ${t}.`)}function ea(e){if(!ei.isDocumentKey(e))throw new V(U.INVALID_ARGUMENT,`Invalid document reference. Document references must have an even number of segments, but ${e} has ${e.length}.`)}function eo(e){if(ei.isDocumentKey(e))throw new V(U.INVALID_ARGUMENT,`Invalid collection reference. Collection references must have an odd number of segments, but ${e} has ${e.length}.`)}function el(e){return"object"==typeof e&&null!==e&&(Object.getPrototypeOf(e)===Object.prototype||null===Object.getPrototypeOf(e))}function eu(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";{var t;let r=(t=e).constructor?t.constructor.name:null;return r?`a custom ${r} object`:"an object"}}return"function"==typeof e?"a function":L(12329,{type:typeof e})}function eh(e,t){if("_delegate"in e&&(e=e._delegate),!(e instanceof t)){if(t.name===e.constructor.name)throw new V(U.INVALID_ARGUMENT,"Type does not match the expected instance. Did you pass a reference from a different Firestore SDK?");{let r=eu(e);throw new V(U.INVALID_ARGUMENT,`Expected type '${t.name}', but it was: ${r}`)}}return e}function ec(e,t){let r={typeString:e};return t&&(r.value=t),r}function ed(e,t){let r;if(!el(e))throw new V(U.INVALID_ARGUMENT,"JSON must be an object");for(let n in t)if(t[n]){let i=t[n].typeString,s="value"in t[n]?{value:t[n].value}:void 0;if(!(n in e)){r=`JSON missing required field: '${n}'`;break}let a=e[n];if(i&&typeof a!==i){r=`JSON field '${n}' must be a ${i}.`;break}if(void 0!==s&&a!==s.value){r=`Expected '${n}' field to equal '${s.value}'`;break}}if(r)throw new V(U.INVALID_ARGUMENT,r);return!0}class ef{static now(){return ef.fromMillis(Date.now())}static fromDate(e){return ef.fromMillis(e.getTime())}static fromMillis(e){let t=Math.floor(e/1e3),r=Math.floor((e-1e3*t)*1e6);return new ef(t,r)}constructor(e,t){if(this.seconds=e,this.nanoseconds=t,t<0||t>=1e9)throw new V(U.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+t);if(e<-0xe7791f700||e>=0x3afff44180)throw new V(U.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?Q(this.nanoseconds,e.nanoseconds):Q(this.seconds,e.seconds)}isEqual(e){return e.seconds===this.seconds&&e.nanoseconds===this.nanoseconds}toString(){return"Timestamp(seconds="+this.seconds+", nanoseconds="+this.nanoseconds+")"}toJSON(){return{type:ef._jsonSchemaVersion,seconds:this.seconds,nanoseconds:this.nanoseconds}}static fromJSON(e){if(ed(e,ef._jsonSchema))return new ef(e.seconds,e.nanoseconds)}valueOf(){return String(this.seconds- -0xe7791f700).padStart(12,"0")+"."+String(this.nanoseconds).padStart(9,"0")}
1}ef._jsonSchemaVersion="firestore/timestamp/1.0",ef._jsonSchema={type:ec("string",ef._jsonSchemaVersion),seconds:ec("number"),nanoseconds:ec("number")};class ep{static fromTimestamp(e){return new ep(e)}static min(){return new ep(new ef(0,0))}static max(){return new ep(new ef(0x3afff4417f,0x3b9ac9ff))}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 em{constructor(e,t,r,n){this.indexId=e,this.collectionGroup=t,this.fields=r,this.indexState=n}}em.UNKNOWN_ID=-1;class eg{constructor(e,t,r){this.readTime=e,this.documentKey=t,this.largestBatchId=r}static min(){return new eg(ep.min(),ei.empty(),-1)}static max(){return new eg(ep.max(),ei.empty(),-1)}}class ey{constructor(){this.onCommittedListeners=[]}addOnCommittedListener(e){this.onCommittedListeners.push(e)}raiseOnCommittedEvent(){this.onCommittedListeners.forEach(e=>e())}}async function ev(e){if(e.code!==U.FAILED_PRECONDITION||"The current tab is not in the required state to perform this operation. It might be necessary to refresh the browser tab."!==e.message)throw e;R("LocalStore","Unexpectedly lost primary lease")}class ew{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&&L(59440),this.callbackAttached=!0,this.isDone?this.error?this.wrapFailure(t,this.error):this.wrapSuccess(e,this.result):new ew((r,n)=>{this.nextCallback=t=>{this.wrapSuccess(e,t).next(r,n)},this.catchCallback=e=>{this.wrapFailure(t,e).next(r,n)}})}toPromise(){return new Promise((e,t)=>{this.next(e,t)})}wrapUserFunction(e){try{let t=e();return t instanceof ew?t:ew.resolve(t)}catch(e){return ew.reject(e)}}wrapSuccess(e,t){return e?this.wrapUserFunction(()=>e(t)):ew.resolve(t)}wrapFailure(e,t){return e?this.wrapUserFunction(()=>e(t)):ew.reject(t)}static resolve(e){return new ew((t,r)=>{t(e)})}static reject(e){return new ew((t,r)=>{r(e)})}static waitFor(e){return new ew((t,r)=>{let n=0,i=0,s=!1;e.forEach(e=>{++n,e.next(()=>{++i,s&&i===n&&t()},e=>r(e))}),s=!0,i===n&&t()})}static or(e){let t=ew.resolve(!1);for(let r of e)t=t.next(e=>e?ew.resolve(e):r());return t}static forEach(e,t){let r=[];return e.forEach((e,n)=>{r.push(t.call(this,e,n))}),this.waitFor(r)}static mapArray(e,t){return new ew((r,n)=>{let i=e.length,s=Array(i),a=0;for(let o=0;o<i;o++){let l=o;t(e[l]).next(e=>{s[l]=e,++a===i&&r(s)},e=>n(e))}})}static doWhile(e,t){return new ew((r,n)=>{let i=()=>{!0===e()?t().next(()=>{i()},n):r()};i()})}}function eE(e){return"IndexedDbTransactionError"===e.name}class e_{constructor(e,t){this.previousValue=e,t&&(t.sequenceNumberHandler=e=>this.ae(e),this.ue=e=>t.writeSequenceNumber(e))}ae(e){return this.previousValue=Math.max(e,this.previousValue),this.previousValue}next(){let e=++this.previousValue;return this.ue&&this.ue(e),e}}e_.ce=-1;function eI(e){return 0===e&&1/e==-1/0}function eT(e){let t=0;for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&t++;return t}function eb(e,t){for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&t(r,e[r])}function eS(e){for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}class eA{constructor(e,t){this.comparator=e,this.root=t||ek.EMPTY}insert(e,t){return new eA(this.comparator,this.root.insert(e,t,this.comparator).copy(null,null,ek.BLACK,null,null))}remove(e){return new eA(this.comparator,this.root.remove(e,this.comparator).copy(null,null,ek.BLACK,null,null))}get(e){let t=this.root;for(;!t.isEmpty();){let r=this.comparator(e,t.key);if(0===r)return t.value;r<0?t=t.left:r>0&&(t=t.right)}return null}indexOf(e){let t=0,r=this.root;for(;!r.isEmpty();){let n=this.comparator(e,r.key);if(0===n)return t+r.left.size;n<0?r=r.left:(t+=r.left.size+1,r=r.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,r)=>(e(t,r),!1))}toString(){let e=[];return this.inorderTraversal((t,r)=>(e.push(`${t}:${r}`),!1)),`{${e.join(", ")}}`}reverseTraversal(e){return this.root.reverseTraversal(e)}getIterator(){return new eC(this.root,null,this.comparator,!1)}getIteratorFrom(e){return new eC(this.root,e,this.comparator,!1)}getReverseIterator(){return new eC(this.root,null,this.comparator,!0)}getReverseIteratorFrom(e){return new eC(this.root,e,this.comparator,!0)}}class eC{constructor(e,t,r,n){this.isReverse=n,this.nodeStack=[];let i=1;for(;!e.isEmpty();)if(i=t?r(e.key,t):1,t&&n&&(i*=-1),i<0)e=this.isReverse?e.left:e.right;else{if(0===i){this.nodeStack.push(e);break}this.nodeStack.push(e),e=this.isReverse?e.right:e.left}}getNext(){let e=this.nodeStack.pop(),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;let e=this.nodeStack[this.nodeStack.length-1];return{key:e.key,value:e.value}}}class ek{constructor(e,t,r,n,i){this.key=e,this.value=t,this.color=null!=r?r:ek.RED,this.left=null!=n?n:ek.EMPTY,this.right=null!=i?i:ek.EMPTY,this.size=this.left.size+1+this.right.size}copy(e,t,r,n,i){return new ek(null!=e?e:this.key,null!=t?t:this.value,
1null!=r?r:this.color,null!=n?n:this.left,null!=i?i:this.right)}isEmpty(){return!1}inorderTraversal(e){return this.left.inorderTraversal(e)||e(this.key,this.value)||this.right.inorderTraversal(e)}reverseTraversal(e){return this.right.reverseTraversal(e)||e(this.key,this.value)||this.left.reverseTraversal(e)}min(){return this.left.isEmpty()?this:this.left.min()}minKey(){return this.min().key}maxKey(){return this.right.isEmpty()?this.key:this.right.maxKey()}insert(e,t,r){let n=this,i=r(e,n.key);return(n=i<0?n.copy(null,null,null,n.left.insert(e,t,r),null):0===i?n.copy(null,t,null,null,null):n.copy(null,null,null,null,n.right.insert(e,t,r))).fixUp()}removeMin(){if(this.left.isEmpty())return ek.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)).fixUp()}remove(e,t){let r,n=this;if(0>t(e,n.key))n.left.isEmpty()||n.left.isRed()||n.left.left.isRed()||(n=n.moveRedLeft()),n=n.copy(null,null,null,n.left.remove(e,t),null);else{if(n.left.isRed()&&(n=n.rotateRight()),n.right.isEmpty()||n.right.isRed()||n.right.left.isRed()||(n=n.moveRedRight()),0===t(e,n.key)){if(n.right.isEmpty())return ek.EMPTY;r=n.right.min(),n=n.copy(r.key,r.value,null,null,n.right.removeMin())}n=n.copy(null,null,null,null,n.right.remove(e,t))}return n.fixUp()}isRed(){return this.color}fixUp(){let e=this;return e.right.isRed()&&!e.left.isRed()&&(e=e.rotateLeft()),e.left.isRed()&&e.left.left.isRed()&&(e=e.rotateRight()),e.left.isRed()&&e.right.isRed()&&(e=e.colorFlip()),e}moveRedLeft(){let e=this.colorFlip();return e.right.left.isRed()&&(e=(e=(e=e.copy(null,null,null,null,e.right.rotateRight())).rotateLeft()).colorFlip()),e}moveRedRight(){let e=this.colorFlip();return e.left.left.isRed()&&(e=(e=e.rotateRight()).colorFlip()),e}rotateLeft(){let e=this.copy(null,null,ek.RED,null,this.right.left);return this.right.copy(null,null,this.color,e,null)}rotateRight(){let e=this.copy(null,null,ek.RED,this.left.right,null);return this.left.copy(null,null,this.color,null,e)}colorFlip(){let 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(){return Math.pow(2,this.check())<=this.size+1}check(){if(this.isRed()&&this.left.isRed())throw L(43730,{key:this.key,value:this.value});if(this.right.isRed())throw L(14113,{key:this.key,value:this.value});let e=this.left.check();if(e!==this.right.check())throw L(27949);return e+ +!this.isRed()}}ek.EMPTY=null,ek.RED=!0,ek.BLACK=!1,ek.EMPTY=new class{constructor(){this.size=0}get key(){throw L(57766)}get value(){throw L(16141)}get color(){throw L(16727)}get left(){throw L(29726)}get right(){throw L(36894)}copy(e,t,r,n,i){return this}insert(e,t,r){return new ek(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 eN{constructor(e){this.comparator=e,this.data=new eA(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,r)=>(e(t),!1))}forEachInRange(e,t){let r=this.data.getIteratorFrom(e[0]);for(;r.hasNext();){let n=r.getNext();if(this.comparator(n.key,e[1])>=0)return;t(n.key)}}forEachWhile(e,t){let r;for(r=void 0!==t?this.data.getIteratorFrom(t):this.data.getIterator();r.hasNext();)if(!e(r.getNext().key))return}firstAfterOrEqual(e){let t=this.data.getIteratorFrom(e);return t.hasNext()?t.getNext().key:null}getIterator(){return new eR(this.data.getIterator())}getIteratorFrom(e){return new eR(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 eN)||this.size!==e.size)return!1;let t=this.data.getIterator(),r=e.data.getIterator();for(;t.hasNext();){let e=t.getNext().key,n=r.getNext().key;if(0!==this.comparator(e,n))return!1}return!0}toArray(){let e=[];return this.forEach(t=>{e.push(t)}),e}toString(){let e=[];return this.forEach(t=>e.push(t)),"SortedSet("+e.toString()+")"}copy(e){let t=new eN(this.comparator);return t.data=e,t}}
1class eR{constructor(e){this.iter=e}getNext(){return this.iter.getNext().key}hasNext(){return this.iter.hasNext()}}class eD{constructor(e){this.fields=e,e.sort(en.comparator)}static empty(){return new eD([])}unionWith(e){let t=new eN(en.comparator);for(let e of this.fields)t=t.add(e);for(let r of e)t=t.add(r);return new eD(t.toArray())}covers(e){for(let t of this.fields)if(t.isPrefixOf(e))return!0;return!1}isEqual(e){return Y(this.fields,e.fields,(e,t)=>e.isEqual(t))}}class eO extends Error{constructor(){super(...arguments),this.name="Base64DecodeError"}}class eP{constructor(e){this.binaryString=e}static fromBase64String(e){return new eP(function(e){try{return atob(e)}catch(e){throw"u">typeof DOMException&&e instanceof DOMException?new eO("Invalid base64 string: "+e):e}}(e))}static fromUint8Array(e){return new eP(function(e){let t="";for(let r=0;r<e.length;++r)t+=String.fromCharCode(e[r]);return t}(e))}[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 btoa(this.binaryString)}toUint8Array(){var e=this.binaryString;let t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t}approximateByteSize(){return 2*this.binaryString.length}compareTo(e){return Q(this.binaryString,e.binaryString)}isEqual(e){return this.binaryString===e.binaryString}}eP.EMPTY_BYTE_STRING=new eP("");let eL=new RegExp(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.(\d+))?Z$/);function ex(e){if(M(!!e,39018),"string"==typeof e){let t=0,r=eL.exec(e);if(M(!!r,46558,{timestamp:e}),r[1]){let e=r[1];t=Number(e=(e+"000000000").substr(0,9))}return{seconds:Math.floor(new Date(e).getTime()/1e3),nanos:t}}return{seconds:eM(e.seconds),nanos:eM(e.nanos)}}function eM(e){return"number"==typeof e?e:"string"==typeof e?Number(e):0}function eU(e){return"string"==typeof e?eP.fromBase64String(e):eP.fromUint8Array(e)}let eV="server_timestamp",eF="__type__",ej="__previous_value__",eB="__local_write_time__";function eq(e){return(e?.mapValue?.fields||{})[eF]?.stringValue===eV}function e$(e){let t=e.mapValue.fields[ej];return eq(t)?e$(t):t}function ez(e){let t=ex(e.mapValue.fields[eB].timestampValue);return new ef(t.seconds,t.nanos)}class eK{constructor(e,t,r,n,i,s,a,o,l,u,h){this.databaseId=e,this.appId=t,this.persistenceKey=r,this.host=n,this.ssl=i,this.forceLongPolling=s,this.autoDetectLongPolling=a,this.longPollingOptions=o,this.useFetchStreams=l,this.isUsingEmulator=u,this.apiKey=h}}let eH="(default)";class eG{constructor(e,t){this.projectId=e,this.database=t||eH}static empty(){return new eG("","")}get isDefaultDatabase(){return this.database===eH}isEqual(e){return e instanceof eG&&e.projectId===this.projectId&&e.database===this.database}}let eW="__type__",eQ="__max__",eJ={fields:{__type__:{stringValue:eQ}}},eX="__vector__",eY="value";function eZ(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?eq(e)?4:ti(e)?0x1fffffffffffff:tr(e)?10:11:L(28295,{value:e})}function e0(e,t){if(e===t)return!0;let r=eZ(e);if(r!==eZ(t))return!1;switch(r){case 0:case 0x1fffffffffffff:return!0;case 1:return e.booleanValue===t.booleanValue;case 4:return ez(e).isEqual(ez(t));case 3:if("string"==typeof e.timestampValue&&"string"==typeof t.timestampValue&&e.timestampValue.length===t.timestampValue.length)return e.timestampValue===t.timestampValue;let n=ex(e.timestampValue),i=ex(t.timestampValue);return n.seconds===i.seconds&&n.nanos===i.nanos;case 5:return e.stringValue===t.stringValue;case 6:return eU(e.bytesValue).isEqual(eU(t.bytesValue));case 7:return e.referenceValue===t.referenceValue;case 8:return eM(e.geoPointValue.latitude)===eM(t.geoPointValue.latitude)&&eM(e.geoPointValue.longitude)===eM(t.geoPointValue.longitude);case 2:if("integerValue"in e&&"integerValue"in t)return eM(e.integerValue)===eM(t.integerValue);if("doubleValue"in e&&"doubleValue"in t){let r=eM(e.doubleValue),n=eM(t.doubleValue);return r===n?eI(r)===eI(n):isNaN(r)&&isNaN(n)}return!1;case 9:return Y(e.arrayValue.values||[],t.arrayValue.values||[],e0);case 10:case 11:let s=e.mapValue.fields||{},a=t.mapValue.fields||{};if(eT(s)!==eT(a))return!1;for(let e in s)if(s.hasOwnProperty(e)&&(void 0===a[e]||!e0(s[e],a[e])))return!1;return!0;default:return L(52216,{left:e})}}function e1(e,t){return void 0!==(e.values||[]).find(e=>e0(e,t))}function e2(e,t){var r,n,i,s,a,o;if(e===t)return 0;let l=eZ(e),u=eZ(t);if(l!==u)return Q(l,u);switch(l){case 0:case 0x1fffffffffffff:return 0;case 1:return Q(e.booleanValue,t.booleanValue);case 2:let h,c;return h=eM(e.integerValue||e.doubleValue),h<(c=eM(t.integerValue||t.doubleValue))?-1:h>c?1:h===c?0:isNaN(h)?isNaN(c)?0:-1:1;case 3:return e6(e.timestampValue,t.timestampValue);case 4:return e6(ez(e),ez(t));case 5:return J(e.stringValue,t.stringValue);case 6:let d,f;return r=e.bytesValue,n=t.bytesValue,d=eU(r),f=eU(n),d.compareTo(f);case 7:return function(e,t){let r=e.split("/"),n=t.split("/");for(let e=0;e<r.length&&e<n.length;e++){let t=Q(r[e],n[e]);if(0!==t)return t}return Q(r.length,n.length)}(e.referenceValue,t.referenceValue);case 8:let p;return i=e.geoPointValue,s=t.geoPointValue,0!==(p=Q(eM(i.latitude),eM(s.latitude)))?p:Q(eM(i.longitude),eM(s.longitude));case 9:return e3(e.arrayValue,t.arrayValue);case 10:let m,g,y,v,w;return a=e.mapValue,o=t.mapValue,m=a.fields||{},g=o.fields||{},y=m[eY]?.arrayValue,v=g[eY]?.arrayValue,0!==(w=Q(y?.values?.length||0,v?.values?.length||0))?w:e3(y,v);case 11:return function(e,t){if(e===eJ&&t===eJ)return 0;if(e===eJ)return 1;if(t===eJ)return -1;let r=e.fields||{},n=Object.keys(r),i=t.fields||{},s=Object.keys(i);n.sort(),s.sort();for(let e=0;e<n.length&&e<s.length;++e){let t=J(n[e],s[e]);if(0!==t)return t;let a=e2(r[n[e]],i[s[e]]);if(0!==a)return a}return Q(n.length,s.length)}(e.mapValue,t.mapValue);default:throw L(23264,{he:l})}}function e6(e,t){if("string"==typeof e&&"string"==typeof t&&e.length===t.length)return Q(e,t);let r=ex(e),n=ex(t),i=Q(r.seconds,n.seconds);return 0!==i?i:Q(r.nanos,n.nanos)}function e3(e,t){let r=e.values||[],n=t.values||[];for(let e=0;e<r.length&&e<n.length;++e){let t=e2(r[e],n[e]);if(t)return t}return Q(r.length,n.length)}function e5(e){var t,r;let n;return"nullValue"in e?"null":"booleanValue"in e?""+e.booleanValue:"integerValue"in e?""+e.integerValue:"doubleValue"in e?""+e.doubleValue:"timestampValue"in e?(n=ex(e.timestampValue),`time(${n.seconds},${n.nanos}
1)`):"stringValue"in e?e.stringValue:"bytesValue"in e?eU(e.bytesValue).toBase64():"referenceValue"in e?(t=e.referenceValue,ei.fromName(t).toString()):"geoPointValue"in e?(r=e.geoPointValue,`geo(${r.latitude},${r.longitude})`):"arrayValue"in e?function(e){let t="[",r=!0;for(let n of e.values||[])r?r=!1:t+=",",t+=e5(n);return t+"]"}(e.arrayValue):"mapValue"in e?function(e){let t=Object.keys(e.fields||{}).sort(),r="{",n=!0;for(let i of t)n?n=!1:r+=",",r+=`${i}:${e5(e.fields[i])}`;return r+"}"}(e.mapValue):L(61005,{value:e})}function e8(e,t){return{referenceValue:`projects/${e.projectId}/databases/${e.database}/documents/${t.path.canonicalString()}`}}function e4(e){return!!e&&"integerValue"in e}function e9(e){return!!e&&"arrayValue"in e}function e7(e){return!!e&&"nullValue"in e}function te(e){return!!e&&"doubleValue"in e&&isNaN(Number(e.doubleValue))}function tt(e){return!!e&&"mapValue"in e}function tr(e){return(e?.mapValue?.fields||{})[eW]?.stringValue===eX}function tn(e){if(e.geoPointValue)return{geoPointValue:{...e.geoPointValue}};if(e.timestampValue&&"object"==typeof e.timestampValue)return{timestampValue:{...e.timestampValue}};if(e.mapValue){let t={mapValue:{fields:{}}};return eb(e.mapValue.fields,(e,r)=>t.mapValue.fields[e]=tn(r)),t}if(e.arrayValue){let t={arrayValue:{values:[]}};for(let r=0;r<(e.arrayValue.values||[]).length;++r)t.arrayValue.values[r]=tn(e.arrayValue.values[r]);return t}return{...e}}function ti(e){return(((e.mapValue||{}).fields||{}).__type__||{}).stringValue===eQ}class ts{constructor(e){this.value=e}static empty(){return new ts({mapValue:{}})}field(e){if(e.isEmpty())return this.value;{let t=this.value;for(let r=0;r<e.length-1;++r)if(!tt(t=(t.mapValue.fields||{})[e.get(r)]))return null;return(t=(t.mapValue.fields||{})[e.lastSegment()])||null}}set(e,t){this.getFieldsMap(e.popLast())[e.lastSegment()]=tn(t)}setAll(e){let t=en.emptyPath(),r={},n=[];e.forEach((e,i)=>{if(!t.isImmediateParentOf(i)){let e=this.getFieldsMap(t);this.applyChanges(e,r,n),r={},n=[],t=i.popLast()}e?r[i.lastSegment()]=tn(e):n.push(i.lastSegment())});let i=this.getFieldsMap(t);this.applyChanges(i,r,n)}delete(e){let t=this.field(e.popLast());tt(t)&&t.mapValue.fields&&delete t.mapValue.fields[e.lastSegment()]}isEqual(e){return e0(this.value,e.value)}getFieldsMap(e){let t=this.value;t.mapValue.fields||(t.mapValue={fields:{}});for(let r=0;r<e.length;++r){let n=t.mapValue.fields[e.get(r)];tt(n)&&n.mapValue.fields||(n={mapValue:{fields:{}}},t.mapValue.fields[e.get(r)]=n),t=n}return t.mapValue.fields}applyChanges(e,t,r){for(let n of(eb(t,(t,r)=>e[t]=r),r))delete e[n]}clone(){return new ts(tn(this.value))}}class ta{constructor(e,t,r,n,i,s,a){this.key=e,this.documentType=t,this.version=r,this.readTime=n,this.createTime=i,this.data=s,this.documentState=a}static newInvalidDocument(e){return new ta(e,0,ep.min(),ep.min(),ep.min(),ts.empty(),0)}static newFoundDocument(e,t,r,n){return new ta(e,1,t,ep.min(),r,n,0)}static newNoDocument(e,t){return new ta(e,2,t,ep.min(),ep.min(),ts.empty(),0)}static newUnknownDocument(e,t){return new ta(e,3,t,ep.min(),ep.min(),ts.empty(),2)}convertToFoundDocument(e,t){return this.createTime.isEqual(ep.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=ts.empty(),this.documentState=0,this}convertToUnknownDocument(e){return this.version=e,this.documentType=3,this.data=ts.empty(),this.documentState=2,this}setHasCommittedMutations(){return this.documentState=2,this}setHasLocalMutations(){return this.documentState=1,this.version=ep.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 ta&&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 ta(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}})`}}
1class to{constructor(e,t){this.position=e,this.inclusive=t}}function tl(e,t,r){let n=0;for(let i=0;i<e.position.length;i++){let s=t[i],a=e.position[i];if(n=s.field.isKeyField()?ei.comparator(ei.fromName(a.referenceValue),r.key):e2(a,r.data.field(s.field)),"desc"===s.dir&&(n*=-1),0!==n)break}return n}function tu(e,t){if(null===e)return null===t;if(null===t||e.inclusive!==t.inclusive||e.position.length!==t.position.length)return!1;for(let r=0;r<e.position.length;r++)if(!e0(e.position[r],t.position[r]))return!1;return!0}class th{constructor(e,t="asc"){this.field=e,this.dir=t}}class tc{}class td extends tc{constructor(e,t,r){super(),this.field=e,this.op=t,this.value=r}static create(e,t,r){return e.isKeyField()?"in"===t||"not-in"===t?this.createKeyFieldInFilter(e,t,r):new tg(e,t,r):"array-contains"===t?new tE(e,r):"in"===t?new t_(e,r):"not-in"===t?new tI(e,r):"array-contains-any"===t?new tT(e,r):new td(e,t,r)}static createKeyFieldInFilter(e,t,r){return"in"===t?new ty(e,r):new tv(e,r)}matches(e){let t=e.data.field(this.field);return"!="===this.op?null!==t&&void 0===t.nullValue&&this.matchesComparison(e2(t,this.value)):null!==t&&eZ(this.value)===eZ(t)&&this.matchesComparison(e2(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 L(47266,{operator:this.op})}}isInequality(){return["<","<=",">",">=","!=","not-in"].indexOf(this.op)>=0}getFlattenedFilters(){return[this]}getFilters(){return[this]}}class tf extends tc{constructor(e,t){super(),this.filters=e,this.op=t,this.Pe=null}static create(e,t){return new tf(e,t)}matches(e){return tp(this)?void 0===this.filters.find(t=>!t.matches(e)):void 0!==this.filters.find(t=>t.matches(e))}getFlattenedFilters(){return null!==this.Pe||(this.Pe=this.filters.reduce((e,t)=>e.concat(t.getFlattenedFilters()),[])),this.Pe}getFilters(){return Object.assign([],this.filters)}}function tp(e){return"and"===e.op}function tm(e){for(let t of e.filters)if(t instanceof tf)return!1;return!0}class tg extends td{constructor(e,t,r){super(e,t,r),this.key=ei.fromName(r.referenceValue)}matches(e){let t=ei.comparator(e.key,this.key);return this.matchesComparison(t)}}class ty extends td{constructor(e,t){super(e,"in",t),this.keys=tw("in",t)}matches(e){return this.keys.some(t=>t.isEqual(e.key))}}class tv extends td{constructor(e,t){super(e,"not-in",t),this.keys=tw("not-in",t)}matches(e){return!this.keys.some(t=>t.isEqual(e.key))}}function tw(e,t){return(t.arrayValue?.values||[]).map(e=>ei.fromName(e.referenceValue))}class tE extends td{constructor(e,t){super(e,"array-contains",t)}matches(e){let t=e.data.field(this.field);return e9(t)&&e1(t.arrayValue,this.value)}}class t_ extends td{constructor(e,t){super(e,"in",t)}matches(e){let t=e.data.field(this.field);return null!==t&&e1(this.value.arrayValue,t)}}class tI extends td{constructor(e,t){super(e,"not-in",t)}matches(e){if(e1(this.value.arrayValue,{nullValue:"NULL_VALUE"}))return!1;let t=e.data.field(this.field);return null!==t&&void 0===t.nullValue&&!e1(this.value.arrayValue,t)}}class tT extends td{constructor(e,t){super(e,"array-contains-any",t)}matches(e){let t=e.data.field(this.field);return!(!e9(t)||!t.arrayValue.values)&&t.arrayValue.values.some(e=>e1(this.value.arrayValue,e))}}class tb{constructor(e,t=null,r=[],n=[],i=null,s=null,a=null){this.path=e,this.collectionGroup=t,this.orderBy=r,this.filters=n,this.limit=i,this.startAt=s,this.endAt=a,this.Te=null}}function tS(e,t=null,r=[],n=[],i=null,s=null,a=null){return new tb(e,t,r,n,i,s,a)}function tA(e){if(null===e.Te){let t=e.path.canonicalString();null!==e.collectionGroup&&(t+="|cg:"+e.collectionGroup),t+="|f:",t+=e.filters.map(e=>(function e(t){if(t instanceof td)return t.field.canonicalString()+t.op.toString()+e5(t.value);if(tm(t)&&tp(t))return t.filters.map(t=>e(t)).join(",");{let r=t.filters.map(t=>e(t)).join(",");return`${t.op}(${r})`}})(e)).join(","),t+="|ob:",t+=e.orderBy.map(e=>e.field.canonicalString()+e.dir).join(","),null==e.limit||(t+="|l:",t+=e.limit),e.startAt&&(t+="|lb:",t+=e.startAt.inclusive?"b:":"a:",t+=e.startAt.position.map(e=>e5(e)).join(",")),e.endAt&&(t+="|ub:",t+=e.endAt.inclusive?"a:":"b:",t+=e.endAt.position.map(e=>e5(e)).join(",")),e.Te=t}return e.Te}function tC(e,t){if(e.limit!==t.limit||e.orderBy.length!==t.orderBy.length)return!1;for(let i=0;i<e.orderBy.length;i++){var r,n;if(r=e.orderBy[i],n=t.orderBy[i],!(r.dir===n.dir&&r.field.isEqual(n.field)))return!1}if(e.filters.length!==t.filters.length)return!1;for(let r=0;r<e.filters.length;r++)if(!function e(t,r){return t instanceof td?r instanceof td&&t.op===r.op&&t.field.isEqual(r.field)&&e0(t.value,r.value):t instanceof tf?r instanceof tf&&t.op===r.op&&t.filters.length===r.filters.length&&t.filters.reduce((t,n,i)=>t&&e(n,r.filters[i]),!0):void L(19439)}(e.filters[r],t.filters[r]))return!1;return e.collectionGroup===t.collectionGroup&&!!e.path.isEqual(t.path)&&!!tu(e.startAt,t.startAt)&&tu(e.endAt,t.endAt)}function tk(e){return ei.isDocumentKey(e.path)&&null===e.collectionGroup&&0===e.filters.length}class tN{constructor(e,t=null,r=[],n=[],i=null,s="F",a=null,o=null){this.path=e,this.collectionGroup=t,this.explicitOrderBy=r,this.filters=n,this.limit=i,this.limitType=s,this.startAt=a,this.endAt=o,this.Ee=null,this.Ie=null,this.Re=null,this.startAt,this.endAt}}function tR(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 tD(e){return null!==e.collectionGroup}function tO(e){if(null===e.Ee){let t;
1e.Ee=[];let r=new Set;for(let t of e.explicitOrderBy)e.Ee.push(t),r.add(t.field.canonicalString());let n=e.explicitOrderBy.length>0?e.explicitOrderBy[e.explicitOrderBy.length-1].dir:"asc";(t=new eN(en.comparator),e.filters.forEach(e=>{e.getFlattenedFilters().forEach(e=>{e.isInequality()&&(t=t.add(e.field))})}),t).forEach(t=>{r.has(t.canonicalString())||t.isKeyField()||e.Ee.push(new th(t,n))}),r.has(en.keyField().canonicalString())||e.Ee.push(new th(en.keyField(),n))}return e.Ee}function tP(e){return e.Ie||(e.Ie=function(e,t){if("F"===e.limitType)return tS(e.path,e.collectionGroup,t,e.filters,e.limit,e.startAt,e.endAt);{t=t.map(e=>{let t="desc"===e.dir?"asc":"desc";return new th(e.field,t)});let r=e.endAt?new to(e.endAt.position,e.endAt.inclusive):null,n=e.startAt?new to(e.startAt.position,e.startAt.inclusive):null;return tS(e.path,e.collectionGroup,t,e.filters,e.limit,r,n)}}(e,tO(e))),e.Ie}function tL(e,t){let r=e.filters.concat([t]);return new tN(e.path,e.collectionGroup,e.explicitOrderBy.slice(),r,e.limit,e.limitType,e.startAt,e.endAt)}function tx(e,t,r){return new tN(e.path,e.collectionGroup,e.explicitOrderBy.slice(),e.filters.slice(),t,r,e.startAt,e.endAt)}function tM(e,t){return tC(tP(e),tP(t))&&e.limitType===t.limitType}function tU(e){return`${tA(tP(e))}|lt:${e.limitType}`}function tV(e){var t;let r;return`Query(target=${r=(t=tP(e)).path.canonicalString(),null!==t.collectionGroup&&(r+=" collectionGroup="+t.collectionGroup),t.filters.length>0&&(r+=`, filters: [${t.filters.map(e=>(function e(t){return t instanceof td?`${t.field.canonicalString()} ${t.op} ${e5(t.value)}`:t instanceof tf?t.op.toString()+" {"+t.getFilters().map(e).join(" ,")+"}":"Filter"})(e)).join(", ")}]`),null==t.limit||(r+=", limit: "+t.limit),t.orderBy.length>0&&(r+=`, orderBy: [${t.orderBy.map(e=>`${e.field.canonicalString()} (${e.dir})`).join(", ")}]`),t.startAt&&(r+=", startAt: ",r+=t.startAt.inclusive?"b:":"a:",r+=t.startAt.position.map(e=>e5(e)).join(",")),t.endAt&&(r+=", endAt: ",r+=t.endAt.inclusive?"a:":"b:",r+=t.endAt.position.map(e=>e5(e)).join(",")),`Target(${r})`}; limitType=${e.limitType})`}function tF(e,t){var r,n,i,s;let a,o,l;return t.isFoundDocument()&&(a=t.key.path,null!==e.collectionGroup?t.key.hasCollectionId(e.collectionGroup)&&e.path.isPrefixOf(a):ei.isDocumentKey(e.path)?e.path.isEqual(a):e.path.isImmediateParentOf(a))&&function(e,t){for(let r of tO(e))if(!r.field.isKeyField()&&null===t.data.field(r.field))return!1;return!0}(e,t)&&function(e,t){for(let r of e.filters)if(!r.matches(t))return!1;return!0}(e,t)&&(r=e,n=t,(!r.startAt||(i=r.startAt,o=tl(i,tO(r),n),i.inclusive?!!(o<=0):!!(o<0)))&&(!r.endAt||(s=r.endAt,l=tl(s,tO(r),n),s.inclusive?!!(l>=0):!!(l>0))))}function tj(e){return(t,r)=>{let n=!1;for(let i of tO(e)){let e=function(e,t,r){var n;let i,s,a=e.field.isKeyField()?ei.comparator(t.key,r.key):(n=e.field,i=t.data.field(n),s=r.data.field(n),null!==i&&null!==s?e2(i,s):L(42886));switch(e.dir){case"asc":return a;case"desc":return -1*a;default:return L(19790,{direction:e.dir})}}(i,t,r);if(0!==e)return e;n=n||i.field.isKeyField()}return 0}}class tB{constructor(e,t){this.mapKeyFn=e,this.equalsFn=t,this.inner={},this.innerSize=0}get(e){let t=this.mapKeyFn(e),r=this.inner[t];if(void 0!==r){for(let[t,n]of r)if(this.equalsFn(t,e))return n}}has(e){return void 0!==this.get(e)}set(e,t){let r=this.mapKeyFn(e),n=this.inner[r];if(void 0===n)return this.inner[r]=[[e,t]],void this.innerSize++;for(let r=0;r<n.length;r++)if(this.equalsFn(n[r][0],e))return void(n[r]=[e,t]);n.push([e,t]),this.innerSize++}delete(e){let t=this.mapKeyFn(e),r=this.inner[t];if(void 0===r)return!1;for(let n=0;n<r.length;n++)if(this.equalsFn(r[n][0],e))return 1===r.length?delete this.inner[t]:r.splice(n,1),this.innerSize--,!0;return!1}forEach(e){eb(this.inner,(t,r)=>{for(let[t,n]of r)e(t,n)})}isEmpty(){return eS(this.inner)}size(){return this.innerSize}}let tq=new eA(ei.comparator),t$=new eA(ei.comparator);function tz(...e){let t=t$;for(let r of e)t=t.insert(r.key,r);return t}function tK(e){let t=t$;return e.forEach((e,r)=>t=t.insert(e,r.overlayedDocument)),t}function tH(){return new tB(e=>e.toString(),(e,t)=>e.isEqual(t))}
1let tG=new eA(ei.comparator),tW=new eN(ei.comparator);function tQ(...e){let t=tW;for(let r of e)t=t.add(r);return t}let tJ=new eN(Q);function tX(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:eI(t)?"-0":t}}function tY(e){return{integerValue:""+e}}class tZ{constructor(){this._=void 0}}function t0(e,t){return e instanceof t8?e4(t)||t&&"doubleValue"in t?t:{integerValue:0}:null}class t1 extends tZ{}class t2 extends tZ{constructor(e){super(),this.elements=e}}function t6(e,t){let r=t9(t);for(let t of e.elements)r.some(e=>e0(e,t))||r.push(t);return{arrayValue:{values:r}}}class t3 extends tZ{constructor(e){super(),this.elements=e}}function t5(e,t){let r=t9(t);for(let t of e.elements)r=r.filter(e=>!e0(e,t));return{arrayValue:{values:r}}}class t8 extends tZ{constructor(e,t){super(),this.serializer=e,this.Ae=t}}function t4(e){return eM(e.integerValue||e.doubleValue)}function t9(e){return e9(e)&&e.arrayValue.values?e.arrayValue.values.slice():[]}class t7{constructor(e,t){this.field=e,this.transform=t}}class re{constructor(e,t){this.version=e,this.transformResults=t}}class rt{constructor(e,t){this.updateTime=e,this.exists=t}static none(){return new rt}static exists(e){return new rt(void 0,e)}static updateTime(e){return new rt(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 rr(e,t){return void 0!==e.updateTime?t.isFoundDocument()&&t.version.isEqual(e.updateTime):void 0===e.exists||e.exists===t.isFoundDocument()}class rn{}function ri(e,t){if(!e.hasLocalMutations||t&&0===t.fields.length)return null;if(null===t)return e.isNoDocument()?new rd(e.key,rt.none()):new ro(e.key,e.data,rt.none());{let r=e.data,n=ts.empty(),i=new eN(en.comparator);for(let e of t.fields)if(!i.has(e)){let t=r.field(e);null===t&&e.length>1&&(e=e.popLast(),t=r.field(e)),null===t?n.delete(e):n.set(e,t),i=i.add(e)}return new rl(e.key,n,new eD(i.toArray()),rt.none())}}function rs(e,t,r,n){return e instanceof ro?function(e,t,r,n){if(!rr(e.precondition,t))return r;let i=e.value.clone(),s=rc(e.fieldTransforms,n,t);return i.setAll(s),t.convertToFoundDocument(t.version,i).setHasLocalMutations(),null}(e,t,r,n):e instanceof rl?function(e,t,r,n){if(!rr(e.precondition,t))return r;let i=rc(e.fieldTransforms,n,t),s=t.data;return(s.setAll(ru(e)),s.setAll(i),t.convertToFoundDocument(t.version,s).setHasLocalMutations(),null===r)?null:r.unionWith(e.fieldMask.fields).unionWith(e.fieldTransforms.map(e=>e.field))}(e,t,r,n):rr(e.precondition,t)?(t.convertToNoDocument(t.version).setHasLocalMutations(),null):r}function ra(e,t){var r,n;return e.type===t.type&&!!e.key.isEqual(t.key)&&!!e.precondition.isEqual(t.precondition)&&(r=e.fieldTransforms,n=t.fieldTransforms,!!(void 0===r&&void 0===n||!(!r||!n)&&Y(r,n,(e,t)=>{var r,n;return e.field.isEqual(t.field)&&(r=e.transform,n=t.transform,r instanceof t2&&n instanceof t2||r instanceof t3&&n instanceof t3?Y(r.elements,n.elements,e0):r instanceof t8&&n instanceof t8?e0(r.Ae,n.Ae):r instanceof t1&&n instanceof t1)}
1)))&&(0===e.type?e.value.isEqual(t.value):1!==e.type||e.data.isEqual(t.data)&&e.fieldMask.isEqual(t.fieldMask))}class ro extends rn{constructor(e,t,r,n=[]){super(),this.key=e,this.value=t,this.precondition=r,this.fieldTransforms=n,this.type=0}getFieldMask(){return null}}class rl extends rn{constructor(e,t,r,n,i=[]){super(),this.key=e,this.data=t,this.fieldMask=r,this.precondition=n,this.fieldTransforms=i,this.type=1}getFieldMask(){return this.fieldMask}}function ru(e){let t=new Map;return e.fieldMask.fields.forEach(r=>{if(!r.isEmpty()){let n=e.data.field(r);t.set(r,n)}}),t}function rh(e,t,r){let n=new Map;M(e.length===r.length,32656,{Ve:r.length,de:e.length});for(let s=0;s<r.length;s++){var i;let a=e[s],o=a.transform,l=t.data.field(a.field);n.set(a.field,(i=r[s],o instanceof t2?t6(o,l):o instanceof t3?t5(o,l):i))}return n}function rc(e,t,r){let n=new Map;for(let i of e){let e=i.transform,s=r.data.field(i.field);n.set(i.field,function(e,t,r){var n;let i,s,a;return e instanceof t1?(n=t,i={fields:{[eF]:{stringValue:eV},[eB]:{timestampValue:{seconds:r.seconds,nanos:r.nanoseconds}}}},n&&eq(n)&&(n=e$(n)),n&&(i.fields[ej]=n),{mapValue:i}):e instanceof t2?t6(e,t):e instanceof t3?t5(e,t):(a=t4(s=t0(e,t))+t4(e.Ae),e4(s)&&e4(e.Ae)?tY(a):tX(e.serializer,a))}(e,s,t))}return n}class rd extends rn{constructor(e,t){super(),this.key=e,this.precondition=t,this.type=2,this.fieldTransforms=[]}getFieldMask(){return null}}class rf extends rn{constructor(e,t){super(),this.key=e,this.precondition=t,this.type=3,this.fieldTransforms=[]}getFieldMask(){return null}}class rp{constructor(e,t,r,n){this.batchId=e,this.localWriteTime=t,this.baseMutations=r,this.mutations=n}applyToRemoteDocument(e,t){let r=t.mutationResults;for(let t=0;t<this.mutations.length;t++){let n=this.mutations[t];n.key.isEqual(e.key)&&function(e,t,r){let n,i;e instanceof ro?(n=e.value.clone(),i=rh(e.fieldTransforms,t,r.transformResults),n.setAll(i),t.convertToFoundDocument(r.version,n).setHasCommittedMutations()):e instanceof rl?function(e,t,r){if(!rr(e.precondition,t))return t.convertToUnknownDocument(r.version);let n=rh(e.fieldTransforms,t,r.transformResults),i=t.data;i.setAll(ru(e)),i.setAll(n),t.convertToFoundDocument(r.version,i).setHasCommittedMutations()}(e,t,r):t.convertToNoDocument(r.version).setHasCommittedMutations()}(n,e,r[t])}}applyToLocalView(e,t){for(let r of this.baseMutations)r.key.isEqual(e.key)&&(t=rs(r,e,t,this.localWriteTime));for(let r of this.mutations)r.key.isEqual(e.key)&&(t=rs(r,e,t,this.localWriteTime));return t}applyToLocalDocumentSet(e,t){let r=tH();return this.mutations.forEach(n=>{let i=e.get(n.key),s=i.overlayedDocument,a=this.applyToLocalView(s,i.mutatedFields),o=ri(s,a=t.has(n.key)?null:a);null!==o&&r.set(n.key,o),s.isValidDocument()||s.convertToNoDocument(ep.min())}),r}keys(){return this.mutations.reduce((e,t)=>e.add(t.key),tQ())}isEqual(e){return this.batchId===e.batchId&&Y(this.mutations,e.mutations,(e,t)=>ra(e,t))&&Y(this.baseMutations,e.baseMutations,(e,t)=>ra(e,t))}}class rm{constructor(e,t,r,n){this.batch=e,this.commitVersion=t,this.mutationResults=r,this.docVersions=n}static from(e,t,r){M(e.mutations.length===r.length,58842,{me:e.mutations.length,fe:r.length});let n=tG,i=e.mutations;for(let e=0;e<i.length;e++)n=n.insert(i[e].key,r[e].version);return new rm(e,t,r,n)}}class rg{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{ 2 largestBatchId: ${this.largestBatchId}, 3 mutation: ${this.mutation.toString()} 4 }`}}class ry{constructor(e,t){this.count=e,this.unchangedNames=t}}function rv(e){if(void 0===e)return D("GRPC error has no .code"),U.UNKNOWN;switch(e){case f.OK:return U.OK;case f.CANCELLED:return U.CANCELLED;case f.UNKNOWN:return U.UNKNOWN;case f.DEADLINE_EXCEEDED:return U.DEADLINE_EXCEEDED;case f.RESOURCE_EXHAUSTED:return U.RESOURCE_EXHAUSTED;case f.INTERNAL:return U.INTERNAL;case f.UNAVAILABLE:return U.UNAVAILABLE;case f.UNAUTHENTICATED:return U.UNAUTHENTICATED;case f.INVALID_ARGUMENT:return U.INVALID_ARGUMENT;case f.NOT_FOUND:return U.NOT_FOUND;case f.ALREADY_EXISTS:return U.ALREADY_EXISTS;case f.PERMISSION_DENIED:return U.PERMISSION_DENIED;case f.FAILED_PRECONDITION:return U.FAILED_PRECONDITION;case f.ABORTED:return U.ABORTED;case f.OUT_OF_RANGE:return U.OUT_OF_RANGE;
4case f.UNIMPLEMENTED:return U.UNIMPLEMENTED;case f.DATA_LOSS:return U.DATA_LOSS;default:return L(39323,{code:e})}}(p=f||(f={}))[p.OK=0]="OK",p[p.CANCELLED=1]="CANCELLED",p[p.UNKNOWN=2]="UNKNOWN",p[p.INVALID_ARGUMENT=3]="INVALID_ARGUMENT",p[p.DEADLINE_EXCEEDED=4]="DEADLINE_EXCEEDED",p[p.NOT_FOUND=5]="NOT_FOUND",p[p.ALREADY_EXISTS=6]="ALREADY_EXISTS",p[p.PERMISSION_DENIED=7]="PERMISSION_DENIED",p[p.UNAUTHENTICATED=16]="UNAUTHENTICATED",p[p.RESOURCE_EXHAUSTED=8]="RESOURCE_EXHAUSTED",p[p.FAILED_PRECONDITION=9]="FAILED_PRECONDITION",p[p.ABORTED=10]="ABORTED",p[p.OUT_OF_RANGE=11]="OUT_OF_RANGE",p[p.UNIMPLEMENTED=12]="UNIMPLEMENTED",p[p.INTERNAL=13]="INTERNAL",p[p.UNAVAILABLE=14]="UNAVAILABLE",p[p.DATA_LOSS=15]="DATA_LOSS";let rw=new n([0xffffffff,0xffffffff],0);function rE(e){let t=(new TextEncoder).encode(e),r=new i;return r.update(t),new Uint8Array(r.digest())}function r_(e){let t=new DataView(e.buffer),r=t.getUint32(0,!0),i=t.getUint32(4,!0),s=t.getUint32(8,!0),a=t.getUint32(12,!0);return[new n([r,i],0),new n([s,a],0)]}class rI{constructor(e,t,r){if(this.bitmap=e,this.padding=t,this.hashCount=r,t<0||t>=8)throw new rT(`Invalid padding: ${t}`);if(r<0||e.length>0&&0===this.hashCount)throw new rT(`Invalid hash count: ${r}`);if(0===e.length&&0!==t)throw new rT(`Invalid padding when bitmap length is 0: ${t}`);this.ge=8*e.length-t,this.pe=n.fromNumber(this.ge)}ye(e,t,r){let i=e.add(t.multiply(n.fromNumber(r)));return 1===i.compare(rw)&&(i=new n([i.getBits(0),i.getBits(1)],0)),i.modulo(this.pe).toNumber()}we(e){return!!(this.bitmap[Math.floor(e/8)]&1<<e%8)}mightContain(e){if(0===this.ge)return!1;let[t,r]=r_(rE(e));for(let e=0;e<this.hashCount;e++){let n=this.ye(t,r,e);if(!this.we(n))return!1}return!0}static create(e,t,r){let n=new rI(new Uint8Array(Math.ceil(e/8)),e%8==0?0:8-e%8,t);return r.forEach(e=>n.insert(e)),n}insert(e){if(0===this.ge)return;let[t,r]=r_(rE(e));for(let e=0;e<this.hashCount;e++){let n=this.ye(t,r,e);this.Se(n)}}Se(e){let t=Math.floor(e/8);this.bitmap[t]|=1<<e%8}}class rT extends Error{constructor(){super(...arguments),this.name="BloomFilterError"}}class rb{constructor(e,t,r,n,i){this.snapshotVersion=e,this.targetChanges=t,this.targetMismatches=r,this.documentUpdates=n,this.resolvedLimboDocuments=i}static createSynthesizedRemoteEventForCurrentChange(e,t,r){let n=new Map;return n.set(e,rS.createSynthesizedTargetChangeForCurrentChange(e,t,r)),new rb(ep.min(),n,new eA(Q),tq,tQ())}}class rS{constructor(e,t,r,n,i){this.resumeToken=e,this.current=t,this.addedDocuments=r,this.modifiedDocuments=n,this.removedDocuments=i}static createSynthesizedTargetChangeForCurrentChange(e,t,r){return new rS(r,t,tQ(),tQ(),tQ())}}class rA{constructor(e,t,r,n){this.be=e,this.removedTargetIds=t,this.key=r,this.De=n}}class rC{constructor(e,t){this.targetId=e,this.Ce=t}}class rk{constructor(e,t,r=eP.EMPTY_BYTE_STRING,n=null){this.state=e,this.targetIds=t,this.resumeToken=r,this.cause=n}}class rN{constructor(){this.ve=0,this.Fe=rO(),this.Me=eP.EMPTY_BYTE_STRING,this.xe=!1,this.Oe=!0}get current(){return this.xe}get resumeToken(){return this.Me}get Ne(){return 0!==this.ve}get Be(){return this.Oe}Le(e){e.approximateByteSize()>0&&(this.Oe=!0,this.Me=e)}ke(){let e=tQ(),t=tQ(),r=tQ();return this.Fe.forEach((n,i)=>{switch(i){case 0:e=e.add(n);break;case 2:t=t.add(n);break;case 1:r=r.add(n);break;default:L(38017,{changeType:i})}}),new rS(this.Me,this.xe,e,t,r)}qe(){this.Oe=!1,this.Fe=rO()}Ke(e,t){this.Oe=!0,this.Fe=this.Fe.insert(e,t)}Ue(e){this.Oe=!0,this.Fe=this.Fe.remove(e)}$e(){this.ve+=1}We(){this.ve-=1,M(this.ve>=0,3241,{ve:this.ve})}Qe(){this.Oe=!0,this.xe=!0}}class rR{constructor(e){this.Ge=e,this.ze=new Map,this.je=tq,this.Je=rD(),this.He=rD(),this.Ze=new eA(Q)}Xe(e){for(let t of e.be)e.De&&e.De.isFoundDocument()?this.Ye(t,e.De):this.et(t,e.key,e.De);for(let t of e.removedTargetIds)this.et(t,e.key,e.De)}tt(e){this.forEachTarget(e,t=>{let r=this.nt(t);switch(e.state){case 0:this.rt(t)&&r.Le(e.resumeToken);break;case 1:r.We(),r.Ne||r.qe(),r.Le(e.resumeToken);break;case 2:r.We(),r.Ne||this.removeTarget(t);break;case 3:this.rt(t)&&(r.Qe(),r.Le(e.resumeToken));break;case 4:this.rt(t)&&(this.it(t),r.Le(e.resumeToken));break;default:L(56790,{state:e.state})}})}forEachTarget(e,t){e.targetIds.length>0?e.targetIds.forEach(t):this.ze.forEach((e,r)=>{this.rt(r)&&t(r)})}st(e){let t=e.targetId,r=e.Ce.count,n=this.ot(t);if(n){let i=n.target;if(tk(i))if(0===r){let e=new ei(i.path);this.et(t,e,ta.newNoDocument(e,ep.min()))}else M(1===r,20013,{expectedCount:r});else{let n=this._t(t);if(n!==r){let r=this.ut(e),i=r?this.ct(r,e,n):1;0!==i&&(this.it(t),this.Ze=this.Ze.insert(t,2===i?"TargetPurposeExistenceFilterMismatchBloom":"TargetPurposeExistenceFilterMismatch"))}}}}ut(e){let t,r,n=e.Ce.unchangedNames;if(!n||!n.bits)return null;let{bits:{bitmap:i="",padding:s=0},hashCount:a=0}=n;try{t=eU(i).toUint8Array()}catch(e){if(e instanceof eO)return O("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{r=new rI(t,s,a)}catch(e){return O(e instanceof rT?"BloomFilter error: ":"Applying bloom filter failed: ",e),null}return 0===r.ge?null:r}ct(e,t,r){return 2*(t.Ce.count!==r-this.Pt(e,t.targetId))}Pt(e,t){let r=this.Ge.getRemoteKeysForTarget(t),n=0;return r.forEach(r=>{let i=this.Ge.ht(),s=`projects/${i.projectId}/databases/${i.database}/documents/${r.path.canonicalString()}`;e.mightContain(s)||(this.et(t,r,null),n++)}),n}Tt(e){let t=new Map;this.ze.forEach((r,n)=>{let i=this.ot(n);if(i){if(r.current&&tk(i.target)){let t=new ei(i.target.path);this.Et(t).has(n)||this.It(n,t)||this.et(n,t,ta.newNoDocument(t,e))}r.Be&&(t.set(n,r.ke()),r.qe())}});let r=tQ();this.He.forEach((e,t)=>{let n=!0;t.forEachWhile(e=>{let t=this.ot(e);return!t||"TargetPurposeLimboResolution"===t.purpose||(n=!1,!1)}),n&&(r=r.add(e))}),this.je.forEach((t,r)=>r.setReadTime(e));let n=new rb(e,t,this.Ze,this.je,r);return this.je=tq,this.Je=rD(),this.He=rD(),this.Ze=new eA(Q),n}Ye(e,t){if(!this.rt(e))return;
4let r=2*!!this.It(e,t.key);this.nt(e).Ke(t.key,r),this.je=this.je.insert(t.key,t),this.Je=this.Je.insert(t.key,this.Et(t.key).add(e)),this.He=this.He.insert(t.key,this.Rt(t.key).add(e))}et(e,t,r){if(!this.rt(e))return;let n=this.nt(e);this.It(e,t)?n.Ke(t,1):n.Ue(t),this.He=this.He.insert(t,this.Rt(t).delete(e)),this.He=this.He.insert(t,this.Rt(t).add(e)),r&&(this.je=this.je.insert(t,r))}removeTarget(e){this.ze.delete(e)}_t(e){let t=this.nt(e).ke();return this.Ge.getRemoteKeysForTarget(e).size+t.addedDocuments.size-t.removedDocuments.size}$e(e){this.nt(e).$e()}nt(e){let t=this.ze.get(e);return t||(t=new rN,this.ze.set(e,t)),t}Rt(e){let t=this.He.get(e);return t||(t=new eN(Q),this.He=this.He.insert(e,t)),t}Et(e){let t=this.Je.get(e);return t||(t=new eN(Q),this.Je=this.Je.insert(e,t)),t}rt(e){let t=null!==this.ot(e);return t||R("WatchChangeAggregator","Detected inactive target",e),t}ot(e){let t=this.ze.get(e);return t&&t.Ne?null:this.Ge.At(e)}it(e){this.ze.set(e,new rN),this.Ge.getRemoteKeysForTarget(e).forEach(t=>{this.et(e,t,null)})}It(e,t){return this.Ge.getRemoteKeysForTarget(e).has(t)}}function rD(){return new eA(ei.comparator)}function rO(){return new eA(ei.comparator)}let rP={asc:"ASCENDING",desc:"DESCENDING"},rL={"<":"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"},rx={and:"AND",or:"OR"};class rM{constructor(e,t){this.databaseId=e,this.useProto3Json=t}}function rU(e,t){return e.useProto3Json||null==t?t:{value:t}}function rV(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 rF(e,t){return e.useProto3Json?t.toBase64():t.toUint8Array()}function rj(e){let t;return M(!!e,49232),ep.fromTimestamp(new ef((t=ex(e)).seconds,t.nanos))}function rB(e,t){return rq(e,t).canonicalString()}function rq(e,t){let r=new et(["projects",e.projectId,"databases",e.database]).child("documents");return void 0===t?r:r.child(t)}function r$(e){let t=et.fromString(e);return M(rY(t),10190,{key:t.toString()}),t}function rz(e,t){return rB(e.databaseId,t.path)}function rK(e,t){let r=r$(t);if(r.get(1)!==e.databaseId.projectId)throw new V(U.INVALID_ARGUMENT,"Tried to deserialize key from different project: "+r.get(1)+" vs "+e.databaseId.projectId);if(r.get(3)!==e.databaseId.database)throw new V(U.INVALID_ARGUMENT,"Tried to deserialize key from different database: "+r.get(3)+" vs "+e.databaseId.database);return new ei(rW(r))}function rH(e,t){return rB(e.databaseId,t)}function rG(e){return new et(["projects",e.databaseId.projectId,"databases",e.databaseId.database]).canonicalString()}function rW(e){return M(e.length>4&&"documents"===e.get(4),29091,{key:e.toString()}),e.popFirst(5)}function rQ(e,t,r){return{name:rz(e,t),fields:r.value.mapValue.fields}}function rJ(e){return{fieldPath:e.canonicalString()}}function rX(e){return en.fromServerFormat(e.fieldPath)}function rY(e){return e.length>=4&&"projects"===e.get(0)&&"databases"===e.get(2)}function rZ(e){return!!e&&"function"==typeof e._toProto&&"ProtoValue"===e._protoValueType}class r0{constructor(e,t,r,n,i=ep.min(),s=ep.min(),a=eP.EMPTY_BYTE_STRING,o=null){this.target=e,this.targetId=t,this.purpose=r,this.sequenceNumber=n,this.snapshotVersion=i,this.lastLimboFreeSnapshotVersion=s,this.resumeToken=a,this.expectedCount=o}withSequenceNumber(e){return new r0(this.target,this.targetId,this.purpose,e,this.snapshotVersion,this.lastLimboFreeSnapshotVersion,this.resumeToken,this.expectedCount)}withResumeToken(e,t){return new r0(this.target,this.targetId,this.purpose,this.sequenceNumber,t,this.lastLimboFreeSnapshotVersion,e,null)}withExpectedCount(e){return new r0(this.target,this.targetId,this.purpose,this.sequenceNumber,this.snapshotVersion,this.lastLimboFreeSnapshotVersion,this.resumeToken,e)}withLastLimboFreeSnapshotVersion(e){return new r0(this.target,this.targetId,this.purpose,this.sequenceNumber,this.snapshotVersion,e,this.resumeToken,this.expectedCount)}}class r1{constructor(e){this.yt=e}}class r2{Dt(e,t){this.Ct(e,t),t.vt()}Ct(e,t){if("nullValue"in e)this.Ft(t,5);else if("booleanValue"in e)this.Ft(t,10),t.Mt(+!!e.booleanValue);else if("integerValue"in e)this.Ft(t,15),t.Mt(eM(e.integerValue));else if("doubleValue"in e){let r=eM(e.doubleValue);isNaN(r)?this.Ft(t,13):(this.Ft(t,15),eI(r)?t.Mt(0):t.Mt(r))}else if("timestampValue"in e){let r=e.timestampValue;this.Ft(t,20),"string"==typeof r&&(r=ex(r)),t.xt(`${r.seconds||""}`),t.Mt(r.nanos||0)}else if("stringValue"in e)this.Ot(e.stringValue,t),this.Nt(t);else if("bytesValue"in e)this.Ft(t,30),t.Bt(eU(e.bytesValue)),this.Nt(t);else if("referenceValue"in e)this.Lt(e.referenceValue,t);else if("geoPointValue"in e){let r=e.geoPointValue;this.Ft(t,45),t.Mt(r.latitude||0),t.Mt(r.longitude||0)}else"mapValue"in e?ti(e)?this.Ft(t,Number.MAX_SAFE_INTEGER):tr(e)?this.kt(e.mapValue,t):(this.qt(e.mapValue,t),this.Nt(t)):"arrayValue"in e?(this.Kt(e.arrayValue,t),this.Nt(t)):L(19022,{Ut:e})}Ot(e,t){this.Ft(t,25),this.$t(e,t)}$t(e,t){t.xt(e)}qt(e,t){let r=e.fields||{};for(let e of(this.Ft(t,55),Object.keys(r)))this.Ot(e,t),this.Ct(r[e],t)}kt(e,t){let r=e.fields||{};this.Ft(t,53);let n=r[eY].arrayValue?.values?.length||0;this.Ft(t,15),t.Mt(eM(n)),this.Ot(eY,t),this.Ct(r[eY],t)}Kt(e,t){let r=e.values||[];for(let e of(this.Ft(t,50),r))this.Ct(e,t)}
4Lt(e,t){this.Ft(t,37),ei.fromName(e).path.forEach(e=>{this.Ft(t,60),this.$t(e,t)})}Ft(e,t){e.Mt(t)}Nt(e){e.Mt(2)}}r2.Wt=new r2;class r6{constructor(){this.bn=new r3}addToCollectionParentIndex(e,t){return this.bn.add(t),ew.resolve()}getCollectionParents(e,t){return ew.resolve(this.bn.getEntries(t))}addFieldIndex(e,t){return ew.resolve()}deleteFieldIndex(e,t){return ew.resolve()}deleteAllFieldIndexes(e){return ew.resolve()}createTargetIndexes(e,t){return ew.resolve()}getDocumentsMatchingTarget(e,t){return ew.resolve(null)}getIndexType(e,t){return ew.resolve(0)}getFieldIndexes(e,t){return ew.resolve([])}getNextCollectionGroupToUpdate(e){return ew.resolve(null)}getMinOffset(e,t){return ew.resolve(eg.min())}getMinOffsetFromCollectionGroup(e,t){return ew.resolve(eg.min())}updateCollectionGroup(e,t,r){return ew.resolve()}updateIndexEntries(e,t){return ew.resolve()}}class r3{constructor(){this.index={}}add(e){let t=e.lastSegment(),r=e.popLast(),n=this.index[t]||new eN(et.comparator),i=!n.has(r);return this.index[t]=n.add(r),i}has(e){let t=e.lastSegment(),r=e.popLast(),n=this.index[t];return n&&n.has(r)}getEntries(e){return(this.index[e]||new eN(et.comparator)).toArray()}}new Uint8Array(0);let r5={didRun:!1,sequenceNumbersCollected:0,targetsRemoved:0,documentsRemoved:0};class r8{static withCacheSize(e){return new r8(e,r8.DEFAULT_COLLECTION_PERCENTILE,r8.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT)}constructor(e,t,r){this.cacheSizeCollectionThreshold=e,this.percentileToCollect=t,this.maximumSequenceNumbersToCollect=r}}r8.DEFAULT_COLLECTION_PERCENTILE=10,r8.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT=1e3,r8.DEFAULT=new r8(0x2800000,r8.DEFAULT_COLLECTION_PERCENTILE,r8.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT),r8.DISABLED=new r8(-1,0,0);class r4{constructor(e){this.sr=e}next(){return this.sr+=2,this.sr}static _r(){return new r4(0)}static ar(){return new r4(-1)}}let r9="LruGarbageCollector";function r7([e,t],[r,n]){let i=Q(e,r);return 0===i?Q(t,n):i}class ne{constructor(e){this.Pr=e,this.buffer=new eN(r7),this.Tr=0}Er(){return++this.Tr}Ir(e){let t=[e,this.Er()];if(this.buffer.size<this.Pr)this.buffer=this.buffer.add(t);else{let e=this.buffer.last();0>r7(t,e)&&(this.buffer=this.buffer.delete(e).add(t))}}get maxValue(){return this.buffer.last()[0]}}class nt{constructor(e,t,r){this.garbageCollector=e,this.asyncQueue=t,this.localStore=r,this.Rr=null}start(){-1!==this.garbageCollector.params.cacheSizeCollectionThreshold&&this.Ar(6e4)}stop(){this.Rr&&(this.Rr.cancel(),this.Rr=null)}get started(){return null!==this.Rr}Ar(e){R(r9,`Garbage collection scheduled in ${e}ms`),this.Rr=this.asyncQueue.enqueueAfterDelay("lru_garbage_collection",e,async()=>{this.Rr=null;try{await this.localStore.collectGarbage(this.garbageCollector)}catch(e){eE(e)?R(r9,"Ignoring IndexedDB error during garbage collection: ",e):await ev(e)}await this.Ar(3e5)})}}class nr{constructor(e,t){this.Vr=e,this.params=t}calculateTargetCount(e,t){return this.Vr.dr(e).next(e=>Math.floor(t/100*e))}nthSequenceNumber(e,t){if(0===t)return ew.resolve(e_.ce);let r=new ne(t);return this.Vr.forEachTarget(e,e=>r.Ir(e.sequenceNumber)).next(()=>this.Vr.mr(e,e=>r.Ir(e))).next(()=>r.maxValue)}removeTargets(e,t,r){return this.Vr.removeTargets(e,t,r)}removeOrphanedDocuments(e,t){return this.Vr.removeOrphanedDocuments(e,t)}collect(e,t){return -1===this.params.cacheSizeCollectionThreshold?(R("LruGarbageCollector","Garbage collection skipped; disabled"),ew.resolve(r5)):this.getCacheSize(e).next(r=>r<this.params.cacheSizeCollectionThreshold?(R("LruGarbageCollector",`Garbage collection skipped; Cache size ${r} is lower than threshold ${this.params.cacheSizeCollectionThreshold}`),r5):this.gr(e,t))}getCacheSize(e){return this.Vr.getCacheSize(e)}gr(e,t){let r,n,i,s,a,o,l,u=Date.now();return this.calculateTargetCount(e,this.params.percentileToCollect).next(t=>(t>this.params.maximumSequenceNumbersToCollect?(R("LruGarbageCollector",`Capping sequence numbers to collect down to the maximum of ${this.params.maximumSequenceNumbersToCollect} from ${t}`),n=this.params.maximumSequenceNumbersToCollect):n=t,s=Date.now(),this.nthSequenceNumber(e,n))).next(n=>(r=n,a=Date.now(),this.removeTargets(e,r,t))).next(t=>(i=t,o=Date.now(),this.removeOrphanedDocuments(e,r))).next(e=>(l=Date.now(),N()<=I.$b.DEBUG&&R("LruGarbageCollector",`LRU Garbage Collection 5 Counted targets in ${s-u}ms 6 Determined least recently used ${n} in `+(a-s)+"ms\n"+` Removed ${i} targets in `+(o-a)+"ms\n"+` Removed ${e} documents in `+(l-o)+"ms\n"+`Total Duration: ${l-u}ms`),ew.resolve({didRun:!0,sequenceNumbersCollected:n,targetsRemoved:i,documentsRemoved:e})))}}class nn{constructor(){this.changes=new tB(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,ta.newInvalidDocument(e).setReadTime(t))}getEntry(e,t){this.assertNotApplied();let r=this.changes.get(t);return void 0!==r?ew.resolve(r):this.getFromCache(e,t)}getEntries(e,t){return this.getAllFromCache(e,t)}apply(e){return this.assertNotApplied(),this.changesApplied=!0,this.applyChanges(e)}
6assertNotApplied(){}}class ni{constructor(e,t){this.overlayedDocument=e,this.mutatedFields=t}}class ns{constructor(e,t,r,n){this.remoteDocumentCache=e,this.mutationQueue=t,this.documentOverlayCache=r,this.indexManager=n}getDocument(e,t){let r=null;return this.documentOverlayCache.getOverlay(e,t).next(n=>(r=n,this.remoteDocumentCache.getEntry(e,t))).next(e=>(null!==r&&rs(r.mutation,e,eD.empty(),ef.now()),e))}getDocuments(e,t){return this.remoteDocumentCache.getEntries(e,t).next(t=>this.getLocalViewOfDocuments(e,t,tQ()).next(()=>t))}getLocalViewOfDocuments(e,t,r=tQ()){let n=tH();return this.populateOverlays(e,n,t).next(()=>this.computeViews(e,t,n,r).next(e=>{let t=tz();return e.forEach((e,r)=>{t=t.insert(e,r.overlayedDocument)}),t}))}getOverlayedDocuments(e,t){let r=tH();return this.populateOverlays(e,r,t).next(()=>this.computeViews(e,t,r,tQ()))}populateOverlays(e,t,r){let n=[];return r.forEach(e=>{t.has(e)||n.push(e)}),this.documentOverlayCache.getOverlays(e,n).next(e=>{e.forEach((e,r)=>{t.set(e,r)})})}computeViews(e,t,r,n){let i=tq,s=tH(),a=tH();return t.forEach((e,t)=>{let a=r.get(t.key);n.has(t.key)&&(void 0===a||a.mutation instanceof rl)?i=i.insert(t.key,t):void 0!==a?(s.set(t.key,a.mutation.getFieldMask()),rs(a.mutation,t,a.mutation.getFieldMask(),ef.now())):s.set(t.key,eD.empty())}),this.recalculateAndSaveOverlays(e,i).next(e=>(e.forEach((e,t)=>s.set(e,t)),t.forEach((e,t)=>a.set(e,new ni(t,s.get(e)??null))),a))}recalculateAndSaveOverlays(e,t){let r=tH(),n=new eA((e,t)=>e-t),i=tQ();return this.mutationQueue.getAllMutationBatchesAffectingDocumentKeys(e,t).next(e=>{for(let i of e)i.keys().forEach(e=>{let s=t.get(e);if(null===s)return;let a=r.get(e)||eD.empty();a=i.applyToLocalView(s,a),r.set(e,a);let o=(n.get(i.batchId)||tQ()).add(e);n=n.insert(i.batchId,o)})}).next(()=>{let s=[],a=n.getReverseIterator();for(;a.hasNext();){let n=a.getNext(),o=n.key,l=n.value,u=tH();l.forEach(e=>{if(!i.has(e)){let n=ri(t.get(e),r.get(e));null!==n&&u.set(e,n),i=i.add(e)}}),s.push(this.documentOverlayCache.saveOverlays(e,o,u))}return ew.waitFor(s)}).next(()=>r)}recalculateAndSaveOverlaysForDocumentKeys(e,t){return this.remoteDocumentCache.getEntries(e,t).next(t=>this.recalculateAndSaveOverlays(e,t))}getDocumentsMatchingQuery(e,t,r,n){return ei.isDocumentKey(t.path)&&null===t.collectionGroup&&0===t.filters.length?this.getDocumentsMatchingDocumentQuery(e,t.path):tD(t)?this.getDocumentsMatchingCollectionGroupQuery(e,t,r,n):this.getDocumentsMatchingCollectionQuery(e,t,r,n)}getNextDocuments(e,t,r,n){return this.remoteDocumentCache.getAllFromCollectionGroup(e,t,r,n).next(i=>{let s=n-i.size>0?this.documentOverlayCache.getOverlaysForCollectionGroup(e,t,r.largestBatchId,n-i.size):ew.resolve(tH()),a=-1,o=i;return s.next(t=>ew.forEach(t,(t,r)=>(a<r.largestBatchId&&(a=r.largestBatchId),i.get(t)?ew.resolve():this.remoteDocumentCache.getEntry(e,t).next(e=>{o=o.insert(t,e)}))).next(()=>this.populateOverlays(e,t,i)).next(()=>this.computeViews(e,o,t,tQ())).next(e=>({batchId:a,changes:tK(e)})))})}getDocumentsMatchingDocumentQuery(e,t){return this.getDocument(e,new ei(t)).next(e=>{let t=tz();return e.isFoundDocument()&&(t=t.insert(e.key,e)),t})}getDocumentsMatchingCollectionGroupQuery(e,t,r,n){let i=t.collectionGroup,s=tz();return this.indexManager.getCollectionParents(e,i).next(a=>ew.forEach(a,a=>{let o=new tN(a.child(i),null,t.explicitOrderBy.slice(),t.filters.slice(),t.limit,t.limitType,t.startAt,t.endAt);return this.getDocumentsMatchingCollectionQuery(e,o,r,n).next(e=>{e.forEach((e,t)=>{s=s.insert(e,t)})})}).next(()=>s))}getDocumentsMatchingCollectionQuery(e,t,r,n){let i;return this.documentOverlayCache.getOverlaysForCollection(e,t.path,r.largestBatchId).next(s=>(i=s,this.remoteDocumentCache.getDocumentsMatchingQuery(e,t,r,i,n))).next(e=>{i.forEach((t,r)=>{let n=r.getKey();null===e.get(n)&&(e=e.insert(n,ta.newInvalidDocument(n)))});let r=tz();return e.forEach((e,n)=>{let s=i.get(e);void 0!==s&&rs(s.mutation,n,eD.empty(),ef.now()),tF(t,n)&&(r=r.insert(e,n))}),r})}}class na{constructor(e){this.serializer=e,this.Nr=new Map,this.Br=new Map}getBundleMetadata(e,t){return ew.resolve(this.Nr.get(t))}
6saveBundleMetadata(e,t){return this.Nr.set(t.id,{id:t.id,version:t.version,createTime:rj(t.createTime)}),ew.resolve()}getNamedQuery(e,t){return ew.resolve(this.Br.get(t))}saveNamedQuery(e,t){var r;let n;return this.Br.set(t.name,{name:t.name,query:(n=function(e){var t,r,n,i;let s,a,o,l,u,h=4===(s=r$(e.parent)).length?et.emptyPath():rW(s),c=e.structuredQuery,d=c.from?c.from.length:0,f=null;if(d>0){M(1===d,65062);let e=c.from[0];e.allDescendants?f=e.collectionId:h=h.child(e.collectionId)}let p=[];c.where&&(p=(a=function e(t){return void 0!==t.unaryFilter?function(e){switch(e.unaryFilter.op){case"IS_NAN":let t=rX(e.unaryFilter.field);return td.create(t,"==",{doubleValue:NaN});case"IS_NULL":let r=rX(e.unaryFilter.field);return td.create(r,"==",{nullValue:"NULL_VALUE"});case"IS_NOT_NAN":let n=rX(e.unaryFilter.field);return td.create(n,"!=",{doubleValue:NaN});case"IS_NOT_NULL":let i=rX(e.unaryFilter.field);return td.create(i,"!=",{nullValue:"NULL_VALUE"});case"OPERATOR_UNSPECIFIED":return L(61313);default:return L(60726)}}(t):void 0!==t.fieldFilter?td.create(rX(t.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";case"OPERATOR_UNSPECIFIED":return L(58110);default:return L(50506)}}(t.fieldFilter.op),t.fieldFilter.value):void 0!==t.compositeFilter?tf.create(t.compositeFilter.filters.map(t=>e(t)),function(e){switch(e){case"AND":return"and";case"OR":return"or";default:return L(1026)}}(t.compositeFilter.op)):L(30097,{filter:t})}(c.where))instanceof tf&&tm(t=a)&&tp(t)?a.getFilters():[a]);let m=[];c.orderBy&&(m=c.orderBy.map(e=>new th(rX(e.field),function(e){switch(e){case"ASCENDING":return"asc";case"DESCENDING":return"desc";default:return}}(e.direction))));let g=null;c.limit&&(g=null==(o="object"==typeof(r=c.limit)?r.value:r)?null:o);let y=null;c.startAt&&(l=!!(n=c.startAt).before,y=new to(n.values||[],l));let v=null;return c.endAt&&(u=!(i=c.endAt).before,v=new to(i.values||[],u)),new tN(h,f,m,p,g,"F",y,v)}({parent:(r=t.bundledQuery).parent,structuredQuery:r.structuredQuery}),"LAST"===r.limitType?tx(n,n.limit,"L"):n),readTime:rj(t.readTime)}),ew.resolve()}}class no{constructor(){this.overlays=new eA(ei.comparator),this.Lr=new Map}getOverlay(e,t){return ew.resolve(this.overlays.get(t))}getOverlays(e,t){let r=tH();return ew.forEach(t,t=>this.getOverlay(e,t).next(e=>{null!==e&&r.set(t,e)})).next(()=>r)}saveOverlays(e,t,r){return r.forEach((r,n)=>{this.St(e,t,n)}),ew.resolve()}removeOverlaysForBatchId(e,t,r){let n=this.Lr.get(r);return void 0!==n&&(n.forEach(e=>this.overlays=this.overlays.remove(e)),this.Lr.delete(r)),ew.resolve()}getOverlaysForCollection(e,t,r){let n=tH(),i=t.length+1,s=new ei(t.child("")),a=this.overlays.getIteratorFrom(s);for(;a.hasNext();){let e=a.getNext().value,s=e.getKey();if(!t.isPrefixOf(s.path))break;s.path.length===i&&e.largestBatchId>r&&n.set(e.getKey(),e)}return ew.resolve(n)}getOverlaysForCollectionGroup(e,t,r,n){let i=new eA((e,t)=>e-t),s=this.overlays.getIterator();for(;s.hasNext();){let e=s.getNext().value;if(e.getKey().getCollectionGroup()===t&&e.largestBatchId>r){let t=i.get(e.largestBatchId);null===t&&(t=tH(),i=i.insert(e.largestBatchId,t)),t.set(e.getKey(),e)}}let a=tH(),o=i.getIterator();for(;o.hasNext()&&(o.getNext().value.forEach((e,t)=>a.set(e,t)),!(a.size()>=n)););return ew.resolve(a)}St(e,t,r){let n=this.overlays.get(r.key);if(null!==n){let e=this.Lr.get(n.largestBatchId).delete(r.key);this.Lr.set(n.largestBatchId,e)}this.overlays=this.overlays.insert(r.key,new rg(t,r));let i=this.Lr.get(t);void 0===i&&(i=tQ(),this.Lr.set(t,i)),this.Lr.set(t,i.add(r.key))}}class nl{constructor(){this.sessionToken=eP.EMPTY_BYTE_STRING}getSessionToken(e){return ew.resolve(this.sessionToken)}setSessionToken(e,t){return this.sessionToken=t,ew.resolve()}}class nu{constructor(){this.kr=new eN(nh.qr),this.Kr=new eN(nh.Ur)}isEmpty(){return this.kr.isEmpty()}addReference(e,t){let r=new nh(e,t);this.kr=this.kr.add(r),this.Kr=this.Kr.add(r)}
6$r(e,t){e.forEach(e=>this.addReference(e,t))}removeReference(e,t){this.Wr(new nh(e,t))}Qr(e,t){e.forEach(e=>this.removeReference(e,t))}Gr(e){let t=new ei(new et([])),r=new nh(t,e),n=new nh(t,e+1),i=[];return this.Kr.forEachInRange([r,n],e=>{this.Wr(e),i.push(e.key)}),i}zr(){this.kr.forEach(e=>this.Wr(e))}Wr(e){this.kr=this.kr.delete(e),this.Kr=this.Kr.delete(e)}jr(e){let t=new ei(new et([])),r=new nh(t,e),n=new nh(t,e+1),i=tQ();return this.Kr.forEachInRange([r,n],e=>{i=i.add(e.key)}),i}containsKey(e){let t=new nh(e,0),r=this.kr.firstAfterOrEqual(t);return null!==r&&e.isEqual(r.key)}}class nh{constructor(e,t){this.key=e,this.Jr=t}static qr(e,t){return ei.comparator(e.key,t.key)||Q(e.Jr,t.Jr)}static Ur(e,t){return Q(e.Jr,t.Jr)||ei.comparator(e.key,t.key)}}class nc{constructor(e,t){this.indexManager=e,this.referenceDelegate=t,this.mutationQueue=[],this.Yn=1,this.Hr=new eN(nh.qr)}checkEmpty(e){return ew.resolve(0===this.mutationQueue.length)}addMutationBatch(e,t,r,n){let i=this.Yn;this.Yn++,this.mutationQueue.length>0&&this.mutationQueue[this.mutationQueue.length-1];let s=new rp(i,t,r,n);for(let t of(this.mutationQueue.push(s),n))this.Hr=this.Hr.add(new nh(t.key,i)),this.indexManager.addToCollectionParentIndex(e,t.key.path.popLast());return ew.resolve(s)}lookupMutationBatch(e,t){return ew.resolve(this.Zr(t))}getNextMutationBatchAfterBatchId(e,t){let r=this.Xr(t+1),n=r<0?0:r;return ew.resolve(this.mutationQueue.length>n?this.mutationQueue[n]:null)}getHighestUnacknowledgedBatchId(){return ew.resolve(0===this.mutationQueue.length?-1:this.Yn-1)}getAllMutationBatches(e){return ew.resolve(this.mutationQueue.slice())}getAllMutationBatchesAffectingDocumentKey(e,t){let r=new nh(t,0),n=new nh(t,1/0),i=[];return this.Hr.forEachInRange([r,n],e=>{let t=this.Zr(e.Jr);i.push(t)}),ew.resolve(i)}getAllMutationBatchesAffectingDocumentKeys(e,t){let r=new eN(Q);return t.forEach(e=>{let t=new nh(e,0),n=new nh(e,1/0);this.Hr.forEachInRange([t,n],e=>{r=r.add(e.Jr)})}),ew.resolve(this.Yr(r))}getAllMutationBatchesAffectingQuery(e,t){let r=t.path,n=r.length+1,i=r;ei.isDocumentKey(i)||(i=i.child(""));let s=new nh(new ei(i),0),a=new eN(Q);return this.Hr.forEachWhile(e=>{let t=e.key.path;return!!r.isPrefixOf(t)&&(t.length===n&&(a=a.add(e.Jr)),!0)},s),ew.resolve(this.Yr(a))}Yr(e){let t=[];return e.forEach(e=>{let r=this.Zr(e);null!==r&&t.push(r)}),t}removeMutationBatch(e,t){M(0===this.ei(t.batchId,"removed"),55003),this.mutationQueue.shift();let r=this.Hr;return ew.forEach(t.mutations,n=>{let i=new nh(n.key,t.batchId);return r=r.delete(i),this.referenceDelegate.markPotentiallyOrphaned(e,n.key)}).next(()=>{this.Hr=r})}nr(e){}containsKey(e,t){let r=new nh(t,0),n=this.Hr.firstAfterOrEqual(r);return ew.resolve(t.isEqual(n&&n.key))}performConsistencyCheck(e){return this.mutationQueue.length,ew.resolve()}ei(e,t){return this.Xr(e)}Xr(e){return 0===this.mutationQueue.length?0:e-this.mutationQueue[0].batchId}Zr(e){let t=this.Xr(e);return t<0||t>=this.mutationQueue.length?null:this.mutationQueue[t]}}class nd{constructor(e){this.ti=e,this.docs=new eA(ei.comparator),this.size=0}setIndexManager(e){this.indexManager=e}addEntry(e,t){let r=t.key,n=this.docs.get(r),i=n?n.size:0,s=this.ti(t);return this.docs=this.docs.insert(r,{document:t.mutableCopy(),size:s}),this.size+=s-i,this.indexManager.addToCollectionParentIndex(e,r.path.popLast())}removeEntry(e){let t=this.docs.get(e);t&&(this.docs=this.docs.remove(e),this.size-=t.size)}getEntry(e,t){let r=this.docs.get(t);return ew.resolve(r?r.document.mutableCopy():ta.newInvalidDocument(t))}getEntries(e,t){let r=tq;return t.forEach(e=>{let t=this.docs.get(e);r=r.insert(e,t?t.document.mutableCopy():ta.newInvalidDocument(e))}),ew.resolve(r)}getDocumentsMatchingQuery(e,t,r,n){let i=tq,s=t.path,a=new ei(s.child("__id-9223372036854775808__")),o=this.docs.getIteratorFrom(a);for(;o.hasNext();){let{key:e,value:{document:a}}=o.getNext();if(!s.isPrefixOf(e.path))break;e.path.length>s.length+1||0>=function(e,t){let r=e.readTime.compareTo(t.readTime);return 0!==r||0!==(r=ei.comparator(e.documentKey,t.documentKey))?r:Q(e.largestBatchId,t.largestBatchId)}(new eg(a.readTime,a.key,-1),r)||(n.has(a.key)||tF(t,a))&&(i=i.insert(a.key,a.mutableCopy()))}return ew.resolve(i)}getAllFromCollectionGroup(e,t,r,n){L(9500)}
vendor: 4,102 bytes, line 6
6ni(e,t){return ew.forEach(this.docs,e=>t(e))}newChangeBuffer(e){return new nf(this)}getSize(e){return ew.resolve(this.size)}}class nf extends nn{constructor(e){super(),this.Mr=e}applyChanges(e){let t=[];return this.changes.forEach((r,n)=>{n.isValidDocument()?t.push(this.Mr.addEntry(e,n)):this.Mr.removeEntry(r)}),ew.waitFor(t)}getFromCache(e,t){return this.Mr.getEntry(e,t)}getAllFromCache(e,t){return this.Mr.getEntries(e,t)}}class np{constructor(e){this.persistence=e,this.ri=new tB(e=>tA(e),tC),this.lastRemoteSnapshotVersion=ep.min(),this.highestTargetId=0,this.ii=0,this.si=new nu,this.targetCount=0,this.oi=r4._r()}forEachTarget(e,t){return this.ri.forEach((e,r)=>t(r)),ew.resolve()}getLastRemoteSnapshotVersion(e){return ew.resolve(this.lastRemoteSnapshotVersion)}getHighestSequenceNumber(e){return ew.resolve(this.ii)}allocateTargetId(e){return this.highestTargetId=this.oi.next(),ew.resolve(this.highestTargetId)}setTargetsMetadata(e,t,r){return r&&(this.lastRemoteSnapshotVersion=r),t>this.ii&&(this.ii=t),ew.resolve()}lr(e){this.ri.set(e.target,e);let t=e.targetId;t>this.highestTargetId&&(this.oi=new r4(t),this.highestTargetId=t),e.sequenceNumber>this.ii&&(this.ii=e.sequenceNumber)}addTargetData(e,t){return this.lr(t),this.targetCount+=1,ew.resolve()}updateTargetData(e,t){return this.lr(t),ew.resolve()}removeTargetData(e,t){return this.ri.delete(t.target),this.si.Gr(t.targetId),this.targetCount-=1,ew.resolve()}removeTargets(e,t,r){let n=0,i=[];return this.ri.forEach((s,a)=>{a.sequenceNumber<=t&&null===r.get(a.targetId)&&(this.ri.delete(s),i.push(this.removeMatchingKeysForTargetId(e,a.targetId)),n++)}),ew.waitFor(i).next(()=>n)}getTargetCount(e){return ew.resolve(this.targetCount)}getTargetData(e,t){let r=this.ri.get(t)||null;return ew.resolve(r)}addMatchingKeys(e,t,r){return this.si.$r(t,r),ew.resolve()}removeMatchingKeys(e,t,r){this.si.Qr(t,r);let n=this.persistence.referenceDelegate,i=[];return n&&t.forEach(t=>{i.push(n.markPotentiallyOrphaned(e,t))}),ew.waitFor(i)}removeMatchingKeysForTargetId(e,t){return this.si.Gr(t),ew.resolve()}getMatchingKeysForTargetId(e,t){let r=this.si.jr(t);return ew.resolve(r)}containsKey(e,t){return ew.resolve(this.si.containsKey(t))}}class nm{constructor(e,t){this._i={},this.overlays={},this.ai=new e_(0),this.ui=!1,this.ui=!0,this.ci=new nl,this.referenceDelegate=e(this),this.li=new np(this),this.indexManager=new r6,this.remoteDocumentCache=function(e){return new nd(e)}(e=>this.referenceDelegate.hi(e)),this.serializer=new r1(t),this.Pi=new na(this.serializer)}start(){return Promise.resolve()}shutdown(){return this.ui=!1,Promise.resolve()}get started(){return this.ui}setDatabaseDeletedListener(){}setNetworkEnabled(){}getIndexManager(e){return this.indexManager}getDocumentOverlayCache(e){let t=this.overlays[e.toKey()];return t||(t=new no,this.overlays[e.toKey()]=t),t}getMutationQueue(e,t){let r=this._i[e.toKey()];return r||(r=new nc(t,this.referenceDelegate),this._i[e.toKey()]=r),r}getGlobalsCache(){return this.ci}getTargetCache(){return this.li}getRemoteDocumentCache(){return this.remoteDocumentCache}getBundleCache(){return this.Pi}runTransaction(e,t,r){R("MemoryPersistence","Starting transaction:",e);let n=new ng(this.ai.next());return this.referenceDelegate.Ti(),r(n).next(e=>this.referenceDelegate.Ei(n).next(()=>e)).toPromise().then(e=>(n.raiseOnCommittedEvent(),e))}Ii(e,t){return ew.or(Object.values(this._i).map(r=>()=>r.containsKey(e,t)))}}class ng extends ey{constructor(e){super(),this.currentSequenceNumber=e}}class ny{constructor(e){this.persistence=e,this.Ri=new nu,this.Ai=null}static Vi(e){return new ny(e)}get di(){if(this.Ai)return this.Ai;throw L(60996)}addReference(e,t,r){return this.Ri.addReference(r,t),this.di.delete(r.toString()),ew.resolve()}removeReference(e,t,r){return this.Ri.removeReference(r,t),this.di.add(r.toString()),ew.resolve()}markPotentiallyOrphaned(e,t){return this.di.add(t.toString()),ew.resolve()}removeTarget(e,t){this.Ri.Gr(t.targetId).forEach(e=>this.di.add(e.toString()));let r=this.persistence.getTargetCache();return r.getMatchingKeysForTargetId(e,t.targetId).next(e=>
6{e.forEach(e=>this.di.add(e.toString()))}).next(()=>r.removeTargetData(e,t))}Ti(){this.Ai=new Set}Ei(e){let t=this.persistence.getRemoteDocumentCache().newChangeBuffer();return ew.forEach(this.di,r=>{let n=ei.fromPath(r);return this.mi(e,n).next(e=>{e||t.removeEntry(n,ep.min())})}).next(()=>(this.Ai=null,t.apply(e)))}updateLimboDocument(e,t){return this.mi(e,t).next(e=>{e?this.di.delete(t.toString()):this.di.add(t.toString())})}hi(e){return 0}mi(e,t){return ew.or([()=>ew.resolve(this.Ri.containsKey(t)),()=>this.persistence.getTargetCache().containsKey(e,t),()=>this.persistence.Ii(e,t)])}}class nv{constructor(e,t){this.persistence=e,this.fi=new tB(e=>(function(e){let t="";for(let r=0;r<e.length;r++)t.length>0&&(t+="\x01\x01"),t=function(e,t){let r=t,n=e.length;for(let t=0;t<n;t++){let n=e.charAt(t);switch(n){case"\0":r+="\x01\x10";break;case"\x01":r+="\x01\x11";break;default:r+=n}}return r}(e.get(r),t);return t+"\x01\x01"})(e.path),(e,t)=>e.isEqual(t)),this.garbageCollector=function(e,t){return new nr(e,t)}(this,t)}static Vi(e,t){return new nv(e,t)}Ti(){}Ei(e){return ew.resolve()}forEachTarget(e,t){return this.persistence.getTargetCache().forEachTarget(e,t)}dr(e){let t=this.pr(e);return this.persistence.getTargetCache().getTargetCount(e).next(e=>t.next(t=>e+t))}pr(e){let t=0;return this.mr(e,e=>{t++}).next(()=>t)}mr(e,t){return ew.forEach(this.fi,(r,n)=>this.wr(e,r,n).next(e=>e?ew.resolve():t(n)))}removeTargets(e,t,r){return this.persistence.getTargetCache().removeTargets(e,t,r)}removeOrphanedDocuments(e,t){let r=0,n=this.persistence.getRemoteDocumentCache(),i=n.newChangeBuffer();return n.ni(e,n=>this.wr(e,n,t).next(e=>{e||(r++,i.removeEntry(n,ep.min()))})).next(()=>i.apply(e)).next(()=>r)}markPotentiallyOrphaned(e,t){return this.fi.set(t,e.currentSequenceNumber),ew.resolve()}removeTarget(e,t){let r=t.withSequenceNumber(e.currentSequenceNumber);return this.persistence.getTargetCache().updateTargetData(e,r)}addReference(e,t,r){return this.fi.set(r,e.currentSequenceNumber),ew.resolve()}removeReference(e,t,r){return this.fi.set(r,e.currentSequenceNumber),ew.resolve()}updateLimboDocument(e,t){return this.fi.set(t,e.currentSequenceNumber),ew.resolve()}hi(e){let t=e.key.toString().length;return e.isFoundDocument()&&(t+=function e(t){switch(eZ(t)){case 0:case 1:return 4;case 2:return 8;case 3:case 8:return 16;case 4:let r=e$(t);return r?16+e(r):16;case 5:return 2*t.stringValue.length;case 6:return eU(t.bytesValue).approximateByteSize();case 7:return t.referenceValue.length;case 9:return(t.arrayValue.values||[]).reduce((t,r)=>t+e(r),0);case 10:case 11:var n;let i;return n=t.mapValue,i=0,eb(n.fields,(t,r)=>{i+=t.length+e(r)}),i;default:throw L(13486,{value:t})}}(e.data.value)),t}wr(e,t,r){return ew.or([()=>this.persistence.Ii(e,t),()=>this.persistence.getTargetCache().containsKey(e,t),()=>{let e=this.fi.get(t);return ew.resolve(void 0!==e&&e>r)}])}getCacheSize(e){return this.persistence.getRemoteDocumentCache().getSize(e)}}class nw{constructor(e,t,r,n){this.targetId=e,this.fromCache=t,this.Ts=r,this.Es=n}static Is(e,t){let r=tQ(),n=tQ();for(let e of t.docChanges)switch(e.type){case 0:r=r.add(e.doc.key);break;case 1:n=n.add(e.doc.key)}return new nw(e,t.fromCache,r,n)}}class nE{constructor(){this._documentReadCount=0}get documentReadCount(){return this._documentReadCount}incrementDocumentReadCount(e){this._documentReadCount+=e}}class n_{constructor(){this.Rs=!1,this.As=!1,this.Vs=100,this.ds=function(){let e;return(0,w.nr)()?8:Number((e=(0,w.ZQ)().match(/Android ([\d.]+)/i))?e[1].split(".").slice(0,2).join("."):"-1")>0?6:4}()}initialize(e,t){this.fs=e,this.indexManager=t,this.Rs=!0}getDocumentsMatchingQuery(e,t,r,n){let i={result:null};return this.gs(e,t).next(e=>{i.result=e}).next(()=>{if(!i.result)return this.ps(e,t,n,r).next(e=>{i.result=e})}).next(()=>{if(i.result)return;let r=new nE;return this.ys(e,t,r).next(n=>{if(i.result=n,this.As)return this.ws(e,t,r,n.size)})}).next(()=>i.result)}ws(e,t,r,n){return r.documentReadCount<this.Vs?(N()<=I.$b.DEBUG&&R("QueryEngine","SDK will not create cache indexes for query:",tV(t),"since it only creates cache indexes for collection contains","more than or equal to",this.Vs,"documents"),ew.resolve()):(N()<=I.$b.DEBUG&&R("QueryEngine","Query:",tV(t),"scans",r.documentReadCount,"local documents and returns",n,"documents as results."),r.documentReadCount>this.ds*n?(N()<=I.$b.DEBUG&&R("QueryEngine","The SDK decides to create cache indexes for query:",tV(t),"as using cache indexes may help improve performance."),this.indexManager.createTargetIndexes(e,tP(t))):ew.resolve())}gs(e,t){if(tR(t))return ew.resolve(null);let r=tP(t);return this.indexManager.getIndexType(e,r).next(n=>0===n?null:(null!==t.limit&&1===n&&(r=tP(t=tx(t,null,"F"))),this.indexManager.getDocumentsMatchingTarget(e,r).next(n=>{let i=tQ(...n);return this.fs.getDocuments(e,i).next(n=>this.indexManager.getMinOffset(e,r).next(r=>{let s=this.Ss(t,n);return this.bs(t,s,i,r.readTime)?this.gs(e,tx(t,null,"F")):this.Ds(e,s,t,r)}))})))}ps(e,t,r,n){return tR(t)||n.isEqual(ep.min())?ew.resolve(null):this.fs.getDocuments(e,r).next(i=>{let s,a,o=this.Ss(t,i);return this.bs(t,o,r,n)?ew.resolve(null):(N()<=I.$b.DEBUG&&R("QueryEngine","Re-using previous result from %s to execute query: %s",n.toString(),tV(t)),this.Ds(e,o,t,(s=n.toTimestamp().seconds,a=n.toTimestamp().nanoseconds+1,new eg(ep.fromTimestamp(1e9===a?new ef(s+1,0):new ef(s,a)),ei.empty(),-1))
6).next(e=>e))})}Ss(e,t){let r=new eN(tj(e));return t.forEach((t,n)=>{tF(e,n)&&(r=r.add(n))}),r}bs(e,t,r,n){if(null===e.limit)return!1;if(r.size!==t.size)return!0;let i="F"===e.limitType?t.last():t.first();return!!i&&(i.hasPendingWrites||i.version.compareTo(n)>0)}ys(e,t,r){return N()<=I.$b.DEBUG&&R("QueryEngine","Using full collection scan to execute query:",tV(t)),this.fs.getDocumentsMatchingQuery(e,t,eg.min(),r)}Ds(e,t,r,n){return this.fs.getDocumentsMatchingQuery(e,r,n).next(e=>(t.forEach(t=>{e=e.insert(t.key,t)}),e))}}let nI="LocalStore";class nT{constructor(e,t,r,n){this.persistence=e,this.Cs=t,this.serializer=n,this.vs=new eA(Q),this.Fs=new tB(e=>tA(e),tC),this.Ms=new Map,this.xs=e.getRemoteDocumentCache(),this.li=e.getTargetCache(),this.Pi=e.getBundleCache(),this.Os(r)}Os(e){this.documentOverlayCache=this.persistence.getDocumentOverlayCache(e),this.indexManager=this.persistence.getIndexManager(e),this.mutationQueue=this.persistence.getMutationQueue(e,this.indexManager),this.localDocuments=new ns(this.xs,this.mutationQueue,this.documentOverlayCache,this.indexManager),this.xs.setIndexManager(this.indexManager),this.Cs.initialize(this.localDocuments,this.indexManager)}collectGarbage(e){return this.persistence.runTransaction("Collect garbage","readwrite-primary",t=>e.collect(t,this.vs))}}async function nb(e,t){return await e.persistence.runTransaction("Handle user change","readonly",r=>{let n;return e.mutationQueue.getAllMutationBatches(r).next(i=>(n=i,e.Os(t),e.mutationQueue.getAllMutationBatches(r))).next(t=>{let i=[],s=[],a=tQ();for(let e of n)for(let t of(i.push(e.batchId),e.mutations))a=a.add(t.key);for(let e of t)for(let t of(s.push(e.batchId),e.mutations))a=a.add(t.key);return e.localDocuments.getDocuments(r,a).next(e=>({Ns:e,removedBatchIds:i,addedBatchIds:s}))})})}function nS(e){return e.persistence.runTransaction("Get last remote snapshot version","readonly",t=>e.li.getLastRemoteSnapshotVersion(t))}async function nA(e,t,r){let n=e.vs.get(t);try{r||await e.persistence.runTransaction("Release target",r?"readwrite":"readwrite-primary",t=>e.persistence.referenceDelegate.removeTarget(t,n))}catch(e){if(!eE(e))throw e;R(nI,`Failed to update sequence numbers for target ${t}: ${e}`)}e.vs=e.vs.remove(t),e.Fs.delete(n.target)}function nC(e,t,r){let n=ep.min(),i=tQ();return e.persistence.runTransaction("Execute query","readwrite",s=>{var a;let o;return(a=tP(t),void 0!==(o=e.Fs.get(a))?ew.resolve(e.vs.get(o)):e.li.getTargetData(s,a)).next(t=>{if(t)return n=t.lastLimboFreeSnapshotVersion,e.li.getMatchingKeysForTargetId(s,t.targetId).next(e=>{i=e})}).next(()=>e.Cs.getDocumentsMatchingQuery(s,t,r?n:ep.min(),r?i:tQ())).next(r=>{var n,s,a;let o;return n=e,s=t.collectionGroup||(t.path.length%2==1?t.path.lastSegment():t.path.get(t.path.length-2)),a=r,o=n.Ms.get(s)||ep.min(),a.forEach((e,t)=>{t.readTime.compareTo(o)>0&&(o=t.readTime)}),n.Ms.set(s,o),{documents:r,ks:i}})})}class nk{constructor(){this.activeTargetIds=tJ}Qs(e){this.activeTargetIds=this.activeTargetIds.add(e)}Gs(e){this.activeTargetIds=this.activeTargetIds.delete(e)}Ws(){return JSON.stringify({activeTargetIds:this.activeTargetIds.toArray(),updateTimeMs:Date.now()})}}class nN{constructor(){this.vo=new nk,this.Fo={},this.onlineStateHandler=null,this.sequenceNumberHandler=null}addPendingMutation(e){}updateMutationState(e,t,r){}addLocalQueryTarget(e,t=!0){return t&&this.vo.Qs(e),this.Fo[e]||"not-current"}updateQueryState(e,t,r){this.Fo[e]=t}removeLocalQueryTarget(e){this.vo.Gs(e)}isLocalQueryTarget(e){return this.vo.activeTargetIds.has(e)}clearQueryState(e){delete this.Fo[e]}getAllActiveQueryTargets(){return this.vo.activeTargetIds}isActiveQueryTarget(e){return this.vo.activeTargetIds.has(e)}start(){return this.vo=new nk,Promise.resolve()}handleUserChange(e,t,r){}setOnlineState(e){}shutdown(){}writeSequenceNumber(e){}notifyBundleLoaded(e){}}class nR{Mo(e){}shutdown(){}}let nD="ConnectivityMonitor";class nO{constructor(){this.xo=()=>this.Oo(),this.No=()=>this.Bo(),this.Lo=[],this.ko()}Mo(e){this.Lo.push(e)}shutdown(){window.removeEventListener("online",this.xo),window.removeEventListener("offline",this.No)}
6ko(){window.addEventListener("online",this.xo),window.addEventListener("offline",this.No)}Oo(){for(let e of(R(nD,"Network connectivity changed: AVAILABLE"),this.Lo))e(0)}Bo(){for(let e of(R(nD,"Network connectivity changed: UNAVAILABLE"),this.Lo))e(1)}static v(){return"u">typeof window&&void 0!==window.addEventListener&&void 0!==window.removeEventListener}}let nP=null;function nL(){return null===nP?nP=0x10000000+Math.round(0x80000000*Math.random()):nP++,"0x"+nP.toString(16)}let nx="RestConnection",nM={BatchGetDocuments:"batchGet",Commit:"commit",RunQuery:"runQuery",RunAggregationQuery:"runAggregationQuery",ExecutePipeline:"executePipeline"};class nU{get qo(){return!1}constructor(e){this.databaseInfo=e,this.databaseId=e.databaseId;const t=e.ssl?"https":"http",r=encodeURIComponent(this.databaseId.projectId),n=encodeURIComponent(this.databaseId.database);this.Ko=t+"://"+e.host,this.Uo=`projects/${r}/databases/${n}`,this.$o=this.databaseId.database===eH?`project_id=${r}`:`project_id=${r}&database_id=${n}`}Wo(e,t,r,n,i){let s=nL(),a=this.Qo(e,t.toUriEncodedString());R(nx,`Sending RPC '${e}' ${s}:`,a,r);let o={"google-cloud-resource-prefix":this.Uo,"x-goog-request-params":this.$o};this.Go(o,n,i);let{host:l}=new URL(a),u=(0,w.zJ)(l);return this.zo(e,a,o,r,u).then(t=>(R(nx,`Received RPC '${e}' ${s}: `,t),t),t=>{throw O(nx,`RPC '${e}' ${s} failed with error: `,t,"url: ",a,"request:",r),t})}jo(e,t,r,n,i,s){return this.Wo(e,t,r,n,i)}Go(e,t,r){e["X-Goog-Api-Client"]="gl-js/ fire/"+C,e["Content-Type"]="text/plain",this.databaseInfo.appId&&(e["X-Firebase-GMPID"]=this.databaseInfo.appId),t&&t.headers.forEach((t,r)=>e[r]=t),r&&r.headers.forEach((t,r)=>e[r]=t)}Qo(e,t){let r=nM[e],n=`${this.Ko}/v1/${t}:${r}`;return this.databaseInfo.apiKey&&(n=`${n}?key=${encodeURIComponent(this.databaseInfo.apiKey)}`),n}terminate(){}}class nV{constructor(e){this.Jo=e.Jo,this.Ho=e.Ho}Zo(e){this.Xo=e}Yo(e){this.e_=e}t_(e){this.n_=e}onMessage(e){this.r_=e}close(){this.Ho()}send(e){this.Jo(e)}i_(){this.Xo()}s_(){this.e_()}o_(e){this.n_(e)}__(e){this.r_(e)}}let nF="WebChannelConnection",nj=(e,t,r)=>{e.listen(t,e=>{try{r(e)}catch(e){setTimeout(()=>{throw e},0)}})};class nB extends nU{constructor(e){super(e),this.a_=[],this.forceLongPolling=e.forceLongPolling,this.autoDetectLongPolling=e.autoDetectLongPolling,this.useFetchStreams=e.useFetchStreams,this.longPollingOptions=e.longPollingOptions}static u_(){nB.c_||(nj(c(),h.STAT_EVENT,e=>{e.stat===u.PROXY?R(nF,"STAT_EVENT: detected buffering proxy"):e.stat===u.NOPROXY&&R(nF,"STAT_EVENT: detected no buffering proxy")}),nB.c_=!0)}zo(e,t,r,n,i){let a=nL();return new Promise((i,u)=>{let h=new s;h.setWithCredentials(!0),h.listenOnce(o.COMPLETE,()=>{try{switch(h.getLastErrorCode()){case l.NO_ERROR:let t=h.getResponseJson();R(nF,`XHR for RPC '${e}' ${a} received:`,JSON.stringify(t)),i(t);break;case l.TIMEOUT:R(nF,`RPC '${e}' ${a} timed out`),u(new V(U.DEADLINE_EXCEEDED,"Request time out"));break;case l.HTTP_ERROR:let r=h.getStatus();if(R(nF,`RPC '${e}' ${a} failed with status:`,r,"response text:",h.getResponseText()),r>0){let e=h.getResponseJson();Array.isArray(e)&&(e=e[0]);let t=e?.error;if(t&&t.status&&t.message){let e,r=(e=t.status.toLowerCase().replace(/_/g,"-"),Object.values(U).indexOf(e)>=0?e:U.UNKNOWN);u(new V(r,t.message))}else u(new V(U.UNKNOWN,"Server responded with status "+h.getStatus()))}else u(new V(U.UNAVAILABLE,"Connection failed."));break;default:L(9055,{l_:e,streamId:a,h_:h.getLastErrorCode(),P_:h.getLastError()})}}finally{R(nF,`RPC '${e}' ${a} completed.`)}});let c=JSON.stringify(n);R(nF,`RPC '${e}' ${a} sending request:`,n),h.send(t,"POST",c,r,15)})}T_(e,t,r){let n=nL(),i=[this.Ko,"/","google.firestore.v1.Firestore","/",e,"/channel"],s=this.createWebChannelTransport(),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},l=this.longPollingOptions.timeoutSeconds;void 0!==l&&(o.longPollingTimeout=Math.round(1e3*l)),this.useFetchStreams&&(o.useFetchStreams=!0),this.Go(o.initMessageHeaders,t,r),o.encodeInitMessageHeaders=!0;let u=i.join("");R(nF,`Creating RPC '${e}' stream ${n}: ${u}`,o);let h=s.createWebChannel(u,o);this.E_(h);let c=!1,d=!1,p=new nV({Jo:t=>{d?R(nF,`Not sending because RPC '${e}' stream ${n} is closed:`,t):(c||(R(nF,`Opening RPC '${e}' stream ${n} transport.`),h.open(),c=!0),R(nF,`RPC '${e}' stream ${n} sending:`,t),h.send(t))},Ho:()=>h.close()});return nj(h,a.EventType.OPEN,()=>{d||(R(nF,`RPC '${e}' stream ${n} transport opened.`),p.i_())}),nj(h,a.EventType.CLOSE,()=>{d||(d=!0,R(nF,`RPC '${e}' stream ${n} transport closed`),p.o_(),this.I_(h))}
6),nj(h,a.EventType.ERROR,t=>{d||(d=!0,O(nF,`RPC '${e}' stream ${n} transport errored. Name:`,t.name,"Message:",t.message),p.o_(new V(U.UNAVAILABLE,"The operation could not be completed")))}),nj(h,a.EventType.MESSAGE,t=>{if(!d){let r=t.data[0];M(!!r,16349);let i=r?.error||r[0]?.error;if(i){R(nF,`RPC '${e}' stream ${n} received error:`,i);let t=i.status,r=function(e){let t=f[e];if(void 0!==t)return rv(t)}(t),s=i.message;"NOT_FOUND"===t&&s.includes("database")&&s.includes("does not exist")&&s.includes(this.databaseId.database)&&O(`Database '${this.databaseId.database}' not found. Please check your project configuration.`),void 0===r&&(r=U.INTERNAL,s="Unknown error status: "+t+" with message "+i.message),d=!0,p.o_(new V(r,s)),h.close()}else R(nF,`RPC '${e}' stream ${n} received:`,r),p.__(r)}}),nB.u_(),setTimeout(()=>{p.s_()},0),p}terminate(){this.a_.forEach(e=>e.close()),this.a_=[]}E_(e){this.a_.push(e)}I_(e){this.a_=this.a_.filter(t=>t===e)}Go(e,t,r){super.Go(e,t,r),this.databaseInfo.apiKey&&(e["x-goog-api-key"]=this.databaseInfo.apiKey)}createWebChannelTransport(){return d()}}function nq(){return"u">typeof document?document:null}function n$(e){return new rM(e,!0)}nB.c_=!1;class nz{constructor(e,t,r=1e3,n=1.5,i=6e4){this.Ci=e,this.timerId=t,this.R_=r,this.A_=n,this.V_=i,this.d_=0,this.m_=null,this.f_=Date.now(),this.reset()}reset(){this.d_=0}g_(){this.d_=this.V_}p_(e){this.cancel();let t=Math.floor(this.d_+this.y_()),r=Math.max(0,Date.now()-this.f_),n=Math.max(0,t-r);n>0&&R("ExponentialBackoff",`Backing off for ${n} ms (base delay: ${this.d_} ms, delay with jitter: ${t} ms, last attempt: ${r} ms ago)`),this.m_=this.Ci.enqueueAfterDelay(this.timerId,n,()=>(this.f_=Date.now(),e())),this.d_*=this.A_,this.d_<this.R_&&(this.d_=this.R_),this.d_>this.V_&&(this.d_=this.V_)}w_(){null!==this.m_&&(this.m_.skipDelay(),this.m_=null)}cancel(){null!==this.m_&&(this.m_.cancel(),this.m_=null)}y_(){return(Math.random()-.5)*this.d_}}let nK="PersistentStream";class nH{constructor(e,t,r,n,i,s,a,o){this.Ci=e,this.S_=r,this.b_=n,this.connection=i,this.authCredentialsProvider=s,this.appCheckCredentialsProvider=a,this.listener=o,this.state=0,this.D_=0,this.C_=null,this.v_=null,this.stream=null,this.F_=0,this.M_=new nz(e,t)}x_(){return 1===this.state||5===this.state||this.O_()}O_(){return 2===this.state||3===this.state}start(){this.F_=0,4!==this.state?this.auth():this.N_()}async stop(){this.x_()&&await this.close(0)}B_(){this.state=0,this.M_.reset()}L_(){this.O_()&&null===this.C_&&(this.C_=this.Ci.enqueueAfterDelay(this.S_,6e4,()=>this.k_()))}q_(e){this.K_(),this.stream.send(e)}async k_(){if(this.O_())return this.close(0)}K_(){this.C_&&(this.C_.cancel(),this.C_=null)}U_(){this.v_&&(this.v_.cancel(),this.v_=null)}async close(e,t){this.K_(),this.U_(),this.M_.cancel(),this.D_++,4!==e?this.M_.reset():t&&t.code===U.RESOURCE_EXHAUSTED?(D(t.toString()),D("Using maximum backoff delay to prevent overloading the backend."),this.M_.g_()):t&&t.code===U.UNAUTHENTICATED&&3!==this.state&&(this.authCredentialsProvider.invalidateToken(),this.appCheckCredentialsProvider.invalidateToken()),null!==this.stream&&(this.W_(),this.stream.close(),this.stream=null),this.state=e,await this.listener.t_(t)}W_(){}auth(){this.state=1;let e=this.Q_(this.D_),t=this.D_;Promise.all([this.authCredentialsProvider.getToken(),this.appCheckCredentialsProvider.getToken()]).then(([e,r])=>{this.D_===t&&this.G_(e,r)},t=>{e(()=>{let e=new V(U.UNKNOWN,"Fetching auth token failed: "+t.message);return this.z_(e)})})}G_(e,t){let r=this.Q_(this.D_);this.stream=this.j_(e,t),this.stream.Zo(()=>{r(()=>this.listener.Zo())}),this.stream.Yo(()=>{r(()=>(this.state=2,this.v_=this.Ci.enqueueAfterDelay(this.b_,1e4,()=>(this.O_()&&(this.state=3),Promise.resolve())),this.listener.Yo()))}),this.stream.t_(e=>{r(()=>this.z_(e))}),this.stream.onMessage(e=>{r(()=>1==++this.F_?this.J_(e):this.onNext(e))})}N_(){this.state=5,this.M_.p_(async()=>{this.state=0,this.start()})}z_(e){return R(nK,`close with error: ${e}`),this.stream=null,this.close(4,e)}Q_(e){return t=>{this.Ci.enqueueAndForget(()=>this.D_===e?t():(R(nK,"stream callback skipped by getCloseGuardedDispatcher."),Promise.resolve()))}}}class nG extends nH{constructor(e,t,r,n,i,s){super(e,"listen_stream_connection_backoff","listen_stream_idle","health_check_timeout",t,r,n,s),this.serializer
6=i}j_(e,t){return this.connection.T_("Listen",e,t)}J_(e){return this.onNext(e)}onNext(e){this.M_.reset();let t=function(e,t){let r;if("targetChange"in t){var n,i;t.targetChange;let s="NO_CHANGE"===(n=t.targetChange.targetChangeType||"NO_CHANGE")?0:"ADD"===n?1:"REMOVE"===n?2:"CURRENT"===n?3:"RESET"===n?4:L(39313,{state:n}),a=t.targetChange.targetIds||[],o=(i=t.targetChange.resumeToken,e.useProto3Json?(M(void 0===i||"string"==typeof i,58123),eP.fromBase64String(i||"")):(M(void 0===i||i instanceof S||i instanceof Uint8Array,16193),eP.fromUint8Array(i||new Uint8Array))),l=t.targetChange.cause;r=new rk(s,a,o,l&&new V(void 0===l.code?U.UNKNOWN:rv(l.code),l.message||"")||null)}else if("documentChange"in t){t.documentChange;let n=t.documentChange;n.document,n.document.name,n.document.updateTime;let i=rK(e,n.document.name),s=rj(n.document.updateTime),a=n.document.createTime?rj(n.document.createTime):ep.min(),o=new ts({mapValue:{fields:n.document.fields}}),l=ta.newFoundDocument(i,s,a,o);r=new rA(n.targetIds||[],n.removedTargetIds||[],l.key,l)}else if("documentDelete"in t){t.documentDelete;let n=t.documentDelete;n.document;let i=rK(e,n.document),s=n.readTime?rj(n.readTime):ep.min(),a=ta.newNoDocument(i,s);r=new rA([],n.removedTargetIds||[],a.key,a)}else if("documentRemove"in t){t.documentRemove;let n=t.documentRemove;n.document;let i=rK(e,n.document);r=new rA([],n.removedTargetIds||[],i,null)}else{if(!("filter"in t))return L(11601,{Vt:t});{t.filter;let e=t.filter;e.targetId;let{count:n=0,unchangedNames:i}=e,s=new ry(n,i);r=new rC(e.targetId,s)}}return r}(this.serializer,e),r=function(e){if(!("targetChange"in e))return ep.min();let t=e.targetChange;return t.targetIds&&t.targetIds.length?ep.min():t.readTime?rj(t.readTime):ep.min()}(e);return this.listener.H_(t,r)}Z_(e){let t,r={};r.database=rG(this.serializer),r.addTarget=function(e,t){var r,n;let i,s,a,o,l,u,h,c=t.target;if((i=tk(c)?{documents:{documents:[rH(e,c.path)]}}:{query:(a={structuredQuery:{}},o=c.path,null!==c.collectionGroup?(s=o,a.structuredQuery.from=[{collectionId:c.collectionGroup,allDescendants:!0}]):(s=o.popLast(),a.structuredQuery.from=[{collectionId:o.lastSegment()}]),a.parent=rH(e,s),(l=function(e){if(0!==e.length)return function e(t){var r;let n;return t instanceof td?function(e){if("=="===e.op){if(te(e.value))return{unaryFilter:{field:rJ(e.field),op:"IS_NAN"}};if(e7(e.value))return{unaryFilter:{field:rJ(e.field),op:"IS_NULL"}}}else if("!="===e.op){if(te(e.value))return{unaryFilter:{field:rJ(e.field),op:"IS_NOT_NAN"}};if(e7(e.value))return{unaryFilter:{field:rJ(e.field),op:"IS_NOT_NULL"}}}return{fieldFilter:{field:rJ(e.field),op:rL[e.op],value:e.value}}}(t):t instanceof tf?1===(n=(r=t).getFilters().map(t=>e(t))).length?n[0]:{compositeFilter:{op:rx[r.op],filters:n}}:L(54877,{filter:t})}(tf.create(e,"and"))}(c.filters))&&(a.structuredQuery.where=l),(u=function(e){if(0!==e.length)return e.map(e=>({field:rJ(e.field),direction:rP[e.dir]}))}(c.orderBy))&&(a.structuredQuery.orderBy=u),null!==(h=rU(e,c.limit))&&(a.structuredQuery.limit=h),c.startAt&&(a.structuredQuery.startAt={before:(r=c.startAt).inclusive,values:r.position}),c.endAt&&(a.structuredQuery.endAt={before:!(n=c.endAt).inclusive,values:n.position}),{ft:a,parent:s}).ft}).targetId=t.targetId,t.resumeToken.approximateByteSize()>0){i.resumeToken=rF(e,t.resumeToken);let r=rU(e,t.expectedCount);null!==r&&(i.expectedCount=r)}else if(t.snapshotVersion.compareTo(ep.min())>0){i.readTime=rV(e,t.snapshotVersion.toTimestamp());let r=rU(e,t.expectedCount);null!==r&&(i.expectedCount=r)}return i}(this.serializer,e);let n=(this.serializer,null==(t=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 L(28987,{purpose:e})}}(e.purpose))?null:{"goog-listen-tags":t});n&&(r.labels=n),this.q_(r)}X_(e){let t={};t.database=rG(this.serializer),t.removeTarget=e,this.q_(t)}}class nW extends nH{constructor(e,t,r,n,i,s){super(e,"write_stream_connection_backoff","write_stream_idle","health_check_timeout",t,r,n,s),this.serializer
6=i}get Y_(){return this.F_>0}start(){this.lastStreamToken=void 0,super.start()}W_(){this.Y_&&this.ea([])}j_(e,t){return this.connection.T_("Write",e,t)}J_(e){return M(!!e.streamToken,31322),this.lastStreamToken=e.streamToken,M(!e.writeResults||0===e.writeResults.length,55816),this.listener.ta()}onNext(e){var t,r;M(!!e.streamToken,12678),this.lastStreamToken=e.streamToken,this.M_.reset();let n=(t=e.writeResults,r=e.commitTime,t&&t.length>0?(M(void 0!==r,14353),t.map(e=>{let t;return(t=e.updateTime?rj(e.updateTime):rj(r)).isEqual(ep.min())&&(t=rj(r)),new re(t,e.transformResults||[])})):[]),i=rj(e.commitTime);return this.listener.na(i,n)}ra(){let e={};e.database=rG(this.serializer),this.q_(e)}ea(e){let t={streamToken:this.lastStreamToken,writes:e.map(e=>(function(e,t){var r,n;let i;if(t instanceof ro)i={update:rQ(e,t.key,t.value)};else if(t instanceof rd)i={delete:rz(e,t.key)};else if(t instanceof rl){let r;i={update:rQ(e,t.key,t.data),updateMask:(n=t.fieldMask,r=[],n.fields.forEach(e=>r.push(e.canonicalString())),{fieldPaths:r})}}else{if(!(t instanceof rf))return L(16599,{dt:t.type});i={verify:rz(e,t.key)}}return t.fieldTransforms.length>0&&(i.updateTransforms=t.fieldTransforms.map(e=>(function(e){let t=e.transform;if(t instanceof t1)return{fieldPath:e.field.canonicalString(),setToServerValue:"REQUEST_TIME"};if(t instanceof t2)return{fieldPath:e.field.canonicalString(),appendMissingElements:{values:t.elements}};if(t instanceof t3)return{fieldPath:e.field.canonicalString(),removeAllFromArray:{values:t.elements}};if(t instanceof t8)return{fieldPath:e.field.canonicalString(),increment:t.Ae};throw L(20930,{transform:e.transform})})(e))),t.precondition.isNone||(i.currentDocument=void 0!==(r=t.precondition).updateTime?{updateTime:rV(e,r.updateTime.toTimestamp())}:void 0!==r.exists?{exists:r.exists}:L(27497)),i})(this.serializer,e))};this.q_(t)}}class nQ{}class nJ extends nQ{constructor(e,t,r,n){super(),this.authCredentials=e,this.appCheckCredentials=t,this.connection=r,this.serializer=n,this.ia=!1}sa(){if(this.ia)throw new V(U.FAILED_PRECONDITION,"The client has already been terminated.")}Wo(e,t,r,n){return this.sa(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then(([i,s])=>this.connection.Wo(e,rq(t,r),n,i,s)).catch(e=>{throw"FirebaseError"===e.name?(e.code===U.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),e):new V(U.UNKNOWN,e.toString())})}jo(e,t,r,n,i){return this.sa(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then(([s,a])=>this.connection.jo(e,rq(t,r),n,s,a,i)).catch(e=>{throw"FirebaseError"===e.name?(e.code===U.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),e):new V(U.UNKNOWN,e.toString())})}terminate(){this.ia=!0,this.connection.terminate()}}class nX{constructor(e,t){this.asyncQueue=e,this.onlineStateHandler=t,this.state="Unknown",this.oa=0,this._a=null,this.aa=!0}ua(){0===this.oa&&(this.ca("Unknown"),this._a=this.asyncQueue.enqueueAfterDelay("online_state_timeout",1e4,()=>(this._a=null,this.la("Backend didn't respond within 10 seconds."),this.ca("Offline"),Promise.resolve())))}ha(e){"Online"===this.state?this.ca("Unknown"):(this.oa++,this.oa>=1&&(this.Pa(),this.la(`Connection failed 1 times. Most recent error: ${e.toString()}`),this.ca("Offline")))}set(e){this.Pa(),this.oa=0,"Online"===e&&(this.aa=!1),this.ca(e)}ca(e){e!==this.state&&(this.state=e,this.onlineStateHandler(e))}la(e){let t=`Could not reach Cloud Firestore backend. ${e} 7This 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.aa?(D(t),this.aa=!1):R("OnlineStateTracker",t)}Pa(){null!==this._a&&(this._a.cancel(),this._a=null)}}let nY="RemoteStore";class nZ{constructor(e,t,r,n,i){this.localStore=e,this.datastore=t,this.asyncQueue=r,this.remoteSyncer={},this.Ta=[],this.Ea=new Map,this.Ia=new Set,this.Ra=[],this.Aa=i,this.Aa.Mo(e=>{r.enqueueAndForget(async()=>
7{n9(this)&&(R(nY,"Restarting streams for network reachability change."),await async function(e){e.Ia.add(4),await n1(e),e.Va.set("Unknown"),e.Ia.delete(4),await n0(e)}(this))})}),this.Va=new nX(r,n)}}async function n0(e){if(n9(e))for(let t of e.Ra)await t(!0)}async function n1(e){for(let t of e.Ra)await t(!1)}function n2(e,t){e.Ea.has(t.targetId)||(e.Ea.set(t.targetId,t),n4(e)?n8(e):ig(e).O_()&&n3(e,t))}function n6(e,t){let r=ig(e);e.Ea.delete(t),r.O_()&&n5(e,t),0===e.Ea.size&&(r.O_()?r.L_():n9(e)&&e.Va.set("Unknown"))}function n3(e,t){if(e.da.$e(t.targetId),t.resumeToken.approximateByteSize()>0||t.snapshotVersion.compareTo(ep.min())>0){let r=e.remoteSyncer.getRemoteKeysForTarget(t.targetId).size;t=t.withExpectedCount(r)}ig(e).Z_(t)}function n5(e,t){e.da.$e(t),ig(e).X_(t)}function n8(e){e.da=new rR({getRemoteKeysForTarget:t=>e.remoteSyncer.getRemoteKeysForTarget(t),At:t=>e.Ea.get(t)||null,ht:()=>e.datastore.serializer.databaseId}),ig(e).start(),e.Va.ua()}function n4(e){return n9(e)&&!ig(e).x_()&&e.Ea.size>0}function n9(e){return 0===e.Ia.size}async function n7(e){e.Va.set("Online")}async function ie(e){e.Ea.forEach((t,r)=>{n3(e,t)})}async function it(e,t){e.da=void 0,n4(e)?(e.Va.ha(t),n8(e)):e.Va.set("Unknown")}async function ir(e,t,r){if(e.Va.set("Online"),t instanceof rk&&2===t.state&&t.cause)try{await async function(e,t){let r=t.cause;for(let n of t.targetIds)e.Ea.has(n)&&(await e.remoteSyncer.rejectListen(n,r),e.Ea.delete(n),e.da.removeTarget(n))}(e,t)}catch(r){R(nY,"Failed to remove targets %s: %s ",t.targetIds.join(","),r),await ii(e,r)}else if(t instanceof rA?e.da.Xe(t):t instanceof rC?e.da.st(t):e.da.tt(t),!r.isEqual(ep.min()))try{let t,n=await nS(e.localStore);r.compareTo(n)>
7=0&&await ((t=e.da.Tt(r)).targetChanges.forEach((t,n)=>{if(t.resumeToken.approximateByteSize()>0){let i=e.Ea.get(n);i&&e.Ea.set(n,i.withResumeToken(t.resumeToken,r))}}),t.targetMismatches.forEach((t,r)=>{let n=e.Ea.get(t);if(!n)return;e.Ea.set(t,n.withResumeToken(eP.EMPTY_BYTE_STRING,n.snapshotVersion)),n5(e,t);let i=new r0(n.target,t,r,n.sequenceNumber);n3(e,i)}),e.remoteSyncer.applyRemoteEvent(t))}catch(t){R(nY,"Failed to raise snapshot:",t),await ii(e,t)}}async function ii(e,t,r){if(!eE(t))throw t;e.Ia.add(1),await n1(e),e.Va.set("Offline"),r||(r=()=>nS(e.localStore)),e.asyncQueue.enqueueRetryable(async()=>{R(nY,"Retrying IndexedDB access"),await r(),e.Ia.delete(1),await n0(e)})}function is(e,t){return t().catch(r=>ii(e,r,t))}async function ia(e){var t;let r=iy(e),n=e.Ta.length>0?e.Ta[e.Ta.length-1].batchId:-1;for(;n9(t=e)&&t.Ta.length<10;)try{let t=await function(e,t){return e.persistence.runTransaction("Get next mutation batch","readonly",r=>(void 0===t&&(t=-1),e.mutationQueue.getNextMutationBatchAfterBatchId(r,t)))}(e.localStore,n);if(null===t){0===e.Ta.length&&r.L_();break}n=t.batchId,function(e,t){e.Ta.push(t);let r=iy(e);r.O_()&&r.Y_&&r.ea(t.mutations)}(e,t)}catch(t){await ii(e,t)}io(e)&&il(e)}function io(e){return n9(e)&&!iy(e).x_()&&e.Ta.length>0}function il(e){iy(e).start()}async function iu(e){iy(e).ra()}async function ih(e){let t=iy(e);for(let r of e.Ta)t.ea(r.mutations)}async function ic(e,t,r){let n=e.Ta.shift(),i=rm.from(n,t,r);await is(e,()=>e.remoteSyncer.applySuccessfulWrite(i)),await ia(e)}async function id(e,t){t&&iy(e).Y_&&await async function(e,t){var r;if(function(e){switch(e){case U.OK:return L(64938);case U.CANCELLED:case U.UNKNOWN:case U.DEADLINE_EXCEEDED:case U.RESOURCE_EXHAUSTED:case U.INTERNAL:case U.UNAVAILABLE:case U.UNAUTHENTICATED:return!1;case U.INVALID_ARGUMENT:case U.NOT_FOUND:case U.ALREADY_EXISTS:case U.PERMISSION_DENIED:case U.FAILED_PRECONDITION:case U.ABORTED:case U.OUT_OF_RANGE:case U.UNIMPLEMENTED:case U.DATA_LOSS:return!0;default:return L(15467,{code:e})}}(r=t.code)&&r!==U.ABORTED){let r=e.Ta.shift();iy(e).B_(),await is(e,()=>e.remoteSyncer.rejectFailedWrite(r.batchId,t)),await ia(e)}}(e,t),io(e)&&il(e)}async function ip(e,t){e.asyncQueue.verifyOperationInProgress(),R(nY,"RemoteStore received new credentials");let r=n9(e);e.Ia.add(3),await n1(e),r&&e.Va.set("Unknown"),await e.remoteSyncer.handleCredentialChange(t),e.Ia.delete(3),await n0(e)}async function im(e,t){t?(e.Ia.delete(2),await n0(e)):t||(e.Ia.add(2),await n1(e),e.Va.set("Unknown"))}function ig(e){var t,r,n;return e.ma||(t=e.datastore,r=e.asyncQueue,n={Zo:n7.bind(null,e),Yo:ie.bind(null,e),t_:it.bind(null,e),H_:ir.bind(null,e)},t.sa(),e.ma=new nG(r,t.connection,t.authCredentials,t.appCheckCredentials,t.serializer,n),e.Ra.push(async t=>{t?(e.ma.B_(),n4(e)?n8(e):e.Va.set("Unknown")):(await e.ma.stop(),e.da=void 0)})),e.ma}function iy(e){var t,r,n;return e.fa||(t=e.datastore,r=e.asyncQueue,n={Zo:()=>Promise.resolve(),Yo:iu.bind(null,e),t_:id.bind(null,e),ta:ih.bind(null,e),na:ic.bind(null,e)},t.sa(),e.fa=new nW(r,t.connection,t.authCredentials,t.appCheckCredentials,t.serializer,n),e.Ra.push(async t=>{t?(e.fa.B_(),await ia(e)):(await e.fa.stop(),e.Ta.length>0&&(R(nY,`Stopping write stream with ${e.Ta.length} pending writes`),e.Ta=[]))})),e.fa}class iv{constructor(e,t,r,n,i){this.asyncQueue=e,this.timerId=t,this.targetTimeMs=r,this.op=n,this.removalCallback=i,this.deferred=new F,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,r,n,i){let s=new iv(e,t,Date.now()+r,n,i);return s.start(r),s}start(e){this.timerHandle=setTimeout(()=>this.handleDelayElapsed(),e)}skipDelay(){return this.handleDelayElapsed()}cancel(e){null!==this.timerHandle&&(this.clearTimeout(),this.deferred.reject(new V(U.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 iw(e,t){if(D("AsyncQueue",`${t}: ${e}`),eE(e))return new V(U.UNAVAILABLE,`${t}: ${e}`);throw e}class iE{static emptySet(e){return new iE(e.comparator)}constructor(e){this.comparator=e?(t,r)=>e(t,r)||ei.comparator(t.key,r.key):(e,t)=>ei.comparator(e.key,t.key),this.keyedMap=tz(),this.sortedSet=new eA(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){let t=this.keyedMap.get(e);return t?this.sortedSet.indexOf(t):-1}get size(){return this.sortedSet.size}forEach(e){this.sortedSet.inorderTraversal((t,r)=>(e(t),!1))}add(e){let t=this.delete(e.key);return t.copy(t.keyedMap.insert(e.key,e),t.sortedSet.insert(e,null))}delete(e){let t=this.get(e);return t?this.copy(this.keyedMap.remove(e),this.sortedSet.remove(t)):this}isEqual(e){if(!(e instanceof iE)||this.size!==e.size)return!1;let t=this.sortedSet.getIterator(),r=e.sortedSet.getIterator();for(;t.hasNext();){let e=t.getNext().key,n=r.getNext().key;if(!e.isEqual(n))return!1}return!0}toString(){let e=[];return this.forEach(t=>{e.push(t.toString())}),0===e.length?"DocumentSet ()":"DocumentSet (\n "+e.join(" \n")+"\n)"}copy(e,t){let r=new iE;return r.comparator=this.comparator,r.keyedMap=e,r.sortedSet=t,r}}class i_{constructor(){this.ga=new eA(ei.comparator)}track(e){let t=e.doc.key,r=this.ga.get(t);r?0!==e.type&&3===r.type?this.ga=this.ga.insert(t,e):3===e.type&&1!==r.type?this.ga=this.ga.insert(t,{type:r.type,doc:e.doc}):2===e.type&&2===r.type?this.ga=this.ga.insert(t,{type:2,doc:e.doc}):2===e.type&&0===r.type?this.ga=this.ga.insert(t,{type:0,doc:e.doc}):1===e.type&&0===r.type?this.ga=this.ga.remove(t):1===e.type&&2===r.type?this.ga=this.ga.insert(t,{type:1,doc:r.doc}):0===e.type&&1===r.type?this.ga=this.ga.insert(t,{type:2,doc:e.doc}):L(63341,{Vt:e,pa:r}):this.ga=this.ga.insert(t,e)}ya(){let e=[];return this.ga.inorderTraversal((t,r)=>{e.push(r)}),e}}class iI{constructor(e,t,r,n,i,s,a,o,l){this.query=e,this.docs=t,this.oldDocs=r,this.docChanges=n,this.mutatedKeys=i,this.fromCache=s,this.syncStateChanged=a,this.excludesMetadataChanges=o,this.hasCachedResults=l}static fromInitialDocuments(e,t,r,n,i){let s=[];
7return t.forEach(e=>{s.push({type:0,doc:e})}),new iI(e,t,iE.emptySet(t),s,r,n,!0,!1,i)}get hasPendingWrites(){return!this.mutatedKeys.isEmpty()}isEqual(e){if(!(this.fromCache===e.fromCache&&this.hasCachedResults===e.hasCachedResults&&this.syncStateChanged===e.syncStateChanged&&this.mutatedKeys.isEqual(e.mutatedKeys)&&tM(this.query,e.query)&&this.docs.isEqual(e.docs)&&this.oldDocs.isEqual(e.oldDocs)))return!1;let t=this.docChanges,r=e.docChanges;if(t.length!==r.length)return!1;for(let e=0;e<t.length;e++)if(t[e].type!==r[e].type||!t[e].doc.isEqual(r[e].doc))return!1;return!0}}class iT{constructor(){this.wa=void 0,this.Sa=[]}ba(){return this.Sa.some(e=>e.Da())}}class ib{constructor(){this.queries=iS(),this.onlineState="Unknown",this.Ca=new Set}terminate(){var e;let t;e=new V(U.ABORTED,"Firestore shutting down"),t=this.queries,this.queries=iS(),t.forEach((t,r)=>{for(let t of r.Sa)t.onError(e)})}}function iS(){return new tB(e=>tU(e),tM)}async function iA(e,t){let r=3,n=t.query,i=e.queries.get(n);i?!i.ba()&&t.Da()&&(r=2):(i=new iT,r=+!t.Da());try{switch(r){case 0:i.wa=await e.onListen(n,!0);break;case 1:i.wa=await e.onListen(n,!1);break;case 2:await e.onFirstRemoteStoreListen(n)}}catch(r){let e=iw(r,`Initialization of query '${tV(t.query)}' failed`);return void t.onError(e)}e.queries.set(n,i),i.Sa.push(t),t.va(e.onlineState),i.wa&&t.Fa(i.wa)&&iR(e)}async function iC(e,t){let r=t.query,n=3,i=e.queries.get(r);if(i){let e=i.Sa.indexOf(t);e>=0&&(i.Sa.splice(e,1),0===i.Sa.length?n=+!t.Da():!i.ba()&&t.Da()&&(n=2))}switch(n){case 0:return e.queries.delete(r),e.onUnlisten(r,!0);case 1:return e.queries.delete(r),e.onUnlisten(r,!1);case 2:return e.onLastRemoteStoreUnlisten(r);default:return}}function ik(e,t){let r=!1;for(let n of t){let t=n.query,i=e.queries.get(t);if(i){for(let e of i.Sa)e.Fa(n)&&(r=!0);i.wa=n}}r&&iR(e)}function iN(e,t,r){let n=e.queries.get(t);if(n)for(let e of n.Sa)e.onError(r);e.queries.delete(t)}function iR(e){e.Ca.forEach(e=>{e.next()})}(g=m||(m={})).Ma="default",g.Cache="cache";class iD{constructor(e,t,r){this.query=e,this.xa=t,this.Oa=!1,this.Na=null,this.onlineState="Unknown",this.options=r||{}}Fa(e){if(!this.options.includeMetadataChanges){let t=[];for(let r of e.docChanges)3!==r.type&&t.push(r);e=new iI(e.query,e.docs,e.oldDocs,t,e.mutatedKeys,e.fromCache,e.syncStateChanged,!0,e.hasCachedResults)}let t=!1;return this.Oa?this.Ba(e)&&(this.xa.next(e),t=!0):this.La(e,this.onlineState)&&(this.ka(e),t=!0),this.Na=e,t}onError(e){this.xa.error(e)}va(e){this.onlineState=e;let t=!1;return this.Na&&!this.Oa&&this.La(this.Na,e)&&(this.ka(this.Na),t=!0),t}La(e,t){return!(e.fromCache&&this.Da())||(!this.options.qa||"Offline"===t)&&(!e.docs.isEmpty()||e.hasCachedResults||"Offline"===t)}Ba(e){if(e.docChanges.length>0)return!0;let t=this.Na&&this.Na.hasPendingWrites!==e.hasPendingWrites;return!(!e.syncStateChanged&&!t)&&!0===this.options.includeMetadataChanges}ka(e){e=iI.fromInitialDocuments(e.query,e.docs,e.mutatedKeys,e.fromCache,e.hasCachedResults),this.Oa=!0,this.xa.next(e)}Da(){return this.options.source!==m.Cache}}class iO{constructor(e){this.key=e}}class iP{constructor(e){this.key=e}}class iL{constructor(e,t){this.query=e,this.Za=t,this.Xa=null,this.hasCachedResults=!1,this.current=!1,this.Ya=tQ(),this.mutatedKeys=tQ(),this.eu=tj(e),this.tu=new iE(this.eu)}get nu(){return this.Za}ru(e,t){let r=t?t.iu:new i_,n=t?t.tu:this.tu,i=t?t.mutatedKeys:this.mutatedKeys,s=n,a=!1,o="F"===this.query.limitType&&n.size===this.query.limit?n.last():null,l="L"===this.query.limitType&&n.size===this.query.limit?n.first():null;if(e.inorderTraversal((e,t)=>{let u=n.get(e),h=tF(this.query,t)?t:null,c=!!u&&this.mutatedKeys.has(u.key),d=!!h&&(h.hasLocalMutations||this.mutatedKeys.has(h.key)&&h.hasCommittedMutations),f=!1;u&&h?u.data.isEqual(h.data)?c!==d&&(r.track({type:3,doc:h}),f=!0):this.su(u,h)||(r.track({type:2,doc:h}),f=!0,(o&&this.eu(h,o)>0||l&&0>this.eu(h,l))&&(a=!0)):!u&&h?(r.track({type:0,doc:h}),f=!0):u&&!h&&(r.track({type:1,doc:u}),f=!0,(o||l)&&(a=!0)),f&&(h?(s=s.add(h),i=d?i.add(e):i.delete(e)):(s=s.delete(e),i=i.delete(e)))}),null!==this.query.limit)for(;s.size>this.query.limit;
7){let e="F"===this.query.limitType?s.last():s.first();s=s.delete(e.key),i=i.delete(e.key),r.track({type:1,doc:e})}return{tu:s,iu:r,bs:a,mutatedKeys:i}}su(e,t){return e.hasLocalMutations&&t.hasCommittedMutations&&!t.hasLocalMutations}applyChanges(e,t,r,n){let i=this.tu;this.tu=e.tu,this.mutatedKeys=e.mutatedKeys;let s=e.iu.ya();s.sort((e,t)=>{var r,n;let i;return r=e.type,n=t.type,(i=e=>{switch(e){case 0:return 1;case 2:case 3:return 2;case 1:return 0;default:return L(20277,{Vt:e})}})(r)-i(n)||this.eu(e.doc,t.doc)}),this.ou(r),n=n??!1;let a=t&&!n?this._u():[],o=0===this.Ya.size&&this.current&&!n?1:0,l=o!==this.Xa;return(this.Xa=o,0!==s.length||l)?{snapshot:new iI(this.query,e.tu,i,s,e.mutatedKeys,0===o,l,!1,!!r&&r.resumeToken.approximateByteSize()>0),au:a}:{au:a}}va(e){return this.current&&"Offline"===e?(this.current=!1,this.applyChanges({tu:this.tu,iu:new i_,mutatedKeys:this.mutatedKeys,bs:!1},!1)):{au:[]}}uu(e){return!this.Za.has(e)&&!!this.tu.has(e)&&!this.tu.get(e).hasLocalMutations}ou(e){e&&(e.addedDocuments.forEac
7h(e=>this.Za=this.Za.add(e)),e.modifiedDocuments.forEach(e=>{}),e.removedDocuments.forEach(e=>this.Za=this.Za.delete(e)),this.current=e.current)}_u(){if(!this.current)return[];let e=this.Ya;this.Ya=tQ(),this.tu.forEach(e=>{this.uu(e.key)&&(this.Ya=this.Ya.add(e.key))});let t=[];return e.forEach(e=>{this.Ya.has(e)||t.push(new iP(e))}),this.Ya.forEach(r=>{e.has(r)||t.push(new iO(r))}),t}cu(e){this.Za=e.ks,this.Ya=tQ();let t=this.ru(e.documents);return this.applyChanges(t,!0)}lu(){return iI.fromInitialDocuments(this.query,this.tu,this.mutatedKeys,0===this.Xa,this.hasCachedResults)}}let ix="SyncEngine";class iM{constructor(e,t,r){this.query=e,this.targetId=t,this.view=r}}class iU{constructor(e){this.key=e,this.hu=!1}}class iV{constructor(e,t,r,n,i,s){this.localStore=e,this.remoteStore=t,this.eventManager=r,this.sharedClientState=n,this.currentUser=i,this.maxConcurrentLimboResolutions=s,this.Pu={},this.Tu=new tB(e=>tU(e),tM),this.Eu=new Map,this.Iu=new Set,this.Ru=new eA(ei.comparator),this.Au=new Map,this.Vu=new nu,this.du={},this.mu=new Map,this.fu=r4.ar(),this.onlineState="Unknown",this.gu=void 0}get isPrimaryClient(){return!0===this.gu}}async function iF(e,t,r=!0){let n,i=i8(e),s=i.Tu.get(t);return s?(i.sharedClientState.addLocalQueryTarget(s.targetId),n=s.view.lu()):n=await iB(i,t,r,!0),n}async function ij(e,t){let r=i8(e);await iB(r,t,!0,!1)}async function iB(e,t,r,n){var i,s;let a,o=await (i=e.localStore,s=tP(t),i.persistence.runTransaction("Allocate target","readwrite",e=>{let t;return i.li.getTargetData(e,s).next(r=>r?(t=r,ew.resolve(t)):i.li.allocateTargetId(e).next(r=>(t=new r0(s,r,"TargetPurposeListen",e.currentSequenceNumber),i.li.addTargetData(e,t).next(()=>t))))}).then(e=>{let t=i.vs.get(e.targetId);return(null===t||e.snapshotVersion.compareTo(t.snapshotVersion)>0)&&(i.vs=i.vs.insert(e.targetId,e),i.Fs.set(s,e.targetId)),e})),l=o.targetId,u=e.sharedClientState.addLocalQueryTarget(l,r);return n&&(a=await iq(e,t,l,"current"===u,o.resumeToken)),e.isPrimaryClient&&r&&n2(e.remoteStore,o),a}async function iq(e,t,r,n,i){e.pu=(t,r,n)=>(async function(e,t,r,n){let i=t.view.ru(r);i.bs&&(i=await nC(e.localStore,t.query,!1).then(({documents:e})=>t.view.ru(e,i)));let s=n&&n.targetChanges.get(t.targetId),a=n&&null!=n.targetMismatches.get(t.targetId),o=t.view.applyChanges(i,e.isPrimaryClient,s,a);return i1(e,t.targetId,o.au),o.snapshot})(e,t,r,n);let s=await nC(e.localStore,t,!0),a=new iL(t,s.ks),o=a.ru(s.documents),l=rS.createSynthesizedTargetChangeForCurrentChange(r,n&&"Offline"!==e.onlineState,i),u=a.applyChanges(o,e.isPrimaryClient,l);i1(e,r,u.au);let h=new iM(t,r,a);return e.Tu.set(t,h),e.Eu.has(r)?e.Eu.get(r).push(t):e.Eu.set(r,[t]),u.snapshot}async function i$(e,t,r){let n=e.Tu.get(t),i=e.Eu.get(n.targetId);i.length>1?(e.Eu.set(n.targetId,i.filter(e=>!tM(e,t))),e.Tu.delete(t)):e.isPrimaryClient?(e.sharedClientState.removeLocalQueryTarget(n.targetId),e.sharedClientState.isActiveQueryTarget(n.targetId)||await nA(e.localStore,n.targetId,!1).then(()=>{e.sharedClientState.clearQueryState(n.targetId),r&&n6(e.remoteStore,n.targetId),iZ(e,n.targetId)}).catch(ev)):(iZ(e,n.targetId),await nA(e.localStore,n.targetId,!0))}async function iz(e,t){let r=e.Tu.get(t),n=e.Eu.get(r.targetId);e.isPrimaryClient&&1===n.length&&(e.sharedClientState.removeLocalQueryTarget(r.targetId),n6(e.remoteStore,r.targetId))}async function iK(e,t,r){var n,i,s;let a=((n=e).remoteStore.remoteSyncer.applySuccessfulWrite=iQ.bind(null,n),n.remoteStore.remoteSyncer.rejectFailedWrite=iJ.bind(null,n),n);try{let e,n,o,l,u,h=await (i=a.localStore,o=ef.now(),l=t.reduce((e,t)=>e.add(t.key),tQ()),i.persistence.runTransaction("Locally write mutations","readwrite",r=>{let s=tq,a=tQ();return i.xs.getEntries(r,l).next(e=>{(s=e).forEach((e,t)=>{t.isValidDocument()||(a=a.add(e))})}).next(()=>i.localDocuments.getOverlayedDocuments(r,s)).next(n=>{e=n;let s=[];for(let r of t){let t=function(e,t){let r=null;for(let n of e.fieldTransforms){let e=t.data.field(n.field),i=t0(n.transform,e||null);null!=i&&(null===r&&(r=ts.empty()),r.set(n.field,i))}return r||null}(r,e.get(r.key).overlayedDocument);null!=t&&s.push(new rl(r.key,t,function e(t){let r=[];return eb(t.fields,(t,n)=>{let i=new en([t]);if(tt(n)){let t=e(n.mapValue).fields;if(0===t.length)r.push(i);else for(let e of t)r.push(i.child(e))}else r.push(i)}),new eD(r)}(t.value.mapValue),rt.exists(!0)))}
7return i.mutationQueue.addMutationBatch(r,o,s,t)}).next(t=>{n=t;let s=t.applyToLocalDocumentSet(e,a);return i.documentOverlayCache.saveOverlays(r,t.batchId,s)})}).then(()=>({batchId:n.batchId,changes:tK(e)})));a.sharedClientState.addPendingMutation(h.batchId),s=h.batchId,(u=a.du[a.currentUser.toKey()])||(u=new eA(Q)),u=u.insert(s,r),a.du[a.currentUser.toKey()]=u,await i6(a,h.changes),await ia(a.remoteStore)}catch(t){let e=iw(t,"Failed to persist write");r.reject(e)}}async function iH(e,t){try{var r,n;let i,s,a=await (r=e.localStore,i=(n=t).snapshotVersion,s=r.vs,r.persistence.runTransaction("Apply remote event","readwrite-primary",e=>{var t,a,o;let l,u,h=r.xs.newChangeBuffer({trackRemovals:!0});s=r.vs;let c=[];n.targetChanges.forEach((t,a)=>{var o;let l=s.get(a);if(!l)return;c.push(r.li.removeMatchingKeys(e,t.removedDocuments,a).next(()=>r.li.addMatchingKeys(e,t.addedDocuments,a)));let u=l.withSequenceNumber(e.currentSequenceNumber);null!==n.targetMismatches.get(a)?u=u.withResumeToken(eP.EMPTY_BYTE_STRING,ep.min()).withLastLimboFreeSnapshotVersion(ep.min()):t.resumeToken.approximateByteSize()>0&&(u=u.withResumeToken(t.resumeToken,i)),s=s.insert(a,u),o=u,(0===l.resumeToken.approximateByteSize()||o.snapshotVersion.toMicroseconds()-l.snapshotVersion.toMicroseconds()>=3e8||t.addedDocuments.size+t.modifiedDocuments.size+t.removedDocuments.size>0)&&c.push(r.li.updateTargetData(e,u))});let d=tq,f=tQ();if(n.documentUpdates.forEach(t=>{n.resolvedLimboDocuments.has(t)&&c.push(r.persistence.referenceDelegate.updateLimboDocument(e,t))}),c.push((t=e,a=h,o=n.documentUpdates,l=tQ(),u=tQ(),o.forEach(e=>l=l.add(e)),a.getEntries(t,l).next(e=>{let t=tq;return o.forEach((r,n)=>{let i=e.get(r);n.isFoundDocument()!==i.isFoundDocument()&&(u=u.add(r)),n.isNoDocument()&&n.version.isEqual(ep.min())?(a.removeEntry(r,n.readTime),t=t.insert(r,n)):!i.isValidDocument()||n.version.compareTo(i.version)>0||0===n.version.compareTo(i.version)&&i.hasPendingWrites?(a.addEntry(n),t=t.insert(r,n)):R(nI,"Ignoring outdated watch update for ",r,". Current version:",i.version," Watch version:",n.version)}),{Bs:t,Ls:u}})).next(e=>{d=e.Bs,f=e.Ls})),!i.isEqual(ep.min())){let t=r.li.getLastRemoteSnapshotVersion(e).next(t=>r.li.setTargetsMetadata(e,e.currentSequenceNumber,i));c.push(t)}return ew.waitFor(c).next(()=>h.apply(e)).next(()=>r.localDocuments.getLocalViewOfDocuments(e,d,f)).next(()=>d)}).then(e=>(r.vs=s,e)));
7t.targetChanges.forEach((t,r)=>{let n=e.Au.get(r);n&&(M(t.addedDocuments.size+t.modifiedDocuments.size+t.removedDocuments.size<=1,22616),t.addedDocuments.size>0?n.hu=!0:t.modifiedDocuments.size>0?M(n.hu,14607):t.removedDocuments.size>0&&(M(n.hu,42227),n.hu=!1))}),await i6(e,a,t)}catch(e){await ev(e)}}function iG(e,t,r){if(e.isPrimaryClient&&0===r||!e.isPrimaryClient&&1===r){var n;let r,i=[];e.Tu.forEach((e,r)=>{let n=r.view.va(t);n.snapshot&&i.push(n.snapshot)}),(n=e.eventManager).onlineState=t,r=!1,n.queries.forEach((e,n)=>{for(let e of n.Sa)e.va(t)&&(r=!0)}),r&&iR(n),i.length&&e.Pu.H_(i),e.onlineState=t,e.isPrimaryClient&&e.sharedClientState.setOnlineState(t)}}async function iW(e,t,r){e.sharedClientState.updateQueryState(t,"rejected",r);let n=e.Au.get(t),i=n&&n.key;if(i){let r=new eA(ei.comparator);r=r.insert(i,ta.newNoDocument(i,ep.min()));let n=tQ().add(i),s=new rb(ep.min(),new Map,new eA(Q),r,n);await iH(e,s),e.Ru=e.Ru.remove(i),e.Au.delete(t),i2(e)}else await nA(e.localStore,t,!1).then(()=>iZ(e,t,r)).catch(ev)}async function iQ(e,t){let r=t.batch.batchId;try{var n,i;let s=await (n=e.localStore,i=t,n.persistence.runTransaction("Acknowledge batch","readwrite-primary",e=>{let t,r,s,a=i.batch.keys(),o=n.xs.newChangeBuffer({trackRemovals:!0});return(r=(t=i.batch).keys(),s=ew.resolve(),r.forEach(r=>{s=s.next(()=>o.getEntry(e,r)).next(e=>{let n=i.docVersions.get(r);M(null!==n,48541),0>e.version.compareTo(n)&&(t.applyToRemoteDocument(e,i),e.isValidDocument()&&(e.setReadTime(i.commitVersion),o.addEntry(e)))})}),s.next(()=>n.mutationQueue.removeMutationBatch(e,t))).next(()=>o.apply(e)).next(()=>n.mutationQueue.performConsistencyCheck(e)).next(()=>n.documentOverlayCache.removeOverlaysForBatchId(e,a,i.batch.batchId)).next(()=>n.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(e,function(e){let t=tQ();for(let r=0;r<e.mutationResults.length;++r)e.mutationResults[r].transformResults.length>0&&(t=t.add(e.batch.mutations[r].key));return t}(i))).next(()=>n.localDocuments.getDocuments(e,a))}));iY(e,r,null),iX(e,r),e.sharedClientState.updateMutationState(r,"acknowledged"),await i6(e,s)}catch(e){await ev(e)}}async function iJ(e,t,r){try{var n;let i=await (n=e.localStore,n.persistence.runTransaction("Reject batch","readwrite-primary",e=>{let r;
7return n.mutationQueue.lookupMutationBatch(e,t).next(t=>(M(null!==t,37113),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))}));iY(e,t,r),iX(e,t),e.sharedClientState.updateMutationState(t,"rejected",r),await i6(e,i)}catch(e){await ev(e)}}function iX(e,t){(e.mu.get(t)||[]).forEach(e=>{e.resolve()}),e.mu.delete(t)}function iY(e,t,r){let n=e.du[e.currentUser.toKey()];if(n){let i=n.get(t);i&&(r?i.reject(r):i.resolve(),n=n.remove(t)),e.du[e.currentUser.toKey()]=n}}function iZ(e,t,r=null){for(let n of(e.sharedClientState.removeLocalQueryTarget(t),e.Eu.get(t)))e.Tu.delete(n),r&&e.Pu.yu(n,r);e.Eu.delete(t),e.isPrimaryClient&&e.Vu.Gr(t).forEach(t=>{e.Vu.containsKey(t)||i0(e,t)})}function i0(e,t){e.Iu.delete(t.path.canonicalString());let r=e.Ru.get(t);null!==r&&(n6(e.remoteStore,r),e.Ru=e.Ru.remove(t),e.Au.delete(r),i2(e))}function i1(e,t,r){for(let n of r)n instanceof iO?(e.Vu.addReference(n.key,t),function(e,t){let r=t.key,n=r.path.canonicalString();e.Ru.get(r)||e.Iu.has(n)||(R(ix,"New document in limbo: "+r),e.Iu.add(n),i2(e))}(e,n)):n instanceof iP?(R(ix,"Document no longer in limbo: "+n.key),e.Vu.removeReference(n.key,t),e.Vu.containsKey(n.key)||i0(e,n.key)):L(19791,{wu:n})}function i2(e){for(;e.Iu.size>0&&e.Ru.size<e.maxConcurrentLimboResolutions;){let t=e.Iu.values().next().value;e.Iu.delete(t);let r=new ei(et.fromString(t)),n=e.fu.next();e.Au.set(n,new iU(r)),e.Ru=e.Ru.insert(r,n),n2(e.remoteStore,new r0(tP(new tN(r.path)),n,"TargetPurposeLimboResolution",e_.ce))}}async function i6(e,t,r){let n=[],i=[],s=[];e.Tu.isEmpty()||(e.Tu.forEach((a,o)=>{s.push(e.pu(o,t,r).then(t=>{if((t||r)&&e.isPrimaryClient){let n=t?!t.fromCache:r?.targetChanges.get(o.targetId)?.current;e.sharedClientState.updateQueryState(o.targetId,n?"current":"not-current")}if(t){n.push(t);let e=nw.Is(o.targetId,t);i.push(e)}}))}),await Promise.all(s),e.Pu.H_(n),await async function(e,t){try{await e.persistence.runTransaction("notifyLocalViewChanges","readwrite",r=>ew.forEach(t,t=>ew.forEach(t.Ts,n=>e.persistence.referenceDelegate.addReference(r,t.targetId,n)).next(()=>ew.forEach(t.Es,n=>e.persistence.referenceDelegate.removeReference(r,t.targetId,n)))))}catch(e){if(!eE(e))throw e;R(nI,"Failed to update sequence numbers: "+e)}for(let r of t){let t=r.targetId;if(!r.fromCache){let r=e.vs.get(t),n=r.snapshotVersion,i=r.withLastLimboFreeSnapshotVersion(n);e.vs=e.vs.insert(t,i)}}}(e.localStore,i))}async function i3(e,t){if(!e.currentUser.isEqual(t)){R(ix,"User change. New user:",t.toKey());let r=await nb(e.localStore,t);e.currentUser=t,e.mu.forEach(e=>{e.forEach(e=>{e.reject(new V(U.CANCELLED,"'waitForPendingWrites' promise is rejected due to a user change."))})}),e.mu.clear(),e.sharedClientState.handleUserChange(t,r.removedBatchIds,r.addedBatchIds),await i6(e,r.Ns)}}function i5(e,t){let r=e.Au.get(t);if(r&&r.hu)return tQ().add(r.key);{let r=tQ(),n=e.Eu.get(t);if(!n)return r;for(let t of n){let n=e.Tu.get(t);r=r.unionWith(n.view.nu)}return r}}function i8(e){return e.remoteStore.remoteSyncer.applyRemoteEvent=iH.bind(null,e),e.remoteStore.remoteSyncer.getRemoteKeysForTarget=i5.bind(null,e),e.remoteStore.remoteSyncer.rejectListen=iW.bind(null,e),e.Pu.H_=ik.bind(null,e.eventManager),e.Pu.yu=iN.bind(null,e.eventManager),e}class i4{constructor(){this.kind="memory",this.synchronizeTabs=!1}async initialize(e){this.serializer=n$(e.databaseInfo.databaseId),this.sharedClientState=this.Du(e),this.persistence=this.Cu(e),await this.persistence.start(),this.localStore=this.vu(e),this.gcScheduler=this.Fu(e,this.localStore),this.indexBackfillerScheduler=this.Mu(e,this.localStore)}Fu(e,t){return null}Mu(e,t){return null}vu(e){var t,r;return t=this.persistence,r=new n_,new nT(t,r,e.initialUser,this.serializer)}Cu(e){return new nm(ny.Vi,this.serializer)}Du(e){return new nN}async terminate(){this.gcScheduler?.stop(),this.indexBackfillerScheduler?.stop(),this.sharedCl
7ientState.shutdown(),await this.persistence.shutdown()}}i4.provider={build:()=>new i4};class i9 extends i4{constructor(e){super(),this.cacheSizeBytes=e}Fu(e,t){return M(this.persistence.referenceDelegate instanceof nv,46915),new nt(this.persistence.referenceDelegate.garbageCollector,e.asyncQueue,t)}Cu(e){let t=void 0!==this.cacheSizeBytes?r8.withCacheSize(this.cacheSizeBytes):r8.DEFAULT;return new nm(e=>nv.Vi(e,t),this.serializer)}}class i7{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=>iG(this.syncEngine,e,1),this.remoteStore.remoteSyncer.handleCredentialChange=i3.bind(null,this.syncEngine),await im(this.remoteStore,this.syncEngine.isPrimaryClient))}createEventManager(e){return new ib}createDatastore(e){var t;let r=n$(e.databaseInfo.databaseId),n=new nB(e.databaseInfo);return t=e.authCredentials,new nJ(t,e.appCheckCredentials,n,r)}createRemoteStore(e){var t,r;return t=this.localStore,r=this.datastore,new nZ(t,r,e.asyncQueue,e=>iG(this.syncEngine,e,0),nO.v()?new nO:new nR)}createSyncEngine(e,t){var r,n,i,s,a,o;let l;return r=this.localStore,n=this.remoteStore,i=this.eventManager,s=this.sharedClientState,a=e.initialUser,o=e.maxConcurrentLimboResolutions,l=new iV(r,n,i,s,a,o),t&&(l.gu=!0),l}async terminate(){await async function(e){R(nY,"RemoteStore shutting down."),e.Ia.add(5),await n1(e),e.Aa.shutdown(),e.Va.set("Unknown")}(this.remoteStore),this.datastore?.terminate(),this.eventManager?.terminate()}}i7.provider={build:()=>new i7};class se{constructor(e){this.observer=e,this.muted=!1}next(e){this.muted||this.observer.next&&this.Ou(this.observer.next,e)}error(e){this.muted||(this.observer.error?this.Ou(this.observer.error,e):D("Uncaught Error in snapshot listener:",e.toString()))}Nu(){this.muted=!0}Ou(e,t){setTimeout(()=>{this.muted||e(t)},0)}}let st="FirestoreClient";class sr{constructor(e,t,r,n,i){this.authCredentials=e,this.appCheckCredentials=t,this.asyncQueue=r,this._databaseInfo=n,this.user=A.UNAUTHENTICATED,this.clientId=W.newId(),this.authCredentialListener=()=>Promise.resolve(),this.appCheckCredentialListener=()=>Promise.resolve(),this._uninitializedComponentsProvider=i,this.authCredentials.start(r,async e=>{R(st,"Received user=",e.uid),await this.authCredentialListener(e),this.user=e}),this.appCheckCredentials.start(r,e=>(R(st,"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();let e=new F;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(r){let t=iw(r,"Failed to shutdown persistence");e.reject(t)}}),e.promise}}async function sn(e,t){e.asyncQueue.verifyOperationInProgress(),R(st,"Initializing OfflineComponentProvider");let r=e.configuration;await t.initialize(r);let n=r.initialUser;e.setCredentialChangeListener(async e=>{n.isEqual(e)||(await nb(t.localStore,e),n=e)}),t.persistence.setDatabaseDeletedListener(()=>e.terminate()),e._offlineComponents=t}async function si(e,t){e.asyncQueue.verifyOperationInProgress();let r=await ss(e);R(st,"Initializing OnlineComponentProvider"),await t.initialize(r,e.configuration),e.setCredentialChangeListener(e=>ip(t.remoteStore,e)),e.setAppCheckTokenChangeListener((e,r)=>ip(t.remoteStore,r)),e._onlineComponents=t}async function ss(e){if(!e._offlineComponents)if(e._uninitializedComponentsProvider){R(st,"Using user provided OfflineComponentProvider");try{await sn(e,e._uninitializedComponentsProvider._offline)}catch(t){if(!("FirebaseError"===t.name?t.code===U.FAILED_PRECONDITION||t.code===U.UNIMPLEMENT
7ED:!("u">typeof DOMException&&t instanceof DOMException)||22===t.code||20===t.code||11===t.code))throw t;O("Error using user provided cache. Falling back to memory cache: "+t),await sn(e,new i4)}}else R(st,"Using default OfflineComponentProvider"),await sn(e,new i9(void 0));return e._offlineComponents}async function sa(e){return e._onlineComponents||(e._uninitializedComponentsProvider?(R(st,"Using user provided OnlineComponentProvider"),await si(e,e._uninitializedComponentsProvider._online)):(R(st,"Using default OnlineComponentProvider"),await si(e,new i7))),e._onlineComponents}async function so(e){let t=await sa(e),r=t.eventManager;return r.onListen=iF.bind(null,t.syncEngine),r.onUnlisten=i$.bind(null,t.syncEngine),r.onFirstRemoteStoreListen=ij.bind(null,t.syncEngine),r.onLastRemoteStoreUnlisten=iz.bind(null,t.syncEngine),r}function sl(e){let t={};return void 0!==e.timeoutSeconds&&(t.timeoutSeconds=e.timeoutSeconds),t}let su=new Map,sh="firestore.googleapis.com";class sc{constructor(e){if(void 0===e.host){if(void 0!==e.ssl)throw new V(U.INVALID_ARGUMENT,"Can't provide ssl option if host option is not set");this.host=sh,this.ssl=!0}else this.host=e.host,this.ssl=e.ssl??!0;if(this.isUsingEmulator=void 0!==e.emulatorOptions,this.credentials=e.credentials,this.ignoreUndefinedProperties=!!e.ignoreUndefinedProperties,this.localCache=e.localCache,void 0===e.cacheSizeBytes)this.cacheSizeBytes=0x2800000;else{if(-1!==e.cacheSizeBytes&&e.cacheSizeBytes<1048576)throw new V(U.INVALID_ARGUMENT,"cacheSizeBytes must be at least 1048576");this.cacheSizeBytes=e.cacheSizeBytes}(function(e,t,r,n){if(!0===t&&!0===n)throw new V(U.INVALID_ARGUMENT,`${e} and ${r} cannot be used together.`)})("experimentalForceLongPolling",e.experimentalForceLongPolling,"experimentalAutoDetectLongPolling",e.experimentalAutoDetectLongPolling),this.experimentalForceLongPolling=!!e.experimentalForceLongPolling,this.experimentalForceLongPolling?this.experimentalAutoDetectLongPolling=!1:void 0===e.experimentalAutoDetectLongPolling?this.experimentalAutoDetectLongPolling=!0:this.experimentalAutoDetectLongPolling=!!e.experimentalAutoDetectLongPolling,this.experimentalLongPollingOptions=sl(e.experimentalLongPollingOptions??{}),function(e){if(void 0!==e.timeoutSeconds){if(isNaN(e.timeoutSeconds))throw new V(U.INVALID_ARGUMENT,`invalid long polling timeout: ${e.timeoutSeconds} (must not be NaN)`);if(e.timeoutSeconds<5)throw new V(U.INVALID_ARGUMENT,`invalid long polling timeout: ${e.timeoutSeconds} (minimum allowed value is 5)`);if(e.timeoutSeconds>30)throw new V(U.INVALID_ARGUMENT,`invalid long polling timeout: ${e.timeoutSeconds} (maximum allowed value is 30)`)}}(this.experimentalLongPollingOptions),this.useFetchStreams=!!e.useFetchStreams}isEqual(e){var t,r;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&&(t=this.experimentalLongPollingOptions,r=e.experimentalLongPollingOptions,t.timeoutSeconds===r.timeoutSeconds)&&this.ignoreUndefinedProperties===e.ignoreUndefinedProperties&&this.useFetchStreams===e.useFetchStreams}}class sd{constructor(e,t,r,n){this._authCredentials=e,this._appCheckCredentials=t,this._databaseId=r,this._app=n,this.type="firestore-lite",this._persistenceKey="(lite)",this._settings=new sc({}),this._settingsFrozen=!1,this._emulatorOptions={},this._terminateTask="notTerminated"}get app(){if(!this._app)throw new V(U.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 V(U.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 sc(e),this._emulatorOptions=e.emulatorOptions||{},void 0!==e.credentials&&(this._authCredentials=function(e){if(!e)return new B;switch(e.type){case"firstParty":return new K(e.sessionIndex||"0",e.iamToken||null,e.authTokenFactory||null);case"provider":return e.client;default:throw new V(U.INVALID_ARGUMENT,"makeAuthCredentialsProvider failed due to invali
7d credential type")}}(e.credentials))}_getSettings(){return this._settings}_getEmulatorOptions(){return this._emulatorOptions}_freezeSettings(){return this._settingsFrozen=!0,this._settings}_delete(){return"notTerminated"===this._terminateTask&&(this._terminateTask=this._terminate()),this._terminateTask}async _restart(){"notTerminated"===this._terminateTask?await this._terminate():this._terminateTask="notTerminated"}toJSON(){return{app:this._app,databaseId:this._databaseId,settings:this._settings}}_terminate(){let e;return(e=su.get(this))&&(R("ComponentProvider","Removing Datastore"),su.delete(this),e.terminate()),Promise.resolve()}}function sf(e,t,r,n={}){e=eh(e,sd);let i=(0,w.zJ)(t),s=e._getSettings(),a={...s,emulatorOptions:e._getEmulatorOptions()},o=`${t}:${r}`;i&&(0,w.gE)(`https://${o}`),s.host!==sh&&s.host!==o&&O("Host has been set in both settings() and connectFirestoreEmulator(), emulator host will be used.");let l={...s,host:o,ssl:i,emulatorOptions:n};if(!(0,w.bD)(l,a)&&(e._setSettings(l),n.mockUserToken)){let t,r;if("string"==typeof n.mockUserToken)t=n.mockUserToken,r=A.MOCK_USER;else{t=(0,w.Fy)(n.mockUserToken,e._app?.options.projectId);let i=n.mockUserToken.sub||n.mockUserToken.user_id;if(!i)throw new V(U.INVALID_ARGUMENT,"mockUserToken must contain 'sub' or 'user_id' field!");r=new A(i)}e._authCredentials=new q(new j(t,r))}}class sp{constructor(e,t,r){this.converter=t,this._query=r,this.type="query",this.firestore=e}withConverter(e){return new sp(this.firestore,e,this._query)}}class sm{constructor(e,t,r){this.converter=t,this._key=r,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 sg(this.firestore,this.converter,this._key.path.popLast())}withConverter(e){return new sm(this.firestore,e,this._key)}toJSON(){return{type:sm._jsonSchemaVersion,referencePath:this._key.toString()}}static fromJSON(e,t,r){if(ed(t,sm._jsonSchema))return new sm(e,r||null,new ei(et.fromString(t.referencePath)))}}sm._jsonSchemaVersion="firestore/documentReference/1.0",sm._jsonSchema={type:ec("string",sm._jsonSchemaVersion),referencePath:ec("string")};class sg extends sp{constructor(e,t,r){super(e,t,function(e){return new tN(e)}(r)),this._path=r,this.type="collection"}get id(){return this._query.path.lastSegment()}get path(){return this._query.path.canonicalString()}get parent(){let e=this._path.popLast();return e.isEmpty()?null:new sm(this.firestore,null,new ei(e))}withConverter(e){return new sg(this.firestore,e,this._path)}}function sy(e,t,...r){if(e=(0,w.Ku)(e),es("collection","path",t),e instanceof sd){let n=et.fromString(t,...r);return eo(n),new sg(e,null,n)}{if(!(e instanceof sm||e instanceof sg))throw new V(U.INVALID_ARGUMENT,"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");let n=e._path.child(et.fromString(t,...r));return eo(n),new sg(e.firestore,null,n)}}function sv(e,t,...r){if(e=(0,w.Ku)(e),1==arguments.length&&(t=W.newId()),es("doc","path",t),e instanceof sd){let n=et.fromString(t,...r);return ea(n),new sm(e,null,new ei(n))}{if(!(e instanceof sm||e instanceof sg))throw new V(U.INVALID_ARGUMENT,"Expected first argument to doc() to be a CollectionReference, a DocumentReference or FirebaseFirestore");let n=e._path.child(et.fromString(t,...r));return ea(n),new sm(e.firestore,e instanceof sg?e.converter:null,new ei(n))}}let sw="AsyncQueue";class sE{constructor(e=Promise.resolve()){this.Yu=[],this.ec=!1,this.tc=[],this.nc=null,this.rc=!1,this.sc=!1,this.oc=[],this.M_=new nz(this,"async_queue_retry"),this._c=()=>{let e=nq();e&&R(sw,"Visibility state changed to "+e.visibilityState),this.M_.w_()},this.ac=e;const t=nq();t&&"function"==typeof t.addEventListener&&t.addEventListener("visibilitychange",this._c)}get isShuttingDown(){return this.ec}enqueueAndForget(e){this.enqueue(e)}enqueueAndForgetEvenWhileRestricted(e){this.uc(),this.cc(e)}enterRestrictedMode(e){if(!this.ec){this.ec=!0,this.sc=e||!1;let t=nq();t&&"function"==typeof t.removeEventListener&&t.removeEventListener("visibilitychange",this._c)}}enqueue(e){if(this.uc(),this.ec)return new Promise(()=>{});let t=new F;return this.cc(()=>this.ec&&this.sc?Promise.resolve():(e().then(t.resolve,t.reject),t.promise)).then(()=>t.promise)}enqueueRetryable(e){this.enqueueAndForget(()=>(this.Yu.push(e),this.lc()))}async lc(){if(0!==this.Yu.length){try{await this.Yu[0](),this.Yu.shift(),this.M_.reset()}catch(e){if(!eE(e))throw e;R(sw,"Operation failed with retryable error: "+e)}this.Yu.length>0&&this.M_.p_(()=>this.lc())}}cc(e){let t=this.ac.then(()=>(this.rc=!0,e().catch(e=>{throw this.nc=e,this.rc=!1,D("INTERNAL UNHANDLED ERROR: ",s_(e)),e}).then(e=>(this.rc=!1,e))));return this.ac=t,t}enqueueAfterDelay(e,t,r){this.uc(),this.oc.indexOf(e)>-1&&(t=0);let n=iv.createAndSchedule(this,e,t,r,e=>this.hc(e));return this.tc.push(n),n}uc(){this.nc&&L(47125,{Pc:s_(this.nc)})}verifyOperationInProgress(){}async Tc(){let e;do e=this.ac,await e;while(e!==this.ac)}Ec(e){for(let t of this.tc)if(t.timerId===e)return!0;return!1}Ic(e){return this.Tc().then(()=>{for(let t of(this.tc.sort((e,t)=>
7e.targetTimeMs-t.targetTimeMs),this.tc))if(t.skipDelay(),"all"!==e&&t.timerId===e)break;return this.Tc()})}Rc(e){this.oc.push(e)}hc(e){let t=this.tc.indexOf(e);this.tc.splice(t,1)}}function s_(e){let t=e.message||"";return e.stack&&(t=e.stack.includes(e.message)?e.stack:e.message+"\n"+e.stack),t}class sI extends sd{constructor(e,t,r,n){super(e,t,r,n),this.type="firestore",this._queue=new sE,this._persistenceKey=n?.name||"[DEFAULT]"}async _terminate(){if(this._firestoreClient){let e=this._firestoreClient.terminate();this._queue=new sE(e),this._firestoreClient=void 0,await e}}}function sT(e,t){let r="object"==typeof e?e:(0,y.Sx)(),n=(0,y.j6)(r,"firestore").getImmediate({identifier:"string"==typeof e?e:t||eH});if(!n._initialized){let e=(0,w.yU)("firestore");e&&sf(n,...e)}return n}function sb(e){if(e._terminated)throw new V(U.FAILED_PRECONDITION,"The client has already been terminated.");return e._firestoreClient||function(e){var t,r,n,i,s;let a,o=e._freezeSettings(),l=(t=e._databaseId,r=e._app?.options.appId||"",n=e._persistenceKey,i=e._app?.options.apiKey,new eK(t,r,n,o.host,o.ssl,o.experimentalForceLongPolling,o.experimentalAutoDetectLongPolling,sl(o.experimentalLongPollingOptions),o.useFetchStreams,o.isUsingEmulator,i));e._componentsProvider||o.localCache?._offlineComponentProvider&&o.localCache?._onlineComponentProvider&&(e._componentsProvider={_offline:o.localCache._offlineComponentProvider,_online:o.localCache._onlineComponentProvider}),e._firestoreClient=new sr(e._authCredentials,e._appCheckCredentials,e._queue,l,e._componentsProvider&&(s=e._componentsProvider,a=s?._online.build(),{_offline:s?._offline.build(a),_online:a}))}(e),e._firestoreClient}class sS{constructor(e){this._byteString=e}static fromBase64String(e){try{return new sS(eP.fromBase64String(e))}catch(e){throw new V(U.INVALID_ARGUMENT,"Failed to construct data from Base64 string: "+e)}}static fromUint8Array(e){return new sS(eP.fromUint8Array(e))}toBase64(){return this._byteString.toBase64()}toUint8Array(){return this._byteString.toUint8Array()}toString(){return"Bytes(base64: "+this.toBase64()+")"}isEqual(e){return this._byteString.isEqual(e._byteString)}toJSON(){return{type:sS._jsonSchemaVersion,bytes:this.toBase64()}}static fromJSON(e){if(ed(e,sS._jsonSchema))return sS.fromBase64String(e.bytes)}}sS._jsonSchemaVersion="firestore/bytes/1.0",sS._jsonSchema={type:ec("string",sS._jsonSchemaVersion),bytes:ec("string")};class sA{constructor(...e){for(let t=0;t<e.length;++t)if(0===e[t].length)throw new V(U.INVALID_ARGUMENT,"Invalid field name at argument $(i + 1). Field names must not be empty.");this._internalPath=new en(e)}isEqual(e){return this._internalPath.isEqual(e._internalPath)}}class sC{constructor(e){this._methodName=e}}class sk{constructor(e,t){if(!isFinite(e)||e<-90||e>90)throw new V(U.INVALID_ARGUMENT,"Latitude must be a number between -90 and 90, but was: "+e);if(!isFinite(t)||t<-180||t>180)throw new V(U.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}_compareTo(e){return Q(this._lat,e._lat)||Q(this._long,e._long)}toJSON(){return{latitude:this._lat,longitude:this._long,type:sk._jsonSchemaVersion}}static fromJSON(e){if(ed(e,sk._jsonSchema))return new sk(e.latitude,e.longitude)}}sk._jsonSchemaVersion="firestore/geoPoint/1.0",sk._jsonSchema={type:ec("string",sk._jsonSchemaVersion),latitude:ec("number"),longitude:ec("number")};class sN{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 r=0;r<e.length;++r)if(e[r]!==t[r])return!1;return!0}(this._values,e._values)}toJSON(){return{type:sN._jsonSchemaVersion,vectorValues:this._values}}static fromJSON(e){if(ed(e,sN._jsonSchema)){if(Array.isArray(e.vectorValues)&&e.vectorValues.every(e=>"number"==typeof e))return new sN(e.vectorValues);throw new V(U.INVALID_ARGUMENT,"Expected 'vectorValues' field to be a number array")}}}sN._jsonSchemaVersion="firestore/vectorValue/1.0",sN._jsonSchema={type:ec("string",sN._jsonSchemaVersion),vectorValues:ec("object")};let sR=/^__.*__$/;class sD{constructor(e,t,r){this.data=e,this.fieldMask=t,this.fieldTransforms=r}toMutation(e,t){return null!==this.fieldMask?new rl(e,this.data,this.fieldMask,t,this.fieldTransforms):new ro(e,this.data,t,this.fieldTransforms)}}class sO{constructor(e,t,r){this.data=e,this.fieldMask=t,this.fieldTransforms=r}toMutation(e,t){return new rl(e,this.data,this.fieldMask,t,this.fieldTransforms)}}function sP(e){switch(e){case 0:case 2:case 1:return!0;case 3:case 4:return!1;default:throw L(40011,{dataSource:e})}}class sL{constructor(e,t,r,n,i,s){this.settings=e,this.databaseId=t,this.serializer
7=r,this.ignoreUndefinedProperties=n,void 0===i&&this.Ac(),this.fieldTransforms=i||[],this.fieldMask=s||[]}get path(){return this.settings.path}get dataSource(){return this.settings.dataSource}i(e){return new sL({...this.settings,...e},this.databaseId,this.serializer,this.ignoreUndefinedProperties,this.fieldTransforms,this.fieldMask)}dc(e){let t=this.path?.child(e),r=this.i({path:t,arrayElement:!1});return r.mc(e),r}fc(e){let t=this.path?.child(e),r=this.i({path:t,arrayElement:!1});return r.Ac(),r}gc(e){return this.i({path:void 0,arrayElement:!0})}yc(e){return sH(e,this.settings.methodName,this.settings.hasConverter||!1,this.path,this.settings.targetDoc)}contains(e){return void 0!==this.fieldMask.find(t=>e.isPrefixOf(t))||void 0!==this.fieldTransforms.find(t=>e.isPrefixOf(t.field))}Ac(){if(this.path)for(let e=0;e<this.path.length;e++)this.mc(this.path.get(e))}mc(e){if(0===e.length)throw this.yc("Document fields must not be empty");if(sP(this.dataSource)&&sR.test(e))throw this.yc('Document fields cannot begin and end with "__"')}}class sx{constructor(e,t,r){this.databaseId=e,this.ignoreUndefinedProperties=t,this.serializer=r||n$(e)}I(e,t,r,n=!1){return new sL({dataSource:e,methodName:t,targetDoc:r,path:en.emptyPath(),arrayElement:!1,hasConverter:n},this.databaseId,this.serializer,this.ignoreUndefinedProperties)}}function sM(e){let t=e._freezeSettings(),r=n$(e._databaseId);return new sx(e._databaseId,!!t.ignoreUndefinedProperties,r)}class sU extends sC{_toFieldTransform(e){if(2!==e.dataSource)throw 1===e.dataSource?e.yc(`${this._methodName}() can only appear at the top level of your update data`):e.yc(`${this._methodName}() cannot be used with set() unless you pass {merge:true}`);return e.fieldMask.push(e.path),null}isEqual(e){return e instanceof sU}}class sV extends sC{_toFieldTransform(e){return new t7(e.path,new t1)}isEqual(e){return e instanceof sV}}function sF(e,t){if(sB(e=(0,w.Ku)(e)))return sq("Unsupported field value:",t,e),sj(e,t);if(e instanceof sC)return function(e,t){if(!sP(t.dataSource))throw t.yc(`${e._methodName}() can only be used with update() and set()`);if(!t.path)throw t.yc(`${e._methodName}() is not currently supported inside arrays`);let r=e._toFieldTransform(t);r&&t.fieldTransforms.push(r)}(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.arrayElement&&4!==t.dataSource)throw t.yc("Nested arrays are not supported");let r=[],n=0;for(let i of e){let e=sF(i,t.gc(n));null==e&&(e={nullValue:"NULL_VALUE"}),r.push(e),n++}return{arrayValue:{values:r}}}return function(e,t){var r,n,i,s;if(null===(e=(0,w.Ku)(e)))return{nullValue:"NULL_VALUE"};if("number"==typeof e)return r=t.serializer,"number"==typeof(i=n=e)&&Number.isInteger(i)&&!eI(i)&&i<=Number.MAX_SAFE_INTEGER&&i>=Number.MIN_SAFE_INTEGER?tY(n):tX(r,n);if("boolean"==typeof e)return{booleanValue:e};if("string"==typeof e)return{stringValue:e};if(e instanceof Date){let r=ef.fromDate(e);return{timestampValue:rV(t.serializer,r)}}if(e instanceof ef){let r=new ef(e.seconds,1e3*Math.floor(e.nanoseconds/1e3));return{timestampValue:rV(t.serializer,r)}}if(e instanceof sk)return{geoPointValue:{latitude:e.latitude,longitude:e.longitude}};if(e instanceof sS)return{bytesValue:rF(t.serializer,e._byteString)};if(e instanceof sm){let r=t.databaseId,n=e.firestore._databaseId;if(!n.isEqual(r))throw t.yc(`Document reference is for database ${n.projectId}/${n.database} but should be for database ${r.projectId}/${r.database}`);return{referenceValue:rB(e.firestore._databaseId||t.databaseId,e._key.path)}}if(e instanceof sN)return{mapValue:{fields:{[eW]:{stringValue:eX},[eY]:{arrayValue:{values:((s=e)instanceof sN?s.toArray():s).map(e=>{if("number"!=typeof e)throw t.yc("VectorValues must only contain numeric values.");return tX(t.serializer,e)})}}}}};if(rZ(e))return e._toProto(t.serializer);throw t.yc(`Unsupported field value: ${eu(e)}`)}(e,t)}function sj(e,t){let r={};return eS(e)?t.path&&t.path.length>0&&t.fieldMask.push(t.path):eb(e,(e,n)=>{let i=sF(n,t.dc(e));null!=i&&(r[e]=i)}),{mapValue:{fields:r}}}function sB(e){return!("object"!=typeof e||null===e||e instanceof Array||e instanceof Date||e instanceof ef||e instanceof sk||e instanceof sS||e instanceof sm||e instanceof sC||e instanceof sN||rZ(e))}function sq(e,t,r){if(!sB(r)||!el(r)){let n=eu(r);throw"an object"===n?t.yc(e+" a custom object"):t.yc(e+" "+n)}}function s$(e,t,r){if((t=(0,w.Ku)(t))instanceof sA)return t._internalPath;if("string"==typeof t)return sK(e,t);throw sH("Field path arguments must be of type string or ",e,!1,void 0,r)}let sz=RegExp("[~\\*/\\[\\]]");function sK(e,t,r){if(t.search(sz)>=0)throw sH(`Invalid field path (${t}). Paths must not contain '~', '*', '/', '[', or ']'`,e,!1,void 0,r);try{return new sA(...t.split("."))._internalPath}catch(n){throw sH(`Invalid field path (${t}). Paths must not be empty, begin with '.', end with '.', or contain '..'`,e,!1,void 0,r)}}function sH(e,t,r,n,i){let s=n&&!n.isEmpty(),a=void 0!==i,o=`Function ${t}
7() called with invalid data`;r&&(o+=" (via `toFirestore()`)"),o+=". ";let l="";return(s||a)&&(l+=" (found",s&&(l+=` in field ${n}`),a&&(l+=` in document ${i}`),l+=")"),new V(U.INVALID_ARGUMENT,o+e+l)}function sG(e,t){return e.some(e=>e.isEqual(t))}class sW{convertValue(e,t="none"){switch(eZ(e)){case 0:return null;case 1:return e.booleanValue;case 2:return eM(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(eU(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 L(62114,{value:e})}}convertObject(e,t){return this.convertObjectMap(e.fields,t)}convertObjectMap(e,t="none"){let r={};return eb(e,(e,n)=>{r[e]=this.convertValue(n,t)}),r}convertVectorValue(e){return new sN(e.fields?.[eY].arrayValue?.values?.map(e=>eM(e.doubleValue)))}convertGeoPoint(e){return new sk(eM(e.latitude),eM(e.longitude))}convertArray(e,t){return(e.values||[]).map(e=>this.convertValue(e,t))}convertServerTimestamp(e,t){switch(t){case"previous":let r=e$(e);return null==r?null:this.convertValue(r,t);case"estimate":return this.convertTimestamp(ez(e));default:return null}}convertTimestamp(e){let t=ex(e);return new ef(t.seconds,t.nanos)}convertDocumentKey(e,t){let r=et.fromString(e);M(rY(r),9688,{name:e});let n=new eG(r.get(1),r.get(3)),i=new ei(r.popFirst(5));return n.isEqual(t)||D(`Document ${i} contains a document reference within a different database (${n.projectId}/${n.database}) which is not supported. It will be treated as a reference in the current database (${t.projectId}/${t.database}) instead.`),i}}class sQ extends sW{constructor(e){super(),this.firestore=e}convertBytes(e){return new sS(e)}convertReference(e){let t=this.convertDocumentKey(e,this.firestore._databaseId);return new sm(this.firestore,null,t)}}function sJ(){return new sV("serverTimestamp")}let sX="@firebase/firestore",sY="4.14.0";class sZ{constructor(e,t,r,n,i){this._firestore=e,this._userDataWriter=t,this._key=r,this._document=n,this._converter=i}get id(){return this._key.path.lastSegment()}get ref(){return new sm(this._firestore,this._converter,this._key)}exists(){return null!==this._document}data(){if(this._document){if(this._converter){let e=new s0(this._firestore,this._userDataWriter,this._key,this._document,null);return this._converter.fromFirestore(e)}return this._userDataWriter.convertValue(this._document.data.value)}}_fieldsProto(){return this._document?.data.clone().value.mapValue.fields??void 0}get(e){if(this._document){let t=this._document.data.field(s$("DocumentSnapshot.get",e));if(null!==t)return this._userDataWriter.convertValue(t)}}}class s0 extends sZ{data(){return super.data()}}class s1{}class s2 extends s1{}function s6(e,t,...r){let n=[];for(let i of(t instanceof s1&&n.push(t),function(e){let t=e.filter(e=>e instanceof s8).length,r=e.filter(e=>e instanceof s3).length;if(t>1||t>0&&r>0)throw new V(U.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(...)))`.")}(n=n.concat(r)),n))e=i._apply(e);return e}class s3 extends s2{constructor(e,t,r){super(),this._field=e,this._op=t,this._value=r,this.type="where"}static _create(e,t,r){return new s3(e,t,r)}_apply(e){let t=this._parse(e);return s7(e._query,t),new sp(e.firestore,e.converter,tL(e._query,t))}_parse(e){let t=sM(e.firestore);return function(e,t,r,n,i,s,a){let o;if(i.isKeyField()){if("array-contains"===s||"array-contains-any"===s)throw new V(U.INVALID_ARGUMENT,`Invalid Query. You can't perform '${s}' queries on documentId().`);if("in"===s||"not-in"===s){s9(a,s);let t=[];for(let r of a)t.push(s4(n,e,r));o={arrayValue:{values:t}}}else o=s4(n,e,a)}else"in"!==s&&"not-in"!==s&&"array-contains-any"!==s||s9(a,s),o=function(e,t,r,n=!1){return sF(r,e.I(n?4:3,t))}(r,t,a,"in"===s||"not-in"===s);return td.create(i,s,o)}(e._query,"where",t,e.firestore._databaseId,this._field,this._op,this._value)}}function s5(e,t,r){let n=s$("where",e);return s3._create(n,t,r)}class s8 extends s1{constructor(e,t){super(),this.type=e,this._queryConstraints=t}static _create(e,t){return new s8(e,t)}_parse(e){let t=this._queryConstraints.map(t=>t._parse(e)).filter(e=>e.getFilters().length>0);return 1===t.length?t[0]:tf.create(t,this._getOperator())}_apply(e){let t=this._parse(e);return 0===t.getFilters().length?e:(function(e,t){let r=e;for(let e of t.getFlattenedFilters())s7(r,e),r=tL(r,e)}(e._query,t),new sp(e.firestore,e.converter,tL(e._query,t)))}_getQueryConstraints(){return this._queryConstraints}_getOperator(){return"and"===this.type?"and":"or"}}
7function s4(e,t,r){if("string"==typeof(r=(0,w.Ku)(r))){if(""===r)throw new V(U.INVALID_ARGUMENT,"Invalid query. When querying with documentId(), you must provide a valid document ID, but it was an empty string.");if(!tD(t)&&-1!==r.indexOf("/"))throw new V(U.INVALID_ARGUMENT,`Invalid query. When querying a collection by documentId(), you must provide a plain document ID, but '${r}' contains a '/' character.`);let n=t.path.child(et.fromString(r));if(!ei.isDocumentKey(n))throw new V(U.INVALID_ARGUMENT,`Invalid query. When querying a collection group by documentId(), the value provided must result in a valid document path, but '${n}' is not because it has an odd number of segments (${n.length}).`);return e8(e,new ei(n))}if(r instanceof sm)return e8(e,r._key);throw new V(U.INVALID_ARGUMENT,`Invalid query. When querying with documentId(), you must provide a valid string or a DocumentReference, but it was: ${eu(r)}.`)}function s9(e,t){if(!Array.isArray(e)||0===e.length)throw new V(U.INVALID_ARGUMENT,`Invalid Query. A non-empty array is required for '${t.toString()}' filters.`)}function s7(e,t){let r=function(e,t){for(let r of e)for(let e of r.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!==r)throw r===t.op?new V(U.INVALID_ARGUMENT,`Invalid query. You cannot use more than one '${t.op.toString()}' filter.`):new V(U.INVALID_ARGUMENT,`Invalid query. You cannot use '${t.op.toString()}' filters with '${r.toString()}' filters.`)}class ae{constructor(e,t){this.hasPendingWrites=e,this.fromCache=t}isEqual(e){return this.hasPendingWrites===e.hasPendingWrites&&this.fromCache===e.fromCache}}class at extends sZ{constructor(e,t,r,n,i,s){super(e,t,r,n,s),this._firestore=e,this._firestoreImpl=e,this.metadata=i}exists(){return super.exists()}data(e={}){if(this._document){if(this._converter){let t=new ar(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){let r=this._document.data.field(s$("DocumentSnapshot.get",e));if(null!==r)return this._userDataWriter.convertValue(r,t.serverTimestamps)}}toJSON(){if(this.metadata.hasPendingWrites)throw new V(U.FAILED_PRECONDITION,"DocumentSnapshot.toJSON() attempted to serialize a document with pending writes. Await waitForPendingWrites() before invoking toJSON().");let e=this._document,t={};return t.type=at._jsonSchemaVersion,t.bundle="",t.bundleSource="DocumentSnapshot",t.bundleName=this._key.toString(),e&&e.isValidDocument()&&e.isFoundDocument()&&(this._userDataWriter.convertObjectMap(e.data.value.mapValue.fields,"previous"),this._firestore,this.ref.path,t.bundle="NOT SUPPORTED"),t}}at._jsonSchemaVersion="firestore/documentSnapshot/1.0",at._jsonSchema={type:ec("string",at._jsonSchemaVersion),bundleSource:ec("string","DocumentSnapshot"),bundleName:ec("string"),bundle:ec("string")};class ar extends at{data(e={}){return super.data(e)}}class an{constructor(e,t,r,n){this._firestore=e,this._userDataWriter=t,this._snapshot=n,this.metadata=new ae(n.hasPendingWrites,n.fromCache),this.query=r}get docs(){let 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(r=>{e.call(t,new ar(this._firestore,this._userDataWriter,r.key,r,new ae(this._snapshot.mutatedKeys.has(r.key),this._snapshot.fromCache),this.query.converter))})}docChanges(e={}){let t=!!e.includeMetadataChanges;if(t&&this._snapshot.excludesMetadataChanges)throw new V(U.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(r=>{let n=new ar(e._firestore,e._userDataWriter,r.doc.key,r.doc,new ae(e._snapshot.mutatedKeys.has(r.doc.key),e._snapshot.fromCache),e.query.converter);return r.doc,{type:"added",doc:n,oldIndex:-1,newIndex:t++}})}{let r=e._snapshot.oldDocs;return e._snapshot.docChanges.filter(e=>t||3!==e.type).map(t=>{let n=new ar(e._firestore,e._userDataWriter,t.doc.key,t.doc,new ae(e._snapshot.mutatedKeys.has(t.doc.key),e._snapshot.fromCache),e.query.converter),i=-1,s=-1;return 0!==t.type&&(i=r.indexOf(t.doc.key),r=r.delete(t.doc.key)),1!==t.type&&(s=(r=r.add(t.doc)).indexOf(t.doc.key)),{type:function(e){switch(e){case 0:return"added";case 2:case 3:return"modified";case 1:return"removed";default:return L(61501,{type:e})}}(t.type),doc:n,oldIndex:i,newIndex:s}})}}(this,t),this._cachedChangesIncludeMetadataChanges=t),this._cachedChanges}toJSON(){if(this.metadata.hasPendingWrites)throw new V(U.FAILED_PRECONDITION,"QuerySnapsh
7ot.toJSON() attempted to serialize a document with pending writes. Await waitForPendingWrites() before invoking toJSON().");let e={};e.type=an._jsonSchemaVersion,e.bundleSource="QuerySnapshot",e.bundleName=W.newId(),this._firestore._databaseId.database,this._firestore._databaseId.projectId;let t=[],r=[],n=[];return this.docs.forEach(e=>{null!==e._document&&(t.push(e._document),r.push(this._userDataWriter.convertObjectMap(e._document.data.value.mapValue.fields,"previous")),n.push(e.ref.path))}),this._firestore,this.query._query,e.bundleName,e.bundle="NOT SUPPORTED",e}}function ai(e){e=eh(e,sm);let t=eh(e.firestore,sI);return(function(e,t,r={}){let n=new F;return e.asyncQueue.enqueueAndForget(async()=>{var i,s;let a,o;return i=await so(e),s=e.asyncQueue,a=new se({next:e=>{a.Nu(),s.enqueueAndForget(()=>iC(i,o));let l=e.docs.has(t);!l&&e.fromCache?n.reject(new V(U.UNAVAILABLE,"Failed to get document because the client is offline.")):l&&e.fromCache&&r&&"server"===r.source?n.reject(new V(U.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.)')):n.resolve(e)},error:e=>n.reject(e)}),iA(i,o=new iD(new tN(t.path),a,{includeMetadataChanges:!0,qa:!0}))}),n.promise})(sb(t),e._key).then(r=>{var n,i,s;let a,o;return n=t,i=e,a=(s=r).docs.get(i._key),o=new sQ(n),new at(n,o,i._key,a,new ae(s.hasPendingWrites,s.fromCache),i.converter)})}function as(e){e=eh(e,sp);let t=eh(e.firestore,sI),r=sb(t),n=new sQ(t);return function(e){if("L"===e.limitType&&0===e.explicitOrderBy.length)throw new V(U.UNIMPLEMENTED,"limitToLast() queries require specifying at least one orderBy() clause")}(e._query),(function(e,t,r={}){let n=new F;return e.asyncQueue.enqueueAndForget(async()=>{var i,s;let a,o;return i=await so(e),s=e.asyncQueue,o=new iD(t,a=new se({next:e=>{a.Nu(),s.enqueueAndForget(()=>iC(i,o)),e.fromCache&&"server"===r.source?n.reject(new V(U.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.)')):n.resolve(e)},error:e=>n.reject(e)}),{includeMetadataChanges:!0,qa:!0}),iA(i,o)}),n.promise})(r,e._query).then(r=>new an(t,n,e,r))}function aa(e,t,r){var n;e=eh(e,sm);let i=eh(e.firestore,sI),s=(n=e.converter,n?r&&(r.merge||r.mergeFields)?n.toFirestore(t,r):n.toFirestore(t):t),a=sM(i);return al(i,[(function(e,t,r,n,i,s={}){let a,o,l=e.I(s.merge||s.mergeFields?2:0,t,r,i);sq("Data must be an object, but it was:",l,n);let u=sj(n,l);if(s.merge)a=new eD(l.fieldMask),o=l.fieldTransforms;else if(s.mergeFields){let e=[];for(let n of s.mergeFields){let i=s$(t,n,r);if(!l.contains(i))throw new V(U.INVALID_ARGUMENT,`Field '${i}' is specified in your field mask but missing from your input data.`);sG(e,i)||e.push(i)}a=new eD(e),o=l.fieldTransforms.filter(e=>a.covers(e.field))}else a=null,o=l.fieldTransforms;return new sD(new ts(u),a,o)})(a,"setDoc",e._key,s,null!==e.converter,r).toMutation(e._key,rt.none())])}function ao(e,t,r,...n){var i,s,a;let o,l,u;e=eh(e,sm);let h=eh(e.firestore,sI),c=sM(h);return al(h,[("string"==typeof(t=(0,w.Ku)(t))||t instanceof sA?function(e,t,r,n,i,s){let a=e.I(1,t,r),o=[s$(t,n,r)],l=[i];if(s.length%2!=0)throw new V(U.INVALID_ARGUMENT,`Function ${t}() needs to be called with an even number of arguments that alternate between field names and values.`);for(let e=0;e<s.length;e+=2)o.push(s$(t,s[e])),l.push(s[e+1]);let u=[],h=ts.empty();for(let e=o.length-1;e>=0;--e)if(!sG(u,o[e])){let t=o[e],r=l[e];r=(0,w.Ku)(r);let n=a.fc(t);if(r instanceof sU)u.push(t);else{let e=sF(r,n);null!=e&&(u.push(t),h.set(t,e))}}return new sO(h,new eD(u),a.fieldTransforms)}(c,"updateDoc",e._key,t,r,n):(i="updateDoc",s=e._key,a=t,sq("Data must be an object, but it was:",o=c.I(1,i,s),a),l=[],u=ts.empty(),eb(a,(e,t)=>{let r=sK(i,e,s);t=(0,w.Ku)(t);let n=o.fc(r);if(t instanceof sU)l.push(r);else{let e=sF(t,n);null!=e&&(l.push(r),u.set(r,e))}}),new sO(u,new eD(l),o.fieldTransforms))).toMutation(e._key,rt.exists(!0))])}function al(e,t){var r;let n;return r=sb(e),n=new F,r.asyncQueue.enqueueAndForget(async()=>iK(await sa(r).then(e=>e.syncEngine),t,n)),n.promise}
7an._jsonSchemaVersion="firestore/querySnapshot/1.0",an._jsonSchema={type:ec("string",an._jsonSchemaVersion),bundleSource:ec("string","QuerySnapshot"),bundleName:ec("string"),bundle:ec("string")},new WeakMap,function(e=!0){C=y.MF,(0,y.om)(new v.uA("firestore",(t,{instanceIdentifier:r,options:n})=>{let i=t.getProvider("app").getImmediate(),s=new sI(new $(t.getProvider("auth-internal")),new G(i,t.getProvider("app-check-internal")),function(e,t){if(!Object.prototype.hasOwnProperty.apply(e.options,["projectId"]))throw new V(U.INVALID_ARGUMENT,'"projectId" not provided in firebase.initializeApp.');return new eG(e.options.projectId,t)}(i,r),i);return n={useFetchStreams:e,...n},s._setSettings(n),s},"PUBLIC").setMultipleInstances(!0)),(0,y.KO)(sX,sY,void 0),(0,y.KO)(sX,sY,"esm2020")}()},62e3:(e,t,r)=>{"use strict";r.r(t),r.d(t,{default:()=>m});var n=r(37876);r(51678),r(27402),r(98236),r(31620);var i=r(14232);let s=(0,i.createContext)(void 0);function a({children:e}){let[t,r]=(0,i.useState)("en");(0,i.useEffect)(()=>{let e=localStorage.getItem("app_lang");("th"===e||"en"===e)&&r(e)},[]);let o=e=>{r(e),localStorage.setItem("app_lang",e)},l=()=>{o("th"===t?"en":"th")},u=(0,i.useMemo)(()=>({lang:t,setLang:o,toggleLang:l}),[t]);return(0,n.jsx)(s.Provider,{value:u,children:e})}var o=r(39540),l=r(89099),u=r(50386);let{loginUrlForPath:h}=r(46074);function c({children:e}){let t=(0,l.useRouter)(),{authUser:r,user:s,loading:a,error:f}=(0,o.As)(),p="/login"===t.pathname||"/register"===t.pathname||t.pathname.startsWith("/liff/"),m="/stock"===t.pathname||(0,u.kL)(s,t.pathname);return((0,i.useEffect)(()=>{!a&&!p&&(r&&s&&"ACTIVE"===s.status||r&&f||t.replace(h(t.asPath)))},[r,s,f,a,p,t,t.asPath]),p)?(0,n.jsx)(n.Fragment,{children:e}):a?(0,n.jsx)("div",{style:{padding:24},children:"Loading..."}):f?(0,n.jsx)(d,{title:"Unable to verify access",detail:"Your account permissions could not be loaded. Please sign in again or contact an administrator."}):s&&"ACTIVE"===s.status?m?(0,n.jsx)(n.Fragment,{children:e}):(0,n.jsx)(d,{title:"403 \xb7 Access denied",detail:"Your account does not have permission to open this page."}):null}function d({title:e,detail:t}){return(0,n.jsx)("main",{style:{minHeight:"100vh",display:"grid",placeItems:"center",background:"#020617",color:"#e2e8f0",padding:24},children:(0,n.jsxs)("section",{style:{maxWidth:560,padding:32,border:"1px solid #1e293b",borderRadius:18,background:"#071326"},children:[(0,n.jsx)("h1",{style:{marginTop:0},children:e}),(0,n.jsx)("p",{style:{marginBottom:0,color:"#94a3b8"},children:t})]})})}class f extends i.Component{static getDerivedStateFromError(){return{failed:!0}}componentDidCatch(e,t){console.error(JSON.stringify({timestamp:new Date().toISOString(),event:"ui_error_boundary",outcome:"error",componentStackAvailable:!!t.componentStack}))}render(){return this.state.failed?(0,n.jsx)("main",{style:{minHeight:"100vh",display:"grid",placeItems:"center",padding:24,background:"#020617",color:"#e2e8f0"},children:(0,n.jsxs)("section",{style:{maxWidth:560},children:[(0,n.jsx)("h1",{children:"Something went wrong"}),(0,n.jsx)("p",{children:"The application could not continue safely. Refresh the page or contact an administrator."}),(0,n.jsx)("button",{type:"button",onClick:()=>window.location.reload(),children:"Reload"})]})}):this.props.children}constructor(...e){super(...e),this.state={failed:!1}}}var p=r(99742);function m({Component:e,pageProps:t}){let r="1"===p.env.NEXT_PUBLIC_LOCAL_TRAINING;return(0,n.jsx)(f,{children:(0,n.jsx)(o.OJ,{children:(0,n.jsxs)(a,{children:[r&&(0,n.jsx)("div",{role:"status",style:{position:"sticky",top:0,zIndex:1e4,padding:"8px 16px",background:"#7c2d12",color:"#fff7ed",fontWeight:800,textAlign:"center",letterSpacing:"0.04em"},children:"LOCAL TRAINING — NOT PRODUCTION"}),(0,n.jsx)(c,{children:(0,n.jsx)(e,{...t})})]})})})}},76653:(e,t,r)=>{"use strict";r.d(t,{cY:()=>g,FA:()=>R,g:()=>N,u:()=>h,Uj:()=>u,Fy:()=>y,tD:()=>U,bD:()=>function e(t,r){if(t===r)return!0;let n=Object.keys(t),i=Object.keys(r);for(let s of n){if(!i.includes(s))return!1;let n=t[s],a=r[s];if(P(n)&&P(a)){if(!e(n,a))return!1}else if(n!==a)return!1}for(let e of i)if(!n.includes(e))return!1;return!0},hp:()=>M,T9:()=>p,yU:()=>f,XA:()=>m,mS:()=>c,Ku:()=>j,ZQ:()=>v,sr:()=>I,zJ:()=>B,c1:()=>_,Im:()=>O,lT:()=>b,zW:()=>C,jZ:()=>w,lV:()=>T,nr:()=>S,Ov:()=>A,gE:()=>q,Am:()=>L,I9:()=>x,eX:()=>k}
7);var n=r(99742);let i=function(e){let t=[],r=0;for(let n=0;n<e.length;n++){let i=e.charCodeAt(n);i<128?t[r++]=i:(i<2048?t[r++]=i>>6|192:((64512&i)==55296&&n+1<e.length&&(64512&e.charCodeAt(n+1))==56320?(i=65536+((1023&i)<<10)+(1023&e.charCodeAt(++n)),t[r++]=i>>18|240,t[r++]=i>>12&63|128):t[r++]=i>>12|224,t[r++]=i>>6&63|128),t[r++]=63&i|128)}return t},s=function(e){let t=[],r=0,n=0;for(;r<e.length;){let i=e[r++];if(i<128)t[n++]=String.fromCharCode(i);else if(i>191&&i<224){let s=e[r++];t[n++]=String.fromCharCode((31&i)<<6|63&s)}else if(i>239&&i<365){let s=((7&i)<<18|(63&e[r++])<<12|(63&e[r++])<<6|63&e[r++])-65536;t[n++]=String.fromCharCode(55296+(s>>10)),t[n++]=String.fromCharCode(56320+(1023&s))}else{let s=e[r++],a=e[r++];t[n++]=String.fromCharCode((15&i)<<12|(63&s)<<6|63&a)}}return t.join("")},a={byteToCharMap_:null,charToByteMap_:null,byteToCharMapWebSafe_:null,charToByteMapWebSafe_:null,ENCODED_VALS_BASE:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",get ENCODED_VALS(){return this.ENCODED_VALS_BASE+"+/="},get ENCODED_VALS_WEBSAFE(){return this.ENCODED_VALS_BASE+"-_."},HAS_NATIVE_SUPPORT:"function"==typeof atob,encodeByteArray(e,t){if(!Array.isArray(e))throw Error("encodeByteArray takes an array as a parameter");this.init_();let r=t?this.byteToCharMapWebSafe_:this.byteToCharMap_,n=[];for(let t=0;t<e.length;t+=3){let i=e[t],s=t+1<e.length,a=s?e[t+1]:0,o=t+2<e.length,l=o?e[t+2]:0,u=i>>2,h=(3&i)<<4|a>>4,c=(15&a)<<2|l>>6,d=63&l;!o&&(d=64,s||(c=64)),n.push(r[u],r[h],r[c],r[d])}return n.join("")},encodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?btoa(e):this.encodeByteArray(i(e),t)},decodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?atob(e):s(this.decodeStringToByteArray(e,t))},decodeStringToByteArray(e,t){this.init_();let r=t?this.charToByteMapWebSafe_:this.charToByteMap_,n=[];for(let t=0;t<e.length;){let i=r[e.charAt(t++)],s=t<e.length?r[e.charAt(t)]:0,a=++t<e.length?r[e.charAt(t)]:64,l=++t<e.length?r[e.charAt(t)]:64;if(++t,null==i||null==s||null==a||null==l)throw new o;let u=i<<2|s>>4;if(n.push(u),64!==a){let e=s<<4&240|a>>2;if(n.push(e),64!==l){let e=a<<6&192|l;n.push(e)}}}return n},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 o extends Error{constructor(){super(...arguments),this.name="DecodeBase64StringError"}}let l=function(e){let t=i(e);return a.encodeByteArray(t,!0)},u=function(e){return l(e).replace(/\./g,"")},h=function(e){try{return a.decodeString(e,!0)}catch(e){console.error("base64Decode failed: ",e)}return null};function c(){if("u">typeof self)return self;if("u">typeof window)return window;if(void 0!==r.g)return r.g;throw Error("Unable to locate global object.")}let d=()=>{try{return c().__FIREBASE_DEFAULTS__||(()=>{if(void 0===n||void 0===n.env)return;let e=n.env.__FIREBASE_DEFAULTS__;if(e)return JSON.parse(e)})()||(()=>{let e;if("u"<typeof document)return;try{e=document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/)}catch(e){return}let t=e&&h(e[1]);return t&&JSON.parse(t)})()}catch(e){console.info(`Unable to get __FIREBASE_DEFAULTS__ due to: ${e}`);return}},f=e=>{let t=d()?.emulatorHosts?.[e];if(!t)return;let r=t.lastIndexOf(":");if(r<=0||r+1===t.length)throw Error(`Invalid host ${t} with no separate hostname and port!`);let n=parseInt(t.substring(r+1),10);return"["===t[0]?[t.substring(1,r-1),n]:[t.substring(0,r),n]},p=()=>d()?.config,m=e=>d()?.[`_${e}`];class g{constructor(){this.reject=()=>{},this.resolve=()=>{},this.promise=new Promise((e,t)=>{this.resolve=e,this.reject=t})}wrapCallback(e){return(t,r)=>{t?this.reject(t):this.resolve(r),"function"==typeof e&&(this.promise.catch(()=>{}),1===e.length?e(t):e(t,r))}}}function y(e,t){if(e.uid)throw Error('The "uid" field is no longer supported by mockUserToken. Please use "sub" instead for Firebase Auth User ID.');let r=t||"demo-project",n=e.iat||0,i=e.sub||e.user_id;if(!i)throw Error("mockUserToken must contain 'sub' or 'user_id' field!");let s={iss:`https://securetoken.google.com/${r}`,aud:r,iat:n,exp:n+3600,auth_time:n,sub:i,user_id:i,firebase:{sign_in_provider:"custom",identities:{}},...e};return[u(JSON.stringify({alg:"none",type:"JWT"})),u(JSON.stringify(s)),""].join(".")}function v(){return"u">typeof navigator&&"string"==typeof navigator.userAgent?navigator.userAgent:""}function w(){return"u">typeof window&&!!(window.cordova||window.phonegap||window.PhoneGap)&&/ios|iphone|ipod|ipad|android|blackberry|iemobile/i.test(v())}function E(){let e=d()?.forceEnvironment;if("node"===e)return!0;
7if("browser"===e)return!1;try{return"[object process]"===Object.prototype.toString.call(r.g.process)}catch(e){return!1}}function _(){return"u">typeof navigator&&"Cloudflare-Workers"===navigator.userAgent}function I(){let e="object"==typeof chrome?chrome.runtime:"object"==typeof browser?browser.runtime:void 0;return"object"==typeof e&&void 0!==e.id}function T(){return"object"==typeof navigator&&"ReactNative"===navigator.product}function b(){let e=v();return e.indexOf("MSIE ")>=0||e.indexOf("Trident/")>=0}function S(){return!E()&&!!navigator.userAgent&&navigator.userAgent.includes("Safari")&&!navigator.userAgent.includes("Chrome")}function A(){return!E()&&!!navigator.userAgent&&(navigator.userAgent.includes("Safari")||navigator.userAgent.includes("WebKit"))&&!navigator.userAgent.includes("Chrome")}function C(){try{return"object"==typeof indexedDB}catch(e){return!1}}function k(){return new Promise((e,t)=>{try{let r=!0,n="validate-browser-context-for-indexeddb-analytics-module",i=self.indexedDB.open(n);i.onsuccess=()=>{i.result.close(),r||self.indexedDB.deleteDatabase(n),e(!0)},i.onupgradeneeded=()=>{r=!1},i.onerror=()=>{t(i.error?.message||"")}}catch(e){t(e)}})}class N extends Error{constructor(e,t,r){super(t),this.code=e,this.customData=r,this.name="FirebaseError",Object.setPrototypeOf(this,N.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,R.prototype.create)}}class R{constructor(e,t,r){this.service=e,this.serviceName=t,this.errors=r}create(e,...t){var r,n;let i=t[0]||{},s=`${this.service}/${e}`,a=this.errors[e],o=a?(r=a,n=i,r.replace(D,(e,t)=>{let r=n[t];return null!=r?String(r):`<${t}?>`})):"Error",l=`${this.serviceName}: ${o} (${s}).`;return new N(s,l,i)}}let D=/\{\$([^}]+)}/g;function O(e){for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}function P(e){return null!==e&&"object"==typeof e}function L(e){let t=[];for(let[r,n]of Object.entries(e))Array.isArray(n)?n.forEach(e=>{t.push(encodeURIComponent(r)+"="+encodeURIComponent(e))}):t.push(encodeURIComponent(r)+"="+encodeURIComponent(n));return t.length?"&"+t.join("&"):""}function x(e){let t={};return e.replace(/^\?/,"").split("&").forEach(e=>{if(e){let[r,n]=e.split("=");
7t[decodeURIComponent(r)]=decodeURIComponent(n)}}),t}function M(e){let t=e.indexOf("?");if(!t)return"";let r=e.indexOf("#",t);return e.substring(t,r>0?r:void 0)}function U(e,t){let r=new V(e,t);return r.subscribe.bind(r)}class V{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,r){let n;if(void 0===e&&void 0===t&&void 0===r)throw Error("Missing Observer.");void 0===(n=!function(e,t){if("object"!=typeof e||null===e)return!1;for(let r of t)if(r in e&&"function"==typeof e[r])return!0;return!1}(e,["next","error","complete"])?{next:e,error:t,complete:r}:e).next&&(n.next=F),void 0===n.error&&(n.error=F),void 0===n.complete&&(n.complete=F);let i=this.unsubscribeOne.bind(this,this.observers.length);return this.finalized&&this.task.then(()=>{try{this.finalError?n.error(this.finalError):n.complete()}catch(e){}}),this.observers.push(n),i}unsubscribeOne(e){void 0!==this.observers&&void 0!==this.observers[e]&&(delete this.observers[e],this.observerCount-=1,0===this.observerCount&&void 0!==this.onNoObservers&&this.onNoObservers(this))}forEachObserver(e){if(!this.finalized)for(let t=0;t<this.observers.length;t++)this.sendOne(t,e)}sendOne(e,t){this.task.then(()=>{if(void 0!==this.observers&&void 0!==this.observers[e])try{t(this.observers[e])}catch(e){"u">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 F(){}function j(e){return e&&e._delegate?e._delegate:e}function B(e){try{return(e.startsWith("http://")||e.startsWith("https://")?new URL(e).hostname:e).endsWith(".cloudworkstations.dev")}catch{return!1}}async function q(e){return(await fetch(e,{credentials:"include"})).ok}},81370:(e,t)=>{"use strict";t.byteLength=function(e){var t=l(e),r=t[0],n=t[1];return(r+n)*3/4-n},t.toByteArray=function(e){var t,r,s=l(e),a=s[0],o=s[1],u=new i((a+o)*3/4-o),h=0,c=o>0?a-4:a;for(r=0;r<c;r+=4)t=n[e.charCodeAt(r)]<<18|n[e.charCodeAt(r+1)]<<12|n[e.charCodeAt(r+2)]<<6|n[e.charCodeAt(r+3)],u[h++]=t>>16&255,u[h++]=t>>8&255,u[h++]=255&t;return 2===o&&(t=n[e.charCodeAt(r)]<<2|n[e.charCodeAt(r+1)]>>4,u[h++]=255&t),1===o&&(t=n[e.charCodeAt(r)]<<10|n[e.charCodeAt(r+1)]<<4|n[e.charCodeAt(r+2)]>>2,u[h++]=t>>8&255,u[h++]=255&t),u},t.fromByteArray=function(e){for(var t,n=e.length,i=n%3,s=[],a=0,o=n-i;a<o;a+=16383)s.push(function(e,t,n){for(var i,s=[],a=t;a<n;a+=3)i=(e[a]<<16&0xff0000)+(e[a+1]<<8&65280)+(255&e[a+2]),s.push(r[i>>18&63]+r[i>>12&63]+r[i>>6&63]+r[63&i]);return s.join("")}(e,a,a+16383>o?o:a+16383));return 1===i?s.push(r[(t=e[n-1])>>2]+r[t<<4&63]+"=="):2===i&&s.push(r[(t=(e[n-2]<<8)+e[n-1])>>10]+r[t>>4&63]+r[t<<2&63]+"="),s.join("")};for(var r=[],n=[],i="u">typeof Uint8Array?Uint8Array:Array,s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",a=0,o=s.length;a<o;++a)r[a]=s[a],n[s.charCodeAt(a)]=a;function l(e){var t=e.length;if(t%4>0)throw Error("Invalid string. Length must be a multiple of 4");var r=e.indexOf("=");-1===r&&(r=t);var n=r===t?0:4-r%4;return[r,n]}n[45]=62,n[95]=63},82909:(e,t,r)=>{"use strict";var n=r(81370),i=r(87247),s="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;function a(e){if(e>0x7fffffff)throw RangeError('The value "'+e+'" is invalid for option "size"');var t=new Uint8Array(e);return Object.setPrototypeOf(t,o.prototype),t}function o(e,t,r){if("number"==typeof e){if("string"==typeof t)throw TypeError('The "string" argument must be of type string. Received type number');return h(e)}return l(e,t,r)}function l(e,t,r){if("string"==typeof e){var n=e,i=t;if(("string"!=typeof i||""===i)&&(i="utf8"),!o.isEncoding(i))throw TypeError("Unknown encoding: "+i);var s=0|p(n,i),l=a(s),u=l.write(n,i);return u!==s&&(l=l.slice(0,u)),l}if(ArrayBuffer.isView(e)){var h=e;if(N(h,Uint8Array)){var m=new Uint8Array(h);return d(m.buffer,m.byteOffset,m.byteLength)}return c(h)}if(null==e)throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);if(N(e,ArrayBuffer)||e&&N(e.buffer,ArrayBuffer)||"u">typeof SharedArrayBuffer&&(N(e,SharedArrayBuffer)||e&&N(e.buffer,SharedArrayBuffer)))return d(e,t,r);if("number"==typeof e)throw TypeError('The "value" argument must not be of type number. Received type number');var g=e.valueOf&&e.valueOf();if(null!=g&&g!==e)return o.from(g,t,r);var y=function(e){if(o.isBuffer(e)){var t=0|f(e.length),r=a(t);return 0===r.length||e.copy(r,0,0,t),r}return void 0!==e.length?"number"!=typeof e.length||function(e){return e!=e}(e.length)?a(0):c(e):"Buffer"===e.type&&Array.isArray(e.data)?c(e.data):void 0}(e);if(y)return y;if("u">typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof e[Symbol.toPrimitive])return o.from(e[Symbol.toPrimitive]("string"),t,r);throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e)}function u(e){if("number"!=typeof e)throw TypeError('"size" argument must be of type number');
vendor: 17,085 bytes, line 7
7if(e<0)throw RangeError('The value "'+e+'" is invalid for option "size"')}function h(e){return u(e),a(e<0?0:0|f(e))}function c(e){for(var t=e.length<0?0:0|f(e.length),r=a(t),n=0;n<t;n+=1)r[n]=255&e[n];return r}function d(e,t,r){var n;if(t<0||e.byteLength<t)throw RangeError('"offset" is outside of buffer bounds');if(e.byteLength<t+(r||0))throw RangeError('"length" is outside of buffer bounds');return Object.setPrototypeOf(n=void 0===t&&void 0===r?new Uint8Array(e):void 0===r?new Uint8Array(e,t):new Uint8Array(e,t,r),o.prototype),n}function f(e){if(e>=0x7fffffff)throw RangeError("Attempt to allocate Buffer larger than maximum size: 0x7fffffff bytes");return 0|e}function p(e,t){if(o.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||N(e,ArrayBuffer))return e.byteLength;if("string"!=typeof e)throw TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof e);var r=e.length,n=arguments.length>2&&!0===arguments[2];if(!n&&0===r)return 0;for(var i=!1;;)switch(t){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":return A(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return C(e).length;default:if(i)return n?-1:A(e).length;t=(""+t).toLowerCase(),i=!0}}function m(e,t,r){var i,s,a,o=!1;if((void 0===t||t<0)&&(t=0),t>this.length||((void 0===r||r>this.length)&&(r=this.length),r<=0||(r>>>=0)<=(t>>>=0)))return"";for(e||(e="utf8");;)switch(e){case"hex":return function(e,t,r){var n=e.length;(!t||t<0)&&(t=0),(!r||r<0||r>n)&&(r=n);for(var i="",s=t;s<r;++s)i+=R[e[s]];return i}(this,t,r);case"utf8":case"utf-8":return w(this,t,r);case"ascii":return function(e,t,r){var n="";r=Math.min(e.length,r);for(var i=t;i<r;++i)n+=String.fromCharCode(127&e[i]);return n}(this,t,r);case"latin1":case"binary":return function(e,t,r){var n="";r=Math.min(e.length,r);for(var i=t;i<r;++i)n+=String.fromCharCode(e[i]);return n}(this,t,r);case"base64":return i=this,s=t,a=r,0===s&&a===i.length?n.fromByteArray(i):n.fromByteArray(i.slice(s,a));case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return function(e,t,r){for(var n=e.slice(t,r),i="",s=0;s<n.length-1;s+=2)i+=String.fromCharCode(n[s]+256*n[s+1]);return i}(this,t,r);default:if(o)throw TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),o=!0}}function g(e,t,r){var n=e[t];e[t]=e[r],e[r]=n}function y(e,t,r,n,i){var s;if(0===e.length)return -1;if("string"==typeof r?(n=r,r=0):r>0x7fffffff?r=0x7fffffff:r<-0x80000000&&(r=-0x80000000),(s=r*=1)!=s&&(r=i?0:e.length-1),r<0&&(r=e.length+r),r>=e.length)if(i)return -1;else r=e.length-1;else if(r<0)if(!i)return -1;else r=0;if("string"==typeof t&&(t=o.from(t,n)),o.isBuffer(t))return 0===t.length?-1:v(e,t,r,n,i);if("number"==typeof t){if(t&=255,"function"==typeof Uint8Array.prototype.indexOf)if(i)return Uint8Array.prototype.indexOf.call(e,t,r);else return Uint8Array.prototype.lastIndexOf.call(e,t,r);return v(e,[t],r,n,i)}throw TypeError("val must be string, number or Buffer")}function v(e,t,r,n,i){var s,a=1,o=e.length,l=t.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(e.length<2||t.length<2)return -1;a=2,o/=2,l/=2,r/=2}function u(e,t){return 1===a?e[t]:e.readUInt16BE(t*a)}if(i){var h=-1;for(s=r;s<o;s++)if(u(e,s)===u(t,-1===h?0:s-h)){if(-1===h&&(h=s),s-h+1===l)return h*a}else -1!==h&&(s-=s-h),h=-1}else for(r+l>o&&(r=o-l),s=r;s>=0;s--){for(var c=!0,d=0;d<l;d++)if(u(e,s+d)!==u(t,d)){c=!1;break}if(c)return s}return -1}function w(e,t,r){r=Math.min(e.length,r);for(var n=[],i=t;i<r;){var s,a,o,l,u=e[i],h=null,c=u>239?4:u>223?3:u>191?2:1;if(i+c<=r)switch(c){case 1:u<128&&(h=u);break;case 2:(192&(s=e[i+1]))==128&&(l=(31&u)<<6|63&s)>127&&(h=l);break;case 3:s=e[i+1],a=e[i+2],(192&s)==128&&(192&a)==128&&(l=(15&u)<<12|(63&s)<<6|63&a)>2047&&(l<55296||l>57343)&&(h=l);break;case 4:s=e[i+1],a=e[i+2],o=e[i+3],(192&s)==128&&(192&a)==128&&(192&o)==128&&(l=(15&u)<<18|(63&s)<<12|(63&a)<<6|63&o)>65535&&l<1114112&&(h=l)}null===h?(h=65533,c=1):h>65535&&(h-=65536,n.push(h>>>10&1023|55296),h=56320|1023&h),n.push(h),i+=c}var d=n,f=d.length;if(f<=4096)return String.fromCharCode.apply(String,d);for(var p="",m=0;m<f;)p+=String.fromCharCode.apply(String,d.slice(m,m+=4096));return p}function E(e,t,r){if(e%1!=0||e<0)throw RangeError("offset is not uint");if(e+t>r)throw RangeError("Trying to access beyond buffer length")}function _(e,t,r,n,i,s){if(!o.isBuffer(e))throw TypeError('"buffer" argument must be a Buffer instance');if(t>i||t<s)throw RangeError('"value" argument is out of bounds');if(r+n>e.length)throw RangeError("Index out of range")}function I(e,t,r,n,i,s){if(r+n>e.length||r<0)throw RangeError("Index out of range")}function T(e,t,r,n,s){return t*=1,r>>>=0,s||I(e,t,r,4,34028234663852886e22,-34028234663852886e22),i.write(e,t,r,n,23,4),r+4}function b(e,t,r,n,s){return t*=1,r>>>=0,s||I(e,t,r,8,17976931348623157e292,-17976931348623157e292),i.write(e,t,r,n,52,8),r+8}t.hp=o,t.IS=50,o.TYPED_ARRAY_SUPPORT=function(){try{var e=new Uint8Array(1),t={foo:function(){return 42}};return Object.setPrototypeOf(t,Uint8Array.prototype),Object.setPrototypeOf(e,t),42===e.foo()}catch(e){return!1}}(),!o.TYPED_ARRAY_SUPPORT&&"u">typeof console&&"function"==typeof console.error&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support."),Object.defineProperty(o.prototype,"parent",{enumerable:!0,get:function(){if(o.isBuffer(this))return this.buffer}}),Object.defineProperty(o.prototype,"offset",{enumerable:!0,get:function(){if(o.isBuffer(this))return this.byteOffset}}),o.poolSize=8192,o.from=function(e,t,r){return l(e,t,r)},Object.setPrototypeOf(o.prototype,Uint8Array.prototype),Object.setPrototypeOf(o,Uint8Array),o.alloc=function(e,t,r){return(u(e),e<=0)?a(e):void 0!==t?"string"==typeof r?a(e).fill(t,r):a(e).fill(t):a(e)},o.allocUnsafe=function(e){return h(e)},o.allocUnsafeSlow=function(e){return h(e)},o.isBuffer=function(e){return null!=e&&!0===e._isBuffer&&e!==o.prototype},o.compare=function(e,t){if(N(e,Uint8Array)&&(e=o.from(e,e.offset,e.byteLength)),N(t,Uint8Array)&&(t=o.from(t,t.offset,t.byteLength)),!o.isBuffer(e)||!o.isBuffer(t))throw TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(e===t)return 0;for(var r=e.length,n=t.length,i=0,s=Math.min(r,n);i<s;++i)if(e[i]!==t[i]){r=e[i],n=t[i];break}return r<n?-1:+(n<r)},o.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},o.concat=function(e,t){if(!Array.isArray(e))throw TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return o.alloc(0);if(void 0===t)for(r=0,t=0;r<e.length;++r)t+=e[r].length;var r,n=o.allocUnsafe(t),i=0;for(r=0;r<e.length;++r){var s=e[r];if(N(s,Uint8Array))i+s.length>n.length?o.from(s).copy(n,i):Uint8Array.prototype.set.call(n,s,i);else if(o.isBuffer(s))s.copy(n,i);else throw TypeError('"list" argument must be an Array of Buffers');i+=s.length}return n},o.byteLength=p,o.prototype._isBuffer=!0,o.prototype.swap16=function(){var e=this.length;if(e%2!=0)throw RangeError("Buffer size must be a multiple of 16-bits");for(var t=0;t<e;t+=2)g(this,t,t+1);return this},o.prototype.swap32=function(){var e=this.length;if(e%4!=0)throw RangeError("Buffer size must be a multiple of 32-bits");for(var t=0;t<e;t+=4)g(this,t,t+3),g(this,t+1,t+2);return this},o.prototype.swap64=function(){var e=this.length;if(e%8!=0)throw RangeError("Buffer size must be a multiple of 64-bits");for(var t=0;t<e;t+=8)g(this,t,t+7),g(this,t+1,t+6),g(this,t+2,t+5),g(this,t+3,t+4);return this},o.prototype.toString=function(){var e=this.length;return 0===e?"":0==arguments.length?w(this,0,e):m.apply(this,arguments)},o.prototype.toLocaleString=o.prototype.toString,o.prototype.equals=function(e){if(!o.isBuffer(e))throw TypeError("Argument must be a Buffer");return this===e||0===o.compare(this,e)},o.prototype.inspect=function(){var e="",r=t.IS;return e=this.toString("hex",0,r).replace(/(.{2})/g,"$1 ").trim(),this.length>r&&(e+=" ... "),"<Buffer "+e+">"},s&&(o.prototype[s]=o.prototype.inspect),o.prototype.compare=function(e,t,r,n,i){if(N(e,Uint8Array)&&(e=o.from(e,e.offset,e.byteLength)),!o.isBuffer(e))throw TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(void 0===t&&(t=0),void 0===r&&(r=e?e.length:0),void 0===n&&(n=0),void 0===i&&(i=this.length),t<0||r>e.length||n<0||i>this.length)throw RangeError("out of range index");if(n>=i&&t>=r)return 0;if(n>=i)return -1;if(t>=r)return 1;if(t>>>=0,r>>>=0,n>>>=0,i>>>=0,this===e)return 0;for(var s=i-n,a=r-t,l=Math.min(s,a),u=this.slice(n,i),h=e.slice(t,r),c=0;c<l;++c)if(u[c]!==h[c]){s=u[c],a=h[c];break}return s<a?-1:+(a<s)},o.prototype.includes=function(e,t,r){return -1!==this.indexOf(e,t,r)},o.prototype.indexOf=function(e,t,r){return y(this,e,t,r,!0)},o.prototype.lastIndexOf=function(e,t,r){return y(this,e,t,r,!1)},o.prototype.write=function(e,t,r,n){if(void 0===t)n="utf8",r=this.length,t=0;else if(void 0===r&&"string"==typeof t)n=t,r=this.length,t=0;else if(isFinite(t))t>>>=0,isFinite(r)?(r>>>=0,void 0===n&&(n="utf8")):(n=r,r=void 0);else throw Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");var i,s,a,o,l,u,h,c,d=this.length-t;if((void 0===r||r>d)&&(r=d),e.length>0&&(r<0||t<0)||t>this.length)throw RangeError("Attempt to write outside buffer bounds");n||(n="utf8");for(var f=!1;;)switch(n){case"hex":return function(e,t,r,n){r=Number(r)||0;var i=e.length-r;n?(n=Number(n))>i&&(n=i):n=i;var s=t.length;n>s/2&&(n=s/2);for(var a=0;a<n;++a){var o,l=parseInt(t.substr(2*a,2),16);if((o=l)!=o)break;e[r+a]=l}return a}(this,e,t,r);case"utf8":case"utf-8":return i=t,s=r,k(A(e,this.length-i),this,i,s);case"ascii":case"latin1":case"binary":return a=t,o=r,k(function(e){for(var t=[],r=0;r<e.length;++r)t.push(255&e.charCodeAt(r));return t}(e),this,a,o);case"base64":return l=t,u=r,k(C(e),this,l,u);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return h=t,c=r,k(function(e,t){for(var r,n,i=[],s=0;s<e.length&&!((t-=2)<0);++s)n=(r=e.charCodeAt(s))>>8,i.push(r%256),i.push(n);return i}(e,this.length-h),this,h,c);default:if(f)throw TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),f=!0}},o.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}},o.prototype.slice=function(e,t){var r=this.length;e=~~e,t=void 0===t?r:~~t,e<0?(e+=r)<0&&(e=0):e>r&&(e=r),t<0?(t+=r)<0&&(t=0):t>r&&(t=r),t<e&&(t=e);var n=this.subarray(e,t);return Object.setPrototypeOf(n,o.prototype),n},o.prototype.readUintLE=o.prototype.readUIntLE=function(e,t,r){e>>>=0,t>>>=0,r||E(e,t,this.length);for(var n=this[e],i=1,s=0;++s<t&&(i*=256);)n+=this[e+s]*i;return n},o.prototype.readUintBE=o.prototype.readUIntBE=function(e,t,r){e>>>=0,t>>>=0,r||E(e,t,this.length);for(var n=this[e+--t],i=1;t>0&&(i*=256);)n+=this[e+--t]*i;return n},o.prototype.readUint8=o.prototype.readUInt8=function(e,t){return e>>>=0,t||E(e,1,this.length),this[e]},o.prototype.readUint16LE=o.prototype.readUInt16LE=function(e,t){return e>>>=0,t||E(e,2,this.length),this[e]|this[e+1]<<8},o.prototype.readUint16BE=o.prototype.readUInt16BE=function(e,t){return e>>>=0,t||E(e,2,this.length),this[e]<<8|this[e+1]},o.prototype.readUint32LE=o.prototype.readUInt32LE=function(e,t){return e>>>=0,t||E(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+0x1000000*this[e+3]},o.prototype.readUint32BE=o.prototype.readUInt32BE=function(e,t){return e>>>=0,t||E(e,4,this.length),0x1000000*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},o.prototype.readIntLE=function(e,t,r){e>>>=0,t>>>=0,r||E(e,t,this.length);for(var n=this[e],i=1,s=0;++s<t&&(i*=256);)n+=this[e+s]*i;return n>=(i*=128)&&(n-=Math.pow(2,8*t)),n},o.prototype.readIntBE=function(e,t,r){e>>>=0,t>>>=0,r||E(e,t,this.length);for(var n=t,i=1,s=this[e+--n];n>0&&(i*=256);)s+=this[e+--n]*i;return s>=(i*=128)&&(s-=Math.pow(2,8*t)),s},o.prototype.readInt8=function(e,t){return(e>>>=0,t||E(e,1,this.length),128&this[e])?-((255-this[e]+1)*1):this[e]},o.prototype.readInt16LE=function(e,t){e>>>=0,t||E(e,2,this.length);var r=this[e]|this[e+1]<<8;return 32768&r?0xffff0000|r:r},o.prototype.readInt16BE=function(e,t){e>>>=0,t||E(e,2,this.length);var r=this[e+1]|this[e]<<8;return 32768&r?0xffff0000|r:r},o.prototype.readInt32LE=function(e,t){return e>>>=0,t||E(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},o.prototype.readInt32BE=function(e,t){return e>>>=0,t||E(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},o.prototype.readFloatLE=function(e,t){return e>>>=0,t||E(e,4,this.length),i.read(this,e,!0,23,4)},o.prototype.readFloatBE=function(e,t){return e>>>=0,t||E(e,4,this.length),i.read(this,e,!1,23,4)},o.prototype.readDoubleLE=function(e,t){return e>>>=0,t||E(e,8,this.length),i.read(this,e,!0,52,8)},o.prototype.readDoubleBE=function(e,t){return e>>>=0,t||E(e,8,this.length),i.read(this,e,!1,52,8)},o.prototype.writeUintLE=o.prototype.writeUIntLE=function(e,t,r,n){if(e*=1,t>>>=0,r>>>=0,!n){var i=Math.pow(2,8*r)-1;_(this,e,t,r,i,0)}var s=1,a=0;for(this[t]=255&e;++a<r&&(s*=256);)this[t+a]=e/s&255;return t+r},o.prototype.writeUintBE=o.prototype.writeUIntBE=function(e,t,r,n){if(e*=1,t>>>=0,r>>>=0,!n){var i=Math.pow(2,8*r)-1;_(this,e,t,r,i,0)}var s=r-1,a=1;for(this[t+s]=255&e;--s>=0&&(a*=256);)this[t+s]=e/a&255;return t+r},o.prototype.writeUint8=o.prototype.writeUInt8=function(e,t,r){return e*=1,t>>>=0,r||_(this,e,t,1,255,0),this[t]=255&e,t+1},o.prototype.writeUint16LE=o.prototype.writeUInt16LE=function(e,t,r){return e*=1,t>>>=0,r||_(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},o.prototype.writeUint16BE=o.prototype.writeUInt16BE=function(e,t,r){return e*=1,t>>>=0,r||_(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},o.prototype.writeUint32LE=o.prototype.writeUInt32LE=function(e,t,r){return e*=1,t>>>=0,r||_(this,e,t,4,0xffffffff,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},o.prototype.writeUint32BE=o.prototype.writeUInt32BE=function(e,t,r){return e*=1,t>>>=0,r||_(this,e,t,4,0xffffffff,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},o.prototype.writeIntLE=function(e,t,r,n){if(e*=1,t>>>=0,!n){var i=Math.pow(2,8*r-1);_(this,e,t,r,i-1,-i)}var s=0,a=1,o=0;for(this[t]=255&e;++s<r&&(a*=256);)e<0&&0===o&&0!==this[t+s-1]&&(o=1),this[t+s]=(e/a|0)-o&255;return t+r},o.prototype.writeIntBE=function(e,t,r,n){if(e*=1,t>>>=0,!n){var i=Math.pow(2,8*r-1);_(this,e,t,r,i-1,-i)}var s=r-1,a=1,o=0;for(this[t+s]=255&e;--s>=0&&(a*=256);)e<0&&0===o&&0!==this[t+s+1]&&(o=1),this[t+s]=(e/a|0)-o&255;return t+r},o.prototype.writeInt8=function(e,t,r){return e*=1,t>>>=0,r||_(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},o.prototype.writeInt16LE=function(e,t,r){return e*=1,t>>>=0,r||_(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},o.prototype.writeInt16BE=function(e,t,r){return e*=1,t>>>=0,r||_(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},o.prototype.writeInt32LE=function(e,t,r){return e*=1,t>>>=0,r||_(this,e,t,4,0x7fffffff,-0x80000000),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},o.prototype.writeInt32BE=function(e,t,r){return e*=1,t>>>=0,r||_(this,e,t,4,0x7fffffff,-0x80000000),e<0&&(e=0xffffffff+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},o.prototype.writeFloatLE=function(e,t,r){return T(this,e,t,!0,r)},o.prototype.writeFloatBE=function(e,t,r){return T(this,e,t,!1,r)},o.prototype.writeDoubleLE=function(e,t,r){return b(this,e,t,!0,r)},o.prototype.writeDoubleBE=function(e,t,r){return b(this,e,t,!1,r)},o.prototype.copy=function(e,t,r,n){if(!o.isBuffer(e))throw TypeError("argument should be a Buffer");if(r||(r=0),n||0===n||(n=this.length),t>=e.length&&(t=e.length),t||(t=0),n>0&&n<r&&(n=r),n===r||0===e.length||0===this.length)return 0;if(t<0)throw RangeError("targetStart out of bounds");if(r<0||r>=this.length)throw RangeError("Index out of range");if(n<0)throw RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),e.length-t<n-r&&(n=e.length-t+r);var i=n-r;return this===e&&"function"==typeof Uint8Array.prototype.copyWithin?this.copyWithin(t,r,n):Uint8Array.prototype.set.call(e,this.subarray(r,n),t),i},o.prototype.fill=function(e,t,r,n){if("string"==typeof e){if("string"==typeof t?(n=t,t=0,r=this.length):"string"==typeof r&&(n=r,r=this.length),void 0!==n&&"string"!=typeof n)throw TypeError("encoding must be a string");if("string"==typeof n&&!o.isEncoding(n))throw TypeError("Unknown encoding: "+n);if(1===e.length){var i,s=e.charCodeAt(0);("utf8"===n&&s<128||"latin1"===n)&&(e=s)}}else"number"==typeof e?e&=255:"boolean"==typeof e&&(e=Number(e));if(t<0||this.length<t||this.length<r)throw RangeError("Out of range index");if(r<=t)return this;if(t>>>=0,r=void 0===r?this.length:r>>>0,e||(e=0),"number"==typeof e)for(i=t;i<r;++i)this[i]=e;else{var a=o.isBuffer(e)?e:o.from(e,n),l=a.length;
7if(0===l)throw TypeError('The value "'+e+'" is invalid for argument "value"');for(i=0;i<r-t;++i)this[i+t]=a[i%l]}return this};var S=/[^+/0-9A-Za-z-_]/g;function A(e,t){t=t||1/0;for(var r,n=e.length,i=null,s=[],a=0;a<n;++a){if((r=e.charCodeAt(a))>55295&&r<57344){if(!i){if(r>56319||a+1===n){(t-=3)>-1&&s.push(239,191,189);continue}i=r;continue}if(r<56320){(t-=3)>-1&&s.push(239,191,189),i=r;continue}r=(i-55296<<10|r-56320)+65536}else i&&(t-=3)>-1&&s.push(239,191,189);if(i=null,r<128){if((t-=1)<0)break;s.push(r)}else if(r<2048){if((t-=2)<0)break;s.push(r>>6|192,63&r|128)}else if(r<65536){if((t-=3)<0)break;s.push(r>>12|224,r>>6&63|128,63&r|128)}else if(r<1114112){if((t-=4)<0)break;s.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}else throw Error("Invalid code point")}return s}function C(e){return n.toByteArray(function(e){if((e=(e=e.split("=")[0]).trim().replace(S,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function k(e,t,r,n){for(var i=0;i<n&&!(i+r>=t.length)&&!(i>=e.length);++i)t[i+r]=e[i];return i}function N(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}var R=function(){for(var e="0123456789abcdef",t=Array(256),r=0;r<16;++r)for(var n=16*r,i=0;i<16;++i)t[n+i]=e[r]+e[i];return t}()},84317:(e,t,r)=>{"use strict";r.d(t,{db:()=>p,h:()=>m,j:()=>f});var n=r(16042),i=r(88036),s=r(55656),a=r(99742);let o={apiKey:a.env.NEXT_PUBLIC_FIREBASE_API_KEY||"AIzaSyD46VEQDwsy4acQG1gwfNjNQwW4wIyUuUg",authDomain:a.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN||"jdp-rental-system.firebaseapp.com",projectId:a.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID||"jdp-rental-system",storageBucket:a.env.NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET||"jdp-rental-system.firebasestorage.app",messagingSenderId:a.env.NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID||"685263158404",appId:a.env.NEXT_PUBLIC_FIREBASE_APP_ID||"1:685263158404:web:87751aa9ac6860fab716d1"},l="1"===a.env.NEXT_PUBLIC_FIREBASE_EMULATORS,u="1"===a.env.NEXT_PUBLIC_CUSTOMER_ASSET_UAT,h="1"===a.env.NEXT_PUBLIC_LOCAL_TRAINING;if(u){if(!l)throw Error("customer-asset-uat/emulators-required");if("demo-bes-customer-assets-uat"!==o.projectId)throw Error("customer-asset-uat/demo-project-required");if("http://127.0.0.1:9199"!==a.env.NEXT_PUBLIC_FIREBASE_AUTH_EMULATOR_URL)throw Error("customer-asset-uat/auth-emulator-required");if("127.0.0.1"!==a.env.NEXT_PUBLIC_FIRESTORE_EMULATOR_HOST||"8180"!==a.env.NEXT_PUBLIC_FIRESTORE_EMULATOR_PORT)throw Error("customer-asset-uat/firestore-emulator-required")}if(h){if(!l)throw Error("local-training/emulators-required");if("demo-bes-local-training"!==o.projectId)throw Error("local-training/demo-project-required");if("http://127.0.0.1:9299"!==a.env.NEXT_PUBLIC_FIREBASE_AUTH_EMULATOR_URL)throw Error("local-training/auth-emulator-required");if("127.0.0.1"!==a.env.NEXT_PUBLIC_FIRESTORE_EMULATOR_HOST||"8280"!==a.env.NEXT_PUBLIC_FIRESTORE_EMULATOR_PORT)throw Error("local-training/firestore-emulator-required")}let c="bes-os",d=(0,n.Dk)().some(e=>e.name===c)?(0,n.Sx)(c):(0,n.Wp)(o,c),f=(0,i.Nu)(d,{persistence:[i.Gt,i.F0,i.iM]}),p=(0,s.aU)(d);if(l){if(!(a.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID||"").startsWith("demo-"))throw Error("firebase/emulator-demo-project-required");let e=globalThis;e.__besFirebaseEmulatorsConnected||((0,i.Wq)(f,a.env.NEXT_PUBLIC_FIREBASE_AUTH_EMULATOR_URL||"http://127.0.0.1:9099",{disableWarnings:!0}),(0,s.vN)(p,a.env.NEXT_PUBLIC_FIRESTORE_EMULATOR_HOST||"127.0.0.1",Number(a.env.NEXT_PUBLIC_FIRESTORE_EMULATOR_PORT||8080)),e.__besFirebaseEmulatorsConnected=!0)}let m=new i.HF;m.setCustomParameters({prompt:"select_account"})},87247:(e,t)=>{t.read=function(e,t,r,n,i){var s,a,o=8*i-n-1,l=(1<<o)-1,u=l>>1,h=-7,c=r?i-1:0,d=r?-1:1,f=e[t+c];for(c+=d,s=f&(1<<-h)-1,f>>=-h,h+=o;h>0;s=256*s+e[t+c],c+=d,h-=8);for(a=s&(1<<-h)-1,s>>=-h,h+=n;h>0;a=256*a+e[t+c],c+=d,h-=8);if(0===s)s=1-u;else{if(s===l)return a?NaN:1/0*(f?-1:1);a+=Math.pow(2,n),s-=u}return(f?-1:1)*a*Math.pow(2,s-n)},t.write=function(e,t,r,n,i,s){var a,o,l,u=8*s-i-1,h=(1<<u)-1,c=h>>1,d=5960464477539062e-23*(23===i),f=n?0:s-1,p=n?1:-1,m=+(t<0||0===t&&1/t<0);for(isNaN(t=Math.abs(t))||t===1/0?(o=+!!isNaN(t),a=h):(a=Math.floor(Math.log(t)/Math.LN2),t*(l=Math.pow(2,-a))<1&&(a--,l*=2),a+c>=1?t+=d/l:t+=d*Math.pow(2,1-c),t*l>=2&&(a++,l/=2),a+c>=h?(o=0,a=h):a+c>=1?(o=(t*l-1)*Math.pow(2,i),a+=c):(o=t*Math.pow(2,c-1)*Math.pow(2,i),a=0));i>=8;e[r+f]=255&o,f+=p,o/=256,i-=8);for(a=a<<i|o,u+=i;u>0;e[r+f]=255&a,f+=p,a/=256,u-=8);e[r+f-p]|=128*m}},88036:(e,t,r)=>{"use strict";r.d(t,{IX:()=>e1,HF:()=>e5,F0:()=>tS,hk:()=>rT,iM:()=>tR,Wq:()=>eP,eJ:()=>tc,hG:()=>tE,Gt:()=>tG,Nu:()=>eO,hg:()=>tv,kZ:()=>to,gA:()=>tf,J1:()=>th,x9:()=>td,df:()=>t8,CI:()=>tw,f3:()=>tg,r7:()=>tm});var n,i=r(36672),s=r(76653),a=r(29979),o=r(21610);function l(){return{"dependent-sdk-initialized-before-auth":"Another Firebase SDK was initialized and is trying to use Auth before Auth is initialized. Please be sure to call `initializeAuth` or `getAuth` before starting any other Firebase SDK."}}let u=new s.FA("auth","Firebase",l()),h=new a.Vy("@firebase/auth");function c(e,...t){h.logLevel<=a.$b.ERROR&&h.error(`Auth (${i.MF}): ${e}`,...t)}function d(e,...t){throw g(e,...t)}function f(e,...t){return g(e,...t)}function p(e,t,r){let n={...l(),[t]:r};
7return new s.FA("auth","Firebase",n).create(t,{appName:e.name})}function m(e){return p(e,"operation-not-supported-in-this-environment","Operations that alter the current user are not supported in conjunction with FirebaseServerApp")}function g(e,...t){if("string"!=typeof e){let r=t[0],n=[...t.slice(1)];return n[0]&&(n[0].appName=e.name),e._errorFactory.create(r,...n)}return u.create(e,...t)}function y(e,t,...r){if(!e)throw g(t,...r)}function v(e){let t="INTERNAL ASSERTION FAILED: "+e;throw c(t),Error(t)}function w(){return"u">typeof self&&self.location?.href||""}function E(){return"u">typeof self&&self.location?.protocol||null}class _{constructor(e,t){this.shortDelay=e,this.longDelay=t,function(e,t){e||v(t)}(t>e,"Short delay should be less than long delay!"),this.isMobile=(0,s.jZ)()||(0,s.lV)()}get(){return!("u">typeof navigator&&navigator&&"onLine"in navigator&&"boolean"==typeof navigator.onLine&&("http:"===E()||"https:"===E()||(0,s.sr)()||"connection"in navigator))||navigator.onLine?this.isMobile?this.longDelay:this.shortDelay:Math.min(5e3,this.shortDelay)}}function I(e,t){var r,n;r=e.emulator,n="Emulator should always be set here",r||v(n);let{url:i}=e.emulator;return t?`${i}${t.startsWith("/")?t.slice(1):t}`:i}class T{static initialize(e,t,r){this.fetchImpl=e,t&&(this.headersImpl=t),r&&(this.responseImpl=r)}static fetch(){return this.fetchImpl?this.fetchImpl:"u">typeof self&&"fetch"in self?self.fetch:"u">typeof globalThis&&globalThis.fetch?globalThis.fetch:"u">typeof fetch?fetch:void v("Could not find fetch implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill")}static headers(){return this.headersImpl?this.headersImpl:"u">typeof self&&"Headers"in self?self.Headers:"u">typeof globalThis&&globalThis.Headers?globalThis.Headers:"u">typeof Headers?Headers:void v("Could not find Headers implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill")}static response(){return this.responseImpl?this.responseImpl:"u">typeof self&&"Response"in self?self.Response:"u">typeof globalThis&&globalThis.Response?globalThis.Response:"u">typeof Response?Response:void v("Could not find Response implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill")}}let b={CREDENTIAL_MISMATCH:"custom-token-mismatch",MISSING_CUSTOM_TOKEN:"internal-error",INVALID_IDENTIFIER:"invalid-email",MISSING_CONTINUE_URI:"internal-error",INVALID_PASSWORD:"wrong-password",MISSING_PASSWORD:"missing-password",INVALID_LOGIN_CREDENTIALS:"invalid-credential",EMAIL_EXISTS:"email-already-in-use",PASSWORD_LOGIN_DISABLED:"operation-not-allowed",INVALID_IDP_RESPONSE:"invalid-credential",INVALID_PENDING_TOKEN:"invalid-credential",FEDERATED_USER_ID_ALREADY_LINKED:"credential-already-in-use",MISSING_REQ_TYPE:"internal-error",EMAIL_NOT_FOUND:"user-not-found",RESET_PASSWORD_EXCEED_LIMIT:"too-many-requests",EXPIRED_OOB_CODE:"expired-action-code",INVALID_OOB_CODE:"invalid-action-code",MISSING_OOB_CODE:"internal-error",CREDENTIAL_TOO_OLD_LOGIN_AGAIN:"requires-recent-login",INVALID_ID_TOKEN:"invalid-user-token",TOKEN_EXPIRED:"user-token-expired",USER_NOT_FOUND:"user-token-expired",TOO_MANY_ATTEMPTS_TRY_LATER:"too-many-requests",PASSWORD_DOES_NOT_MEET_REQUIREMENTS:"password-does-not-meet-requirements",INVALID_CODE:"invalid-verification-code",INVALID_SESSION_INFO:"invalid-verification-id",INVALID_TEMPORARY_PROOF:"invalid-credential",MISSING_SESSION_INFO:"missing-verification-id",SESSION_EXPIRED:"code-expired",MISSING_ANDROID_PACKAGE_NAME:"missing-android-pkg-name",UNAUTHORIZED_DOMAIN:"unauthorized-continue-uri",INVALID_OAUTH_CLIENT_ID:"invalid-oauth-client-id",ADMIN_ONLY_OPERATION:"admin-restricted-operation",INVALID_MFA_PENDING_CREDENTIAL:"invalid-multi-factor-session",MFA_ENROLLMENT_NOT_FOUND:"multi-factor-info-not-found",MISSING_MFA_ENROLLMENT_ID:"missing-multi-factor-info",MISSING_MFA_PENDING_CREDENTIAL:"missing-multi-factor-session",SECOND_FACTOR_EXISTS:"second-factor-already-in-use",SECOND_FACTOR_LIMIT_EXCEEDED:"maximum-second-factor-count-exceeded",BLOCKING_FUNCTION_ERROR_RESPONSE:"internal-error",RECAPTCHA_NOT_ENABLED:"recaptcha-not-enabled",MISSING_RECAPTCHA_TOKEN:"missing-rec
7aptcha-token",INVALID_RECAPTCHA_TOKEN:"invalid-recaptcha-token",INVALID_RECAPTCHA_ACTION:"invalid-recaptcha-action",MISSING_CLIENT_TYPE:"missing-client-type",MISSING_RECAPTCHA_VERSION:"missing-recaptcha-version",INVALID_RECAPTCHA_VERSION:"invalid-recaptcha-version",INVALID_REQ_TYPE:"invalid-req-type"},S=["/v1/accounts:signInWithCustomToken","/v1/accounts:signInWithEmailLink","/v1/accounts:signInWithIdp","/v1/accounts:signInWithPassword","/v1/accounts:signInWithPhoneNumber","/v1/token"],A=new _(3e4,6e4);function C(e,t){return e.tenantId&&!t.tenantId?{...t,tenantId:e.tenantId}:t}async function k(e,t,r,n,i={}){return N(e,i,async()=>{let i={},a={};n&&("GET"===t?a=n:i={body:JSON.stringify(n)});let o=(0,s.Am)({key:e.config.apiKey,...a}).slice(1),l=await e._getAdditionalHeaders();l["Content-Type"]="application/json",e.languageCode&&(l["X-Firebase-Locale"]=e.languageCode);let u={method:t,headers:l,...i};return(0,s.c1)()||(u.referrerPolicy="no-referrer"),e.emulatorConfig&&(0,s.zJ)(e.emulatorConfig.host)&&(u.credentials="include"),T.fetch()(await D(e,e.config.apiHost,r,o),u)})}async function N(e,t,r){e._canInitEmulator=!1;let n={...b,...t};try{let t=new O(e),i=await Promise.race([r(),t.promise]);t.clearNetworkTimeout();let s=await i.json();if("needConfirmation"in s)throw P(e,"account-exists-with-different-credential",s);if(i.ok&&!("errorMessage"in s))return s;{let[t,r]=(i.ok?s.errorMessage:s.error.message).split(" : ");if("FEDERATED_USER_ID_ALREADY_LINKED"===t)throw P(e,"credential-already-in-use",s);if("EMAIL_EXISTS"===t)throw P(e,"email-already-in-use",s);if("USER_DISABLED"===t)throw P(e,"user-disabled",s);let a=n[t]||t.toLowerCase().replace(/[_\s]+/g,"-");if(r)throw p(e,a,r);d(e,a)}}catch(t){if(t instanceof s.g)throw t;d(e,"network-request-failed",{message:String(t)})}}async function R(e,t,r,n,i={}){let s=await k(e,t,r,n,i);return"mfaPendingCredential"in s&&d(e,"multi-factor-auth-required",{_serverResponse:s}),s}async function D(e,t,r,n){let i=`${t}${r}?${n}`,s=e.config.emulator?I(e.config,i):`${e.config.apiScheme}://${i}`;return S.includes(r)&&(await e._persistenceManagerAvailable,"COOKIE"===e._getPersistenceType())?e._getPersistence()._getFinalTarget(s).toString():s}class O{clearNetworkTimeout(){clearTimeout(this.timer)}constructor(e){this.auth=e,this.timer=null,this.promise=new Promise((e,t)=>{this.timer=setTimeout(()=>t(f(this.auth,"network-request-failed")),A.get())})}}function P(e,t,r){let n={appName:e.name};r.email&&(n.email=r.email),r.phoneNumber&&(n.phoneNumber=r.phoneNumber);let i=f(e,t,n);return i.customData._tokenResponse=r,i}function L(e){return void 0!==e&&void 0!==e.enterprise}class x{constructor(e){if(this.siteKey="",this.recaptchaEnforcementState=[],void 0===e.recaptchaKey)throw Error("recaptchaKey undefined");this.siteKey=e.recaptchaKey.split("/")[3],this.recaptchaEnforcementState=e.recaptchaEnforcementState}getProviderEnforcementState(e){if(!this.recaptchaEnforcementState||0===this.recaptchaEnforcementState.length)return null;for(let t of this.recaptchaEnforcementState)if(t.provider&&t.provider===e)switch(t.enforcementState){case"ENFORCE":return"ENFORCE";case"AUDIT":return"AUDIT";case"OFF":return"OFF";default:return"ENFORCEMENT_STATE_UNSPECIFIED"}return null}isProviderEnabled(e){return"ENFORCE"===this.getProviderEnforcementState(e)||"AUDIT"===this.getProviderEnforcementState(e)}isAnyProviderEnabled(){return this.isProviderEnabled("EMAIL_PASSWORD_PROVIDER")||this.isProviderEnabled("PHONE_PROVIDER")}}async function M(e,t){return k(e,"GET","/v2/recaptchaConfig",C(e,t))}async function U(e,t){return k(e,"POST","/v1/accounts:delete",t)}async function V(e,t){return k(e,"POST","/v1/accounts:lookup",t)}function F(e){if(e)try{let t=new Date(Number(e));if(!isNaN(t.getTime()))return t.toUTCString()}catch(e){}}async function j(e,t=!1){let r=(0,s.Ku)(e),n=await r.getIdToken(t),i=q(n);y(i&&i.exp&&i.auth_time&&i.iat,r.auth,"internal-error");let a="object"==typeof i.firebase?i.firebase:void 0,o=a?.sign_in_provider;return{claims:i,token:n,authTime:F(B(i.auth_time)),issuedAtTime:F(B(i.iat)),expirationTime:F(B(i.exp)),signInProvider:o||null,signInSecondFactor:a?.sign_in_second_factor||null}}function B(e){return 1e3*Number(e)}function q(e){let[t,r,n]=e.split(".");if(void 0===t||void 0===r||void 0===n)return c("JWT malformed, contained fewer than 3 sections"),null;try{let e=(0,s.u)(r);if(!e)return c("Failed to decode base64 JWT payload"),null;return JSON.parse(e)}catch(e){return c("Caught error parsing JWT payload as JSON",e?.toString()),null}}function $(e){let t=q(e);return y(t,"internal-error"),y(void 0!==t.exp,"internal-error"),y(void 0!==t.iat,"internal-error"),Number(t.exp)-Number(t.iat)}async function z(e,t,r=!1){if(r)return t;try{return await t}catch(t){throw t instanceof s.g&&function({code:e}){return"auth/user-disabled"===e||"auth/user-token-expired"===e}(t)&&e.auth.currentUser===e&&await e.auth.signOut(),t}}class K{constructor(e){this.user=e,this.isRunning=!1,this.timerId=null,this.errorBackoff=3e4}_start(){this.isRunning||(this.isRunning=!0,this.schedule())}_stop(){this.isRunning&&(this.isRunning=!1,null!==this.timerId&&clearTimeout(this.timerId))}getInterval(e){if(!e)return this.errorBackoff=3e4,Math.max(0,(this.user.stsTokenManager.expirationTime??0)-Date.now()-3e5);{let e=this.errorBackoff;return this.errorBackoff=Math.min(2*this.errorBackoff,96e4),e}}schedule(e=!1){if(!this.isRunning)return;let t=this.getInterval(e);this.timerId=setTimeout(async()=>{await this.iteration()},t)}async iteration(){try{await this.user.getIdToken(!0)}catch(e){e?.code==="auth/network-request-failed"&&this.schedule(!0);return}this.schedule()}}class H{constructor(e,t){this.createdAt=e,this.lastLoginAt=t,this._initializeTime()}_initializeTime(){this.lastSignInTime=F(this.lastLoginAt),this.creationTime=F(this.createdAt)}_copy(e){this.createdAt=e.createdAt,this.lastLoginAt=e.lastLoginAt,this._initializeTime()}toJSON(){return{createdAt:this.createdAt,lastLoginAt:this.lastLoginAt}}}async function G(e){var t,r;let n=e.auth,i=await e.getIdToken(),s=await z(e,V(n,{idToken:i}));y(s?.users.length,n,"internal-error");let a=s.users[0];e._notifyReloadListener(a);let o=a.providerUserInfo?.length?Q(a.providerUserInfo):[],l=(t=e.providerData,r=o,[...t.filter(e=>!r.some(t=>t.providerId===e.providerId)),...r]),u=e.isAnonymous,h=!(e.email&&a.passwordHash)&&!l?.length;Object.assign(e,{uid:a.localId,displayName:a.displayName||null,photoURL:a.photoUrl||null,email:a.email||null,emailVerified:a.emailVerified||!1,phoneNumber:a.phoneNumber||null,tenantId:a.tenantId||null,providerData:l,metadata:new H(a.createdAt,a.lastLoginAt),isAnonymous:!!u&&h})}async function W(e){let t=(0,s.Ku)(e);await G(t),await t.auth._persistUserIfCurrent(t),t.auth._notifyListenersIfCurrent(t)}function Q(e){return e.map(({providerId:e,...t})=>
7({providerId:e,uid:t.rawId||"",displayName:t.displayName||null,email:t.email||null,phoneNumber:t.phoneNumber||null,photoURL:t.photoUrl||null}))}async function J(e,t){let r=await N(e,{},async()=>{let r=(0,s.Am)({grant_type:"refresh_token",refresh_token:t}).slice(1),{tokenApiHost:n,apiKey:i}=e.config,a=await D(e,n,"/v1/token",`key=${i}`),o=await e._getAdditionalHeaders();o["Content-Type"]="application/x-www-form-urlencoded";let l={method:"POST",headers:o,body:r};return e.emulatorConfig&&(0,s.zJ)(e.emulatorConfig.host)&&(l.credentials="include"),T.fetch()(a,l)});return{accessToken:r.access_token,expiresIn:r.expires_in,refreshToken:r.refresh_token}}async function X(e,t){return k(e,"POST","/v2/accounts:revokeToken",C(e,t))}class Y{constructor(){this.refreshToken=null,this.accessToken=null,this.expirationTime=null}get isExpired(){return!this.expirationTime||Date.now()>this.expirationTime-3e4}updateFromServerResponse(e){y(e.idToken,"internal-error"),y(void 0!==e.idToken,"internal-error"),y(void 0!==e.refreshToken,"internal-error");let t="expiresIn"in e&&void 0!==e.expiresIn?Number(e.expiresIn):$(e.idToken);this.updateTokensAndExpiration(e.idToken,e.refreshToken,t)}updateFromIdToken(e){y(0!==e.length,"internal-error");let t=$(e);this.updateTokensAndExpiration(e,null,t)}async getToken(e,t=!1){return t||!this.accessToken||this.isExpired?(y(this.refreshToken,e,"user-token-expired"),this.refreshToken)?(await this.refresh(e,this.refreshToken),this.accessToken):null:this.accessToken}clearRefreshToken(){this.refreshToken=null}async refresh(e,t){let{accessToken:r,refreshToken:n,expiresIn:i}=await J(e,t);this.updateTokensAndExpiration(r,n,Number(i))}updateTokensAndExpiration(e,t,r){this.refreshToken=t||null,this.accessToken=e||null,this.expirationTime=Date.now()+1e3*r}static fromJSON(e,t){let{refreshToken:r,accessToken:n,expirationTime:i}=t,s=new Y;return r&&(y("string"==typeof r,"internal-error",{appName:e}),s.refreshToken=r),n&&(y("string"==typeof n,"internal-error",{appName:e}),s.accessToken=n),i&&(y("number"==typeof i,"internal-error",{appName:e}),s.expirationTime=i),s}toJSON(){return{refreshToken:this.refreshToken,accessToken:this.accessToken,expirationTime:this.expirationTime}}_assign(e){this.accessToken=e.accessToken,this.refreshToken=e.refreshToken,this.expirationTime=e.expirationTime}_clone(){return Object.assign(new Y,this.toJSON())}_performRefresh(){return v("not implemented")}}function Z(e,t){y("string"==typeof e||void 0===e,"internal-error",{appName:t})}class ee{constructor({uid:e,auth:t,stsTokenManager:r,...n}){this.providerId="firebase",this.proactiveRefresh=new K(this),this.reloadUserInfo=null,this.reloadListener=null,this.uid=e,this.auth=t,this.stsTokenManager=r,this.accessToken=r.accessToken,this.displayName=n.displayName||null,this.email=n.email||null,this.emailVerified=n.emailVerified||!1,this.phoneNumber=n.phoneNumber||null,this.photoURL=n.photoURL||null,this.isAnonymous=n.isAnonymous||!1,this.tenantId=n.tenantId||null,this.providerData=n.providerData?[...n.providerData]:[],this.metadata=new H(n.createdAt||void 0,n.lastLoginAt||void 0)}async getIdToken(e){let t=await z(this,this.stsTokenManager.getToken(this.auth,e));return y(t,this.auth,"internal-error"),this.accessToken!==t&&(this.accessToken=t,await this.auth._persistUserIfCurrent(this),this.auth._notifyListenersIfCurrent(this)),t}getIdTokenResult(e){return j(this,e)}reload(){return W(this)}_assign(e){this!==e&&(y(this.uid===e.uid,this.auth,"internal-error"),this.displayName=e.displayName,this.photoURL=e.photoURL,this.email=e.email,this.emailVerified=e.emailVerified,this.phoneNumber=e.phoneNumber,this.isAnonymous=e.isAnonymous,this.tenantId=e.tenantId,this.providerData=e.providerData.map(e=>({...e})),this.metadata._copy(e.metadata),this.stsTokenManager._assign(e.stsTokenManager))}_clone(e){let t=new ee({...this,auth:e,stsTokenManager:this.stsTokenManager._clone()});return t.metadata._copy(this.metadata),t}_onReload(e){y(!this.reloadListener,this.auth,"internal-error"),this.reloadListener=e,this.reloadUserInfo&&(this._notifyReloadListener(this.reloadUserInfo),this.reloadUserInfo=null)}_notifyReloadListener(e){this.reloadListener?this.reloadListener(e):this.reloadUserInfo=e}_startProactiveRefresh(){this.proactiveRefresh._start()}_stopProactiveRefresh(){this.proactiveRefresh._stop()}async _updateTokensIfNecessary(e,t=!1){let r=!1;e.idToken&&e.idToken!==this.stsTokenManager.accessToken&&(this.stsTokenManager.updateFromServerResponse(e),r=!0),t&&await G(this),await this.auth._persistUserIfCurrent(this),r&&this.auth._notifyListenersIfCurrent(this)}async delete(){if((0,i.xZ)(this.auth.app))return Promise.reject(m(this.auth));let e=await this.getIdToken();return await z(this,U(this.auth,{idToken:e})),this.stsTokenManager.clearRefreshToken(),this.auth.signOut()}toJSON(){return{uid:this.uid,email:this.email||void 0,emailVerified:this.emailVerified,displayName:this.displayName||void 0,isA
7nonymous:this.isAnonymous,photoURL:this.photoURL||void 0,phoneNumber:this.phoneNumber||void 0,tenantId:this.tenantId||void 0,providerData:this.providerData.map(e=>({...e})),stsTokenManager:this.stsTokenManager.toJSON(),_redirectEventId:this._redirectEventId,...this.metadata.toJSON(),apiKey:this.auth.config.apiKey,appName:this.auth.name}}get refreshToken(){return this.stsTokenManager.refreshToken||""}static _fromJSON(e,t){let r=t.displayName??void 0,n=t.email??void 0,i=t.phoneNumber??void 0,s=t.photoURL??void 0,a=t.tenantId??void 0,o=t._redirectEventId??void 0,l=t.createdAt??void 0,u=t.lastLoginAt??void 0,{uid:h,emailVerified:c,isAnonymous:d,providerData:f,stsTokenManager:p}=t;y(h&&p,e,"internal-error");let m=Y.fromJSON(this.name,p);y("string"==typeof h,e,"internal-error"),Z(r,e.name),Z(n,e.name),y("boolean"==typeof c,e,"internal-error"),y("boolean"==typeof d,e,"internal-error"),Z(i,e.name),Z(s,e.name),Z(a,e.name),Z(o,e.name),Z(l,e.name),Z(u,e.name);let g=new ee({uid:h,auth:e,email:n,emailVerified:c,displayName:r,isAnonymous:d,photoURL:s,phoneNumber:i,tenantId:a,stsTokenManager:m,createdAt:l,lastLoginAt:u});return f&&Array.isArray(f)&&(g.providerData=f.map(e=>({...e}))),o&&(g._redirectEventId=o),g}static async _fromIdTokenResponse(e,t,r=!1){let n=new Y;n.updateFromServerResponse(t);let i=new ee({uid:t.localId,auth:e,stsTokenManager:n,isAnonymous:r});return await G(i),i}static async _fromGetAccountInfoResponse(e,t,r){let n=t.users[0];y(void 0!==n.localId,"internal-error");let i=void 0!==n.providerUserInfo?Q(n.providerUserInfo):[],s=!(n.email&&n.passwordHash)&&!i?.length,a=new Y;a.updateFromIdToken(r);let o=new ee({uid:n.localId,auth:e,stsTokenManager:a,isAnonymous:s});return Object.assign(o,{uid:n.localId,displayName:n.displayName||null,photoURL:n.photoUrl||null,email:n.email||null,emailVerified:n.emailVerified||!1,phoneNumber:n.phoneNumber||null,tenantId:n.tenantId||null,providerData:i,metadata:new H(n.createdAt,n.lastLoginAt),isAnonymous:!(n.email&&n.passwordHash)&&!i?.length}),o}}let et=new Map;function er(e){var t,r;t="Expected a class definition",e instanceof Function||v(t);let n=et.get(e);return n?(r="Instance stored in cache mismatched with class",n instanceof e||v(r)):(n=new e,et.set(e,n)),n}class en{constructor(){this.type="NONE",this.storage={}}async _isAvailable(){return!0}async _set(e,t){this.storage[e]=t}async _get(e){let t=this.storage[e];return void 0===t?null:t}async _remove(e){delete this.storage[e]}_addListener(e,t){}_removeListener(e,t){}}function ei(e,t,r){return`firebase:${e}:${t}:${r}`}en.type="NONE";class es{constructor(e,t,r){this.persistence=e,this.auth=t,this.userKey=r;const{config:n,name:i}=this.auth;this.fullUserKey=ei(this.userKey,n.apiKey,i),this.fullPersistenceKey=ei("persistence",n.apiKey,i),this.boundEventHandler=t._onStorageEvent.bind(t),this.persistence._addListener(this.fullUserKey,this.boundEventHandler)}setCurrentUser(e){return this.persistence._set(this.fullUserKey,e.toJSON())}async getCurrentUser(){let e=await this.persistence._get(this.fullUserKey);if(!e)return null;if("string"==typeof e){let t=await V(this.auth,{idToken:e}).catch(()=>void 0);return t?ee._fromGetAccountInfoResponse(this.auth,t,e):null}return ee._fromJSON(this.auth,e)}removeCurrentUser(){return this.persistence._remove(this.fullUserKey)}savePersistenceForRedirect(){return this.persistence._set(this.fullPersistenceKey,this.persistence.type)}async setPersistence(e){if(this.persistence===e)return;let t=await this.getCurrentUser();if(await this.removeCurrentUser(),this.persistence=e,t)return this.setCurrentUser(t)}delete(){this.persistence._removeListener(this.fullUserKey,this.boundEventHandler)}static async create(e,t,r="authUser"){if(!t.length)return new es(er(en),e,r);let n=(await Promise.all(t.map(async e=>{if(await e._isAvailable())return e}))).filter(e=>e),i=n[0]||er(en),s=ei(r,e.config.apiKey,e.name),a=null;for(let r of t)try{let t=await r._get(s);if(t){let n;if("string"==typeof t){let r=await V(e,{idToken:t}).catch(()=>void 0);if(!r)break;n=await ee._fromGetAccountInfoResponse(e,r,t)}else n=ee._fromJSON(e,t);r!==i&&(a=n),i=r;break}}catch{}let o=n.filter(e=>e._shouldAllowMigration);return i._shouldAllowMigration&&o.length&&(i=o[0],a&&await i._set(s,a.toJSON()),await Promise.all(t.map(async e=>{if(e!==i)try{await e._remove(s)}catch{}}))),new es(i,e,r)}}function ea(e){let t=e.toLowerCase();if(t.includes("opera/")||t.includes("opr/")||t.includes("opios/"))return"Opera";{if(eh(t))return"IEMobile";if(t.includes("msie")||t.includes("trident/"))return"IE";if(t.includes("edge/"))return"Edge";if(eo(t))return"Firefox";if(t.includes("silk/"))return"Silk";if(ed(t))return"Blackberry";if(ef(t))return"Webos";if(el(t))return"Safari";
7if((t.includes("chrome/")||eu(t))&&!t.includes("edge/"))return"Chrome";if(ec(t))return"Android";let r=e.match(/([a-zA-Z\d\.]+)\/[a-zA-Z\d\.]*$/);if(r?.length===2)return r[1]}return"Other"}function eo(e=(0,s.ZQ)()){return/firefox\//i.test(e)}function el(e=(0,s.ZQ)()){let t=e.toLowerCase();return t.includes("safari/")&&!t.includes("chrome/")&&!t.includes("crios/")&&!t.includes("android")}function eu(e=(0,s.ZQ)()){return/crios\//i.test(e)}function eh(e=(0,s.ZQ)()){return/iemobile/i.test(e)}function ec(e=(0,s.ZQ)()){return/android/i.test(e)}function ed(e=(0,s.ZQ)()){return/blackberry/i.test(e)}function ef(e=(0,s.ZQ)()){return/webos/i.test(e)}function ep(e=(0,s.ZQ)()){return/iphone|ipad|ipod/i.test(e)||/macintosh/i.test(e)&&/mobile/i.test(e)}function em(e=(0,s.ZQ)()){return ep(e)||ec(e)||ef(e)||ed(e)||/windows phone/i.test(e)||eh(e)}function eg(e,t=[]){let r;switch(e){case"Browser":r=ea((0,s.ZQ)());break;case"Worker":r=`${ea((0,s.ZQ)())}-${e}`;break;default:r=e}let n=t.length?t.join(","):"FirebaseCore-web";return`${r}/JsCore/${i.MF}/${n}`}class ey{constructor(e){this.auth=e,this.queue=[]}pushCallback(e,t){let r=t=>new Promise((r,n)=>{try{let n=e(t);r(n)}catch(e){n(e)}});r.onAbort=t,this.queue.push(r);let n=this.queue.length-1;return()=>{this.queue[n]=()=>Promise.resolve()}}async runMiddleware(e){if(this.auth.currentUser===e)return;let t=[];try{for(let r of this.queue)await r(e),r.onAbort&&t.push(r.onAbort)}catch(e){for(let e of(t.reverse(),t))try{e()}catch(e){}throw this.auth._errorFactory.create("login-blocked",{originalMessage:e?.message})}}}async function ev(e,t={}){return k(e,"GET","/v2/passwordPolicy",C(e,t))}class ew{constructor(e){const t=e.customStrengthOptions;this.customStrengthOptions={},this.customStrengthOptions.minPasswordLength=t.minPasswordLength??6,t.maxPasswordLength&&(this.customStrengthOptions.maxPasswordLength=t.maxPasswordLength),void 0!==t.containsLowercaseCharacter&&(this.customStrengthOptions.containsLowercaseLetter=t.containsLowercaseCharacter),void 0!==t.containsUppercaseCharacter&&(this.customStrengthOptions.containsUppercaseLetter=t.containsUppercaseCharacter),void 0!==t.containsNumericCharacter&&(this.customStrengthOptions.containsNumericCharacter=t.containsNumericCharacter),void 0!==t.containsNonAlphanumericCharacter&&(this.customStrengthOptions.containsNonAlphanumericCharacter=t.containsNonAlphanumericCharacter),this.enforcementState=e.enforcementState,"ENFORCEMENT_STATE_UNSPECIFIED"===this.enforcementState&&(this.enforcementState="OFF"),this.allowedNonAlphanumericCharacters=e.allowedNonAlphanumericCharacters?.join("")??"",this.forceUpgradeOnSignin=e.forceUpgradeOnSignin??!1,this.schemaVersion=e.schemaVersion}validatePassword(e){let t={isValid:!0,passwordPolicy:this};return this.validatePasswordLengthOptions(e,t),this.validatePasswordCharacterOptions(e,t),t.isValid&&(t.isValid=t.meetsMinPasswordLength??!0),t.isValid&&(t.isValid=t.meetsMaxPasswordLength??!0),t.isValid&&(t.isValid=t.containsLowercaseLetter??!0),t.isValid&&(t.isValid=t.containsUppercaseLetter??!0),t.isValid&&(t.isValid=t.containsNumericCharacter??!0),t.isValid&&(t.isValid=t.containsNonAlphanumericCharacter??!0),t}validatePasswordLengthOptions(e,t){let r=this.customStrengthOptions.minPasswordLength,n=this.customStrengthOptions.maxPasswordLength;r&&(t.meetsMinPasswordLength=e.length>=r),n&&(t.meetsMaxPasswordLength=e.length<=n)}validatePasswordCharacterOptions(e,t){let r;this.updatePasswordCharacterOptionsStatuses(t,!1,!1,!1,!1);for(let n=0;n<e.length;n++)r=e.charAt(n),this.updatePasswordCharacterOptionsStatuses(t,r>="a"&&r<="z",r>="A"&&r<="Z",r>="0"&&r<="9",this.allowedNonAlphanumericCharacters.includes(r))}updatePasswordCharacterOptionsStatuses(e,t,r,n,i){this.customStrengthOptions.containsLowercaseLetter&&(e.containsLowercaseLetter||(e.containsLowercaseLetter=t)),this.customStrengthOptions.containsUppercaseLetter&&(e.containsUppercaseLetter||(e.containsUppercaseLetter=r)),this.customStrengthOptions.containsNumericCharacter&&(e.containsNumericCharacter||(e.containsNumericCharacter=n)),this.customStrengthOptions.containsNonAlphanumericCharacter&&(e.containsNonAlphanumericCharacter||(e.containsNonAlphanumericCharacter=i))}}class eE{constructor(e,t,r,n){this.app=e,this.heartbeatServiceProvider=t,this.appCheckServiceProvider=r,this.config=n,this.currentUser=null,this.emulatorConfig=null,this.operations=Promise.resolve(),this.authStateSubscription=new eI(this),this.idTokenSubscription=new eI(this),this.beforeStateQueue=new ey(this),this.redirectUser=null,this.isProactiveRefreshEnabled=!1,this.EXPECTED_PASSWORD_POLICY_SCHEMA_VERSION=1,this._canInitEmulator=!0,this._isInitialized=!1,this._deleted=!1,this._initializationPromise=null,this._popupRedirectResolver=null,this._errorFactory=u,this._agentRecaptchaConfig=null,this._tenantRecaptchaConfigs={},this._projectPasswordPolicy=null,this._tenantPasswordPolicies={},this._resolvePersistenceManagerAvailable=void 0,this.lastNotifiedUid=void 0,this.languageCode=null,this.tenantId=null,this.settings={appVerificationDisabledForTesting:!1},this.frameworks=[],this.name=e.name,this.clientVersion=n.sdkClientVersion,this._persistenceManagerAvailable=new Promise(e=>this._resolvePersistenceManagerAvailable=e)}_initializeWithPersistence(e,t){return t&&(this._popupRedirectResolver=er(t)),this._initializationPromise=this.queue(async()=>
7{if(!this._deleted){if(this.persistenceManager=await es.create(this,e),this._resolvePersistenceManagerAvailable?.(),!this._deleted){if(this._popupRedirectResolver?._shouldInitProactively)try{await this._popupRedirectResolver._initialize(this)}catch(e){}await this.initializeCurrentUser(t),this.lastNotifiedUid=this.currentUser?.uid||null,this._deleted||(this._isInitialized=!0)}}}),this._initializationPromise}async _onStorageEvent(){if(this._deleted)return;let e=await this.assertedPersistence.getCurrentUser();if(this.currentUser||e){if(this.currentUser&&e&&this.currentUser.uid===e.uid){this._currentUser._assign(e),await this.currentUser.getIdToken();return}await this._updateCurrentUser(e,!0)}}async initializeCurrentUserFromIdToken(e){try{let t=await V(this,{idToken:e}),r=await ee._fromGetAccountInfoResponse(this,t,e);await this.directlySetCurrentUser(r)}catch(e){console.warn("FirebaseServerApp could not login user with provided authIdToken: ",e),await this.directlySetCurrentUser(null)}}async initializeCurrentUser(e){if((0,i.xZ)(this.app)){let e=this.app.settings.authIdToken;return e?new Promise(t=>{setTimeout(()=>this.initializeCurrentUserFromIdToken(e).then(t,t))}):this.directlySetCurrentUser(null)}let t=await this.assertedPersistence.getCurrentUser(),r=t,n=!1;if(e&&this.config.authDomain){await this.getOrInitRedirectPersistenceManager();let t=this.redirectUser?._redirectEventId,i=r?._redirectEventId,s=await this.tryRedirectSignIn(e);(!t||t===i)&&s?.user&&(r=s.user,n=!0)}if(!r)return this.directlySetCurrentUser(null);if(!r._redirectEventId){if(n)try{await this.beforeStateQueue.runMiddleware(r)}catch(e){r=t,this._popupRedirectResolver._overrideRedirectResult(this,()=>Promise.reject(e))}return r?this.reloadAndSetCurrentUserOrClear(r):this.directlySetCurrentUser(null)}return(y(this._popupRedirectResolver,this,"argument-error"),await this.getOrInitRedirectPersistenceManager(),this.redirectUser&&this.redirectUser._redirectEventId===r._redirectEventId)?this.directlySetCurrentUser(r):this.reloadAndSetCurrentUserOrClear(r)}async tryRedirectSignIn(e){let t=null;try{t=await this._popupRedirectResolver._completeRedirectFn(this,e,!0)}catch(e){await this._setRedirectUser(null)}return t}async reloadAndSetCurrentUserOrClear(e){try{await G(e)}catch(e){if(e?.code!=="auth/network-request-failed")return this.directlySetCurrentUser(null)}return this.directlySetCurrentUser(e)}useDeviceLanguage(){this.languageCode=function(){if("u"<typeof navigator)return null;let e=navigator;return e.languages&&e.languages[0]||e.language||null}()}async _delete(){this._deleted=!0}async updateCurrentUser(e){if((0,i.xZ)(this.app))return Promise.reject(m(this));let t=e?(0,s.Ku)(e):null;return t&&y(t.auth.config.apiKey===this.config.apiKey,this,"invalid-user-token"),this._updateCurrentUser(t&&t._clone(this))}async _updateCurrentUser(e,t=!1){if(!this._deleted)return e&&y(this.tenantId===e.tenantId,this,"tenant-id-mismatch"),t||await this.beforeStateQueue.runMiddleware(e),this.queue(async()=>{await this.directlySetCurrentUser(e),this.notifyAuthListeners()})}async signOut(){return(0,i.xZ)(this.app)?Promise.reject(m(this)):(await this.beforeStateQueue.runMiddleware(null),(this.redirectPersistenceManager||this._popupRedirectResolver)&&await this._setRedirectUser(null),this._updateCurrentUser(null,!0))}setPersistence(e){return(0,i.xZ)(this.app)?Promise.reject(m(this)):this.queue(async()=>{await this.assertedPersistence.setPersistence(er(e))})}_getRecaptchaConfig(){return null==this.tenantId?this._agentRecaptchaConfig:this._tenantRecaptchaConfigs[this.tenantId]}async validatePassword(e){this._getPasswordPolicyInternal()||await this._updatePasswordPolicy();let t=this._getPasswordPolicyInternal();return t.schemaVersion!==this.EXPECTED_PASSWORD_POLICY_SCHEMA_VERSION?Promise.reject(this._errorFactory.create("unsupported-password-policy-schema-version",{})):t.validatePassword(e)}_getPasswordPolicyInternal(){return null===this.tenantId?this._projectPasswordPolicy:this._tenantPasswordPolicies[this.tenantId]}async _updatePasswordPolicy(){let e=new ew(await ev(this));null===this.tenantId?this._projectPasswordPolicy=e:this._tenantPasswordPolicies[this.tenantId]=e}_getPersistenceType(){return this.assertedPersistence.persistence.type}_getPersistence(){return this.assertedPersistence.persistence}_updateErrorMap(e){this._errorFactory=new s.FA("auth","Firebase",e())}onAuthStateChanged(e,t,r){return this.registerStateListener(this.authStateSubscription,e,t,r)}beforeAuthStateChanged(e,t){return this.beforeStateQueue.pushCallback(e,t)}onIdTokenChanged(e,t,r){return this.registerStateListener(this.idTokenSubscription,e,t,r)}authStateReady(){return new Promise((e,t)=>
7{if(this.currentUser)e();else{let r=this.onAuthStateChanged(()=>{r(),e()},t)}})}async revokeAccessToken(e){if(this.currentUser){let t={providerId:"apple.com",tokenType:"ACCESS_TOKEN",token:e,idToken:await this.currentUser.getIdToken()};null!=this.tenantId&&(t.tenantId=this.tenantId),await X(this,t)}}toJSON(){return{apiKey:this.config.apiKey,authDomain:this.config.authDomain,appName:this.name,currentUser:this._currentUser?.toJSON()}}async _setRedirectUser(e,t){let r=await this.getOrInitRedirectPersistenceManager(t);return null===e?r.removeCurrentUser():r.setCurrentUser(e)}async getOrInitRedirectPersistenceManager(e){if(!this.redirectPersistenceManager){let t=e&&er(e)||this._popupRedirectResolver;y(t,this,"argument-error"),this.redirectPersistenceManager=await es.create(this,[er(t._redirectPersistence)],"redirectUser"),this.redirectUser=await this.redirectPersistenceManager.getCurrentUser()}return this.redirectPersistenceManager}async _redirectUserForId(e){return(this._isInitialized&&await this.queue(async()=>{}),this._currentUser?._redirectEventId===e)?this._currentUser:this.redirectUser?._redirectEventId===e?this.redirectUser:null}async _persistUserIfCurrent(e){if(e===this.currentUser)return this.queue(async()=>this.directlySetCurrentUser(e))}_notifyListenersIfCurrent(e){e===this.currentUser&&this.notifyAuthListeners()}_key(){return`${this.config.authDomain}:${this.config.apiKey}:${this.name}`}_startProactiveRefresh(){this.isProactiveRefreshEnabled=!0,this.currentUser&&this._currentUser._startProactiveRefresh()}_stopProactiveRefresh(){this.isProactiveRefreshEnabled=!1,this.currentUser&&this._currentUser._stopProactiveRefresh()}get _currentUser(){return this.currentUser}notifyAuthListeners(){if(!this._isInitialized)return;this.idTokenSubscription.next(this.currentUser);let e=this.currentUser?.uid??null;this.lastNotifiedUid!==e&&(this.lastNotifiedUid=e,this.authStateSubscription.next(this.currentUser))}registerStateListener(e,t,r,n){if(this._deleted)return()=>{};let i="function"==typeof t?t:t.next.bind(t),s=!1,a=this._isInitialized?Promise.resolve():this._initializationPromise;if(y(a,this,"internal-error"),a.then(()=>{s||i(this.currentUser)}),"function"==typeof t){let i=e.addObserver(t,r,n);return()=>{s=!0,i()}}{let r=e.addObserver(t);return()=>{s=!0,r()}}}async directlySetCurrentUser(e){this.currentUser&&this.currentUser!==e&&this._currentUser._stopProactiveRefresh(),e&&this.isProactiveRefreshEnabled&&e._startProactiveRefresh(),this.currentUser=e,e?await this.assertedPersistence.setCurrentUser(e):await this.assertedPersistence.removeCurrentUser()}queue(e){return this.operations=this.operations.then(e,e),this.operations}get assertedPersistence(){return y(this.persistenceManager,this,"internal-error"),this.persistenceManager}_logFramework(e){!e||this.frameworks.includes(e)||(this.frameworks.push(e),this.frameworks.sort(),this.clientVersion=eg(this.config.clientPlatform,this._getFrameworks()))}_getFrameworks(){return this.frameworks}async _getAdditionalHeaders(){let e={"X-Client-Version":this.clientVersion};this.app.options.appId&&(e["X-Firebase-gmpid"]=this.app.options.appId);let t=await this.heartbeatServiceProvider.getImmediate({optional:!0})?.getHeartbeatsHeader();t&&(e["X-Firebase-Client"]=t);let r=await this._getAppCheckToken();return r&&(e["X-Firebase-AppCheck"]=r),e}async _getAppCheckToken(){if((0,i.xZ)(this.app)&&this.app.settings.appCheckToken)return this.app.settings.appCheckToken;let e=await this.appCheckServiceProvider.getImmediate({optional:!0})?.getToken();return e?.error&&function(e,...t){h.logLevel<=a.$b.WARN&&h.warn(`Auth (${i.MF}): ${e}`,...t)}(`Error while retrieving App Check token: ${e.error}`),e?.token}}function e_(e){return(0,s.Ku)(e)}class eI{constructor(e){this.auth=e,this.observer=null,this.addObserver=(0,s.tD)(e=>this.observer=e)}get next(){return y(this.observer,this.auth,"internal-error"),this.observer.next.bind(this.observer)}}let eT={async loadJS(){throw Error("Unable to load external scripts")},recaptchaV2Script:"",recaptchaEnterpriseScript:"",gapiScript:""};function eb(e){return`__${e}${Math.floor(1e6*Math.random())}`}class eS{constructor(){this.enterprise=new eA}ready(e){e()}execute(e,t){return Promise.resolve("token")}render(e,t){return""}}class eA{ready(e){e()}execute(e,t){return Promise.resolve("token")}render(e,t){return""}}let eC="NO_RECAPTCHA";class ek{constructor(e){this.type="recaptcha-enterprise",this.auth=e_(e)}async verify(e="verify",t=!1){async function r(e){if(!t){if(null==e.tenantId&&null!=e._agentRecaptchaConfig)return e._agentRecaptchaConfig.siteKey;if(null!=e.tenantId&&void 0!==e._tenantRecaptchaConfigs[e.tenantId])return e._tenantRecaptchaConfigs[e.tenantId].siteKey}return new Promise(async(t,r)=>
7{M(e,{clientType:"CLIENT_TYPE_WEB",version:"RECAPTCHA_ENTERPRISE"}).then(n=>{if(void 0===n.recaptchaKey)r(Error("recaptcha Enterprise site key undefined"));else{let r=new x(n);return null==e.tenantId?e._agentRecaptchaConfig=r:e._tenantRecaptchaConfigs[e.tenantId]=r,t(r.siteKey)}}).catch(e=>{r(e)})})}function n(t,r,n){let i=window.grecaptcha;L(i)?i.enterprise.ready(()=>{i.enterprise.execute(t,{action:e}).then(e=>{r(e)}).catch(()=>{r(eC)})}):n(Error("No reCAPTCHA enterprise script loaded."))}return this.auth.settings.appVerificationDisabledForTesting?new eS().execute("siteKey",{action:"verify"}):new Promise((e,i)=>{r(this.auth).then(r=>{if(!t&&L(window.grecaptcha))n(r,e,i);else{var s;if("u"<typeof window)return void i(Error("RecaptchaVerifier is only supported in browser"));let t=eT.recaptchaEnterpriseScript;0!==t.length&&(t+=r),(s=t,eT.loadJS(s)).then(()=>{n(r,e,i)}).catch(e=>{i(e)})}}).catch(e=>{i(e)})})}}async function eN(e,t,r,n=!1,i=!1){let s,a=new ek(e);if(i)s=eC;else try{s=await a.verify(r)}catch(e){s=await a.verify(r,!0)}let o={...t};if("mfaSmsEnrollment"===r||"mfaSmsSignIn"===r){if("phoneEnrollmentInfo"in o){let e=o.phoneEnrollmentInfo.phoneNumber,t=o.phoneEnrollmentInfo.recaptchaToken;Object.assign(o,{phoneEnrollmentInfo:{phoneNumber:e,recaptchaToken:t,captchaResponse:s,clientType:"CLIENT_TYPE_WEB",recaptchaVersion:"RECAPTCHA_ENTERPRISE"}})}else if("phoneSignInInfo"in o){let e=o.phoneSignInInfo.recaptchaToken;Object.assign(o,{phoneSignInInfo:{recaptchaToken:e,captchaResponse:s,clientType:"CLIENT_TYPE_WEB",recaptchaVersion:"RECAPTCHA_ENTERPRISE"}})}return o}return n?Object.assign(o,{captchaResp:s}):Object.assign(o,{captchaResponse:s}),Object.assign(o,{clientType:"CLIENT_TYPE_WEB"}),Object.assign(o,{recaptchaVersion:"RECAPTCHA_ENTERPRISE"}),o}async function eR(e,t,r,n,i){if("EMAIL_PASSWORD_PROVIDER"===i)if(!e._getRecaptchaConfig()?.isProviderEnabled("EMAIL_PASSWORD_PROVIDER"))return n(e,t).catch(async i=>{if("auth/missing-recaptcha-token"!==i.code)return Promise.reject(i);{console.log(`${r} is protected by reCAPTCHA Enterprise for this project. Automatically triggering the reCAPTCHA flow and restarting the flow.`);let i=await eN(e,t,r,"getOobCode"===r);return n(e,i)}});else{let i=await eN(e,t,r,"getOobCode"===r);return n(e,i)}if("PHONE_PROVIDER"!==i)return Promise.reject(i+" provider is not supported.");if(e._getRecaptchaConfig()?.isProviderEnabled("PHONE_PROVIDER")){let i=await eN(e,t,r);return n(e,i).catch(async i=>{if(e._getRecaptchaConfig()?.getProviderEnforcementState("PHONE_PROVIDER")==="AUDIT"&&("auth/missing-recaptcha-token"===i.code||"auth/invalid-app-credential"===i.code)){console.log(`Failed to verify with reCAPTCHA Enterprise. Automatically triggering the reCAPTCHA v2 flow to complete the ${r} flow.`);let i=await eN(e,t,r,!1,!0);return n(e,i)}return Promise.reject(i)})}{let i=await eN(e,t,r,!1,!0);return n(e,i)}}async function eD(e){let t=e_(e),r=new x(await M(t,{clientType:"CLIENT_TYPE_WEB",version:"RECAPTCHA_ENTERPRISE"}));null==t.tenantId?t._agentRecaptchaConfig=r:t._tenantRecaptchaConfigs[t.tenantId]=r,r.isAnyProviderEnabled()&&new ek(t).verify()}function eO(e,t){let r=(0,i.j6)(e,"auth");if(r.isInitialized()){let e=r.getImmediate(),n=r.getOptions();if((0,s.bD)(n,t??{}))return e;d(e,"already-initialized")}return r.initialize({options:t})}function eP(e,t,r){let n=e_(e);y(/^https?:\/\//.test(t),n,"invalid-emulator-scheme");let i=!!r?.disableWarnings,a=eL(t),{host:o,port:l}=function(e){let t=eL(e),r=/(\/\/)?([^?#/]+)/.exec(e.substr(t.length));if(!r)return{host:"",port:null};let n=r[2].split("@").pop()||"",i=/^(\[[^\]]+\])(:|$)/.exec(n);if(i){let e=i[1];return{host:e,port:ex(n.substr(e.length+1))}}{let[e,t]=n.split(":");return{host:e,port:ex(t)}}}(t),u=null===l?"":`:${l}`,h={url:`${a}//${o}${u}/`},c=Object.freeze({host:o,port:l,protocol:a.replace(":",""),options:Object.freeze({disableWarnings:i})});if(!n._canInitEmulator){y(n.config.emulator&&n.emulatorConfig,n,"emulator-config-failed"),y((0,s.bD)(h,n.config.emulator)&&(0,s.bD)(c,n.emulatorConfig),n,"emulator-config-failed");return}n.config.emulator=h,n.emulatorConfig=c,n.settings.appVerificationDisabledForTesting=!0,(0,s.zJ)(o)?(0,s.gE)(`${a}//${o}${u}`):i||function(){function e(){let e=document.createElement("p"),t=e.style;e.innerText="Running in emulator mode. Do not use with production credentials.",t.position="fixed",t.width="100%",t.backgroundColor="#ffffff",t.border=".1em solid #000000",t.color="#b50000",t.bottom="0px",t.left="0px",t.margin="0px",t.zIndex="10000",t.textAlign="center",e.classList.add("firebase-emulator-warning"),document.body.appendChild(e)}"u">typeof console&&"function"==typeof console.info&&console.info("WARNING: You are using the Auth Emulator, which is intended for local testing only. Do not use with production credentials."),"u">typeof window&&"u">typeof document&&("loading"===document.readyState?window.addEventListener("DOMContentLoaded",e):e())}()}function eL(e){let t=e.indexOf(":");
7return t<0?"":e.substr(0,t+1)}function ex(e){if(!e)return null;let t=Number(e);return isNaN(t)?null:t}class eM{constructor(e,t){this.providerId=e,this.signInMethod=t}toJSON(){return v("not implemented")}_getIdTokenResponse(e){return v("not implemented")}_linkToIdToken(e,t){return v("not implemented")}_getReauthenticationResolver(e){return v("not implemented")}}async function eU(e,t){return k(e,"POST","/v1/accounts:update",t)}async function eV(e,t){return k(e,"POST","/v1/accounts:signUp",t)}async function eF(e,t){return R(e,"POST","/v1/accounts:signInWithPassword",C(e,t))}async function ej(e,t){return k(e,"POST","/v1/accounts:sendOobCode",C(e,t))}async function eB(e,t){return ej(e,t)}async function eq(e,t){return ej(e,t)}async function e$(e,t){return R(e,"POST","/v1/accounts:signInWithEmailLink",C(e,t))}async function ez(e,t){return R(e,"POST","/v1/accounts:signInWithEmailLink",C(e,t))}class eK extends eM{constructor(e,t,r,n=null){super("password",r),this._email=e,this._password=t,this._tenantId=n}static _fromEmailAndPassword(e,t){return new eK(e,t,"password")}static _fromEmailAndCode(e,t,r=null){return new eK(e,t,"emailLink",r)}toJSON(){return{email:this._email,password:this._password,signInMethod:this.signInMethod,tenantId:this._tenantId}}static fromJSON(e){let t="string"==typeof e?JSON.parse(e):e;if(t?.email&&t?.password){if("password"===t.signInMethod)return this._fromEmailAndPassword(t.email,t.password);else if("emailLink"===t.signInMethod)return this._fromEmailAndCode(t.email,t.password,t.tenantId)}return null}async _getIdTokenResponse(e){switch(this.signInMethod){case"password":return eR(e,{returnSecureToken:!0,email:this._email,password:this._password,clientType:"CLIENT_TYPE_WEB"},"signInWithPassword",eF,"EMAIL_PASSWORD_PROVIDER");case"emailLink":return e$(e,{email:this._email,oobCode:this._password});default:d(e,"internal-error")}}async _linkToIdToken(e,t){switch(this.signInMethod){case"password":return eR(e,{idToken:t,returnSecureToken:!0,email:this._email,password:this._password,clientType:"CLIENT_TYPE_WEB"},"signUpPassword",eV,"EMAIL_PASSWORD_PROVIDER");case"emailLink":return ez(e,{idToken:t,email:this._email,oobCode:this._password});default:d(e,"internal-error")}}_getReauthenticationResolver(e){return this._getIdTokenResponse(e)}}async function eH(e,t){return R(e,"POST","/v1/accounts:signInWithIdp",C(e,t))}class eG extends eM{constructor(){super(...arguments),this.pendingToken=null}static _fromParams(e){let t=new eG(e.providerId,e.signInMethod);return e.idToken||e.accessToken?(e.idToken&&(t.idToken=e.idToken),e.accessToken&&(t.accessToken=e.accessToken),e.nonce&&!e.pendingToken&&(t.nonce=e.nonce),e.pendingToken&&(t.pendingToken=e.pendingToken)):e.oauthToken&&e.oauthTokenSecret?(t.accessToken=e.oauthToken,t.secret=e.oauthTokenSecret):d("argument-error"),t}toJSON(){return{idToken:this.idToken,accessToken:this.accessToken,secret:this.secret,n
7once:this.nonce,pendingToken:this.pendingToken,providerId:this.providerId,signInMethod:this.signInMethod}}static fromJSON(e){let{providerId:t,signInMethod:r,...n}="string"==typeof e?JSON.parse(e):e;if(!t||!r)return null;let i=new eG(t,r);return i.idToken=n.idToken||void 0,i.accessToken=n.accessToken||void 0,i.secret=n.secret,i.nonce=n.nonce,i.pendingToken=n.pendingToken||null,i}_getIdTokenResponse(e){return eH(e,this.buildRequest())}_linkToIdToken(e,t){let r=this.buildRequest();return r.idToken=t,eH(e,r)}_getReauthenticationResolver(e){let t=this.buildRequest();return t.autoCreate=!1,eH(e,t)}buildRequest(){let e={requestUri:"http://localhost",returnSecureToken:!0};if(this.pendingToken)e.pendingToken=this.pendingToken;else{let t={};this.idToken&&(t.id_token=this.idToken),this.accessToken&&(t.access_token=this.accessToken),this.secret&&(t.oauth_token_secret=this.secret),t.providerId=this.providerId,this.nonce&&!this.pendingToken&&(t.nonce=this.nonce),e.postBody=(0,s.Am)(t)}return e}}async function eW(e,t){return k(e,"POST","/v1/accounts:sendVerificationCode",C(e,t))}async function eQ(e,t){return R(e,"POST","/v1/accounts:signInWithPhoneNumber",C(e,t))}async function eJ(e,t){let r=await R(e,"POST","/v1/accounts:signInWithPhoneNumber",C(e,t));if(r.temporaryProof)throw P(e,"account-exists-with-different-credential",r);return r}let eX={USER_NOT_FOUND:"user-not-found"};async function eY(e,t){return R(e,"POST","/v1/accounts:signInWithPhoneNumber",C(e,{...t,operation:"REAUTH"}),eX)}class eZ extends eM{constructor(e){super("phone","phone"),this.params=e}static _fromVerification(e,t){return new eZ({verificationId:e,verificationCode:t})}static _fromTokenResponse(e,t){return new eZ({phoneNumber:e,temporaryProof:t})}_getIdTokenResponse(e){return eQ(e,this._makeVerificationRequest())}_linkToIdToken(e,t){return eJ(e,{idToken:t,...this._makeVerificationRequest()})}_getReauthenticationResolver(e){return eY(e,this._makeVerificationRequest())}_makeVerificationRequest(){let{temporaryProof:e,phoneNumber:t,verificationId:r,verificationCode:n}=this.params;return e&&t?{temporaryProof:e,phoneNumber:t}:{sessionInfo:r,code:n}}toJSON(){let e={providerId:this.providerId};return this.params.phoneNumber&&(e.phoneNumber=this.params.phoneNumber),this.params.temporaryProof&&(e.temporaryProof=this.params.temporaryProof),this.params.verificationCode&&(e.verificationCode=this.params.verificationCode),this.params.verificationId&&(e.verificationId=this.params.verificationId),e}static fromJSON(e){"string"==typeof e&&(e=JSON.parse(e));let{verificationId:t,verificationCode:r,phoneNumber:n,temporaryProof:i}=e;return r||t||n||i?new eZ({verificationId:t,verificationCode:r,phoneNumber:n,temporaryProof:i}):null}}class e0{constructor(e){const t=(0,s.I9)((0,s.hp)(e)),r=t.apiKey??null,n=t.oobCode??null,i=function(e){switch(e){case"recoverEmail":return"RECOVER_EMAIL";case"resetPassword":return"PASSWORD_RESET";case"signIn":return"EMAIL_SIGNIN";case"verifyEmail":return"VERIFY_EMAIL";case"verifyAndChangeEmail":return"VERIFY_AND_CHANGE_EMAIL";case"revertSecondFactorAddition":return"REVERT_SECOND_FACTOR_ADDITION";default:return null}}(t.mode??null);y(r&&n&&i,"argument-error"),this.apiKey=r,this.operation=i,this.code=n,this.continueUrl=t.continueUrl??null,this.languageCode=t.lang??null,this.tenantId=t.tenantId??null}static parseLink(e){let t,r,n,i=(r=(t=(0,s.I9)((0,s.hp)(e)).link)?(0,s.I9)((0,s.hp)(t)).deep_link_id:null,((n=(0,s.I9)((0,s.hp)(e)).deep_link_id)?(0,s.I9)((0,s.hp)(n)).link:null)||n||r||t||e);try{return new e0(i)}catch{return null}}}class e1{constructor(){this.providerId=e1.PROVIDER_ID}static credential(e,t){return eK._fromEmailAndPassword(e,t)}static credentialWithLink(e,t){let r=e0.parseLink(t);return y(r,"argument-error"),eK._fromEmailAndCode(e,r.code,r.tenantId)}}e1.PROVIDER_ID="password",e1.EMAIL_PASSWORD_SIGN_IN_METHOD="password",e1.EMAIL_LINK_SIGN_IN_METHOD="emailLink";class e2{constructor(e){this.providerId=e,this.defaultLanguageCode=null,this.customParameters={}}setDefaultLanguage(e){this.defaultLanguageCode=e}setCustomParameters(e){return this.customParameters=e,this}getCustomParameters(){return this.customParameters}}class e6 extends e2{constructor(){super(...arguments),this.scopes=[]}addScope(e){return this.scopes.includes(e)||this.scopes.push(e),this}getScopes(){return[...this.scopes]}}class e3 extends e6{constructor(){super("facebook.com")}static credential(e){return eG._fromParams({providerId:e3.PROVIDER_ID,signInMethod:e3.FACEBOOK_SIGN_IN_METHOD,accessToken:e})}static credentialFromResult(e){return e3.credentialFromTaggedObject(e)}static credentialFromError(e){return e3.credentialFromTaggedObject(e.customData||{})}
7static credentialFromTaggedObject({_tokenResponse:e}){if(!e||!("oauthAccessToken"in e)||!e.oauthAccessToken)return null;try{return e3.credential(e.oauthAccessToken)}catch{return null}}}e3.FACEBOOK_SIGN_IN_METHOD="facebook.com",e3.PROVIDER_ID="facebook.com";class e5 extends e6{constructor(){super("google.com"),this.addScope("profile")}static credential(e,t){return eG._fromParams({providerId:e5.PROVIDER_ID,signInMethod:e5.GOOGLE_SIGN_IN_METHOD,idToken:e,accessToken:t})}static credentialFromResult(e){return e5.credentialFromTaggedObject(e)}static credentialFromError(e){return e5.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;let{oauthIdToken:t,oauthAccessToken:r}=e;if(!t&&!r)return null;try{return e5.credential(t,r)}catch{return null}}}e5.GOOGLE_SIGN_IN_METHOD="google.com",e5.PROVIDER_ID="google.com";class e8 extends e6{constructor(){super("github.com")}static credential(e){return eG._fromParams({providerId:e8.PROVIDER_ID,signInMethod:e8.GITHUB_SIGN_IN_METHOD,accessToken:e})}static credentialFromResult(e){return e8.credentialFromTaggedObject(e)}static credentialFromError(e){return e8.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e||!("oauthAccessToken"in e)||!e.oauthAccessToken)return null;try{return e8.credential(e.oauthAccessToken)}catch{return null}}}e8.GITHUB_SIGN_IN_METHOD="github.com",e8.PROVIDER_ID="github.com";class e4 extends e6{constructor(){super("twitter.com")}static credential(e,t){return eG._fromParams({providerId:e4.PROVIDER_ID,signInMethod:e4.TWITTER_SIGN_IN_METHOD,oauthToken:e,oauthTokenSecret:t})}static credentialFromResult(e){return e4.credentialFromTaggedObject(e)}static credentialFromError(e){return e4.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;let{oauthAccessToken:t,oauthTokenSecret:r}=e;if(!t||!r)return null;try{return e4.credential(t,r)}catch{return null}}}async function e9(e,t){return R(e,"POST","/v1/accounts:signUp",C(e,t))}e4.TWITTER_SIGN_IN_METHOD="twitter.com",e4.PROVIDER_ID="twitter.com";class e7{constructor(e){this.user=e.user,this.providerId=e.providerId,this._tokenResponse=e._tokenResponse,this.operationType=e.operationType}static async _fromIdTokenResponse(e,t,r,n=!1){return new e7({user:await ee._fromIdTokenResponse(e,r,n),providerId:te(r),_tokenResponse:r,operationType:t})}static async _forOperation(e,t,r){return await e._updateTokensIfNecessary(r,!0),new e7({user:e,providerId:te(r),_tokenResponse:r,operationType:t})}}function te(e){return e.providerId?e.providerId:"phoneNumber"in e?"phone":null}class tt extends s.g{constructor(e,t,r,n){super(t.code,t.message),this.operationType=r,this.user=n,Object.setPrototypeOf(this,tt.prototype),this.customData={appName:e.name,tenantId:e.tenantId??void 0,_serverResponse:t.customData._serverResponse,operationType:r}}static _fromErrorAndOperation(e,t,r,n){return new tt(e,t,r,n)}}function tr(e,t,r,n){return("reauthenticate"===t?r._getReauthenticationResolver(e):r._getIdTokenResponse(e)).catch(r=>{if("auth/multi-factor-auth-required"===r.code)throw tt._fromErrorAndOperation(e,r,t,n);throw r})}async function tn(e,t,r=!1){let n=await z(e,t._linkToIdToken(e.auth,await e.getIdToken()),r);return e7._forOperation(e,"link",n)}async function ti(e,t,r=!1){let{auth:n}=e;if((0,i.xZ)(n.app))return Promise.reject(m(n));let s="reauthenticate";try{let i=await z(e,tr(n,s,t,e),r);y(i.idToken,n,"internal-error");let a=q(i.idToken);y(a,n,"internal-error");let{sub:o}=a;return y(e.uid===o,n,"user-mismatch"),e7._forOperation(e,s,i)}catch(e){throw e?.code==="auth/user-not-found"&&d(n,"user-mismatch"),e}}async function ts(e,t,r=!1){if((0,i.xZ)(e.app))return Promise.reject(m(e));let n="signIn",s=await tr(e,n,t),a=await e7._fromIdTokenResponse(e,n,s);return r||await e._updateCurrentUser(a.user),a}async function ta(e,t){return ts(e_(e),t)}async function to(e,t){return ti((0,s.Ku)(e),t)}function tl(e,t,r){y(r.url?.length>0,e,"invalid-continue-uri"),y(void 0===r.dynamicLinkDomain||r.dynamicLinkDomain.length>
70,e,"invalid-dynamic-link-domain"),y(void 0===r.linkDomain||r.linkDomain.length>0,e,"invalid-hosting-link-domain"),t.continueUrl=r.url,t.dynamicLinkDomain=r.dynamicLinkDomain,t.linkDomain=r.linkDomain,t.canHandleCodeInApp=r.handleCodeInApp,r.iOS&&(y(r.iOS.bundleId.length>0,e,"missing-ios-bundle-id"),t.iOSBundleId=r.iOS.bundleId),r.android&&(y(r.android.packageName.length>0,e,"missing-android-pkg-name"),t.androidInstallApp=r.android.installApp,t.androidMinimumVersionCode=r.android.minimumVersion,t.androidPackageName=r.android.packageName)}async function tu(e){let t=e_(e);t._getPasswordPolicyInternal()&&await t._updatePasswordPolicy()}async function th(e,t,r){let n=e_(e),i={requestType:"PASSWORD_RESET",email:t,clientType:"CLIENT_TYPE_WEB"};r&&tl(n,i,r),await eR(n,i,"getOobCode",eq,"EMAIL_PASSWORD_PROVIDER")}async function tc(e,t,r){if((0,i.xZ)(e.app))return Promise.reject(m(e));let n=e_(e),s=eR(n,{returnSecureToken:!0,email:t,password:r,clientType:"CLIENT_TYPE_WEB"},"signUpPassword",e9,"EMAIL_PASSWORD_PROVIDER"),a=await s.catch(t=>{throw"auth/password-does-not-meet-requirements"===t.code&&tu(e),t}),o=await e7._fromIdTokenResponse(n,"signIn",a);return await n._updateCurrentUser(o.user),o}function td(e,t,r){return(0,i.xZ)(e.app)?Promise.reject(m(e)):ta((0,s.Ku)(e),e1.credential(t,r)).catch(async t=>{throw"auth/password-does-not-meet-requirements"===t.code&&tu(e),t})}async function tf(e,t){let r=(0,s.Ku)(e),n={requestType:"VERIFY_EMAIL",idToken:await e.getIdToken()};t&&tl(r.auth,n,t);let{email:i}=await eB(r.auth,n);i!==e.email&&await e.reload()}async function tp(e,t){return k(e,"POST","/v1/accounts:update",t)}async function tm(e,{displayName:t,photoURL:r}){if(void 0===t&&void 0===r)return;let n=(0,s.Ku)(e),i=await n.getIdToken(),a=await z(n,tp(n.auth,{idToken:i,displayName:t,photoUrl:r,returnSecureToken:!0}));n.displayName=a.displayName||null,n.photoURL=a.photoUrl||null;let o=n.providerData.find(({providerId:e})=>"password"===e);o&&(o.displayName=n.displayName,o.photoURL=n.photoURL),await n._updateTokensIfNecessary(a)}function tg(e,t){return ty((0,s.Ku)(e),null,t)}async function ty(e,t,r){let{auth:n}=e,i={idToken:await e.getIdToken(),returnSecureToken:!0};t&&(i.email=t),r&&(i.password=r);let s=await z(e,eU(n,i));await e._updateTokensIfNecessary(s,!0)}function tv(e,t,r,n){return(0,s.Ku)(e).onAuthStateChanged(t,r,n)}function tw(e){return(0,s.Ku)(e).signOut()}async function tE(e){return(0,s.Ku)(e).delete()}function t_(e,t){return k(e,"POST","/v2/accounts/mfaEnrollment:start",C(e,t))}new WeakMap;let tI="__sak";class tT{constructor(e,t){this.storageRetriever=e,this.type=t}_isAvailable(){try{if(!this.storage)return Promise.resolve(!1);return this.storage.setItem(tI,"1"),this.storage.removeItem(tI),Promise.resolve(!0)}catch{return Promise.resolve(!1)}}_set(e,t){return this.storage.setItem(e,JSON.stringify(t)),Promise.resolve()}_get(e){let t=this.storage.getItem(e);return Promise.resolve(t?JSON.parse(t):null)}_remove(e){return this.storage.removeItem(e),Promise.resolve()}get storage(){return this.storageRetriever()}}class tb extends tT{constructor(){super(()=>window.localStorage,"LOCAL"),this.boundEventHandler=(e,t)=>this.onStorageEvent(e,t),this.listeners={},this.localCache={},this.pollTimer=null,this.fallbackToPolling=em(),this._shouldAllowMigration=!0}forAllChangedKeys(e){for(let t of Object.keys(this.listeners)){let r=this.storage.getItem(t),n=this.localCache[t];r!==n&&e(t,n,r)}}onStorageEvent(e,t=!1){if(!e.key)return void this.forAllChangedKeys((e,t,r)=>{this.notifyListeners(e,r)});let r=e.key;t?this.detachListener():this.stopPolling();let n=()=>{let e=this.storage.getItem(r);(t||this.localCache[r]!==e)&&this.notifyListeners(r,e)},i=this.storage.getItem(r);(0,s.lT)()&&10===document.documentMode&&i!==e.newValue&&e.newValue!==e.oldValue?setTimeout(n,10):n()}notifyListeners(e,t){this.localCache[e]=t;let r=this.listeners[e];if(r)for(let e of Array.from(r))e(t?JSON.parse(t):t)}startPolling(){this.stopPolling(),this.pollTimer=setInterval(()=>{this.forAllChangedKeys((e,t,r)=>{this.onStorageEvent(new StorageEvent("storage",{key:e,oldValue:t,newValue:r}),!0)})},1e3)}stopPolling(){this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=null)}attachListener(){window.addEventListener("storage",this.boundEventHandler)}detachListener(){window.removeEventListener("storage",this.boundEventHandler)}_addListener(e,t){0===Object.keys(this.listeners).length&&(this.fallbackToPolling?this.startPolling():this.attachListener()),this.listeners[e]||(this.listeners[e]=new Set,this.localCache[e]=this.storage.getItem(e)),this.listeners[e].add(t)}_removeListener(e,t){this.listeners[e]&&(this.listeners[e].delete(t),0===this.listeners[e].size&&delete this.listeners[e]),0===Object.keys(this.listeners).length&&(this.detachListener(),this.stopPolling())}async _set(e,t){await super._set(e,t),this.localCache[e]=JSON.stringify(t)}async _get(e){let t=await super._get(e);return this.localCache[e]=JSON.stringify(t),t}async _remove(e){await super._remove(e),delete this.localCache[e]}}tb.type="LOCAL";let tS=tb;function tA(e){let t=e.replace(/[\\^$.*+?()[\]{}|]/g,"\\$&"),r=RegExp(`${t}=([^;]+)`);return document.cookie.match(r)?.[1]??null}function tC(e){let t="http:"===window.location.protocol;return`${t?"__dev_":"__HOST-"}FIREBASE_${e.split(":")[3]}`}class tk{constructor(){this.type="COOKIE",this.listenerUnsubscribes=new Map}_getFinalTarget(e){let t=new URL(`${window.location.origin}/__cookies__`);return t.searchParams.set("finalTarget",e),t}async _isAvailable(){return!("boolean"==typeof isSecureContext&&!isSecureContext||"u"<typeof navigator||"u"<typeof document)&&(navigator.cookieEnabled??!0)}async _set(e,t){}async _get(e){if(!this._isAvailable())return null;let t=tC(e);if(window.cookieStore){let e=await window.cookieStore.get(t);return e?.value}return tA(t)}async _remove(e){if(!this._isAvailable()||!await this._get(e))return;let t=tC(e);document.cookie=`${t}=;Max-Age=34560000;Partitioned;Secure;SameSite=Strict;Path=/;
7Priority=High`,await fetch("/__cookies__",{method:"DELETE"}).catch(()=>void 0)}_addListener(e,t){if(!this._isAvailable())return;let r=tC(e);if(window.cookieStore){let e=e=>{let n=e.changed.find(e=>e.name===r);n&&t(n.value),e.deleted.find(e=>e.name===r)&&t(null)};return this.listenerUnsubscribes.set(t,()=>window.cookieStore.removeEventListener("change",e)),window.cookieStore.addEventListener("change",e)}let n=tA(r),i=setInterval(()=>{let e=tA(r);e!==n&&(t(e),n=e)},1e3);this.listenerUnsubscribes.set(t,()=>clearInterval(i))}_removeListener(e,t){let r=this.listenerUnsubscribes.get(t);r&&(r(),this.listenerUnsubscribes.delete(t))}}tk.type="COOKIE";class tN extends tT{constructor(){super(()=>window.sessionStorage,"SESSION")}_addListener(e,t){}_removeListener(e,t){}}tN.type="SESSION";let tR=tN;class tD{constructor(e){this.eventTarget=e,this.handlersMap={},this.boundEventHandler=this.handleEvent.bind(this)}static _getInstance(e){let t=this.receivers.find(t=>t.isListeningto(e));if(t)return t;let r=new tD(e);return this.receivers.push(r),r}isListeningto(e){return this.eventTarget===e}async handleEvent(e){let{eventId:t,eventType:r,data:n}=e.data,i=this.handlersMap[r];if(!i?.size)return;e.ports[0].postMessage({status:"ack",eventId:t,eventType:r});let s=Array.from(i).map(async t=>t(e.origin,n)),a=await Promise.all(s.map(async e=>{try{let t=await e;return{fulfilled:!0,value:t}}catch(e){return{fulfilled:!1,reason:e}}}));e.ports[0].postMessage({status:"done",eventId:t,eventType:r,response:a})}_subscribe(e,t){0===Object.keys(this.handlersMap).length&&this.eventTarget.addEventListener("message",this.boundEventHandler),this.handlersMap[e]||(this.handlersMap[e]=new Set),this.handlersMap[e].add(t)}_unsubscribe(e,t){this.handlersMap[e]&&t&&this.handlersMap[e].delete(t),t&&0!==this.handlersMap[e].size||delete this.handlersMap[e],0===Object.keys(this.handlersMap).length&&this.eventTarget.removeEventListener("message",this.boundEventHandler)}}function tO(e="",t=10){let r="";for(let e=0;e<t;e++)r+=Math.floor(10*Math.random());return e+r}tD.receivers=[];class tP{constructor(e){this.target=e,this.handlers=new Set}removeMessageHandler(e){e.messageChannel&&(e.messageChannel.port1.removeEventListener("message",e.onMessage),e.messageChannel.port1.close()),this.handlers.delete(e)}async _send(e,t,r=50){let n,i,s="u">typeof MessageChannel?new MessageChannel:null;if(!s)throw Error("connection_unavailable");return new Promise((a,o)=>{let l=tO("",20);s.port1.start();let u=setTimeout(()=>{o(Error("unsupported_event"))},r);i={messageChannel:s,onMessage(e){if(e.data.eventId===l)switch(e.data.status){case"ack":clearTimeout(u),n=setTimeout(()=>{o(Error("timeout"))},3e3);break;case"done":clearTimeout(n),a(e.data.response);break;default:clearTimeout(u),clearTimeout(n),o(Error("invalid_response"))}}},this.handlers.add(i),s.port1.addEventListener("message",i.onMessage),this.target.postMessage({eventType:e,eventId:l,data:t},[s.port2])}).finally(()=>{i&&this.removeMessageHandler(i)})}}function tL(){return window}function tx(){return void 0!==tL().WorkerGlobalScope&&"function"==typeof tL().importScripts}async function tM(){if(!navigator?.serviceWorker)return null;try{return(await navigator.serviceWorker.ready).active}catch{return null}}let tU="firebaseLocalStorageDb",tV="firebaseLocalStorage",tF="fbase_key";class tj{constructor(e){this.request=e}toPromise(){return new Promise((e,t)=>{this.request.addEventListener("success",()=>{e(this.request.result)}),this.request.addEventListener("error",()=>{t(this.request.error)})})}}function tB(e,t){return e.transaction([tV],t?"readwrite":"readonly").objectStore(tV)}
7function tq(){let e=indexedDB.open(tU,1);return new Promise((t,r)=>{e.addEventListener("error",()=>{r(e.error)}),e.addEventListener("upgradeneeded",()=>{let t=e.result;try{t.createObjectStore(tV,{keyPath:tF})}catch(e){r(e)}}),e.addEventListener("success",async()=>{let r=e.result;r.objectStoreNames.contains(tV)?t(r):(r.close(),await new tj(indexedDB.deleteDatabase(tU)).toPromise(),t(await tq()))})})}async function t$(e,t,r){return new tj(tB(e,!0).put({[tF]:t,value:r})).toPromise()}async function tz(e,t){let r=tB(e,!1).get(t),n=await new tj(r).toPromise();return void 0===n?null:n.value}function tK(e,t){return new tj(tB(e,!0).delete(t)).toPromise()}class tH{constructor(){this.type="LOCAL",this._shouldAllowMigration=!0,this.listeners={},this.localCache={},this.pollTimer=null,this.pendingWrites=0,this.receiver=null,this.sender=null,this.serviceWorkerReceiverAvailable=!1,this.activeServiceWorker=null,this._workerInitializationPromise=this.initializeServiceWorkerMessaging().then(()=>{},()=>{})}async _openDb(){return this.db||(this.db=await tq()),this.db}async _withRetries(e){let t=0;for(;;)try{let t=await this._openDb();return await e(t)}catch(e){if(t++>3)throw e;this.db&&(this.db.close(),this.db=void 0)}}async initializeServiceWorkerMessaging(){return tx()?this.initializeReceiver():this.initializeSender()}async initializeReceiver(){this.receiver=tD._getInstance(tx()?self:null),this.receiver._subscribe("keyChanged",async(e,t)=>({keyProcessed:(await this._poll()).includes(t.key)})),this.receiver._subscribe("ping",async(e,t)=>["keyChanged"])}async initializeSender(){if(this.activeServiceWorker=await tM(),!this.activeServiceWorker)return;this.sender=new tP(this.activeServiceWorker);let e=await this.sender._send("ping",{},800);e&&e[0]?.fulfilled&&e[0]?.value.includes("keyChanged")&&(this.serviceWorkerReceiverAvailable=!0)}async notifyServiceWorker(e){if(this.sender&&this.activeServiceWorker&&(navigator?.serviceWorker?.controller||null)===this.activeServiceWorker)try{await this.sender._send("keyChanged",{key:e},this.serviceWorkerReceiverAvailable?800:50)}catch{}}async _isAvailable(){try{if(!indexedDB)return!1;let e=await tq();return await t$(e,tI,"1"),await tK(e,tI),!0}catch{}return!1}async _withPendingWrite(e){this.pendingWrites++;try{await e()}finally{this.pendingWrites--}}async _set(e,t){return this._withPendingWrite(async()=>(await this._withRetries(r=>t$(r,e,t)),this.localCache[e]=t,this.notifyServiceWorker(e)))}async _get(e){let t=await this._withRetries(t=>tz(t,e));return this.localCache[e]=t,t}async _remove(e){return this._withPendingWrite(async()=>(await this._withRetries(t=>tK(t,e)),delete this.localCache[e],this.notifyServiceWorker(e)))}async _poll(){let e=await this._withRetries(e=>new tj(tB(e,!1).getAll()).toPromise());if(!e||0!==this.pendingWrites)return[];let t=[],r=new Set;if(0!==e.length)for(let{fbase_key:n,value:i}of e)r.add(n),JSON.stringify(this.localCache[n])!==JSON.stringify(i)&&(this.notifyListeners(n,i),t.push(n));for(let e of Object.keys(this.localCache))this.localCache[e]&&!r.has(e)&&(this.notifyListeners(e,null),t.push(e));return t}notifyListeners(e,t){this.localCache[e]=t;let r=this.listeners[e];if(r)for(let e of Array.from(r))e(t)}startPolling(){this.stopPolling(),this.pollTimer=setInterval(async()=>this._poll(),800)}stopPolling(){this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=null)}_addListener(e,t){0===Object.keys(this.listeners).length&&this.startPolling(),this.listeners[e]||(this.listeners[e]=new Set,this._get(e)),this.listeners[e].add(t)}_removeListener(e,t){this.listeners[e]&&(this.listeners[e].delete(t),0===this.listeners[e].size&&delete this.listeners[e]),0===Object.keys(this.listeners).length&&this.stopPolling()}}tH.type="LOCAL";let tG=tH;function tW(e,t){return k(e,"POST","/v2/accounts/mfaSignIn:start",C(e,t))}eb("rcb"),new _(3e4,6e4);let tQ="recaptcha";async function tJ(e,t,r){if(!e._getRecaptchaConfig())try{await eD(e)}catch(e){console.log("Failed to initialize reCAPTCHA Enterprise config. Triggering the reCAPTCHA v2 verification.")}try{let n;if(n="string"==typeof t?{phoneNumber:t}
7:t,"session"in n){let t=n.session;if("phoneNumber"in n){y("enroll"===t.type,e,"internal-error");let i={idToken:t.credential,phoneEnrollmentInfo:{phoneNumber:n.phoneNumber,clientType:"CLIENT_TYPE_WEB"}},s=async(e,t)=>{if(t.phoneEnrollmentInfo.captchaResponse===eC){y(r?.type===tQ,e,"argument-error");let n=await tX(e,t,r);return t_(e,n)}return t_(e,t)},a=eR(e,i,"mfaSmsEnrollment",s,"PHONE_PROVIDER");return(await a.catch(e=>Promise.reject(e))).phoneSessionInfo.sessionInfo}{y("signin"===t.type,e,"internal-error");let i=n.multiFactorHint?.uid||n.multiFactorUid;y(i,e,"missing-multi-factor-info");let s={mfaPendingCredential:t.credential,mfaEnrollmentId:i,phoneSignInInfo:{clientType:"CLIENT_TYPE_WEB"}},a=async(e,t)=>{if(t.phoneSignInInfo.captchaResponse===eC){y(r?.type===tQ,e,"argument-error");let n=await tX(e,t,r);return tW(e,n)}return tW(e,t)},o=eR(e,s,"mfaSmsSignIn",a,"PHONE_PROVIDER");return(await o.catch(e=>Promise.reject(e))).phoneResponseInfo.sessionInfo}}{let t={phoneNumber:n.phoneNumber,clientType:"CLIENT_TYPE_WEB"},i=async(e,t)=>{if(t.captchaResponse===eC){y(r?.type===tQ,e,"argument-error");let n=await tX(e,t,r);return eW(e,n)}return eW(e,t)},s=eR(e,t,"sendVerificationCode",i,"PHONE_PROVIDER");return(await s.catch(e=>Promise.reject(e))).sessionInfo}}finally{r?._reset()}}async function tX(e,t,r){y(r.type===tQ,e,"argument-error");let n=await r.verify();y("string"==typeof n,e,"argument-error");let i={...t};if("phoneEnrollmentInfo"in i){let e=i.phoneEnrollmentInfo.phoneNumber,t=i.phoneEnrollmentInfo.captchaResponse,r=i.phoneEnrollmentInfo.clientType,s=i.phoneEnrollmentInfo.recaptchaVersion;return Object.assign(i,{phoneEnrollmentInfo:{phoneNumber:e,recaptchaToken:n,captchaResponse:t,clientType:r,recaptchaVersion:s}}),i}if(!("phoneSignInInfo"in i))return Object.assign(i,{recaptchaToken:n}),i;{let e=i.phoneSignInInfo.captchaResponse,t=i.phoneSignInInfo.clientType,r=i.phoneSignInInfo.recaptchaVersion;return Object.assign(i,{phoneSignInInfo:{recaptchaToken:n,captchaResponse:e,clientType:t,recaptchaVersion:r}}),i}}class tY{constructor(e){this.providerId=tY.PROVIDER_ID,this.auth=e_(e)}verifyPhoneNumber(e,t){return tJ(this.auth,e,(0,s.Ku)(t))}static credential(e,t){return eZ._fromVerification(e,t)}static credentialFromResult(e){return tY.credentialFromTaggedObject(e)}static credentialFromError(e){return tY.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;let{phoneNumber:t,temporaryProof:r}=e;return t&&r?eZ._fromTokenResponse(t,r):null}}function tZ(e,t){return t?er(t):(y(e._popupRedirectResolver,e,"argument-error"),e._popupRedirectResolver)}tY.PROVIDER_ID="phone",tY.PHONE_SIGN_IN_METHOD="phone";class t0 extends eM{constructor(e){super("custom","custom"),this.params=e}_getIdTokenResponse(e){return eH(e,this._buildIdpRequest())}_linkToIdToken(e,t){return eH(e,this._buildIdpRequest(t))}_getReauthenticationResolver(e){return eH(e,this._buildIdpRequest())}_buildIdpRequest(e){let t={requestUri:this.params.requestUri,sessionId:this.params.sessionId,postBody:this.params.postBody,tenantId:this.params.tenantId,pendingToken:this.params.pendingToken,returnSecureToken:!0,returnIdpCredential:!0};return e&&(t.idToken=e),t}}function t1(e){return ts(e.auth,new t0(e),e.bypassAuthState)}function t2(e){let{auth:t,user:r}=e;return y(r,t,"internal-error"),ti(r,new t0(e),e.bypassAuthState)}async function t6(e){let{auth:t,user:r}=e;return y(r,t,"internal-error"),tn(r,new t0(e),e.bypassAuthState)}class t3{constructor(e,t,r,n,i=!1){this.auth=e,this.resolver=r,this.user=n,this.bypassAuthState=i,this.pendingPromise=null,this.eventManager=null,this.filter=Array.isArray(t)?t:[t]}execute(){return new Promise(async(e,t)=>{this.pendingPromise={resolve:e,reject:t};try{this.eventManager=await this.resolver._initialize(this.auth),await this.onExecution(),this.eventManager.registerConsumer(this)}catch(e){this.reject(e)}})}async onAuthEvent(e){let{urlResponse:t,sessionId:r,postBody:n,tenantId:i,error:s,type:a}=e;if(s)return void this.reject(s);let o={auth:this.auth,requestUri:t,sessionId:r,tenantId:i||void 0,postBody:n||void 0,user:this.user,bypassAuthState:this.bypassAuthState};try{this.resolve(await this.getIdpTask(a)(o))}catch(e){this.reject(e)}}onError(e){this.reject(e)}getIdpTask(e){switch(e){case"signInViaPopup":case"signInViaRedirect":return t1;case"linkViaPopup":case"linkViaRedirect":return t6;case"reauthViaPopup":case"reauthViaRedirect":return t2;default:d(this.auth,"internal-error")}}resolve(e){var t,r;t=this.pendingPromise,r="Pending promise was never set",t||v(r),this.pendingPromise.resolve(e),this.unregisterAndCleanUp()}reject(e){var t,r;t=this.pendingPromise,r="Pending promise was never set",t||v(r),this.pendingPromise.reject(e),this.unregisterAndCleanUp()}unregisterAndCleanUp(){this.eventManager&&this.eventManager.unregisterConsumer(this),this.pendingPromise=null,this.cleanUp()}}let t5=new _(2e3,1e4);async function t8(e,t,r){if((0,i.xZ)(e.app))return Promise.reject(f(e,"operation-not-supported-in-this-environment"));let n=e_(e);
7if(!(t instanceof e2))throw e2.name!==t.constructor.name&&d(e,"argument-error"),p(e,"argument-error",`Type of ${t.constructor.name} does not match expected instance.Did you pass a reference from a different Auth SDK?`);let s=tZ(n,r);return new t4(n,"signInViaPopup",t,s).executeNotNull()}class t4 extends t3{constructor(e,t,r,n,i){super(e,t,n,i),this.provider=r,this.authWindow=null,this.pollId=null,t4.currentPopupAction&&t4.currentPopupAction.cancel(),t4.currentPopupAction=this}async executeNotNull(){let e=await this.execute();return y(e,this.auth,"internal-error"),e}async onExecution(){var e,t;e=1===this.filter.length,t="Popup operations only handle one event",e||v(t);let r=tO();this.authWindow=await this.resolver._openPopup(this.auth,this.provider,this.filter[0],r),this.authWindow.associatedEvent=r,this.resolver._originValidation(this.auth).catch(e=>{this.reject(e)}),this.resolver._isIframeWebStorageSupported(this.auth,e=>{e||this.reject(f(this.auth,"web-storage-unsupported"))}),this.pollUserCancellation()}get eventId(){return this.authWindow?.associatedEvent||null}cancel(){this.reject(f(this.auth,"cancelled-popup-request"))}cleanUp(){this.authWindow&&this.authWindow.close(),this.pollId&&window.clearTimeout(this.pollId),this.authWindow=null,this.pollId=null,t4.currentPopupAction=null}pollUserCancellation(){let e=()=>{if(this.authWindow?.window?.closed){this.pollId=window.setTimeout(()=>{this.pollId=null,this.reject(f(this.auth,"popup-closed-by-user"))},8e3);return}this.pollId=window.setTimeout(e,t5.get())};e()}}t4.currentPopupAction=null;let t9=new Map;class t7 extends t3{constructor(e,t,r=!1){super(e,["signInViaRedirect","linkViaRedirect","reauthViaRedirect","unknown"],t,void 0,r),this.eventId=null}async execute(){let e=t9.get(this.auth._key());if(!e){try{let t=await re(this.resolver,this.auth)?await super.execute():null;e=()=>Promise.resolve(t)}catch(t){e=()=>Promise.reject(t)}t9.set(this.auth._key(),e)}return this.bypassAuthState||t9.set(this.auth._key(),()=>Promise.resolve(null)),e()}async onAuthEvent(e){if("signInViaRedirect"===e.type)return super.onAuthEvent(e);if("unknown"===e.type)return void this.resolve(null);if(e.eventId){let t=await this.auth._redirectUserForId(e.eventId);if(t)return this.user=t,super.onAuthEvent(e);this.resolve(null)}}async onExecution(){}cleanUp(){}}async function re(e,t){var r;let n=ei("pendingRedirect",(r=t).config.apiKey,r.name),i=er(e._redirectPersistence);if(!await i._isAvailable())return!1;let s=await i._get(n)==="true";return await i._remove(n),s}function rt(e,t){t9.set(e._key(),t)}async function rr(e,t,r=!1){if((0,i.xZ)(e.app))return Promise.reject(m(e));let n=e_(e),s=tZ(n,t),a=new t7(n,s,r),o=await a.execute();return o&&!r&&(delete o.user._redirectEventId,await n._persistUserIfCurrent(o.user),await n._setRedirectUser(null,t)),o}class rn{constructor(e){this.auth=e,this.cachedEventUids=new Set,this.consumers=new Set,this.queuedRedirectEvent=null,this.hasHandledPotentialRedirect=!1,this.lastProcessedEventTime=Date.now()}registerConsumer(e){this.consumers.add(e),this.queuedRedirectEvent&&this.isEventForConsumer(this.queuedRedirectEvent,e)&&(this.sendToConsumer(this.queuedRedirectEvent,e),this.saveEventToCache(this.queuedRedirectEvent),this.queuedRedirectEvent=null)}unregisterConsumer(e){this.consumers.delete(e)}onEvent(e){if(this.hasEventBeenHandled(e))return!1;let t=!1;return this.consumers.forEach(r=>{this.isEventForConsumer(e,r)&&(t=!0,this.sendToConsumer(e,r),this.saveEventToCache(e))}),this.hasHandledPotentialRedirect||!function(e){switch(e.type){case"signInViaRedirect":case"linkViaRedirect":case"reauthViaRedirect":return!0;case"unknown":return rs(e);default:return!1}}(e)||(this.hasHandledPotentialRedirect=!0,t||(this.queuedRedirectEvent=e,t=!0)),t}sendToConsumer(e,t){if(e.error&&!rs(e)){let r=e.error.code?.split("auth/")[1]||"internal-error";t.onError(f(this.auth,r))}else t.onAuthEvent(e)}isEventForConsumer(e,t){let r=null===t.eventId||!!e.eventId&&e.eventId===t.eventId;return t.filter.includes(e.type)&&r}hasEventBeenHandled(e){return Date.now()-this.lastProcessedEventTime>=6e5&&this.cachedEventUids.clear(),this.cachedEventUids.has(ri(e))}saveEventToCache(e){this.cachedEventUids.add(ri(e)),this.lastProcessedEventTime=
7Date.now()}}function ri(e){return[e.type,e.eventId,e.sessionId,e.tenantId].filter(e=>e).join("-")}function rs({type:e,error:t}){return"unknown"===e&&t?.code==="auth/no-auth-event"}async function ra(e,t={}){return k(e,"GET","/v1/projects",t)}let ro=/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/,rl=/^https?/;async function ru(e){if(e.config.emulator)return;let{authorizedDomains:t}=await ra(e);for(let e of t)try{if(function(e){let t=w(),{protocol:r,hostname:n}=new URL(t);if(e.startsWith("chrome-extension://")){let i=new URL(e);return""===i.hostname&&""===n?"chrome-extension:"===r&&e.replace("chrome-extension://","")===t.replace("chrome-extension://",""):"chrome-extension:"===r&&i.hostname===n}if(!rl.test(r))return!1;if(ro.test(e))return n===e;let i=e.replace(/\./g,"\\.");return RegExp("^(.+\\."+i+"|"+i+")$","i").test(n)}(e))return}catch{}d(e,"unauthorized-domain")}let rh=new _(3e4,6e4);function rc(){let e=tL().___jsl;if(e?.H){for(let t of Object.keys(e.H))if(e.H[t].r=e.H[t].r||[],e.H[t].L=e.H[t].L||[],e.H[t].r=[...e.H[t].L],e.CP)for(let t=0;t<e.CP.length;t++)e.CP[t]=null}}let rd=null,rf=new _(5e3,15e3),rp={style:{position:"absolute",top:"-100px",width:"1px",height:"1px"},"aria-hidden":"true",tabindex:"-1"},rm=new Map([["identitytoolkit.googleapis.com","p"],["staging-identitytoolkit.sandbox.googleapis.com","s"],["test-identitytoolkit.sandbox.googleapis.com","t"]]);async function rg(e){let t,r,n,a,o,l=await (rd=rd||new Promise((t,r)=>{function n(){rc(),gapi.load("gapi.iframes",{callback:()=>{t(gapi.iframes.getContext())},ontimeout:()=>{rc(),r(f(e,"network-request-failed"))},timeout:rh.get()})}if(tL().gapi?.iframes?.Iframe)t(gapi.iframes.getContext());else if(tL().gapi?.load)n();else{var i;let t=eb("iframefcb");return tL()[t]=()=>{gapi.load?n():r(f(e,"network-request-failed"))},(i=`${eT.gapiScript}?onload=${t}`,eT.loadJS(i)).catch(e=>r(e))}}).catch(e=>{throw rd=null,e})),u=tL().gapi;return y(u,e,"internal-error"),l.open({where:document.body,url:(y((t=e.config).authDomain,e,"auth-domain-config-required"),r=t.emulator?I(t,"emulator/auth/iframe"):`https://${e.config.authDomain}/__/auth/iframe`,n={apiKey:t.apiKey,appName:e.name,v:i.MF},(a=rm.get(e.config.apiHost))&&(n.eid=a),(o=e._getFrameworks()).length&&(n.fw=o.join(",")),`${r}?${(0,s.Am)(n).slice(1)}`),messageHandlersFilter:u.iframes.CROSS_ORIGIN_IFRAMES_FILTER,attributes:rp,dontclear:!0},t=>new Promise(async(r,n)=>{await t.restyle({setHideOnLeave:!1});let i=f(e,"network-request-failed"),s=tL().setTimeout(()=>{n(i)},rf.get());function a(){tL().clearTimeout(s),r(t)}t.ping(a).then(a,()=>{n(i)})}))}let ry={location:"yes",resizable:"yes",statusbar:"yes",toolbar:"no"};class rv{constructor(e){this.window=e,this.associatedEvent=null}close(){if(this.window)try{this.window.close()}catch(e){}}}let rw=encodeURIComponent("fac");async function rE(e,t,r,n,a,o){y(e.config.authDomain,e,"auth-domain-config-required"),y(e.config.apiKey,e,"invalid-api-key");let l={apiKey:e.config.apiKey,appName:e.name,authType:r,redirectUrl:n,v:i.MF,eventId:a};if(t instanceof e2)for(let[r,n]of(t.setDefaultLanguage(e.languageCode),l.providerId=t.providerId||"",(0,s.Im)(t.getCustomParameters())||(l.customParameters=JSON.stringify(t.getCustomParameters())),Object.entries(o||{})))l[r]=n;if(t instanceof e6){let e=t.getScopes().filter(e=>""!==e);e.length>0&&(l.scopes=e.join(","))}for(let t of(e.tenantId&&(l.tid=e.tenantId),Object.keys(l)))void 0===l[t]&&delete l[t];let u=await e._getAppCheckToken(),h=u?`#${rw}=${encodeURIComponent(u)}`:"";return`${function({config:e}){return e.emulator?I(e,"emulator/auth/handler"):`https://${e.authDomain}/__/auth/handler`}(e)}?${(0,s.Am)(l).slice(1)}${h}`}let r_="webStorageSupport";class rI{constructor(){this.eventManagers={},this.iframes={},this.originValidationPromises={},this._redirectPersistence=tR,this._completeRedirectFn=rr,this._overrideRedirectResult=rt}async _openPopup(e,t,r,n){var i,a;i=this.eventManagers[e._key()]?.manager,a="_initialize() not called before _openPopup()",i||v(a);let o=await rE(e,t,r,w(),n);return function(e,t,r,n=500,i=600){let a=Math.max((window.screen.availHeight-i)/2,0).toString(),o=Math.max((window.screen.availWi
7dth-n)/2,0).toString(),l="",u={...ry,width:n.toString(),height:i.toString(),top:a,left:o},h=(0,s.ZQ)().toLowerCase();r&&(l=eu(h)?"_blank":r),eo(h)&&(t=t||"http://localhost",u.scrollbars="yes");let c=Object.entries(u).reduce((e,[t,r])=>`${e}${t}=${r},`,"");if(function(e=(0,s.ZQ)()){return ep(e)&&!!window.navigator?.standalone}(h)&&"_self"!==l){var d,f;let e,r;return d=t||"",f=l,(e=document.createElement("a")).href=d,e.target=f,(r=document.createEvent("MouseEvent")).initMouseEvent("click",!0,!0,window,1,0,0,0,0,!1,!1,!1,!1,1,null),e.dispatchEvent(r),new rv(null)}let p=window.open(t||"",l,c);y(p,e,"popup-blocked");try{p.focus()}catch(e){}return new rv(p)}(e,o,tO())}async _openRedirect(e,t,r,n){var i;return await this._originValidation(e),i=await rE(e,t,r,w(),n),tL().location.href=i,new Promise(()=>{})}_initialize(e){let t=e._key();if(this.eventManagers[t]){var r;let{manager:e,promise:n}=this.eventManagers[t];return e?Promise.resolve(e):(r="If manager is not set, promise should be",n||v(r),n)}let n=this.initAndGetManager(e);return this.eventManagers[t]={promise:n},n.catch(()=>{delete this.eventManagers[t]}),n}async initAndGetManager(e){let t=await rg(e),r=new rn(e);return t.register("authEvent",t=>(y(t?.authEvent,e,"invalid-auth-event"),{status:r.onEvent(t.authEvent)?"ACK":"ERROR"}),gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER),this.eventManagers[e._key()]={manager:r},this.iframes[e._key()]=t,r}_isIframeWebStorageSupported(e,t){this.iframes[e._key()].send(r_,{type:r_},r=>{let n=r?.[0]?.[r_];void 0!==n&&t(!!n),d(e,"internal-error")},gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER)}_originValidation(e){let t=e._key();return this.originValidationPromises[t]||(this.originValidationPromises[t]=ru(e)),this.originValidationPromises[t]}get _shouldInitProactively(){return em()||el()||ep()}}let rT=rI;class rb{constructor(e){this.factorId=e}_process(e,t,r){switch(t.type){case"enroll":return this._finalizeEnroll(e,t.credential,r);case"signin":return this._finalizeSignIn(e,t.credential);default:return v("unexpected MultiFactorSessionType")}}}class rS extends rb{constructor(e){super("phone"),this.credential=e}static _fromCredential(e){return new rS(e)}_finalizeEnroll(e,t,r){return k(e,"POST","/v2/accounts/mfaEnrollment:finalize",C(e,{idToken:t,displayName:r,phoneVerificationInfo:this.credential._makeVerificationRequest()}))}_finalizeSignIn(e,t){return k(e,"POST","/v2/accounts/mfaSignIn:finalize",C(e,{mfaPendingCredential:t,phoneVerificationInfo:this.credential._makeVerificationRequest()}))}}class rA{static assertion(e){return rS._fromCredential(e)}}rA.FACTOR_ID="phone";class rC{static assertionForEnrollment(e,t){return rk._fromSecret(e,t)}static assertionForSignIn(e,t){return rk._fromEnrollmentId(e,t)}static async generateSecret(e){var t;y(void 0!==e.user?.auth,"internal-error");let r=await k(t=e.user.auth,"POST","/v2/accounts/mfaEnrollment:start",C(t,{idToken:e.credential,totpEnrollmentInfo:{}}));return rN._fromStartTotpMfaEnrollmentResponse(r,e.user.auth)}}rC.FACTOR_ID="totp";class rk extends rb{constructor(e,t,r){super("totp"),this.otp=e,this.enrollmentId=t,this.secret=r}static _fromSecret(e,t){return new rk(t,void 0,e)}static _fromEnrollmentId(e,t){return new rk(t,e)}async _finalizeEnroll(e,t,r){return y(void 0!==this.secret,e,"argument-error"),k(e,"POST","/v2/accounts/mfaEnrollment:finalize",C(e,{idToken:t,displayName:r,totpVerificationInfo:this.secret._makeTotpVerificationInfo(this.otp)}))}async _finalizeSignIn(e,t){y(void 0!==this.enrollmentId&&void 0!==this.otp,e,"argument-error");let r={verificationCode:this.otp};return k(e,"POST","/v2/accounts/mfaSignIn:finalize",C(e,{mfaPendingCredential:t,mfaEnrollmentId:this.enrollmentId,totpVerificationInfo:r}))}}class rN{constructor(e,t,r,n,i,s,a){this.sessionInfo=s,this.auth=a,this.secretKey=e,this.hashingAlgorithm=t,this.codeLength=r,this.codeIntervalSeconds=n,this.enrollmentCompletionDeadline=i}static _fromStartTotpMfaEnrollmentResponse(e,t){return new rN(e.totpSessionInfo.sharedSecretKey,e.totpSessionInfo.hashingAlgorithm,e.totpSessionInfo.verificationCodeLength,e.totpSessionInfo.periodSec,new Date(e.totpSessionInfo.finalizeEnrollmentTime).toUTCString(),e.totpSessionInfo.sessionInfo,t)}_makeTotpVerificationInfo(e){return{sessionInfo:this.sessionInfo,verificationCode:e}}generateQrCodeUrl(e,t){let r=!1;return(rR(e)||rR(t))&&(r=!0),r&&(rR(e)&&(e=this.auth.currentUser?.email||"unknownuser"),rR(t)&&(t=this.auth.name)),`otpauth://totp/${t}:${e}?secret=${this.secretKey}&issuer=${t}&algorithm=${this.hashingAlgorithm}&digits=${this.codeLength}`}}function rR(e){return void 0===e||e?.length===0}var rD="@firebase/auth",rO="1.13.0";class rP{constructor(e){this.auth=e,this.internalListeners=new Map}getUid(){return this.assertAuthConfigured(),this.auth.currentUser?.uid||null}async getToken(e){return(this.assertAuthConfigured(),await this.auth._initializationPromise,this.auth.currentUser)?{accessToken:await this.auth.currentUser.getIdToken(e)}:null}addAuthTokenListener(e){if(this.assertAuthConfigured(),this.internalListeners.has(e))return;let t=this.auth.onIdTokenChanged(t=>{e(t?.stsTokenManager.accessToken||null)});this.internalListeners.set(e,t),this.updateProactiveRefresh()}removeAuthTokenListener(e){this.assertAuthConfigured();let t=this.internalListeners.get(e);t&&(this.internalListeners.delete(e),t(),this.updateProactiveRefresh())}assertAuthConfigured(){y(this.auth._initializationPromise,"dependent-sdk-initialized-before-auth")}updateProactiveRefresh(){this.internalListeners.size>0?this.auth._startProactiveRefresh():this.auth._stopProactiveRefresh()}}(0,s.XA)("authIdTokenMaxAge"),eT={loadJS:e=>
7new Promise((t,r)=>{let n=document.createElement("script");n.setAttribute("src",e),n.onload=t,n.onerror=e=>{let t=f("internal-error");t.customData=e,r(t)},n.type="text/javascript",n.charset="UTF-8",(document.getElementsByTagName("head")?.[0]??document).appendChild(n)}),gapiScript:"https://apis.google.com/js/api.js",recaptchaV2Script:"https://www.google.com/recaptcha/api.js",recaptchaEnterpriseScript:"https://www.google.com/recaptcha/enterprise.js?render="},n="Browser",(0,i.om)(new o.uA("auth",(e,{options:t})=>{let r,i,s=e.getProvider("app").getImmediate(),a=e.getProvider("heartbeat"),o=e.getProvider("app-check-internal"),{apiKey:l,authDomain:u}=s.options;y(l&&!l.includes(":"),"invalid-api-key",{appName:s.name});let h=new eE(s,a,o,{apiKey:l,authDomain:u,clientPlatform:n,apiHost:"identitytoolkit.googleapis.com",tokenApiHost:"securetoken.googleapis.com",apiScheme:"https",sdkClientVersion:eg(n)});return i=(Array.isArray(r=t?.persistence||[])?r:[r]).map(er),t?.errorMap&&h._updateErrorMap(t.errorMap),h._initializeWithPersistence(i,t?.popupRedirectResolver),h},"PUBLIC").setInstantiationMode("EXPLICIT").setInstanceCreatedCallback((e,t,r)=>{e.getProvider("auth-internal").initialize()})),(0,i.om)(new o.uA("auth-internal",e=>new rP(e_(e.getProvider("auth").getImmediate())),"PRIVATE").setInstantiationMode("EXPLICIT")),(0,i.KO)(rD,rO,function(e){switch(e){case"Node":return"node";case"ReactNative":return"rn";case"Worker":return"webworker";case"Cordova":return"cordova";case"WebExtension":return"web-extension";default:return}}(n)),(0,i.KO)(rD,rO,"esm2020")},89099:(e,t,r)=>{e.exports=r(59603)},98236:()=>{}},e=>{var t=t=>e(e.s=t);e.O(0,[6593,8792],()=>(t(92),t(59603))),_N_E=e.O()}]);
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.