PageSourceSearch

https://firebase-beautifulslides-static-assets.cdn.beautiful.ai/bu…rding-firebase-init.6a8e5397e438c6aba54c.js

js beautiful.ai collected 2026-09-24 08:27:37 UTC 593,945 bytes, 3 lines download raw bytes

1/*! For license information please see onboarding-firebase-init.6a8e5397e438c6aba54c.js.LICENSE.txt */
2"use strict";(self["webpackChunkbeautifulslides"]=self["webpackChunkbeautifulslides"]||[]).push([[709],{37207(e,t,n){var r=n(36183);var i=n(95282);var s=n(50218);var o=n(40767);function _interopNamespace(e){if(e&&e.__esModule)return e;var t=Object.create(null);if(e){Object.keys(e).forEach((function(n){if(n!=="default"){var r=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,r.get?r:{enumerable:true,get:function(){return e[n]}})}}))}t["default"]=e;return Object.freeze(t)}var a=_interopNamespace(s);class FirebaseAppImpl{constructor(e,t){this._delegate=e;this.firebase=t;s._addComponent(e,new i.Component("app-compat",(()=>this),"PUBLIC"));this.container=e.container}get automaticDataCollectionEnabled(){return this._delegate.automaticDataCollectionEnabled}set automaticDataCollectionEnabled(e){this._delegate.automaticDataCollectionEnabled=e}get name(){return this._delegate.name}get options(){return this._delegate.options}delete(){return new Promise((e=>{this._delegate.checkDestroyed();e()})).then((()=>{this.firebase.INTERNAL.removeApp(this.name);return s.deleteApp(this._delegate)}))}_getService(e,t=s._DEFAULT_ENTRY_NAME){this._delegate.checkDestroyed();const n=this._delegate.container.getProvider(e);if(!n.isInitialized()&&n.getComponent()?.instantiationMode==="EXPLICIT"){n.initialize()}return n.getImmediate({identifier:t})}_removeServiceInstance(e,t=s._DEFAULT_ENTRY_NAME){this._delegate.container.getProvider(e).clearInstance(t)}_addComponent(e){s._addComponent(this._delegate,e)}_addOrOverwriteComponent(e){s._addOrOverwriteComponent(this._delegate,e)}toJSON(){return{name:this.name,automaticDataCollectionEnabled:this.automaticDataCollectionEnabled,options:this.options}}}const c={["no-app"]:"No Firebase App '{$appName}' has been created - "+"call Firebase App.initializeApp()",["invalid-app-argument"]:"firebase.{$appName}() takes either no argument or a "+"Firebase App instance."};const l=new r.ErrorFactory("app-compat","Firebase",c);function createFirebaseNamespaceCore(e){const t={};const n={__esModule:true,initializeApp:initializeAppCompat,app,registerVersion:a.registerVersion,setLogLevel:a.setLogLevel,onLog:a.onLog,apps:null,SDK_VERSION:a.SDK_VERSION,INTERNAL:{registerComponent:registerComponentCompat,removeApp,useAsService,modularAPIs:a}};n["default"]=n;Object.defineProperty(n,"apps",{get:getApps});function removeApp(e){delete t[e]}function app(e){e=e||a._DEFAULT_ENTRY_NAME;if(!r.contains(t,e)){throw l.create("no-app",{appName:e})}return t[e]}app["App"]=e;function initializeAppCompat(i,s={}){const o=a.initializeApp(i,s);if(r.contains(t,o.name)){return t[o.name]}const c=new e(o,n);t[o.name]=c;return c}function getApps(){return Object.keys(t).map((e=>t[e]))}function registerComponentCompat(t){const i=t.name;const s=i.replace("-compat","");if(a._registerComponent(t)&&t.type==="PUBLIC"){const serviceNamespace=(e=app())=>{if(typeof e[s]!=="function"){throw l.create("invalid-app-argument",{appName:i})}return e[s]()};
2if(t.serviceProps!==undefined){r.deepExtend(serviceNamespace,t.serviceProps)}n[s]=serviceNamespace;e.prototype[s]=function(...e){const n=this._getService.bind(this,i);return n.apply(this,t.multipleInstances?e:[])}}return t.type==="PUBLIC"?n[s]:null}function useAsService(e,t){if(t==="serverAuth"){return null}const n=t;return n}return n}function createFirebaseNamespace(){const e=createFirebaseNamespaceCore(FirebaseAppImpl);e.INTERNAL={...e.INTERNAL,createFirebaseNamespace,extendNamespace,createSubscribe:r.createSubscribe,ErrorFactory:r.ErrorFactory,deepExtend:r.deepExtend};function extendNamespace(t){r.deepExtend(e,t)}return e}const u=createFirebaseNamespace();const d=new o.Logger("@firebase/app-compat");const h="@firebase/app-compat";const p="0.5.13";function registerCoreComponents(e){s.registerVersion(h,p,e)}try{const e=r.getGlobal();if(e.firebase!==undefined){d.warn(`\n      Warning: Firebase is already defined in the global scope. Please make sure\n      Firebase library is only loaded once.\n    `);const t=e.firebase.SDK_VERSION;if(t&&t.indexOf("LITE")>=0){d.warn(`\n        Warning: You are trying to load Firebase while using Firebase Performance standalone script.\n        You should load Firebase Performance with this instance of Firebase to avoid loading duplicate code.\n        `)}}}catch{}const f=u;registerCoreComponents();e.exports=f},50218(e,t,n){Object.defineProperty(t,"__esModule",{value:true});var r=n(95282);var i=n(40767);var s=n(36183);var o=n(42650);class PlatformLoggerServiceImpl{constructor(e){this.container=e}getPlatformInfoString(){const e=this.container.getProviders();return e.map((e=>{if(isVersionServiceProvider(e)){const t=e.getImmediate();return`${t.library}/${t.version}`}else{return null}})).filter((e=>e)).join(" ")}}function isVersionServiceProvider(e){const t=e.getComponent();return t?.type==="VERSION"}const a="@firebase/app";const c="0.14.13";const l=new i.Logger("@firebase/app");const u="@firebase/app-compat";const d="@firebase/analytics-compat";const h="@firebase/analytics";const p="@firebase/app-check-compat";const f="@firebase/app-check";const m="@firebase/auth";const g="@firebase/auth-compat";const _="@firebase/database";const v="@firebase/data-connect";const y="@firebase/database-compat";const I="@firebase/functions";const C="@firebase/functions-compat";const w="@firebase/installations";const E="@firebase/installations-compat";const T="@firebase/messaging";const P="@firebase/messaging-compat";const A="@firebase/performance";const S="@firebase/performance-compat";const b="@firebase/remote-config";const R="@firebase/remote-config-compat";const k="@firebase/storage";const N="@firebase/storage-compat";const O="@firebase/firestore";const D="@firebase/ai";const L="@firebase/firestore-compat";const M="firebase";const F="12.14.0";const U="[DEFAULT]";const x={[a]:"fire-core",[u]:"fire-core-compat",[h]:"fire-analytics",[d]:"fire-analytics-compat",[f]:"fire-app-check",[p]:"fire-app-check-compat",[m]:"fire-auth",[g]:"fire-auth-compat",[_]:"fire-rtdb",[v]:"fire-data-connect",[y]:"fire-rtdb-compat",[I]:"fire-fn",[C]:"fire-fn-compat",[w]:"fire-iid",[E]:"fire-iid-compat",[T]:"fire-fcm",[P]:"fire-fcm-compat",[A]:"fire-perf",[S]:"fire-perf-compat",[b]:"fire-rc",[R]:"fire-rc-compat",[k]:"fire-gcs",[N]:"fire-gcs-compat",[O]:"fire-fst",[L]:"fire-fst-compat",[D]:"fire-vertex","fire-js":"fire-js",[M]:"fire-js-all"};const W=new Map;const V=new Map;const q=new Map;function _addComponent(e,t){try{e.container.addComponent(t)}catch(n){l.debug(`Component ${t.name} failed to register with FirebaseApp ${e.name}`,n)}}function _addOrOverwriteComponent(e,t){e.container.addOrOverwriteComponent(t)}function _registerComponent(e){const t=e.name;if(q.has(t)){l.debug(`There were multiple attempts to register component ${t}.`);return false}q.set(t,e);for(const t of W.values()){_addComponent(t,e)}for(const t of V.values()){_addComponent(t,e)}return true}function _getProvider(e,t){const n=e.container.getProvider("heartbeat").getImmediate({optional:true});if(n){void n.triggerHeartbeat()}return e.container.getProvider(t)}function _removeServiceInstance(e,t,n=U){_getProvider(e,t).clearInstance(n)}function _isFirebaseApp(e){return e.options!==undefined}function _isFirebaseServerAppSettings(e){if(_isFirebaseApp(e)){return false}return"authIdToken"in e||"appCheckToken"in e||"releaseOnDeref"in e||"automaticDataCollectionEnabled"in e}function _isFirebaseServerApp(e){if(e===null||e===undefined){return false}return e.settings!==undefined}function _clearComponents(){q.clear()}const G={["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.",["invali
2d-app-argument"]:"firebase.{$appName}() takes either no argument or a "+"Firebase App instance.",["invalid-log-argument"]:"First argument to `onLog` must be null or a function.",["idb-open"]:"Error thrown when opening IndexedDB. Original error: {$originalErrorMessage}.",["idb-get"]:"Error thrown when reading from IndexedDB. Original error: {$originalErrorMessage}.",["idb-set"]:"Error thrown when writing to IndexedDB. Original error: {$originalErrorMessage}.",["idb-delete"]:"Error thrown when deleting from IndexedDB. Original error: {$originalErrorMessage}.",["finalization-registry-not-supported"]:"FirebaseServerApp deleteOnDeref field defined but the JS runtime does not support FinalizationRegistry.",["invalid-server-app-environment"]:"FirebaseServerApp is not for use in browser environments."};const B=new s.ErrorFactory("app","Firebase",G);class FirebaseAppImpl{constructor(e,t,n){this._isDeleted=false;this._options={...e};this._config={...t};this._name=t.name;this._automaticDataCollectionEnabled=t.automaticDataCollectionEnabled;this._container=n;this.container.addComponent(new r.Component("app",(()=>this),"PUBLIC"))}get automaticDataCollectionEnabled(){this.checkDestroyed();return this._automaticDataCollectionEnabled}set automaticDataCollectionEnabled(e){this.checkDestroyed();this._automaticDataCollectionEnabled=e}get name(){this.checkDestroyed();return this._name}get options(){this.checkDestroyed();return this._options}get config(){this.checkDestroyed();return this._config}get container(){return this._container}get isDeleted(){return this._isDeleted}set isDeleted(e){this._isDeleted=e}checkDestroyed(){if(this.isDeleted){throw B.create("app-deleted",{appName:this._name})}}}function validateTokenTTL(e,t){const n=s.base64Decode(e.split(".")[1]);if(n===null){console.error(`FirebaseServerApp ${t} is invalid: second part could not be parsed.`);return}const r=JSON.parse(n).exp;if(r===undefined){console.error(`FirebaseServerApp ${t} is invalid: expiration claim could not be parsed`);return}const i=JSON.parse(n).exp*1e3;const o=(new Date).getTime();const a=i-o;if(a<=0){console.error(`FirebaseServerApp ${t} is invalid: the token has expired.`)}}class FirebaseServerAppImpl extends FirebaseAppImpl{constructor(e,t,n,r){const i=t.automaticDataCollectionEnabled!==undefined?t.automaticDataCollectionEnabled:true;const s={name:n,automaticDataCollectionEnabled:i};if(e.apiKey!==undefined){super(e,s,r)}else{const t=e;super(t.options,s,r)}this._serverConfig={automaticDataCollectionEnabled:i,...t};if(this._serverConfig.authIdToken){validateTokenTTL(this._serverConfig.authIdToken,"authIdToken")}if(this._serverConfig.appCheckToken){validateTokenTTL(this._serverConfig.appCheckToken,"appCheckToken")}this._finalizationRegistry=null;if(typeof FinalizationRegistry!=="undefined"){this._finalizationRegistry=new FinalizationRegistry((()=>{this.automaticCleanup()}))}this._refCount=0;this.incRefCount(this._serverConfig.releaseOnDeref);this._serverConfig.releaseOnDeref=undefined;t.releaseOnDeref=undefined;registerVersion(a,c,"serverapp")}toJSON(){return undefined}get refCount(){return this._refCount}incRefCount(e){if(this.isDeleted){return}this._refCount++;if(e!==undefined&&this._finalizationRegistry!==null){this._finalizationRegistry.register(e,this)}}decRefCount(){if(this.isDeleted){return 0}return--this._refCount}automaticCleanup(){void deleteApp(this)}get settings(){this.checkDestroyed();return this._serverConfig}checkDestroyed(){if(this.isDeleted){throw B.create("server-app-deleted")}}}const H=F;function initializeApp(e,t={}){let n=e;if(typeof t!=="object"){const e=t;t={name:e}}const i={name:U,automaticDataCollectionEnabled:true,...t};const o=i.name;if(typeof o!=="string"||!o){throw B.create("bad-app-name",{appName:String(o)})}n||(n=s.getDefaultAppConfig());if(!n){throw B.create("no-options")}const a=W.get(o);if(a){if(s.deepEqual(n,a.options)&&s.deepEqual(i,a.config)){return a}else{throw B.create("duplicate-app",{appName:o})}}const c=new r.ComponentContainer(o);for(const e of q.values()){c.addComponent(e)}const l=new FirebaseAppImpl(n,i,c);W.set(o,l);return l}function initializeServerApp(e,t={}){if(s.isBrowser()&&!s.isWebWorker()){throw B.create("invalid-server-app-environment")}let n;let i=t||{};if(e){if(_isFirebaseApp(e)){n=e.options}else if(_isFirebaseServerAppSettings(e)){i=e}else{n=e}}if(i.automaticDataCollectionEnabled===undefined){i.automaticDataCollectionEnabled=true}n||(n=s.getDefaultAppConfig());if(!n){throw B.create("no-options")}const o={...i,...n};if(o.releaseOnDeref!==undefined){delete o.releaseOnDeref}const hashCode=e=>[...e].reduce(((e,t)=>Math.imul(31,e)+t.charCodeAt(0)|0),0);if(i.releaseOnDeref!==undefined){if(typeof FinalizationRegistry==="undefined"){throw B.create("finalization-registry-not-supported",{})}}const a=""+hashCode(JSON.stringify(o));const c=V.get(a);if(c){c.incRefCount(i.releaseOnDeref);return c}const l=new r.ComponentContainer(a);for(const e of q.values()){l.addComponent(e)}const u=new FirebaseServerAppImpl(n,i,a,l);V.set(a,u);return u}function getApp(e=U){const t=W.get(e);if(!t&&e===U&&s.getDefaultAppConfig()){return initializeApp()}if(!t){throw B.create("no-app",{appName:e})}return t}function getApps(){return Array.from(W.values())}async function deleteApp(e){let t=false;const n=e.name;if(W.has(n)){t=true;W.delete(n)}else if(V.has(n)){const r=e;if(r.decRefCount()<=0){V.delete(n);t=true}}if(t){await Promise.all(e.container.getProviders().map((e=>e.delete())));e.isDeleted=true}}function registerVersion(e,t,n){let i=x[e]??e;if(n){i+=`-${n}`}const s=i.match(/\s|\//);const o=t.match(/\s|\//);if(s||o){const e=[`Unable to register library "${i}" with version "${t}":`];if(s){e.push(`library name "${i}" contains illegal characters (whitespace or "/")`)}if(s&&o){e.push("and")}if(o){e.push(`version name "${t}" contains illegal characters (whitespace or "/")`)}l.warn(e.join(" "));return}_registerComponent(new r.Component(`${i}-version`,(()=>({library:i,version:t})),"VERSION"))}function onLog(e,t){if(e!==null&&typeof e!=="function"){throw B.create("invalid-log-argument")}i.setUserLogHandler(e,t)}function setLogLevel(e){i.setLogLevel(e)}const j="firebase-heartbeat-database";const z=1;const K="firebase-heartbeat-store";let $=null;function getDbPromise(){if(!$){$=o.openDB(j,z,{upgrade:(e,t)=>{switch(t){case 0:try{e.createObjectStore(K)}catch(e){console.warn(e)}}}}).catch((e=>{throw B.create("idb-open",{originalErrorMessage:e.message})}))}return $}async function readHeartbeatsFromIndexedDB(e){try{const t=await getDbPromise();const n=t.transaction(K);const r=await n.objectStore(K).get(computeKey(e));await n.done;return r}catch(e){if(e instanceof s.FirebaseError){l.warn(e.message)}else{const t=B.create("idb-get",{originalErrorMessage:e?.message});l.warn(t.message)}}}async function writeHeartbeatsToIndexedDB(e,t){try{const n=await getDbPromise();const r=n.transaction(K,"readwrite");const i=r.objectStore(K);await i.put(t,computeKey(e));await r.done}catch(e){if(e instanceof s.FirebaseError){l.warn(e.message)}else{const t=B.create("idb-set",{originalErrorMessage:e?.message});l.warn(t.message)}}}function computeKey(e){return`${e.name}!${e.options.appId}`}const Q=1024;const Y=30;class HeartbeatServiceImpl{constructor(e){this.container=e;this._heartbeatsCache=null;const t=this.container.getProvider("app").getImmediate();this._storage=new HeartbeatStorageImpl(t);this._heartbeatsCachePromise=this._storage.read().then((e=>{this._heartbeatsCache=e;return e}))}async triggerHeartbeat(){try{const e=this.container.getProvider("platform-logger").getImmediate();const t=e.getPlatformInfoString();const n=getUTCDateString();if(this._heartbeatsCache?.heartbeats==null){this._heartbeatsCache=await this._heartbeatsCachePromise;if(this._heartbeatsCache?.heartbeats==null){return}}if(this._heartbeatsCache.lastSentHeartbeatDate===n||this._heartbeatsCache.heartbeats.some((e=>e.date===n))){return}else{this._heartbeatsCache.heartbeats.push({date:n,agent:t});if(this._heartbeatsCache.heartbeats.length>Y){const e=getEarliestHeartbeatIdx(this._heartbeatsCache.heartbeats);this._heartbeatsCache.heartbeats.splice(e,1)}}return this._storage.overwrite(this._heartbeatsCache)}catch(e){l.warn(e)}}async getHeartbeatsHeader(){try{if(this._heartbeatsCache===null){await this._heartbeatsCachePromise}if(this._heartbeatsCache?.heartbeats==null||this._heartbeatsCache.heartbeats.length===0){return""}const e=getUTCDateString();const{heartbeatsToSend:t,unsentEntries:n}=extractHeartbeatsForHeader(this._heartbeatsCache.heartbeats);const r=s.base64urlEncodeWithoutPadding(JSON.stringify({version:2,heartbeats:t}));this._heartbeatsCache.lastSentHeartbeatDate=e;if(n.length>0){this._heartbeatsCache.heartbeats=n;await this._storage.overwrite(this._heartbeatsCache)}else{this._heartbeatsCache.heartbeats=[];void this._storage.overwrite(this._heartbeatsCache)}return r}catch(e){l.warn(e);return""}}}function getUTCDateString(){const e=new Date;return e.toISOString().substring(0,10)}function extractHeartbeatsForHeader(e,t=Q){const n=[];let r=e.slice();for(const i of e){const e=n.find((e=>e.agent===i.agent));if(!e){n.push({agent:i.agent,dates:[i.date]});if(countBytes(n)>t){n.pop();break}}else{e.dates.push(i.date);if(countBytes(n)>t){e.dates.pop();break}}r=r.slice(1)}return{heartbeatsToSend:n,unsentEntries:r}}class HeartbeatStorageImpl{constructor(e){this.app=e;this._canUseIndexedDBPromise=this.runIndexedDBEnvironmentCheck()}async runIndexedDBEnvironmentCheck(){if(!s.isIndexedDBAvailable()){return false}else{return s.validateIndexedDBOpenable().then((()=>true)).catch((()=>false))}}async read(){const e=await this._canUseIndexedDBPromise;if(!e){return{heartbeats:[]}}else{const e=await readHeartbeatsFromIndexedDB(this.app);if(e?.heartbeats){return e}else{return{heartbeats:[]}}}}async overwrite(e){const t=await this._canUseIndexedDBPromise;if(!t){return}else{const t=await this.read();return writeHeartbeatsToIndexedDB(this.app,{lastSentHeartbeatDate:e.lastSentHeartbeatDate??t.lastSentHeartbeatDate,heartbeats:e.heartbeats})}}async add(e){const t=await this._canUseIndexedDBPromise;if(!t){return}else{const t=await this.read();return writeHeartbeatsToIndexedDB(this.app,{lastSentHeartbeatDate:e.lastSentHeartbeatDate??t.lastSentHeartbeatDate,heartbeats:[...t.heartbeats,...e.heartbeats]})}}}function countBytes(e){return s.base64urlEncodeWithoutPadding(JSON.stringify({version:2,heartbeats:e})).length}function getEarliestHeartbeatIdx(e){if(e.length===0){return-1}let t=0;let n=e[0].date;for(let r=1;r<e.length;r++){if(e[r].date<n){n=e[r].date;t=r}}return t}function registerCoreComponents(e){_registerComponent(new r.Component("platform-logger",(e=>new PlatformLoggerServiceImpl(e)),"PRIVATE"));_registerComponent(new r.Component("heartbeat",(e=>new HeartbeatServiceImpl(e)),"PRIVATE"));registerVersion(a,c,e);registerVersion(a,c,"cjs2020");registerVersion("fire-js","")}registerCoreComponents("node");Object.defineProperty(t,"FirebaseError",{enumerable:true,get:function(){return s.FirebaseError}});t.SDK_VERSION=H;t._DEFAULT_ENTRY_NAME=U;t._addComponent=_addComponent;t._addOrOverwriteComponent=_addOrOverwriteComponent;t._apps=W;t._clearComponents=_clearComponents;t._components=q;t._getProvider=_getProvider;t._isFirebaseApp=_isFirebaseApp;t._isFirebaseServerApp=_isFirebaseServerApp;t._isFirebaseServerAppSettings=_isFirebaseServerAppSettings;t._registerComponent=_registerComponent;t._removeServiceInstance=_removeServiceInstance;t._serverApps=V;t.deleteApp=deleteApp;t.getApp=getApp;t.getApps=getApps;t.initializeApp=initializeApp;t.initializeServerApp=initializeServerApp;t.onLog=onLog;t.registerVersion=registerVersion;t.setLogLevel=setLogLevel},89314(e,t,n){var r=n(37207);var i=n(71929);var s=n(95282);var o=n(36183);function _interopDefaultLegacy(e){return e&&typeof e==="object"&&"default"in e?e:{default:e}}
2function _interopNamespace(e){if(e&&e.__esModule)return e;var t=Object.create(null);if(e){Object.keys(e).forEach((function(n){if(n!=="default"){var r=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,r.get?r:{enumerable:true,get:function(){return e[n]}})}}))}t["default"]=e;return Object.freeze(t)}var a=_interopDefaultLegacy(r);var c=_interopNamespace(i);var l="@firebase/auth-compat";var u="0.6.7";const d=1e3;function _getCurrentScheme(){return self?.location?.protocol||null}function _isHttpOrHttps(){return _getCurrentScheme()==="http:"||_getCurrentScheme()==="https:"}function _isAndroidOrIosCordovaScheme(e=o.getUA()){return!!((_getCurrentScheme()==="file:"||_getCurrentScheme()==="ionic:"||_getCurrentScheme()==="capacitor:")&&e.toLowerCase().match(/iphone|ipad|ipod|android/))}function _isNativeEnvironment(){return o.isReactNative()||o.isNode()}function _isIe11(){return o.isIE()&&document?.documentMode===11}function _isEdge(e=o.getUA()){return/Edge\/\d+/.test(e)}function _isLocalStorageNotSynchronized(e=o.getUA()){return _isIe11()||_isEdge(e)}function _isWebStorageSupported(){try{const e=self.localStorage;const t=c._generateEventId();if(e){e["setItem"](t,"1");e["removeItem"](t);if(_isLocalStorageNotSynchronized()){return o.isIndexedDBAvailable()}return true}}catch(e){return _isWorker()&&o.isIndexedDBAvailable()}return false}function _isWorker(){return typeof n.g!=="undefined"&&"WorkerGlobalScope"in n.g&&"importScripts"in n.g}function _isPopupRedirectSupported(){return(_isHttpOrHttps()||o.isBrowserExtension()||_isAndroidOrIosCordovaScheme())&&!_isNativeEnvironment()&&_isWebStorageSupported()&&!_isWorker()}function _isLikelyCordova(){return _isAndroidOrIosCordovaScheme()&&typeof document!=="undefined"}async function _isCordova(){if(!_isLikelyCordova()){return false}return new Promise((e=>{const t=setTimeout((()=>{e(false)}),d);document.addEventListener("deviceready",(()=>{clearTimeout(t);e(true)}))}))}function _getSelfWindow(){return typeof window!=="undefined"?window:null}const h={LOCAL:"local",NONE:"none",SESSION:"session"};const p=c._assert;const f="persistence";function _validatePersistenceArgument(e,t){p(Object.values(h).includes(t),e,"invalid-persistence-type");if(o.isReactNative()){p(t!==h.SESSION,e,"unsupported-persistence-type");return}if(o.isNode()){p(t===h.NONE,e,"unsupported-persistence-type");return}if(_isWorker()){p(t===h.NONE||t===h.LOCAL&&o.isIndexedDBAvailable(),e,"unsupported-persistence-type");return}p(t===h.NONE||_isWebStorageSupported(),e,"unsupported-persistence-type")}async function _savePersistenceForRedirect(e){await e._initializationPromise;const t=getSessionStorageIfAvailable();const n=c._persistenceKeyName(f,e.config.apiKey,e.name);if(t){t.setItem(n,e._getPersistenceType())}}function _getPersistencesFromRedirect(e,t){const n=getSessionStorageIfAvailable();if(!n){return[]}const r=c._persistenceKeyName(f,e,t);const i=n.getItem(r);switch(i){case h.NONE:return[c.inMemoryPersistence];case h.LOCAL:return[c.indexedDBLocalPersistence,c.browserSessionPersistence];case h.SESSION:return[c.browserSessionPersistence];default:return[]}}function getSessionStorageIfAvailable(){try{return _getSelfWindow()?.sessionStorage||null}catch(e){return null}}const m=c._assert;class CompatPopupRedirectResolver{constructor(){this.browserResolver=c._getInstance(c.browserPopupRedirectResolver);this.cordovaResolver=c._getInstance(c.cordovaPopupRedirectResolver);this.underlyingResolver=null;this._redirectPersistence=c.browserSessionPersistence;this._completeRedirectFn=c._getRedirectResult;this._overrideRedirectResult=c._overrideRedirectResult}async _initialize(e){await this.selectUnderlyingResolver();return this.assertedUnderlyingResolver._initialize(e)}async _openPopup(e,t,n,r){await this.selectUnderlyingResolver();return this.assertedUnderlyingResolver._openPopup(e,t,n,r)}async _openRedirect(e,t,n,r){await this.selectUnderlyingResolver();return this.assertedUnderlyingResolver._openRedirect(e,t,n,r)}_isIframeWebStorageSupported(e,t){this.assertedUnderlyingResolver._isIframeWebStorageSupported(e,t)}_originValidation(e){return this.assertedUnderlyingResolver._originValidation(e)}get _shouldInitProactively(){return _isLikelyCordova()||this.browserResolver._shouldInitProactively}get assertedUnderlyingResolver(){m(this.underlyingResolver,"internal-error");return this.underlyingResolver}async selectUnderlyingResolver(){if(this.underlyingResolver){return}const e=await _isCordova();this.underlyingResolver=e?this.cordovaResolver:this.browserResolver}}function unwrap(e){return e.unwrap()}function wrapped(e){return e.wrapped()}function credentialFromResponse(e){return credentialFromObject(e)}function attachExtraErrorFields(e,t){const n=t.customData?._tokenResponse;if(t?.code==="auth/multi-factor-auth-required"){const n=t;n.resolver=new MultiFactorResolver(e,c.getMultiFactorResolver(e,t))}else if(n){const e=credentialFromObject(t);const r=t;if(e){r.credential=e;r.tenantId=n.tenantId||undefined;r.email=n.email||undefined;r.phoneNumber=n.phoneNumber||undefined}}}function credentialFromObject(e){const{_tokenResponse:t}=e instanceof o.FirebaseError?e.customData:e;if(!t){return null}if(!(e instanceof o.FirebaseError)){if("temporaryProof"in t&&"phoneNumber"in t){return c.PhoneAuthProvider.credentialFromResult(e)}}const n=t.providerId;if(!n||n===c.ProviderId.PASSWORD){return null}let r;switch(n){case c.ProviderId.GOOGLE:r=c.GoogleAuthProvider;break;case c.ProviderId.FACEBOOK:r=c.FacebookAuthProvider;break;case c.ProviderId.GITHUB:r=c.GithubAuthProvider;break;case c.ProviderId.TWITTER:r=c.TwitterAuthProvider;break;default:const{oauthIdToken:e,oauthAccessToken:i,oauthTokenSecret:s,pendingToken:o,nonce:a}=t;if(!i&&!s&&!e&&!o){return null}if(o){if(n.startsWith("saml.")){return c.SAMLAuthCredential._create(n,o)}else{return c.OAuthCredential._fromParams({providerId:n,signInMethod:n,pendingToken:o,idToken:e,accessToken:i})}}return new c.OAuthProvider(n).credential({idToken:e,accessToken:i,rawNonce:a})}return e instanceof o.FirebaseError?r.credentialFromError(e):r.credentialFromResult(e)}function convertCredential(e,t){return t.catch((t=>{if(t instanceof o.FirebaseError){attachExtraErrorFields(e,t)}throw t})).then((e=>{const t=e.operationType;const n=e.user;return{operationType:t,credential:credentialFromResponse(e),additionalUserInfo:c.getAdditionalUserInfo(e),user:User.getOrCreate(n)}}))}async function convertConfirmationResult(e,t){const n=await t;return{verificationId:n.verificationId,confirm:t=>convertCredential(e,n.confirm(t))}}class MultiFactorResolver{constructor(e,t){this.resolver=t;this.auth=wrapped(e)}get session(){return this.resolver.session}get hints(){return this.resolver.hints}resolveSignIn(e){return convertCredential(unwrap(this.auth),this.resolver.resolveSignIn(e))}}class User{constructor(e){this._delegate=e;this.multiFactor=c.multiFactor(e)}static getOrCreate(e){if(!User.USER_MAP.has(e)){User.USER_MAP.set(e,new User(e))}return User.USER_MAP.get(e)}delete(){return this._delegate.delete()}reload(){return this._delegate.reload()}toJSON(){return this._delegate.toJSON()}getIdTokenResult(e){return this._delegate.getIdTokenResult(e)}getIdToken(e){return this._delegate.getIdToken(e)}linkAndRetrieveDataWithCredential(e){return this.linkWithCredential(e)}async linkWithCredential(e){return convertCredential(this.auth,c.linkWithCredential(this._delegate,e))}async linkWithPhoneNumber(e,t){return convertConfirmationResult(this.auth,c.linkWithPhoneNumber(this._delegate,e,t))}async linkWithPopup(e){return convertCredential(this.auth,c.linkWithPopup(this._delegate,e,CompatPopupRedirectResolver))}async linkWithRedirect(e){await _savePersistenceForRedirect(c._castAuth(this.auth));return c.linkWithRedirect(this._delegate,e,CompatPopupRedirectResolver)}reauthenticateAndRetrieveDataWithCredential(e){return this.reauthenticateWithCredential(e)}async reauthenticateWithCredential(e){return convertCredential(this.auth,c.reauthenticateWithCredential(this._delegate,e))}reauthenticateWithPhoneNumber(e,t){return convertConfirmationResult(this.auth,c.reauthenticateWithPhoneNumber(this._delegate,e,t))}reauthenticateWithPopup(e){return convertCredential(this.auth,c.reauthenticateWithPopup(this._delegate,e,CompatPopupRedirectResolver))}async reauthenticateWithRedirect(e){await _savePersistenceForRedirect(c._castAuth(this.auth));return c.reauthenticateWithRedirect(this._delegate,e,CompatPopupRedirectResolver)}sendEmailVerification(e){return c.sendEmailVerification(this._delegate,e)}async unlink(e){await c.unlink(this._delegate,e);return this}updateEmail(e){return c.updateEmail(this._delegate,e)}updatePassword(e){return c.updatePassword(this._delegate,e)}updatePhoneNumber(e){return c.updatePhoneNumber(this._delegate,e)}updateProfile(e){return c.updateProfile(this._delegate,e)}verifyBeforeUpdateEmail(e,t){return c.verifyBeforeUpdateEmail(this._delegate,e,t)}get emailVerified(){return this._delegate.emailVerified}get isAnonymous(){return this._delegate.isAnonymous}get metadata(){return this._delegate.metadata}get phoneNumber(){return this._delegate.phoneNumber}get providerData(){return this._delegate.providerData}get refreshToken(){return this._delegate.refreshToken}get tenantId(){return this._delegate.tenantId}get displayName(){return this._delegate.displayName}get email(){return this._delegate.email}get photoURL(){return this._delegate.photoURL}get providerId(){return this._delegate.providerId}get uid(){return this._delegate.uid}get auth(){return this._delegate.auth}}User.USER_MAP=new WeakMap;const g=c._assert;class Auth{constructor(e,t){this.app=e;if(t.isInitialized()){this._delegate=t.getImmediate();this.linkUnderlyingAuth();return}const{apiKey:n}=e.options;
2g(n,"invalid-api-key",{appName:e.name});g(n,"invalid-api-key",{appName:e.name});const r=typeof window!=="undefined"?CompatPopupRedirectResolver:undefined;this._delegate=t.initialize({options:{persistence:buildPersistenceHierarchy(n,e.name),popupRedirectResolver:r}});this._delegate._updateErrorMap(c.debugErrorMap);this.linkUnderlyingAuth()}get emulatorConfig(){return this._delegate.emulatorConfig}get currentUser(){if(!this._delegate.currentUser){return null}return User.getOrCreate(this._delegate.currentUser)}get languageCode(){return this._delegate.languageCode}set languageCode(e){this._delegate.languageCode=e}get settings(){return this._delegate.settings}get tenantId(){return this._delegate.tenantId}set tenantId(e){this._delegate.tenantId=e}useDeviceLanguage(){this._delegate.useDeviceLanguage()}signOut(){return this._delegate.signOut()}useEmulator(e,t){c.connectAuthEmulator(this._delegate,e,t)}applyActionCode(e){return c.applyActionCode(this._delegate,e)}checkActionCode(e){return c.checkActionCode(this._delegate,e)}confirmPasswordReset(e,t){return c.confirmPasswordReset(this._delegate,e,t)}async createUserWithEmailAndPassword(e,t){return convertCredential(this._delegate,c.createUserWithEmailAndPassword(this._delegate,e,t))}fetchProvidersForEmail(e){return this.fetchSignInMethodsForEmail(e)}fetchSignInMethodsForEmail(e){return c.fetchSignInMethodsForEmail(this._delegate,e)}isSignInWithEmailLink(e){return c.isSignInWithEmailLink(this._delegate,e)}async getRedirectResult(){g(_isPopupRedirectSupported(),this._delegate,"operation-not-supported-in-this-environment");const e=await c.getRedirectResult(this._delegate,CompatPopupRedirectResolver);if(!e){return{credential:null,user:null}}return convertCredential(this._delegate,Promise.resolve(e))}addFrameworkForLogging(e){c.addFrameworkForLogging(this._delegate,e)}onAuthStateChanged(e,t,n){const{next:r,error:i,complete:s}=wrapObservers(e,t,n);return this._delegate.onAuthStateChanged(r,i,s)}onIdTokenChanged(e,t,n){const{next:r,error:i,complete:s}=wrapObservers(e,t,n);return this._delegate.onIdTokenChanged(r,i,s)}sendSignInLinkToEmail(e,t){return c.sendSignInLinkToEmail(this._delegate,e,t)}sendPasswordResetEmail(e,t){return c.sendPasswordResetEmail(this._delegate,e,t||undefined)}async setPersistence(e){_validatePersistenceArgument(this._delegate,e);let t;switch(e){case h.SESSION:t=c.browserSessionPersistence;break;case h.LOCAL:const e=await c._getInstance(c.indexedDBLocalPersistence)._isAvailable();t=e?c.indexedDBLocalPersistence:c.browserLocalPersistence;break;case h.NONE:t=c.inMemoryPersistence;break;default:return c._fail("argument-error",{appName:this._delegate.name})}return this._delegate.setPersistence(t)}signInAndRetrieveDataWithCredential(e){return this.signInWithCredential(e)}signInAnonymously(){return convertCredential(this._delegate,c.signInAnonymously(this._delegate))}signInWithCredential(e){return convertCredential(this._delegate,c.signInWithCredential(this._delegate,e))}signInWithCustomToken(e){return convertCredential(this._delegate,c.signInWithCustomToken(this._delegate,e))}signInWithEmailAndPassword(e,t){return convertCredential(this._delegate,c.signInWithEmailAndPassword(this._delegate,e,t))}signInWithEmailLink(e,t){return convertCredential(this._delegate,c.signInWithEmailLink(this._delegate,e,t))}signInWithPhoneNumber(e,t){return convertConfirmationResult(this._delegate,c.signInWithPhoneNumber(this._delegate,e,t))}async signInWithPopup(e){g(_isPopupRedirectSupported(),this._delegate,"operation-not-supported-in-this-environment");return convertCredential(this._delegate,c.signInWithPopup(this._delegate,e,CompatPopupRedirectResolver))}async signInWithRedirect(e){g(_isPopupRedirectSupported(),this._delegate,"operation-not-supported-in-this-environment");await _savePersistenceForRedirect(this._delegate);return c.signInWithRedirect(this._delegate,e,CompatPopupRedirectResolver)}updateCurrentUser(e){return this._delegate.updateCurrentUser(e)}verifyPasswordResetCode(e){return c.verifyPasswordResetCode(this._delegate,e)}unwrap(){return this._delegate}_delete(){return this._delegate._delete()}linkUnderlyingAuth(){this._delegate.wrapped=()=>this}}Auth.Persistence=h;function wrapObservers(e,t,n){let r=e;if(typeof e!=="function"){({next:r,error:t,complete:n}=e)}const i=r;const newNext=e=>i(e&&User.getOrCreate(e));return{next:newNext,error:t,complete:n}}function buildPersistenceHierarchy(e,t){const n=_getPersistencesFromRedirect(e,t);if(typeof self!=="undefined"&&!n.includes(c.indexedDBLocalPersistence)){n.push(c.indexedDBLocalPersistence)}if(typeof window!=="undefined"){for(const e of[c.browserLocalPersistence,c.browserSessionPersistence]){if(!n.includes(e)){n.push(e)}}}if(!n.includes(c.inMemoryPersistence)){n.push(c.inMemoryPersistence)}return n}class PhoneAuthProvider{static credential(e,t){return c.PhoneAuthProvider.credential(e,t)}constructor(){this.providerId="phone";this._delegate=new c.PhoneAuthProvider(unwrap(a["default"].auth()))}verifyPhoneNumber(e,t){return this._delegate.verifyPhoneNumber(e,t)}unwrap(){return this._delegate}}PhoneAuthProvider.PHONE_SIGN_IN_METHOD=c.PhoneAuthProvider.PHONE_SIGN_IN_METHOD;PhoneAuthProvider.PROVIDER_ID=c.PhoneAuthProvider.PROVIDER_ID;const _=c._assert;class RecaptchaVerifier{constructor(e,t,n=a["default"].app()){_(n.options?.apiKey,"invalid-api-key",{appName:n.name});this._delegate=new c.RecaptchaVerifier(n.auth(),e,t);this.type=this._delegate.type}clear(){this._delegate.clear()}render(){return this._delegate.render()}verify(){return this._delegate.verify()}}const v="auth-compat";function registerAuthCompat(e){e.INTERNAL.registerComponent(new s.Component(v,(e=>{const t=e.getProvider("app-compat").getImmediate();const n=e.getProvider("auth");return new Auth(t,n)}),"PUBLIC").setServiceProps({ActionCodeInfo:{Operation:{EMAIL_SIGNIN:c.ActionCodeOperation.EMAIL_SIGNIN,PASSWORD_RESET:c.ActionCodeOperation.PASSWORD_RESET,RECOVER_EMAIL:c.ActionCodeOperation.RECOVER_EMAIL,REVERT_SECOND_FACTOR_ADDITION:c.ActionCodeOperation.REVERT_SECOND_FACTOR_ADDITION,VERIFY_AND_CHANGE_EMAIL:c.ActionCodeOperation.VERIFY_AND_CHANGE_EMAIL,VERIFY_EMAIL:c.ActionCodeOperation.VERIFY_EMAIL}},EmailAuthProvider:c.EmailAuthProvider,FacebookAuthProvider:c.FacebookAuthProvider,GithubAuthProvider:c.GithubAuthProvider,GoogleAuthProvider:c.GoogleAuthProvider,OAuthProvider:c.OAuthProvider,SAMLAuthProvider:c.SAMLAuthProvider,PhoneAuthProvider,PhoneMultiFactorGenerator:c.PhoneMultiFactorGenerator,RecaptchaVerifier,TwitterAuthProvider:c.TwitterAuthProvider,Auth,AuthCredential:c.AuthCredential,Error:o.FirebaseError}).setInstantiationMode("LAZY").setMultipleInstances(false));e.registerVersion(l,u)}registerAuthCompat(a["default"])},41386(e,t,n){var r=n(50218);var i=n(36183);var s=n(40767);var o=n(95282);const a={PHONE:"phone",TOTP:"totp"};const c={FACEBOOK:"facebook.com",GITHUB:"github.com",GOOGLE:"google.com",PASSWORD:"password",PHONE:"phone",TWITTER:"twitter.com"};const l={EMAIL_LINK:"emailLink",EMAIL_PASSWORD:"password",FACEBOOK:"facebook.com",GITHUB:"github.com",GOOGLE:"google.com",PHONE:"phone",TWITTER:"twitter.com"};const u={LINK:"link",REAUTHENTICATE:"reauthenticate",SIGN_IN:"signIn"};const d={EMAIL_SIGNIN:"EMAIL_SIGNIN",PASSWORD_RESET:"PASSWORD_RESET",RECOVER_EMAIL:"RECOVER_EMAIL",REVERT_SECOND_FACTOR_ADDITION:"REVERT_SECOND_FACTOR_ADDITION",VERIFY_AND_CHANGE_EMAIL:"VERIFY_AND_CHANGE_EMAIL",VERIFY_EMAIL:"VERIFY_EMAIL"};function _debugErrorMap(){return{["admin-restricted-operation"]:"This operation is restricted to administrators only.",["argument-error"]:"",["app-not-authorized"]:"This app, identified by the domain where it's hosted, is not "+"authorized to use Firebase Authentication with the provided API key. "+"Review your key configuration in the Google API console.",["app-not-installed"]:"The requested mobile application corresponding to the identifier ("+"Android package name or iOS bundle ID) provided is not installed on "+"this device.",["captcha-check-failed"]:"The reCAPTCHA response token provided is either invalid, expired, "+"already used or the domain associated with it does not match the list "+"of whitelisted domains.",["code-expired"]:"The SMS code has expired. Please re-send the verification code to try "+"again.",["cordova-not-ready"]:"Cordova framework is not ready.",["cors-unsupported"]:"This browser is not supported.",["credential-already-in-use"]:"This credential is already associated with a different user account.",["custom-token-mismatch"]:"The custom token corresponds to a different audience.",["requires-recent-login"]:"This operation is sensitive and requires recent authentication. Log in "+"again before retrying this request.",["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.",["dynamic-link-not-activated"]:"Please activate Dynamic Links in the Firebase Console and agree to the terms and "+"conditions.",["email-change-needs-verification"]:"Multi-factor users must al
2ways have a verified email.",["email-already-in-use"]:"The email address is already in use by another account.",["emulator-config-failed"]:"Auth instance has already been used to make a network call. Auth can "+"no longer be configured to use the emulator. Try calling "+'"connectAuthEmulator()" sooner.',["expired-action-code"]:"The action code has expired.",["cancelled-popup-request"]:"This operation has been cancelled due to another conflicting popup being opened.",["internal-error"]:"An internal AuthError has occurred.",["invalid-app-credential"]:"The phone verification request contains an invalid application verifier."+" The reCAPTCHA token response is either invalid or expired.",["invalid-app-id"]:"The mobile app identifier is not registered for the current project.",["invalid-user-token"]:"This user's credential isn't valid for this project. This can happen "+"if the user's token has been tampered with, or if the user isn't for "+"the project associated with this API key.",["invalid-auth-event"]:"An internal AuthError has occurred.",["invalid-verification-code"]:"The SMS verification code used to create the phone auth credential is "+"invalid. Please resend the verification code sms and be sure to use the "+"verification code provided by the user.",["invalid-continue-uri"]:"The continue URL provided in the request is invalid.",["invalid-cordova-configuration"]:"The following Cordova plugins must be installed to enable OAuth sign-in: "+"cordova-plugin-buildinfo, cordova-universal-links-plugin, "+"cordova-plugin-browsertab, cordova-plugin-inappbrowser and "+"cordova-plugin-customurlscheme.",["invalid-custom-token"]:"The custom token format is incorrect. Please check the documentation.",["invalid-dynamic-link-domain"]:"The provided dynamic link domain is not configured or authorized for the current project.",["invalid-email"]:"The email address is badly formatted.",["invalid-emulator-scheme"]:"Emulator URL must start with a valid scheme (http:// or https://).",["invalid-api-key"]:"Your API key is invalid, please check you have copied it correctly.",["invalid-cert-hash"]:"The SHA-1 certificate hash provided is invalid.",["invalid-credential"]:"The supplied auth credential is incorrect, malformed or has expired.",["invalid-message-payload"]:"The email template corresponding to this action contains invalid characters in its message. "+"Please fix by going to the Auth email templates section in the Firebase Console.",["invalid-multi-factor-session"]:"The request does not contain a valid proof of first factor successful sign-in.",["invalid-oauth-provider"]:"EmailAuthProvider is not supported for this operation. This operation "+"only supports OAuth providers.",["invalid-oauth-client-id"]:"The OAuth client ID provided is either invalid or does not match the "+"specified API key.",["unauthorized-domain"]:"This domain is not authorized for OAuth operations for your Firebase "+"project. Edit the list of authorized domains from the Firebase console.",["invalid-action-code"]:"The action code is invalid. This can happen if the code is malformed, "+"expired, or has already been used.",["wrong-password"]:"The password is invalid or the user does not have a password.",["invalid-persistence-type"]:"The specified persistence type is invalid. It can only be local, session or none.",["invalid-phone-number"]:"The format of the phone number provided is incorrect. Please enter the "+"phone number in a format that can be parsed into E.164 format. E.164 "+"phone numbers are written in the format [+][country code][subscriber "+"number including area code].",["invalid-provider-id"]:"The specified provider ID is invali
2d.",["invalid-recipient-email"]:"The email corresponding to this action failed to send as the provided "+"recipient email address is invalid.",["invalid-sender"]:"The email template corresponding to this action contains an invalid sender email or name. "+"Please fix by going to the Auth email templates section in the Firebase Console.",["invalid-verification-id"]:"The verification ID used to create the phone auth credential is invalid.",["invalid-tenant-id"]:"The Auth instance's tenant ID is invalid.",["login-blocked"]:"Login blocked by user-provided method: {$originalMessage}",["missing-android-pkg-name"]:"An Android Package Name must be provided if the Android App is required to be installed.",["auth-domain-config-required"]:"Be sure to include authDomain when calling firebase.initializeApp(), "+"by following the instructions in the Firebase console.",["missing-app-credential"]:"The phone verification request is missing an application verifier "+"assertion. A reCAPTCHA response token needs to be provided.",["missing-verification-code"]:"The phone auth credential was created with an empty SMS verification code.",["missing-continue-uri"]:"A continue URL must be provided in the request.",["missing-iframe-start"]:"An internal AuthError has occurred.",["missing-ios-bundle-id"]:"An iOS Bundle ID must be provided if an App Store ID is provided.",["missing-or-invalid-nonce"]:"The request does not contain a valid nonce. This can occur if the "+"SHA-256 hash of the provided raw nonce does not match the hashed nonce "+"in the ID token payload.",["missing-password"]:"A non-empty password must be provided",["missing-multi-factor-info"]:"No second factor identifier is provided.",["missing-multi-factor-session"]:"The request is missing proof of first factor successful sign-in.",["missing-phone-number"]:"To send verification codes, provide a phone number for the recipient.",["missing-verification-id"]:"The phone auth credential was created with an empty verification ID.",["app-deleted"]:"This instance of FirebaseApp has been deleted.",["multi-factor-info-not-found"]:"The user does not have a second factor matching the identifier provided.",["multi-factor-auth-required"]:"Proof of ownership of a second factor is required to complete sign-in.",["account-exists-with-different-credential"]:"An account already exists with the same email address but different "+"sign-in credentials. Sign in using a provider associated with this "+"email address.",["network-request-failed"]:"A network AuthError (such as timeout, interrupted connection or unreachable host) has occurred.",["no-auth-event"]:"An internal AuthError has occurred.",["no-such-provider"]:"User was not linked to an account with the given provider.",["null-user"]:"A null user object was provided as the argument for an operation which "+"requires a non-null user object.",["operation-not-allowed"]:"The given sign-in provider is disabled for this Firebase project. "+"Enable it in the Firebase console, under the sign-in method tab of the "+"Auth section.",["operation-not-supported-in-this-environment"]:"This operation is not supported in the environment this application is "+'running on. "location.protocol" must be http, https or chrome-extension'+" and web storage must be enabled.",["popup-blocked"]:"Unable to establish a connection with the popup. It may have been blocked by the browser.",["popup-closed-by-user"]:"The popup has been closed by the user before finalizing the operation.",["provider-already-linked"]:"User can only be linked to one identity for the given provider.",["quota-exceeded"]:"The project's quota for this operation has been exceeded.",["redirect-cancelled-by-user"]:"The redirect operation has been cancelled by the user before finalizing.",["redirect-operation-pending"]:"A redirect sign-in operation is already pending.",["rejected-credential"]:"The request contains malformed or mismatching credentials.",["second-factor-already-in-use"]:"The second factor is already enrolled on this account.",["maximum-second-factor-count-exceeded"]:"The maximum allowed number of second factors on a user has been exceeded.",["tenant-id-mismatch"]:"The provided tenant ID does not match the Auth instance's tenant ID",["timeout"]:"The operation has timed out.",["user-token-expired"]:"The user's credential is no longer valid. The user must sign in again.",["too-many-requests"]:"We have blocked all requests from this device due to unusual activity. "+"Try again later.",["unauthorized-continue-uri"]:"The domain of the continue URL is not whitelisted.  Please whitelist "+"the domain in the Firebase console.",["unsupported-first-factor"]:"Enrolling a second factor or signing in with a multi-factor account requires sign-in with a supported first factor.",["unsupported-persistence-type"]:"The current environment does not support the specified persistence type.",["unsupported-tenant-operation"]:"This operation is not supported in a multi-tenant context.",["unverified-email"]:"The operation requires a verified email.",["user-cancelled"]:"The user did not grant your application the permissions it requested.",["user-not-found"]:"There is no user record corresponding to this identifier. The user may "+"have been deleted.",["user-disabled"]:"The user account has been disabled by an administrator.",["user-mismatch"]:"The supplied credentials do not correspond to the previously signed in user.",["user-signed-out"]:"",["weak-password"]:"The password must be 6 characters long or more.",["web-storage-unsupported"]:"This browser is not supported or 3rd party cookies and data may be disabled.",["already-initialized"]:"initializeAuth() has already been called with "+"different options. To avoid this error, call initializeAuth() with the "+"same options as when it was originally called, or call getAuth() to return the"+" already initialized instance.",["missing-rec
2aptcha-token"]:"The reCAPTCHA token is missing when sending request to the backend.",["invalid-recaptcha-token"]:"The reCAPTCHA token is invalid when sending request to the backend.",["invalid-recaptcha-action"]:"The reCAPTCHA action is invalid when sending request to the backend.",["recaptcha-not-enabled"]:"reCAPTCHA Enterprise integration is not enabled for this project.",["missing-client-type"]:"The reCAPTCHA client type is missing when sending request to the backend.",["missing-recaptcha-version"]:"The reCAPTCHA version is missing when sending request to the backend.",["invalid-req-type"]:"Invalid request parameters.",["invalid-recaptcha-version"]:"The reCAPTCHA version is invalid when sending request to the backend.",["unsupported-password-policy-schema-version"]:"The password policy received from the backend uses a schema version that is not supported by this version of the Firebase SDK.",["password-does-not-meet-requirements"]:"The password does not meet the requirements.",["invalid-hosting-link-domain"]:"The provided Hosting link domain is not configured in Firebase Hosting or is not owned by "+"the current project. This cannot be a default Hosting domain (`web.app` or `firebaseapp.com`)."}}function _prodErrorMap(){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."}}const h=_debugErrorMap;const p=_prodErrorMap;const f=new i.ErrorFactory("auth","Firebase",_prodErrorMap());const m={ADMIN_ONLY_OPERATION:"auth/admin-restricted-operation",ARGUMENT_ERROR:"auth/argument-error",APP_NOT_AUTHORIZED:"auth/app-not-authorized",APP_NOT_INSTALLED:"auth/app-not-installed",CAPTCHA_CHECK_FAILED:"auth/captcha-check-failed",CODE_EXPIRED:"auth/code-expired",CORDOVA_NOT_READY:"auth/cordova-not-ready",CORS_UNSUPPORTED:"auth/cors-unsupported",CREDENTIAL_ALREADY_IN_USE:"auth/credential-already-in-use",CREDENTIAL_MISMATCH:"auth/custom-token-mismatch",CREDENTIAL_TOO_OLD_LOGIN_AGAIN:"auth/requires-recent-login",DEPENDENT_SDK_INIT_BEFORE_AUTH:"auth/dependent-sdk-initialized-before-auth",DYNAMIC_LINK_NOT_ACTIVATED:"auth/dynamic-link-not-activated",EMAIL_CHANGE_NEEDS_VERIFICATION:"auth/email-change-needs-verification",EMAIL_EXISTS:"auth/email-already-in-use",EMULATOR_CONFIG_FAILED:"auth/emulator-config-failed",EXPIRED_OOB_CODE:"auth/expired-action-code",EXPIRED_POPUP_REQUEST:"auth/cancelled-popup-request",INTERNAL_ERROR:"auth/internal-error",INVALID_API_KEY:"auth/invalid-api-key",INVALID_APP_CREDENTIAL:"auth/invalid-app-credential",INVALID_APP_ID:"auth/invalid-app-id",INVALID_AUTH:"auth/invalid-user-token",INVALID_AUTH_EVENT:"auth/invalid-auth-event",INVALID_CERT_HASH:"auth/invalid-cert-hash",INVALID_CODE:"auth/invalid-verification-code",INVALID_CONTINUE_URI:"auth/invalid-continue-uri",INVALID_CORDOVA_CONFIGURATION:"auth/invalid-cordova-configuration",INVALID_CUSTOM_TOKEN:"auth/invalid-custom-token",INVALID_DYNAMIC_LINK_DOMAIN:"auth/invalid-dynamic-link-domain",INVALID_EMAIL:"auth/invalid-email",INVALID_EMULATOR_SCHEME:"auth/invalid-emulator-scheme",INVALID_IDP_RESPONSE:"auth/invalid-credential",INVALID_LOGIN_CREDENTIALS:"auth/invalid-credential",INVALID_MESSAGE_PAYLOAD:"auth/invalid-message-payload",INVALID_MFA_SESSION:"auth/invalid-multi-factor-session",INVALID_OAUTH_CLIENT_ID:"auth/invalid-oauth-client-id",INVALID_OAUTH_PROVIDER:"auth/invalid-oauth-provider",INVALID_OOB_CODE:"auth/invalid-action-code",INVALID_ORIGIN:"auth/unauthorized-domain",INVALID_PASSWORD:"auth/wrong-password",INVALID_PERSISTENCE:"auth/invalid-persistence-type",INVALID_PHONE_NUMBER:"auth/invalid-phone-number",INVALID_PROVIDER_ID:"auth/invalid-provider-id",INVALID_RECIPIENT_EMAIL:"auth/invalid-recipient-email",INVALID_SENDER:"auth/invalid-sender",INVALID_SESSION_INFO:"auth/invalid-verification-id",INVALID_TENANT_ID:"auth/invalid-tenant-id",MFA_INFO_NOT_FOUND:"auth/multi-factor-info-not-found",MFA_REQUIRED:"auth/multi-factor-auth-required",MISSING_ANDROID_PACKAGE_NAME:"auth/missing-android-pkg-name",MISSING_APP_CREDENTIAL:"auth/missing-app-credential",MISSING_AUTH_DOMAIN:"auth/auth-domain-config-required",MISSING_CODE:"auth/missing-verification-code",MISSING_CONTINUE_URI:"auth/missing-continue-uri",MISSING_IFRAME_START:"auth/missing-iframe-start",MISSING_IOS_BUNDLE_ID:"auth/missing-ios-bundle-id",MISSING_OR_INVALID_
2NONCE:"auth/missing-or-invalid-nonce",MISSING_MFA_INFO:"auth/missing-multi-factor-info",MISSING_MFA_SESSION:"auth/missing-multi-factor-session",MISSING_PHONE_NUMBER:"auth/missing-phone-number",MISSING_PASSWORD:"auth/missing-password",MISSING_SESSION_INFO:"auth/missing-verification-id",MODULE_DESTROYED:"auth/app-deleted",NEED_CONFIRMATION:"auth/account-exists-with-different-credential",NETWORK_REQUEST_FAILED:"auth/network-request-failed",NULL_USER:"auth/null-user",NO_AUTH_EVENT:"auth/no-auth-event",NO_SUCH_PROVIDER:"auth/no-such-provider",OPERATION_NOT_ALLOWED:"auth/operation-not-allowed",OPERATION_NOT_SUPPORTED:"auth/operation-not-supported-in-this-environment",POPUP_BLOCKED:"auth/popup-blocked",POPUP_CLOSED_BY_USER:"auth/popup-closed-by-user",PROVIDER_ALREADY_LINKED:"auth/provider-already-linked",QUOTA_EXCEEDED:"auth/quota-exceeded",REDIRECT_CANCELLED_BY_USER:"auth/redirect-cancelled-by-user",REDIRECT_OPERATION_PENDING:"auth/redirect-operation-pending",REJECTED_CREDENTIAL:"auth/rejected-credential",SECOND_FACTOR_ALREADY_ENROLLED:"auth/second-factor-already-in-use",SECOND_FACTOR_LIMIT_EXCEEDED:"auth/maximum-second-factor-count-exceeded",TENANT_ID_MISMATCH:"auth/tenant-id-mismatch",TIMEOUT:"auth/timeout",TOKEN_EXPIRED:"auth/user-token-expired",TOO_MANY_ATTEMPTS_TRY_LATER:"auth/too-many-requests",UNAUTHORIZED_DOMAIN:"auth/unauthorized-continue-uri",UNSUPPORTED_FIRST_FACTOR:"auth/unsupported-first-factor",UNSUPPORTED_PERSISTENCE:"auth/unsupported-persistence-type",UNSUPPORTED_TENANT_OPERATION:"auth/unsupported-tenant-operation",UNVERIFIED_EMAIL:"auth/unverified-email",USER_CANCELLED:"auth/user-cancelled",USER_DELETED:"auth/user-not-found",USER_DISABLED:"auth/user-disabled",USER_MISMATCH:"auth/user-mismatch",USER_SIGNED_OUT:"auth/user-signed-out",WEAK_PASSWORD:"auth/weak-password",WEB_STORAGE_UNSUPPORTED:"auth/web-storage-unsupported",ALREADY_INITIALIZED:"auth/already-initialized",RECAPTCHA_NOT_ENABLED:"auth/recaptcha-not-enabled",MISSING_RECAPTCHA_TOKEN:"auth/missing-recaptcha-token",INVALID_RECAPTCHA_TOKEN:"auth/invalid-recaptcha-token",INVALID_RECAPTCHA_ACTION:"auth/invalid-recaptcha-action",MISSING_CLIENT_TYPE:"auth/missing-client-type",MISSING_RECAPTCHA_VERSION:"auth/missing-recaptcha-version",INVALID_RECAPTCHA_VERSION:"auth/invalid-recaptcha-version",INVALID_REQ_TYPE:"auth/invalid-req-type",INVALID_HOSTING_LINK_DOMAIN:"auth/invalid-hosting-link-domain"};const g=new s.Logger("@firebase/auth");function _logWarn(e,...t){if(g.logLevel<=s.LogLevel.WARN){g.warn(`Auth (${r.SDK_VERSION}): ${e}`,...t)}}function _logError(e,...t){if(g.logLevel<=s.LogLevel.ERROR){g.error(`Auth (${r.SDK_VERSION}): ${e}`,...t)}}function _fail(e,...t){throw createErrorInternal(e,...t)}function _createError(e,...t){return createErrorInternal(e,...t)}function _errorWithCustomMessage(e,t,n){const r={...p(),[t]:n};const s=new i.ErrorFactory("auth","Firebase",r);return s.create(t,{appName:e.name})}function _serverAppCurrentUserOperationNotSupportedError(e){return _errorWithCustomMessage(e,"operation-not-supported-in-this-environment","Operations that alter the current user are not supported in conjunction with FirebaseServerApp")}function _assertInstanceOf(e,t,n){const r=n;if(!(t instanceof r)){if(r.name!==t.constructor.name){_fail(e,"argument-error")}throw _errorWithCustomMessage(e,"argument-error",`Type of ${t.constructor.name} does not match expected instance.`+`Did you pass a reference from a different Auth SDK?`)}}function createErrorInternal(e,...t){if(typeof e!=="string"){const n=t[0];const r=[...t.slice(1)];if(r[0]){r[0].appName=e.name}return e._errorFactory.create(n,...r)}return f.create(e,...t)}function _assert(e,t,...n){if(!e){throw createErrorInternal(t,...n)}}function debugFail(e){const t=`INTERNAL ASSERTION FAILED: `+e;_logError(t);throw new Error(t)}function debugAssert(e,t){if(!e){debugFail(t)}}function _getCurrentUrl(){return typeof self!=="undefined"&&self.location?.href||""}function _isHttpOrHttps(){return _getCurrentScheme()==="http:"||_getCurrentScheme()==="https:"}function _getCurrentScheme(){return typeof self!=="undefined"&&self.location?.protocol||null}function _isOnline(){if(typeof navigator!=="undefined"&&navigator&&"onLine"in navigator&&typeof navigator.onLine==="boolean"&&(_isHttpOrHttps()||i.isBrowserExtension()||"connection"in navigator)){return navigator.onLine}return true}function _getUserLanguage(){if(typeof navigator==="undefined"){return null}const e=navigator;return e.languages&&e.languages[0]||e.language||null}class Delay{constructor(e,t){this.shortDelay=e;this.longDelay=t;debugAssert(t>
2e,"Short delay should be less than long delay!");this.isMobile=i.isMobileCordova()||i.isReactNative()}get(){if(!_isOnline()){return Math.min(5e3,this.shortDelay)}return this.isMobile?this.longDelay:this.shortDelay}}function _emulatorUrl(e,t){debugAssert(e.emulator,"Emulator should always be set here");const{url:n}=e.emulator;if(!t){return n}return`${n}${t.startsWith("/")?t.slice(1):t}`}class FetchProvider{static initialize(e,t,n){this.fetchImpl=e;if(t){this.headersImpl=t}if(n){this.responseImpl=n}}static fetch(){if(this.fetchImpl){return this.fetchImpl}if(typeof self!=="undefined"&&"fetch"in self){return self.fetch}if(typeof globalThis!=="undefined"&&globalThis.fetch){return globalThis.fetch}if(typeof fetch!=="undefined"){return fetch}debugFail("Could not find fetch implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill")}static headers(){if(this.headersImpl){return this.headersImpl}if(typeof self!=="undefined"&&"Headers"in self){return self.Headers}if(typeof globalThis!=="undefined"&&globalThis.Headers){return globalThis.Headers}if(typeof Headers!=="undefined"){return Headers}debugFail("Could not find Headers implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill")}static response(){if(this.responseImpl){return this.responseImpl}if(typeof self!=="undefined"&&"Response"in self){return self.Response}if(typeof globalThis!=="undefined"&&globalThis.Response){return globalThis.Response}if(typeof Response!=="undefined"){return Response}debugFail("Could not find Response implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill")}}const _={["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-recaptcha-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"};const v=["/v1/accounts:signInWithCustomToken","/v1/accounts:signInWithEmailLink","/v1/accounts:signInWithIdp","/v1/accounts:signInWithPassword","/v1/accounts:signInWithPhoneNumber","/v1/token"];const y=new Delay(3e4,6e4);function _addTidIfNecessary(e,t){if(e.tenantId&&!t.tenantId){return{...t,tenantId:e.tenantId}}return t}async function _performApiRequest(e,t,n,r,s={}){return _performFetchWithErrorHandling(e,s,(async()=>{let s={};let o={};if(r){if(t==="GET"){o=r}else{s={body:JSON.stringify(r)}}}const a=i.querystring({key:e.config.apiKey,...o}).slice(1);const c=await e._getAdditionalHeaders();c["Content-Type"]="application/json";if(e.languageCode){c["X-Firebase-Locale"]=e.languageCode}const l={method:t,headers:c,...s};if(!i.isCloudflareWorker()){l.referrerPolicy="no-referrer"}if(e.emulatorConfig&&i.isCloudWorkstation(e.emulatorConfig.host)){l.credentials="include"}
2return FetchProvider.fetch()(await _getFinalTarget(e,e.config.apiHost,n,a),l)}))}async function _performFetchWithErrorHandling(e,t,n){e._canInitEmulator=false;const r={..._,...t};try{const t=new NetworkTimeout(e);const i=await Promise.race([n(),t.promise]);t.clearNetworkTimeout();const s=await i.json();if("needConfirmation"in s){throw _makeTaggedError(e,"account-exists-with-different-credential",s)}if(i.ok&&!("errorMessage"in s)){return s}else{const t=i.ok?s.errorMessage:s.error.message;const[n,o]=t.split(" : ");if(n==="FEDERATED_USER_ID_ALREADY_LINKED"){throw _makeTaggedError(e,"credential-already-in-use",s)}else if(n==="EMAIL_EXISTS"){throw _makeTaggedError(e,"email-already-in-use",s)}else if(n==="USER_DISABLED"){throw _makeTaggedError(e,"user-disabled",s)}const a=r[n]||n.toLowerCase().replace(/[_\s]+/g,"-");if(o){throw _errorWithCustomMessage(e,a,o)}else{_fail(e,a)}}}catch(t){if(t instanceof i.FirebaseError){throw t}_fail(e,"network-request-failed",{message:String(t)})}}async function _performSignInRequest(e,t,n,r,i={}){const s=await _performApiRequest(e,t,n,r,i);if("mfaPendingCredential"in s){_fail(e,"multi-factor-auth-required",{_serverResponse:s})}return s}async function _getFinalTarget(e,t,n,r){const i=`${t}${n}?${r}`;const s=e;const o=s.config.emulator?_emulatorUrl(e.config,i):`${e.config.apiScheme}://${i}`;if(v.includes(n)){await s._persistenceManagerAvailable;if(s._getPersistenceType()==="COOKIE"){const e=s._getPersistence();return e._getFinalTarget(o).toString()}}return o}function _parseEnforcementState(e){switch(e){case"ENFORCE":return"ENFORCE";case"AUDIT":return"AUDIT";case"OFF":return"OFF";default:return"ENFORCEMENT_STATE_UNSPECIFIED"}}class NetworkTimeout{clearNetworkTimeout(){clearTimeout(this.timer)}constructor(e){this.auth=e;this.timer=null;this.promise=new Promise(((e,t)=>{this.timer=setTimeout((()=>t(_createError(this.auth,"network-request-failed"))),y.get())}))}}function _makeTaggedError(e,t,n){const r={appName:e.name};if(n.email){r.email=n.email}if(n.phoneNumber){r.phoneNumber=n.phoneNumber}const i=_createError(e,t,r);i.customData._tokenResponse=n;return i}function isV2(e){return e!==undefined&&e.getResponse!==undefined}function isEnterprise(e){return e!==undefined&&e.enterprise!==undefined}class RecaptchaConfig{constructor(e){this.siteKey="";this.recaptchaEnforcementState=[];if(e.recaptchaKey===undefined){throw new Error("recaptchaKey undefined")}this.siteKey=e.recaptchaKey.split("/")[3];this.recaptchaEnforcementState=e.recaptchaEnforcementState}getProviderEnforcementState(e){if(!this.recaptchaEnforcementState||this.recaptchaEnforcementState.length===0){return null}for(const t of this.recaptchaEnforcementState){if(t.provider&&t.provider===e){return _parseEnforcementState(t.enforcementState)}}return null}isProviderEnabled(e){return this.getProviderEnforcementState(e)==="ENFORCE"||this.getProviderEnforcementState(e)==="AUDIT"}isAnyProviderEnabled(){return this.isProviderEnabled("EMAIL_PASSWORD_PROVIDER")||this.isProviderEnabled("PHONE_PROVIDER")}}async function getRecaptchaParams(e){return(await _performApiRequest(e,"GET","/v1/recaptchaParams")).recaptchaSiteKey||""}async function getRecaptchaConfig(e,t){return _performApiRequest(e,"GET","/v2/recaptchaConfig",_addTidIfNecessary(e,t))}async function deleteAccount(e,t){return _performApiRequest(e,"POST","/v1/accounts:delete",t)}async function deleteLinkedAccounts(e,t){return _performApiRequest(e,"POST","/v1/accounts:update",t)}async function getAccountInfo(e,t){return _performApiRequest(e,"POST","/v1/accounts:lookup",t)}function utcTimestampToDateString(e){if(!e){return undefined}try{const t=new Date(Number(e));if(!isNaN(t.getTime())){return t.toUTCString()}}catch(e){}return undefined}function getIdToken(e,t=false){return i.getModularInstance(e).getIdToken(t)}async function getIdTokenResult(e,t=false){const n=i.getModularInstance(e);const r=await n.getIdToken(t);const s=_parseToken(r);_assert(s&&s.exp&&s.auth_time&&s.iat,n.auth,"internal-error");const o=typeof s.firebase==="object"?s.firebase:undefined;const a=o?.["sign_in_provider"];return{claims:s,token:r,authTime:utcTimestampToDateString(secondsStringToMilliseconds(s.auth_time)),issuedAtTime:utcTimestampToDateString(secondsStringToMilliseconds(s.iat)),expirationTime:utcTimestampToDateString(secondsStringToMilliseconds(s.exp
2)),signInProvider:a||null,signInSecondFactor:o?.["sign_in_second_factor"]||null}}function secondsStringToMilliseconds(e){return Number(e)*1e3}function _parseToken(e){const[t,n,r]=e.split(".");if(t===undefined||n===undefined||r===undefined){_logError("JWT malformed, contained fewer than 3 sections");return null}try{const e=i.base64Decode(n);if(!e){_logError("Failed to decode base64 JWT payload");return null}return JSON.parse(e)}catch(e){_logError("Caught error parsing JWT payload as JSON",e?.toString());return null}}function _tokenExpiresIn(e){const t=_parseToken(e);_assert(t,"internal-error");_assert(typeof t.exp!=="undefined","internal-error");_assert(typeof t.iat!=="undefined","internal-error");return Number(t.exp)-Number(t.iat)}async function _logoutIfInvalidated(e,t,n=false){if(n){return t}try{return await t}catch(t){if(t instanceof i.FirebaseError&&isUserInvalidated(t)){if(e.auth.currentUser===e){await e.auth.signOut()}}throw t}}function isUserInvalidated({code:e}){return e===`auth/${"user-disabled"}`||e===`auth/${"user-token-expired"}`}class ProactiveRefresh{constructor(e){this.user=e;this.isRunning=false;this.timerId=null;this.errorBackoff=3e4}_start(){if(this.isRunning){return}this.isRunning=true;this.schedule()}_stop(){if(!this.isRunning){return}this.isRunning=false;if(this.timerId!==null){clearTimeout(this.timerId)}}getInterval(e){if(e){const e=this.errorBackoff;this.errorBackoff=Math.min(this.errorBackoff*2,96e4);return e}else{this.errorBackoff=3e4;const e=this.user.stsTokenManager.expirationTime??0;const t=e-Date.now()-3e5;return Math.max(0,t)}}schedule(e=false){if(!this.isRunning){return}const t=this.getInterval(e);this.timerId=setTimeout((async()=>{await this.iteration()}),t)}async iteration(){try{await this.user.getIdToken(true)}catch(e){if(e?.code===`auth/${"network-request-failed"}`){this.schedule(true)}return}this.schedule()}}class UserMetadata{constructor(e,t){this.createdAt=e;this.lastLoginAt=t;this._initializeTime()}_initializeTime(){this.lastSignInTime=utcTimestampToDateString(this.lastLoginAt);this.creationTime=utcTimestampToDateString(this.createdAt)}_copy(e){this.createdAt=e.createdAt;this.lastLoginAt=e.lastLoginAt;this._initializeTime()}toJSON(){return{createdAt:this.createdAt,lastLoginAt:this.lastLoginAt}}}async function _reloadWithoutSaving(e){const t=e.auth;const n=await e.getIdToken();const r=await _logoutIfInvalidated(e,getAccountInfo(t,{idToken:n}));_assert(r?.users.length,t,"internal-error");const i=r.users[0];e._notifyReloadListener(i);const s=i.providerUserInfo?.length?extractProviderData(i.providerUserInfo):[];const o=mergeProviderData(e.providerData,s);const a=e.isAnonymous;const c=!(e.email&&i.passwordHash)&&!o?.length;const l=!a?false:c;const u={uid:i.localId,displayName:i.displayName||null,photoURL:i.photoUrl||null,email:i.email||null,emailVerified:i.emailVerified||false,phoneNumber:i.phoneNumber||null,tenantId:i.tenantId||null,providerData:o,metadata:new UserMetadata(i.createdAt,i.lastLoginAt),isAnonymous:l};Object.assign(e,u)}async function reload(e){const t=i.getModularInstance(e);await _reloadWithoutSaving(t);await t.auth._persistUserIfCurrent(t);t.auth._notifyListenersIfCurrent(t)}function mergeProviderData(e,t){const n=e.filter((e=>!t.some((t=>t.providerId===e.providerId))));return[...n,...t]}function extractProviderData(e){return e.map((({providerId:e,...t})=>({providerId:e,uid:t.rawId||"",displayName:t.displayName||null,email:t.email||null,phoneNumber:t.phoneNumber||null,photoURL:t.photoUrl||null})))}async function requestStsToken(e,t){const n=await _performFetchWithErrorHandling(e,{},(async()=>{const n=i.querystring({grant_type:"refresh_token",refresh_token:t}).slice(1);const{tokenApiHost:r,apiKey:s}=e.config;const o=await _getFinalTarget(e,r,"/v1/token",`key=${s}`);const a=await e._getAdditionalHeaders();a["Content-Type"]="application/x-www-form-urlencoded";const c={method:"POST",headers:a,body:n};if(e.emulatorConfig&&i.isCloudWorkstation(e.emulatorConfig.host)){c.credentials="include"}return FetchProvider.fetch()(o,c)}));return{accessToken:n.access_token,expiresIn:n.expires_in,refreshToken:n.refresh_token}}async function revokeToken(e,t){return _performApiRequest(e,"POST","/v2/accounts:revokeToken",_addTidIfNecessary(e,t))}class StsTokenManager{constructor(){this.refreshToken=null;this.accessToken=null;this.expirationTime=null}get isExpired(){return!this.expirationTime||Date.now()>this.expirationTime-3e4}updateFromServerResponse(e){_assert(e.idToken,"internal-error");_assert(typeof e.idToken!=="undefined","internal-error");_assert(typeof e.refreshToken!=="undefined","internal-error");
2const t="expiresIn"in e&&typeof e.expiresIn!=="undefined"?Number(e.expiresIn):_tokenExpiresIn(e.idToken);this.updateTokensAndExpiration(e.idToken,e.refreshToken,t)}updateFromIdToken(e){_assert(e.length!==0,"internal-error");const t=_tokenExpiresIn(e);this.updateTokensAndExpiration(e,null,t)}async getToken(e,t=false){if(!t&&this.accessToken&&!this.isExpired){return this.accessToken}_assert(this.refreshToken,e,"user-token-expired");if(this.refreshToken){await this.refresh(e,this.refreshToken);return this.accessToken}return null}clearRefreshToken(){this.refreshToken=null}async refresh(e,t){const{accessToken:n,refreshToken:r,expiresIn:i}=await requestStsToken(e,t);this.updateTokensAndExpiration(n,r,Number(i))}updateTokensAndExpiration(e,t,n){this.refreshToken=t||null;this.accessToken=e||null;this.expirationTime=Date.now()+n*1e3}static fromJSON(e,t){const{refreshToken:n,accessToken:r,expirationTime:i}=t;const s=new StsTokenManager;if(n){_assert(typeof n==="string","internal-error",{appName:e});s.refreshToken=n}if(r){_assert(typeof r==="string","internal-error",{appName:e});s.accessToken=r}if(i){_assert(typeof i==="number","internal-error",{appName:e});s.expirationTime=i}return 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 StsTokenManager,this.toJSON())}_performRefresh(){return debugFail("not implemented")}}function assertStringOrUndefined(e,t){_assert(typeof e==="string"||typeof e==="undefined","internal-error",{appName:t})}class UserImpl{constructor({uid:e,auth:t,stsTokenManager:n,...r}){this.providerId="firebase";this.proactiveRefresh=new ProactiveRefresh(this);this.reloadUserInfo=null;this.reloadListener=null;this.uid=e;this.auth=t;this.stsTokenManager=n;this.accessToken=n.accessToken;this.displayName=r.displayName||null;this.email=r.email||null;this.emailVerified=r.emailVerified||false;this.phoneNumber=r.phoneNumber||null;this.photoURL=r.photoURL||null;this.isAnonymous=r.isAnonymous||false;this.tenantId=r.tenantId||null;this.providerData=r.providerData?[...r.providerData]:[];this.metadata=new UserMetadata(r.createdAt||undefined,r.lastLoginAt||undefined)}async getIdToken(e){const t=await _logoutIfInvalidated(this,this.stsTokenManager.getToken(this.auth,e));_assert(t,this.auth,"internal-error");if(this.accessToken!==t){this.accessToken=t;await this.auth._persistUserIfCurrent(this);this.auth._notifyListenersIfCurrent(this)}return t}getIdTokenResult(e){return getIdTokenResult(this,e)}reload(){return reload(this)}_assign(e){if(this===e){return}_assert(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){const t=new UserImpl({...this,auth:e,stsTokenManager:this.stsTokenManager._clone()});t.metadata._copy(this.metadata);return t}_onReload(e){_assert(!this.reloadListener,this.auth,"internal-error");this.reloadListener=e;if(this.reloadUserInfo){this._notifyReloadListener(this.reloadUserInfo);this.reloadUserInfo=null}}_notifyReloadListener(e){if(this.reloadListener){this.reloadListener(e)}else{this.reloadUserInfo=e}}_startProactiveRefresh(){this.proactiveRefresh._start()}_stopProactiveRefresh(){this.proactiveRefresh._stop()}async _updateTokensIfNecessary(e,t=false){let n=false;if(e.idToken&&e.idToken!==this.stsTokenManager.accessToken){this.stsTokenManager.updateFromServerResponse(e);n=true}if(t){await _reloadWithoutSaving(this)}await this.auth._persistUserIfCurrent(this);if(n){this.auth._notifyListenersIfCurrent(this)}}async delete(){if(r._isFirebaseServerApp(this.auth.app)){return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(this.auth))}const e=await this.getIdToken();await _logoutIfInvalidated(this,deleteAccount(this.auth,{idToken:e}));this.stsTokenManager.clearRefreshToken();return this.auth.signOut()}toJSON(){return{uid:this.uid,email:this.email||undefined,emailVerified:this.emailVerified,displayName:this.displayName||undefined,isAnonymous:this.isAnonymous,photoURL:this.photoURL||undefined,phoneNumber:this.phoneNumber||undefined,tenantId:this.tenantId||undefined,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){const n=t.displayName??undefined;const r=t.email??undefined;const i=t.phoneNumber??undefined;const s=t.photoURL??undefined;const o=t.tenantId??undefined;const a=t._redirectEventId??undefined;const c=t.createdAt??undefined;const l=t.lastLoginAt??undefined;const{uid:u,emailVerified:d,isAnonymous:h,providerData:p,stsTokenManager:f}=t;_assert(u&&f,e,"internal-error");const m=StsTokenManager.fromJSON(this.name,f);_assert(typeof u==="string",e,"internal-error");assertStringOrUndefined(n,e.name);assertStringOrUndefined(r,e.name);_assert(typeof d==="boolean",e,"internal-error");_assert(typeof h==="boolean",e,"internal-error");assertStringOrUndefined(i,e.name);assertStringOrUndefined(s,e.name);assertStringOrUndefined(o,e.name);assertStringOrUndefined(a,e.name);assertStringOrUndefined(c,e.name);assertStringOrUndefined(l,e.name);const g=new UserImpl({uid:u,auth:e,email:r,emailVerified:d,displayName:n,isAnonymous:h,photoURL:s,phoneNumber:i,tenantId:o,stsTokenManager:m,createdAt:c,lastLoginAt:l});if(p&&Array.isArray(p)){g.providerData=p.map((e=>({...e})))}if(a){g._redirectEventId=a}return g}static async _fromIdTokenResponse(e,t,n=false){const r=new StsTokenManager;r.updateFromServerResponse(t);const i=new UserImpl({uid:t.localId,auth:e,stsTokenManager:r,isAnonymous:n});await _reloadWithoutSaving(i);return i}static async _fromGetAccountInfoResponse(e,t,n){const r=t.users[0];_assert(r.localId!==undefined,"internal-error");const i=r.providerUserInfo!==undefined?extractProviderData(r.providerUserInfo):[];const s=!(r.email&&r.passwordHash)&&!i?.length;const o=new StsTokenManager;o.updateFromIdToken(n);const a=new UserImpl({uid:r.localId,auth:e,stsTokenManager:o,isAnonymous:s});const c={uid:r.localId,displayName:r.displayName||null,photoURL:r.photoUrl||null,email:r.email||null,emailVerified:r.emailVerified||false,ph
2oneNumber:r.phoneNumber||null,tenantId:r.tenantId||null,providerData:i,metadata:new UserMetadata(r.createdAt,r.lastLoginAt),isAnonymous:!(r.email&&r.passwordHash)&&!i?.length};Object.assign(a,c);return a}}const I=new Map;function _getInstance(e){debugAssert(e instanceof Function,"Expected a class definition");let t=I.get(e);if(t){debugAssert(t instanceof e,"Instance stored in cache mismatched with class");return t}t=new e;I.set(e,t);return t}class InMemoryPersistence{constructor(){this.type="NONE";this.storage={}}async _isAvailable(){return true}async _set(e,t){this.storage[e]=t}async _get(e){const t=this.storage[e];return t===undefined?null:t}async _remove(e){delete this.storage[e]}_addListener(e,t){return}_removeListener(e,t){return}}InMemoryPersistence.type="NONE";const C=InMemoryPersistence;function _persistenceKeyName(e,t,n){return`${"firebase"}:${e}:${t}:${n}`}class PersistenceUserManager{constructor(e,t,n){this.persistence=e;this.auth=t;this.userKey=n;const{config:r,name:i}=this.auth;this.fullUserKey=_persistenceKeyName(this.userKey,r.apiKey,i);this.fullPersistenceKey=_persistenceKeyName("persistence",r.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(){const e=await this.persistence._get(this.fullUserKey);if(!e){return null}if(typeof e==="string"){const t=await getAccountInfo(this.auth,{idToken:e}).catch((()=>undefined));if(!t){return null}return UserImpl._fromGetAccountInfoResponse(this.auth,t,e)}return UserImpl._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}const t=await this.getCurrentUser();await this.removeCurrentUser();this.persistence=e;if(t){return this.setCurrentUser(t)}}delete(){this.persistence._removeListener(this.fullUserKey,this.boundEventHandler)}static async create(e,t,n="authUser"){if(!t.length){return new PersistenceUserManager(_getInstance(C),e,n)}const r=(await Promise.all(t.map((async e=>{if(await e._isAvailable()){return e}return undefined})))).filter((e=>e));let i=r[0]||_getInstance(C);const s=_persistenceKeyName(n,e.config.apiKey,e.name);let o=null;for(const n of t){try{const t=await n._get(s);if(t){let r;if(typeof t==="string"){const n=await getAccountInfo(e,{idToken:t}).catch((()=>undefined));if(!n){break}r=await UserImpl._fromGetAccountInfoResponse(e,n,t)}else{r=UserImpl._fromJSON(e,t)}if(n!==i){o=r}i=n;break}}catch{}}const a=r.filter((e=>e._shouldAllowMigration));if(!i._shouldAllowMigration||!a.length){return new PersistenceUserManager(i,e,n)}i=a[0];if(o){await i._set(s,o.toJSON())}await Promise.all(t.map((async e=>{if(e!==i){try{await e._remove(s)}catch{}}})));return new PersistenceUserManager(i,e,n)}}function _getBrowserName(e){const t=e.toLowerCase();if(t.includes("opera/")||t.includes("opr/")||t.includes("opios/")){return"Opera"}else if(_isIEMobile(t)){return"IEMobile"}else if(t.includes("msie")||t.includes("trident/")){return"IE"}else if(t.includes("edge/")){return"Edge"}else if(_isFirefox(t)){return"Firefox"}else if(t.includes("silk/")){return"Silk"}else if(_isBlackBerry(t)){return"Blackberry"}else if(_isWebOS(t)){return"Webos"}else if(_isSafari(t)){return"Safari"}else if((t.includes("chrome/")||_isChromeIOS(t))&&!t.includes("edge/")){return"Chrome"}else if(_isAndroid(t)){return"Android"}else{const t=/([a-zA-Z\d\.]+)\/[a-zA-Z\d\.]*$/;const n=e.match(t);if(n?.length===2){return n[1]}}return"Other"}function _isFirefox(e=i.getUA()){return/firefox\//i.test(e)}function _isSafari(e=i.getUA()){const t=e.toLowerCase();return t.includes("safari/")&&!t.includes("chrome/")&&!t.includes("crios/")&&!t.includes("android")}function _isChromeIOS(e=i.getUA()){return/crios\//i.test(e)}function _isIEMobile(e=i.getUA()){return/iemobile/i.test(e)}function _isAndroid(e=i.getUA()){return/android/i.test(e)}function _isBlackBerry(e=i.getUA()){return/blackberry/i.test(e)}function _isWebOS(e=i.getUA()){return/webos/i.test(e)}function _isIOS(e=i.getUA()){return/iphone|ipad|ipod/i.test(e)||/macintosh/i.test(e)&&/mobile/i.test(e)}function _isIOS7Or8(e=i.getUA()){return/(iPad|iPhone|iPod).*OS 7_\d/i.test(e)||/(iPad|iPhone|iPod).*OS 8_\d/i.test(e)}function _isIOSStandalone(e=i.getUA()){return _isIOS(e)&&!!window.navigator?.standalone}function _isIE10(){return i.isIE()&&document.documentMode===10}function _isMobileBrowser(e=i.getUA()){return _isIOS(e)||_isAndroid(e)||_isWebOS(e)||_isBlackBerry(e)||/windows phone/i.test(e)||_isIEMobile(e)}function _getClientVersion(e,t=[]){let n;switch(e){case"Browser":n=_getBrowserName(i.getUA());break;case"Worker":n=`${_getBrowserName(i.getUA())}-${e}`;break;default:n=e}const s=t.length?t.join(","):"FirebaseCore-web";return`${n}/${"JsCore"}/${r.SDK_VERSION}/${s}`}class AuthMiddlewareQueue{constructor(e){this.auth=e;this.queue=[]}pushCallback(e,t){const wrappedCallback=t=>new Promise(((n,r)=>{try{const r=e(t);n(r)}catch(e){r(e)}}));wrappedCallback.onAbort=t;this.queue.push(wrappedCallback);const n=this.queue.length-1;return()=>{this.queue[n]=()=>Promise.resolve()}}async runMiddleware(e){if(this.auth.currentUser===e){return}const t=[];try{for(const n of this.queue){await n(e);if(n.onAbort){t.push(n.onAbort)}}}catch(e){t.reverse();for(const e of t){try{e()}catch(e){}}throw this.auth._errorFactory.create("login-blocked",{originalMessage:e?.message})}}}async function _getPasswordPolicy(e,t={}){return _performApiRequest(e,"GET","/v2/passwordPolicy",_addTidIfNecessary(e,t))}const w=6;class PasswordPolicyImpl{constructor(e){const t=e.customStrengthOptions;this.customStrengthOptions={};this.customStrengthOptions.minPasswordLength=t.minPasswordLength??w;if(t.maxPasswordLength){this.customStrengthOptions.maxPasswordLength=t.maxPasswordLength}if(t.containsLowercaseCharacter!==undefined){this.customStrengthOptions.containsLowercaseLetter=t.containsLowercaseCharacter}if(t.containsUppercaseCharacter!==undefined){this.customStrengthOptions.containsUppercaseLetter=t.containsUppercaseCharacter}if(t.containsNumericCharacter!==undefined){this.customStrengthOptions.containsNumericCharacter=t.containsNumericCharacter}if(t.containsNonAlphanumericCharacter!==undefined){this.customStrengthOptions.containsNonAlphanumericCharacter=t.containsNonAlphanumericCharacter}this.enforcementState=e.enforcementState;if(this.enforcementState==="ENFORCEMENT_STATE_UNSPECIFIED"){this.enforcementState="OFF"}this.allowedNonAlphanumericCharacters=e.allowedNonAlphanumericCharacters?.join("")??"";this.forceUpgradeOnSignin=e.forceUpgradeOnSignin??false;this.schemaVersion=e.schemaVersion}validatePassword(e){const t={isValid:true,passwordPolicy:this};this.validatePasswordLengthOptions(e,t);this.validatePasswordCharacterOptions(e,t);
2t.isValid&&(t.isValid=t.meetsMinPasswordLength??true);t.isValid&&(t.isValid=t.meetsMaxPasswordLength??true);t.isValid&&(t.isValid=t.containsLowercaseLetter??true);t.isValid&&(t.isValid=t.containsUppercaseLetter??true);t.isValid&&(t.isValid=t.containsNumericCharacter??true);t.isValid&&(t.isValid=t.containsNonAlphanumericCharacter??true);return t}validatePasswordLengthOptions(e,t){const n=this.customStrengthOptions.minPasswordLength;const r=this.customStrengthOptions.maxPasswordLength;if(n){t.meetsMinPasswordLength=e.length>=n}if(r){t.meetsMaxPasswordLength=e.length<=r}}validatePasswordCharacterOptions(e,t){this.updatePasswordCharacterOptionsStatuses(t,false,false,false,false);let n;for(let r=0;r<e.length;r++){n=e.charAt(r);this.updatePasswordCharacterOptionsStatuses(t,n>="a"&&n<="z",n>="A"&&n<="Z",n>="0"&&n<="9",this.allowedNonAlphanumericCharacters.includes(n))}}updatePasswordCharacterOptionsStatuses(e,t,n,r,i){if(this.customStrengthOptions.containsLowercaseLetter){e.containsLowercaseLetter||(e.containsLowercaseLetter=t)}if(this.customStrengthOptions.containsUppercaseLetter){e.containsUppercaseLetter||(e.containsUppercaseLetter=n)}if(this.customStrengthOptions.containsNumericCharacter){e.containsNumericCharacter||(e.containsNumericCharacter=r)}if(this.customStrengthOptions.containsNonAlphanumericCharacter){e.containsNonAlphanumericCharacter||(e.containsNonAlphanumericCharacter=i)}}}class AuthImpl{constructor(e,t,n,r){this.app=e;this.heartbeatServiceProvider=t;this.appCheckServiceProvider=n;this.config=r;this.currentUser=null;this.emulatorConfig=null;this.operations=Promise.resolve();this.authStateSubscription=new Subscription(this);this.idTokenSubscription=new Subscription(this);this.beforeStateQueue=new AuthMiddlewareQueue(this);this.redirectUser=null;this.isProactiveRefreshEnabled=false;this.EXPECTED_PASSWORD_POLICY_SCHEMA_VERSION=1;this._canInitEmulator=true;this._isInitialized=false;this._deleted=false;this._initializationPromise=null;this._popupRedirectResolver=null;this._errorFactory=f;this._agentRecaptchaConfig=null;this._tenantRecaptchaConfigs={};this._projectPasswordPolicy=null;this._tenantPasswordPolicies={};this._resolvePersistenceManagerAvailable=undefined;this.lastNotifiedUid=undefined;this.languageCode=null;this.tenantId=null;this.settings={appVerificationDisabledForTesting:false};this.frameworks=[];this.name=e.name;this.clientVersion=r.sdkClientVersion;this._persistenceManagerAvailable=new Promise((e=>this._resolvePersistenceManagerAvailable=e))}_initializeWithPersistence(e,t){if(t){this._popupRedirectResolver=_getInstance(t)}this._initializationPromise=this.queue((async()=>{if(this._deleted){return}this.persistenceManager=await PersistenceUserManager.create(this,e);this._resolvePersistenceManagerAvailable?.();if(this._deleted){return}if(this._popupRedirectResolver?._shouldInitProactively){try{await this._popupRedirectResolver._initialize(this)}catch(e){}}await this.initializeCurrentUser(t);this.lastNotifiedUid=this.currentUser?.uid||null;if(this._deleted){return}this._isInitialized=true}));return this._initializationPromise}async _onStorageEvent(){if(this._deleted){return}const e=await this.assertedPersistence.getCurrentUser();if(!this.currentUser&&!e){return}if(this.currentUser&&e&&this.currentUser.uid===e.uid){this._currentUser._assign(e);await this.currentUser.getIdToken();return}await this._updateCurrentUser(e,true)}async initializeCurrentUserFromIdToken(e){try{const t=await getAccountInfo(this,{idToken:e});const n=await UserImpl._fromGetAccountInfoResponse(this,t,e);await this.directlySetCurrentUser(n)}catch(e){console.warn("FirebaseServerApp could not login user with provided authIdToken: ",e);await this.directlySetCurrentUser(null)}}async initializeCurrentUser(e){if(r._isFirebaseServerApp(this.app)){const e=this.app.settings.authIdToken;if(e){return new Promise((t=>{setTimeout((()=>this.initializeCurrentUserFromIdToken(e).then(t,t)))}))}else{return this.directlySetCurrentUser(null)}}const t=await this.assertedPersistence.getCurrentUser();let n=t;let i=false;if(e&&this.config.authDomain){await this.getOrInitRedirectPersistenceManager();const t=this.redirectUser?._redirectEventId;const r=n?._redirectEventId;const s=await this.tryRedirectSignIn(e);if((!t||t===r)&&s?.user){n=s.user;i=true}}if(!n){return this.directlySetCurrentUser(null)}
2if(!n._redirectEventId){if(i){try{await this.beforeStateQueue.runMiddleware(n)}catch(e){n=t;this._popupRedirectResolver._overrideRedirectResult(this,(()=>Promise.reject(e)))}}if(n){return this.reloadAndSetCurrentUserOrClear(n)}else{return this.directlySetCurrentUser(null)}}_assert(this._popupRedirectResolver,this,"argument-error");await this.getOrInitRedirectPersistenceManager();if(this.redirectUser&&this.redirectUser._redirectEventId===n._redirectEventId){return this.directlySetCurrentUser(n)}return this.reloadAndSetCurrentUserOrClear(n)}async tryRedirectSignIn(e){let t=null;try{t=await this._popupRedirectResolver._completeRedirectFn(this,e,true)}catch(e){await this._setRedirectUser(null)}return t}async reloadAndSetCurrentUserOrClear(e){try{await _reloadWithoutSaving(e)}catch(e){if(e?.code!==`auth/${"network-request-failed"}`){return this.directlySetCurrentUser(null)}}return this.directlySetCurrentUser(e)}useDeviceLanguage(){this.languageCode=_getUserLanguage()}async _delete(){this._deleted=true}async updateCurrentUser(e){if(r._isFirebaseServerApp(this.app)){return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(this))}const t=e?i.getModularInstance(e):null;if(t){_assert(t.auth.config.apiKey===this.config.apiKey,this,"invalid-user-token")}return this._updateCurrentUser(t&&t._clone(this))}async _updateCurrentUser(e,t=false){if(this._deleted){return}if(e){_assert(this.tenantId===e.tenantId,this,"tenant-id-mismatch")}if(!t){await this.beforeStateQueue.runMiddleware(e)}return this.queue((async()=>{await this.directlySetCurrentUser(e);this.notifyAuthListeners()}))}async signOut(){if(r._isFirebaseServerApp(this.app)){return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(this))}await this.beforeStateQueue.runMiddleware(null);if(this.redirectPersistenceManager||this._popupRedirectResolver){await this._setRedirectUser(null)}return this._updateCurrentUser(null,true)}setPersistence(e){if(r._isFirebaseServerApp(this.app)){return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(this))}return this.queue((async()=>{await this.assertedPersistence.setPersistence(_getInstance(e))}))}_getRecaptchaConfig(){if(this.tenantId==null){return this._agentRecaptchaConfig}else{return this._tenantRecaptchaConfigs[this.tenantId]}}async validatePassword(e){if(!this._getPasswordPolicyInternal()){await this._updatePasswordPolicy()}const t=this._getPasswordPolicyInternal();if(t.schemaVersion!==this.EXPECTED_PASSWORD_POLICY_SCHEMA_VERSION){return Promise.reject(this._errorFactory.create("unsupported-password-policy-schema-version",{}))}return t.validatePassword(e)}_getPasswordPolicyInternal(){if(this.tenantId===null){return this._projectPasswordPolicy}else{return this._tenantPasswordPolicies[this.tenantId]}}async _updatePasswordPolicy(){const e=await _getPasswordPolicy(this);const t=new PasswordPolicyImpl(e);if(this.tenantId===null){this._projectPasswordPolicy=t}else{this._tenantPasswordPolicies[this.tenantId]=t}}_getPersistenceType(){return this.assertedPersistence.persistence.type}_getPersistence(){return this.assertedPersistence.persistence}_updateErrorMap(e){this._errorFactory=new i.ErrorFactory("auth","Firebase",e())}onAuthStateChanged(e,t,n){return this.registerStateListener(this.authStateSubscription,e,t,n)}beforeAuthStateChanged(e,t){return this.beforeStateQueue.pushCallback(e,t)}onIdTokenChanged(e,t,n){return this.registerStateListener(this.idTokenSubscription,e,t,n)}authStateReady(){return new Promise(((e,t)=>{if(this.currentUser){e()}else{const n=this.onAuthStateChanged((()=>{n();e()}),t)}}))}async revokeAccessToken(e){if(this.currentUser){const t=await this.currentUser.getIdToken();const n={providerId:"apple.com",tokenType:"ACCESS_TOKEN",token:e,idToken:t};if(this.tenantId!=null){n.tenantId=this.tenantId}await revokeToken(this,n)}}toJSON(){return{apiKey:this.config.apiKey,authDomain:this.config.authDomain,appName:this.name,currentUser:this._currentUser?.toJSON()}}async _setRedirectUser(e,t){const n=await this.getOrInitRedirectPersistenceManager(t);return e===null?n.removeCurrentUser():n.setCurrentUser(e)}async getOrInitRedirectPersistenceManager(e){if(!this.redirectPersistenceManager){const t=e&&_getInstance(e)||this._popupRedirectResolver;_assert(t,this,"argument-error");this.redirectPersistenceManager=await PersistenceUserManager.create(this,[_getInstance(t._redirectPersistence)],"redirectUser");this.redirectUser=await this.redirectPersistenceManager.getCurrentUser()}return this.redirectPersistenceManager}async _redirectUserForId(e){if(this._isInitialized){await this.queue((async()=>{}))}if(this._currentUser?._redirectEventId===e){return this._currentUser}if(this.redirectUser?._redirectEventId===e){return this.redirectUser}return null}async _persistUserIfCurrent(e){if(e===this.currentUser){return this.queue((async()=>this.directlySetCurrentUser(e)))}}_notifyListenersIfCurrent(e){if(e===this.currentUser){this.notifyAuthListeners()}}_key(){return`${this.config.authDomain}:${this.config.apiKey}:${this.name}`}_startProactiveRefresh(){this.isProactiveRefreshEnabled=true;if(this.currentUser){this._currentUser._startProactiveRefresh()}}_stopProactiveRefresh(){this.isProactiveRefreshEnabled=false;if(this.currentUser){this._currentUser._stopProactiveRefresh()}}get _currentUser(){return this.currentUser}notifyAuthListeners(){if(!this._isInitialized){return}this.idTokenSubscription.next(this.currentUser);const e=this.currentUser?.uid??null;if(this.lastNotifiedUid!==e){this.lastNotifiedUid=e;this.authStateSubscription.next(this.currentUser)}}registerStateListener(e,t,n,r){if(this._deleted){return()=>{}}const i=typeof t==="function"?t:t.next.bind(t);let s=false;const o=this._isInitialized?Promise.resolve():this._initializationPromise;_assert(o,this,"internal-error");o.then((()=>
2{if(s){return}i(this.currentUser)}));if(typeof t==="function"){const i=e.addObserver(t,n,r);return()=>{s=true;i()}}else{const n=e.addObserver(t);return()=>{s=true;n()}}}async directlySetCurrentUser(e){if(this.currentUser&&this.currentUser!==e){this._currentUser._stopProactiveRefresh()}if(e&&this.isProactiveRefreshEnabled){e._startProactiveRefresh()}this.currentUser=e;if(e){await this.assertedPersistence.setCurrentUser(e)}else{await this.assertedPersistence.removeCurrentUser()}}queue(e){this.operations=this.operations.then(e,e);return this.operations}get assertedPersistence(){_assert(this.persistenceManager,this,"internal-error");return this.persistenceManager}_logFramework(e){if(!e||this.frameworks.includes(e)){return}this.frameworks.push(e);this.frameworks.sort();this.clientVersion=_getClientVersion(this.config.clientPlatform,this._getFrameworks())}_getFrameworks(){return this.frameworks}async _getAdditionalHeaders(){const e={["X-Client-Version"]:this.clientVersion};if(this.app.options.appId){e["X-Firebase-gmpid"]=this.app.options.appId}const t=await(this.heartbeatServiceProvider.getImmediate({optional:true})?.getHeartbeatsHeader());if(t){e["X-Firebase-Client"]=t}const n=await this._getAppCheckToken();if(n){e["X-Firebase-AppCheck"]=n}return e}async _getAppCheckToken(){if(r._isFirebaseServerApp(this.app)&&this.app.settings.appCheckToken){return this.app.settings.appCheckToken}const e=await(this.appCheckServiceProvider.getImmediate({optional:true})?.getToken());if(e?.error){_logWarn(`Error while retrieving App Check token: ${e.error}`)}return e?.token}}function _castAuth(e){return i.getModularInstance(e)}class Subscription{constructor(e){this.auth=e;this.observer=null;this.addObserver=i.createSubscribe((e=>this.observer=e))}get next(){_assert(this.observer,this.auth,"internal-error");return this.observer.next.bind(this.observer)}}let E={async loadJS(){throw new Error("Unable to load external scripts")},recaptchaV2Script:"",recaptchaEnterpriseScript:"",gapiScript:""};function _setExternalJSProvider(e){E=e}function _loadJS(e){return E.loadJS(e)}function _recaptchaV2ScriptUrl(){return E.recaptchaV2Script}function _recaptchaEnterpriseScriptUrl(){return E.recaptchaEnterpriseScript}function _gapiScriptUrl(){return E.gapiScript}function _generateCallbackName(e){return`__${e}${Math.floor(Math.random()*1e6)}`}const T=500;const P=6e4;const A=1e12;class MockReCaptcha{constructor(e){this.auth=e;this.counter=A;this._widgets=new Map}render(e,t){const n=this.counter;this._widgets.set(n,new MockWidget(e,this.auth.name,t||{}));this.counter++;return n}reset(e){const t=e||A;void this._widgets.get(t)?.delete();this._widgets.delete(t)}getResponse(e){const t=e||A;return this._widgets.get(t)?.getResponse()||""}async execute(e){const t=e||A;void this._widgets.get(t)?.execute();return""}}class MockGreCAPTCHATopLevel{constructor(){this.enterprise=new MockGreCAPTCHA}ready(e){e()}execute(e,t){return Promise.resolve("token")}render(e,t){return""}}class MockGreCAPTCHA{ready(e){e()}execute(e,t){return Promise.resolve("token")}render(e,t){return""}}class MockWidget{constructor(e,t,n){this.params=n;this.timerId=null;this.deleted=false;this.responseToken=null;this.clickHandler=()=>{this.execute()};const r=typeof e==="string"?document.getElementById(e):e;_assert(r,"argument-error",{appName:t});this.container=r;this.isVisible=this.params.size!=="invisible";if(this.isVisible){this.execute()}else{this.container.addEventListener("click",this.clickHandler)}}getResponse(){this.checkIfDeleted();return this.responseToken}delete(){this.checkIfDeleted();this.deleted=true;if(this.timerId){clearTimeout(this.timerId);this.timerId=null}this.container.removeEventListener("click",this.clickHandler)}execute(){this.checkIfDeleted();if(this.timerId){return}this.timerId=window.setTimeout((()=>{this.responseToken=generateRandomAlphaNumericString(50);const{callback:e,"expired-callback":t}=this.params;if(e){try{e(this.responseToken)}catch(e){}}this.timerId=window.setTimeout((()=>{this.timerId=null;this.responseToken=null;if(t){try{t()}catch(e){}}if(this.isVisible){this.execute()}}),P)}),T)}checkIfDeleted(){if(this.deleted){throw new Error("reCAPTCHA mock was already deleted!")}}}function generateRandomAlphaNumericString(e){const t=[];const n="1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";for(let r=0;r<e;r++){t.push(n.charAt(Math.floor(Math.random()*n.length)))}return t.join("")}const S="recaptcha-enterprise";const b="NO_RECAPTCHA";class RecaptchaEnterpriseVerifier{constructor(e){this.type=S;this.auth=_castAuth(e)}async verify(e="verify",t=false){async function retrieveSiteKey(e){if(!t){if(e.tenantId==null&&e._agentRecaptchaConfig!=null){return e._agentRecaptchaConfig.siteKey}if(e.tenantId!=null&&e._tenantRecaptchaConfigs[e.tenantId]!==undefined){return e._tenantRecaptchaConfigs[e.tenantId].siteKey}}return new Promise((async(t,n)=>
2{getRecaptchaConfig(e,{clientType:"CLIENT_TYPE_WEB",version:"RECAPTCHA_ENTERPRISE"}).then((r=>{if(r.recaptchaKey===undefined){n(new Error("recaptcha Enterprise site key undefined"))}else{const n=new RecaptchaConfig(r);if(e.tenantId==null){e._agentRecaptchaConfig=n}else{e._tenantRecaptchaConfigs[e.tenantId]=n}return t(n.siteKey)}})).catch((e=>{n(e)}))}))}function retrieveRecaptchaToken(t,n,r){const i=window.grecaptcha;if(isEnterprise(i)){i.enterprise.ready((()=>{i.enterprise.execute(t,{action:e}).then((e=>{n(e)})).catch((()=>{n(b)}))}))}else{r(Error("No reCAPTCHA enterprise script loaded."))}}if(this.auth.settings.appVerificationDisabledForTesting){const e=new MockGreCAPTCHATopLevel;return e.execute("siteKey",{action:"verify"})}return new Promise(((e,n)=>{retrieveSiteKey(this.auth).then((r=>{if(!t&&isEnterprise(window.grecaptcha)){retrieveRecaptchaToken(r,e,n)}else{if(typeof window==="undefined"){n(new Error("RecaptchaVerifier is only supported in browser"));return}let t=_recaptchaEnterpriseScriptUrl();if(t.length!==0){t+=r}_loadJS(t).then((()=>{retrieveRecaptchaToken(r,e,n)}
2)).catch((e=>{n(e)}))}})).catch((e=>{n(e)}))}))}}async function injectRecaptchaFields(e,t,n,r=false,i=false){const s=new RecaptchaEnterpriseVerifier(e);let o;if(i){o=b}else{try{o=await s.verify(n)}catch(e){o=await s.verify(n,true)}}const a={...t};if(n==="mfaSmsEnrollment"||n==="mfaSmsSignIn"){if("phoneEnrollmentInfo"in a){const e=a.phoneEnrollmentInfo.phoneNumber;const t=a.phoneEnrollmentInfo.recaptchaToken;Object.assign(a,{phoneEnrollmentInfo:{phoneNumber:e,recaptchaToken:t,captchaResponse:o,clientType:"CLIENT_TYPE_WEB",recaptchaVersion:"RECAPTCHA_ENTERPRISE"}})}else if("phoneSignInInfo"in a){const e=a.phoneSignInInfo.recaptchaToken;Object.assign(a,{phoneSignInInfo:{recaptchaToken:e,captchaResponse:o,clientType:"CLIENT_TYPE_WEB",recaptchaVersion:"RECAPTCHA_ENTERPRISE"}})}return a}if(!r){Object.assign(a,{captchaResponse:o})}else{Object.assign(a,{captchaResp:o})}Object.assign(a,{clientType:"CLIENT_TYPE_WEB"});Object.assign(a,{recaptchaVersion:"RECAPTCHA_ENTERPRISE"});return a}async function handleRecaptchaFlow(e,t,n,r,i){if(i==="EMAIL_PASSWORD_PROVIDER"){if(e._getRecaptchaConfig()?.isProviderEnabled("EMAIL_PASSWORD_PROVIDER")){const i=await injectRecaptchaFields(e,t,n,n==="getOobCode");return r(e,i)}else{return r(e,t).catch((async i=>{if(i.code===`auth/${"missing-recaptcha-token"}`){console.log(`${n} is protected by reCAPTCHA Enterprise for this project. Automatically triggering the reCAPTCHA flow and restarting the flow.`);const i=await injectRecaptchaFields(e,t,n,n==="getOobCode");return r(e,i)}else{return Promise.reject(i)}}))}}else if(i==="PHONE_PROVIDER"){if(e._getRecaptchaConfig()?.isProviderEnabled("PHONE_PROVIDER")){const i=await injectRecaptchaFields(e,t,n);return r(e,i).catch((async i=>{if(e._getRecaptchaConfig()?.getProviderEnforcementState("PHONE_PROVIDER")==="AUDIT"){if(i.code===`auth/${"missing-recaptcha-token"}`||i.code===`auth/${"invalid-app-credential"}`){console.log(`Failed to verify with reCAPTCHA Enterprise. Automatically triggering the reCAPTCHA v2 flow to complete the ${n} flow.`);const i=await injectRecaptchaFields(e,t,n,false,true);return r(e,i)}}return Promise.reject(i)}))}else{const i=await injectRecaptchaFields(e,t,n,false,true);return r(e,i)}}else{return Promise.reject(i+" provider is not supported.")}}async function _initializeRecaptchaConfig(e){const t=_castAuth(e);const n=await getRecaptchaConfig(t,{clientType:"CLIENT_TYPE_WEB",version:"RECAPTCHA_ENTERPRISE"});const r=new RecaptchaConfig(n);if(t.tenantId==null){t._agentRecaptchaConfig=r}else{t._tenantRecaptchaConfigs[t.tenantId]=r}if(r.isAnyProviderEnabled()){const e=new RecaptchaEnterpriseVerifier(t);void e.verify()}}function initializeAuth(e,t){const n=r._getProvider(e,"auth");if(n.isInitialized()){const e=n.getImmediate();const r=n.getOptions();if(i.deepEqual(r,t??{})){return e}else{_fail(e,"already-initialized")}}const s=n.initialize({options:t});return s}function _initializeAuthInstance(e,t){const n=t?.persistence||[];const r=(Array.isArray(n)?n:[n]).map(_getInstance);if(t?.errorMap){e._updateErrorMap(t.errorMap)}e._initializeWithPersistence(r,t?.popupRedirectResolver)}function connectAuthEmulator(e,t,n){const r=_castAuth(e);_assert(/^https?:\/\//.test(t),r,"invalid-emulator-scheme");const s=!!n?.disableWarnings;const o=extractProtocol(t);const{host:a,port:c}=extractHostAndPort(t);const l=c===null?"":`:${c}`;const u={url:`${o}//${a}${l}/`};const d=Object.freeze({host:a,port:c,protocol:o.replace(":",""),options:Object.freeze({disableWarnings:s})});if(!r._canInitEmulator){_assert(r.config.emulator&&r.emulatorConfig,r,"emulator-config-failed");_assert(i.deepEqual(u,r.config.emulator)&&i.deepEqual(d,r.emulatorConfig),r,"emulator-config-failed");return}r.config.emulator=u;r.emulatorConfig=d;r.settings.appVerificationDisabledForTesting=true;if(i.isCloudWorkstation(a)){void i.pingServer(`${o}//${a}${l}`)}else if(!s){emitEmulatorWarning()}}function extractProtocol(e){const t=e.indexOf(":");return t<0?"":e.substr(0,t+1)}function extractHostAndPort(e){const t=extractProtocol(e);const n=/(\/\/)?([^?#/]+)/.exec(e.substr(t.length));if(!n){return{host:"",port:null}}const r=n[2].split("@").pop()||"";const i=/^(\[[^\]]+\])(:|$)/.exec(r);if(i){const e=i[1];return{host:e,port:parsePort(r.substr(e.length+1))}}else{const[e,t]=r.split(":");return{host:e,port:parsePort(t)}}}function parsePort(e){if(!e){return null}const t=Number(e);if(isNaN(t)){return null}return t}function emitEmulatorWarning(){function attachBanner(){const e=document.createElement("p");const 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)}if(typeof console!=="undefined"&&typeof console.info==="function"){console.info("WARNING: You are using the Auth Emulator,"+" which is intended for local testing only.  Do not use with"+" production credentials.")}if(typeof window!=="undefined"&&typeof document!=="undefined"){if(document.readyState==="loading"){window.addEventListener("DOMContentLoaded",attachBanner)}else{attachBanner()}}}class AuthCredential{constructor(e,t){this.providerId=e;this.signInMethod=t}toJSON(){return debugFail("not implemented")}_getIdTokenResponse(e){return debugFail("not implemented")}_linkToIdToken(e,t){return debugFail("not implemented")}_getReauthenticationResolver(e){return debugFail("not implemented")}}async function resetPassword(e,t){return _performApiRequest(e,"POST","/v1/accounts:resetPassword",_addTidIfNecessary(e,t))}async function updateEmailPassword(e,t){return _performApiRequest(e,"POST","/v1/accounts:update",t)}async function linkEmailPassword(e,t){return _performApiRequest(e,"POST","/v1/accounts:signUp",t)}async function applyActionCode$1(e,t){return _performApiRequest(e,"POST","/v1/accounts:update",_addTidIfNecessary(e,t))}async function signInWithPassword(e,t){return _performSignInRequest(e,"POST","/v1/accounts:signInWithPassword",_addTidIfNecessary(e,t))}async function sendOobCode(e,t){return _performApiRequest(e,"POST","/v1/accounts:sendOobCode",_addTidIfNecessary(e,t))}async function sendEmailVerification$1(e,t){return sendOobCode(e,t)}async function sendPasswordResetEmail$1(e,t){return sendOobCode(e,t)}async function sendSignInLinkToEmail$1(e,t){return sendOobCode(e,t)}async function verifyAndChangeEmail(e,t){return sendOobCode(e,t)}async function signInWithEmailLink$1(e,t){return _performSignInRequest(e,"POST","/v1/accounts:signInWithEmailLink",_addTidIfNecessary(e,t))}async function signInWithEmailLinkForLinking(e,t){return _performSignInRequest(e,"POST","/v1/accounts:signInWithEmailLink",_addTidIfNecessary(e,t))}class EmailAuthCredential extends AuthCredential{constructor(e,t,n,r=null){super("password",n);this._email=e;this._password=t;this._tenantId=r}static _fromEmailAndPassword(e,t){return new EmailAuthCredential(e,t,"password")}static _fromEmailAndCode(e,t,n=null){return new EmailAuthCredential(e,t,"emailLink",n)}toJSON(){return{email:this._email,password:this._password,signInMethod:this.signInMethod,tenantId:this._tenantId}}static fromJSON(e){const t=typeof e==="string"?JSON.parse(e):e;if(t?.email&&t?.password){if(t.signInMethod==="password"){return this._fromEmailAndPassword(t.email,t.password)}else if(t.signInMethod==="emailLink"){return this._fromEmailAndCode(t.email,t.password,t.tenantId)}}return null}async _getIdTokenResponse(e){switch(this.signInMethod){case"password":const t={returnSecureToken:true,email:this._email,password:this._password,clientType:"CLIENT_TYPE_WEB"};return handleRecaptchaFlow(e,t,"signInWithPassword",signInWithPassword,"EMAIL_PASSWORD_PROVIDER");case"emailLink":return signInWithEmailLink$1(e,{email:this._email,oobCode:this._password});default:_fail(e,"internal-error")}}async _linkToIdToken(e,t){switch(this.signInMethod){case"password":const n={idToken:t,returnSecureToken:true,email:this._email,password:this._password,clientType:"CLIENT_TYPE_WEB"};return handleRecaptchaFlow(e,n,"signUpPassword",linkEmailPassword,"EMAIL_PASSWORD_PROVIDER");case"emailLink":return signInWithEmailLinkForLinking(e,{idToken:t,email:this._email,oobCode:this._password});default:_fail(e,"internal-error")}}_getReauthenticationResolver(e){return this._getIdTokenResponse(e)}}async function signInWithIdp(e,t){return _performSignInRequest(e,"POST","/v1/accounts:signInWithIdp",_addTidIfNecessary(e,t))}const R="http://localhost";class OAuthCredential extends AuthCredential{constructor(){super(...arguments);this.pendingToken=null}static _fromParams(e){const t=new OAuthCredential(e.providerId,e.signInMethod);if(e.idToken||e.accessToken){if(e.idToken){t.idToken=e.idToken}if(e.accessToken){t.accessToken=e.accessToken}if(e.nonce&&!e.pendingToken){t.nonce=e.nonce}if(e.pendingToken){t.pendingToken=e.pendingToken}}else if(e.oauthToken&&e.oauthTokenSecret){t.accessToken=e.oauthToken;t.secret=e.oauthTokenSecret}else{_fail("argument-error")}return t}toJSON(){return{idToken:this.idToken,accessToken:this.accessToken,secret:this.secret,n
2once:this.nonce,pendingToken:this.pendingToken,providerId:this.providerId,signInMethod:this.signInMethod}}static fromJSON(e){const t=typeof e==="string"?JSON.parse(e):e;const{providerId:n,signInMethod:r,...i}=t;if(!n||!r){return null}const s=new OAuthCredential(n,r);s.idToken=i.idToken||undefined;s.accessToken=i.accessToken||undefined;s.secret=i.secret;s.nonce=i.nonce;s.pendingToken=i.pendingToken||null;return s}_getIdTokenResponse(e){const t=this.buildRequest();return signInWithIdp(e,t)}_linkToIdToken(e,t){const n=this.buildRequest();n.idToken=t;return signInWithIdp(e,n)}_getReauthenticationResolver(e){const t=this.buildRequest();t.autoCreate=false;return signInWithIdp(e,t)}buildRequest(){const e={requestUri:R,returnSecureToken:true};if(this.pendingToken){e.pendingToken=this.pendingToken}else{const t={};if(this.idToken){t["id_token"]=this.idToken}if(this.accessToken){t["access_token"]=this.accessToken}if(this.secret){t["oauth_token_secret"]=this.secret}t["providerId"]=this.providerId;if(this.nonce&&!this.pendingToken){t["nonce"]=this.nonce}e.postBody=i.querystring(t)}return e}}async function sendPhoneVerificationCode(e,t){return _performApiRequest(e,"POST","/v1/accounts:sendVerificationCode",_addTidIfNecessary(e,t))}async function signInWithPhoneNumber$1(e,t){return _performSignInRequest(e,"POST","/v1/accounts:signInWithPhoneNumber",_addTidIfNecessary(e,t))}async function linkWithPhoneNumber$1(e,t){const n=await _performSignInRequest(e,"POST","/v1/accounts:signInWithPhoneNumber",_addTidIfNecessary(e,t));if(n.temporaryProof){throw _makeTaggedError(e,"account-exists-with-different-credential",n)}return n}const k={["USER_NOT_FOUND"]:"user-not-found"};async function verifyPhoneNumberForExisting(e,t){const n={...t,operation:"REAUTH"};return _performSignInRequest(e,"POST","/v1/accounts:signInWithPhoneNumber",_addTidIfNecessary(e,n),k)}class PhoneAuthCredential extends AuthCredential{constructor(e){super("phone","phone");this.params=e}static _fromVerification(e,t){return new PhoneAuthCredential({verificationId:e,verificationCode:t})}static _fromTokenResponse(e,t){return new PhoneAuthCredential({phoneNumber:e,temporaryProof:t})}_getIdTokenResponse(e){return signInWithPhoneNumber$1(e,this._makeVerificationRequest())}_linkToIdToken(e,t){return linkWithPhoneNumber$1(e,{idToken:t,...this._makeVerificationRequest()})}_getReauthenticationResolver(e){return verifyPhoneNumberForExisting(e,this._makeVerificationRequest())}_makeVerificationRequest(){const{temporaryProof:e,phoneNumber:t,verificationId:n,verificationCode:r}=this.params;if(e&&t){return{temporaryProof:e,phoneNumber:t}}return{sessionInfo:n,code:r}}toJSON(){const e={providerId:this.providerId};if(this.params.phoneNumber){e.phoneNumber=this.params.phoneNumber}if(this.params.temporaryProof){e.temporaryProof=this.params.temporaryProof}if(this.params.verificationCode){e.verificationCode=this.params.verificationCode}if(this.params.verificationId){e.verificationId=this.params.verificationId}return e}static fromJSON(e){if(typeof e==="string"){e=JSON.parse(e)}const{verificationId:t,verificationCode:n,phoneNumber:r,temporaryProof:i}=e;if(!n&&!t&&!r&&!i){return null}return new PhoneAuthCredential({verificationId:t,verificationCode:n,phoneNumber:r,temporaryProof:i})}}function parseMode(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}}function parseDeepLink(e){const t=i.querystringDecode(i.extractQuerystring(e))["link"];const n=t?i.querystringDecode(i.extractQuerystring(t))["deep_link_id"]:null;const r=i.querystringDecode(i.extractQuerystring(e))["deep_link_id"];const s=r?i.querystringDecode(i.extractQuerystring(r))["link"]:null;return s||r||n||t||e}class ActionCodeURL{constructor(e){const t=i.querystringDecode(i.extractQuerystring(e));const n=t["apiKey"]??null;const r=t["oobCode"]??null;const s=parseMode(t["mode"]??null);_assert(n&&r&&s,"argument-error");this.apiKey=n;this.operation=s;
2this.code=r;this.continueUrl=t["continueUrl"]??null;this.languageCode=t["lang"]??null;this.tenantId=t["tenantId"]??null}static parseLink(e){const t=parseDeepLink(e);try{return new ActionCodeURL(t)}catch{return null}}}function parseActionCodeURL(e){return ActionCodeURL.parseLink(e)}class EmailAuthProvider{constructor(){this.providerId=EmailAuthProvider.PROVIDER_ID}static credential(e,t){return EmailAuthCredential._fromEmailAndPassword(e,t)}static credentialWithLink(e,t){const n=ActionCodeURL.parseLink(t);_assert(n,"argument-error");return EmailAuthCredential._fromEmailAndCode(e,n.code,n.tenantId)}}EmailAuthProvider.PROVIDER_ID="password";EmailAuthProvider.EMAIL_PASSWORD_SIGN_IN_METHOD="password";EmailAuthProvider.EMAIL_LINK_SIGN_IN_METHOD="emailLink";class FederatedAuthProvider{constructor(e){this.providerId=e;this.defaultLanguageCode=null;this.customParameters={}}setDefaultLanguage(e){this.defaultLanguageCode=e}setCustomParameters(e){this.customParameters=e;return this}getCustomParameters(){return this.customParameters}}class BaseOAuthProvider extends FederatedAuthProvider{constructor(){super(...arguments);this.scopes=[]}addScope(e){if(!this.scopes.includes(e)){this.scopes.push(e)}return this}getScopes(){return[...this.scopes]}}class OAuthProvider extends BaseOAuthProvider{static credentialFromJSON(e){const t=typeof e==="string"?JSON.parse(e):e;_assert("providerId"in t&&"signInMethod"in t,"argument-error");return OAuthCredential._fromParams(t)}credential(e){return this._credential({...e,nonce:e.rawNonce})}_credential(e){_assert(e.idToken||e.accessToken,"argument-error");return OAuthCredential._fromParams({...e,providerId:this.providerId,sign
2InMethod:this.providerId})}static credentialFromResult(e){return OAuthProvider.oauthCredentialFromTaggedObject(e)}static credentialFromError(e){return OAuthProvider.oauthCredentialFromTaggedObject(e.customData||{})}static oauthCredentialFromTaggedObject({_tokenResponse:e}){if(!e){return null}const{oauthIdToken:t,oauthAccessToken:n,oauthTokenSecret:r,pendingToken:i,nonce:s,providerId:o}=e;if(!n&&!r&&!t&&!i){return null}if(!o){return null}try{return new OAuthProvider(o)._credential({idToken:t,accessToken:n,nonce:s,pendingToken:i})}catch(e){return null}}}class FacebookAuthProvider extends BaseOAuthProvider{constructor(){super("facebook.com")}static credential(e){return OAuthCredential._fromParams({providerId:FacebookAuthProvider.PROVIDER_ID,signInMethod:FacebookAuthProvider.FACEBOOK_SIGN_IN_METHOD,accessToken:e})}static credentialFromResult(e){return FacebookAuthProvider.credentialFromTaggedObject(e)}static credentialFromError(e){return FacebookAuthProvider.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e||!("oauthAccessToken"in e)){return null}if(!e.oauthAccessToken){return null}try{return FacebookAuthProvider.credential(e.oauthAccessToken)}catch{return null}}}FacebookAuthProvider.FACEBOOK_SIGN_IN_METHOD="facebook.com";FacebookAuthProvider.PROVIDER_ID="facebook.com";class GoogleAuthProvider extends BaseOAuthProvider{constructor(){super("google.com");this.addScope("profile")}static credential(e,t){return OAuthCredential._fromParams({providerId:GoogleAuthProvider.PROVIDER_ID,signInMethod:GoogleAuthProvider.GOOGLE_SIGN_IN_METHOD,idToken:e,accessToken:t})}static credentialFromResult(e){return GoogleAuthProvider.credentialFromTaggedObject(e)}static credentialFromError(e){return GoogleAuthProvider.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e){return null}const{oauthIdToken:t,oauthAccessToken:n}=e;if(!t&&!n){return null}try{return GoogleAuthProvider.credential(t,n)}catch{return null}}}GoogleAuthProvider.GOOGLE_SIGN_IN_METHOD="google.com";GoogleAuthProvider.PROVIDER_ID="google.com";class GithubAuthProvider extends BaseOAuthProvider{constructor(){super("github.com")}static credential(e){return OAuthCredential._fromParams({providerId:GithubAuthProvider.PROVIDER_ID,signInMethod:GithubAuthProvider.GITHUB_SIGN_IN_METHOD,accessToken:e})}static credentialFromResult(e){return GithubAuthProvider.credentialFromTaggedObject(e)}static credentialFromError(e){return GithubAuthProvider.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e||!("oauthAccessToken"in e)){return null}if(!e.oauthAccessToken){return null}try{return GithubAuthProvider.credential(e.oauthAccessToken)}catch{return null}}}GithubAuthProvider.GITHUB_SIGN_IN_METHOD="github.com";GithubAuthProvider.PROVIDER_ID="github.com";const N="http://localhost";class SAMLAuthCredential extends AuthCredential{constructor(e,t){super(e,e);this.pendingToken=t}_getIdTokenResponse(e){const t=this.buildRequest();return signInWithIdp(e,t)}_linkToIdToken(e,t){const n=this.buildRequest();n.idToken=t;return signInWithIdp(e,n)}_getReauthenticationResolver(e){const t=this.buildRequest();t.autoCreate=false;return signInWithIdp(e,t)}toJSON(){return{signInMethod:this.signInMethod,providerId:this.providerId,pendingToken:this.pendingToken}}static fromJSON(e){const t=typeof e==="string"?JSON.parse(e):e;const{providerId:n,signInMethod:r,pendingToken:i}=t;if(!n||!r||!i||n!==r){return null}return new SAMLAuthCredential(n,i)}static _create(e,t){return new SAMLAuthCredential(e,t)}buildRequest(){return{requestUri:N,returnSecureToken:true,pendingToken:this.pendingToken}}}const O="saml.";class SAMLAuthProvider extends FederatedAuthProvider{constructor(e){_assert(e.startsWith(O),"argument-error");super(e)}static credentialFromResult(e){return SAMLAuthProvider.samlCredentialFromTaggedObject(e)}static credentialFromError(e){return SAMLAuthProvider.samlCredentialFromTaggedObject(e.customData||{})}static credentialFromJSON(e){const t=SAMLAuthCredential.fromJSON(e);_assert(t,"argument-error");return t}
2static samlCredentialFromTaggedObject({_tokenResponse:e}){if(!e){return null}const{pendingToken:t,providerId:n}=e;if(!t||!n){return null}try{return SAMLAuthCredential._create(n,t)}catch(e){return null}}}class TwitterAuthProvider extends BaseOAuthProvider{constructor(){super("twitter.com")}static credential(e,t){return OAuthCredential._fromParams({providerId:TwitterAuthProvider.PROVIDER_ID,signInMethod:TwitterAuthProvider.TWITTER_SIGN_IN_METHOD,oauthToken:e,oauthTokenSecret:t})}static credentialFromResult(e){return TwitterAuthProvider.credentialFromTaggedObject(e)}static credentialFromError(e){return TwitterAuthProvider.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e){return null}const{oauthAccessToken:t,oauthTokenSecret:n}=e;if(!t||!n){return null}try{return TwitterAuthProvider.credential(t,n)}catch{return null}}}TwitterAuthProvider.TWITTER_SIGN_IN_METHOD="twitter.com";TwitterAuthProvider.PROVIDER_ID="twitter.com";async function signUp(e,t){return _performSignInRequest(e,"POST","/v1/accounts:signUp",_addTidIfNecessary(e,t))}class UserCredentialImpl{constructor(e){this.user=e.user;this.providerId=e.providerId;this._tokenResponse=e._tokenResponse;this.operationType=e.operationType}static async _fromIdTokenResponse(e,t,n,r=false){const i=await UserImpl._fromIdTokenResponse(e,n,r);const s=providerIdForResponse(n);const o=new UserCredentialImpl({user:i,providerId:s,_tokenResponse:n,operationType:t});return o}static async _forOperation(e,t,n){await e._updateTokensIfNecessary(n,true);const r=providerIdForResponse(n);return new UserCredentialImpl({user:e,providerId:r,_tokenResponse:n,operationType:t})}}function providerIdForResponse(e){if(e.providerId){return e.providerId}if("phoneNumber"in e){return"phone"}return null}async function signInAnonymously(e){if(r._isFirebaseServerApp(e.app)){return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(e))}const t=_castAuth(e);await t._initializationPromise;if(t.currentUser?.isAnonymous){return new UserCredentialImpl({user:t.currentUser,providerId:null,operationType:"signIn"})}const n=await signUp(t,{returnSecureToken:true});const i=await UserCredentialImpl._fromIdTokenResponse(t,"signIn",n,true);await t._updateCurrentUser(i.user);return i}class MultiFactorError extends i.FirebaseError{constructor(e,t,n,r){super(t.code,t.message);this.operationType=n;this.user=r;Object.setPrototypeOf(this,MultiFactorError.prototype);this.customData={appName:e.name,tenantId:e.tenantId??undefined,_serverResponse:t.customData._serverResponse,operationType:n}}static _fromErrorAndOperation(e,t,n,r){return new MultiFactorError(e,t,n,r)}}function _processCredentialSavingMfaContextIfNecessary(e,t,n,r){const i=t==="reauthenticate"?n._getReauthenticationResolver(e):n._getIdTokenResponse(e);return i.catch((n=>{if(n.code===`auth/${"multi-factor-auth-required"}`){throw MultiFactorError._fromErrorAndOperation(e,n,t,r)}throw n}))}function providerDataAsNames(e){return new Set(e.map((({providerId:e})=>e)).filter((e=>!!e)))}async function unlink(e,t){const n=i.getModularInstance(e);await _assertLinkedStatus(true,n,t);const{providerUserInfo:r}=await deleteLinkedAccounts(n.auth,{idToken:await n.getIdToken(),deleteProvider:[t]});const s=providerDataAsNames(r||[]);n.providerData=n.providerData.filter((e=>s.has(e.providerId)));if(!s.has("phone")){n.phoneNumber=null}await n.auth._persistUserIfCurrent(n);return n}async function _link$1(e,t,n=false){const r=await _logoutIfInvalidated(e,t._linkToIdToken(e.auth,await e.getIdToken()),n);return UserCredentialImpl._forOperation(e,"link",r)}async function _assertLinkedStatus(e,t,n){await _reloadWithoutSaving(t);const r=providerDataAsNames(t.providerData);const i=e===false?"provider-already-linked":"no-such-provider";_assert(r.has(n)===e,t.auth,i)}async function _reauthenticate(e,t,n=false){const{auth:i}=e;if(r._isFirebaseServerApp(i.app)){return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(i))}const s="reauthenticate";try{const r=await _logoutIfInvalidated(e,_processCredentialSavingMfaContextIfNecessary(i,s,t,e),n);_assert(r.idToken,i,"internal-error");const o=_parseToken(r.idToken);_assert(o,i,"internal-error");const{sub:a}=o;_assert(e.uid===a,i,"user-mismatch");return UserCredentialImpl._forOperation(e,s,r)}catch(e){if(e?.code===`auth/${"user-not-found"}`){_fail(i,"user-mismatch")}throw e}}async function _signInWithCredential(e,t,n=false){if(r._isFirebaseServerApp(e.app)){return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(e))}const i="signIn";const s=await _processCredentialSavingMfaContextIfNecessary(e,i,t);const o=await UserCredentialImpl._fromIdTokenResponse(e,i,s);if(!n){await e._updateCurrentUser(o.user)}return o}async function signInWithCredential(e,t){return _signInWithCredential(_castAuth(e),t)}async function linkWithCredential(e,t){const n=i.getModularInstance(e);await _assertLinkedStatus(false,n,t.providerId);return _link$1(n,t)}async function reauthenticateWithCredential(e,t){return _reauthenticate(i.getModularInstance(e),t)}async function signInWithCustomToken$1(e,t){return _performSignInRequest(e,"POST","/v1/accounts:signInWithCustomToken",_addTidIfNecessary(e,t))}async function signInWithCustomToken(e,t){if(r._isFirebaseServerApp(e.app)){return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(e))}const n=_castAuth(e);const i=await signInWithCustomToken$1(n,{token:t,returnSecureToken:true});const s=await UserCredentialImpl._fromIdTokenResponse(n,"signIn",i);await n._updateCurrentUser(s.user);return s}class MultiFactorInfoImpl{constructor(e,t){this.factorId=e;this.uid=t.mfaEnrollmentId;this.enrollmentTime=new Date(t.enrolledAt).toUTCString();this.displayName=t.displayName}static _fromServerResponse(e,t){if("phoneInfo"in t){return PhoneMultiFactorInfoImpl._fromServerResponse(e,t)}else if("totpInfo"in t){return TotpMultiFactorInfoImpl._fromServerResponse(e,t)}return _fail(e,"internal-error")}}class PhoneMultiFactorInfoImpl extends MultiFactorInfoImpl{constructor(e){super("phone",e);this.phoneNumber=e.phoneInfo}static _fromServerResponse(e,t){return new PhoneMultiFactorInfoImpl(t)}}class TotpMultiFactorInfoImpl extends MultiFactorInfoImpl{constructor(e){super("totp",e)}static _fromServerResponse(e,t){return new TotpMultiFactorInfoImpl(t)}}function _setActionCodeSettingsOnRequest(e,t,n){_assert(n.url?.length>
20,e,"invalid-continue-uri");_assert(typeof n.dynamicLinkDomain==="undefined"||n.dynamicLinkDomain.length>0,e,"invalid-dynamic-link-domain");_assert(typeof n.linkDomain==="undefined"||n.linkDomain.length>0,e,"invalid-hosting-link-domain");t.continueUrl=n.url;t.dynamicLinkDomain=n.dynamicLinkDomain;t.linkDomain=n.linkDomain;t.canHandleCodeInApp=n.handleCodeInApp;if(n.iOS){_assert(n.iOS.bundleId.length>0,e,"missing-ios-bundle-id");t.iOSBundleId=n.iOS.bundleId}if(n.android){_assert(n.android.packageName.length>0,e,"missing-android-pkg-name");t.androidInstallApp=n.android.installApp;t.androidMinimumVersionCode=n.android.minimumVersion;t.androidPackageName=n.android.packageName}}async function recachePasswordPolicy(e){const t=_castAuth(e);if(t._getPasswordPolicyInternal()){await t._updatePasswordPolicy()}}async function sendPasswordResetEmail(e,t,n){const r=_castAuth(e);const i={requestType:"PASSWORD_RESET",email:t,clientType:"CLIENT_TYPE_WEB"};if(n){_setActionCodeSettingsOnRequest(r,i,n)}await handleRecaptchaFlow(r,i,"getOobCode",sendPasswordResetEmail$1,"EMAIL_PASSWORD_PROVIDER")}async function confirmPasswordReset(e,t,n){await resetPassword(i.getModularInstance(e),{oobCode:t,newPassword:n}).catch((async t=>{if(t.code===`auth/${"password-does-not-meet-requirements"}`){void recachePasswordPolicy(e)}throw t}))}async function applyActionCode(e,t){await applyActionCode$1(i.getModularInstance(e),{oobCode:t})}async function checkActionCode(e,t){const n=i.getModularInstance(e);const r=await resetPassword(n,{oobCode:t});const s=r.requestType;_assert(s,n,"internal-error");switch(s){case"EMAIL_SIGNIN":break;case"VERIFY_AND_CHANGE_EMAIL":_assert(r.newEmail,n,"internal-error");break;case"REVERT_SECOND_FACTOR_ADDITION":_assert(r.mfaInfo,n,"internal-error");default:_assert(r.email,n,"internal-error")}let o=null;if(r.mfaInfo){o=MultiFactorInfoImpl._fromServerResponse(_castAuth(n),r.mfaInfo)}return{data:{email:(r.requestType==="VERIFY_AND_CHANGE_EMAIL"?r.newEmail:r.email)||null,previousEmail:(r.requestType==="VERIFY_AND_CHANGE_EMAIL"?r.email:r.newEmail)||null,multiFactorInfo:o},operation:s}}async function verifyPasswordResetCode(e,t){const{data:n}=await checkActionCode(i.getModularInstance(e),t);return n.email}async function createUserWithEmailAndPassword(e,t,n){if(r._isFirebaseServerApp(e.app)){return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(e))}const i=_castAuth(e);const s={returnSecureToken:true,email:t,password:n,clientType:"CLIENT_TYPE_WEB"};const o=handleRecaptchaFlow(i,s,"signUpPassword",signUp,"EMAIL_PASSWORD_PROVIDER");const a=await o.catch((t=>{if(t.code===`auth/${"password-does-not-meet-requirements"}`){void recachePasswordPolicy(e)}throw t}));const c=await UserCredentialImpl._fromIdTokenResponse(i,"signIn",a);await i._updateCurrentUser(c.user);return c}function signInWithEmailAndPassword(e,t,n){if(r._isFirebaseServerApp(e.app)){return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(e))}return signInWithCredential(i.getModularInstance(e),EmailAuthProvider.credential(t,n)).catch((async t=>{if(t.code===`auth/${"password-does-not-meet-requirements"}`){void recachePasswordPolicy(e)}throw t}))}async function sendSignInLinkToEmail(e,t,n){const r=_castAuth(e);const i={requestType:"EMAIL_SIGNIN",email:t,clientType:"CLIENT_TYPE_WEB"};function setActionCodeSettings(e,t){_assert(t.handleCodeInApp,r,"argument-error");if(t){_setActionCodeSettingsOnRequest(r,e,t)}}setActionCodeSettings(i,n);await handleRecaptchaFlow(r,i,"getOobCode",sendSignInLinkToEmail$1,"EMAIL_PASSWORD_PROVIDER")}function isSignInWithEmailLink(e,t){const n=ActionCodeURL.parseLink(t);return n?.operation==="EMAIL_SIGNIN"}async function signInWithEmailLink(e,t,n){if(r._isFirebaseServerApp(e.app)){return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(e))}const s=i.getModularInstance(e);const o=EmailAuthProvider.credentialWithLink(t,n||_getCurrentUrl());_assert(o._tenantId===(s.tenantId||null),s,"tenant-id-mismatch");return signInWithCredential(s,o)}async function createAuthUri(e,t){return _performApiRequest(e,"POST","/v1/accounts:createAuthUri",_addTidIfNecessary(e,t))}async function fetchSignInMethodsForEmail(e,t){const n=_isHttpOrHttps()?_getCurrentUrl():"http://localhost";const r={identifier:t,continueUri:n};const{signinMethods:s}=await createAuthUri(i.getModularInstance(e),r);return s||[]}async function sendEmailVerification(e,t){const n=i.getModularInstance(e);const r=await e.getIdToken();const s={requestType:"VERIFY_EMAIL",idToken:r};if(t){_setActionCodeSettingsOnRequest(n.auth,s,t)}const{email:o}=await sendEmailVerification$1(n.auth,s);if(o!==e.email){await e.reload()}}async function verifyBeforeUpdateEmail(e,t,n){const r=i.getModularInstance(e);const s=await e.getIdToken();const o={requestType:"VERIFY_AND_CHANGE_EMAIL",idToken:s,newEmail:t};if(n){_setActionCodeSettingsOnRequest(r.auth,o,n)}const{email:a}=await verifyAndChangeEmail(r.auth,o);if(a!==e.email){await e.reload()}}async function updateProfile$1(e,t){return _performApiRequest(e,"POST","/v1/accounts:update",t)}async function updateProfile(e,{displayName:t,photoURL:n}){if(t===undefined&&n===undefined){return}const r=i.getModularInstance(e);const s=await r.getIdToken();const o={idToken:s,displayName:t,photoUrl:n,returnSecureToken:true};const a=await _logoutIfInvalidated(r,updateProfile$1(r.auth,o));r.displayName=a.displayName||null;r.photoURL=a.photoUrl||null;const c=r.providerData.find((({providerId:e})=>e==="password"));if(c){c.displayName=r.displayName;c.photoURL=r.photoURL}await r._updateTokensIfNecessary(a)}function updateEmail(e,t){const n=i.getModularInstance(e);if(r._isFirebaseServerApp(n.auth.app)){return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(n.auth))}return updateEmailOrPassword(n,t,null)}function updatePassword(e,t){return updateEmailOrPassword(i.getModularInstance(e),null,t)}async function updateEmailOrPassword(e,t,n){const{auth:r}=e;const i=await e.getIdToken();const s={idToken:i,returnSecureToken:true};if(t){s.email=t}if(n){s.password=n}const o=await _logoutIfInvalidated(e,updateEmailPassword(r,s));await e._updateTokensIfNecessary(o,true)}function _fromIdTokenResponse(e){if(!e){return null}const{providerId:t}=e;const n=e.rawUserInfo?JSON.parse(e.rawUserInfo):{};const r=e.isNewUser||e.kind==="identitytoolkit#SignupNewUserResponse";if(!t&&e?.idToken){const t=_parseToken(e.idToken)?.firebase?.["sign_in_provider"];if(t){const e=t!=="anonymous"&&t!=="custom"?t:null;return new GenericAdditionalUserInfo(r,e)}}if(!t){return null}switch(t){case"facebook.com":return new FacebookAdditionalUserInfo(r,n);case"github.com":return new GithubAdditionalUserInfo(r,n);case"google.com":return new GoogleAdditionalUserInfo(r,n);case"twitter.com":return new TwitterAdditionalUserInfo(r,n,e.screenName||null);
2case"custom":case"anonymous":return new GenericAdditionalUserInfo(r,null);default:return new GenericAdditionalUserInfo(r,t,n)}}class GenericAdditionalUserInfo{constructor(e,t,n={}){this.isNewUser=e;this.providerId=t;this.profile=n}}class FederatedAdditionalUserInfoWithUsername extends GenericAdditionalUserInfo{constructor(e,t,n,r){super(e,t,n);this.username=r}}class FacebookAdditionalUserInfo extends GenericAdditionalUserInfo{constructor(e,t){super(e,"facebook.com",t)}}class GithubAdditionalUserInfo extends FederatedAdditionalUserInfoWithUsername{constructor(e,t){super(e,"github.com",t,typeof t?.login==="string"?t?.login:null)}}class GoogleAdditionalUserInfo extends GenericAdditionalUserInfo{constructor(e,t){super(e,"google.com",t)}}class TwitterAdditionalUserInfo extends FederatedAdditionalUserInfoWithUsername{constructor(e,t,n){super(e,"twitter.com",t,n)}}function getAdditionalUserInfo(e){const{user:t,_tokenResponse:n}=e;if(t.isAnonymous&&!n){return{providerId:null,isNewUser:false,profile:null}}return _fromIdTokenResponse(n)}function setPersistence(e,t){return i.getModularInstance(e).setPersistence(t)}function initializeRecaptchaConfig(e){return _initializeRecaptchaConfig(e)}async function validatePassword(e,t){const n=_castAuth(e);return n.validatePassword(t)}function onIdTokenChanged(e,t,n,r){return i.getModularInstance(e).onIdTokenChanged(t,n,r)}function beforeAuthStateChanged(e,t,n){return i.getModularInstance(e).beforeAuthStateChanged(t,n)}function onAuthStateChanged(e,t,n,r){return i.getModularInstance(e).onAuthStateChanged(t,n,r)}function useDeviceLanguage(e){i.getModularInstance(e).useDeviceLanguage()}function updateCurrentUser(e,t){return i.getModularInstance(e).updateCurrentUser(t)}function signOut(e){return i.getModularInstance(e).signOut()}function revokeAccessToken(e,t){const n=_castAuth(e);return n.revokeAccessToken(t)}async function deleteUser(e){return i.getModularInstance(e).delete()}class MultiFactorSessionImpl{constructor(e,t,n){this.type=e;this.credential=t;this.user=n}static _fromIdtoken(e,t){return new MultiFactorSessionImpl("enroll",e,t)}static _fromMfaPendingCredential(e){return new MultiFactorSessionImpl("signin",e)}toJSON(){const e=this.type==="enroll"?"idToken":"pendingCredential";return{multiFactorSession:{[e]:this.credential}}}static fromJSON(e){if(e?.multiFactorSession){if(e.multiFactorSession?.pendingCredential){return MultiFactorSessionImpl._fromMfaPendingCredential(e.multiFactorSession.pendingCredential)}else if(e.multiFactorSession?.idToken){return MultiFactorSessionImpl._fromIdtoken(e.multiFactorSession.idToken)}}return null}}class MultiFactorResolverImpl{constructor(e,t,n){this.session=e;this.hints=t;this.signInResolver=n}static _fromError(e,t){const n=_castAuth(e);const r=t.customData._serverResponse;const i=(r.mfaInfo||[]).map((e=>MultiFactorInfoImpl._fromServerResponse(n,e)));_assert(r.mfaPendingCredential,n,"internal-error");const s=MultiFactorSessionImpl._fromMfaPendingCredential(r.mfaPendingCredential);return new MultiFactorResolverImpl(s,i,(async e=>{const i=await e._process(n,s);delete r.mfaInfo;delete r.mfaPendingCredential;const o={...r,idToken:i.idToken,refreshToken:i.refreshToken};switch(t.operationType){case"signIn":const e=await UserCredentialImpl._fromIdTokenResponse(n,t.operationType,o);await n._updateCurrentUser(e.user);return e;case"reauthenticate":_assert(t.user,n,"internal-error");return UserCredentialImpl._forOperation(t.user,t.operationType,o);default:_fail(n,"internal-error")}}))}async resolveSignIn(e){const t=e;return this.signInResolver(t)}}function getMultiFactorResolver(e,t){const n=i.getModularInstance(e);const r=t;_assert(t.customData.operationType,n,"argument-error");_assert(r.customData._serverResponse?.mfaPendingCredential,n,"argument-error");return MultiFactorResolverImpl._fromError(n,r)}function startEnrollPhoneMfa(e,t){return _performApiRequest(e,"POST","/v2/accounts/mfaEnrollment:start",_addTidIfNecessary(e,t))}function finalizeEnrollPhoneMfa(e,t){return _performApiRequest(e,"POST","/v2/accounts/mfaEnrollment:finalize",_addTidIfNecessary(e,t))}function startEnrollTotpMfa(e,t){return _performApiRequest(e,"POST","/v2/accounts/mfaEnrollment:start",_addTidIfNecessary(e,t))}function finalizeEnrollTotpMfa(e,t){return _performApiRequest(e,"POST","/v2/accounts/mfaEnrollment:finalize",_addTidIfNecessary(e,t))}function withdrawMfa(e,t){return _performApiRequest(e,"POST","/v2/accounts/mfaEnrollment:withdraw",_addTidIfNecessary(e,t))}class MultiFactorUserImpl{constructor(e){this.user=e;this.enrolledFactors=[];e._onReload((t=>{if(t.mfaInfo){this.enrolledFactors=t.mfaInfo.map((t=>MultiFactorInfoImpl._fromServerResponse(e.auth,t)))}}))}static _fromUser(e){return new MultiFactorUserImpl(e)}async getSession(){return MultiFactorSessionImpl._fromIdtoken(await this.user.getIdToken(),this.user)}async enroll(e,t){const n=e;
2const r=await this.getSession();const i=await _logoutIfInvalidated(this.user,n._process(this.user.auth,r,t));await this.user._updateTokensIfNecessary(i);return this.user.reload()}async unenroll(e){const t=typeof e==="string"?e:e.uid;const n=await this.user.getIdToken();try{const e=await _logoutIfInvalidated(this.user,withdrawMfa(this.user.auth,{idToken:n,mfaEnrollmentId:t}));this.enrolledFactors=this.enrolledFactors.filter((({uid:e})=>e!==t));await this.user._updateTokensIfNecessary(e);await this.user.reload()}catch(e){throw e}}}const D=new WeakMap;function multiFactor(e){const t=i.getModularInstance(e);if(!D.has(t)){D.set(t,MultiFactorUserImpl._fromUser(t))}return D.get(t)}const L="__sak";class BrowserPersistenceClass{constructor(e,t){this.storageRetriever=e;this.type=t}_isAvailable(){try{if(!this.storage){return Promise.resolve(false)}this.storage.setItem(L,"1");this.storage.removeItem(L);return Promise.resolve(true)}catch{return Promise.resolve(false)}}_set(e,t){this.storage.setItem(e,JSON.stringify(t));return Promise.resolve()}_get(e){const t=this.storage.getItem(e);return Promise.resolve(t?JSON.parse(t):null)}_remove(e){this.storage.removeItem(e);return Promise.resolve()}get storage(){return this.storageRetriever()}}const M=1e3;const F=10;class BrowserLocalPersistence extends BrowserPersistenceClass{constructor(){super((()=>window.localStorage),"LOCAL");this.boundEventHandler=(e,t)=>this.onStorageEvent(e,t);this.listeners={};this.localCache={};this.pollTimer=null;this.fallbackToPolling=_isMobileBrowser();this._shouldAllowMigration=true}forAllChangedKeys(e){for(const t of Object.keys(this.listeners)){const n=this.storage.getItem(t);const r=this.localCache[t];if(n!==r){e(t,r,n)}}}onStorageEvent(e,t=false){if(!e.key){this.forAllChangedKeys(((e,t,n)=>{this.notifyListeners(e,n)}));return}const n=e.key;if(t){this.detachListener()}else{this.stopPolling()}const triggerListeners=()=>{const e=this.storage.getItem(n);if(!t&&this.localCache[n]===e){return}this.notifyListeners(n,e)};const r=this.storage.getItem(n);if(_isIE10()&&r!==e.newValue&&e.newValue!==e.oldValue){setTimeout(triggerListeners,F)}else{triggerListeners()}}notifyListeners(e,t){this.localCache[e]=t;const n=this.listeners[e];if(n){for(const e of Array.from(n)){e(t?JSON.parse(t):t)}}}startPolling(){this.stopPolling();this.pollTimer=setInterval((()=>{this.forAllChangedKeys(((e,t,n)=>{this.onStorageEvent(new StorageEvent("storage",{key:e,oldValue:t,newValue:n}),true)}))}),M)}stopPolling(){if(this.pollTimer){clearInterval(this.pollTimer);this.pollTimer=null}}attachListener(){window.addEventListener("storage",this.boundEventHandler)}detachListener(){window.removeEventListener("storage",this.boundEventHandler)}_addListener(e,t){if(Object.keys(this.listeners).length===0){if(this.fallbackToPolling){this.startPolling()}else{this.attachListener()}}if(!this.listeners[e]){this.listeners[e]=new Set;this.localCache[e]=this.storage.getItem(e)}this.listeners[e].add(t)}_removeListener(e,t){if(this.listeners[e]){this.listeners[e].delete(t);if(this.listeners[e].size===0){delete this.listeners[e]}}if(Object.keys(this.listeners).length===0){this.detachListener();this.stopPolling()}}async _set(e,t){await super._set(e,t);this.localCache[e]=JSON.stringify(t)}async _get(e){const t=await super._get(e);this.localCache[e]=JSON.stringify(t);return t}async _remove(e){await super._remove(e);delete this.localCache[e]}}BrowserLocalPersistence.type="LOCAL";const U=BrowserLocalPersistence;const x=1e3;function getDocumentCookie(e){const t=e.replace(/[\\^$.*+?()[\]{}|]/g,"\\$&");const n=RegExp(`${t}=([^;]+)`);return document.cookie.match(n)?.[1]??null}function getCookieName(e){const t=window.location.protocol==="http:";return`${t?"__dev_":"__HOST-"}FIREBASE_${e.split(":")[3]}`}class CookiePersistence{constructor(){this.type="COOKIE";this.listenerUnsubscribes=new Map}_getFinalTarget(e){if(typeof window===undefined){return e}const t=new URL(`${window.location.origin}/__cookies__`);t.searchParams.set("finalTarget",e);return t}async _isAvailable(){if(typeof isSecureContext==="boolean"&&!isSecureContext){return false}if(typeof navigator==="undefined"||typeof document==="undefined"){return false}return navigator.cookieEnabled??true}async _set(e,t){return}async _get(e){if(!this._isAvailable()){return null}const t=getCookieName(e);
2if(window.cookieStore){const e=await window.cookieStore.get(t);return e?.value}return getDocumentCookie(t)}async _remove(e){if(!this._isAvailable()){return}const t=await this._get(e);if(!t){return}const n=getCookieName(e);document.cookie=`${n}=;Max-Age=34560000;Partitioned;Secure;SameSite=Strict;Path=/;Priority=High`;await fetch(`/__cookies__`,{method:"DELETE"}).catch((()=>undefined))}_addListener(e,t){if(!this._isAvailable()){return}const n=getCookieName(e);if(window.cookieStore){const cb=e=>{const r=e.changed.find((e=>e.name===n));if(r){t(r.value)}const i=e.deleted.find((e=>e.name===n));if(i){t(null)}};const unsubscribe=()=>window.cookieStore.removeEventListener("change",cb);this.listenerUnsubscribes.set(t,unsubscribe);return window.cookieStore.addEventListener("change",cb)}let r=getDocumentCookie(n);const i=setInterval((()=>{const e=getDocumentCookie(n);if(e!==r){t(e);r=e}}),x);const unsubscribe=()=>clearInterval(i);this.listenerUnsubscribes.set(t,unsubscribe)}_removeListener(e,t){const n=this.listenerUnsubscribes.get(t);if(!n){return}n();this.listenerUnsubscribes.delete(t)}}CookiePersistence.type="COOKIE";const W=CookiePersistence;class BrowserSessionPersistence extends BrowserPersistenceClass{constructor(){super((()=>window.sessionStorage),"SESSION")}_addListener(e,t){return}_removeListener(e,t){return}}BrowserSessionPersistence.type="SESSION";const V=BrowserSessionPersistence;function _allSettled(e){return Promise.all(e.map((async e=>{try{const t=await e;return{fulfilled:true,value:t}}catch(e){return{fulfilled:false,reason:e}}})))}class Receiver{constructor(e){this.eventTarget=e;this.handlersMap={};this.boundEventHandler=this.handleEvent.bind(this)}static _getInstance(e){const t=this.receivers.find((t=>t.isListeningto(e)));if(t){return t}const n=new Receiver(e);this.receivers.push(n);return n}isListeningto(e){return this.eventTarget===e}async handleEvent(e){const t=e;const{eventId:n,eventType:r,data:i}=t.data;const s=this.handlersMap[r];if(!s?.size){return}t.ports[0].postMessage({status:"ack",eventId:n,eventType:r});const o=Array.from(s).map((async e=>e(t.origin,i)));const a=await _allSettled(o);t.ports[0].postMessage({status:"done",eventId:n,eventType:r,response:a})}_subscribe(e,t){if(Object.keys(this.handlersMap).length===0){this.eventTarget.addEventListener("message",this.boundEventHandler)}if(!this.handlersMap[e]){this.handlersMap[e]=new Set}this.handlersMap[e].add(t)}_unsubscribe(e,t){if(this.handlersMap[e]&&t){this.handlersMap[e].delete(t)}if(!t||this.handlersMap[e].size===0){delete this.handlersMap[e]}if(Object.keys(this.handlersMap).length===0){this.eventTarget.removeEventListener("message",this.boundEventHandler)}}}Receiver.receivers=[];function _generateEventId(e="",t=10){let n="";for(let e=0;e<t;e++){n+=Math.floor(Math.random()*10)}return e+n}class Sender{constructor(e){this.target=e;this.handlers=new Set}removeMessageHandler(e){if(e.messageChannel){e.messageChannel.port1.removeEventListener("message",e.onMessage);e.messageChannel.port1.close()}this.handlers.delete(e)}async _send(e,t,n=50){const r=typeof MessageChannel!=="undefined"?new MessageChannel:null;if(!r){throw new Error("connection_unavailable")}let i;let s;return new Promise(((o,a)=>{const c=_generateEventId("",20);r.port1.start();const l=setTimeout((()=>{a(new Error("unsupported_event"))}),n);s={messageChannel:r,onMessage(e){const t=e;if(t.data.eventId!==c){return}switch(t.data.status){case"ack":clearTimeout(l);i=setTimeout((()=>{a(new Error("timeout"))}),3e3);break;case"done":clearTimeout(i);o(t.data.response);break;default:clearTimeout(l);clearTimeout(i);a(new Error("invalid_response"));break}}};this.handlers.add(s);r.port1.addEventListener("message",s.onMessage);this.target.postMessage({eventType:e,eventId:c,data:t},[r.port2])})).finally((()=>{if(s){this.removeMessageHandler(s)}}))}}function _window(){return window}function _setWindowLocation(e){_window().location.href=e}function _isWorker(){return typeof _window()["WorkerGlobalScope"]!=="undefined"&&typeof _window()["importScripts"]==="function"}async function _getActiveServiceWorker(){if(!navigator?.serviceWorker){return null}try{const e=await navigator.serviceWorker.ready;return e.active}catch{return null}}function _getServiceWorkerController(){return navigator?.serviceWorker?.controller||null}function _getWorkerGlobalScope(){return _isWorker()?self:null}const q="firebaseLocalStorageDb";const G=1;const B="firebaseLocalStorage";const H="fbase_key";class DBPromise{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)}))}
2))}}function getObjectStore(e,t){return e.transaction([B],t?"readwrite":"readonly").objectStore(B)}function _deleteDatabase(){const e=indexedDB.deleteDatabase(q);return new DBPromise(e).toPromise()}function _openDatabase(){const e=indexedDB.open(q,G);return new Promise(((t,n)=>{e.addEventListener("error",(()=>{n(e.error)}));e.addEventListener("upgradeneeded",(()=>{const t=e.result;try{t.createObjectStore(B,{keyPath:H})}catch(e){n(e)}}));e.addEventListener("success",(async()=>{const n=e.result;if(!n.objectStoreNames.contains(B)){n.close();await _deleteDatabase();t(await _openDatabase())}else{t(n)}}))}))}async function _putObject(e,t,n){const r=getObjectStore(e,true).put({[H]:t,value:n});return new DBPromise(r).toPromise()}async function getObject(e,t){const n=getObjectStore(e,false).get(t);const r=await new DBPromise(n).toPromise();return r===undefined?null:r.value}function _deleteObject(e,t){const n=getObjectStore(e,true).delete(t);return new DBPromise(n).toPromise()}const j=800;const z=3;class IndexedDBLocalPersistence{constructor(){this.type="LOCAL";this.dbPromise=null;this._shouldAllowMigration=true;this.listeners={};this.localCache={};this.pollTimer=null;this.pendingWrites=0;this.receiver=null;this.sender=null;this.serviceWorkerReceiverAvailable=false;this.activeServiceWorker=null;this._workerInitializationPromise=this.initializeServiceWorkerMessaging().then((()=>{}),(()=>{}))}async _openDb(){if(this.dbPromise){return this.dbPromise}this.dbPromise=_openDatabase();this.dbPromise.catch((()=>{this.dbPromise=null}));return this.dbPromise}async _withRetries(e){let t=0;while(true){try{const t=await this._openDb();return await e(t)}catch(e){if(t++>z){throw e}if(this.dbPromise){const e=await this.dbPromise;e.close();this.dbPromise=null}}}}async initializeServiceWorkerMessaging(){return _isWorker()?this.initializeReceiver():this.initializeSender()}async initializeReceiver(){this.receiver=Receiver._getInstance(_getWorkerGlobalScope());this.receiver._subscribe("keyChanged",(async(e,t)=>{const n=await this._poll();return{keyProcessed:n.includes(t.key)}}));this.receiver._subscribe("ping",(async(e,t)=>["keyChanged"]))}async initializeSender(){this.activeServiceWorker=await _getActiveServiceWorker();if(!this.activeServiceWorker){return}this.sender=new Sender(this.activeServiceWorker);const e=await this.sender._send("ping",{},800);if(!e){return}if(e[0]?.fulfilled&&e[0]?.value.includes("keyChanged")){this.serviceWorkerReceiverAvailable=true}}async notifyServiceWorker(e){if(!this.sender||!this.activeServiceWorker||_getServiceWorkerController()!==this.activeServiceWorker){return}try{await this.sender._send("keyChanged",{key:e},this.serviceWorkerReceiverAvailable?800:50)}catch{}}async _isAvailable(){try{if(!indexedDB){return false}await this._withRetries((async e=>{await _putObject(e,L,"1");await _deleteObject(e,L)}));return true}catch{}return false}async _withPendingWrite(e){this.pendingWrites++;try{await e()}finally{this.pendingWrites--}}async _set(e,t){return this._withPendingWrite((async()=>{await this._withRetries((n=>_putObject(n,e,t)));this.localCache[e]=t;return this.notifyServiceWorker(e)}))}async _get(e){const t=await this._withRetries((t=>getObject(t,e)));this.localCache[e]=t;return t}async _remove(e){return this._withPendingWrite((async()=>{await this._withRetries((t=>_deleteObject(t,e)));delete this.localCache[e];return this.notifyServiceWorker(e)}))}async _poll(){const e=await this._withRetries((e=>{const t=getObjectStore(e,false).getAll();return new DBPromise(t).toPromise()}));if(!e){return[]}if(this.pendingWrites!==0){return[]}const t=[];const n=new Set;if(e.length!==0){for(const{fbase_key:r,value:i}of e){n.add(r);if(JSON.stringify(this.localCache[r])!==JSON.stringify(i)){this.notifyListeners(r,i);t.push(r)}}}for(const e of Object.keys(this.localCache)){if(this.localCache[e]&&!n.has(e)){this.notifyListeners(e,null);t.push(e)}}return t}notifyListeners(e,t){this.localCache[e]=t;const n=this.listeners[e];if(n){for(const e of Array.from(n)){e(t)}}}startPolling(){this.stopPolling();this.pollTimer=setInterval((async()=>this._poll()),j)}stopPolling(){if(this.pollTimer){clearInterval(this.pollTimer);this.pollTimer=null}}_addListener(e,t){if(Object.keys(this.listeners).length===0){this.startPolling()}if(!this.listeners[e]){this.listeners[e]=new Set;void this._get(e)}this.listeners[e].add(t)}_removeListener(e,t){if(this.listeners[e]){this.listeners[e].delete(t);if(this.listeners[e].size===0){delete this.listeners[e]}}if(Object.keys(this.listeners).length===0){this.stopPolling()}}}IndexedDBLocalPersistence.type="LOCAL";const K=IndexedDBLocalPersistence;function startSignInPhoneMfa(e,t){return _performApiRequest(e,"POST","/v2/accounts/mfaSignIn:start",_addTidIfNecessary(e,t))}function finalizeSignInPhoneMfa(e,t){return _performApiRequest(e,"POST","/v2/accounts/mfaSignIn:finalize",_addTidIfNecessary(e,t))}function finalizeSignInTotpMfa(e,t){return _performApiRequest(e,"POST","/v2/accounts/mfaSignIn:finalize",_addTidIfNecessary(e,t))}const $=_generateCallbackName("rcb");const Q=new Delay(3e4,6e4);class ReCaptchaLoaderImpl{constructor(){this.hostLanguage="";this.counter=0;this.librarySeparatelyLoaded=!!_window().grecaptcha?.render}load(e,t=""){_assert(isHostLanguageValid(t),e,"argument-error");
2if(this.shouldResolveImmediately(t)&&isV2(_window().grecaptcha)){return Promise.resolve(_window().grecaptcha)}return new Promise(((n,r)=>{const s=_window().setTimeout((()=>{r(_createError(e,"network-request-failed"))}),Q.get());_window()[$]=()=>{_window().clearTimeout(s);delete _window()[$];const i=_window().grecaptcha;if(!i||!isV2(i)){r(_createError(e,"internal-error"));return}const o=i.render;i.render=(e,t)=>{const n=o(e,t);this.counter++;return n};this.hostLanguage=t;n(i)};const o=`${_recaptchaV2ScriptUrl()}?${i.querystring({onload:$,render:"explicit",hl:t})}`;_loadJS(o).catch((()=>{clearTimeout(s);r(_createError(e,"internal-error"))}))}))}clearedOneInstance(){this.counter--}shouldResolveImmediately(e){return!!_window().grecaptcha?.render&&(e===this.hostLanguage||this.counter>0||this.librarySeparatelyLoaded)}}function isHostLanguageValid(e){return e.length<=6&&/^\s*[a-zA-Z0-9\-]*\s*$/.test(e)}class MockReCaptchaLoaderImpl{async load(e){return new MockReCaptcha(e)}clearedOneInstance(){}}const Y="recaptcha";const J={theme:"light",type:"image"};class RecaptchaVerifier{constructor(e,t,n={...J}){this.parameters=n;this.type=Y;this.destroyed=false;this.widgetId=null;this.tokenChangeListeners=new Set;this.renderPromise=null;this.recaptcha=null;this.auth=_castAuth(e);this.isInvisible=this.parameters.size==="invisible";_assert(typeof document!=="undefined",this.auth,"operation-not-supported-in-this-environment");const r=typeof t==="string"?document.getElementById(t):t;_assert(r,this.auth,"argument-error");this.container=r;this.parameters.callback=this.makeTokenCallback(this.parameters.callback);this._recaptchaLoader=this.auth.settings.appVerificationDisabledForTesting?new MockReCaptchaLoaderImpl:new ReCaptchaLoaderImpl;this.validateStartingState()}async verify(){this.assertNotDestroyed();const e=await this.render();const t=this.getAssertedRecaptcha();const n=t.getResponse(e);if(n){return n}return new Promise((n=>{const tokenChange=e=>{if(!e){return}this.tokenChangeListeners.delete(tokenChange);n(e)};this.tokenChangeListeners.add(tokenChange);if(this.isInvisible){t.execute(e)}}))}render(){try{this.assertNotDestroyed()}catch(e){return Promise.reject(e)}if(this.renderPromise){return this.renderPromise}this.renderPromise=this.makeRenderPromise().catch((e=>{this.renderPromise=null;throw e}));return this.renderPromise}_reset(){this.assertNotDestroyed();if(this.widgetId!==null){this.getAssertedRecaptcha().reset(this.widgetId)}}clear(){this.assertNotDestroyed();this.destroyed=true;this._recaptchaLoader.clearedOneInstance();if(!this.isInvisible){this.container.childNodes.forEach((e=>{this.container.removeChild(e)}))}}validateStartingState(){_assert(!this.parameters.sitekey,this.auth,"argument-error");_assert(this.isInvisible||!this.container.hasChildNodes(),this.auth,"argument-error");_assert(typeof document!=="undefined",this.auth,"operation-not-supported-in-this-environment")}makeTokenCallback(e){return t=>{this.tokenChangeListeners.forEach((e=>e(t)));if(typeof e==="function"){e(t)}else if(typeof e==="string"){const n=_window()[e];if(typeof n==="function"){n(t)}}}}
2assertNotDestroyed(){_assert(!this.destroyed,this.auth,"internal-error")}async makeRenderPromise(){await this.init();if(!this.widgetId){let e=this.container;if(!this.isInvisible){const t=document.createElement("div");e.appendChild(t);e=t}this.widgetId=this.getAssertedRecaptcha().render(e,this.parameters)}return this.widgetId}async init(){_assert(_isHttpOrHttps()&&!_isWorker(),this.auth,"internal-error");await domReady();this.recaptcha=await this._recaptchaLoader.load(this.auth,this.auth.languageCode||undefined);const e=await getRecaptchaParams(this.auth);_assert(e,this.auth,"internal-error");this.parameters.sitekey=e}getAssertedRecaptcha(){_assert(this.recaptcha,this.auth,"internal-error");return this.recaptcha}}function domReady(){let e=null;return new Promise((t=>{if(document.readyState==="complete"){t();return}e=()=>t();window.addEventListener("load",e)})).catch((t=>{if(e){window.removeEventListener("load",e)}throw t}))}class ConfirmationResultImpl{constructor(e,t){this.verificationId=e;this.onConfirmation=t}confirm(e){const t=PhoneAuthCredential._fromVerification(this.verificationId,e);return this.onConfirmation(t)}}async function signInWithPhoneNumber(e,t,n){if(r._isFirebaseServerApp(e.app)){return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(e))}const s=_castAuth(e);const o=await _verifyPhoneNumber(s,t,i.getModularInstance(n));return new ConfirmationResultImpl(o,(e=>signInWithCredential(s,e)))}async function linkWithPhoneNumber(e,t,n){const r=i.getModularInstance(e);await _assertLinkedStatus(false,r,"phone");const s=await _verifyPhoneNumber(r.auth,t,i.getModularInstance(n));return new ConfirmationResultImpl(s,(e=>linkWithCredential(r,e)))}async function reauthenticateWithPhoneNumber(e,t,n){const s=i.getModularInstance(e);if(r._isFirebaseServerApp(s.auth.app)){return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(s.auth))}const o=await _verifyPhoneNumber(s.auth,t,i.getModularInstance(n));return new ConfirmationResultImpl(o,(e=>reauthenticateWithCredential(s,e)))}async function _verifyPhoneNumber(e,t,n){if(!e._getRecaptchaConfig()){try{await _initializeRecaptchaConfig(e)}catch(e){console.log("Failed to initialize reCAPTCHA Enterprise config. Triggering the reCAPTCHA v2 verification.")}}try{let r;if(typeof t==="string"){r={phoneNumber:t}}else{r=t}if("session"in r){const t=r.session;if("phoneNumber"in r){_assert(t.type==="enroll",e,"internal-error");const i={idToken:t.credential,phoneEnrollmentInfo:{phoneNumber:r.phoneNumber,clientType:"CLIENT_TYPE_WEB"}};const startEnrollPhoneMfaActionCallback=async(e,t)=>{if(t.phoneEnrollmentInfo.captchaResponse===b){_assert(n?.type===Y,e,"argument-error");const r=await injectRecaptchaV2Token(e,t,n);return startEnrollPhoneMfa(e,r)}return startEnrollPhoneMfa(e,t)};const s=handleRecaptchaFlow(e,i,"mfaSmsEnrollment",startEnrollPhoneMfaActionCallback,"PHONE_PROVIDER");const o=await s.catch((e=>Promise.reject(e)));return o.phoneSessionInfo.sessionInfo}else{_assert(t.type==="signin",e,"internal-error");const i=r.multiFactorHint?.uid||r.multiFactorUid;_assert(i,e,"missing-multi-factor-info");const s={mfaPendingCredential:t.credential,mfaEnrollmentId:i,phoneSignInInfo:{clientType:"CLIENT_TYPE_WEB"}};const startSignInPhoneMfaActionCallback=async(e,t)=>{if(t.phoneSignInInfo.captchaResponse===b){_assert(n?.type===Y,e,"argument-error");const r=await injectRecaptchaV2Token(e,t,n);return startSignInPhoneMfa(e,r)}return startSignInPhoneMfa(e,t)};const o=handleRecaptchaFlow(e,s,"mfaSmsSignIn",startSignInPhoneMfaActionCallback,"PHONE_PROVIDER");const a=await o.catch((e=>Promise.reject(e)));return a.phoneResponseInfo.sessionInfo}}else{const t={phoneNumber:r.phoneNumber,clientType:"CLIENT_TYPE_WEB"};const sendPhoneVerificationCodeActionCallback=async(e,t)=>{if(t.captchaResponse===b){_assert(n?.type===Y,e,"argument-error");const r=await injectRecaptchaV2Token(e,t,n);return sendPhoneVerificationCode(e,r)}return sendPhoneVerificationCode(e,t)};const i=handleRecaptchaFlow(e,t,"sendVerificationCode",sendPhoneVerificationCodeActionCallback,"PHONE_PROVIDER");const s=await i.catch((e=>Promise.reject(e)));return s.sessionInfo}}finally{n?._reset()}}async function updatePhoneNumber(e,t){const n=i.getModularInstance(e);if(r._isFirebaseServerApp(n.auth.app)){return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(n.auth))}await _link$1(n,t)}async function injectRecaptchaV2Token(e,t,n){_assert(n.type===Y,e,"argument-error");const r=await n.verify();_assert(typeof r==="string",e,"argument-error");const i={...t};if("phoneEnrollmentInfo"in i){const e=i.phoneEnrollmentInfo.phoneNumber;const t=i.phoneEnrollmentInfo.captchaResponse;const n=i.phoneEnrollmentInfo.clientType;const s=i.phoneEnrollmentInfo.recaptchaVersion;Object.assign(i,{phoneEnrollmentInfo:{phoneNumber:e,recaptchaToken:r,captchaResponse:t,clientType:n,recaptchaVersion:s}});return i}else if("phoneSignInInfo"in i){const e=i.phoneSignInInfo.captchaResponse;const t=i.phoneSignInInfo.clientType;const n=i.phoneSignInInfo.recaptchaVersion;Object.assign(i,{phoneSignInInfo:{recaptchaToken:r,captchaResponse:e,clientType:t,recaptchaVersion:n}});return i}else{Object.assign(i,{recaptchaToken:r});return i}}class PhoneAuthProvider{constructor(e){this.providerId=PhoneAuthProvider.PROVIDER_ID;this.auth=_castAuth(e)}verifyPhoneNumber(e,t){return _verifyPhoneNumber(this.auth,e,i.getModularInstance(t))}static credential(e,t){return PhoneAuthCredential._fromVerification(e,t)}static credentialFromResult(e){const t=e;return PhoneAuthProvider.credentialFromTaggedObject(t)}static credentialFromError(e){return PhoneAuthProvider.credentialFromTaggedObject(e.customData||{})}
2static credentialFromTaggedObject({_tokenResponse:e}){if(!e){return null}const{phoneNumber:t,temporaryProof:n}=e;if(t&&n){return PhoneAuthCredential._fromTokenResponse(t,n)}return null}}PhoneAuthProvider.PROVIDER_ID="phone";PhoneAuthProvider.PHONE_SIGN_IN_METHOD="phone";function _withDefaultResolver(e,t){if(t){return _getInstance(t)}_assert(e._popupRedirectResolver,e,"argument-error");return e._popupRedirectResolver}class IdpCredential extends AuthCredential{constructor(e){super("custom","custom");this.params=e}_getIdTokenResponse(e){return signInWithIdp(e,this._buildIdpRequest())}_linkToIdToken(e,t){return signInWithIdp(e,this._buildIdpRequest(t))}_getReauthenticationResolver(e){return signInWithIdp(e,this._buildIdpRequest())}_buildIdpRequest(e){const t={requestUri:this.params.requestUri,sessionId:this.params.sessionId,postBody:this.params.postBody,tenantId:this.params.tenantId,pendingToken:this.params.pendingToken,returnSecureToken:true,returnIdpCredential:true};if(e){t.idToken=e}return t}}function _signIn(e){return _signInWithCredential(e.auth,new IdpCredential(e),e.bypassAuthState)}function _reauth(e){const{auth:t,user:n}=e;_assert(n,t,"internal-error");return _reauthenticate(n,new IdpCredential(e),e.bypassAuthState)}async function _link(e){const{auth:t,user:n}=e;_assert(n,t,"internal-error");return _link$1(n,new IdpCredential(e),e.bypassAuthState)}class AbstractPopupRedirectOperation{constructor(e,t,n,r,i=false){this.auth=e;this.resolver=n;this.user=r;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){const{urlResponse:t,sessionId:n,postBody:r,tenantId:i,error:s,type:o}=e;if(s){this.reject(s);return}const a={auth:this.auth,requestUri:t,sessionId:n,tenantId:i||undefined,postBody:r||undefined,user:this.user,bypassAuthState:this.bypassAuthState};try{this.resolve(await this.getIdpTask(o)(a))}catch(e){this.reject(e)}}onError(e){this.reject(e)}getIdpTask(e){switch(e){case"signInViaPopup":case"signInViaRedirect":return _signIn;case"linkViaPopup":case"linkViaRedirect":return _link;case"reauthViaPopup":case"reauthViaRedirect":return _reauth;default:_fail(this.auth,"internal-error")}}resolve(e){debugAssert(this.pendingPromise,"Pending promise was never set");this.pendingPromise.resolve(e);this.unregisterAndCleanUp()}reject(e){debugAssert(this.pendingPromise,"Pending promise was never set");this.pendingPromise.reject(e);this.unregisterAndCleanUp()}unregisterAndCleanUp(){if(this.eventManager){this.eventManager.unregisterConsumer(this)}this.pendingPromise=null;this.cleanUp()}}const X=new Delay(2e3,1e4);async function signInWithPopup(e,t,n){if(r._isFirebaseServerApp(e.app)){return Promise.reject(_createError(e,"operation-not-supported-in-this-environment"))}const i=_castAuth(e);_assertInstanceOf(e,t,FederatedAuthProvider);const s=_withDefaultResolver(i,n);const o=new PopupOperation(i,"signInViaPopup",t,s);return o.executeNotNull()}async function reauthenticateWithPopup(e,t,n){const s=i.getModularInstance(e);if(r._isFirebaseServerApp(s.auth.app)){return Promise.reject(_createError(s.auth,"operation-not-supported-in-this-environment"))}_assertInstanceOf(s.auth,t,FederatedAuthProvider);const o=_withDefaultResolver(s.auth,n);const a=new PopupOperation(s.auth,"reauthViaPopup",t,o,s);return a.executeNotNull()}async function linkWithPopup(e,t,n){const r=i.getModularInstance(e);_assertInstanceOf(r.auth,t,FederatedAuthProvider);const s=_withDefaultResolver(r.auth,n);const o=new PopupOperation(r.auth,"linkViaPopup",t,s,r);return o.executeNotNull()}class PopupOperation extends AbstractPopupRedirectOperation{constructor(e,t,n,r,i){super(e,t,r,i);this.provider=n;this.authWindow=null;this.pollId=null;if(PopupOperation.currentPopupAction){PopupOperation.currentPopupAction.cancel()}PopupOperation.currentPopupAction=this}async executeNotNull(){const e=await this.execute();_assert(e,this.auth,"internal-error");return e}async onExecution(){debugAssert(this.filter.length===1,"Popup operations only handle one event");const e=_generateEventId();this.authWindow=await this.resolver._openPopup(this.auth,this.provider,this.filter[0],e);this.authWindow.associatedEvent=e;this.resolver._originValidation(this.auth).catch((e=>{this.reject(e)}));this.resolver._isIframeWebStorageSupported(this.auth,(e=>{if(!e){this.reject(_createError(this.auth,"web-storage-unsupported"))}}));this.pollUserCancellation()}get eventId(){return this.authWindow?.associatedEvent||null}cancel(){this.reject(_createError(this.auth,"cancelled-popup-request"))}cleanUp(){if(this.authWindow){this.authWindow.close()}if(this.pollId){window.clearTimeout(this.pollId)}this.authWindow=null;this.pollId=null;PopupOperation.currentPopupAction=null}pollUserCancellation(){const poll=()=>{if(this.authWindow?.window?.closed){this.pollId=window.setTimeout((()=>{this.pollId=null;this.reject(_createError(this.auth,"popup-closed-by-user"))}),8e3);return}this.pollId=window.setTimeout(poll,X.get())};poll()}}PopupOperation.currentPopupAction=null;const Z="pendingRedirect";const ee=new Map;class RedirectAction extends AbstractPopupRedirectOperation{constructor(e,t,n=false){super(e,["signInViaRedirect","linkViaRedirect","reauthViaRedirect","unknown"],t,undefined,n);this.eventId=null}async execute(){let e=ee.get(this.auth._key());if(!e){try{const t=await _getAndClearPendingRedirectStatus(this.resolver,this.auth);const n=t?await super.execute():null;e=()=>Promise.resolve(n)}catch(t){e=()=>Promise.reject(t)}ee.set(this.auth._key(),e)}if(!this.bypassAuthState){ee.set(this.auth._key(),(()=>Promise.resolve(null)))}return e()}
2async onAuthEvent(e){if(e.type==="signInViaRedirect"){return super.onAuthEvent(e)}else if(e.type==="unknown"){this.resolve(null);return}if(e.eventId){const t=await this.auth._redirectUserForId(e.eventId);if(t){this.user=t;return super.onAuthEvent(e)}else{this.resolve(null)}}}async onExecution(){}cleanUp(){}}async function _getAndClearPendingRedirectStatus(e,t){const n=pendingRedirectKey(t);const r=resolverPersistence(e);if(!await r._isAvailable()){return false}const i=await r._get(n)==="true";await r._remove(n);return i}async function _setPendingRedirectStatus(e,t){return resolverPersistence(e)._set(pendingRedirectKey(t),"true")}function _clearRedirectOutcomes(){ee.clear()}function _overrideRedirectResult(e,t){ee.set(e._key(),t)}function resolverPersistence(e){return _getInstance(e._redirectPersistence)}function pendingRedirectKey(e){return _persistenceKeyName(Z,e.config.apiKey,e.name)}function signInWithRedirect(e,t,n){return _signInWithRedirect(e,t,n)}async function _signInWithRedirect(e,t,n){if(r._isFirebaseServerApp(e.app)){return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(e))}const i=_castAuth(e);_assertInstanceOf(e,t,FederatedAuthProvider);await i._initializationPromise;const s=_withDefaultResolver(i,n);await _setPendingRedirectStatus(s,i);return s._openRedirect(i,t,"signInViaRedirect")}function reauthenticateWithRedirect(e,t,n){return _reauthenticateWithRedirect(e,t,n)}async function _reauthenticateWithRedirect(e,t,n){const s=i.getModularInstance(e);_assertInstanceOf(s.auth,t,FederatedAuthProvider);if(r._isFirebaseServerApp(s.auth.app)){return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(s.auth))}await s.auth._initializationPromise;const o=_withDefaultResolver(s.auth,n);await _setPendingRedirectStatus(o,s.auth);const a=await prepareUserForRedirect(s);return o._openRedirect(s.auth,t,"reauthViaRedirect",a)}function linkWithRedirect(e,t,n){return _linkWithRedirect(e,t,n)}async function _linkWithRedirect(e,t,n){const r=i.getModularInstance(e);_assertInstanceOf(r.auth,t,FederatedAuthProvider);await r.auth._initializationPromise;const s=_withDefaultResolver(r.auth,n);await _assertLinkedStatus(false,r,t.providerId);await _setPendingRedirectStatus(s,r.auth);const o=await prepareUserForRedirect(r);return s._openRedirect(r.auth,t,"linkViaRedirect",o)}async function getRedirectResult(e,t){await _castAuth(e)._initializationPromise;return _getRedirectResult(e,t,false)}async function _getRedirectResult(e,t,n=false){if(r._isFirebaseServerApp(e.app)){return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(e))}const i=_castAuth(e);const s=_withDefaultResolver(i,t);const o=new RedirectAction(i,s,n);const a=await o.execute();if(a&&!n){delete a.user._redirectEventId;await i._persistUserIfCurrent(a.user);await i._setRedirectUser(null,t)}return a}async function prepareUserForRedirect(e){const t=_generateEventId(`${e.uid}:::`);e._redirectEventId=t;await e.auth._setRedirectUser(e);await e.auth._persistUserIfCurrent(e);return t}const te=10*60*1e3;class AuthEventManager{constructor(e){this.auth=e;this.cachedEventUids=new Set;this.consumers=new Set;this.queuedRedirectEvent=null;this.hasHandledPotentialRedirect=false;this.lastProcessedEventTime=Date.now()}registerConsumer(e){this.consumers.add(e);if(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 false}let t=false;this.consumers.forEach((n=>{if(this.isEventForConsumer(e,n)){t=true;this.sendToConsumer(e,n);this.saveEventToCache(e)}}));if(this.hasHandledPotentialRedirect||!isRedirectEvent(e)){return t}this.hasHandledPotentialRedirect=true;if(!t){this.queuedRedirectEvent=e;t=true}return t}sendToConsumer(e,t){if(e.error&&!isNullRedirectEvent(e)){const n=e.error.code?.split("auth/")[1]||"internal-error";t.onError(_createError(this.auth,n))}else{t.onAuthEvent(e)}}isEventForConsumer(e,t){const n=t.eventId===null||!!e.eventId&&e.eventId===t.eventId;return t.filter.includes(e.type)&&n}hasEventBeenHandled(e){if(Date.now()-this.lastProcessedEventTime>=te){this.cachedEventUids.clear()}return this.cachedEventUids.has(eventUid(e))}saveEventToCache(e){this.cachedEventUids.add(eventUid(e));
2this.lastProcessedEventTime=Date.now()}}function eventUid(e){return[e.type,e.eventId,e.sessionId,e.tenantId].filter((e=>e)).join("-")}function isNullRedirectEvent({type:e,error:t}){return e==="unknown"&&t?.code===`auth/${"no-auth-event"}`}function isRedirectEvent(e){switch(e.type){case"signInViaRedirect":case"linkViaRedirect":case"reauthViaRedirect":return true;case"unknown":return isNullRedirectEvent(e);default:return false}}async function _getProjectConfig(e,t={}){return _performApiRequest(e,"GET","/v1/projects",t)}const ne=/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;const re=/^https?/;async function _validateOrigin(e){if(e.config.emulator){return}const{authorizedDomains:t}=await _getProjectConfig(e);for(const e of t){try{if(matchDomain(e)){return}}catch{}}_fail(e,"unauthorized-domain")}function matchDomain(e){const t=_getCurrentUrl();const{protocol:n,hostname:r}=new URL(t);if(e.startsWith("chrome-extension://")){const i=new URL(e);if(i.hostname===""&&r===""){return n==="chrome-extension:"&&e.replace("chrome-extension://","")===t.replace("chrome-extension://","")}return n==="chrome-extension:"&&i.hostname===r}if(!re.test(n)){return false}if(ne.test(e)){return r===e}const i=e.replace(/\./g,"\\.");const s=new RegExp("^(.+\\."+i+"|"+i+")$","i");return s.test(r)}const ie=new Delay(3e4,6e4);function resetUnloadedGapiModules(){const e=_window().___jsl;if(e?.H){for(const t of Object.keys(e.H)){e.H[t].r=e.H[t].r||[];e.H[t].L=e.H[t].L||[];e.H[t].r=[...e.H[t].L];if(e.CP){for(let t=0;t<e.CP.length;t++){e.CP[t]=null}}}}}function loadGapi(e){return new Promise(((t,n)=>{function loadGapiIframe(){resetUnloadedGapiModules();gapi.load("gapi.iframes",{callback:()=>{t(gapi.iframes.getContext())},ontimeout:()=>{resetUnloadedGapiModules();n(_createError(e,"network-request-failed"))},timeout:ie.get()})}if(_window().gapi?.iframes?.Iframe){t(gapi.iframes.getContext())}else if(!!_window().gapi?.load){loadGapiIframe()}else{const t=_generateCallbackName("iframefcb");_window()[t]=()=>{if(!!gapi.load){loadGapiIframe()}else{n(_createError(e,"network-request-failed"))}};return _loadJS(`${_gapiScriptUrl()}?onload=${t}`).catch((e=>n(e)))}})).catch((e=>{se=null;throw e}))}let se=null;function _loadGapi(e){se=se||loadGapi(e);return se}const oe=new Delay(5e3,15e3);const ae="__/auth/iframe";const ce="emulator/auth/iframe";const le={style:{position:"absolute",top:"-100px",width:"1px",height:"1px"},"aria-hidden":"true",tabindex:"-1"};const ue=new Map([["identitytoolkit.googleapis.com","p"],["staging-identitytoolkit.sandbox.googleapis.com","s"],["test-identitytoolkit.sandbox.googleapis.com","t"]]);function getIframeUrl(e){const t=e.config;_assert(t.authDomain,e,"auth-domain-config-required");const n=t.emulator?_emulatorUrl(t,ce):`https://${e.config.authDomain}/${ae}`;const s={apiKey:t.apiKey,appName:e.name,v:r.SDK_VERSION};const o=ue.get(e.config.apiHost);if(o){s.eid=o}const a=e._getFrameworks();if(a.length){s.fw=a.join(",")}return`${n}?${i.querystring(s).slice(1)}`}async function _openIframe(e){const t=await _loadGapi(e);const n=_window().gapi;_assert(n,e,"internal-error");return t.open({where:document.body,url:getIframeUrl(e),messageHandlersFilter:n.iframes.CROSS_ORIGIN_IFRAMES_FILTER,attributes:le,dontclear:true},(t=>new Promise((async(n,r)=>{await t.restyle({setHideOnLeave:false});const i=_createError(e,"network-request-failed");const s=_window().setTimeout((()=>{r(i)}),oe.get());function clearTimerAndResolve(){_window().clearTimeout(s);n(t)}t.ping(clearTimerAndResolve).then(clearTimerAndResolve,(()=>{r(i)}))}))))}const de={location:"yes",resizable:"yes",statusbar:"yes",toolbar:"no"};const he=500;const pe=600;const fe="_blank";const me="http://localhost";class AuthPopup{constructor(e){this.window=e;this.associatedEvent=null}close(){if(this.window){try{this.window.close()}catch(e){}}}}function _open(e,t,n,r=he,s=pe){const o=Math.max((window.screen.availHeight-s)/2,0).toString();const a=Math.max((window.screen.availWidth-r)/2,0).toString();let c="";const l={...de,width:r.toString(),height:s.toString(),top:o,left:a};const u=i.getUA().toLowerCase();if(n){c=_isChromeIOS(u)?fe:n}if(_isFirefox(u)){t=t||me;l.scrollbars="yes"}const d=Object.entries(l).reduce(((e,[t,n])=>`${e}${t}=${n},`),"");if(_isIOSStandalone(u)&&c!=="_self"){openAsNewWindowIOS(t||"",c);return new AuthPopup(null)}const h=window.open(t||"",c,d);_assert(h,e,"popup-blocked");try{h.focus()}catch(e){}return new AuthPopup(h)}function openAsNewWindowIOS(e,t){const n=document.createElement("a");n.href=e;n.target=t;const r=document.createEvent("MouseEvent");r.initMouseEvent("click",true,true,window,1,0,0,0,0,false,false,false,false,1,null);n.dispatchEvent(r)}const ge="__/auth/handler";const _e="emulator/auth/handler";const ve=encodeURIComponent("fac");async function _getRedirectUrl(e,t,n,s,o,a){_assert(e.config.authDomain,e,"auth-domain-config-required");
2_assert(e.config.apiKey,e,"invalid-api-key");const c={apiKey:e.config.apiKey,appName:e.name,authType:n,redirectUrl:s,v:r.SDK_VERSION,eventId:o};if(t instanceof FederatedAuthProvider){t.setDefaultLanguage(e.languageCode);c.providerId=t.providerId||"";if(!i.isEmpty(t.getCustomParameters())){c.customParameters=JSON.stringify(t.getCustomParameters())}for(const[e,t]of Object.entries(a||{})){c[e]=t}}if(t instanceof BaseOAuthProvider){const e=t.getScopes().filter((e=>e!==""));if(e.length>0){c.scopes=e.join(",")}}if(e.tenantId){c.tid=e.tenantId}const l=c;for(const e of Object.keys(l)){if(l[e]===undefined){delete l[e]}}const u=await e._getAppCheckToken();const d=u?`#${ve}=${encodeURIComponent(u)}`:"";return`${getHandlerBase(e)}?${i.querystring(l).slice(1)}${d}`}function getHandlerBase({config:e}){if(!e.emulator){return`https://${e.authDomain}/${ge}`}return _emulatorUrl(e,_e)}const ye="webStorageSupport";class BrowserPopupRedirectResolver{constructor(){this.eventManagers={};this.iframes={};this.originValidationPromises={};this._redirectPersistence=V;this._completeRedirectFn=_getRedirectResult;this._overrideRedirectResult=_overrideRedirectResult}async _openPopup(e,t,n,r){debugAssert(this.eventManagers[e._key()]?.manager,"_initialize() not called before _openPopup()");const i=await _getRedirectUrl(e,t,n,_getCurrentUrl(),r);return _open(e,i,_generateEventId())}async _openRedirect(e,t,n,r){await this._originValidation(e);const i=await _getRedirectUrl(e,t,n,_getCurrentUrl(),r);_setWindowLocation(i);return new Promise((()=>{}))}_initialize(e){const t=e._key();if(this.eventManagers[t]){const{manager:e,promise:n}=this.eventManagers[t];if(e){return Promise.resolve(e)}else{debugAssert(n,"If manager is not set, promise should be");return n}}const n=this.initAndGetManager(e);this.eventManagers[t]={promise:n};n.catch((()=>{delete this.eventManagers[t]}));return n}async initAndGetManager(e){const t=await _openIframe(e);const n=new AuthEventManager(e);t.register("authEvent",(t=>{_assert(t?.authEvent,e,"invalid-auth-event");const r=n.onEvent(t.authEvent);return{status:r?"ACK":"ERROR"}}),gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER);this.eventManagers[e._key()]={manager:n};this.iframes[e._key()]=t;return n}_isIframeWebStorageSupported(e,t){const n=this.iframes[e._key()];n.send(ye,{type:ye},(n=>{const r=n?.[0]?.[ye];if(r!==undefined){t(!!r)}_fail(e,"internal-error")}),gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER)}_originValidation(e){const t=e._key();if(!this.originValidationPromises[t]){this.originValidationPromises[t]=_validateOrigin(e)}return this.originValidationPromises[t]}get _shouldInitProactively(){return _isMobileBrowser()||_isSafari()||_isIOS()}}const Ie=BrowserPopupRedirectResolver;class MultiFactorAssertionImpl{constructor(e){this.factorId=e}_process(e,t,n){switch(t.type){case"enroll":return this._finalizeEnroll(e,t.credential,n);case"signin":return this._finalizeSignIn(e,t.credential);default:return debugFail("unexpected MultiFactorSessionType")}}}class PhoneMultiFactorAssertionImpl extends MultiFactorAssertionImpl{constructor(e){super("phone");this.credential=e}static _fromCredential(e){return new PhoneMultiFactorAssertionImpl(e)}_finalizeEnroll(e,t,n){return finalizeEnrollPhoneMfa(e,{idToken:t,displayName:n,phoneVerificationInfo:this.credential._makeVerificationRequest()})}_finalizeSignIn(e,t){return finalizeSignInPhoneMfa(e,{mfaPendingCredential:t,phoneVerificationInfo:this.credential._makeVerificationRequest()})}}class PhoneMultiFactorGenerator{constructor(){}static assertion(e){return PhoneMultiFactorAssertionImpl._fromCredential(e)}}PhoneMultiFactorGenerator.FACTOR_ID="phone";class TotpMultiFactorGenerator{static assertionForEnrollment(e,t){return TotpMultiFactorAssertionImpl._fromSecret(e,t)}static assertionForSignIn(e,t){return TotpMultiFactorAssertionImpl._fromEnrollmentId(e,t)}static async generateSecret(e){const t=e;_assert(typeof t.user?.auth!=="undefined","internal-error");const n=await startEnrollTotpMfa(t.user.auth,{idToken:t.credential,totpEnrollmentInfo:{}});return TotpSecret._fromStartTotpMfaEnrollmentResponse(n,t.user.auth)}}TotpMultiFactorGenerator.FACTOR_ID="totp";class TotpMultiFactorAssertionImpl extends MultiFactorAssertionImpl{constructor(e,t,n){super("totp");this.otp=e;this.enrollmentId=t;this.secret=n}static _fromSecret(e,t){return new TotpMultiFactorAssertionImpl(t,undefined,e)}static _fromEnrollmentId(e,t){return new TotpMultiFactorAssertionImpl(t,e)}async _finalizeEnroll(e,t,n){_assert(typeof this.secret!=="undefined",e,"argument-error");return finalizeEnrollTotpMfa(e,{idToken:t,displayName:n,totpVerificationInfo:this.secret._makeTotpVerificationInfo(this.otp)})}async _finalizeSignIn(e,t){_assert(this.enrollmentId!==undefined&&this.otp!==undefined,e,"argument-error");const n={verificationCode:this.otp};return finalizeSignInTotpMfa(e,{mfaPendingCredential:t,mfaEnrollmentId:this.enrollmentId,totpVerificationInfo:n})}}class TotpSecret{constructor(e,t,n,r,i,s,o){this.sessionInfo=s;this.auth=o;this.secretKey=e;this.hashingAlgorithm=t;this.codeLength=n;
2this.codeIntervalSeconds=r;this.enrollmentCompletionDeadline=i}static _fromStartTotpMfaEnrollmentResponse(e,t){return new TotpSecret(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 n=false;if(_isEmptyString(e)||_isEmptyString(t)){n=true}if(n){if(_isEmptyString(e)){e=this.auth.currentUser?.email||"unknownuser"}if(_isEmptyString(t)){t=this.auth.name}}return`otpauth://totp/${t}:${e}?secret=${this.secretKey}&issuer=${t}&algorithm=${this.hashingAlgorithm}&digits=${this.codeLength}`}}function _isEmptyString(e){return typeof e==="undefined"||e?.length===0}var Ce="@firebase/auth";var we="1.13.2";class AuthInterop{constructor(e){this.auth=e;this.internalListeners=new Map}getUid(){this.assertAuthConfigured();return this.auth.currentUser?.uid||null}async getToken(e){this.assertAuthConfigured();await this.auth._initializationPromise;if(!this.auth.currentUser){return null}const t=await this.auth.currentUser.getIdToken(e);return{accessToken:t}}addAuthTokenListener(e){this.assertAuthConfigured();if(this.internalListeners.has(e)){return}const t=this.auth.onIdTokenChanged((t=>{e(t?.stsTokenManager.accessToken||null)}));this.internalListeners.set(e,t);this.updateProactiveRefresh()}removeAuthTokenListener(e){this.assertAuthConfigured();const t=this.internalListeners.get(e);if(!t){return}this.internalListeners.delete(e);t();this.updateProactiveRefresh()}assertAuthConfigured(){_assert(this.auth._initializationPromise,"dependent-sdk-initialized-before-auth")}updateProactiveRefresh(){if(this.internalListeners.size>0){this.auth._startProactiveRefresh()}else{this.auth._stopProactiveRefresh()}}}function getVersionForPlatform(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 undefined}}function registerAuth(e){r._registerComponent(new o.Component("auth",((t,{options:n})=>{const r=t.getProvider("app").getImmediate();const i=t.getProvider("heartbeat");const s=t.getProvider("app-check-internal");const{apiKey:o,authDomain:a}=r.options;_assert(o&&!o.includes(":"),"invalid-api-key",{appName:r.name});const c={apiKey:o,authDomain:a,clientPlatform:e,apiHost:"identitytoolkit.googleapis.com",tokenApiHost:"securetoken.googleapis.com",apiScheme:"https",sdkClientVersion:_getClientVersion(e)};const l=new AuthImpl(r,i,s,c);_initializeAuthInstance(l,n);return l}),"PUBLIC").setInstantiationMode("EXPLICIT").setInstanceCreatedCallback(((e,t,n)=>{const r=e.getProvider("auth-internal");r.initialize()})));r._registerComponent(new o.Component("auth-internal",(e=>{const t=_castAuth(e.getProvider("auth").getImmediate());return(e=>new AuthInterop(e))(t)}),"PRIVATE").setInstantiationMode("EXPLICIT"));r.registerVersion(Ce,we,getVersionForPlatform(e));r.registerVersion(Ce,we,"cjs2020")}const Ee=5*60;const Te=i.getExperimentalSetting("authIdTokenMaxAge")||Ee;let Pe=null;const mintCookieFactory=e=>async t=>{const n=t&&await t.getIdTokenResult();const r=n&&((new Date).getTime()-Date.parse(n.issuedAtTime))/1e3;if(r&&r>Te){return}const i=n?.token;if(Pe===i){return}Pe=i;await fetch(e,{method:i?"POST":"DELETE",headers:i?{Authorization:`Bearer ${i}`}:{}})};function getAuth(e=r.getApp()){const t=r._getProvider(e,"auth");if(t.isInitialized()){return t.getImmediate()}const n=initializeAuth(e,{popupRedirectResolver:Ie,persistence:[K,U,V]});const s=i.getExperimentalSetting("authTokenSyncURL");if(s&&typeof isSecureContext==="boolean"&&isSecureContext){const e=new URL(s,location.origin);if(location.origin===e.origin){const t=mintCookieFactory(e.toString());beforeAuthStateChanged(n,t,(()=>t(n.currentUser)));onIdTokenChanged(n,(e=>t(e)))}}const o=i.getDefaultEmulatorHost("auth");if(o){connectAuthEmulator(n,`http://${o}`)}return n}function getScriptParentElement(){return document.getElementsByTagName("head")?.[0]??document}
2_setExternalJSProvider({loadJS(e){return new Promise(((t,n)=>{const r=document.createElement("script");r.setAttribute("src",e);r.onload=t;r.onerror=e=>{const t=_createError("internal-error");t.customData=e;n(t)};r.type="text/javascript";r.charset="UTF-8";getScriptParentElement().appendChild(r)}))},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="});registerAuth("Browser");t.AUTH_ERROR_CODES_MAP_DO_NOT_USE_INTERNALLY=m;t.ActionCodeOperation=d;t.ActionCodeURL=ActionCodeURL;t.AuthCredential=AuthCredential;t.AuthEventManager=AuthEventManager;t.AuthImpl=AuthImpl;t.AuthPopup=AuthPopup;t.EmailAuthCredential=EmailAuthCredential;t.EmailAuthProvider=EmailAuthProvider;t.FacebookAuthProvider=FacebookAuthProvider;t.FactorId=a;t.FetchProvider=FetchProvider;t.GithubAuthProvider=GithubAuthProvider;t.GoogleAuthProvider=GoogleAuthProvider;t.OAuthCredential=OAuthCredential;t.OAuthProvider=OAuthProvider;t.OperationType=u;t.PhoneAuthCredential=PhoneAuthCredential;t.PhoneAuthProvider=PhoneAuthProvider;t.PhoneMultiFactorGenerator=PhoneMultiFactorGenerator;t.ProviderId=c;t.RecaptchaVerifier=RecaptchaVerifier;t.SAMLAuthCredential=SAMLAuthCredential;t.SAMLAuthProvider=SAMLAuthProvider;t.SignInMethod=l;t.TotpMultiFactorGenerator=TotpMultiFactorGenerator;t.TotpSecret=TotpSecret;t.TwitterAuthProvider=TwitterAuthProvider;t.UserImpl=UserImpl;t._assert=_assert;t._castAuth=_castAuth;t._clearRedirectOutcomes=_clearRedirectOutcomes;t._createError=_createError;t._fail=_fail;t._generateEventId=_generateEventId;t._getClientVersion=_getClientVersion;t._getInstance=_getInstance;t._getProjectConfig=_getProjectConfig;t._getRedirectResult=_getRedirectResult;t._getRedirectUrl=_getRedirectUrl;t._isAndroid=_isAndroid;t._isIOS=_isIOS;t._isIOS7Or8=_isIOS7Or8;t._overrideRedirectResult=_overrideRedirectResult;t._persistenceKeyName=_persistenceKeyName;t.applyActionCode=applyActionCode;t.beforeAuthStateChanged=beforeAuthStateChanged;t.browserCookiePersistence=W;t.browserLocalPersistence=U;t.browserPopupRedirectResolver=Ie;t.browserSessionPersistence=V;t.checkActionCode=checkActionCode;t.confirmPasswordReset=confirmPasswordReset;t.connectAuthEmulator=connectAuthEmulator;t.createUserWithEmailAndPassword=createUserWithEmailAndPassword;t.debugAssert=debugAssert;t.debugErrorMap=h;t.deleteUser=deleteUser;t.fetchSignInMethodsForEmail=fetchSignInMethodsForEmail;t.getAdditionalUserInfo=getAdditionalUserInfo;t.getAuth=getAuth;t.getIdToken=getIdToken;t.getIdTokenResult=getIdTokenResult;t.getMultiFactorResolver=getMultiFactorResolver;t.getRedirectResult=getRedirectResult;t.inMemoryPersistence=C;t.indexedDBLocalPersistence=K;t.initializeAuth=initializeAuth;t.initializeRecaptchaConfig=initializeRecaptchaConfig;t.isSignInWithEmailLink=isSignInWithEmailLink;t.linkWithCredential=linkWithCredential;t.linkWithPhoneNumber=linkWithPhoneNumber;t.linkWithPopup=linkWithPopup;t.linkWithRedirect=linkWithRedirect;t.multiFactor=multiFactor;t.onAuthStateChanged=onAuthStateChanged;t.onIdTokenChanged=onIdTokenChanged;t.parseActionCodeURL=parseActionCodeURL;t.prodErrorMap=p;t.reauthenticateWithCredential=reauthenticateWithCredential;t.reauthenticateWithPhoneNumber=reauthenticateWithPhoneNumber;t.reauthenticateWithPopup=reauthenticateWithPopup;t.reauthenticateWithRedirect=reauthenticateWithRedirect;t.reload=reload;t.revokeAccessToken=revokeAccessToken;t.sendEmailVerification=sendEmailVerification;t.sendPasswordResetEmail=sendPasswordResetEmail;t.sendSignInLinkToEmail=sendSignInLinkToEmail;t.setPersistence=setPersistence;t.signInAnonymously=signInAnonymously;t.signInWithCredential=signInWithCredential;t.signInWithCustomToken=signInWithCustomToken;t.signInWithEmailAndPassword=signInWithEmailAndPassword;t.signInWithEmailLink=signInWithEmailLink;t.signInWithPhoneNumber=signInWithPhoneNumber;t.signInWithPopup=signInWithPopup;t.signInWithRedirect=signInWithRedirect;t.signOut=signOut;t.unlink=unlink;t.updateCurrentUser=updateCurrentUser;t.updateEmail=updateEmail;t.updatePassword=updatePassword;t.updatePhoneNumber=updatePhoneNumber;t.updateProfile=updateProfile;t.useDeviceLanguage=useDeviceLanguage;t.validatePassword=validatePassword;t.verifyBeforeUpdateEmail=verifyBeforeUpdateEmail;t.verifyPasswordResetCode=verifyPasswordResetCode}
2,71929(e,t,n){Object.defineProperty(t,"__esModule",{value:true});var r=n(41386);var i=n(36183);n(50218);n(40767);n(95282);function _cordovaWindow(){return window}const s=2e3;async function _generateHandlerUrl(e,t,n){const{BuildInfo:i}=_cordovaWindow();r.debugAssert(t.sessionId,"AuthEvent did not contain a session ID");const s=await computeSha256(t.sessionId);const o={};if(r._isIOS()){o["ibi"]=i.packageName}else if(r._isAndroid()){o["apn"]=i.packageName}else{r._fail(e,"operation-not-supported-in-this-environment")}if(i.displayName){o["appDisplayName"]=i.displayName}o["sessionId"]=s;return r._getRedirectUrl(e,n,t.type,undefined,t.eventId??undefined,o)}async function _validateOrigin(e){const{BuildInfo:t}=_cordovaWindow();const n={};if(r._isIOS()){n.iosBundleId=t.packageName}else if(r._isAndroid()){n.androidPackageName=t.packageName}else{r._fail(e,"operation-not-supported-in-this-environment")}await r._getProjectConfig(e,n)}function _performRedirect(e){const{cordova:t}=_cordovaWindow();return new Promise((n=>{t.plugins.browsertab.isAvailable((i=>{let s=null;if(i){t.plugins.browsertab.openUrl(e)}else{s=t.InAppBrowser.open(e,r._isIOS7Or8()?"_blank":"_system","location=yes")}n(s)}))}))}async function _waitForAppResume(e,t,n){const{cordova:i}=_cordovaWindow();let cleanup=()=>{};try{await new Promise(((o,a)=>{let c=null;function authEventSeen(){o();const e=i.plugins.browsertab?.close;if(typeof e==="function"){e()}if(typeof n?.close==="function"){n.close()}}function resumed(){if(c){return}c=window.setTimeout((()=>{a(r._createError(e,"redirect-cancelled-by-user"))}),s)}function visibilityChanged(){if(document?.visibilityState==="visible"){resumed()}}t.addPassiveListener(authEventSeen);document.addEventListener("resume",resumed,false);if(r._isAndroid()){document.addEventListener("visibilitychange",visibilityChanged,false)}cleanup=()=>{t.removePassiveListener(authEventSeen);document.removeEventListener("resume",resumed,false);document.removeEventListener("visibilitychange",visibilityChanged,false);if(c){window.clearTimeout(c)}}}))}finally{cleanup()}}function _checkCordovaConfiguration(e){const t=_cordovaWindow();r._assert(typeof t?.universalLinks?.subscribe==="function",e,"invalid-cordova-configuration",{missingPlugin:"cordova-universal-links-plugin-fix"});r._assert(typeof t?.BuildInfo?.packageName!=="undefined",e,"invalid-cordova-configuration",{missingPlugin:"cordova-plugin-buildInfo"});r._assert(typeof t?.cordova?.plugins?.browsertab?.openUrl==="function",e,"invalid-cordova-configuration",{missingPlugin:"cordova-plugin-browsertab"});r._assert(typeof t?.cordova?.plugins?.browsertab?.isAvailable==="function",e,"invalid-cordova-configuration",{missingPlugin:"cordova-plugin-browsertab"});r._assert(typeof t?.cordova?.InAppBrowser?.open==="function",e,"invalid-cordova-configuration",{missingPlugin:"cordova-plugin-inappbrowser"})}async function computeSha256(e){const t=stringToArrayBuffer(e);const n=await crypto.subtle.digest("SHA-256",t);const r=Array.from(new Uint8Array(n));return r.map((e=>e.toString(16).padStart(2,"0"))).join("")}function stringToArrayBuffer(e){r.debugAssert(/[0-9a-zA-Z]+/.test(e),"Can only convert alpha-numeric strings");if(typeof TextEncoder!=="undefined"){return(new TextEncoder).encode(e)}const t=new ArrayBuffer(e.length);const n=new Uint8Array(t);for(let t=0;t<e.length;t++){n[t]=e.charCodeAt(t)}return n}const o=20;class CordovaAuthEventManager extends r.AuthEventManager{constructor(){super(...arguments);this.passiveListeners=new Set;this.initPromise=new Promise((e=>{this.resolveInitialized=e}))}addPassiveListener(e){this.passiveListeners.add(e)}removePassiveListener(e){this.passiveListeners.delete(e)}resetRedirect(){this.queuedRedirectEvent=null;this.hasHandledPotentialRedirect=false}onEvent(e){this.resolveInitialized();this.passiveListeners.forEach((t=>t(e)));return super.onEvent(e)}async initialized(){await this.initPromise}}function _generateNewEvent(e,t,n=null){return{type:t,eventId:n,urlResponse:null,sessionId:generateSessionId(),postBody:null,tenantId:e.tenantId,error:r._createError(e,"no-auth-event")}}function _savePartialEvent(e,t){return storage()._set(persistenceKey(e),t)}async function _getAndRemoveEvent(e){const t=await storage()._get(persistenceKey(e));if(t){await storage()._remove(persistenceKey(e))}return t}
2function _eventFromPartialAndUrl(e,t){const n=_getDeepLinkFromCallback(t);if(n.includes("/__/auth/callback")){const t=searchParamsOrEmpty(n);const i=t["firebaseError"]?parseJsonOrNull(decodeURIComponent(t["firebaseError"])):null;const s=i?.["code"]?.split("auth/")?.[1];const o=s?r._createError(s):null;if(o){return{type:e.type,eventId:e.eventId,tenantId:e.tenantId,error:o,urlResponse:null,sessionId:null,postBody:null}}else{return{type:e.type,eventId:e.eventId,tenantId:e.tenantId,sessionId:e.sessionId,urlResponse:n,postBody:null}}}return null}function generateSessionId(){const e=[];const t="1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";for(let n=0;n<o;n++){const n=Math.floor(Math.random()*t.length);e.push(t.charAt(n))}return e.join("")}function storage(){return r._getInstance(r.browserLocalPersistence)}function persistenceKey(e){return r._persistenceKeyName("authEvent",e.config.apiKey,e.name)}function parseJsonOrNull(e){try{return JSON.parse(e)}catch(e){return null}}function _getDeepLinkFromCallback(e){const t=searchParamsOrEmpty(e);const n=t["link"]?decodeURIComponent(t["link"]):undefined;const r=searchParamsOrEmpty(n)["link"];const i=t["deep_link_id"]?decodeURIComponent(t["deep_link_id"]):undefined;const s=searchParamsOrEmpty(i)["link"];return s||i||r||n||e}function searchParamsOrEmpty(e){if(!e?.includes("?")){return{}}const[t,...n]=e.split("?");return i.querystringDecode(n.join("?"))}const a=500;class CordovaPopupRedirectResolver{constructor(){this._redirectPersistence=r.browserSessionPersistence;this._shouldInitProactively=true;this.eventManagers=new Map;this.originValidationPromises={};this._completeRedirectFn=r._getRedirectResult;this._overrideRedirectResult=r._overrideRedirectResult}async _initialize(e){const t=e._key();let n=this.eventManagers.get(t);if(!n){n=new CordovaAuthEventManager(e);this.eventManagers.set(t,n);this.attachCallbackListeners(e,n)}return n}_openPopup(e){r._fail(e,"operation-not-supported-in-this-environment")}async _openRedirect(e,t,n,i){_checkCordovaConfiguration(e);const s=await this._initialize(e);await s.initialized();s.resetRedirect();r._clearRedirectOutcomes();await this._originValidation(e);const o=_generateNewEvent(e,n,i);await _savePartialEvent(e,o);const a=await _generateHandlerUrl(e,o,t);const c=await _performRedirect(a);return _waitForAppResume(e,s,c)}_isIframeWebStorageSupported(e,t){throw new Error("Method not implemented.")}_originValidation(e){const t=e._key();if(!this.originValidationPromises[t]){this.originValidationPromises[t]=_validateOrigin(e)}return this.originValidationPromises[t]}attachCallbackListeners(e,t){const{universalLinks:n,handleOpenURL:r,BuildInfo:i}=_cordovaWindow();const s=setTimeout((async()=>{await _getAndRemoveEvent(e);t.onEvent(generateNoEvent())}),a);const universalLinksCb=async n=>{clearTimeout(s);const r=await _getAndRemoveEvent(e);let i=null;if(r&&n?.["url"]){i=_eventFromPartialAndUrl(r,n["url"])}t.onEvent(i||generateNoEvent())};if(typeof n!=="undefined"&&typeof n.subscribe==="function"){n.subscribe(null,universalLinksCb)}const o=r;const c=`${i.packageName.toLowerCase()}://`;_cordovaWindow().handleOpenURL=async e=>{if(e.toLowerCase().startsWith(c)){universalLinksCb({url:e})}if(typeof o==="function"){try{o(e)}catch(e){console.error(e)}}}}}const c=CordovaPopupRedirectResolver;function generateNoEvent(){return{type:"unknown",eventId:null,sessionId:null,urlResponse:null,postBody:null,tenantId:null,error:r._createError("no-auth-event")}}function addFrameworkForLogging(e,t){r._castAuth(e)._logFramework(t)}t.ActionCodeOperation=r.ActionCodeOperation;t.ActionCodeURL=r.ActionCodeURL;t.AuthCredential=r.AuthCredential;t.AuthErrorCodes=r.AUTH_ERROR_CODES_MAP_DO_NOT_USE_INTERNALLY;t.AuthImpl=r.AuthImpl;t.AuthPopup=r.AuthPopup;t.EmailAuthCredential=r.EmailAuthCredential;t.EmailAuthProvider=r.EmailAuthProvider;t.FacebookAuthProvider=r.FacebookAuthProvider;t.FactorId=r.FactorId;t.FetchProvider=r.FetchProvider;t.GithubAuthProvider=r.GithubAuthProvider;t.GoogleAuthProvider=r.GoogleAuthProvider;t.OAuthCredential=r.OAuthCredential;t.OAuthProvider=r.OAuthProvider;t.OperationType=r.OperationType;t.PhoneAuthCredential=r.PhoneAuthCredential;t.PhoneAuthProvider=r.PhoneAuthProvider;t.PhoneMultiFactorGenerator=r.PhoneMultiFactorGenerator;t.ProviderId=r.ProviderId;t.RecaptchaVerifier=r.RecaptchaVerifier;t.SAMLAuthCredential=r.SAMLAuthCredential;t.SAMLAuthProvider=r.SAMLAuthProvider;t.SignInMethod=r.SignInMethod;t.TotpMultiFactorGenerator=r.TotpMultiFactorGenerator;t.TotpSecret=r.TotpSecret;t.TwitterAuthProvider=r.TwitterAuthProvider;t.UserImpl=r.UserImpl;t._assert=r._assert;t._castAuth=r._castAuth;t._fail=r._fail;t._generateEventId=r._generateEventId;t._getClientVersion=r._getClientVersion;t._getInstance=r._getInstance;t._getRedirectResult=r._getRedirectResult;t._overrideRedirectResult=r._overrideRedirectResult;t._persistenceKeyName=r._persistenceKeyName;t.applyActionCode=r.applyActionCode;t.beforeAuthStateChanged=r.beforeAuthStateChanged;t.browserCookiePersistence=r.browserCookiePersistence;t.browserLocalPersistence=r.browserLocalPersistence;t.browserPopupRedirectResolver=r.browserPopupRedirectResolver;t.browserSessionPersistence=r.browserSessionPersistence;t.checkActionCode=r.checkActionCode;t.confirmPasswordReset=r.confirmPasswordReset;t.connectAuthEmulator=r.connectAuthEmulator;t.createUserWithEmailAndPassword=r.createUserWithEmailAndPassword;t.debugErrorMap=r.debugErrorMap;t.deleteUser=r.deleteUser;t.fetchSignInMethodsForEmail=r.fetchSignInMethodsForEmail;t.getAdditionalUserInfo=r.getAdditionalUserInfo;t.getAuth=r.getAuth;t.getIdToken=r.getIdToken;t.getIdTokenResult=r.getIdTokenResult;t.getMultiFactorResolver=r.getMultiFactorResolver;t.getRedirectResult=r.getRedirectResult;t.inMemoryPersistence=r.inMemoryPersistence;t.indexedDBLocalPersistence=r.indexedDBLocalPersistence;t.initializeAuth=r.initializeAuth;t.initializeRecaptchaConfig=r.initializeRecaptchaConfig;t.isSignInWithEmailLink=r.isSignInWithEmailLink;t.linkWithCredential=r.linkWithCredential;t.linkWithPhoneNumber=r.linkWithPhoneNumber;t.linkWithPopup=r.linkWithPopup;t.linkWithRedirect=r.linkWithRedirect;t.multiFactor=r.multiFactor;t.onAuthStateChanged=r.onAuthStateChanged;t.onIdTokenChanged=r.onIdTokenChanged;t.parseActionCodeURL=r.parseActionCodeURL;t.prodErrorMap=r.prodErrorMap;t.reauthenticateWithCredential=r.reauthenticateWithCredential;t.reauthenticateWithPhoneNumber=r.reauthenticateWithPhoneNumber;t.reauthenticateWithPopup=r.reauthenticateWithPopup;t.reauthenticateWithRedirect=r.reauthenticateWithRedirect;t.reload=r.reload;t.revokeAccessToken=r.revokeAccessToken;t.sendEmailVerification=r.sendEmailVerification;t.sendPasswordResetEmail=r.sendPasswordResetEmail;t.sendSignInLinkToEmail=r.sendSignInLinkToEmail;t.setPersistence=r.setPersistence;t.signInAnonymously=r.signInAnonymously;t.signInWithCredential=r.signInWithCredential;t.signInWithCustomToken=r.signInWithCustomToken;t.signInWithEmailAndPassword=r.signInWithEmailAndPassword;t.signInWithEmailLink=r.signInWithEmailLink;t.signInWithPhoneNumber=r.signInWithPhoneNumber;t.signInWithPopup=r.signInWithPopup;t.signInWithRedirect=r.signInWithRedirect;t.signOut=r.signOut;t.unlink=r.unlink;t.updateCurrentUser=r.updateCurrentUser;t.updateEmail=r.updateEmail;t.updatePassword=r.updatePassword;t.updatePhoneNumber=r.updatePhoneNumber;t.updateProfile=r.updateProfile;t.useDeviceLanguage=r.useDeviceLanguage;t.validatePassword=r.validatePassword;t.verifyBeforeUpdateEmail=r.verifyBeforeUpdateEmail;t.verifyPasswordResetCode=r.verifyPasswordResetCode;t.addFrameworkForLogging=addFrameworkForLogging;t.cordovaPopupRedirectResolver=c}
2,95282(e,t,n){Object.defineProperty(t,"__esModule",{value:true});var r=n(36183);class Component{constructor(e,t,n){this.name=e;this.instanceFactory=t;this.type=n;this.multipleInstances=false;this.serviceProps={};this.instantiationMode="LAZY";this.onInstanceCreated=null}setInstantiationMode(e){this.instantiationMode=e;return this}setMultipleInstances(e){this.multipleInstances=e;return this}setServiceProps(e){this.serviceProps=e;return this}setInstanceCreatedCallback(e){this.onInstanceCreated=e;return this}}const i="[DEFAULT]";class Provider{constructor(e,t){this.name=e;this.container=t;this.component=null;this.instances=new Map;this.instancesDeferred=new Map;this.instancesOptions=new Map;this.onInitCallbacks=new Map}get(e){const t=this.normalizeInstanceIdentifier(e);if(!this.instancesDeferred.has(t)){const e=new r.Deferred;this.instancesDeferred.set(t,e);if(this.isInitialized(t)||this.shouldAutoInitialize()){try{const n=this.getOrInitializeService({instanceIdentifier:t});if(n){e.resolve(n)}}catch(e){}}}return this.instancesDeferred.get(t).promise}getImmediate(e){const t=this.normalizeInstanceIdentifier(e?.identifier);const n=e?.optional??false;if(this.isInitialized(t)||this.shouldAutoInitialize()){try{return this.getOrInitializeService({instanceIdentifier:t})}catch(e){if(n){return null}else{throw e}}}else{if(n){return null}else{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`)}this.component=e;if(!this.shouldAutoInitialize()){return}if(isComponentEager(e)){try{this.getOrInitializeService({instanceIdentifier:i})}catch(e){}}for(const[e,t]of this.instancesDeferred.entries()){const n=this.normalizeInstanceIdentifier(e);try{const e=this.getOrInitializeService({instanceIdentifier:n});t.resolve(e)}catch(e){}}}clearInstance(e=i){this.instancesDeferred.delete(e);this.instancesOptions.delete(e);this.instances.delete(e)}async delete(){const e=Array.from(this.instances.values());await Promise.all([...e.filter((e=>"INTERNAL"in e)).map((e=>e.INTERNAL.delete())),...e.filter((e=>"_delete"in e)).map((e=>e._delete()))])}isComponentSet(){return this.component!=null}isInitialized(e=i){return this.instances.has(e)}getOptions(e=i){return this.instancesOptions.get(e)||{}}initialize(e={}){const{options:t={}}=e;const n=this.normalizeInstanceIdentifier(e.instanceIdentifier);if(this.isInitialized(n)){throw Error(`${this.name}(${n}) has already been initialized`)}if(!this.isComponentSet()){throw Error(`Component ${this.name} has not been registered yet`)}const r=this.getOrInitializeService({instanceIdentifier:n,options:t});for(const[e,t]of this.instancesDeferred.entries()){const i=this.normalizeInstanceIdentifier(e);if(n===i){t.resolve(r)}}return r}onInit(e,t){const n=this.normalizeInstanceIdentifier(t);const r=this.onInitCallbacks.get(n)??new Set;r.add(e);this.onInitCallbacks.set(n,r);const i=this.instances.get(n);if(i){e(i,n)}return()=>{r.delete(e)}}invokeOnInitCallbacks(e,t){const n=this.onInitCallbacks.get(t);if(!n){return}for(const r of n){try{r(e,t)}catch{}}}getOrInitializeService({instanceIdentifier:e,options:t={}}){let n=this.instances.get(e);if(!n&&this.component){n=this.component.instanceFactory(this.container,{instanceIdentifier:normalizeIdentifierForFactory(e),options:t});this.instances.set(e,n);this.instancesOptions.set(e,t);this.invokeOnInitCallbacks(n,e);if(this.component.onInstanceCreated){try{this.component.onInstanceCreated(this.container,e,n)}catch{}}}return n||null}normalizeInstanceIdentifier(e=i){if(this.component){return this.component.multipleInstances?e:i}else{return e}}shouldAutoInitialize(){return!!this.component&&this.component.instantiationMode!=="EXPLICIT"}}function normalizeIdentifierForFactory(e){return e===i?undefined:e}function isComponentEager(e){return e.instantiationMode==="EAGER"}
2class ComponentContainer{constructor(e){this.name=e;this.providers=new Map}addComponent(e){const t=this.getProvider(e.name);if(t.isComponentSet()){throw new Error(`Component ${e.name} has already been registered with ${this.name}`)}t.setComponent(e)}addOrOverwriteComponent(e){const t=this.getProvider(e.name);if(t.isComponentSet()){this.providers.delete(e.name)}this.addComponent(e)}getProvider(e){if(this.providers.has(e)){return this.providers.get(e)}const t=new Provider(e,this);this.providers.set(e,t);return t}getProviders(){return Array.from(this.providers.values())}}t.Component=Component;t.ComponentContainer=ComponentContainer;t.Provider=Provider},84273(e,t,n){var r=n(37207);var i=n(95282);var s=n(584);var o=n(36183);var a=n(40767);function _interopDefaultLegacy(e){return e&&typeof e==="object"&&"default"in e?e:{default:e}}var c=_interopDefaultLegacy(r);const l="@firebase/database-compat";const u="2.1.4";const d=new a.Logger("@firebase/database-compat");const warn=function(e){const t="FIREBASE WARNING: "+e;d.warn(t)};const validateBoolean=function(e,t,n,r){if(r&&n===undefined){return}if(typeof n!=="boolean"){throw new Error(o.errorPrefix(e,t)+"must be a boolean.")}};const validateEventType=function(e,t,n){if(n&&t===undefined){return}switch(t){case"value":case"child_added":case"child_removed":case"child_changed":case"child_moved":break;default:throw new Error(o.errorPrefix(e,"eventType")+'must be a valid event type = "value", "child_added", "child_removed", '+'"child_changed", or "child_moved".')}};class OnDisconnect{constructor(e){this._delegate=e}cancel(e){o.validateArgCount("OnDisconnect.cancel",0,1,arguments.length);o.validateCallback("OnDisconnect.cancel","onComplete",e,true);const t=this._delegate.cancel();if(e){t.then((()=>e(null)),(t=>e(t)))}return t}remove(e){o.validateArgCount("OnDisconnect.remove",0,1,arguments.length);o.validateCallback("OnDisconnect.remove","onComplete",e,true);const t=this._delegate.remove();if(e){t.then((()=>e(null)),(t=>e(t)))}return t}set(e,t){o.validateArgCount("OnDisconnect.set",1,2,arguments.length);o.validateCallback("OnDisconnect.set","onComplete",t,true);const n=this._delegate.set(e);if(t){n.then((()=>t(null)),(e=>t(e)))}return n}setWithPriority(e,t,n){o.validateArgCount("OnDisconnect.setWithPriority",2,3,arguments.length);o.validateCallback("OnDisconnect.setWithPriority","onComplete",n,true);const r=this._delegate.setWithPriority(e,t);if(n){r.then((()=>n(null)),(e=>n(e)))}return r}update(e,t){o.validateArgCount("OnDisconnect.update",1,2,arguments.length);if(Array.isArray(e)){const t={};for(let n=0;n<e.length;++n){t[""+n]=e[n]}e=t;warn("Passing an Array to firebase.database.onDisconnect().update() is deprecated. Use set() if you want to overwrite the "+"existing data, or an Object with integer keys if you really do want to only update some of the children.")}o.validateCallback("OnDisconnect.update","onComplete",t,true);const n=this._delegate.update(e);if(t){n.then((()=>t(null)),(e=>t(e)))}return n}}class TransactionResult{constructor(e,t){this.committed=e;this.snapshot=t}toJSON(){o.validateArgCount("TransactionResult.toJSON",0,1,arguments.length);return{committed:this.committed,snapshot:this.snapshot.toJSON()}}}class DataSnapshot{constructor(e,t){this._database=e;this._delegate=t}val(){o.validateArgCount("DataSnapshot.val",0,0,arguments.length);return this._delegate.val()}exportVal(){o.validateArgCount("DataSnapshot.exportVal",0,0,arguments.length);return this._delegate.exportVal()}toJSON(){o.validateArgCount("DataSnapshot.toJSON",0,1,arguments.length);return this._delegate.toJSON()}exists(){o.validateArgCount("DataSnapshot.exists",0,0,arguments.length);return this._delegate.exists()}child(e){o.validateArgCount("DataSnapshot.child",0,1,arguments.length);e=String(e);s._validatePathString("DataSnapshot.child","path",e,false);return new DataSnapshot(this._database,this._delegate.child(e))}hasChild(e){o.validateArgCount("DataSnapshot.hasChild",1,1,arguments.length);s._validatePathString("DataSnapshot.hasChild","path",e,false);return this._delegate.hasChild(e)}getPriority(){o.validateArgCount("DataSnapshot.getPriority",0,0,arguments.length);return this._delegate.priority}forEach(e){o.validateArgCount("DataSnapshot.forEach",1,1,arguments.length);o.validateCallback("DataSnapshot.forEach","action",e,false);return this._delegate.forEach((t=>e(new DataSnapshot(this._database,t))))}hasChildren(){o.validateArgCount("DataSnapshot.hasChildren",0,0,arguments.length);return this._delegate.hasChildren()}get key(){return this._delegate.key}numChildren(){o.validateArgCount("DataSnapshot.numChildren",0,0,arguments.length);return this._delegate.size}getRef(){o.validateArgCount("DataSnapshot.ref",0,0,arguments.length);return new Reference(this._database,this._delegate.ref)}get ref(){return this.getRef()}}class Query{constructor(e,t){this.database=e;this._delegate=t}on(e,t,n,r){o.validateArgCount("Query.on",2,4,arguments.length);o.validateCallback("Query.on","callback",t,false);const i=Query.getCancelAndContextArgs_("Query.on",n,r);const valueCallback=(e,n)=>{t.call(i.context,new DataSnapshot(this.database,e),n)};valueCallback.userCallback=t;valueCallback.context=i.context;const a=i.cancel?.bind(i.context);switch(e){case"value":s.onValue(this._delegate,valueCallback,a);return t;case"child_added":s.onChildAdded(this._delegate,valueCallback,a);return t;case"child_removed":s.onChildRemoved(this._delegate,valueCallback,a);return t;case"child_changed":s.onChildChanged(this._delegate,valueCallback,a);return t;case"child_moved":s.onChildMoved(this._delegate,valueCallback,a);return t;default:throw new Error(o.errorPrefix("Query.on","eventType")+'must be a valid event type = "value", "child_added", "child_removed", '+'"child_changed", or "child_moved".')}}off(e,t,n){o.validateArgCount("Query.off",0,3,arguments.length);validateEventType("Query.off",e,true);o.validateCallback("Query.off","callback",t,true);o.validateContextObject("Query.off","context",n,true);if(t){const valueCallback=()=>{};valueCallback.userCallback=t;valueCallback.context=n;s.off(this._delegate,e,valueCallback)}else{s.off(this._delegate,e)}}get(){return s.get(this._delegate).then((e=>new DataSnapshot(this.database,e)))}once(e,t,n,r){o.validateArgCount("Query.once",1,4,arguments.length);o.validateCallback("Query.once","callback",t,true);const i=Query.getCancelAndContextArgs_("Query.once",n,r);const a=new o.Deferred;const valueCallback=(e,n)=>{const r=new DataSnapshot(this.database,e);if(t){t.call(i.context,r,n)}a.resolve(r)};valueCallback.userCallback=t;valueCallback.context=i.context;const cancelCallback=e=>{if(i.cancel){i.cancel.call(i.context,e)}a.reject(e)};switch(e){case"value":s.onValue(this._delegate,valueCallback,cancelCallback,{onlyOnce:true});break;case"child_added":s.onChildAdded(this._delegate,valueCallback,cancelCallback,{onlyOnce:true});break;case"child_removed":s.onChildRemoved(this._delegate,valueCallback,cancelCallback,{onlyOnce:true});break;case"child_changed":s.onChildChanged(this._delegate,valueCallback,cancelCallback,{onlyOnce:true});break;case"child_moved":s.onChildMoved(this._delegate,valueCallback,cancelCallback,{onlyOnce:true});break;default:throw new Error(o.errorPrefix("Query.once","eventType")+'must be a valid event type = "value", "child_added", "child_removed", '+'"child_changed", or "child_moved".')}return a.promise}limitToFirst(e){o.validateArgCount("Query.limitToFirst",1,1,arguments.length);return new Query(this.database,s.query(this._delegate,s.limitToFirst(e)))}limitToLast(e){o.validateArgCount("Query.limitToLast",1,1,arguments.length);return new Query(this.database,s.query(this._delegate,s.limitToLast(e)))}orderByChild(e){o.validateArgCount("Query.orderByChild",1,1,arguments.length);return new Query(this.database,s.query(this._delegate,s.orderByChild(e)))}orderByKey(){o.validateArgCount("Query.orderByKey",0,0,arguments.length);return new Query(this.database,s.query(this._delegate,s.orderByKey()))}orderByPriority(){o.validateArgCount("Query.orderByPriority",0,0,arguments.length);return new Query(this.database,s.query(this._delegate,s.orderByPriority()))}orderByValue(){o.validateArgCount("Query.orderByValue",0,0,arguments.length);return new Query(this.database,s.query(this._delegate,s.orderByValue()))}startAt(e=null,t){o.validateArgCount("Query.startAt",0,2,arguments.length);return new Query(this.database,s.query(this._delegate,s.startAt(e,t)))}startAfter(e=null,t){o.validateArgCount("Query.startAfter",0,2,arguments.length);return new Query(this.database,s.query(this._delegate,s.startAfter(e,t)))}endAt(e=null,t){o.validateArgCount("Query.endAt",0,2,arguments.length);return new Query(this.database,s.query(this._delegate,s.endAt(e,t)))}endBefore(e=null,t){o.validateArgCount("Query.endBefore",0,2,arguments.length);return new Query(this.database,s.query(this._delegate,s.endBefore(e,t)))}equalTo(e,t){o.validateArgCount("Query.equalTo",1,2,arguments.length);return new Query(this.database,s.query(this._delegate,s.equalTo(e,t)))}toString(){o.validateArgCount("Query.toString",0,0,arguments.length);return this._delegate.toString()}toJSON(){o.validateArgCount("Query.toJSON",0,1,arguments.length);return this._delegate.toJSON()}isEqual(e){o.validateArgCount("Query.isEqual",1,1,arguments.length);if(!(e instanceof Query)){const e="Query.isEqual failed: First argument must be an instance of firebase.database.Query.";throw new Error(e)}return this._delegate.isEqual(e._delegate)}static getCancelAndContextArgs_(e,t,n){const r={cancel:undefined,context:undefined};if(t&&n){r.cancel=t;o.validateCallback(e,"cancel",r.cancel,true);r.context=n;o.validateContextObject(e,"context",r.context,true)}else if(t){if(typeof t==="object"&&t!==null){r.context=t}else if(typeof t==="function"){r.cancel=t}else{throw new Error(o.errorPrefix(e,"cancelOrContext")+" must either be a cancel callback or a context object.")}}return r}get ref(){return new Reference(this.database,new s._ReferenceImpl(this._delegate._repo,this._delegate._path))}}class Reference extends Query{constructor(e,t){super(e,new s._QueryImpl(t._repo,t._path,new s._QueryParams,false));this.database=e;this._delegate=t}getKey(){o.validateArgCount("Reference.key",0,0,arguments.length);return this._delegate.key}child(e){o.validateArgCount("Reference.child",1,1,arguments.length);if(typeof e==="number"){e=String(e)}return new Reference(this.database,s.child(this._delegate,e))}getParent(){o.validateArgCount("Reference.parent",0,0,arguments.length);const e=this._delegate.parent;return e?new Reference(this.database,e):null}getRoot(){o.validateArgCount("Reference.root",0,0,arguments.length);return new Reference(this.database,this._delegate.root)}set(e,t){o.validateArgCount("Reference.set",1,2,arguments.length);o.validateCallback("Reference.set","onComplete",t,true);const n=s.set(this._delegate,e);if(t){n.then((()=>t(null)),(e=>t(e)))}return n}update(e,t){o.validateArgCount("Reference.update",1,2,arguments.length);if(Array.isArray(e)){const t={};for(let n=0;n<e.length;++n){t[""+n]=e[n]}e=t;
2warn("Passing an Array to Firebase.update() is deprecated. "+"Use set() if you want to overwrite the existing data, or "+"an Object with integer keys if you really do want to "+"only update some of the children.")}s._validateWritablePath("Reference.update",this._delegate._path);o.validateCallback("Reference.update","onComplete",t,true);const n=s.update(this._delegate,e);if(t){n.then((()=>t(null)),(e=>t(e)))}return n}setWithPriority(e,t,n){o.validateArgCount("Reference.setWithPriority",2,3,arguments.length);o.validateCallback("Reference.setWithPriority","onComplete",n,true);const r=s.setWithPriority(this._delegate,e,t);if(n){r.then((()=>n(null)),(e=>n(e)))}return r}remove(e){o.validateArgCount("Reference.remove",0,1,arguments.length);o.validateCallback("Reference.remove","onComplete",e,true);const t=s.remove(this._delegate);if(e){t.then((()=>e(null)),(t=>e(t)))}return t}transaction(e,t,n){o.validateArgCount("Reference.transaction",1,3,arguments.length);o.validateCallback("Reference.transaction","transactionUpdate",e,false);o.validateCallback("Reference.transaction","onComplete",t,true);validateBoolean("Reference.transaction","applyLocally",n,true);const r=s.runTransaction(this._delegate,e,{applyLocally:n}).then((e=>new TransactionResult(e.committed,new DataSnapshot(this.database,e.snapshot))));if(t){r.then((e=>t(null,e.committed,e.snapshot)),(e=>t(e,false,null)))}return r}setPriority(e,t){o.validateArgCount("Reference.setPriority",1,2,arguments.length);o.validateCallback("Reference.setPriority","onComplete",t,true);const n=s.setPriority(this._delegate,e);if(t){n.then((()=>t(null)),(e=>t(e)))}return n}push(e,t){o.validateArgCount("Reference.push",0,2,arguments.length);o.validateCallback("Reference.push","onComplete",t,true);const n=s.push(this._delegate,e);const r=n.then((e=>new Reference(this.database,e)));if(t){r.then((()=>t(null)),(e=>t(e)))}const i=new Reference(this.database,n);i.then=r.then.bind(r);i.catch=r.catch.bind(r,undefined);return i}onDisconnect(){s._validateWritablePath("Reference.onDisconnect",this._delegate._path);return new OnDisconnect(new s.OnDisconnect(this._delegate._repo,this._delegate._path))}get key(){return this.getKey()}get parent(){return this.getParent()}get root(){return this.getRoot()}}class Database{constructor(e,t){this._delegate=e;this.app=t;this.INTERNAL={delete:()=>this._delegate._delete(),forceWebSockets:s.forceWebSockets,forceLongPolling:s.forceLongPolling}}useEmulator(e,t,n={}){s.connectDatabaseEmulator(this._delegate,e,t,n)}ref(e){o.validateArgCount("database.ref",0,1,arguments.length);if(e instanceof Reference){const t=s.refFromURL(this._delegate,e.toString());return new Reference(this,t)}else{const t=s.ref(this._delegate,e);return new Reference(this,t)}}refFromURL(e){const t="database.refFromURL";o.validateArgCount(t,1,1,arguments.length);const n=s.refFromURL(this._delegate,e);return new Reference(this,n)}goOffline(){o.validateArgCount("database.goOffline",0,0,arguments.length);return s.goOffline(this._delegate)}goOnline(){o.validateArgCount("database.goOnline",0,0,arguments.length);return s.goOnline(this._delegate)}}Database.ServerValue={TIMESTAMP:s.serverTimestamp(),increment:e=>s.increment(e)};function initStandalone({app:e,url:t,version:n,customAuthImpl:r,customAppCheckImpl:o,namespace:a,nodeAdmin:c=false}){s._setSDKVersion(n);const l=new i.ComponentContainer("database-standalone");const u=new i.Provider("auth-internal",l);u.setComponent(new i.Component("auth-internal",(()=>r),"PRIVATE"));let d=undefined;if(o){d=new i.Provider("app-check-internal",l);d.setComponent(new i.Component("app-check-internal",(()=>o),"PRIVATE"))}return{instance:new Database(s._repoManagerDatabaseFromApp(e,u,d,t,c),e),namespace:a}}var h=Object.freeze({__proto__:null,initStandalone});const p=Database.ServerValue;function registerDatabase(e){e.INTERNAL.registerComponent(new i.Component("database-compat",((e,{instanceIdentifier:t})=>{const n=e.getProvider("app-compat").getImmediate();const r=e.getProvider("database").getImmediate({identifier:t});return new Database(r,n)}),"PUBLIC").setServiceProps({Reference,Query,Database,DataSnapshot,enableLogging:s.enableLogging,INTERNAL:h,ServerValue:p}).setMultipleInstances(true));
2e.registerVersion(l,u,"node")}registerDatabase(c["default"])},584(e,t,n){var r=n(8237);Object.defineProperty(t,"__esModule",{value:true});var i=n(50218);var s=n(95282);var o=n(36183);var a=n(40767);const c="@firebase/database";const l="1.1.3";let u="";function setSDKVersion(e){u=e}class DOMStorageWrapper{constructor(e){this.domStorage_=e;this.prefix_="firebase:"}set(e,t){if(t==null){this.domStorage_.removeItem(this.prefixedName_(e))}else{this.domStorage_.setItem(this.prefixedName_(e),o.stringify(t))}}get(e){const t=this.domStorage_.getItem(this.prefixedName_(e));if(t==null){return null}else{return o.jsonEval(t)}}remove(e){this.domStorage_.removeItem(this.prefixedName_(e))}prefixedName_(e){return this.prefix_+e}toString(){return this.domStorage_.toString()}}class MemoryStorage{constructor(){this.cache_={};this.isInMemoryStorage=true}set(e,t){if(t==null){delete this.cache_[e]}else{this.cache_[e]=t}}get(e){if(o.contains(this.cache_,e)){return this.cache_[e]}return null}remove(e){delete this.cache_[e]}}const createStoragefor=function(e){try{if(typeof window!=="undefined"&&typeof window[e]!=="undefined"){const t=window[e];t.setItem("firebase:sentinel","cache");t.removeItem("firebase:sentinel");return new DOMStorageWrapper(t)}}catch(e){}return new MemoryStorage};const d=createStoragefor("localStorage");const h=createStoragefor("sessionStorage");const p=new a.Logger("@firebase/database");const f=function(){let e=1;return function(){return e++}}();const sha1=function(e){const t=o.stringToByteArray(e);const n=new o.Sha1;n.update(t);const r=n.digest();return o.base64.encodeByteArray(r)};const buildLogMessage_=function(...e){let t="";for(let n=0;n<e.length;n++){const r=e[n];if(Array.isArray(r)||r&&typeof r==="object"&&typeof r.length==="number"){t+=buildLogMessage_.apply(null,r)}else if(typeof r==="object"){t+=o.stringify(r)}else{t+=r}t+=" "}return t};let m=null;let g=true;const enableLogging$1=function(e,t){o.assert(!t||e===true||e===false,"Can't turn on custom loggers persistently.");if(e===true){p.logLevel=a.LogLevel.VERBOSE;m=p.log.bind(p);if(t){h.set("logging_enabled",true)}}else if(typeof e==="function"){m=e}else{m=null;h.remove("logging_enabled")}};const log=function(...e){if(g===true){g=false;if(m===null&&h.get("logging_enabled")===true){enableLogging$1(true)}}if(m){const t=buildLogMessage_.apply(null,e);m(t)}};const logWrapper=function(e){return function(...t){log(e,...t)}};const error=function(...e){const t="FIREBASE INTERNAL ERROR: "+buildLogMessage_(...e);p.error(t)};const fatal=function(...e){const t=`FIREBASE FATAL ERROR: ${buildLogMessage_(...e)}`;p.error(t);throw new Error(t)};const warn=function(...e){const t="FIREBASE WARNING: "+buildLogMessage_(...e);p.warn(t)};const warnIfPageIsSecure=function(){if(typeof window!=="undefined"&&window.location&&window.location.protocol&&window.location.protocol.indexOf("https:")!==-1){warn("Insecure Firebase access from a secure page. "+"Please use https in calls to new Firebase().")}};const isInvalidJSONNumber=function(e){return typeof e==="number"&&(e!==e||e===Number.POSITIVE_INFINITY||e===Number.NEGATIVE_INFINITY)};const executeWhenDOMReady=function(e){if(o.isNodeSdk()||document.readyState==="complete"){e()}else{let t=false;const wrappedFn=function(){if(!document.body){setTimeout(wrappedFn,Math.floor(10));return}if(!t){t=true;e()}};if(document.addEventListener){document.addEventListener("DOMContentLoaded",wrappedFn,false);window.addEventListener("load",wrappedFn,false)}else if(document.attachEvent){document.attachEvent("onreadystatechange",(()=>{if(document.readyState==="complete"){wrappedFn()}}));window.attachEvent("onload",wrappedFn)}}};const _="[MIN_NAME]";const v="[MAX_NAME]";const nameCompare=function(e,t){if(e===t){return 0}else if(e===_||t===v){return-1}else if(t===_||e===v){return 1}else{const n=tryParseInt(e),r=tryParseInt(t);if(n!==null){if(r!==null){return n-r===0?e.length-t.length:n-r}else{return-1}}else if(r!==null){return 1}else{return e<t?-1:1}}};const stringCompare=function(e,t){if(e===t){return 0}else if(e<t){return-1}else{return 1}};const requireKey=function(e,t){if(t&&e in t){return t[e]}else{throw new Error("Missing required key ("+e+") in object: "+o.stringify(t))}};
2const ObjectToUniqueKey=function(e){if(typeof e!=="object"||e===null){return o.stringify(e)}const t=[];for(const n in e){t.push(n)}t.sort();let n="{";for(let r=0;r<t.length;r++){if(r!==0){n+=","}n+=o.stringify(t[r]);n+=":";n+=ObjectToUniqueKey(e[t[r]])}n+="}";return n};const splitStringBySize=function(e,t){const n=e.length;if(n<=t){return[e]}const r=[];for(let i=0;i<n;i+=t){if(i+t>n){r.push(e.substring(i,n))}else{r.push(e.substring(i,i+t))}}return r};function each(e,t){for(const n in e){if(e.hasOwnProperty(n)){t(n,e[n])}}}const doubleToIEEE754String=function(e){o.assert(!isInvalidJSONNumber(e),"Invalid JSON number");const t=11,n=52;const r=(1<<t-1)-1;let i,s,a,c,l;if(e===0){s=0;a=0;i=1/e===-Infinity?1:0}else{i=e<0;e=Math.abs(e);if(e>=Math.pow(2,1-r)){c=Math.min(Math.floor(Math.log(e)/Math.LN2),r);s=c+r;a=Math.round(e*Math.pow(2,n-c)-Math.pow(2,n))}else{s=0;a=Math.round(e/Math.pow(2,1-r-n))}}const u=[];for(l=n;l;l-=1){u.push(a%2?1:0);a=Math.floor(a/2)}for(l=t;l;l-=1){u.push(s%2?1:0);s=Math.floor(s/2)}u.push(i?1:0);u.reverse();const d=u.join("");let h="";for(l=0;l<64;l+=8){let e=parseInt(d.substr(l,8),2).toString(16);if(e.length===1){e="0"+e}h=h+e}return h.toLowerCase()};const isChromeExtensionContentScript=function(){return!!(typeof window==="object"&&window["chrome"]&&window["chrome"]["extension"]&&!/^chrome/.test(window.location.href))};const isWindowsStoreApp=function(){return typeof Windows==="object"&&typeof Windows.UI==="object"};function errorForServerCode(e,t){let n="Unknown Error";if(e==="too_big"){n="The data requested exceeds the maximum size "+"that can be accessed with a single request."}else if(e==="permission_denied"){n="Client doesn't have permission to access the desired data."}else if(e==="unavailable"){n="The service is unavailable"}const r=new Error(e+" at "+t._path.toString()+": "+n);r.code=e.toUpperCase();return r}const y=new RegExp("^-?(0*)\\d{1,10}$");const I=-2147483648;const C=2147483647;const tryParseInt=function(e){if(y.test(e)){const t=Number(e);if(t>=I&&t<=C){return t}}return null};const exceptionGuard=function(e){try{e()}catch(e){setTimeout((()=>{const t=e.stack||"";warn("Exception was thrown by user callback.",t);throw e}),Math.floor(0))}};const beingCrawled=function(){const e=typeof window==="object"&&window["navigator"]&&window["navigator"]["userAgent"]||"";return e.search(/googlebot|google webmaster tools|bingbot|yahoo! slurp|baiduspider|yandexbot|duckduckbot/i)>=0};const setTimeoutNonBlocking=function(e,t){const n=setTimeout(e,t);if(typeof n==="number"&&typeof Deno!=="undefined"&&Deno["unrefTimer"]){Deno.unrefTimer(n)}else if(typeof n==="object"&&n["unref"]){n["unref"]()}return n};class AppCheckTokenProvider{constructor(e,t){this.appCheckProvider=t;this.appName=e.name;if(i._isFirebaseServerApp(e)&&e.settings.appCheckToken){this.serverAppAppCheckToken=e.settings.appCheckToken}this.appCheck=t?.getImmediate({optional:true});if(!this.appCheck){t?.get().then((e=>this.appCheck=e))}}getToken(e){if(this.serverAppAppCheckToken){if(e){throw new Error("Attempted reuse of `FirebaseServerApp.appCheckToken` after previous usage failed.")}return Promise.resolve({token:this.serverAppAppCheckToken})}if(!this.appCheck){return new Promise(((t,n)=>{setTimeout((()=>{if(this.appCheck){this.getToken(e).then(t,n)}else{t(null)}}),0)}))}return this.appCheck.getToken(e)}addTokenChangeListener(e){this.appCheckProvider?.get().then((t=>t.addTokenListener(e)))}notifyForInvalidToken(){warn(`Provided AppCheck credentials for the app named "${this.appName}" `+"are invalid. This usually indicates your app was not initialized correctly.")}}class FirebaseAuthTokenProvider{constructor(e,t,n){this.appName_=e;this.firebaseOptions_=t;this.authProvider_=n;this.auth_=null;this.auth_=n.getImmediate({optional:true});if(!this.auth_){n.onInit((e=>this.auth_=e))}}getToken(e){if(!this.auth_){return new Promise(((t,n)=>{setTimeout((()=>{if(this.auth_){this.getToken(e).then(t,n)}else{t(null)}}),0)}))}return this.auth_.getToken(e).catch((e=>{if(e&&e.code==="auth/token-not-initialized"){log("Got auth/token-not-initialized error.  Treating as null token.");return null}else{return Promise.reject(e)}}))}addTokenChangeListener(e){if(this.auth_){this.auth_.addAuthTokenListener(e)}else{this.authProvider_.get().then((t=>t.addAuthTokenListener(e)))}}removeTokenChangeListener(e){this.authProvider_.get().then((t=>t.removeAuthTokenListener(e)))}notifyForInvalidToken(){let e='Provided authentication credentials for the app named "'+this.appName_+'" are invalid. This usually indicates your app was not '+"initialized correctly. ";if("credential"in this.firebaseOptions_){e+='Make sure the "credential" property provided to initializeApp() '+'is authorized to access the specified "databaseURL" and is from the correct '+"project."}else if("serviceAccount"in this.firebaseOptions_){e+='Make sure the "serviceAccount" property provided to initializeApp() '+'is authorized to access the specified "databaseURL" and is from the correct '+"project."}else{e+='Make sure the "apiKey" and "databaseURL" properties provided to '+"initializeApp() match the values provided for your app at "+"https://console.firebase.google.com/."}warn(e)}}class EmulatorTokenProvider{constructor(e){this.accessToken=e}getToken(e){return Promise.resolve({accessToken:this.accessToken})}addTokenChangeListener(e){e(this.accessToken)}removeTokenChangeListener(e){}notifyForInvalidToken(){}}EmulatorTokenProvider.OWNER="owner";const w="5";const E="v";const T="s";const P="r";const A="f";const S=/(console\.firebase|firebase-console-\w+\.corp|firebase\.corp)\.google\.com/;const b="ls";const R="p";
2const k="ac";const N="websocket";const O="long_polling";class RepoInfo{constructor(e,t,n,r,i=false,s="",o=false,a=false,c=null){this.secure=t;this.namespace=n;this.webSocketOnly=r;this.nodeAdmin=i;this.persistenceKey=s;this.includeNamespaceInQueryParams=o;this.isUsingEmulator=a;this.emulatorOptions=c;this._host=e.toLowerCase();this._domain=this._host.substr(this._host.indexOf(".")+1);this.internalHost=d.get("host:"+e)||this._host}isCacheableHost(){return this.internalHost.substr(0,2)==="s-"}isCustomHost(){return this._domain!=="firebaseio.com"&&this._domain!=="firebaseio-demo.com"}get host(){return this._host}set host(e){if(e!==this.internalHost){this.internalHost=e;if(this.isCacheableHost()){d.set("host:"+this._host,this.internalHost)}}}toString(){let e=this.toURLString();if(this.persistenceKey){e+="<"+this.persistenceKey+">"}return e}toURLString(){const e=this.secure?"https://":"http://";const t=this.includeNamespaceInQueryParams?`?ns=${this.namespace}`:"";return`${e}${this.host}/${t}`}}function repoInfoNeedsQueryParam(e){return e.host!==e.internalHost||e.isCustomHost()||e.includeNamespaceInQueryParams}function repoInfoConnectionURL(e,t,n){o.assert(typeof t==="string","typeof type must == string");o.assert(typeof n==="object","typeof params must == object");let r;if(t===N){r=(e.secure?"wss://":"ws://")+e.internalHost+"/.ws?"}else if(t===O){r=(e.secure?"https://":"http://")+e.internalHost+"/.lp?"}else{throw new Error("Unknown connection type: "+t)}if(repoInfoNeedsQueryParam(e)){n["ns"]=e.namespace}const i=[];each(n,((e,t)=>{i.push(e+"="+t)}));return r+i.join("&")}class StatsCollection{constructor(){this.counters_={}}incrementCounter(e,t=1){if(!o.contains(this.counters_,e)){this.counters_[e]=0}this.counters_[e]+=t}get(){return o.deepCopy(this.counters_)}}const D={};const L={};function statsManagerGetCollection(e){const t=e.toString();if(!D[t]){D[t]=new StatsCollection}return D[t]}function statsManagerGetOrCreateReporter(e,t){const n=e.toString();if(!L[n]){L[n]=t()}return L[n]}class PacketReceiver{constructor(e){this.onMessage_=e;this.pendingResponses=[];this.currentResponseNum=0;this.closeAfterResponse=-1;this.onClose=null}closeAfter(e,t){this.closeAfterResponse=e;this.onClose=t;if(this.closeAfterResponse<this.currentResponseNum){this.onClose();this.onClose=null}}handleResponse(e,t){this.pendingResponses[e]=t;while(this.pendingResponses[this.currentResponseNum]){const e=this.pendingResponses[this.currentResponseNum];delete this.pendingResponses[this.currentResponseNum];for(let t=0;t<e.length;++t){if(e[t]){exceptionGuard((()=>{this.onMessage_(e[t])}))}}if(this.currentResponseNum===this.closeAfterResponse){if(this.onClose){this.onClose();this.onClose=null}break}this.currentResponseNum++}}}const M="start";const F="close";const U="pLPCommand";const x="pRTLPCB";const W="id";const V="pw";const q="ser";const G="cb";const B="seg";const H="ts";const j="d";const z="dframe";const K=1870;const $=30;const Q=K-$;const Y=25e3;const J=3e4;class BrowserPollConnection{constructor(e,t,n,r,i,s,o){this.connId=e;this.repoInfo=t;this.applicationId=n;this.appCheckToken=r;this.authToken=i;this.transportSessionId=s;this.lastSessionId=o;this.bytesSent=0;this.bytesReceived=0;this.everConnected_=false;this.log_=logWrapper(e);this.stats_=statsManagerGetCollection(t);this.urlFn=e=>{if(this.appCheckToken){e[k]=this.appCheckToken}return repoInfoConnectionURL(t,O,e)}}open(e,t){this.curSegmentNum=0;this.onDisconnect_=t;this.myPacketOrderer=new PacketReceiver(e);this.isClosed_=false;this.connectTimeoutTimer_=setTimeout((()=>{this.log_("Timed out trying to connect.");this.onClosed_();this.connectTimeoutTimer_=null}),Math.floor(J));executeWhenDOMReady((()=>{if(this.isClosed_){return}this.scriptTagHolder=new FirebaseIFrameScriptHolder(((...e)=>{const[t,n,r,i,s]=e;this.incrementIncomingBytes_(e);if(!this.scriptTagHolder){return}if(this.connectTimeoutTimer_){clearTimeout(this.connectTimeoutTimer_);this.connectTimeoutTimer_=null}this.everConnected_=true;if(t===M){this.id=n;this.password=r}else if(t===F){if(n){this.scriptTagHolder.sendNewPolls=false;this.myPacketOrderer.closeAfter(n,(()=>{this.onClosed_()}))}else{this.onClosed_()}}else{throw new Error("Unrecognized command received: "+t)}}),((...e)=>{const[t,n]=e;this.incrementIncomingBytes_(e);this.myPacketOrderer.handleResponse(t,n)}),(()=>{this.onClosed_()}),this.urlFn);const e={};e[M]="t";e[q]=Math.floor(Math.random()*1e8);if(this.scriptTagHolder.uniqueCallbackIdentifier){e[G]=this.scriptTagHolder.uniqueCallbackIdentifier}e[E]=w;if(this.transportSessionId){e[T]=this.transportSessionId}if(this.lastSessionId){e[b]=this.lastSessionId}if(this.applicationId){e[R]=this.applicationId}if(this.appCheckToken){e[k]=this.appCheckToken}if(typeof location!=="undefined"&&location.hostname&&S.test(location.hostname)){e[P]=A}const t=this.urlFn(e);this.log_("Connecting via long-poll to "+t);this.scriptTagHolder.addTag(t,(()=>{}))}))}start(){this.scriptTagHolder.startLongPoll(this.id,this.password);this.addDisconnectPingFrame(this.id,this.password)}static forceAllow(){BrowserPollConnection.forceAllow_=true}static forceDisallow(){BrowserPollConnection.forceDisallow_=true}static isAvailable(){if(o.isNodeSdk()){return false}else if(BrowserPollConnection.forceAllow_){return true}else{return!BrowserPollConnection.forceDisallow_&&typeof document!=="undefined"&&document.createElement!=null&&!isChromeExtensionContentScript()&&!isWindowsStoreApp()}}markConnectionHealthy(){}shutdown_(){this.isClosed_=true;if(this.scriptTagHolder){this.scriptTagHolder.close();this.scriptTagHolder=null}if(this.myDisconnFrame){document.body.removeChild(this.myDisconnFrame);this.myDisconnFrame=null}if(this.connectTimeoutTimer_){clearTimeout(this.connectTimeoutTimer_);this.connectTimeoutTimer_=null}}onClosed_(){if(!this.isClosed_){this.log_("Longpoll is closing itself");this.shutdown_();if(this.onDisconnect_){this.onDisconnect_(this.everConnected_);this.onDisconnect_=null}}}close(){if(!this.isClosed_){this.log_("Longpoll is being closed.");this.shutdown_()}}
2send(e){const t=o.stringify(e);this.bytesSent+=t.length;this.stats_.incrementCounter("bytes_sent",t.length);const n=o.base64Encode(t);const r=splitStringBySize(n,Q);for(let e=0;e<r.length;e++){this.scriptTagHolder.enqueueSegment(this.curSegmentNum,r.length,r[e]);this.curSegmentNum++}}addDisconnectPingFrame(e,t){if(o.isNodeSdk()){return}this.myDisconnFrame=document.createElement("iframe");const n={};n[z]="t";n[W]=e;n[V]=t;this.myDisconnFrame.src=this.urlFn(n);this.myDisconnFrame.style.display="none";document.body.appendChild(this.myDisconnFrame)}incrementIncomingBytes_(e){const t=o.stringify(e).length;this.bytesReceived+=t;this.stats_.incrementCounter("bytes_received",t)}}class FirebaseIFrameScriptHolder{constructor(e,t,n,r){this.onDisconnect=n;this.urlFn=r;this.outstandingRequests=new Set;this.pendingSegs=[];this.currentSerial=Math.floor(Math.random()*1e8);this.sendNewPolls=true;if(!o.isNodeSdk()){this.uniqueCallbackIdentifier=f();window[U+this.uniqueCallbackIdentifier]=e;window[x+this.uniqueCallbackIdentifier]=t;this.myIFrame=FirebaseIFrameScriptHolder.createIFrame_();let n="";if(this.myIFrame.src&&this.myIFrame.src.substr(0,"javascript:".length)==="javascript:"){const e=document.domain;n='<script>document.domain="'+e+'";<\/script>'}const r="<html><body>"+n+"</body></html>";try{this.myIFrame.doc.open();this.myIFrame.doc.write(r);this.myIFrame.doc.close()}catch(e){log("frame writing exception");if(e.stack){log(e.stack)}log(e)}}else{this.commandCB=e;this.onMessageCB=t}}static createIFrame_(){const e=document.createElement("iframe");e.style.display="none";if(document.body){document.body.appendChild(e);try{const t=e.contentWindow.document;if(!t){log("No IE domain setting required")}}catch(t){const n=document.domain;e.src="javascript:void((function(){document.open();document.domain='"+n+"';document.close();})())"}}else{throw"Document body has not initialized. Wait to initialize Firebase until after the document is ready."}if(e.contentDocument){e.doc=e.contentDocument}else if(e.contentWindow){e.doc=e.contentWindow.document}else if(e.document){e.doc=e.document}return e}close(){this.alive=false;if(this.myIFrame){this.myIFrame.doc.body.textContent="";setTimeout((()=>{if(this.myIFrame!==null){document.body.removeChild(this.myIFrame);this.myIFrame=null}}),Math.floor(0))}const e=this.onDisconnect;if(e){this.onDisconnect=null;e()}}
2startLongPoll(e,t){this.myID=e;this.myPW=t;this.alive=true;while(this.newRequest_()){}}newRequest_(){if(this.alive&&this.sendNewPolls&&this.outstandingRequests.size<(this.pendingSegs.length>0?2:1)){this.currentSerial++;const e={};e[W]=this.myID;e[V]=this.myPW;e[q]=this.currentSerial;let t=this.urlFn(e);let n="";let r=0;while(this.pendingSegs.length>0){const e=this.pendingSegs[0];if(e.d.length+$+n.length<=K){const e=this.pendingSegs.shift();n=n+"&"+B+r+"="+e.seg+"&"+H+r+"="+e.ts+"&"+j+r+"="+e.d;r++}else{break}}t=t+n;this.addLongPollTag_(t,this.currentSerial);return true}else{return false}}enqueueSegment(e,t,n){this.pendingSegs.push({seg:e,ts:t,d:n});if(this.alive){this.newRequest_()}}addLongPollTag_(e,t){this.outstandingRequests.add(t);const doNewRequest=()=>{this.outstandingRequests.delete(t);this.newRequest_()};const n=setTimeout(doNewRequest,Math.floor(Y));const readyStateCB=()=>{clearTimeout(n);doNewRequest()};this.addTag(e,readyStateCB)}addTag(e,t){if(o.isNodeSdk()){this.doNodeLongPoll(e,t)}else{setTimeout((()=>{try{if(!this.sendNewPolls){return}const n=this.myIFrame.doc.createElement("script");n.type="text/javascript";n.async=true;n.src=e;n.onload=n.onreadystatechange=function(){const e=n.readyState;if(!e||e==="loaded"||e==="complete"){n.onload=n.onreadystatechange=null;if(n.parentNode){n.parentNode.removeChild(n)}t()}};n.onerror=()=>{log("Long-poll script failed to load: "+e);this.sendNewPolls=false;this.close()};this.myIFrame.doc.body.appendChild(n)}catch(e){}}),Math.floor(1))}}}const X=16384;const Z=45e3;let ee=null;if(typeof MozWebSocket!=="undefined"){ee=MozWebSocket}else if(typeof WebSocket!=="undefined"){ee=WebSocket}class WebSocketConnection{constructor(e,t,n,r,i,s,o){this.connId=e;this.applicationId=n;this.appCheckToken=r;this.authToken=i;this.keepaliveTimer=null;this.frames=null;this.totalFrames=0;this.bytesSent=0;this.bytesReceived=0;this.log_=logWrapper(this.connId);this.stats_=statsManagerGetCollection(t);this.connURL=WebSocketConnection.connectionURL_(t,s,o,r,n);this.nodeAdmin=t.nodeAdmin}static connectionURL_(e,t,n,r,i){const s={};s[E]=w;if(!o.isNodeSdk()&&typeof location!=="undefined"&&location.hostname&&S.test(location.hostname)){s[P]=A}if(t){s[T]=t}if(n){s[b]=n}if(r){s[k]=r}if(i){s[R]=i}return repoInfoConnectionURL(e,N,s)}open(e,t){this.onDisconnect=t;this.onMessage=e;this.log_("Websocket connecting to "+this.connURL);this.everConnected_=false;d.set("previous_websocket_failure",true);try{let e;if(o.isNodeSdk()){const t=this.nodeAdmin?"AdminNode":"Node";e={headers:{"User-Agent":`Firebase/${w}/${u}/${r.platform}/${t}`,"X-Firebase-GMPID":this.applicationId||""}};if(this.authToken){e.headers["Authorization"]=`Bearer ${this.authToken}`}if(this.appCheckToken){e.headers["X-Firebase-AppCheck"]=this.appCheckToken}const n=r["env"];const i=this.connURL.indexOf("wss://")===0?n["HTTPS_PROXY"]||n["https_proxy"]:n["HTTP_PROXY"]||n["http_proxy"];if(i){e["proxy"]={origin:i}}}this.mySock=new ee(this.connURL,[],e)}catch(e){this.log_("Error instantiating WebSocket.");const t=e.message||e.data;if(t){this.log_(t)}this.onClosed_();return}this.mySock.onopen=()=>{this.log_("Websocket connected.");this.everConnected_=true};this.mySock.onclose=()=>{this.log_("Websocket connection was disconnected.");this.mySock=null;this.onClosed_()};this.mySock.onmessage=e=>{this.handleIncomingFrame(e)};this.mySock.onerror=e=>{this.log_("WebSocket error.  Closing connection.");const t=e.message||e.data;if(t){this.log_(t)}this.onClosed_()}}start(){}static forceDisallow(){WebSocketConnection.forceDisallow_=true}static isAvailable(){let e=false;if(typeof navigator!=="undefined"&&navigator.userAgent){const t=/Android ([0-9]{0,}\.[0-9]{0,})/;const n=navigator.userAgent.match(t);if(n&&n.length>1){if(parseFloat(n[1])<4.4){e=true}}}return!e&&ee!==null&&!WebSocketConnection.forceDisallow_}static previouslyFailed(){return d.isInMemoryStorage||d.get("previous_websocket_failure")===true}markConnectionHealthy(){d.remove("previous_websocket_failure")}appendFrame_(e){this.frames.push(e);if(this.frames.length===this.totalFrames){const e=this.frames.join("");this.frames=null;const t=o.jsonEval(e);this.onMessage(t)}}handleNewFrameCount_(e){this.totalFrames=e;this.frames=[]}extractFrameCount_(e){o.assert(this.frames===null,"We already have a frame buffer");if(e.length<=6){const t=Number(e);if(!isNaN(t)){this.handleNewFrameCount_(t);return null}}this.handleNewFrameCount_(1);return e}handleIncomingFrame(e){if(this.mySock===null){return}const t=e["data"];this.bytesReceived+=t.length;this.stats_.incrementCounter("bytes_received",t.length);this.resetKeepAlive();if(this.frames!==null){this.appendFrame_(t)}else{const e=this.extractFrameCount_(t);if(e!==null){this.appendFrame_(e)}}}send(e){this.resetKeepAlive();
2const t=o.stringify(e);this.bytesSent+=t.length;this.stats_.incrementCounter("bytes_sent",t.length);const n=splitStringBySize(t,X);if(n.length>1){this.sendString_(String(n.length))}for(let e=0;e<n.length;e++){this.sendString_(n[e])}}shutdown_(){this.isClosed_=true;if(this.keepaliveTimer){clearInterval(this.keepaliveTimer);this.keepaliveTimer=null}if(this.mySock){this.mySock.close();this.mySock=null}}onClosed_(){if(!this.isClosed_){this.log_("WebSocket is closing itself");this.shutdown_();if(this.onDisconnect){this.onDisconnect(this.everConnected_);this.onDisconnect=null}}}close(){if(!this.isClosed_){this.log_("WebSocket is being closed");this.shutdown_()}}resetKeepAlive(){clearInterval(this.keepaliveTimer);this.keepaliveTimer=setInterval((()=>{if(this.mySock){this.sendString_("0")}this.resetKeepAlive()}),Math.floor(Z))}sendString_(e){try{this.mySock.send(e)}catch(e){this.log_("Exception thrown from WebSocket.send():",e.message||e.data,"Closing connection.");setTimeout(this.onClosed_.bind(this),0)}}}WebSocketConnection.responsesRequiredToBeHealthy=2;WebSocketConnection.healthyTimeout=3e4;class TransportManager{static get ALL_TRANSPORTS(){return[BrowserPollConnection,WebSocketConnection]}static get IS_TRANSPORT_INITIALIZED(){return this.globalTransportInitialized_}constructor(e){this.initTransports_(e)}initTransports_(e){const t=WebSocketConnection&&WebSocketConnection["isAvailable"]();let n=t&&!WebSocketConnection.previouslyFailed();if(e.webSocketOnly){if(!t){warn("wss:// URL used, but browser isn't known to support websockets.  Trying anyway.")}n=true}if(n){this.transports_=[WebSocketConnection]}else{const e=this.transports_=[];for(const t of TransportManager.ALL_TRANSPORTS){if(t&&t["isAvailable"]()){e.push(t)}}TransportManager.globalTransportInitialized_=true}}initialTransport(){if(this.transports_.length>0){return this.transports_[0]}else{throw new Error("No transports available")}}upgradeTransport(){if(this.transports_.length>1){return this.transports_[1]}else{return null}}}TransportManager.globalTransportInitialized_=false;const te=6e4;const ne=5e3;const re=10*1024;const ie=100*1024;const se="t";const oe="d";const ae="s";const ce="r";const le="e";const ue="o";const de="a";const he="n";const pe="p";const fe="h";class Connection{constructor(e,t,n,r,i,s,o,a,c,l){this.id=e;this.repoInfo_=t;this.applicationId_=n;this.appCheckToken_=r;this.authToken_=i;this.onMessage_=s;this.onReady_=o;this.onDisconnect_=a;this.onKill_=c;this.lastSessionId=l;this.connectionCount=0;this.pendingDataMessages=[];this.state_=0;this.log_=logWrapper("c:"+this.id+":");this.transportManager_=new TransportManager(t);this.log_("Connection created");this.start_()}start_(){const e=this.transportManager_.initialTransport();this.conn_=new e(this.nextTransportId_(),this.repoInfo_,this.applicationId_,this.appCheckToken_,this.authToken_,null,this.lastSessionId);this.primaryResponsesRequired_=e["responsesRequiredToBeHealthy"]||0;const t=this.connReceiver_(this.conn_);const n=this.disconnReceiver_(this.conn_);this.tx_=this.conn_;this.rx_=this.conn_;this.secondaryConn_=null;this.isHealthy_=false;setTimeout((()=>{this.conn_&&this.conn_.open(t,n)}),Math.floor(0));const r=e["healthyTimeout"]||0;if(r>0){this.healthyTimeout_=setTimeoutNonBlocking((()=>{this.healthyTimeout_=null;if(!this.isHealthy_){if(this.conn_&&this.conn_.bytesReceived>ie){this.log_("Connection exceeded healthy timeout but has received "+this.conn_.bytesReceived+" bytes.  Marking connection healthy.");this.isHealthy_=true;this.conn_.markConnectionHealthy()}else if(this.conn_&&this.conn_.bytesSent>re){this.log_("Connection exceeded healthy timeout but has sent "+this.conn_.bytesSent+" bytes.  Leaving connection alive.")}else{this.log_("Closing unhealthy connection after timeout.");this.close()}}}),Math.floor(r))}}nextTransportId_(){return"c:"+this.id+":"+this.connectionCount++}disconnReceiver_(e){return t=>{if(e===this.conn_){this.onConnectionLost_(t)}else if(e===this.secondaryConn_){this.log_("Secondary connection lost.");this.onSecondaryConnectionLost_()}else{this.log_("closing an old connection")}}}connReceiver_(e){return t=>{if(this.state_!==2){if(e===this.rx_){this.onPrimaryMessageReceived_(t)}else if(e===this.secondaryConn_){this.onSecondaryMessageReceived_(t)}else{this.log_("message on old connection")}}}}sendRequest(e){const t={t:"d",d:e};this.sendData_(t)}tryCleanupConnection(){if(this.tx_===this.secondaryConn_&&this.rx_===this.secondaryConn_){this.log_("cleaning up and promoting a connection: "+this.secondaryConn_.connId);this.conn_=this.secondaryConn_;this.secondaryConn_=null}}onSecondaryControl_(e){if(se in e){const t=e[se];if(t===de){this.upgradeIfSecondaryHealthy_()}else if(t===ce){this.log_("Got a reset on secondary, closing it");this.secondaryConn_.close();if(this.tx_===this.secondaryConn_||this.rx_===this.secondaryConn_){this.close()}}else if(t===ue){this.log_("got pong on secondary.");this.secondaryResponsesRequired_--;this.upgradeIfSecondaryHealthy_()}}}onSecondaryMessageReceived_(e){const t=requireKey("t",e);const n=requireKey("d",e);if(t==="c"){this.onSecondaryControl_(n)}else if(t==="d"){this.pendingDataMessages.push(n)}else{throw new Error("Unknown protocol layer: "+t)}}upgradeIfSecondaryHealthy_(){if(this.secondaryResponsesRequired_<=0){this.log_("Secondary connection is healthy.");this.isHealthy_=true;this.secondaryConn_.markConnectionHealthy();this.proceedWithUpgrade_()}else{this.log_("sending ping on secondary.");
2this.secondaryConn_.send({t:"c",d:{t:pe,d:{}}})}}proceedWithUpgrade_(){this.secondaryConn_.start();this.log_("sending client ack on secondary");this.secondaryConn_.send({t:"c",d:{t:de,d:{}}});this.log_("Ending transmission on primary");this.conn_.send({t:"c",d:{t:he,d:{}}});this.tx_=this.secondaryConn_;this.tryCleanupConnection()}onPrimaryMessageReceived_(e){const t=requireKey("t",e);const n=requireKey("d",e);if(t==="c"){this.onControl_(n)}else if(t==="d"){this.onDataMessage_(n)}}onDataMessage_(e){this.onPrimaryResponse_();this.onMessage_(e)}onPrimaryResponse_(){if(!this.isHealthy_){this.primaryResponsesRequired_--;if(this.primaryResponsesRequired_<=0){this.log_("Primary connection is healthy.");this.isHealthy_=true;this.conn_.markConnectionHealthy()}}}onControl_(e){const t=requireKey(se,e);if(oe in e){const n=e[oe];if(t===fe){const e={...n};if(this.repoInfo_.isUsingEmulator){e.h=this.repoInfo_.host}this.onHandshake_(e)}else if(t===he){this.log_("recvd end transmission on primary");this.rx_=this.secondaryConn_;for(let e=0;e<this.pendingDataMessages.length;++e){this.onDataMessage_(this.pendingDataMessages[e])}this.pendingDataMessages=[];this.tryCleanupConnection()}else if(t===ae){this.onConnectionShutdown_(n)}else if(t===ce){this.onReset_(n)}else if(t===le){error("Server Error: "+n)}else if(t===ue){this.log_("got pong on primary.");this.onPrimaryResponse_();this.sendPingOnPrimaryIfNecessary_()}else{error("Unknown control packet command: "+t)}}}onHandshake_(e){const t=e.ts;const n=e.v;const r=e.h;this.sessionId=e.s;this.repoInfo_.host=r;if(this.state_===0){this.conn_.start();this.onConnectionEstablished_(this.conn_,t);if(w!==n){warn("Protocol version mismatch detected")}this.tryStartUpgrade_()}}tryStartUpgrade_(){const e=this.transportManager_.upgradeTransport();if(e){this.startUpgrade_(e)}}startUpgrade_(e){this.secondaryConn_=new e(this.nextTransportId_(),this.repoInfo_,this.applicationId_,this.appCheckToken_,this.authToken_,this.sessionId);this.secondaryResponsesRequired_=e["responsesRequiredToBeHealthy"]||0;const t=this.connReceiver_(this.secondaryConn_);const n=this.disconnReceiver_(this.secondaryConn_);this.secondaryConn_.open(t,n);setTimeoutNonBlocking((()=>{if(this.secondaryConn_){this.log_("Timed out trying to upgrade.");this.secondaryConn_.close()}}),Math.floor(te))}onReset_(e){this.log_("Reset packet received.  New host: "+e);this.repoInfo_.host=e;if(this.state_===1){this.close()}else{this.closeConnections_();this.start_()}}onConnectionEstablished_(e,t){this.log_("Realtime connection established.");this.conn_=e;this.state_=1;if(this.onReady_){this.onReady_(t,this.sessionId);this.onReady_=null}if(this.primaryResponsesRequired_===0){this.log_("Primary connection is healthy.");this.isHealthy_=true}else{setTimeoutNonBlocking((()=>{this.sendPingOnPrimaryIfNecessary_()}),Math.floor(ne))}}sendPingOnPrimaryIfNecessary_(){if(!this.isHealthy_&&this.state_===1){this.log_("sending ping on primary.");this.sendData_({t:"c",d:{t:pe,d:{}}})}}onSecondaryConnectionLost_(){const e=this.secondaryConn_;this.secondaryConn_=null;if(this.tx_===e||this.rx_===e){this.close()}}onConnectionLost_(e){this.conn_=null;if(!e&&this.state_===0){this.log_("Realtime connection failed.");if(this.repoInfo_.isCacheableHost()){d.remove("host:"+this.repoInfo_.host);this.repoInfo_.internalHost=this.repoInfo_.host}}else if(this.state_===1){this.log_("Realtime connection lost.")}this.close()}onConnectionShutdown_(e){this.log_("Connection shutdown command received. Shutting down...");if(this.onKill_){this.onKill_(e);this.onKill_=null}this.onDisconnect_=null;this.close()}sendData_(e){if(this.state_!==1){throw"Connection is not connected"}else{this.tx_.send(e)}}close(){if(this.state_!==2){this.log_("Closing realtime connection.");this.state_=2;this.closeConnections_();if(this.onDisconnect_){this.onDisconnect_();this.onDisconnect_=null}}}closeConnections_(){this.log_("Shutting down all connections");if(this.conn_){this.conn_.close();this.conn_=null}if(this.secondaryConn_){this.secondaryConn_.close();this.secondaryConn_=null}if(this.healthyTimeout_){clearTimeout(this.healthyTimeout_);this.healthyTimeout_=null}}}class ServerActions{put(e,t,n,r){}merge(e,t,n,r){}refreshAuthToken(e){}refreshAppCheckToken(e){}onDisconnectPut(e,t,n){}onDisconnectMerge(e,t,n){}onDisconnectCancel(e,t){}reportStats(e){}}class EventEmitter{constructor(e){this.allowedEvents_=e;this.listeners_={};o.assert(Array.isArray(e)&&e.length>0,"Requires a non-empty array")}trigger(e,...t){if(Array.isArray(this.listeners_[e])){const n=[...this.listeners_[e]];for(let e=0;e<n.length;e++){n[e].callback.apply(n[e].context,t)}}}on(e,t,n){this.validateEventType_(e);this.listeners_[e]=this.listeners_[e]||[];this.listeners_[e].push({callback:t,context:n});const r=this.getInitialEvent(e);
2if(r){t.apply(n,r)}}off(e,t,n){this.validateEventType_(e);const r=this.listeners_[e]||[];for(let e=0;e<r.length;e++){if(r[e].callback===t&&(!n||n===r[e].context)){r.splice(e,1);return}}}validateEventType_(e){o.assert(this.allowedEvents_.find((t=>t===e)),"Unknown event: "+e)}}class OnlineMonitor extends EventEmitter{static getInstance(){return new OnlineMonitor}constructor(){super(["online"]);this.online_=true;if(typeof window!=="undefined"&&typeof window.addEventListener!=="undefined"&&!o.isMobileCordova()){window.addEventListener("online",(()=>{if(!this.online_){this.online_=true;this.trigger("online",true)}}),false);window.addEventListener("offline",(()=>{if(this.online_){this.online_=false;this.trigger("online",false)}}),false)}}getInitialEvent(e){o.assert(e==="online","Unknown event type: "+e);return[this.online_]}currentlyOnline(){return this.online_}}const me=32;const ge=768;class Path{constructor(e,t){if(t===void 0){this.pieces_=e.split("/");let t=0;for(let e=0;e<this.pieces_.length;e++){if(this.pieces_[e].length>0){this.pieces_[t]=this.pieces_[e];t++}}this.pieces_.length=t;this.pieceNum_=0}else{this.pieces_=e;this.pieceNum_=t}}toString(){let e="";for(let t=this.pieceNum_;t<this.pieces_.length;t++){if(this.pieces_[t]!==""){e+="/"+this.pieces_[t]}}return e||"/"}}function newEmptyPath(){return new Path("")}function pathGetFront(e){if(e.pieceNum_>=e.pieces_.length){return null}return e.pieces_[e.pieceNum_]}function pathGetLength(e){return e.pieces_.length-e.pieceNum_}function pathPopFront(e){let t=e.pieceNum_;if(t<e.pieces_.length){t++}return new Path(e.pieces_,t)}function pathGetBack(e){if(e.pieceNum_<e.pieces_.length){return e.pieces_[e.pieces_.length-1]}return null}function pathToUrlEncodedString(e){let t="";for(let n=e.pieceNum_;n<e.pieces_.length;n++){if(e.pieces_[n]!==""){t+="/"+encodeURIComponent(String(e.pieces_[n]))}}return t||"/"}function pathSlice(e,t=0){return e.pieces_.slice(e.pieceNum_+t)}function pathParent(e){if(e.pieceNum_>=e.pieces_.length){return null}const t=[];for(let n=e.pieceNum_;n<e.pieces_.length-1;n++){t.push(e.pieces_[n])}return new Path(t,0)}function pathChild(e,t){const n=[];for(let t=e.pieceNum_;t<e.pieces_.length;t++){n.push(e.pieces_[t])}if(t instanceof Path){for(let e=t.pieceNum_;e<t.pieces_.length;e++){n.push(t.pieces_[e])}}else{const e=t.split("/");for(let t=0;t<e.length;t++){if(e[t].length>0){n.push(e[t])}}}return new Path(n,0)}function pathIsEmpty(e){return e.pieceNum_>=e.pieces_.length}function newRelativePath(e,t){const n=pathGetFront(e),r=pathGetFront(t);if(n===null){return t}else if(n===r){return newRelativePath(pathPopFront(e),pathPopFront(t))}else{throw new Error("INTERNAL ERROR: innerPath ("+t+") is not within "+"outerPath ("+e+")")}}function pathCompare(e,t){const n=pathSlice(e,0);const r=pathSlice(t,0);for(let e=0;e<n.length&&e<r.length;e++){const t=nameCompare(n[e],r[e]);if(t!==0){return t}}if(n.length===r.length){return 0}return n.length<r.length?-1:1}function pathEquals(e,t){if(pathGetLength(e)!==pathGetLength(t)){return false}for(let n=e.pieceNum_,r=t.pieceNum_;n<=e.pieces_.length;n++,r++){if(e.pieces_[n]!==t.pieces_[r]){return false}}return true}function pathContains(e,t){let n=e.pieceNum_;let r=t.pieceNum_;if(pathGetLength(e)>pathGetLength(t)){return false}while(n<e.pieces_.length){if(e.pieces_[n]!==t.pieces_[r]){return false}++n;++r}return true}class ValidationPath{constructor(e,t){this.errorPrefix_=t;this.parts_=pathSlice(e,0);this.byteLength_=Math.max(1,this.parts_.length);for(let e=0;e<this.parts_.length;e++){this.byteLength_+=o.stringLength(this.parts_[e])}validationPathCheckValid(this)}}function validationPathPush(e,t){if(e.parts_.length>0){e.byteLength_+=1}e.parts_.push(t);e.byteLength_+=o.stringLength(t);validationPathCheckValid(e)}function validationPathPop(e){const t=e.parts_.pop();e.byteLength_-=o.stringLength(t);if(e.parts_.length>0){e.byteLength_-=1}}function validationPathCheckValid(e){if(e.byteLength_>ge){throw new Error(e.errorPrefix_+"has a key path longer than "+ge+" bytes ("+e.byteLength_+").")}if(e.parts_.length>me){throw new Error(e.errorPrefix_+"path specified exceeds the maximum depth that can be written ("+me+") or object c
2ontains a cycle "+validationPathToErrorString(e))}}function validationPathToErrorString(e){if(e.parts_.length===0){return""}return"in property '"+e.parts_.join(".")+"'"}class VisibilityMonitor extends EventEmitter{static getInstance(){return new VisibilityMonitor}constructor(){super(["visible"]);let e;let t;if(typeof document!=="undefined"&&typeof document.addEventListener!=="undefined"){if(typeof document["hidden"]!=="undefined"){t="visibilitychange";e="hidden"}else if(typeof document["mozHidden"]!=="undefined"){t="mozvisibilitychange";e="mozHidden"}else if(typeof document["msHidden"]!=="undefined"){t="msvisibilitychange";e="msHidden"}else if(typeof document["webkitHidden"]!=="undefined"){t="webkitvisibilitychange";e="webkitHidden"}}this.visible_=true;if(t){document.addEventListener(t,(()=>{const t=!document[e];if(t!==this.visible_){this.visible_=t;this.trigger("visible",t)}}),false)}}getInitialEvent(e){o.assert(e==="visible","Unknown event type: "+e);return[this.visible_]}}const _e=1e3;const ve=60*5*1e3;const ye=30*1e3;const Ie=1.3;const Ce=3e4;const we="server_kill";const Ee=3;class PersistentConnection extends ServerActions{constructor(e,t,n,r,i,s,a,c){super();this.repoInfo_=e;this.applicationId_=t;this.onDataUpdate_=n;this.onConnectStatus_=r;this.onServerInfoUpdate_=i;this.authTokenProvider_=s;this.appCheckTokenProvider_=a;this.authOverride_=c;this.id=PersistentConnection.nextPersistentConnectionId_++;this.log_=logWrapper("p:"+this.id+":");this.interruptReasons_={};this.listens=new Map;this.outstandingPuts_=[];this.outstandingGets_=[];this.outstandingPutCount_=0;this.outstandingGetCount_=0;this.onDisconnectRequestQueue_=[];this.connected_=false;this.reconnectDelay_=_e;this.maxReconnectDelay_=ve;this.securityDebugCallback_=null;this.lastSessionId=null;this.establishConnectionTimer_=null;this.visible_=false;this.requestCBHash_={};this.requestNumber_=0;this.realtime_=null;this.authToken_=null;this.appCheckToken_=null;this.forceTokenRefresh_=false;this.invalidAuthTokenCount_=0;this.invalidAppCheckTokenCount_=0;this.firstConnection_=true;this.lastConnectionAttemptTime_=null;this.lastConnectionEstablishedTime_=null;if(c&&!o.isNodeSdk()){throw new Error("Auth override specified in options, but not supported on non Node.js platforms")}VisibilityMonitor.getInstance().on("visible",this.onVisible_,this);if(e.host.indexOf("fblocal")===-1){OnlineMonitor.getInstance().on("online",this.onOnline_,this)}}sendRequest(e,t,n){const r=++this.requestNumber_;const i={r,a:e,b:t};this.log_(o.stringify(i));o.assert(this.connected_,"sendRequest call when we're not connected not allowed.");this.realtime_.sendRequest(i);if(n){this.requestCBHash_[r]=n}}get(e){this.initConnection_();const t=new o.Deferred;const n={p:e._path.toString(),q:e._queryObject};const r={action:"g",request:n,onComplete:e=>{const n=e["d"];if(e["s"]==="ok"){t.resolve(n)}else{t.reject(n)}}};this.outstandingGets_.push(r);this.outstandingGetCount_++;const i=this.outstandingGets_.length-1;if(this.connected_){this.sendGet_(i)}return t.promise}listen(e,t,n,r){this.initConnection_();const i=e._queryIdentifier;const s=e._path.toString();this.log_("Listen called for "+s+" "+i);if(!this.listens.has(s)){this.listens.set(s,new Map)}o.assert(e._queryParams.isDefault()||!e._queryParams.loadsAllData(),"listen() called for non-default but complete query");o.assert(!this.listens.get(s).has(i),`listen() called twice for same path/queryId.`);const a={onComplete:r,hashFn:t,query:e,tag:n};this.listens.get(s).set(i,a);if(this.connected_){this.sendListen_(a)}}sendGet_(e){const t=this.outstandingGets_[e];this.sendRequest("g",t.request,(n=>{delete this.outstandingGets_[e];this.outstandingGetCount_--;if(this.outstandingGetCount_===0){this.outstandingGets_=[]}if(t.onComplete){t.onComplete(n)}}))}sendListen_(e){const t=e.query;const n=t._path.toString();const r=t._queryIdentifier;this.log_("Listen on "+n+" for "+r);const i={p:n};const s="q";if(e.tag){i["q"]=t._queryObject;i["t"]=e.tag}i["h"]=e.hashFn();this.sendRequest(s,i,(i=>{const s=i["d"];const o=i["s"];PersistentConnection.warnOnListenWarnings_(s,t);const a=this.listens.get(n)&&this.listens.get(n).get(r);if(a===e){this.log_("listen response",i);if(o!=="ok"){this.removeListen_(n,r)}if(e.onComplete){e.onComplete(o,s)}}}))}static warnOnListenWarnings_(e,t){if(e&&typeof e==="object"&&o.contains(e,"w")){const n=o.safeGet(e,"w");if(Array.isArray(n)&&~n.indexOf("no_index")){const e='".indexOn": "'+t._queryParams.getIndex().toString()+'"';const n=t._path.toString();warn(`Using an unspecified index. Your data will be downloaded and `+`filtered on the client. Consider adding ${e} at `+`${n} to your security rules for better performance.`)}}}refreshAuthToken(e){this.authToken_=e;this.log_("Auth token refreshed");if(this.authToken_){this.tryAuth()}else{if(this.connected_){this.sendRequest("unauth",{},(()=>{}))}}this.reduceReconnectDelayIfAdminCredential_(e)}reduceReconnectDelayIfAdminCredential_(e){const t=e&&e.length===40;if(t||o.isAdmin(e)){this.log_("Admin auth credential detected.  Reducing max reconnect time.");this.maxReconnectDelay_=ye}}refreshAppCheckToken(e){this.appCheckToken_=e;this.log_("App check token refreshed");if(this.appCheckToken_){this.tryAppCheck()}else{if(this.connected_){this.sendRequest("unappeck",{},(()=>{}))}}}tryAuth(){if(this.connected_&&this.authToken_){const e=this.authToken_;const t=o.isValidFormat(e)?"auth":"gauth";const n={cred:e};if(this.authOverride_===null){n["noauth"]=true}else if(typeof this.authOverride_==="object"){n["authvar"]=this.authOverride_}this.sendRequest(t,n,(t=>{const n=t["s"];const r=t["d"]||"error";if(this.authToken_===e){if(n==="ok"){this.invalidAuthTokenCount_=0}else{this.onAuthRevoked_(n,r)}}}))}}tryAppCheck(){if(this.connected_&&this.appCheckToken_){this.sendRequest("appcheck",{token:this.appCheckToken_},(e=>{const t=e["s"];const n=e["d"]||"error";if(t==="ok"){this.invalidAppCheckTokenCount_=0}else{this.onAppCheckRevoked_(t,n)}}))}}unlisten(e,t){const n=e._path.toString();const r=e._queryIdentifier;this.log_("Unlisten called for "+n+" "+r);o.assert(e._queryParams.isDefault()||!e._queryParams.loadsAllData(),"unlisten() called for non-default but complete query");const i=this.removeListen_(n,r);if(i&&this.connected_){this.sendUnlisten_(n,r,e._queryObject,t)}}sendUnlisten_(e,t,n,r){this.log_("Unlisten on "+e+" for "+t);const i={p:e};const s="n";if(r){i["q"]=n;i["t"]=r}this.sendRequest(s,i)}onDisconnectPut(e,t,n){this.initConnection_();if(this.connected_){this.sendOnDisconnect_("o",e,t,n)}else{this.onDisconnectRequestQueue_.push({pathString:e,action:"o",data:t,onComplete:n})}}onDisconnectMerge(e,t,n){this.initConnection_();if(this.connected_){this.sendOnDisconnect_("om",e,t,n)}else{this.onDisconnectRequestQueue_.push({pathString:e,action:"om",data:t,onComplete:n})}}onDisconnectCancel(e,t){this.initConnection_();if(this.connected_){this.sendOnDisconnect_("oc",e,null,t)}else{this.onDisconnectRequestQueue_.push({pathString:e,action:"oc",data:null,onComplete:t})}}sendOnDisconnect_(e,t,n,r){const i={p:t,d:n};this.log_("onDisconnect "+e,i);this.sendRequest(e,i,(e=>{if(r){setTimeout((()=>{r(e["s"],e["d"])}),Math.floor(0))}}))}put(e,t,n,r){this.putInternal("p",e,t,n,r)}merge(e,t,n,r){this.putInternal("m",e,t,n,r)}putInternal(e,t,n,r,i){this.initConnection_();const s={p:t,d:n};
2if(i!==undefined){s["h"]=i}this.outstandingPuts_.push({action:e,request:s,onComplete:r});this.outstandingPutCount_++;const o=this.outstandingPuts_.length-1;if(this.connected_){this.sendPut_(o)}else{this.log_("Buffering put: "+t)}}sendPut_(e){const t=this.outstandingPuts_[e].action;const n=this.outstandingPuts_[e].request;const r=this.outstandingPuts_[e].onComplete;this.outstandingPuts_[e].queued=this.connected_;this.sendRequest(t,n,(n=>{this.log_(t+" response",n);delete this.outstandingPuts_[e];this.outstandingPutCount_--;if(this.outstandingPutCount_===0){this.outstandingPuts_=[]}if(r){r(n["s"],n["d"])}}))}reportStats(e){if(this.connected_){const t={c:e};this.log_("reportStats",t);this.sendRequest("s",t,(e=>{const t=e["s"];if(t!=="ok"){const t=e["d"];this.log_("reportStats","Error sending stats: "+t)}}))}}onDataMessage_(e){if("r"in e){this.log_("from server: "+o.stringify(e));const t=e["r"];const n=this.requestCBHash_[t];if(n){delete this.requestCBHash_[t];n(e["b"])}}else if("error"in e){throw"A server-side error has occurred: "+e["error"]}else if("a"in e){this.onDataPush_(e["a"],e["b"])}}onDataPush_(e,t){this.log_("handleServerMessage",e,t);if(e==="d"){this.onDataUpdate_(t["p"],t["d"],false,t["t"])}else if(e==="m"){this.onDataUpdate_(t["p"],t["d"],true,t["t"])}else if(e==="c"){this.onListenRevoked_(t["p"],t["q"])}else if(e==="ac"){this.onAuthRevoked_(t["s"],t["d"])}else if(e==="apc"){this.onAppCheckRevoked_(t["s"],t["d"])}else if(e==="sd"){this.onSecurityDebugPacket_(t)}else{error("Unrecognized action received from server: "+o.stringify(e)+"\nAre you using the latest client?")}}onReady_(e,t){this.log_("connection ready");this.connected_=true;this.lastConnectionEstablishedTime_=(new Date).getTime();this.handleTimestamp_(e);this.lastSessionId=t;if(this.firstConnection_){this.sendConnectStats_()}this.restoreState_();this.firstConnection_=false;this.onConnectStatus_(true)}scheduleConnect_(e){o.assert(!this.realtime_,"Scheduling a connect when we're already connected/ing?");if(this.establishConnectionTimer_){clearTimeout(this.establishConnectionTimer_)}this.establishConnectionTimer_=setTimeout((()=>{this.establishConnectionTimer_=null;this.establishConnection_()}),Math.floor(e))}initConnection_(){if(!this.realtime_&&this.firstConnection_){this.scheduleConnect_(0)}}onVisible_(e){if(e&&!this.visible_&&this.reconnectDelay_===this.maxReconnectDelay_){this.log_("Window became visible.  Reducing delay.");this.reconnectDelay_=_e;if(!this.realtime_){this.scheduleConnect_(0)}}this.visible_=e}onOnline_(e){if(e){this.log_("Browser went online.");this.reconnectDelay_=_e;if(!this.realtime_){this.scheduleConnect_(0)}}else{this.log_("Browser went offline.  Killing connection.");if(this.realtime_){this.realtime_.close()}}}onRealtimeDisconnect_(){this.log_("data client disconnected");this.connected_=false;this.realtime_=null;this.cancelSentTransactions_();this.requestCBHash_={};if(this.shouldReconnect_()){if(!this.visible_){this.log_("Window isn't visible.  Delaying reconnect.");this.reconnectDelay_=this.maxReconnectDelay_;this.lastConnectionAttemptTime_=(new Date).getTime()}else if(this.lastConnectionEstablishedTime_){const e=(new Date).getTime()-this.lastConnectionEstablishedTime_;if(e>Ce){this.reconnectDelay_=_e}this.lastConnectionEstablishedTime_=null}const e=Math.max(0,(new Date).getTime()-this.lastConnectionAttemptTime_);let t=Math.max(0,this.reconnectDelay_-e);t=Math.random()*t;this.log_("Trying to reconnect in "+t+"ms");this.scheduleConnect_(t);this.reconnectDelay_=Math.min(this.maxReconnectDelay_,this.reconnectDelay_*Ie)}this.onConnectStatus_(false)}async establishConnection_(){if(this.shouldReconnect_()){this.log_("Making a connection attempt");this.lastConnectionAttemptTime_=(new Date).getTime();this.lastConnectionEstablishedTime_=null;const e=this.onDataMessage_.bind(this);const t=this.onReady_.bind(this);const n=this.onRealtimeDisconnect_.bind(this);const r=this.id+":"+PersistentConnection.nextConnectionId_++;const i=this.lastSessionId;let s=false;let a=null;const closeFn=function(){if(a){a.close()}else{s=true;n()}};const sendRequestFn=function(e){o.assert(a,"sendRequest call when we're not connected not allowed.");a.sendRequest(e)};
2this.realtime_={close:closeFn,sendRequest:sendRequestFn};const c=this.forceTokenRefresh_;this.forceTokenRefresh_=false;try{const[o,l]=await Promise.all([this.authTokenProvider_.getToken(c),this.appCheckTokenProvider_.getToken(c)]);if(!s){log("getToken() completed. Creating connection.");this.authToken_=o&&o.accessToken;this.appCheckToken_=l&&l.token;a=new Connection(r,this.repoInfo_,this.applicationId_,this.appCheckToken_,this.authToken_,e,t,n,(e=>{warn(e+" ("+this.repoInfo_.toString()+")");this.interrupt(we)}),i)}else{log("getToken() completed but was canceled")}}catch(e){this.log_("Failed to get token: "+e);if(!s){if(this.repoInfo_.nodeAdmin){warn(e)}closeFn()}}}}interrupt(e){log("Interrupting connection for reason: "+e);this.interruptReasons_[e]=true;if(this.realtime_){this.realtime_.close()}else{if(this.establishConnectionTimer_){clearTimeout(this.establishConnectionTimer_);this.establishConnectionTimer_=null}if(this.connected_){this.onRealtimeDisconnect_()}}}resume(e){log("Resuming connection for reason: "+e);delete this.interruptReasons_[e];if(o.isEmpty(this.interruptReasons_)){this.reconnectDelay_=_e;if(!this.realtime_){this.scheduleConnect_(0)}}}handleTimestamp_(e){const t=e-(new Date).getTime();this.onServerInfoUpdate_({serverTimeOffset:t})}cancelSentTransactions_(){for(let e=0;e<this.outstandingPuts_.length;e++){const t=this.outstandingPuts_[e];if(t&&"h"in t.request&&t.queued){if(t.onComplete){t.onComplete("disconnect")}delete this.outstandingPuts_[e];this.outstandingPutCount_--}}if(this.outstandingPutCount_===0){this.outstandingPuts_=[]}}onListenRevoked_(e,t){let n;if(!t){n="default"}else{n=t.map((e=>ObjectToUniqueKey(e))).join("$")}const r=this.removeListen_(e,n);if(r&&r.onComplete){r.onComplete("permission_denied")}}removeListen_(e,t){const n=new Path(e).toString();let r;if(this.listens.has(n)){const e=this.listens.get(n);r=e.get(t);e.delete(t);if(e.size===0){this.listens.delete(n)}}else{r=undefined}return r}onAuthRevoked_(e,t){log("Auth token revoked: "+e+"/"+t);this.authToken_=null;this.forceTokenRefresh_=true;this.realtime_.close();if(e==="invalid_token"||e==="permission_denied"){this.invalidAuthTokenCount_++;if(this.invalidAuthTokenCount_>=Ee){this.reconnectDelay_=ye;this.authTokenProvider_.notifyForInvalidToken()}}}onAppCheckRevoked_(e,t){log("App check token revoked: "+e+"/"+t);this.appCheckToken_=null;this.forceTokenRefresh_=true;if(e==="invalid_token"||e==="permission_denied"){this.invalidAppCheckTokenCount_++;if(this.invalidAppCheckTokenCount_>=Ee){this.appCheckTokenProvider_.notifyForInvalidToken()}}}onSecurityDebugPacket_(e){if(this.securityDebugCallback_){this.securityDebugCallback_(e)}else{if("msg"in e){console.log("FIREBASE: "+e["msg"].replace("\n","\nFIREBASE: "))}}}restoreState_(){this.tryAuth();this.tryAppCheck();for(const e of this.listens.values()){for(const t of e.values()){this.sendListen_(t)}}for(let e=0;e<this.outstandingPuts_.length;e++){if(this.outstandingPuts_[e]){this.sendPut_(e)}}while(this.onDisconnectRequestQueue_.length){const e=this.onDisconnectRequestQueue_.shift();this.sendOnDisconnect_(e.action,e.pathString,e.data,e.onComplete)}for(let e=0;e<this.outstandingGets_.length;e++){if(this.outstandingGets_[e]){this.sendGet_(e)}}}sendConnectStats_(){const e={};let t="js";if(o.isNodeSdk()){if(this.repoInfo_.nodeAdmin){t="admin_node"}else{t="node"}}e["sdk."+t+"."+u.replace(/\./g,"-")]=1;if(o.isMobileCordova()){e["framework.cordova"]=1}else if(o.isReactNative()){e["framework.reactnative"]=1}this.reportStats(e)}shouldReconnect_(){const e=OnlineMonitor.getInstance().currentlyOnline();return o.isEmpty(this.interruptReasons_)&&e}}PersistentConnection.nextPersistentConnectionId_=0;PersistentConnection.nextConnectionId_=0;
2class NamedNode{constructor(e,t){this.name=e;this.node=t}static Wrap(e,t){return new NamedNode(e,t)}}class Index{getCompare(){return this.compare.bind(this)}indexedValueChanged(e,t){const n=new NamedNode(_,e);const r=new NamedNode(_,t);return this.compare(n,r)!==0}minPost(){return NamedNode.MIN}}let Te;class KeyIndex extends Index{static get __EMPTY_NODE(){return Te}static set __EMPTY_NODE(e){Te=e}compare(e,t){return nameCompare(e.name,t.name)}isDefinedOn(e){throw o.assertionError("KeyIndex.isDefinedOn not expected to be called.")}indexedValueChanged(e,t){return false}minPost(){return NamedNode.MIN}maxPost(){return new NamedNode(v,Te)}makePost(e,t){o.assert(typeof e==="string","KeyIndex indexValue must always be a string.");return new NamedNode(e,Te)}toString(){return".key"}}const Pe=new KeyIndex;class SortedMapIterator{constructor(e,t,n,r,i=null){this.isReverse_=r;this.resultGenerator_=i;this.nodeStack_=[];let s=1;while(!e.isEmpty()){e=e;s=t?n(e.key,t):1;if(r){s*=-1}if(s<0){if(this.isReverse_){e=e.left}else{e=e.right}}else if(s===0){this.nodeStack_.push(e);break}else{this.nodeStack_.push(e);if(this.isReverse_){e=e.right}else{e=e.left}}}}getNext(){if(this.nodeStack_.length===0){return null}let e=this.nodeStack_.pop();let t;if(this.resultGenerator_){t=this.resultGenerator_(e.key,e.value)}else{t={key:e.key,value:e.value}}if(this.isReverse_){e=e.left;while(!e.isEmpty()){this.nodeStack_.push(e);e=e.right}}else{e=e.right;while(!e.isEmpty()){this.nodeStack_.push(e);e=e.left}}return t}hasNext(){return this.nodeStack_.length>0}peek(){if(this.nodeStack_.length===0){return null}const e=this.nodeStack_[this.nodeStack_.length-1];if(this.resultGenerator_){return this.resultGenerator_(e.key,e.value)}else{return{key:e.key,value:e.value}}}}class LLRBNode{constructor(e,t,n,r,i){this.key=e;this.value=t;this.color=n!=null?n:LLRBNode.RED;this.left=r!=null?r:SortedMap.EMPTY_NODE;this.right=i!=null?i:SortedMap.EMPTY_NODE}copy(e,t,n,r,i){return new LLRBNode(e!=null?e:this.key,t!=null?t:this.value,n!=null?n:this.color,r!=null?r:this.left,i!=null?i:this.right)}count(){return this.left.count()+1+this.right.count()}isEmpty(){return false}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_(){if(this.left.isEmpty()){return this}else{return this.left.min_()}}minKey(){return this.min_().key}maxKey(){if(this.right.isEmpty()){return this.key}else{return this.right.maxKey()}}insert(e,t,n){let r=this;const i=n(e,r.key);if(i<0){r=r.copy(null,null,null,r.left.insert(e,t,n),null)}else if(i===0){r=r.copy(null,t,null,null,null)}else{r=r.copy(null,null,null,null,r.right.insert(e,t,n))}return r.fixUp_()}removeMin_(){if(this.left.isEmpty()){return SortedMap.EMPTY_NODE}let e=this;if(!e.left.isRed_()&&!e.left.left.isRed_()){e=e.moveRedLeft_()}e=e.copy(null,null,null,e.left.removeMin_(),null);return e.fixUp_()}remove(e,t){let n,r;n=this;if(t(e,n.key)<0){if(!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_()}if(!n.right.isEmpty()&&!n.right.isRed_()&&!n.right.left.isRed_()){n=n.moveRedRight_()}if(t(e,n.key)===0){if(n.right.isEmpty()){return SortedMap.EMPTY_NODE}else{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;if(e.right.isRed_()&&!e.left.isRed_()){e=e.rotateLeft_()}if(e.left.isRed_()&&e.left.left.isRed_()){e=e.rotateRight_()}
2if(e.left.isRed_()&&e.right.isRed_()){e=e.colorFlip_()}return e}moveRedLeft_(){let e=this.colorFlip_();if(e.right.left.isRed_()){e=e.copy(null,null,null,null,e.right.rotateRight_());e=e.rotateLeft_();e=e.colorFlip_()}return e}moveRedRight_(){let e=this.colorFlip_();if(e.left.left.isRed_()){e=e.rotateRight_();e=e.colorFlip_()}return e}rotateLeft_(){const e=this.copy(null,null,LLRBNode.RED,null,this.right.left);return this.right.copy(null,null,this.color,e,null)}rotateRight_(){const e=this.copy(null,null,LLRBNode.RED,this.left.right,null);return this.left.copy(null,null,this.color,null,e)}colorFlip_(){const e=this.left.copy(null,null,!this.left.color,null,null);const t=this.right.copy(null,null,!this.right.color,null,null);return this.copy(null,null,!this.color,e,t)}checkMaxDepth_(){const e=this.check_();return Math.pow(2,e)<=this.count()+1}check_(){if(this.isRed_()&&this.left.isRed_()){throw new Error("Red node has red child("+this.key+","+this.value+")")}if(this.right.isRed_()){throw new Error("Right child of ("+this.key+","+this.value+") is red")}const e=this.left.check_();if(e!==this.right.check_()){throw new Error("Black depths differ")}else{return e+(this.isRed_()?0:1)}}}LLRBNode.RED=true;LLRBNode.BLACK=false;class LLRBEmptyNode{copy(e,t,n,r,i){return this}insert(e,t,n){return new LLRBNode(e,t,null)}remove(e,t){return this}count(){return 0}isEmpty(){return true}inorderTraversal(e){return false}reverseTraversal(e){return false}minKey(){return null}maxKey(){return null}check_(){return 0}isRed_(){return false}}class SortedMap{constructor(e,t=SortedMap.EMPTY_NODE){this.comparator_=e;this.root_=t}insert(e,t){return new SortedMap(this.comparator_,this.root_.insert(e,t,this.comparator_).copy(null,null,LLRBNode.BLACK,null,null))}remove(e){return new SortedMap(this.comparator_,this.root_.remove(e,this.comparator_).copy(null,null,LLRBNode.BLACK,null,null))}get(e){let t;let n=this.root_;while(!n.isEmpty()){t=this.comparator_(e,n.key);if(t===0){return n.value}else if(t<0){n=n.left}else if(t>0){n=n.right}}return null}getPredecessorKey(e){let t,n=this.root_,r=null;while(!n.isEmpty()){t=this.comparator_(e,n.key);if(t===0){if(!n.left.isEmpty()){n=n.left;while(!n.right.isEmpty()){n=n.right}return n.key}else if(r){return r.key}else{return null}}else if(t<0){n=n.left}else if(t>0){r=n;n=n.right}}throw new Error("Attempted to find predecessor key for a nonexistent key.  What gives?")}isEmpty(){return this.root_.isEmpty()}count(){return this.root_.count()}minKey(){return this.root_.minKey()}maxKey(){return this.root_.maxKey()}inorderTraversal(e){return this.root_.inorderTraversal(e)}reverseTraversal(e){return this.root_.reverseTraversal(e)}getIterator(e){return new SortedMapIterator(this.root_,null,this.comparator_,false,e)}getIteratorFrom(e,t){return new SortedMapIterator(this.root_,e,this.comparator_,false,t)}getReverseIteratorFrom(e,t){return new SortedMapIterator(this.root_,e,this.comparator_,true,t)}getReverseIterator(e){return new SortedMapIterator(this.root_,null,this.comparator_,true,e)}}SortedMap.EMPTY_NODE=new LLRBEmptyNode;function NAME_ONLY_COMPARATOR(e,t){return nameCompare(e.name,t.name)}function NAME_COMPARATOR(e,t){return nameCompare(e,t)}let Ae;function setMaxNode$1(e){Ae=e}const priorityHashText=function(e){if(typeof e==="number"){return"number:"+doubleToIEEE754String(e)}else{return"string:"+e}};const validatePriorityNode=function(e){if(e.isLeafNode()){const t=e.val();o.assert(typeof t==="string"||typeof t==="number"||typeof t==="object"&&o.contains(t,".sv"),"Priority must be a string or number.")}else{o.assert(e===Ae||e.isEmpty(),"priority of unexpected type.")}o.assert(e===Ae||e.getPriority().isEmpty(),"Priority nodes can't have a priority of their own.")};let Se;class LeafNode{static set __childrenNodeConstructor(e){Se=e}static get __childrenNodeConstructor(){return Se}constructor(e,t=LeafNode.__childrenNodeConstructor.EMPTY_NODE){this.value_=e;this.priorityNode_=t;this.lazyHash_=null;o.assert(this.value_!==undefined&&this.value_!==null,"LeafNode shouldn't be created with null/undefined value.");validatePriorityNode(this.priorityNode_)}isLeafNode(){return true}getPriority(){return this.priorityNode_}updatePriority(e){return new LeafNode(this.value_,e)}getImmediateChild(e){if(e===".priority"){return this.priorityNode_}else{return LeafNode.__childrenNodeConstructor.EMPTY_NODE}}getChild(e){if(pathIsEmpty(e)){return this}else if(pathGetFront(e)===".priority"){return this.priorityNode_}else{return LeafNode.__childrenNodeConstructor.EMPTY_NODE}}hasChild(){return false}getPredecessorChildName(e,t){return null}updateImmediateChild(e,t){if(e===".priority"){return this.updatePriority(t)}else if(t.isEmpty()&&e!==".priority"){return this}else{return LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateImmediateChild(e,t).updatePriority(this.priorityNode_)}}updateChild(e,t){const n=pathGetFront(e);if(n===null){return t}else if(t.isEmpty()&&n!==".priority"){return this}else{o.assert(n!==".priority"||pathGetLength(e)===1,".priority must be the last token in a path");return this.updateImmediateChild(n,LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateChild(pathPopFront(e),t))}}isEmpty(){return false}numChildren(){return 0}forEachChild(e,t){return false}
2val(e){if(e&&!this.getPriority().isEmpty()){return{".value":this.getValue(),".priority":this.getPriority().val()}}else{return this.getValue()}}hash(){if(this.lazyHash_===null){let e="";if(!this.priorityNode_.isEmpty()){e+="priority:"+priorityHashText(this.priorityNode_.val())+":"}const t=typeof this.value_;e+=t+":";if(t==="number"){e+=doubleToIEEE754String(this.value_)}else{e+=this.value_}this.lazyHash_=sha1(e)}return this.lazyHash_}getValue(){return this.value_}compareTo(e){if(e===LeafNode.__childrenNodeConstructor.EMPTY_NODE){return 1}else if(e instanceof LeafNode.__childrenNodeConstructor){return-1}else{o.assert(e.isLeafNode(),"Unknown node type");return this.compareToLeafNode_(e)}}compareToLeafNode_(e){const t=typeof e.value_;const n=typeof this.value_;const r=LeafNode.VALUE_TYPE_ORDER.indexOf(t);const i=LeafNode.VALUE_TYPE_ORDER.indexOf(n);o.assert(r>=0,"Unknown leaf type: "+t);o.assert(i>=0,"Unknown leaf type: "+n);if(r===i){if(n==="object"){return 0}else{if(this.value_<e.value_){return-1}else if(this.value_===e.value_){return 0}else{return 1}}}else{return i-r}}withIndex(){return this}isIndexed(){return true}equals(e){if(e===this){return true}else if(e.isLeafNode()){const t=e;return this.value_===t.value_&&this.priorityNode_.equals(t.priorityNode_)}else{return false}}}LeafNode.VALUE_TYPE_ORDER=["object","boolean","number","string"];let be;let Re;function setNodeFromJSON(e){be=e}function setMaxNode(e){Re=e}class PriorityIndex extends Index{compare(e,t){const n=e.node.getPriority();const r=t.node.getPriority();const i=n.compareTo(r);if(i===0){return nameCompare(e.name,t.name)}else{return i}}isDefinedOn(e){return!e.getPriority().isEmpty()}indexedValueChanged(e,t){return!e.getPriority().equals(t.getPriority())}minPost(){return NamedNode.MIN}maxPost(){return new NamedNode(v,new LeafNode("[PRIORITY-POST]",Re))}makePost(e,t){const n=be(e);return new NamedNode(t,new LeafNode("[PRIORITY-POST]",n))}toString(){return".priority"}}const ke=new PriorityIndex;const Ne=Math.log(2);class Base12Num{constructor(e){const logBase2=e=>parseInt(Math.log(e)/Ne,10);const bitMask=e=>parseInt(Array(e+1).join("1"),2);this.count=logBase2(e+1);this.current_=this.count-1;const t=bitMask(this.count);this.bits_=e+1&t}nextBitIsOne(){const e=!(this.bits_&1<<this.current_);this.current_--;return e}}const buildChildSet=function(e,t,n,r){e.sort(t);const buildBalancedTree=function(t,r){const i=r-t;let s;let o;if(i===0){return null}else if(i===1){s=e[t];o=n?n(s):s;return new LLRBNode(o,s.node,LLRBNode.BLACK,null,null)}else{const a=parseInt(i/2,10)+t;const c=buildBalancedTree(t,a);const l=buildBalancedTree(a+1,r);s=e[a];o=n?n(s):s;return new LLRBNode(o,s.node,LLRBNode.BLACK,c,l)}};const buildFrom12Array=function(t){let r=null;let i=null;let s=e.length;const buildPennant=function(t,r){const i=s-t;const o=s;s-=t;const a=buildBalancedTree(i+1,o);const c=e[i];const l=n?n(c):c;attachPennant(new LLRBNode(l,c.node,r,null,a))};const attachPennant=function(e){if(r){r.left=e;r=e}else{i=e;r=e}};for(let e=0;e<t.count;++e){const n=t.nextBitIsOne();const r=Math.pow(2,t.count-(e+1));if(n){buildPennant(r,LLRBNode.BLACK)}else{buildPennant(r,LLRBNode.BLACK);buildPennant(r,LLRBNode.RED)}}return i};const i=new Base12Num(e.length);const s=buildFrom12Array(i);return new SortedMap(r||t,s)};let Oe;const De={};class IndexMap{static get Default(){o.assert(De&&ke,"ChildrenNode.ts has not been loaded");Oe=Oe||new IndexMap({".priority":De},{".priority":ke});return Oe}constructor(e,t){this.indexes_=e;this.indexSet_=t}get(e){const t=o.safeGet(this.indexes_,e);if(!t){throw new Error("No index defined for "+e)}if(t instanceof SortedMap){return t}else{return null}}hasIndex(e){return o.contains(this.indexSet_,e.toString())}addIndex(e,t){o.assert(e!==Pe,"KeyIndex always exists and isn't meant to be added to the IndexMap.");const n=[];let r=false;const i=t.getIterator(NamedNode.Wrap);let s=i.getNext();while(s){r=r||e.isDefinedOn(s.node);n.push(s);s=i.getNext()}let a;if(r){a=buildChildSet(n,e.getCompare())}else{a=De}const c=e.toString();const l={...this.indexSet_};l[c]=e;const u={...this.indexes_};u[c]=a;return new IndexMap(u,l)}addToIndexes(e,t){const n=o.map(this.indexes_,((n,r)=>{const i=o.safeGet(this.indexSet_,r);o.assert(i,"Missing index implementation for "+r);if(n===De){if(i.isDefinedOn(e.node)){const n=[];const r=t.getIterator(NamedNode.Wrap);let s=r.getNext();while(s){if(s.name!==e.name){n.push(s)}s=r.getNext()}n.push(e);return buildChildSet(n,i.getCompare())}else{return De}}
2else{const r=t.get(e.name);let i=n;if(r){i=i.remove(new NamedNode(e.name,r))}return i.insert(e,e.node)}}));return new IndexMap(n,this.indexSet_)}removeFromIndexes(e,t){const n=o.map(this.indexes_,(n=>{if(n===De){return n}else{const r=t.get(e.name);if(r){return n.remove(new NamedNode(e.name,r))}else{return n}}}));return new IndexMap(n,this.indexSet_)}}let Le;class ChildrenNode{static get EMPTY_NODE(){return Le||(Le=new ChildrenNode(new SortedMap(NAME_COMPARATOR),null,IndexMap.Default))}constructor(e,t,n){this.children_=e;this.priorityNode_=t;this.indexMap_=n;this.lazyHash_=null;if(this.priorityNode_){validatePriorityNode(this.priorityNode_)}if(this.children_.isEmpty()){o.assert(!this.priorityNode_||this.priorityNode_.isEmpty(),"An empty node cannot have a priority")}}isLeafNode(){return false}getPriority(){return this.priorityNode_||Le}updatePriority(e){if(this.children_.isEmpty()){return this}else{return new ChildrenNode(this.children_,e,this.indexMap_)}}getImmediateChild(e){if(e===".priority"){return this.getPriority()}else{const t=this.children_.get(e);return t===null?Le:t}}getChild(e){const t=pathGetFront(e);if(t===null){return this}return this.getImmediateChild(t).getChild(pathPopFront(e))}hasChild(e){return this.children_.get(e)!==null}updateImmediateChild(e,t){o.assert(t,"We should always be passing snapshot nodes");if(e===".priority"){return this.updatePriority(t)}else{const n=new NamedNode(e,t);let r,i;if(t.isEmpty()){r=this.children_.remove(e);i=this.indexMap_.removeFromIndexes(n,this.children_)}else{r=this.children_.insert(e,t);i=this.indexMap_.addToIndexes(n,this.children_)}const s=r.isEmpty()?Le:this.priorityNode_;return new ChildrenNode(r,s,i)}}updateChild(e,t){const n=pathGetFront(e);if(n===null){return t}else{o.assert(pathGetFront(e)!==".priority"||pathGetLength(e)===1,".priority must be the last token in a path");const r=this.getImmediateChild(n).updateChild(pathPopFront(e),t);return this.updateImmediateChild(n,r)}}isEmpty(){return this.children_.isEmpty()}numChildren(){return this.children_.count()}val(e){if(this.isEmpty()){return null}const t={};let n=0,r=0,i=true;this.forEachChild(ke,((s,o)=>{t[s]=o.val(e);n++;if(i&&ChildrenNode.INTEGER_REGEXP_.test(s)){r=Math.max(r,Number(s))}else{i=false}}));if(!e&&i&&r<2*n){const e=[];for(const n in t){e[n]=t[n]}return e}else{if(e&&!this.getPriority().isEmpty()){t[".priority"]=this.getPriority().val()}return t}}hash(){if(this.lazyHash_===null){let e="";if(!this.getPriority().isEmpty()){e+="priority:"+priorityHashText(this.getPriority().val())+":"}this.forEachChild(ke,((t,n)=>{const r=n.hash();if(r!==""){e+=":"+t+":"+r}}));this.lazyHash_=e===""?"":sha1(e)}return this.lazyHash_}getPredecessorChildName(e,t,n){const r=this.resolveIndex_(n);if(r){const n=r.getPredecessorKey(new NamedNode(e,t));return n?n.name:null}else{return this.children_.getPredecessorKey(e)}}getFirstChildName(e){const t=this.resolveIndex_(e);if(t){const e=t.minKey();return e&&e.name}else{return this.children_.minKey()}}getFirstChild(e){const t=this.getFirstChildName(e);if(t){return new NamedNode(t,this.children_.get(t))}else{return null}}getLastChildName(e){const t=this.resolveIndex_(e);if(t){const e=t.maxKey();return e&&e.name}else{return this.children_.maxKey()}}getLastChild(e){const t=this.getLastChildName(e);if(t){return new NamedNode(t,this.children_.get(t))}else{return null}}forEachChild(e,t){const n=this.resolveIndex_(e);if(n){return n.inorderTraversal((e=>t(e.name,e.node)))}else{return this.children_.inorderTraversal(t)}}getIterator(e){return this.getIteratorFrom(e.minPost(),e)}getIteratorFrom(e,t){const n=this.resolveIndex_(t);if(n){return n.getIteratorFrom(e,(e=>e))}else{const n=this.children_.getIteratorFrom(e.name,NamedNode.Wrap);let r=n.peek();while(r!=null&&t.compare(r,e)<0){n.getNext();r=n.peek()}return n}}getReverseIterator(e){return this.getReverseIteratorFrom(e.maxPost(),e)}getReverseIteratorFrom(e,t){const n=this.resolveIndex_(t);if(n){return n.getReverseIteratorFrom(e,(e=>e))}else{const n=this.children_.getReverseIteratorFrom(e.name,NamedNode.Wrap);let r=n.peek();while(r!=null&&t.compare(r,e)>0){n.getNext();r=n.peek()}return n}}compareTo(e){if(this.isEmpty()){if(e.isEmpty()){return 0}else{return-1}}else if(e.isLeafNode()||e.isEmpty()){return 1}else if(e===Me){return-1}else{return 0}}withIndex(e){if(e===Pe||this.indexMap_.hasIndex(e)){return this}else{const t=this.indexMap_.addIndex(e,this.children_);return new ChildrenNode(this.children_,this.priorityNode_,t)}}isIndexed(e){return e===Pe||this.indexMap_.hasIndex(e)}equals(e){if(e===this){return true}else if(e.isLeafNode()){return false}else{const t=e;
2if(!this.getPriority().equals(t.getPriority())){return false}else if(this.children_.count()===t.children_.count()){const e=this.getIterator(ke);const n=t.getIterator(ke);let r=e.getNext();let i=n.getNext();while(r&&i){if(r.name!==i.name||!r.node.equals(i.node)){return false}r=e.getNext();i=n.getNext()}return r===null&&i===null}else{return false}}}resolveIndex_(e){if(e===Pe){return null}else{return this.indexMap_.get(e.toString())}}}ChildrenNode.INTEGER_REGEXP_=/^(0|[1-9]\d*)$/;class MaxNode extends ChildrenNode{constructor(){super(new SortedMap(NAME_COMPARATOR),ChildrenNode.EMPTY_NODE,IndexMap.Default)}compareTo(e){if(e===this){return 0}else{return 1}}equals(e){return e===this}getPriority(){return this}getImmediateChild(e){return ChildrenNode.EMPTY_NODE}isEmpty(){return false}}const Me=new MaxNode;Object.defineProperties(NamedNode,{MIN:{value:new NamedNode(_,ChildrenNode.EMPTY_NODE)},MAX:{value:new NamedNode(v,Me)}});KeyIndex.__EMPTY_NODE=ChildrenNode.EMPTY_NODE;LeafNode.__childrenNodeConstructor=ChildrenNode;setMaxNode$1(Me);setMaxNode(Me);const Fe=true;function nodeFromJSON(e,t=null){if(e===null){return ChildrenNode.EMPTY_NODE}if(typeof e==="object"&&".priority"in e){t=e[".priority"]}o.assert(t===null||typeof t==="string"||typeof t==="number"||typeof t==="object"&&".sv"in t,"Invalid priority type found: "+typeof t);if(typeof e==="object"&&".value"in e&&e[".value"]!==null){e=e[".value"]}if(typeof e!=="object"||".sv"in e){const n=e;return new LeafNode(n,nodeFromJSON(t))}if(!(e instanceof Array)&&Fe){const n=[];let r=false;const i=e;each(i,((e,t)=>{if(e.substring(0,1)!=="."){const i=nodeFromJSON(t);if(!i.isEmpty()){r=r||!i.getPriority().isEmpty();n.push(new NamedNode(e,i))}}}));if(n.length===0){return ChildrenNode.EMPTY_NODE}const s=buildChildSet(n,NAME_ONLY_COMPARATOR,(e=>e.name),NAME_COMPARATOR);if(r){const e=buildChildSet(n,ke.getCompare());return new ChildrenNode(s,nodeFromJSON(t),new IndexMap({".priority":e},{".priority":ke}))}else{return new ChildrenNode(s,nodeFromJSON(t),IndexMap.Default)}}else{let n=ChildrenNode.EMPTY_NODE;each(e,((t,r)=>{if(o.contains(e,t)){if(t.substring(0,1)!=="."){const e=nodeFromJSON(r);if(e.isLeafNode()||!e.isEmpty()){n=n.updateImmediateChild(t,e)}}}}));return n.updatePriority(nodeFromJSON(t))}}setNodeFromJSON(nodeFromJSON);class PathIndex extends Index{constructor(e){super();this.indexPath_=e;o.assert(!pathIsEmpty(e)&&pathGetFront(e)!==".priority","Can't create PathIndex with empty path or .priority key")}extractChild(e){return e.getChild(this.indexPath_)}isDefinedOn(e){return!e.getChild(this.indexPath_).isEmpty()}compare(e,t){const n=this.extractChild(e.node);const r=this.extractChild(t.node);const i=n.compareTo(r);if(i===0){return nameCompare(e.name,t.name)}else{return i}}makePost(e,t){const n=nodeFromJSON(e);const r=ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_,n);return new NamedNode(t,r)}maxPost(){const e=ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_,Me);return new NamedNode(v,e)}toString(){return pathSlice(this.indexPath_,0).join("/")}}class ValueIndex extends Index{compare(e,t){const n=e.node.compareTo(t.node);if(n===0){return nameCompare(e.name,t.name)}else{return n}}isDefinedOn(e){return true}indexedValueChanged(e,t){return!e.equals(t)}minPost(){return NamedNode.MIN}maxPost(){return NamedNode.MAX}makePost(e,t){const n=nodeFromJSON(e);return new NamedNode(t,n)}toString(){return".value"}}const Ue=new ValueIndex;function changeValue(e){return{type:"value",snapshotNode:e}}function changeChildAdded(e,t){return{type:"child_added",snapshotNode:t,childName:e}}function changeChildRemoved(e,t){return{type:"child_removed",snapshotNode:t,childName:e}}function changeChildChanged(e,t,n){return{type:"child_changed",snapshotNode:t,childName:e,oldSnap:n}}function changeChildMoved(e,t){return{type:"child_moved",snapshotNode:t,childName:e}}class IndexedFilter{constructor(e){this.index_=e}updateChild(e,t,n,r,i,s){o.assert(e.isIndexed(this.index_),"A node must be indexed if only a child is updated");const a=e.getImmediateChild(t);if(a.getChild(r).equals(n.getChild(r))){if(a.isEmpty()===n.isEmpty()){return e}}if(s!=null){if(n.isEmpty()){if(e.hasChild(t)){s.trackChildChange(c
2hangeChildRemoved(t,a))}else{o.assert(e.isLeafNode(),"A child remove without an old child only makes sense on a leaf node")}}else if(a.isEmpty()){s.trackChildChange(changeChildAdded(t,n))}else{s.trackChildChange(changeChildChanged(t,n,a))}}if(e.isLeafNode()&&n.isEmpty()){return e}else{return e.updateImmediateChild(t,n).withIndex(this.index_)}}updateFullNode(e,t,n){if(n!=null){if(!e.isLeafNode()){e.forEachChild(ke,((e,r)=>{if(!t.hasChild(e)){n.trackChildChange(changeChildRemoved(e,r))}}))}if(!t.isLeafNode()){t.forEachChild(ke,((t,r)=>{if(e.hasChild(t)){const i=e.getImmediateChild(t);if(!i.equals(r)){n.trackChildChange(changeChildChanged(t,r,i))}}else{n.trackChildChange(changeChildAdded(t,r))}}))}}return t.withIndex(this.index_)}updatePriority(e,t){if(e.isEmpty()){return ChildrenNode.EMPTY_NODE}else{return e.updatePriority(t)}}filtersNodes(){return false}getIndexedFilter(){return this}getIndex(){return this.index_}}class RangedFilter{constructor(e){this.indexedFilter_=new IndexedFilter(e.getIndex());this.index_=e.getIndex();this.startPost_=RangedFilter.getStartPost_(e);this.endPost_=RangedFilter.getEndPost_(e);this.startIsInclusive_=!e.startAfterSet_;this.endIsInclusive_=!e.endBeforeSet_}getStartPost(){return this.startPost_}getEndPost(){return this.endPost_}matches(e){const t=this.startIsInclusive_?this.index_.compare(this.getStartPost(),e)<=0:this.index_.compare(this.getStartPost(),e)<0;const n=this.endIsInclusive_?this.index_.compare(e,this.getEndPost())<=0:this.index_.compare(e,this.getEndPost())<0;return t&&n}updateChild(e,t,n,r,i,s){if(!this.matches(new NamedNode(t,n))){n=ChildrenNode.EMPTY_NODE}return this.indexedFilter_.updateChild(e,t,n,r,i,s)}updateFullNode(e,t,n){if(t.isLeafNode()){t=ChildrenNode.EMPTY_NODE}let r=t.withIndex(this.index_);r=r.updatePriority(ChildrenNode.EMPTY_NODE);const i=this;t.forEachChild(ke,((e,t)=>{if(!i.matches(new NamedNode(e,t))){r=r.updateImmediateChild(e,ChildrenNode.EMPTY_NODE)}}));return this.indexedFilter_.updateFullNode(e,r,n)}updatePriority(e,t){return e}filtersNodes(){return true}getIndexedFilter(){return this.indexedFilter_}getIndex(){return this.index_}static getStartPost_(e){if(e.hasStart()){const t=e.getIndexStartName();return e.getIndex().makePost(e.getIndexStartValue(),t)}else{return e.getIndex().minPost()}}static getEndPost_(e){if(e.hasEnd()){const t=e.getIndexEndName();return e.getIndex().makePost(e.getIndexEndValue(),t)}else{return e.getIndex().maxPost()}}}class LimitedFilter{constructor(e){this.withinDirectionalStart=e=>this.reverse_?this.withinEndPost(e):this.withinStartPost(e);this.withinDirectionalEnd=e=>this.reverse_?this.withinStartPost(e):this.withinEndPost(e);this.withinStartPost=e=>{const t=this.index_.compare(this.rangedFilter_.getStartPost(),e);return this.startIsInclusive_?t<=0:t<0};this.withinEndPost=e=>{const t=this.index_.compare(e,this.rangedFilter_.getEndPost());return this.endIsInclusive_?t<=0:t<0};this.rangedFilter_=new RangedFilter(e);this.index_=e.getIndex();this.limit_=e.getLimit();this.reverse_=!e.isViewFromLeft();this.startIsInclusive_=!e.startAfterSet_;this.endIsInclusive_=!e.endBeforeSet_}updateChild(e,t,n,r,i,s){if(!this.rangedFilter_.matches(new NamedNode(t,n))){n=ChildrenNode.EMPTY_NODE}if(e.getImmediateChild(t).equals(n)){return e}else if(e.numChildren()<this.limit_){return this.rangedFilter_.getIndexedFilter().updateChild(e,t,n,r,i,s)}else{return this.fullLimitUpdateChild_(e,t,n,i,s)}}updateFullNode(e,t,n){let r;if(t.isLeafNode()||t.isEmpty()){r=ChildrenNode.EMPTY_NODE.withIndex(this.index_)}else{if(this.limit_*2<t.numChildren()&&t.isIndexed(this.index_)){r=ChildrenNode.EMPTY_NODE.withIndex(this.index_);let e;if(this.reverse_){e=t.getReverseIteratorFrom(this.rangedFilter_.getEndPost(),this.index_)}else{e=t.getIteratorFrom(this.rangedFilter_.getStartPost(),this.index_)}let n=0;while(e.hasNext()&&n<this.limit_){const t=e.getNext();if(!this.withinDirectionalStart(t)){continue}else if(!this.withinDirectionalEnd(t)){break}else{r=r.updateImmediateChild(t.name,t.node);n++}}}else{r=t.withIndex(this.index_);r=r.updatePriority(ChildrenNode.EMPTY_NODE);let e;if(this.reverse_){e=r.getReverseIterator(this.index_)}else{e=r.getIterator(this.index_)}let n=0;while(e.hasNext()){const t=e.getNext();const i=n<this.limit_&&this.withinDirectionalStart(t)&&this.withinDirectionalEnd(t);if(i){n++}else{r=r.updateImmediateChild(t.name,ChildrenNode.EMPTY_NODE)}}}}return this.rangedFilter_.getIndexedFilter().updateFullNode(e,r,n)}updatePriority(e,t){return e}filtersNodes(){return true}getIndexedFilter(){return this.rangedFilter_.getIndexedFilter()}getIndex(){return this.index_}
2fullLimitUpdateChild_(e,t,n,r,i){let s;if(this.reverse_){const e=this.index_.getCompare();s=(t,n)=>e(n,t)}else{s=this.index_.getCompare()}const a=e;o.assert(a.numChildren()===this.limit_,"");const c=new NamedNode(t,n);const l=this.reverse_?a.getFirstChild(this.index_):a.getLastChild(this.index_);const u=this.rangedFilter_.matches(c);if(a.hasChild(t)){const e=a.getImmediateChild(t);let o=r.getChildAfterChild(this.index_,l,this.reverse_);while(o!=null&&(o.name===t||a.hasChild(o.name))){o=r.getChildAfterChild(this.index_,o,this.reverse_)}const d=o==null?1:s(o,c);const h=u&&!n.isEmpty()&&d>=0;if(h){if(i!=null){i.trackChildChange(changeChildChanged(t,n,e))}return a.updateImmediateChild(t,n)}else{if(i!=null){i.trackChildChange(changeChildRemoved(t,e))}const n=a.updateImmediateChild(t,ChildrenNode.EMPTY_NODE);const r=o!=null&&this.rangedFilter_.matches(o);if(r){if(i!=null){i.trackChildChange(changeChildAdded(o.name,o.node))}return n.updateImmediateChild(o.name,o.node)}else{return n}}}else if(n.isEmpty()){return e}else if(u){if(s(l,c)>=0){if(i!=null){i.trackChildChange(changeChildRemoved(l.name,l.node));i.trackChildChange(changeChildAdded(t,n))}return a.updateImmediateChild(t,n).updateImmediateChild(l.name,ChildrenNode.EMPTY_NODE)}else{return e}}else{return e}}}class QueryParams{constructor(){this.limitSet_=false;this.startSet_=false;this.startNameSet_=false;this.startAfterSet_=false;this.endSet_=false;this.endNameSet_=false;this.endBeforeSet_=false;this.limit_=0;this.viewFrom_="";this.indexStartValue_=null;this.indexStartName_="";this.indexEndValue_=null;this.indexEndName_="";this.index_=ke}hasStart(){return this.startSet_}isViewFromLeft(){if(this.viewFrom_===""){return this.startSet_}else{return this.viewFrom_==="l"}}getIndexStartValue(){o.assert(this.startSet_,"Only valid if start has been set");return this.indexStartValue_}getIndexStartName(){o.assert(this.startSet_,"Only valid if start has been set");if(this.startNameSet_){return this.indexStartName_}else{return _}}hasEnd(){return this.endSet_}getIndexEndValue(){o.assert(this.endSet_,"Only valid if end has been set");return this.indexEndValue_}getIndexEndName(){o.assert(this.endSet_,"Only valid if end has been set");if(this.endNameSet_){return this.indexEndName_}else{return v}}hasLimit(){return this.limitSet_}hasAnchoredLimit(){return this.limitSet_&&this.viewFrom_!==""}getLimit(){o.assert(this.limitSet_,"Only valid if limit has been set");return this.limit_}getIndex(){return this.index_}loadsAllData(){return!(this.startSet_||this.endSet_||this.limitSet_)}isDefault(){return this.loadsAllData()&&this.index_===ke}copy(){const e=new QueryParams;e.limitSet_=this.limitSet_;e.limit_=this.limit_;e.startSet_=this.startSet_;e.startAfterSet_=this.startAfterSet_;e.indexStartValue_=this.indexStartValue_;e.startNameSet_=this.startNameSet_;e.indexStartName_=this.indexStartName_;e.endSet_=this.endSet_;e.endBeforeSet_=this.endBeforeSet_;e.indexEndValue_=this.indexEndValue_;e.endNameSet_=this.endNameSet_;e.indexEndName_=this.indexEndName_;e.index_=this.index_;e.viewFrom_=this.viewFrom_;return e}}function queryParamsGetNodeFilter(e){if(e.loadsAllData()){return new IndexedFilter(e.getIndex())}else if(e.hasLimit()){return new LimitedFilter(e)}else{return new RangedFilter(e)}}function queryParamsLimitToFirst(e,t){const n=e.copy();n.limitSet_=true;n.limit_=t;n.viewFrom_="l";return n}function queryParamsLimitToLast(e,t){const n=e.copy();n.limitSet_=true;n.limit_=t;n.viewFrom_="r";return n}function queryParamsStartAt(e,t,n){const r=e.copy();r.startSet_=true;if(t===undefined){t=null}r.indexStartValue_=t;if(n!=null){r.startNameSet_=true;r.indexStartName_=n}else{r.startNameSet_=false;r.indexStartName_=""}return r}function queryParamsStartAfter(e,t,n){let r;if(e.index_===Pe||!!n){r=queryParamsStartAt(e,t,n)}else{r=queryParamsStartAt(e,t,v)}r.startAfterSet_=true;return r}function queryParamsEndAt(e,t,n){const r=e.copy();r.endSet_=true;if(t===undefined){t=null}r.indexEndValue_=t;if(n!==undefined){r.endNameSet_=true;r.indexEndName_=n}else{r.endNameSet_=false;r.indexEndName_=""}return r}function queryParamsEndBefore(e,t,n){let r;
2if(e.index_===Pe||!!n){r=queryParamsEndAt(e,t,n)}else{r=queryParamsEndAt(e,t,_)}r.endBeforeSet_=true;return r}function queryParamsOrderBy(e,t){const n=e.copy();n.index_=t;return n}function queryParamsToRestQueryStringParameters(e){const t={};if(e.isDefault()){return t}let n;if(e.index_===ke){n="$priority"}else if(e.index_===Ue){n="$value"}else if(e.index_===Pe){n="$key"}else{o.assert(e.index_ instanceof PathIndex,"Unrecognized index type!");n=e.index_.toString()}t["orderBy"]=o.stringify(n);if(e.startSet_){const n=e.startAfterSet_?"startAfter":"startAt";t[n]=o.stringify(e.indexStartValue_);if(e.startNameSet_){t[n]+=","+o.stringify(e.indexStartName_)}}if(e.endSet_){const n=e.endBeforeSet_?"endBefore":"endAt";t[n]=o.stringify(e.indexEndValue_);if(e.endNameSet_){t[n]+=","+o.stringify(e.indexEndName_)}}if(e.limitSet_){if(e.isViewFromLeft()){t["limitToFirst"]=e.limit_}else{t["limitToLast"]=e.limit_}}return t}function queryParamsGetQueryObject(e){const t={};if(e.startSet_){t["sp"]=e.indexStartValue_;if(e.startNameSet_){t["sn"]=e.indexStartName_}t["sin"]=!e.startAfterSet_}if(e.endSet_){t["ep"]=e.indexEndValue_;if(e.endNameSet_){t["en"]=e.indexEndName_}t["ein"]=!e.endBeforeSet_}if(e.limitSet_){t["l"]=e.limit_;let n=e.viewFrom_;if(n===""){if(e.isViewFromLeft()){n="l"}else{n="r"}}t["vf"]=n}if(e.index_!==ke){t["i"]=e.index_.toString()}return t}class ReadonlyRestClient extends ServerActions{reportStats(e){throw new Error("Method not implemented.")}static getListenId_(e,t){if(t!==undefined){return"tag$"+t}else{o.assert(e._queryParams.isDefault(),"should have a tag if it's not a default query.");return e._path.toString()}}constructor(e,t,n,r){super();this.repoInfo_=e;this.onDataUpdate_=t;this.authTokenProvider_=n;this.appCheckTokenProvider_=r;this.log_=logWrapper("p:rest:");this.listens_={}}listen(e,t,n,r){const i=e._path.toString();this.log_("Listen called for "+i+" "+e._queryIdentifier);const s=ReadonlyRestClient.getListenId_(e,n);const a={};this.listens_[s]=a;const c=queryParamsToRestQueryStringParameters(e._queryParams);this.restRequest_(i+".json",c,((e,t)=>{let c=t;if(e===404){c=null;e=null}if(e===null){this.onDataUpdate_(i,c,false,n)}if(o.safeGet(this.listens_,s)===a){let t;if(!e){t="ok"}else if(e===401){t="permission_denied"}else{t="rest_error:"+e}r(t,null)}}))}unlisten(e,t){const n=ReadonlyRestClient.getListenId_(e,t);delete this.listens_[n]}get(e){const t=queryParamsToRestQueryStringParameters(e._queryParams);const n=e._path.toString();const r=new o.Deferred;this.restRequest_(n+".json",t,((e,t)=>{let i=t;if(e===404){i=null;e=null}if(e===null){this.onDataUpdate_(n,i,false,null);r.resolve(i)}else{r.reject(new Error(i))}}));return r.promise}refreshAuthToken(e){}restRequest_(e,t={},n){t["format"]="export";return Promise.all([this.authTokenProvider_.getToken(false),this.appCheckTokenProvider_.getToken(false)]).then((([r,i])=>{if(r&&r.accessToken){t["auth"]=r.accessToken}if(i&&i.token){t["ac"]=i.token}const s=(this.repoInfo_.secure?"https://":"http://")+this.repoInfo_.host+e+"?"+"ns="+this.repoInfo_.namespace+o.querystring(t);this.log_("Sending REST request for "+s);const a=new XMLHttpRequest;a.onreadystatechange=()=>{if(n&&a.readyState===4){this.log_("REST Response for "+s+" received. status:",a.status,"response:",a.responseText);let e=null;if(a.status>=200&&a.status<300){try{e=o.jsonEval(a.responseText)}catch(e){warn("Failed to parse JSON response for "+s+": "+a.responseText)}n(null,e)}else{if(a.status!==401&&a.status!==404){warn("Got unsuccessful REST response for "+s+" Status: "+a.status)}n(a.status)}n=null}};a.open("GET",s,true);a.send()}))}}class SnapshotHolder{constructor(){this.rootNode_=ChildrenNode.EMPTY_NODE}getNode(e){return this.rootNode_.getChild(e)}updateSnapshot(e,t){this.rootNode_=this.rootNode_.updateChild(e,t)}}function newSparseSnapshotTree(){return{value:null,children:new Map}}function sparseSnapshotTreeRemember(e,t,n){if(pathIsEmpty(t)){e.value=n;e.children.clear()}else if(e.value!==null){e.value=e.value.updateChild(t,n)}else{const r=pathGetFront(t);if(!e.children.has(r)){e.children.set(r,newSparseSnapshotTree())}const i=e.children.get(r);t=pathPopFront(t);sparseSnapshotTreeRemember(i,t,n)}}function sparseSnapshotTreeForget(e,t){if(pathIsEmpty(t)){e.value=null;e.children.clear();return true}else{if(e.value!==null){if(e.value.isLeafNode()){return false}else{const n=e.value;e.value=null;
2n.forEachChild(ke,((t,n)=>{sparseSnapshotTreeRemember(e,new Path(t),n)}));return sparseSnapshotTreeForget(e,t)}}else if(e.children.size>0){const n=pathGetFront(t);t=pathPopFront(t);if(e.children.has(n)){const r=sparseSnapshotTreeForget(e.children.get(n),t);if(r){e.children.delete(n)}}return e.children.size===0}else{return true}}}function sparseSnapshotTreeForEachTree(e,t,n){if(e.value!==null){n(t,e.value)}else{sparseSnapshotTreeForEachChild(e,((e,r)=>{const i=new Path(t.toString()+"/"+e);sparseSnapshotTreeForEachTree(r,i,n)}))}}function sparseSnapshotTreeForEachChild(e,t){e.children.forEach(((e,n)=>{t(n,e)}))}class StatsListener{constructor(e){this.collection_=e;this.last_=null}get(){const e=this.collection_.get();const t={...e};if(this.last_){each(this.last_,((e,n)=>{t[e]=t[e]-n}))}this.last_=e;return t}}const xe=10*1e3;const We=30*1e3;const Ve=5*60*1e3;class StatsReporter{constructor(e,t){this.server_=t;this.statsToReport_={};this.statsListener_=new StatsListener(e);const n=xe+(We-xe)*Math.random();setTimeoutNonBlocking(this.reportStats_.bind(this),Math.floor(n))}reportStats_(){const e=this.statsListener_.get();const t={};let n=false;each(e,((e,r)=>{if(r>0&&o.contains(this.statsToReport_,e)){t[e]=r;n=true}}));if(n){this.server_.reportStats(t)}setTimeoutNonBlocking(this.reportStats_.bind(this),Math.floor(Math.random()*2*Ve))}}var qe;(function(e){e[e["OVERWRITE"]=0]="OVERWRITE";e[e["MERGE"]=1]="MERGE";e[e["ACK_USER_WRITE"]=2]="ACK_USER_WRITE";e[e["LISTEN_COMPLETE"]=3]="LISTEN_COMPLETE"})(qe||(qe={}));function newOperationSourceUser(){return{fromUser:true,fromServer:false,queryId:null,tagged:false}}function newOperationSourceServer(){return{fromUser:false,fromServer:true,queryId:null,tagged:false}}function newOperationSourceServerTaggedQuery(e){return{fromUser:false,fromServer:true,queryId:e,tagged:true}}class AckUserWrite{constructor(e,t,n){this.path=e;this.affectedTree=t;this.revert=n;this.type=qe.ACK_USER_WRITE;this.source=newOperationSourceUser()}operationForChild(e){if(!pathIsEmpty(this.path)){o.assert(pathGetFront(this.path)===e,"operationForChild called for unrelated child.");return new AckUserWrite(pathPopFront(this.path),this.affectedTree,this.revert)}else if(this.affectedTree.value!=null){o.assert(this.affectedTree.children.isEmpty(),"affectedTree should not have overlapping affected paths.");return this}else{const t=this.affectedTree.subtree(new Path(e));return new AckUserWrite(newEmptyPath(),t,this.revert)}}}class ListenComplete{constructor(e,t){this.source=e;this.path=t;this.type=qe.LISTEN_COMPLETE}operationForChild(e){if(pathIsEmpty(this.path)){return new ListenComplete(this.source,newEmptyPath())}else{return new ListenComplete(this.source,pathPopFront(this.path))}}}class Overwrite{constructor(e,t,n){this.source=e;this.path=t;this.snap=n;this.type=qe.OVERWRITE}operationForChild(e){if(pathIsEmpty(this.path)){return new Overwrite(this.source,newEmptyPath(),this.snap.getImmediateChild(e))}else{return new Overwrite(this.source,pathPopFront(this.path),this.snap)}}}class Merge{constructor(e,t,n){this.source=e;this.path=t;this.children=n;this.type=qe.MERGE}operationForChild(e){if(pathIsEmpty(this.path)){const t=this.children.subtree(new Path(e));if(t.isEmpty()){return null}else if(t.value){return new Overwrite(this.source,newEmptyPath(),t.value)}else{return new Merge(this.source,newEmptyPath(),t)}}else{o.assert(pathGetFront(this.path)===e,"Can't get a merge for a child not on the path of the operation");return new Merge(this.source,pathPopFront(this.path),this.children)}}toString(){return"Operation("+this.path+": "+this.source.toString()+" merge: "+this.children.toString()+")"}}class CacheNode{constructor(e,t,n){this.node_=e;this.fullyInitialized_=t;this.filtered_=n}isFullyInitialized(){return this.fullyInitialized_}isFiltered(){return this.filtered_}isCompleteForPath(e){if(pathIsEmpty(e)){return this.isFullyInitialized()&&!this.filtered_}const t=pathGetFront(e);return this.isCompleteForChild(t)}isCompleteForChild(e){return this.isFullyInitialized()&&!this.filtered_||this.node_.hasChild(e)}getNode(){return this.node_}}class EventGenerator{constructor(e){this.query_=e;this.index_=this.query_._queryParams.getIndex()}}function eventGeneratorGenerateEventsForChanges(e,t,n,r){const i=[];const s=[];t.forEach((t=>{if(t.type==="child_changed"&&e.index_.indexedValueChanged(t.oldSnap,t.snapshotNode)){s.push(changeChildMoved(t.childName,t.snapshotNode))}}));eventGeneratorGenerateEventsForType(e,i,"child_removed",t,r,n);eventGeneratorGenerateEventsForType(e,i,"child_added",t,r,n);eventGeneratorGenerateEventsForType(e,i,"child_moved",s,r,n);eventGeneratorGenerateEventsForType(e,i,"child_changed",t,r,n);eventGeneratorGenerateEventsForType(e,i,"value",t,r,n);return i}function eventGeneratorGenerateEventsForType(e,t,n,r,i,s){const o=r.filter((e=>e.type===n));o.sort(((t,n)=>
2eventGeneratorCompareChanges(e,t,n)));o.forEach((n=>{const r=eventGeneratorMaterializeSingleChange(e,n,s);i.forEach((i=>{if(i.respondsTo(n.type)){t.push(i.createEvent(r,e.query_))}}))}))}function eventGeneratorMaterializeSingleChange(e,t,n){if(t.type==="value"||t.type==="child_removed"){return t}else{t.prevName=n.getPredecessorChildName(t.childName,t.snapshotNode,e.index_);return t}}function eventGeneratorCompareChanges(e,t,n){if(t.childName==null||n.childName==null){throw o.assertionError("Should only compare child_ events.")}const r=new NamedNode(t.childName,t.snapshotNode);const i=new NamedNode(n.childName,n.snapshotNode);return e.index_.compare(r,i)}function newViewCache(e,t){return{eventCache:e,serverCache:t}}function viewCacheUpdateEventSnap(e,t,n,r){return newViewCache(new CacheNode(t,n,r),e.serverCache)}function viewCacheUpdateServerSnap(e,t,n,r){return newViewCache(e.eventCache,new CacheNode(t,n,r))}function viewCacheGetCompleteEventSnap(e){return e.eventCache.isFullyInitialized()?e.eventCache.getNode():null}function viewCacheGetCompleteServerSnap(e){return e.serverCache.isFullyInitialized()?e.serverCache.getNode():null}let Ge;const EmptyChildren=()=>{if(!Ge){Ge=new SortedMap(stringCompare)}return Ge};class ImmutableTree{static fromObject(e){let t=new ImmutableTree(null);each(e,((e,n)=>{t=t.set(new Path(e),n)}));return t}constructor(e,t=EmptyChildren()){this.value=e;this.children=t}isEmpty(){return this.value===null&&this.children.isEmpty()}findRootMostMatchingPathAndValue(e,t){if(this.value!=null&&t(this.value)){return{path:newEmptyPath(),value:this.value}}else{if(pathIsEmpty(e)){return null}else{const n=pathGetFront(e);const r=this.children.get(n);if(r!==null){const i=r.findRootMostMatchingPathAndValue(pathPopFront(e),t);if(i!=null){const e=pathChild(new Path(n),i.path);return{path:e,value:i.value}}else{return null}}else{return null}}}}findRootMostValueAndPath(e){return this.findRootMostMatchingPathAndValue(e,(()=>true))}subtree(e){if(pathIsEmpty(e)){return this}else{const t=pathGetFront(e);const n=this.children.get(t);if(n!==null){return n.subtree(pathPopFront(e))}else{return new ImmutableTree(null)}}}set(e,t){if(pathIsEmpty(e)){return new ImmutableTree(t,this.children)}else{const n=pathGetFront(e);const r=this.children.get(n)||new ImmutableTree(null);const i=r.set(pathPopFront(e),t);const s=this.children.insert(n,i);return new ImmutableTree(this.value,s)}}remove(e){if(pathIsEmpty(e)){if(this.children.isEmpty()){return new ImmutableTree(null)}else{return new ImmutableTree(null,this.children)}}else{const t=pathGetFront(e);const n=this.children.get(t);if(n){const r=n.remove(pathPopFront(e));let i;if(r.isEmpty()){i=this.children.remove(t)}else{i=this.children.insert(t,r)}if(this.value===null&&i.isEmpty()){return new ImmutableTree(null)}else{return new ImmutableTree(this.value,i)}}else{return this}}}get(e){if(pathIsEmpty(e)){return this.value}else{const t=pathGetFront(e);const n=this.children.get(t);if(n){return n.get(pathPopFront(e))}else{return null}}}setTree(e,t){if(pathIsEmpty(e)){return t}else{const n=pathGetFront(e);const r=this.children.get(n)||new ImmutableTree(null);const i=r.setTree(pathPopFront(e),t);let s;if(i.isEmpty()){s=this.children.remove(n)}else{s=this.children.insert(n,i)}return new ImmutableTree(this.value,s)}}fold(e){return this.fold_(newEmptyPath(),e)}fold_(e,t){const n={};this.children.inorderTraversal(((r,i)=>{n[r]=i.fold_(pathChild(e,r),t)}));return t(e,this.value,n)}findOnPath(e,t){return this.findOnPath_(e,newEmptyPath(),t)}findOnPath_(e,t,n){const r=this.value?n(t,this.value):false;if(r){return r}else{if(pathIsEmpty(e)){return null}else{const r=pathGetFront(e);const i=this.children.get(r);if(i){return i.findOnPath_(pathPopFront(e),pathChild(t,r),n)}else{return null}}}}foreachOnPath(e,t){return this.foreachOnPath_(e,newEmptyPath(),t)}foreachOnPath_(e,t,n){if(pathIsEmpty(e)){return this}else{if(this.value){n(t,this.value)}const r=pathGetFront(e);const i=this.children.get(r);if(i){return i.foreachOnPath_(pathPopFront(e),pathChild(t,r),n)}else{return new ImmutableTree(null)}}}foreach(e){this.foreach_(newEmptyPath(),e)}foreach_(e,t){this.children.inorderTraversal(((n,r)=>{r.foreach_(pathChild(e,n),t)}));if(this.value){t(e,this.value)}}foreachChild(e){this.children.inorderTraversal(((t,n)=>{if(n.value){e(t,n.value)}}))}}class CompoundWrite{constructor(e){this.writeTree_=e}static empty(){return new CompoundWrite(new ImmutableTree(null))}}function compoundWriteAddWrite(e,t,n){if(pathIsEmpty(t)){return new CompoundWrite(new ImmutableTree(n))}else{const r=e.writeTree_.findRootMostValueAndPath(t);if(r!=null){const i=r.path;let s=r.value;const o=newRelativePath(i,t);s=s.updateChild(o,n);return new CompoundWrite(e.writeTree_.set(i,s))}else{const r=new ImmutableTree(n);const i=e.writeTree_.setTree(t,r);return new CompoundWrite(i)}}}
2function compoundWriteAddWrites(e,t,n){let r=e;each(n,((e,n)=>{r=compoundWriteAddWrite(r,pathChild(t,e),n)}));return r}function compoundWriteRemoveWrite(e,t){if(pathIsEmpty(t)){return CompoundWrite.empty()}else{const n=e.writeTree_.setTree(t,new ImmutableTree(null));return new CompoundWrite(n)}}function compoundWriteHasCompleteWrite(e,t){return compoundWriteGetCompleteNode(e,t)!=null}function compoundWriteGetCompleteNode(e,t){const n=e.writeTree_.findRootMostValueAndPath(t);if(n!=null){return e.writeTree_.get(n.path).getChild(newRelativePath(n.path,t))}else{return null}}function compoundWriteGetCompleteChildren(e){const t=[];const n=e.writeTree_.value;if(n!=null){if(!n.isLeafNode()){n.forEachChild(ke,((e,n)=>{t.push(new NamedNode(e,n))}))}}else{e.writeTree_.children.inorderTraversal(((e,n)=>{if(n.value!=null){t.push(new NamedNode(e,n.value))}}))}return t}function compoundWriteChildCompoundWrite(e,t){if(pathIsEmpty(t)){return e}else{const n=compoundWriteGetCompleteNode(e,t);if(n!=null){return new CompoundWrite(new ImmutableTree(n))}else{return new CompoundWrite(e.writeTree_.subtree(t))}}}function compoundWriteIsEmpty(e){return e.writeTree_.isEmpty()}function compoundWriteApply(e,t){return applySubtreeWrite(newEmptyPath(),e.writeTree_,t)}function applySubtreeWrite(e,t,n){if(t.value!=null){return n.updateChild(e,t.value)}else{let r=null;t.children.inorderTraversal(((t,i)=>{if(t===".priority"){o.assert(i.value!==null,"Priority writes must always be leaf nodes");r=i.value}else{n=applySubtreeWrite(pathChild(e,t),i,n)}}));if(!n.getChild(e).isEmpty()&&r!==null){n=n.updateChild(pathChild(e,".priority"),r)}return n}}function writeTreeChildWrites(e,t){return newWriteTreeRef(t,e)}function writeTreeAddOverwrite(e,t,n,r,i){o.assert(r>e.lastWriteId,"Stacking an older write on top of newer ones");if(i===undefined){i=true}e.allWrites.push({path:t,snap:n,writeId:r,visible:i});if(i){e.visibleWrites=compoundWriteAddWrite(e.visibleWrites,t,n)}e.lastWriteId=r}function writeTreeAddMerge(e,t,n,r){o.assert(r>e.lastWriteId,"Stacking an older merge on top of newer ones");e.allWrites.push({path:t,children:n,writeId:r,visible:true});e.visibleWrites=compoundWriteAddWrites(e.visibleWrites,t,n);e.lastWriteId=r}function writeTreeGetWrite(e,t){for(let n=0;n<e.allWrites.length;n++){const r=e.allWrites[n];if(r.writeId===t){return r}}return null}function writeTreeRemoveWrite(e,t){const n=e.allWrites.findIndex((e=>e.writeId===t));o.assert(n>=0,"removeWrite called with nonexistent writeId.");const r=e.allWrites[n];e.allWrites.splice(n,1);let i=r.visible;let s=false;let a=e.allWrites.length-1;while(i&&a>=0){const t=e.allWrites[a];if(t.visible){if(a>=n&&writeTreeRecordContainsPath_(t,r.path)){i=false}else if(pathContains(r.path,t.path)){s=true}}a--}if(!i){return false}else if(s){writeTreeResetTree_(e);return true}else{if(r.snap){e.visibleWrites=compoundWriteRemoveWrite(e.visibleWrites,r.path)}else{const t=r.children;each(t,(t=>{e.visibleWrites=compoundWriteRemoveWrite(e.visibleWrites,pathChild(r.path,t))}))}return true}}function writeTreeRecordContainsPath_(e,t){if(e.snap){return pathContains(e.path,t)}else{for(const n in e.children){if(e.children.hasOwnProperty(n)&&pathContains(pathChild(e.path,n),t)){return true}}return false}}function writeTreeResetTree_(e){e.visibleWrites=writeTreeLayerTree_(e.allWrites,writeTreeDefaultFilter_,newEmptyPath());if(e.allWrites.length>0){e.lastWriteId=e.allWrites[e.allWrites.length-1].writeId}else{e.lastWriteId=-1}}function writeTreeDefaultFilter_(e){return e.visible}function writeTreeLayerTree_(e,t,n){let r=CompoundWrite.empty();for(let i=0;i<e.length;++i){const s=e[i];if(t(s)){const e=s.path;let t;if(s.snap){if(pathContains(n,e)){t=newRelativePath(n,e);r=compoundWriteAddWrite(r,t,s.snap)}else if(pathContains(e,n)){t=newRelativePath(e,n);r=compoundWriteAddWrite(r,newEmptyPath(),s.snap.getChild(t))}else;}else if(s.children){if(pathContains(n,e)){t=newRelativePath(n,e);r=compoundWriteAddWrites(r,t,s.children)}else if(pathContains(e,n)){t=newRelativePath(e,n);if(pathIsEmpty(t)){r=compoundWriteAddWrites(r,newEmptyPath(),s.children)}else{const e=o.safeGet(s.children,pathGetFront(t));if(e){const n=e.getChild(pathPopFront(t));r=compoundWriteAddWrite(r,newEmptyPath(),n)}}}else;}else{throw o.assertionError("WriteRecord should have .snap or .children")}}}return r}function writeTreeCalcCompleteEventCache(e,t,n,r,i){if(!r&&!i){const r=compoundWriteGetCompleteNode(e.visibleWrites,t);
2if(r!=null){return r}else{const r=compoundWriteChildCompoundWrite(e.visibleWrites,t);if(compoundWriteIsEmpty(r)){return n}else if(n==null&&!compoundWriteHasCompleteWrite(r,newEmptyPath())){return null}else{const e=n||ChildrenNode.EMPTY_NODE;return compoundWriteApply(r,e)}}}else{const s=compoundWriteChildCompoundWrite(e.visibleWrites,t);if(!i&&compoundWriteIsEmpty(s)){return n}else{if(!i&&n==null&&!compoundWriteHasCompleteWrite(s,newEmptyPath())){return null}else{const filter=function(e){return(e.visible||i)&&(!r||!~r.indexOf(e.writeId))&&(pathContains(e.path,t)||pathContains(t,e.path))};const s=writeTreeLayerTree_(e.allWrites,filter,t);const o=n||ChildrenNode.EMPTY_NODE;return compoundWriteApply(s,o)}}}}function writeTreeCalcCompleteEventChildren(e,t,n){let r=ChildrenNode.EMPTY_NODE;const i=compoundWriteGetCompleteNode(e.visibleWrites,t);if(i){if(!i.isLeafNode()){i.forEachChild(ke,((e,t)=>{r=r.updateImmediateChild(e,t)}))}return r}else if(n){const i=compoundWriteChildCompoundWrite(e.visibleWrites,t);n.forEachChild(ke,((e,t)=>{const n=compoundWriteApply(compoundWriteChildCompoundWrite(i,new Path(e)),t);r=r.updateImmediateChild(e,n)}));compoundWriteGetCompleteChildren(i).forEach((e=>{r=r.updateImmediateChild(e.name,e.node)}));return r}else{const n=compoundWriteChildCompoundWrite(e.visibleWrites,t);compoundWriteGetCompleteChildren(n).forEach((e=>{r=r.updateImmediateChild(e.name,e.node)}));return r}}function writeTreeCalcEventCacheAfterServerOverwrite(e,t,n,r,i){o.assert(r||i,"Either existingEventSnap or existingServerSnap must exist");const s=pathChild(t,n);if(compoundWriteHasCompleteWrite(e.visibleWrites,s)){return null}else{const t=compoundWriteChildCompoundWrite(e.visibleWrites,s);if(compoundWriteIsEmpty(t)){return i.getChild(n)}else{return compoundWriteApply(t,i.getChild(n))}}}function writeTreeCalcCompleteChild(e,t,n,r){const i=pathChild(t,n);const s=compoundWriteGetCompleteNode(e.visibleWrites,i);if(s!=null){return s}else{if(r.isCompleteForChild(n)){const t=compoundWriteChildCompoundWrite(e.visibleWrites,i);return compoundWriteApply(t,r.getNode().getImmediateChild(n))}else{return null}}}function writeTreeShadowingWrite(e,t){return compoundWriteGetCompleteNode(e.visibleWrites,t)}function writeTreeCalcIndexedSlice(e,t,n,r,i,s,o){let a;const c=compoundWriteChildCompoundWrite(e.visibleWrites,t);const l=compoundWriteGetCompleteNode(c,newEmptyPath());if(l!=null){a=l}else if(n!=null){a=compoundWriteApply(c,n)}else{return[]}a=a.withIndex(o);if(!a.isEmpty()&&!a.isLeafNode()){const e=[];const t=o.getCompare();const n=s?a.getReverseIteratorFrom(r,o):a.getIteratorFrom(r,o);let c=n.getNext();while(c&&e.length<i){if(t(c,r)!==0){e.push(c)}c=n.getNext()}return e}else{return[]}}function newWriteTree(){return{visibleWrites:CompoundWrite.empty(),allWrites:[],lastWriteId:-1}}function writeTreeRefCalcCompleteEventCache(e,t,n,r){return writeTreeCalcCompleteEventCache(e.writeTree,e.treePath,t,n,r)}function writeTreeRefCalcCompleteEventChildren(e,t){return writeTreeCalcCompleteEventChildren(e.writeTree,e.treePath,t)}function writeTreeRefCalcEventCacheAfterServerOverwrite(e,t,n,r){return writeTreeCalcEventCacheAfterServerOverwrite(e.writeTree,e.treePath,t,n,r)}function writeTreeRefShadowingWrite(e,t){return writeTreeShadowingWrite(e.writeTree,pathChild(e.treePath,t))}function writeTreeRefCalcIndexedSlice(e,t,n,r,i,s){return writeTreeCalcIndexedSlice(e.writeTree,e.treePath,t,n,r,i,s)}function writeTreeRefCalcCompleteChild(e,t,n){return writeTreeCalcCompleteChild(e.writeTree,e.treePath,t,n)}function writeTreeRefChild(e,t){return newWriteTreeRef(pathChild(e.treePath,t),e.writeTree)}function newWriteTreeRef(e,t){return{treePath:e,writeTree:t}}class ChildChangeAccumulator{constructor(){this.changeMap=new Map}trackChildChange(e){const t=e.type;const n=e.childName;o.assert(t==="child_added"||t==="child_changed"||t==="child_removed","Only child changes supported for tracking");o.assert(n!==".priority","Only non-priority child changes can be tracked.");const r=this.changeMap.get(n);if(r){const i=r.type;if(t==="child_added"&&i==="child_removed"){this.changeMap.set(n,changeChildCh
2anged(n,e.snapshotNode,r.snapshotNode))}else if(t==="child_removed"&&i==="child_added"){this.changeMap.delete(n)}else if(t==="child_removed"&&i==="child_changed"){this.changeMap.set(n,changeChildRemoved(n,r.oldSnap))}else if(t==="child_changed"&&i==="child_added"){this.changeMap.set(n,changeChildAdded(n,e.snapshotNode))}else if(t==="child_changed"&&i==="child_changed"){this.changeMap.set(n,changeChildChanged(n,e.snapshotNode,r.oldSnap))}else{throw o.assertionError("Illegal combination of changes: "+e+" occurred after "+r)}}else{this.changeMap.set(n,e)}}getChanges(){return Array.from(this.changeMap.values())}}class NoCompleteChildSource_{getCompleteChild(e){return null}getChildAfterChild(e,t,n){return null}}const Be=new NoCompleteChildSource_;class WriteTreeCompleteChildSource{constructor(e,t,n=null){this.writes_=e;this.viewCache_=t;this.optCompleteServerCache_=n}getCompleteChild(e){const t=this.viewCache_.eventCache;if(t.isCompleteForChild(e)){return t.getNode().getImmediateChild(e)}else{const t=this.optCompleteServerCache_!=null?new CacheNode(this.optCompleteServerCache_,true,false):this.viewCache_.serverCache;return writeTreeRefCalcCompleteChild(this.writes_,e,t)}}getChildAfterChild(e,t,n){const r=this.optCompleteServerCache_!=null?this.optCompleteServerCache_:viewCacheGetCompleteServerSnap(this.viewCache_);const i=writeTreeRefCalcIndexedSlice(this.writes_,r,t,1,n,e);if(i.length===0){return null}else{return i[0]}}}function newViewProcessor(e){return{filter:e}}function viewProcessorAssertIndexed(e,t){o.assert(t.eventCache.getNode().isIndexed(e.filter.getIndex()),"Event snap not indexed");o.assert(t.serverCache.getNode().isIndexed(e.filter.getIndex()),"Server snap not indexed")}function viewProcessorApplyOperation(e,t,n,r,i){const s=new ChildChangeAccumulator;let a,c;if(n.type===qe.OVERWRITE){const l=n;if(l.source.fromUser){a=viewProcessorApplyUserOverwrite(e,t,l.path,l.snap,r,i,s)}else{o.assert(l.source.fromServer,"Unknown source.");c=l.source.tagged||t.serverCache.isFiltered()&&!pathIsEmpty(l.path);a=viewProcessorApplyServerOverwrite(e,t,l.path,l.snap,r,i,c,s)}}else if(n.type===qe.MERGE){const l=n;if(l.source.fromUser){a=viewProcessorApplyUserMerge(e,t,l.path,l.children,r,i,s)}else{o.assert(l.source.fromServer,"Unknown source.");c=l.source.tagged||t.serverCache.isFiltered();a=viewProcessorApplyServerMerge(e,t,l.path,l.children,r,i,c,s)}}else if(n.type===qe.ACK_USER_WRITE){const o=n;if(!o.revert){a=viewProcessorAckUserWrite(e,t,o.path,o.affectedTree,r,i,s)}else{a=viewProcessorRevertUserWrite(e,t,o.path,r,i,s)}}else if(n.type===qe.LISTEN_COMPLETE){a=viewProcessorListenComplete(e,t,n.path,r,s)}else{throw o.assertionError("Unknown operation type: "+n.type)}const l=s.getChanges();viewProcessorMaybeAddValueEvent(t,a,l);return{viewCache:a,changes:l}}function viewProcessorMaybeAddValueEvent(e,t,n){const r=t.eventCache;if(r.isFullyInitialized()){const i=r.getNode().isLeafNode()||r.getNode().isEmpty();const s=viewCacheGetCompleteEventSnap(e);if(n.length>0||!e.eventCache.isFullyInitialized()||i&&!r.getNode().equals(s)||!r.getNode().getPriority().equals(s.getPriority())){n.push(changeValue(viewCacheGetCompleteEventSnap(t)))}}}function viewProcessorGenerateEventCacheAfterServerEvent(e,t,n,r,i,s){const a=t.eventCache;if(writeTreeRefShadowingWrite(r,n)!=null){return t}else{let c,l;if(pathIsEmpty(n)){o.assert(t.serverCache.isFullyInitialized(),"If change path is empty, we must have complete server data");if(t.serverCache.isFiltered()){const n=viewCacheGetCompleteServerSnap(t);const i=n instanceof ChildrenNode?n:ChildrenNode.EMPTY_NODE;const o=writeTreeRefCalcCompleteEventChildren(r,i);c=e.filter.updateFullNode(t.eventCache.getNode(),o,s)}else{const n=writeTreeRefCalcCompleteEventCache(r,viewCacheGetCompleteServerSnap(t));c=e.filter.updateFullNode(t.eventCache.getNode(),n,s)}}else{const u=pathGetFront(n);if(u===".priority"){o.assert(pathGetLength(n)===1,"Can't have a priority with additional path components");const i=a.getNode();l=t.serverCache.getNode();const s=writeTreeRefCalcEventCacheAfterServerOverwrite(r,n,i,l);if(s!=null){c=e.filter.updatePriority(i,s)}else{c=a.getNode()}}else{const o=pathPopFront(n);let d;if(a.isCompleteForChild(u)){l=t.serverCache.getNode();const e=writeTreeRefCalcEventCacheAfterServerOverwrite(r,n,a.getNode(),l);if(e!=null){d=a.getNode().getImmediateChild(u).updateChild(o,e)}else{d=a.getNode().getImmediateChild(u)}}else{d=writeTreeRefCalcCompleteChild(r,u,t.serverCache)}if(d!=null){c=e.filter.updateChild(a.getNode(),u,d,o,i,s)}else{c=a.getNode()}}}return viewCacheUpdateEventSnap(t,c,a.isFullyInitialized()||pathIsEmpty(n),e.filter.filtersNodes())}}function viewProcessorApplyServerOverwrite(e,t,n,r,i,s,o,a){const c=t.serverCache;let l;const u=o?e.filter:e.filter.getIndexedFilter();if(pathIsEmpty(n)){l=u.updateFullNode(c.getNode(),r,null)}else if(u.filtersNodes()&&!c.isFiltered()){const e=c.getNode().updateChild(n,r);l=u.updateFullNode(c.getNode(),e,null)}else{const e=pathGetFront(n);if(!c.isCompleteForPath(n)&&pathGetLength(n)>1){return t}const i=pathPopFront(n);const s=c.getNode().getImmediateChild(e);const o=s.updateChild(i,r);if(e===".priority"){l=u.updatePriority(c.getNode(),o)}else{l=u.updateChild(c.getNode(),e,o,i,Be,null)}}const d=viewCacheUpdateServerSnap(t,l,c.isFullyInitialized()||pathIsEmpty(n),u.filtersNodes());const h=new WriteTreeCompleteChildSource(i,d,s);return viewProcessorGenerateEventCacheAfterServerEvent(e,d,n,i,h,a)}function viewProcessorApplyUserOverwrite(e,t,n,r,i,s,o){const a=t.eventCache;let c,l;const u=new WriteTreeCompleteChildSource(i,t,s);if(pathIsEmpty(n)){l=e.filter.updateFullNode(t.eventCache.getNode(),r,o);c=viewCacheUpdateEventSnap(t,l,true,e.filter.filtersNodes())}else{const i=pathGetFront(n);if(i===".priority"){l=e.filter.updatePriority(t.eventCache.getNode(),r);c=viewCacheUpdateEventSnap(t,l,a.isFullyInitialized(),a.isFiltered())}else{const s=pathPopFront(n);const l=a.getNode().getImmediateChild(i);let d;if(pathIsEmpty(s)){d=r}else{const e=u.getCompleteChild(i);if(e!=null){if(pathGetBack(s)===".priority"&&e.getChild(pathParent(s)).isEmpty()){d=e}else{d=e.updateChild(s,r)}}else{d=ChildrenNode.EMPTY_NODE}}if(!l.equals(d)){const n=e.filter.updateChild(a.getNode(),i,d,s,u,o);c=viewCacheUpdateEventSnap(t,n,a.isFullyInitialized(),e.filter.filtersNodes())}else{c=t}}}return c}function viewProcessorCacheHasChild(e,t){return e.eventCache.isCompleteForChild(t)}function viewProcessorApplyUserMerge(e,t,n,r,i,s,o){let a=t;r.foreach(((r,c)=>{const l=pathChild(n,r);if(viewProcessorCacheHasChild(t,pathGetFront(l))){a=viewProcessorApplyUserOverwrite(e,a,l,c,i,s,o)}}));r.foreach(((r,c)=>{const l=pathChild(n,r);if(!viewProcessorCacheHasChild(t,pathGetFront(l))){a=viewProcessorApplyUserOverwrite(e,a,l,c,i,s,o)}}));return a}function viewProcessorApplyMerge(e,t,n){n.foreach(((e,n)=>{t=t.updateChild(e,n)}));return t}function viewProcessorApplyServerMerge(e,t,n,r,i,s,o,a){if(t.serverCache.getNode().isEmpty()&&!t.serverCache.isFullyInitialized()){return t}let c=t;let l;if(pathIsEmpty(n)){l=r}else{l=new ImmutableTree(null).setTree(n,r)}const u=t.serverCache.getNode();l.children.inorderTraversal(((n,r)=>{if(u.hasChild(n)){const l=t.serverCache.getNode().getImmediateChild(n);const u=viewProcessorApplyMerge(e,l,r);c=viewProcessorApplyServerOverwrite(e,c,new Path(n),u,i,s,o,a)}}));l.children.inorderTraversal(((n,r)=>{const l=!t.serverCache.isCompleteForChild(n)&&r.value===null;if(!u.hasChild(n)&&!l){const l=t.serverCache.getNode().getImmediateChild(n);const u=viewProcessorApplyMerge(e,l,r);c=viewProcessorApplyServerOverwrite(e,c,new Path(n),u,i,s,o,a)}}));return c}function viewProcessorAckUserWrite(e,t,n,r,i,s,o){if(writeTreeRefShadowingWrite(i,n)!=null){return t}const a=t.serverCache.isFiltered();const c=t.serverCache;if(r.value!=null){if(pathIsEmpty(n)&&c.isFullyInitialized()||c.isCompleteForPath(n)){return viewProcessorApplyServerOverwrite(e,t,n,c.getNode().getChild(n),i,s,a,o)}else if(pathIsEmpty(n)){let r=new ImmutableTree(null);
2c.getNode().forEachChild(Pe,((e,t)=>{r=r.set(new Path(e),t)}));return viewProcessorApplyServerMerge(e,t,n,r,i,s,a,o)}else{return t}}else{let l=new ImmutableTree(null);r.foreach(((e,t)=>{const r=pathChild(n,e);if(c.isCompleteForPath(r)){l=l.set(e,c.getNode().getChild(r))}}));return viewProcessorApplyServerMerge(e,t,n,l,i,s,a,o)}}function viewProcessorListenComplete(e,t,n,r,i){const s=t.serverCache;const o=viewCacheUpdateServerSnap(t,s.getNode(),s.isFullyInitialized()||pathIsEmpty(n),s.isFiltered());return viewProcessorGenerateEventCacheAfterServerEvent(e,o,n,r,Be,i)}function viewProcessorRevertUserWrite(e,t,n,r,i,s){let a;if(writeTreeRefShadowingWrite(r,n)!=null){return t}else{const c=new WriteTreeCompleteChildSource(r,t,i);const l=t.eventCache.getNode();let u;if(pathIsEmpty(n)||pathGetFront(n)===".priority"){let n;if(t.serverCache.isFullyInitialized()){n=writeTreeRefCalcCompleteEventCache(r,viewCacheGetCompleteServerSnap(t))}else{const e=t.serverCache.getNode();o.assert(e instanceof ChildrenNode,"serverChildren would be complete if leaf node");n=writeTreeRefCalcCompleteEventChildren(r,e)}n=n;u=e.filter.updateFullNode(l,n,s)}else{const i=pathGetFront(n);let o=writeTreeRefCalcCompleteChild(r,i,t.serverCache);if(o==null&&t.serverCache.isCompleteForChild(i)){o=l.getImmediateChild(i)}if(o!=null){u=e.filter.updateChild(l,i,o,pathPopFront(n),c,s)}else if(t.eventCache.getNode().hasChild(i)){u=e.filter.updateChild(l,i,ChildrenNode.EMPTY_NODE,pathPopFront(n),c,s)}else{u=l}if(u.isEmpty()&&t.serverCache.isFullyInitialized()){a=writeTreeRefCalcCompleteEventCache(r,viewCacheGetCompleteServerSnap(t));if(a.isLeafNode()){u=e.filter.updateFullNode(u,a,s)}}}a=t.serverCache.isFullyInitialized()||writeTreeRefShadowingWrite(r,newEmptyPath())!=null;return viewCacheUpdateEventSnap(t,u,a,e.filter.filtersNodes())}}class View{constructor(e,t){this.query_=e;this.eventRegistrations_=[];const n=this.query_._queryParams;const r=new IndexedFilter(n.getIndex());const i=queryParamsGetNodeFilter(n);this.processor_=newViewProcessor(i);const s=t.serverCache;const o=t.eventCache;const a=r.updateFullNode(ChildrenNode.EMPTY_NODE,s.getNode(),null);const c=i.updateFullNode(ChildrenNode.EMPTY_NODE,o.getNode(),null);const l=new CacheNode(a,s.isFullyInitialized(),r.filtersNodes());const u=new CacheNode(c,o.isFullyInitialized(),i.filtersNodes());this.viewCache_=newViewCache(u,l);this.eventGenerator_=new EventGenerator(this.query_)}get query(){return this.query_}}function viewGetServerCache(e){return e.viewCache_.serverCache.getNode()}function viewGetCompleteNode(e){return viewCacheGetCompleteEventSnap(e.viewCache_)}function viewGetCompleteServerCache(e,t){const n=viewCacheGetCompleteServerSnap(e.viewCache_);if(n){if(e.query._queryParams.loadsAllData()||!pathIsEmpty(t)&&!n.getImmediateChild(pathGetFront(t)).isEmpty()){return n.getChild(t)}}return null}function viewIsEmpty(e){return e.eventRegistrations_.length===0}function viewAddEventRegistration(e,t){e.eventRegistrations_.push(t)}function viewRemoveEventRegistration(e,t,n){const r=[];if(n){o.assert(t==null,"A cancel should cancel all event registrations.");const i=e.query._path;e.eventRegistrations_.forEach((e=>{const t=e.createCancelEvent(n,i);if(t){r.push(t)}}))}if(t){let n=[];for(let r=0;r<e.eventRegistrations_.length;++r){const i=e.eventRegistrations_[r];if(!i.matches(t)){n.push(i)}else if(t.hasAnyCallback()){n=n.concat(e.eventRegistrations_.slice(r+1));break}}e.eventRegistrations_=n}else{e.eventRegistrations_=[]}return r}function viewApplyOperation(e,t,n,r){if(t.type===qe.MERGE&&t.source.queryId!==null){o.assert(viewCacheGetCompleteServerSnap(e.viewCache_),"We should always have a full cache before handling merges");o.assert(viewCacheGetCompleteEventSnap(e.viewCache_),"Missing event cache, even though we have a server cache")}const i=e.viewCache_;const s=viewProcessorApplyOperation(e.processor_,i,t,n,r);viewProcessorAssertIndexed(e.processor_,s.viewCache);o.assert(s.viewCache.serverCache.isFullyInitialized()||!i.serverCache.isFullyInitialized(),"Once a server snap is complete, it should never go back");e.viewCache_=s.viewCache;return viewGenerateEventsForChanges_(e,s.changes,s.viewCache.eventCache.getNode(),null)}function viewGetInitialEvents(e,t){const n=e.viewCache_.eventCache;
2const r=[];if(!n.getNode().isLeafNode()){const e=n.getNode();e.forEachChild(ke,((e,t)=>{r.push(changeChildAdded(e,t))}))}if(n.isFullyInitialized()){r.push(changeValue(n.getNode()))}return viewGenerateEventsForChanges_(e,r,n.getNode(),t)}function viewGenerateEventsForChanges_(e,t,n,r){const i=r?[r]:e.eventRegistrations_;return eventGeneratorGenerateEventsForChanges(e.eventGenerator_,t,n,i)}let He;class SyncPoint{constructor(){this.views=new Map}}function syncPointSetReferenceConstructor(e){o.assert(!He,"__referenceConstructor has already been defined");He=e}function syncPointGetReferenceConstructor(){o.assert(He,"Reference.ts has not been loaded");return He}function syncPointIsEmpty(e){return e.views.size===0}function syncPointApplyOperation(e,t,n,r){const i=t.source.queryId;if(i!==null){const s=e.views.get(i);o.assert(s!=null,"SyncTree gave us an op for an invalid query.");return viewApplyOperation(s,t,n,r)}else{let i=[];for(const s of e.views.values()){i=i.concat(viewApplyOperation(s,t,n,r))}return i}}function syncPointGetView(e,t,n,r,i){const s=t._queryIdentifier;const o=e.views.get(s);if(!o){let e=writeTreeRefCalcCompleteEventCache(n,i?r:null);let s=false;if(e){s=true}else if(r instanceof ChildrenNode){e=writeTreeRefCalcCompleteEventChildren(n,r);s=false}else{e=ChildrenNode.EMPTY_NODE;s=false}const o=newViewCache(new CacheNode(e,s,false),new CacheNode(r,i,false));return new View(t,o)}return o}function syncPointAddEventRegistration(e,t,n,r,i,s){const o=syncPointGetView(e,t,r,i,s);if(!e.views.has(t._queryIdentifier)){e.views.set(t._queryIdentifier,o)}viewAddEventRegistration(o,n);return viewGetInitialEvents(o,n)}function syncPointRemoveEventRegistration(e,t,n,r){const i=t._queryIdentifier;const s=[];let o=[];const a=syncPointHasCompleteView(e);if(i==="default"){for(const[t,i]of e.views.entries()){o=o.concat(viewRemoveEventRegistration(i,n,r));if(viewIsEmpty(i)){e.views.delete(t);if(!i.query._queryParams.loadsAllData()){s.push(i.query)}}}}else{const t=e.views.get(i);if(t){o=o.concat(viewRemoveEventRegistration(t,n,r));if(viewIsEmpty(t)){e.views.delete(i);if(!t.query._queryParams.loadsAllData()){s.push(t.query)}}}}if(a&&!syncPointHasCompleteView(e)){s.push(new(syncPointGetReferenceConstructor())(t._repo,t._path))}return{removed:s,events:o}}function syncPointGetQueryViews(e){const t=[];for(const n of e.views.values()){if(!n.query._queryParams.loadsAllData()){t.push(n)}}return t}function syncPointGetCompleteServerCache(e,t){let n=null;for(const r of e.views.values()){n=n||viewGetCompleteServerCache(r,t)}return n}function syncPointViewForQuery(e,t){const n=t._queryParams;if(n.loadsAllData()){return syncPointGetCompleteView(e)}else{const n=t._queryIdentifier;return e.views.get(n)}}function syncPointViewExistsForQuery(e,t){return syncPointViewForQuery(e,t)!=null}function syncPointHasCompleteView(e){return syncPointGetCompleteView(e)!=null}function syncPointGetCompleteView(e){for(const t of e.views.values()){if(t.query._queryParams.loadsAllData()){return t}}return null}let je;function syncTreeSetReferenceConstructor(e){o.assert(!je,"__referenceConstructor has already been defined");je=e}function syncTreeGetReferenceConstructor(){o.assert(je,"Reference.ts has not been loaded");return je}let ze=1;class SyncTree{constructor(e){this.listenProvider_=e;this.syncPointTree_=new ImmutableTree(null);this.pendingWriteTree_=newWriteTree();this.tagToQueryMap=new Map;this.queryToTagMap=new Map}}function syncTreeApplyUserOverwrite(e,t,n,r,i){writeTreeAddOverwrite(e.pendingWriteTree_,t,n,r,i);if(!i){return[]}else{return syncTreeApplyOperationToSyncPoints_(e,new Overwrite(newOperationSourceUser(),t,n))}}function syncTreeApplyUserMerge(e,t,n,r){writeTreeAddMerge(e.pendingWriteTree_,t,n,r);const i=ImmutableTree.fromObject(n);return syncTreeApplyOperationToSyncPoints_(e,new Merge(newOperationSourceUser(),t,i))}function syncTreeAckUserWrite(e,t,n=false){const r=writeTreeGetWrite(e.pendingWriteTree_,t);const i=writeTreeRemoveWrite(e.pendingWriteTree_,t);if(!i){return[]}else{let t=new ImmutableTree(null);if(r.snap!=null){t=t.set(newEmptyPath(),true)}else{each(r.children,(e=>{t=t.set(new Path(e),true)}))}return syncTreeApplyOperationToSyncPoints_(e,new AckUserWrite(r.path,t,n))}}function syncTreeApplyServerOverwrite(e,t,n){return syncTreeApplyOperationToSyncPoints_(e,new Overwrite(newOperationSourceServer(),t,n))}function syncTreeApplyServerMerge(e,t,n){const r=ImmutableTree.fromObject(n);return syncTreeApplyOperationToSyncPoints_(e,new Merge(newOperationSourceServer(),t,r))}function syncTreeApplyListenComplete(e,t){return syncTreeApplyOperationToSyncPoints_(e,new ListenComplete(newOperationSourceServer(),t))}function syncTreeApplyTaggedListenComplete(e,t,n){const r=syncTreeQueryKeyForTag_(e,n);if(r){const n=syncTreeParseQueryKey_(r);const i=n.path,s=n.queryId;const o=newRelativePath(i,t);const a=new ListenComplete(newOperationSourceServerTaggedQuery(s),o);return syncTreeApplyTaggedOperation_(e,i,a)}else{return[]}}function syncTreeRemoveEventRegistration(e,t,n,r,i=false){const s=t._path;const o=e.syncPointTree_.get(s);let a=[];if(o&&(t._queryIdentifier==="default"||syncPointViewExistsForQuery(o,t))){const c=syncPointRemoveEventRegistration(o,t,n,r);if(syncPointIsEmpty(o)){e.syncPointTree_=e.syncPointTree_.remove(s)}const l=c.removed;a=c.events;if(!i){const n=-1!==l.findIndex((e=>e._queryParams.loadsAllData()));const i=e.syncPointTree_.findOnPath(s,((e,t)=>syncPointHasCompleteView(t)));if(n&&!i){const t=e.syncPointTree_.subtree(s);if(!t.isEmpty()){const n=syncTreeCollectDistinctViewsForSubTree_(t);for(let t=0;t<n.length;++t){const r=n[t],i=r.query;const s=syncTreeCreateListenerForView_(e,r);
2e.listenProvider_.startListening(syncTreeQueryForListening_(i),syncTreeTagForQuery(e,i),s.hashFn,s.onComplete)}}}if(!i&&l.length>0&&!r){if(n){const n=null;e.listenProvider_.stopListening(syncTreeQueryForListening_(t),n)}else{l.forEach((t=>{const n=e.queryToTagMap.get(syncTreeMakeQueryKey_(t));e.listenProvider_.stopListening(syncTreeQueryForListening_(t),n)}))}}}syncTreeRemoveTags_(e,l)}return a}function syncTreeApplyTaggedQueryOverwrite(e,t,n,r){const i=syncTreeQueryKeyForTag_(e,r);if(i!=null){const r=syncTreeParseQueryKey_(i);const s=r.path,o=r.queryId;const a=newRelativePath(s,t);const c=new Overwrite(newOperationSourceServerTaggedQuery(o),a,n);return syncTreeApplyTaggedOperation_(e,s,c)}else{return[]}}function syncTreeApplyTaggedQueryMerge(e,t,n,r){const i=syncTreeQueryKeyForTag_(e,r);if(i){const r=syncTreeParseQueryKey_(i);const s=r.path,o=r.queryId;const a=newRelativePath(s,t);const c=ImmutableTree.fromObject(n);const l=new Merge(newOperationSourceServerTaggedQuery(o),a,c);return syncTreeApplyTaggedOperation_(e,s,l)}else{return[]}}function syncTreeAddEventRegistration(e,t,n,r=false){const i=t._path;let s=null;let a=false;e.syncPointTree_.foreachOnPath(i,((e,t)=>{const n=newRelativePath(e,i);s=s||syncPointGetCompleteServerCache(t,n);a=a||syncPointHasCompleteView(t)}));let c=e.syncPointTree_.get(i);if(!c){c=new SyncPoint;e.syncPointTree_=e.syncPointTree_.set(i,c)}else{a=a||syncPointHasCompleteView(c);s=s||syncPointGetCompleteServerCache(c,newEmptyPath())}let l;if(s!=null){l=true}else{l=false;s=ChildrenNode.EMPTY_NODE;const t=e.syncPointTree_.subtree(i);t.foreachChild(((e,t)=>{const n=syncPointGetCompleteServerCache(t,newEmptyPath());if(n){s=s.updateImmediateChild(e,n)}}))}const u=syncPointViewExistsForQuery(c,t);if(!u&&!t._queryParams.loadsAllData()){const n=syncTreeMakeQueryKey_(t);o.assert(!e.queryToTagMap.has(n),"View does not exist, but we have a tag");const r=syncTreeGetNextQueryTag_();e.queryToTagMap.set(n,r);e.tagToQueryMap.set(r,n)}const d=writeTreeChildWrites(e.pendingWriteTree_,i);let h=syncPointAddEventRegistration(c,t,n,d,s,l);if(!u&&!a&&!r){const n=syncPointViewForQuery(c,t);h=h.concat(syncTreeSetupListener_(e,t,n))}return h}function syncTreeCalcCompleteEventCache(e,t,n){const r=true;const i=e.pendingWriteTree_;const s=e.syncPointTree_.findOnPath(t,((e,n)=>{const r=newRelativePath(e,t);const i=syncPointGetCompleteServerCache(n,r);if(i){return i}}));return writeTreeCalcCompleteEventCache(i,t,s,n,r)}function syncTreeGetServerValue(e,t){const n=t._path;let r=null;e.syncPointTree_.foreachOnPath(n,((e,t)=>{const i=newRelativePath(e,n);r=r||syncPointGetCompleteServerCache(t,i)}));let i=e.syncPointTree_.get(n);if(!i){i=new SyncPoint;e.syncPointTree_=e.syncPointTree_.set(n,i)}else{r=r||syncPointGetCompleteServerCache(i,newEmptyPath())}const s=r!=null;const o=s?new CacheNode(r,true,false):null;const a=writeTreeChildWrites(e.pendingWriteTree_,t._path);const c=syncPointGetView(i,t,a,s?o.getNode():ChildrenNode.EMPTY_NODE,s);return viewGetCompleteNode(c)}function syncTreeApplyOperationToSyncPoints_(e,t){return syncTreeApplyOperationHelper_(t,e.syncPointTree_,null,writeTreeChildWrites(e.pendingWriteTree_,newEmptyPath()))}function syncTreeApplyOperationHelper_(e,t,n,r){if(pathIsEmpty(e.path)){return syncTreeApplyOperationDescendantsHelper_(e,t,n,r)}else{const i=t.get(newEmptyPath());if(n==null&&i!=null){n=syncPointGetCompleteServerCache(i,newEmptyPath())}let s=[];const o=pathGetFront(e.path);const a=e.operationForChild(o);const c=t.children.get(o);if(c&&a){const e=n?n.getImmediateChild(o):null;const t=writeTreeRefChild(r,o);s=s.concat(syncTreeApplyOperationHelper_(a,c,e,t))}if(i){s=s.concat(syncPointApplyOperation(i,e,r,n))}return s}}function syncTreeApplyOperationDescendantsHelper_(e,t,n,r){const i=t.get(newEmptyPath());if(n==null&&i!=null){n=syncPointGetCompleteServerCache(i,newEmptyPath())}let s=[];t.children.inorderTraversal(((t,i)=>{const o=n?n.getImmediateChild(t):null;const a=writeTreeRefChild(r,t);const c=e.operationForChild(t);if(c){s=s.concat(syncTreeApplyOperationDescendantsHelper_(c,i,o,a))}}));if(i){s=s.concat(syncPointApplyOperation(i,e,r,n))}return s}function syncTreeCreateListenerForView_(e,t){const n=t.query;const r=syncTreeTagForQuery(e,n);return{hashFn:()=>{const e=viewGetServerCache(t)||ChildrenNode.EMPTY_NODE;return e.hash()},onComplete:t=>{if(t==="ok"){if(r){return syncTreeApplyTaggedListenComplete(e,n._path,r)}else{return syncTreeApplyListenComplete(e,n._path)}}else{const r=errorForServerCode(t,n);return syncTreeRemoveEventRegistration(e,n,null,r)}}}}function syncTreeTagForQuery(e,t){const n=syncTreeMakeQueryKey_(t);return e.queryToTagMap.get(n)}function syncTreeMakeQueryKey_(e){return e._path.toString()+"$"+e._queryIdentifier}function syncTreeQueryKeyForTag_(e,t){return e.tagToQueryMap.get(t)}function syncTreeParseQueryKey_(e){const t=e.indexOf("$");o.assert(t!==-1&&t<e.length-1,"Bad queryKey.");return{queryId:e.substr(t+1),path:new Path(e.substr(0,t))}}function syncTreeApplyTaggedOperation_(e,t,n){const r=e.syncPointTree_.get(t);o.assert(r,"Missing sync point for query tag that we're tracking");const i=writeTreeChildWrites(e.pendingWriteTree_,t);return syncPointApplyOperation(r,n,i,null)}function syncTreeCollectDistinctViewsForSubTree_(e){return e.fold(((e,t,n)=>{if(t&&syncPointHasCompleteView(t)){const e=syncPointGetCompleteView(t);return[e]}else{let e=[];
2if(t){e=syncPointGetQueryViews(t)}each(n,((t,n)=>{e=e.concat(n)}));return e}}))}function syncTreeQueryForListening_(e){if(e._queryParams.loadsAllData()&&!e._queryParams.isDefault()){return new(syncTreeGetReferenceConstructor())(e._repo,e._path)}else{return e}}function syncTreeRemoveTags_(e,t){for(let n=0;n<t.length;++n){const r=t[n];if(!r._queryParams.loadsAllData()){const t=syncTreeMakeQueryKey_(r);const n=e.queryToTagMap.get(t);e.queryToTagMap.delete(t);e.tagToQueryMap.delete(n)}}}function syncTreeGetNextQueryTag_(){return ze++}function syncTreeSetupListener_(e,t,n){const r=t._path;const i=syncTreeTagForQuery(e,t);const s=syncTreeCreateListenerForView_(e,n);const a=e.listenProvider_.startListening(syncTreeQueryForListening_(t),i,s.hashFn,s.onComplete);const c=e.syncPointTree_.subtree(r);if(i){o.assert(!syncPointHasCompleteView(c.value),"If we're adding a query, it shouldn't be shadowed")}else{const t=c.fold(((e,t,n)=>{if(!pathIsEmpty(e)&&t&&syncPointHasCompleteView(t)){return[syncPointGetCompleteView(t).query]}else{let e=[];if(t){e=e.concat(syncPointGetQueryViews(t).map((e=>e.query)))}each(n,((t,n)=>{e=e.concat(n)}));return e}}));for(let n=0;n<t.length;++n){const r=t[n];e.listenProvider_.stopListening(syncTreeQueryForListening_(r),syncTreeTagForQuery(e,r))}}return a}class ExistingValueProvider{constructor(e){this.node_=e}getImmediateChild(e){const t=this.node_.getImmediateChild(e);return new ExistingValueProvider(t)}node(){return this.node_}}class DeferredValueProvider{constructor(e,t){this.syncTree_=e;this.path_=t}getImmediateChild(e){const t=pathChild(this.path_,e);return new DeferredValueProvider(this.syncTree_,t)}node(){return syncTreeCalcCompleteEventCache(this.syncTree_,this.path_)}}const generateWithValues=function(e){e=e||{};e["timestamp"]=e["timestamp"]||(new Date).getTime();return e};const resolveDeferredLeafValue=function(e,t,n){if(!e||typeof e!=="object"){return e}o.assert(".sv"in e,"Unexpected leaf node or priority contents");if(typeof e[".sv"]==="string"){return resolveScalarDeferredValue(e[".sv"],t,n)}else if(typeof e[".sv"]==="object"){return resolveComplexDeferredValue(e[".sv"],t)}else{o.assert(false,"Unexpected server value: "+JSON.stringify(e,null,2))}};const resolveScalarDeferredValue=function(e,t,n){switch(e){case"timestamp":return n["timestamp"];default:o.assert(false,"Unexpected server value: "+e)}};const resolveComplexDeferredValue=function(e,t,n){if(!e.hasOwnProperty("increment")){o.assert(false,"Unexpected server value: "+JSON.stringify(e,null,2))}const r=e["increment"];if(typeof r!=="number"){o.assert(false,"Unexpected increment value: "+r)}const i=t.node();o.assert(i!==null&&typeof i!=="undefined","Expected ChildrenNode.EMPTY_NODE for nulls");if(!i.isLeafNode()){return r}const s=i;const a=s.getValue();if(typeof a!=="number"){return r}return a+r};const resolveDeferredValueTree=function(e,t,n,r){return resolveDeferredValue(t,new DeferredValueProvider(n,e),r)};const resolveDeferredValueSnapshot=function(e,t,n){return resolveDeferredValue(e,new ExistingValueProvider(t),n)};function resolveDeferredValue(e,t,n){const r=e.getPriority().val();const i=resolveDeferredLeafValue(r,t.getImmediateChild(".priority"),n);let s;if(e.isLeafNode()){const r=e;const s=resolveDeferredLeafValue(r.getValue(),t,n);if(s!==r.getValue()||i!==r.getPriority().val()){return new LeafNode(s,nodeFromJSON(i))}else{return e}}else{const r=e;s=r;if(i!==r.getPriority().val()){s=s.updatePriority(new LeafNode(i))}r.forEachChild(ke,((e,r)=>{const i=resolveDeferredValue(r,t.getImmediateChild(e),n);if(i!==r){s=s.updateImmediateChild(e,i)}}));return s}}class Tree{constructor(e="",t=null,n={children:{},childCount:0}){this.name=e;this.parent=t;this.node=n}}function treeSubTree(e,t){let n=t instanceof Path?t:new Path(t);let r=e,i=pathGetFront(n);while(i!==null){const e=o.safeGet(r.node.children,i)||{children:{},childCount:0};r=new Tree(i,r,e);n=pathPopFront(n);i=pathGetFront(n)}return r}function treeGetValue(e){return e.node.value}function treeSetValue(e,t){e.node.value=t;treeUpdateParents(e)}function treeHasChildren(e){return e.node.childCount>0}function treeIsEmpty(e){return treeGetValue(e)===undefined&&!treeHasChildren(e)}function treeForEachChild(e,t){each(e.node.children,((n,r)=>{t(new Tree(n,e,r))}))}function treeForEachDescendant(e,t,n,r){if(n&&!r){t(e)}treeForEachChild(e,(e=>{treeForEachDescendant(e,t,true,r)}
2));if(n&&r){t(e)}}function treeForEachAncestor(e,t,n){let r=n?e:e.parent;while(r!==null){if(t(r)){return true}r=r.parent}return false}function treeGetPath(e){return new Path(e.parent===null?e.name:treeGetPath(e.parent)+"/"+e.name)}function treeUpdateParents(e){if(e.parent!==null){treeUpdateChild(e.parent,e.name,e)}}function treeUpdateChild(e,t,n){const r=treeIsEmpty(n);const i=o.contains(e.node.children,t);if(r&&i){delete e.node.children[t];e.node.childCount--;treeUpdateParents(e)}else if(!r&&!i){e.node.children[t]=n.node;e.node.childCount++;treeUpdateParents(e)}}const Ke=/[\[\].#$\/\u0000-\u001F\u007F]/;const $e=/[\[\].#$\u0000-\u001F\u007F]/;const Qe=10*1024*1024;const isValidKey=function(e){return typeof e==="string"&&e.length!==0&&!Ke.test(e)};const isValidPathString=function(e){return typeof e==="string"&&e.length!==0&&!$e.test(e)};const isValidRootPathString=function(e){if(e){e=e.replace(/^\/*\.info(\/|$)/,"/")}return isValidPathString(e)};const isValidPriority=function(e){return e===null||typeof e==="string"||typeof e==="number"&&!isInvalidJSONNumber(e)||e&&typeof e==="object"&&o.contains(e,".sv")};const validateFirebaseDataArg=function(e,t,n,r){if(r&&t===undefined){return}validateFirebaseData(o.errorPrefix(e,"value"),t,n)};const validateFirebaseData=function(e,t,n){const r=n instanceof Path?new ValidationPath(n,e):n;if(t===undefined){throw new Error(e+"contains undefined "+validationPathToErrorString(r))}if(typeof t==="function"){throw new Error(e+"contains a function "+validationPathToErrorString(r)+" with contents = "+t.toString())}if(isInvalidJSONNumber(t)){throw new Error(e+"contains "+t.toString()+" "+validationPathToErrorString(r))}if(typeof t==="string"&&t.length>Qe/3&&o.stringLength(t)>Qe){throw new Error(e+"contains a string greater than "+Qe+" utf8 bytes "+validationPathToErrorString(r)+" ('"+t.substring(0,50)+"...')")}if(t&&typeof t==="object"){let n=false;let i=false;each(t,((t,s)=>{if(t===".value"){n=true}else if(t!==".priority"&&t!==".sv"){i=true;if(!isValidKey(t)){throw new Error(e+" contains an invalid key ("+t+") "+validationPathToErrorString(r)+".  Keys must be non-empty strings "+'and can\'t contain ".", "#", "$", "/", "[", or "]"')}}validationPathPush(r,t);validateFirebaseData(e,s,r);validationPathPop(r)}));if(n&&i){throw new Error(e+' contains ".value" child '+validationPathToErrorString(r)+" in addition to actual children.")}}};const validateFirebaseMergePaths=function(e,t){let n,r;for(n=0;n<t.length;n++){r=t[n];const i=pathSlice(r);for(let t=0;t<i.length;t++){if(i[t]===".priority"&&t===i.length-1);else if(!isValidKey(i[t])){throw new Error(e+"contains an invalid key ("+i[t]+") in path "+r.toString()+". Keys must be non-empty strings "+'and can\'t contain ".", "#", "$", "/", "[", or "]"')}}}t.sort(pathCompare);let i=null;for(n=0;n<t.length;n++){r=t[n];if(i!==null&&pathContains(i,r)){throw new Error(e+"contains a path "+i.toString()+" that is ancestor of another path "+r.toString())}i=r}};const validateFirebaseMergeDataArg=function(e,t,n,r){if(r&&t===undefined){return}const i=o.errorPrefix(e,"values");if(!(t&&typeof t==="object")||Array.isArray(t)){throw new Error(i+" must be an object containing the children to replace.")}const s=[];each(t,((e,t)=>{const r=new Path(e);validateFirebaseData(i,t,pathChild(n,r));if(pathGetBack(r)===".priority"){if(!isValidPriority(t)){throw new Error(i+"contains an invalid value for '"+r.toString()+"', which must be a valid "+"Firebase priority (a string, finite number, server value, or null).")}}s.push(r)}));validateFirebaseMergePaths(i,s)};const validatePriority=function(e,t,n){if(n&&t===undefined){return}if(isInvalidJSONNumber(t)){throw new Error(o.errorPrefix(e,"priority")+"is "+t.toString()+", but must be a valid Firebase priority (a string, finite number, "+"server value, or null).")}if(!isValidPriority(t)){throw new Error(o.errorPrefix(e,"priority")+"must be a valid Firebase priority "+"(a string, finite number, server value, or null).")}};const validateKey=function(e,t,n,r){if(r&&n===undefined){return}if(!isValidKey(n)){throw new Error(o.errorPrefix(e,t)+'was an invali
2d key = "'+n+'".  Firebase keys must be non-empty strings and '+'can\'t contain ".", "#", "$", "/", "[", or "]").')}};const validatePathString=function(e,t,n,r){if(r&&n===undefined){return}if(!isValidPathString(n)){throw new Error(o.errorPrefix(e,t)+'was an invalid path = "'+n+'". Paths must be non-empty strings and '+'can\'t contain ".", "#", "$", "[", or "]"')}};const validateRootPathString=function(e,t,n,r){if(n){n=n.replace(/^\/*\.info(\/|$)/,"/")}validatePathString(e,t,n,r)};const validateWritablePath=function(e,t){if(pathGetFront(t)===".info"){throw new Error(e+" failed = Can't modify data under /.info/")}};const validateUrl=function(e,t){const n=t.path.toString();if(!(typeof t.repoInfo.host==="string")||t.repoInfo.host.length===0||!isValidKey(t.repoInfo.namespace)&&t.repoInfo.host.split(":")[0]!=="localhost"||n.length!==0&&!isValidRootPathString(n)){throw new Error(o.errorPrefix(e,"url")+"must be a valid firebase URL and "+'the path can\'t contain ".", "#", "$", "[", or "]".')}};class EventQueue{constructor(){this.eventLists_=[];this.recursionDepth_=0}}function eventQueueQueueEvents(e,t){let n=null;for(let r=0;r<t.length;r++){const i=t[r];const s=i.getPath();if(n!==null&&!pathEquals(s,n.path)){e.eventLists_.push(n);n=null}if(n===null){n={events:[],path:s}}n.events.push(i)}if(n){e.eventLists_.push(n)}}function eventQueueRaiseEventsAtPath(e,t,n){eventQueueQueueEvents(e,n);eventQueueRaiseQueuedEventsMatchingPredicate(e,(e=>pathEquals(e,t)))}function eventQueueRaiseEventsForChangedPath(e,t,n){eventQueueQueueEvents(e,n);eventQueueRaiseQueuedEventsMatchingPredicate(e,(e=>pathContains(e,t)||pathContains(t,e)))}function eventQueueRaiseQueuedEventsMatchingPredicate(e,t){e.recursionDepth_++;let n=true;for(let r=0;r<e.eventLists_.length;r++){const i=e.eventLists_[r];if(i){const s=i.path;if(t(s)){eventListRaise(e.eventLists_[r]);e.eventLists_[r]=null}else{n=false}}}if(n){e.eventLists_=[]}e.recursionDepth_--}function eventListRaise(e){for(let t=0;t<e.events.length;t++){const n=e.events[t];if(n!==null){e.events[t]=null;const r=n.getEventRunner();if(m){log("event: "+n.toString())}exceptionGuard(r)}}}const Ye="repo_interrupt";const Je=25;class Repo{constructor(e,t,n,r){this.repoInfo_=e;this.forceRestClient_=t;this.authTokenProvider_=n;this.appCheckProvider_=r;this.dataUpdateCount=0;this.statsListener_=null;this.eventQueue_=new EventQueue;this.nextWriteId_=1;this.interceptServerDataCallback_=null;this.onDisconnect_=newSparseSnapshotTree();this.transactionQueueTree_=new Tree;this.persistentConnection_=null;this.key=this.repoInfo_.toURLString()}toString(){return(this.repoInfo_.secure?"https://":"http://")+this.repoInfo_.host}}function repoStart(e,t,n){e.stats_=statsManagerGetCollection(e.repoInfo_);if(e.forceRestClient_||beingCrawled()){e.server_=new ReadonlyRestClient(e.repoInfo_,((t,n,r,i)=>{repoOnDataUpdate(e,t,n,r,i)}),e.authTokenProvider_,e.appCheckProvider_);setTimeout((()=>repoOnConnectStatus(e,true)),0)}else{if(typeof n!=="undefined"&&n!==null){if(typeof n!=="object"){throw new Error("Only objects are supported for option databaseAuthVariableOverride")}try{o.stringify(n)}catch(e){throw new Error("Invalid authOverride provided: "+e)}}e.persistentConnection_=new PersistentConnection(e.repoInfo_,t,((t,n,r,i)=>{repoOnDataUpdate(e,t,n,r,i)}),(t=>{repoOnConnectStatus(e,t)}),(t=>{repoOnServerInfoUpdate(e,t)}),e.authTokenProvider_,e.appCheckProvider_,n);e.server_=e.persistentConnection_}e.authTokenProvider_.addTokenChangeListener((t=>{e.server_.refreshAuthToken(t)}));e.appCheckProvider_.addTokenChangeListener((t=>{e.server_.refreshAppCheckToken(t.token)}));e.statsReporter_=statsManagerGetOrCreateReporter(e.repoInfo_,(()=>new StatsReporter(e.stats_,e.server_)));e.infoData_=new SnapshotHolder;e.infoSyncTree_=new SyncTree({startListening:(t,n,r,i)=>{let s=[];const o=e.infoData_.getNode(t._path);if(!o.isEmpty()){s=syncTreeApplyServerOverwrite(e.infoSyncTree_,t._path,o);setTimeout((()=>{i("ok")}),0)}return s},stopListening:()=>{}});repoUpdateInfo(e,"connected",false);e.serverSyncTree_=new SyncTree({startListening:(t,n,r,i)=>{e.server_.listen(t,r,n,((n,r)=>{const s=i(n,r);eventQueueRaiseEventsForChangedPath(e.eventQueue_,t._path,s)}));return[]},stopListening:(t,n)=>{e.server_.unlisten(t,n)}})}function repoServerTime(e){const t=e.infoData_.getNode(new Path(".info/serverTimeOffset"));const n=t.val()||0;return(new Date).getTime()+n}function repoGenerateServerValues(e){return generateWithValues({timestamp:repoServerTime(e)})}function repoOnDataUpdate(e,t,n,r,i){e.dataUpdateCount++;const s=new Path(t);n=e.interceptServerDataCallback_?e.interceptServerDataCallback_(t,n):n;let a=[];if(i){if(r){const t=o.map(n,(e=>nodeFromJSON(e)));a=syncTreeApplyTaggedQueryMerge(e.serverSyncTree_,s,t,i)}else{const t=nodeFromJSON(n);a=syncTreeApplyTaggedQueryOverwrite(e.serverSyncTree_,s,t,i)}}else if(r){const t=o.map(n,(e=>nodeFromJSON(e)));a=syncTreeApplyServerMerge(e.serverSyncTree_,s,t)}else{const t=nodeFromJSON(n);a=syncTreeApplyServerOverwrite(e.serverSyncTree_,s,t)}let c=s;if(a.length>0){c=repoRerunTransactions(e,s)}eventQueueRaiseEventsForChangedPath(e.eventQueue_,c,a)}function repoOnConnectStatus(e,t){repoUpdateInfo(e,"connected",t);if(t===false){repoRunOnDisconnectEvents(e)}}function repoOnServerInfoUpdate(e,t){each(t,((t,n)=>{repoUpdateInfo(e,t,n)}))}function repoUpdateInfo(e,t,n){const r=new Path("/.info/"+t);const i=nodeFromJSON(n);e.infoData_.updateSnapshot(r,i);const s=syncTreeApplyServerOverwrite(e.infoSyncTree_,r,i);eventQueueRaiseEventsForChangedPath(e.eventQueue_,r,s)}
2function repoGetNextWriteId(e){return e.nextWriteId_++}function repoGetValue(e,t,n){const r=syncTreeGetServerValue(e.serverSyncTree_,t);if(r!=null){return Promise.resolve(r)}return e.server_.get(t).then((r=>{const i=nodeFromJSON(r).withIndex(t._queryParams.getIndex());syncTreeAddEventRegistration(e.serverSyncTree_,t,n,true);let s;if(t._queryParams.loadsAllData()){s=syncTreeApplyServerOverwrite(e.serverSyncTree_,t._path,i)}else{const n=syncTreeTagForQuery(e.serverSyncTree_,t);s=syncTreeApplyTaggedQueryOverwrite(e.serverSyncTree_,t._path,i,n)}eventQueueRaiseEventsForChangedPath(e.eventQueue_,t._path,s);syncTreeRemoveEventRegistration(e.serverSyncTree_,t,n,null,true);return i}),(n=>{repoLog(e,"get for query "+o.stringify(t)+" failed: "+n);return Promise.reject(new Error(n))}))}function repoSetWithPriority(e,t,n,r,i){repoLog(e,"set",{path:t.toString(),value:n,priority:r});const s=repoGenerateServerValues(e);const o=nodeFromJSON(n,r);const a=syncTreeCalcCompleteEventCache(e.serverSyncTree_,t);const c=resolveDeferredValueSnapshot(o,a,s);const l=repoGetNextWriteId(e);const u=syncTreeApplyUserOverwrite(e.serverSyncTree_,t,c,l,true);eventQueueQueueEvents(e.eventQueue_,u);e.server_.put(t.toString(),o.val(true),((n,r)=>{const s=n==="ok";if(!s){warn("set at "+t+" failed: "+n)}const o=syncTreeAckUserWrite(e.serverSyncTree_,l,!s);eventQueueRaiseEventsForChangedPath(e.eventQueue_,t,o);repoCallOnCompleteCallback(e,i,n,r)}));const d=repoAbortTransactions(e,t);repoRerunTransactions(e,d);eventQueueRaiseEventsForChangedPath(e.eventQueue_,d,[])}function repoUpdate(e,t,n,r){repoLog(e,"update",{path:t.toString(),value:n});let i=true;const s=repoGenerateServerValues(e);const o={};each(n,((n,r)=>{i=false;o[n]=resolveDeferredValueTree(pathChild(t,n),nodeFromJSON(r),e.serverSyncTree_,s)}));if(!i){const i=repoGetNextWriteId(e);const s=syncTreeApplyUserMerge(e.serverSyncTree_,t,o,i);eventQueueQueueEvents(e.eventQueue_,s);e.server_.merge(t.toString(),n,((n,s)=>{const o=n==="ok";if(!o){warn("update at "+t+" failed: "+n)}const a=syncTreeAckUserWrite(e.serverSyncTree_,i,!o);const c=a.length>0?repoRerunTransactions(e,t):t;eventQueueRaiseEventsForChangedPath(e.eventQueue_,c,a);repoCallOnCompleteCallback(e,r,n,s)}));each(n,(n=>{const r=repoAbortTransactions(e,pathChild(t,n));repoRerunTransactions(e,r)}));eventQueueRaiseEventsForChangedPath(e.eventQueue_,t,[])}else{log("update() called with empty data.  Don't do anything.");repoCallOnCompleteCallback(e,r,"ok",undefined)}}function repoRunOnDisconnectEvents(e){repoLog(e,"onDisconnectEvents");const t=repoGenerateServerValues(e);const n=newSparseSnapshotTree();sparseSnapshotTreeForEachTree(e.onDisconnect_,newEmptyPath(),((r,i)=>{const s=resolveDeferredValueTree(r,i,e.serverSyncTree_,t);sparseSnapshotTreeRemember(n,r,s)}));let r=[];sparseSnapshotTreeForEachTree(n,newEmptyPath(),((t,n)=>{r=r.concat(syncTreeApplyServerOverwrite(e.serverSyncTree_,t,n));const i=repoAbortTransactions(e,t);repoRerunTransactions(e,i)}));e.onDisconnect_=newSparseSnapshotTree();eventQueueRaiseEventsForChangedPath(e.eventQueue_,newEmptyPath(),r)}function repoOnDisconnectCancel(e,t,n){e.server_.onDisconnectCancel(t.toString(),((r,i)=>{if(r==="ok"){sparseSnapshotTreeForget(e.onDisconnect_,t)}repoCallOnCompleteCallback(e,n,r,i)}))}function repoOnDisconnectSet(e,t,n,r){const i=nodeFromJSON(n);e.server_.onDisconnectPut(t.toString(),i.val(true),((n,s)=>{if(n==="ok"){sparseSnapshotTreeRemember(e.onDisconnect_,t,i)}repoCallOnCompleteCallback(e,r,n,s)}))}function repoOnDisconnectSetWithPriority(e,t,n,r,i){const s=nodeFromJSON(n,r);e.server_.onDisconnectPut(t.toString(),s.val(true),((n,r)=>{if(n==="ok"){sparseSnapshotTreeRemember(e.onDisconnect_,t,s)}repoCallOnCompleteCallback(e,i,n,r)}))}function repoOnDisconnectUpdate(e,t,n,r){if(o.isEmpty(n)){log("onDisconnect().update() called with empty data.  Don't do anything.");repoCallOnCompleteCallback(e,r,"ok",undefined);return}e.server_.onDisconnectMerge(t.toString(),n,((i,s)=>{if(i==="ok"){each(n,((n,r)=>{const i=nodeFromJSON(r);sparseSnapshotTreeRemember(e.onDisconnect_,pathChild(t,n),i)}))}repoCallOnCompleteCallback(e,r,i,s)}))}function repoAddEventCallbackForQuery(e,t,n){let r;if(pathGetFront(t._path)===".info"){r=syncTreeAddEventRegistration(e.infoSyncTree_,t,n)}else{r=syncTreeAddEventRegistration(e.serverSyncTree_,t,n)}eventQueueRaiseEventsAtPath(e.eventQueue_,t._path,r)}function repoRemoveEventCallbackForQuery(e,t,n){let r;if(pathGetFront(t._path)===".info"){r=syncTreeRemoveEventRegistration(e.infoSyncTree_,t,n)}else{r=syncTreeRemoveEventRegistration(e.serverSyncTree_,t,n)}eventQueueRaiseEventsAtPath(e.eventQueue_,t._path,r)}function repoInterrupt(e){if(e.persistentConnection_){e.persistentConnection_.interrupt(Ye)}}function repoResume(e){if(e.persistentConnection_){e.persistentConnection_.resume(Ye)}}function repoLog(e,...t){let n="";if(e.persistentConnection_){n=e.persistentConnection_.id+":"}log(n,...t)}function repoCallOnCompleteCallback(e,t,n,r){if(t){exceptionGuard((()=>
2{if(n==="ok"){t(null)}else{const e=(n||"error").toUpperCase();let i=e;if(r){i+=": "+r}const s=new Error(i);s.code=e;t(s)}}))}}function repoStartTransaction(e,t,n,r,i,s){repoLog(e,"transaction on "+t);const a={path:t,update:n,onComplete:r,status:null,order:f(),applyLocally:s,retryCount:0,unwatcher:i,abortReason:null,currentWriteId:null,currentInputSnapshot:null,currentOutputSnapshotRaw:null,currentOutputSnapshotResolved:null};const c=repoGetLatestState(e,t,undefined);a.currentInputSnapshot=c;const l=a.update(c.val());if(l===undefined){a.unwatcher();a.currentOutputSnapshotRaw=null;a.currentOutputSnapshotResolved=null;if(a.onComplete){a.onComplete(null,false,a.currentInputSnapshot)}}else{validateFirebaseData("transaction failed: Data returned ",l,a.path);a.status=0;const n=treeSubTree(e.transactionQueueTree_,t);const r=treeGetValue(n)||[];r.push(a);treeSetValue(n,r);let i;if(typeof l==="object"&&l!==null&&o.contains(l,".priority")){i=o.safeGet(l,".priority");o.assert(isValidPriority(i),"Invalid priority returned by transaction. "+"Priority must be a valid string, finite number, server value, or null.")}else{const n=syncTreeCalcCompleteEventCache(e.serverSyncTree_,t)||ChildrenNode.EMPTY_NODE;i=n.getPriority().val()}const s=repoGenerateServerValues(e);const u=nodeFromJSON(l,i);const d=resolveDeferredValueSnapshot(u,c,s);a.currentOutputSnapshotRaw=u;a.currentOutputSnapshotResolved=d;a.currentWriteId=repoGetNextWriteId(e);const h=syncTreeApplyUserOverwrite(e.serverSyncTree_,t,d,a.currentWriteId,a.applyLocally);eventQueueRaiseEventsForChangedPath(e.eventQueue_,t,h);repoSendReadyTransactions(e,e.transactionQueueTree_)}}function repoGetLatestState(e,t,n){return syncTreeCalcCompleteEventCache(e.serverSyncTree_,t,n)||ChildrenNode.EMPTY_NODE}function repoSendReadyTransactions(e,t=e.transactionQueueTree_){if(!t){repoPruneCompletedTransactionsBelowNode(e,t)}if(treeGetValue(t)){const n=repoBuildTransactionQueue(e,t);o.assert(n.length>0,"Sending zero length transaction queue");const r=n.every((e=>e.status===0));if(r){repoSendTransactionQueue(e,treeGetPath(t),n)}}else if(treeHasChildren(t)){treeForEachChild(t,(t=>{repoSendReadyTransactions(e,t)}))}}function repoSendTransactionQueue(e,t,n){const r=n.map((e=>e.currentWriteId));const i=repoGetLatestState(e,t,r);let s=i;const a=i.hash();for(let e=0;e<n.length;e++){const r=n[e];o.assert(r.status===0,"tryToSendTransactionQueue_: items in queue should all be run.");r.status=1;r.retryCount++;const i=newRelativePath(t,r.path);s=s.updateChild(i,r.currentOutputSnapshotRaw)}const c=s.val(true);const l=t;e.server_.put(l.toString(),c,(r=>{repoLog(e,"transaction put response",{path:l.toString(),status:r});let i=[];if(r==="ok"){const r=[];for(let t=0;t<n.length;t++){n[t].status=2;i=i.concat(syncTreeAckUserWrite(e.serverSyncTree_,n[t].currentWriteId));if(n[t].onComplete){r.push((()=>n[t].onComplete(null,true,n[t].currentOutputSnapshotResolved)))}n[t].unwatcher()}repoPruneCompletedTransactionsBelowNode(e,treeSubTree(e.transactionQueueTree_,t));repoSendReadyTransactions(e,e.transactionQueueTree_);eventQueueRaiseEventsForChangedPath(e.eventQueue_,t,i);for(let e=0;e<r.length;e++){exceptionGuard(r[e])}}else{if(r==="datastale"){for(let e=0;e<n.length;e++){if(n[e].status===3){n[e].status=4}else{n[e].status=0}}}else{warn("transaction at "+l.toString()+" failed: "+r);for(let e=0;e<n.length;e++){n[e].status=4;n[e].abortReason=r}}repoRerunTransactions(e,t)}}),a)}function repoRerunTransactions(e,t){const n=repoGetAncestorTransactionNode(e,t);const r=treeGetPath(n);const i=repoBuildTransactionQueue(e,n);repoRerunTransactionQueue(e,i,r);return r}function repoRerunTransactionQueue(e,t,n){if(t.length===0){return}const r=[];let i=[];const s=t.filter((e=>e.status===0));const a=s.map((e=>e.currentWriteId));for(let s=0;s<t.length;s++){const c=t[s];const l=newRelativePath(n,c.path);let u=false,d;o.assert(l!==null,"rerunTransactionsUnderNode_: relativePath should not be null.");if(c.status===4){u=true;d=c.abortReason;i=i.concat(syncTreeAckUserWrite(e.serverSyncTree_,c.currentWriteId,true))}else if(c.status===0){if(c.retryCount>=Je){u=true;d="maxretry";
2i=i.concat(syncTreeAckUserWrite(e.serverSyncTree_,c.currentWriteId,true))}else{const n=repoGetLatestState(e,c.path,a);c.currentInputSnapshot=n;const r=t[s].update(n.val());if(r!==undefined){validateFirebaseData("transaction failed: Data returned ",r,c.path);let t=nodeFromJSON(r);const s=typeof r==="object"&&r!=null&&o.contains(r,".priority");if(!s){t=t.updatePriority(n.getPriority())}const l=c.currentWriteId;const u=repoGenerateServerValues(e);const d=resolveDeferredValueSnapshot(t,n,u);c.currentOutputSnapshotRaw=t;c.currentOutputSnapshotResolved=d;c.currentWriteId=repoGetNextWriteId(e);a.splice(a.indexOf(l),1);i=i.concat(syncTreeApplyUserOverwrite(e.serverSyncTree_,c.path,d,c.currentWriteId,c.applyLocally));i=i.concat(syncTreeAckUserWrite(e.serverSyncTree_,l,true))}else{u=true;d="nodata";i=i.concat(syncTreeAckUserWrite(e.serverSyncTree_,c.currentWriteId,true))}}}eventQueueRaiseEventsForChangedPath(e.eventQueue_,n,i);i=[];if(u){t[s].status=2;(function(e){setTimeout(e,Math.floor(0))})(t[s].unwatcher);if(t[s].onComplete){if(d==="nodata"){r.push((()=>t[s].onComplete(null,false,t[s].currentInputSnapshot)))}else{r.push((()=>t[s].onComplete(new Error(d),false,null)))}}}}repoPruneCompletedTransactionsBelowNode(e,e.transactionQueueTree_);for(let e=0;e<r.length;e++){exceptionGuard(r[e])}repoSendReadyTransactions(e,e.transactionQueueTree_)}function repoGetAncestorTransactionNode(e,t){let n;let r=e.transactionQueueTree_;n=pathGetFront(t);while(n!==null&&treeGetValue(r)===undefined){r=treeSubTree(r,n);t=pathPopFront(t);n=pathGetFront(t)}return r}function repoBuildTransactionQueue(e,t){const n=[];repoAggregateTransactionQueuesForNode(e,t,n);n.sort(((e,t)=>e.order-t.order));return n}function repoAggregateTransactionQueuesForNode(e,t,n){const r=treeGetValue(t);if(r){for(let e=0;e<r.length;e++){n.push(r[e])}}treeForEachChild(t,(t=>{repoAggregateTransactionQueuesForNode(e,t,n)}))}function repoPruneCompletedTransactionsBelowNode(e,t){const n=treeGetValue(t);if(n){let e=0;for(let t=0;t<n.length;t++){if(n[t].status!==2){n[e]=n[t];e++}}n.length=e;treeSetValue(t,n.length>0?n:undefined)}treeForEachChild(t,(t=>{repoPruneCompletedTransactionsBelowNode(e,t)}))}function repoAbortTransactions(e,t){const n=treeGetPath(repoGetAncestorTransactionNode(e,t));const r=treeSubTree(e.transactionQueueTree_,t);treeForEachAncestor(r,(t=>{repoAbortTransactionsOnNode(e,t)}));repoAbortTransactionsOnNode(e,r);treeForEachDescendant(r,(t=>{repoAbortTransactionsOnNode(e,t)}));return n}function repoAbortTransactionsOnNode(e,t){const n=treeGetValue(t);if(n){const r=[];let i=[];let s=-1;for(let t=0;t<n.length;t++){if(n[t].status===3);else if(n[t].status===1){o.assert(s===t-1,"All SENT items should be at beginning of queue.");s=t;n[t].status=3;n[t].abortReason="set"}else{o.assert(n[t].status===0,"Unexpected transaction status in abort");n[t].unwatcher();i=i.concat(syncTreeAckUserWrite(e.serverSyncTree_,n[t].currentWriteId,true));if(n[t].onComplete){r.push(n[t].onComplete.bind(null,new Error("set"),false,null))}}}if(s===-1){treeSetValue(t,undefined)}else{n.length=s+1}eventQueueRaiseEventsForChangedPath(e.eventQueue_,treeGetPath(t),i);for(let e=0;e<r.length;e++){exceptionGuard(r[e])}}}function decodePath(e){let t="";const n=e.split("/");for(let e=0;e<n.length;e++){if(n[e].length>0){let r=n[e];try{r=decodeURIComponent(r.replace(/\+/g," "))}catch(e){}t+="/"+r}}return t}function decodeQuery(e){const t={};if(e.charAt(0)==="?"){e=e.substring(1)}for(const n of e.split("&")){if(n.length===0){continue}const r=n.split("=");if(r.length===2){t[decodeURIComponent(r[0])]=decodeURIComponent(r[1])}else{warn(`Invalid query segment '${n}' in query '${e}'`)}}return t}const parseRepoInfo=function(e,t){const n=parseDatabaseURL(e),r=n.namespace;if(n.domain==="firebase.com"){fatal(n.host+" is no longer supported. "+"Please use <YOUR FIREBASE>.firebaseio.com instead")}if((!r||r==="undefined")&&n.domain!=="localhost"){fatal("Cannot parse Firebase url. Please use https://<YOUR FIREBASE>.firebaseio.com")}if(!n.secure){warnIfPageIsSecure()}const i=n.scheme==="ws"||n.scheme==="wss";return{repoInfo:new RepoInfo(n.host,n.secure,r,i,t,"",r!==n.subdomain),path:new Path(n.pathString)}};const parseDatabaseURL=function(e){let t="",n="",r="",i="",s="";let o=true,a="https",c=443;if(typeof e==="string"){let l=e.indexOf("//");if(l>=0){a=e.substring(0,l-1);e=e.substring(l+2)}let u=e.indexOf("/");if(u===-1){u=e.length}let d=e.indexOf("?");if(d===-1){d=e.length}t=e.substring(0,Math.min(u,d));if(u<d){i=decodePath(e.substring(u,d))}const h=decodeQuery(e.substring(Math.min(e.length,d)));l=t.indexOf(":");if(l>=0){o=a==="https"||a==="wss";c=parseInt(t.substring(l+1),10)}else{l=t.length}const p=t.slice(0,l);if(p.toLowerCase()==="localhost"){n="localhost"}else if(p.split(".").length<=2){n=p}else{const e=t.indexOf(".");r=t.substring(0,e).toLowerCase();n=t.substring(e+1);s=r}if("ns"in h){s=h["ns"]}}return{host:t,port:c,domain:n,subdomain:r,secure:o,scheme:a,pathString:i,namespace:s}};const Xe="-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz";const Ze=function(){let e=0;const t=[];return function(n){const r=n===e;e=n;let i;const s=new Array(8);for(i=7;i>=0;i--){s[i]=Xe.charAt(n%64);n=Math.floor(n/64)}o.assert(n===0,"Cannot push at time == 0");let a=s.join("");if(!r){for(i=0;i<12;i++){t[i]=Math.floor(Math.random()*64)}}else{for(i=11;i>=0&&t[i]===63;i--){t[i]=0}t[i]++}for(i=0;i<12;i++){a+=Xe.charAt(t[i])}o.assert(a.length===20,"nextPushId: Length should be 20.");return a}}();class DataEvent{constructor(e,t,n,r){this.eventType=e;this.eventRegistration=t;this.snapshot=n;this.prevName=r}getPath(){const e=this.snapshot.ref;if(this.eventType==="value"){return e._path}else{return e.parent._path}}getEventType(){return this.eventType}getEventRunner(){return this.eventRegistration.getEventRunner(this)}toString(){return this.getPath().toString()+":"+this.eventType+":"+o.str
2ingify(this.snapshot.exportVal())}}class CancelEvent{constructor(e,t,n){this.eventRegistration=e;this.error=t;this.path=n}getPath(){return this.path}getEventType(){return"cancel"}getEventRunner(){return this.eventRegistration.getEventRunner(this)}toString(){return this.path.toString()+":cancel"}}class CallbackContext{constructor(e,t){this.snapshotCallback=e;this.cancelCallback=t}onValue(e,t){this.snapshotCallback.call(null,e,t)}onCancel(e){o.assert(this.hasCancelCallback,"Raising a cancel event on a listener with no cancel callback");return this.cancelCallback.call(null,e)}get hasCancelCallback(){return!!this.cancelCallback}matches(e){return this.snapshotCallback===e.snapshotCallback||this.snapshotCallback.userCallback!==undefined&&this.snapshotCallback.userCallback===e.snapshotCallback.userCallback&&this.snapshotCallback.context===e.snapshotCallback.context}}class OnDisconnect{constructor(e,t){this._repo=e;this._path=t}cancel(){const e=new o.Deferred;repoOnDisconnectCancel(this._repo,this._path,e.wrapCallback((()=>{})));return e.promise}remove(){validateWritablePath("OnDisconnect.remove",this._path);const e=new o.Deferred;repoOnDisconnectSet(this._repo,this._path,null,e.wrapCallback((()=>{})));return e.promise}set(e){validateWritablePath("OnDisconnect.set",this._path);validateFirebaseDataArg("OnDisconnect.set",e,this._path,false);const t=new o.Deferred;repoOnDisconnectSet(this._repo,this._path,e,t.wrapCallback((()=>{})));return t.promise}setWithPriority(e,t){validateWritablePath("OnDisconnect.setWithPriority",this._path);validateFirebaseDataArg("OnDisconnect.setWithPriority",e,this._path,false);validatePriority("OnDisconnect.setWithPriority",t,false);const n=new o.Deferred;repoOnDisconnectSetWithPriority(this._repo,this._path,e,t,n.wrapCallback((()=>{})));return n.promise}update(e){validateWritablePath("OnDisconnect.update",this._path);validateFirebaseMergeDataArg("OnDisconnect.update",e,this._path,false);const t=new o.Deferred;repoOnDisconnectUpdate(this._repo,this._path,e,t.wrapCallback((()=>{})));return t.promise}}class QueryImpl{constructor(e,t,n,r){this._repo=e;this._path=t;this._queryParams=n;this._orderByCalled=r}get key(){if(pathIsEmpty(this._path)){return null}else{return pathGetBack(this._path)}}get ref(){return new ReferenceImpl(this._repo,this._path)}get _queryIdentifier(){const e=queryParamsGetQueryObject(this._queryParams);const t=ObjectToUniqueKey(e);return t==="{}"?"default":t}get _queryObject(){return queryParamsGetQueryObject(this._queryParams)}isEqual(e){e=o.getModularInstance(e);if(!(e instanceof QueryImpl)){return false}const t=this._repo===e._repo;const n=pathEquals(this._path,e._path);const r=this._queryIdentifier===e._queryIdentifier;return t&&n&&r}toJSON(){return this.toString()}toString(){return this._repo.toString()+pathToUrlEncodedString(this._path)}}function validateNoPreviousOrderByCall(e,t){if(e._orderByCalled===true){throw new Error(t+": You can't combine multiple orderBy calls.")}}function validateQueryEndpoints(e){let t=null;let n=null;if(e.hasStart()){t=e.getIndexStartValue()}if(e.hasEnd()){n=e.getIndexEndValue()}if(e.getIndex()===Pe){const r="Query: When ordering by key, you may only pass one argument to "+"startAt(), endAt(), or equalTo().";const i="Query: When ordering by key, the argument passed to startAt(), startAfter(), "+"endAt(), endBefore(), or equalTo() must be a string.";if(e.hasStart()){const n=e.getIndexStartName();if(n!==_){throw new Error(r)}else if(typeof t!=="string"){throw new Error(i)}}if(e.hasEnd()){const t=e.getIndexEndName();if(t!==v){throw new Error(r)}else if(typeof n!=="string"){throw new Error(i)}}}else if(e.getIndex()===ke){if(t!=null&&!isValidPriority(t)||n!=null&&!isValidPriority(n)){throw new Error("Query: When ordering by priority, the first argument passed to startAt(), "+"startAfter() endAt(), endBefore(), or equalTo() must be a valid priority value "+"(null, a number, or a string).")}}else{o.assert(e.getIndex()instanceof PathIndex||e.getIndex()===Ue,"unknown index type.");if(t!=null&&typeof t==="object"||n!=null&&typeof n==="object"){throw new Error("Query: First argument passed to startAt(), startAfter(), endAt(), endBefore(), or "+"equalTo() cannot be an object.")}}}function validateLimit(e){if(e.hasStart()&&e.hasEnd()&&e.hasLimit()&&!e.hasAnchoredLimit()){throw new Error("Query: Can't combine startAt(), startAfter(), endAt(), endBefore(), and limit(). Use "+"limitToFirst() or limitToLast() instead.")}}class ReferenceImpl extends QueryImpl{constructor(e,t){super(e,t,new QueryParams,false)}get parent(){const e=pathParent(this._path);return e===null?null:new ReferenceImpl(this._repo,e)}get root(){let e=this;while(e.parent!==null){e=e.parent}return e}}class DataSnapshot{constructor(e,t,n){this._node=e;this.ref=t;this._index=n}get priority(){return this._node.getPriority().val()}get key(){return this.ref.key}get size(){return this._node.numChildren()}child(e){const t=new Path(e);const n=child(this.ref,e);return new DataSnapshot(this._node.getChild(t),n,ke)}exists(){return!this._node.isEmpty()}exportVal(){return this._node.val(true)}forEach(e){if(this._node.isLeafNode()){return false}const t=this._node;return!!t.forEachChild(this._index,((t,n)=>
2e(new DataSnapshot(n,child(this.ref,t),ke))))}hasChild(e){const t=new Path(e);return!this._node.getChild(t).isEmpty()}hasChildren(){if(this._node.isLeafNode()){return false}else{return!this._node.isEmpty()}}toJSON(){return this.exportVal()}val(){return this._node.val()}}function ref(e,t){e=o.getModularInstance(e);e._checkNotDeleted("ref");return t!==undefined?child(e._root,t):e._root}function refFromURL(e,t){e=o.getModularInstance(e);e._checkNotDeleted("refFromURL");const n=parseRepoInfo(t,e._repo.repoInfo_.nodeAdmin);validateUrl("refFromURL",n);const r=n.repoInfo;if(!e._repo.repoInfo_.isCustomHost()&&r.host!==e._repo.repoInfo_.host){fatal("refFromURL"+": Host name does not match the current database: "+"(found "+r.host+" but expected "+e._repo.repoInfo_.host+")")}return ref(e,n.path.toString())}function child(e,t){e=o.getModularInstance(e);if(pathGetFront(e._path)===null){validateRootPathString("child","path",t,false)}else{validatePathString("child","path",t,false)}return new ReferenceImpl(e._repo,pathChild(e._path,t))}function onDisconnect(e){e=o.getModularInstance(e);return new OnDisconnect(e._repo,e._path)}function push(e,t){e=o.getModularInstance(e);validateWritablePath("push",e._path);validateFirebaseDataArg("push",t,e._path,true);const n=repoServerTime(e._repo);const r=Ze(n);const i=child(e,r);const s=child(e,r);let a;if(t!=null){a=set(s,t).then((()=>s))}else{a=Promise.resolve(s)}i.then=a.then.bind(a);i.catch=a.then.bind(a,undefined);return i}function remove(e){validateWritablePath("remove",e._path);return set(e,null)}function set(e,t){e=o.getModularInstance(e);validateWritablePath("set",e._path);validateFirebaseDataArg("set",t,e._path,false);const n=new o.Deferred;repoSetWithPriority(e._repo,e._path,t,null,n.wrapCallback((()=>{})));return n.promise}function setPriority(e,t){e=o.getModularInstance(e);validateWritablePath("setPriority",e._path);validatePriority("setPriority",t,false);const n=new o.Deferred;repoSetWithPriority(e._repo,pathChild(e._path,".priority"),t,null,n.wrapCallback((()=>{})));return n.promise}function setWithPriority(e,t,n){validateWritablePath("setWithPriority",e._path);validateFirebaseDataArg("setWithPriority",t,e._path,false);validatePriority("setWithPriority",n,false);if(e.key===".length"||e.key===".keys"){throw"setWithPriority failed: "+e.key+" is a read-only object."}const r=new o.Deferred;repoSetWithPriority(e._repo,e._path,t,n,r.wrapCallback((()=>{})));return r.promise}function update(e,t){validateFirebaseMergeDataArg("update",t,e._path,false);const n=new o.Deferred;repoUpdate(e._repo,e._path,t,n.wrapCallback((()=>{})));return n.promise}function get(e){e=o.getModularInstance(e);const t=new CallbackContext((()=>{}));const n=new ValueEventRegistration(t);return repoGetValue(e._repo,e,n).then((t=>new DataSnapshot(t,new ReferenceImpl(e._repo,e._path),e._queryParams.getIndex())))}class ValueEventRegistration{constructor(e){this.callbackContext=e}respondsTo(e){return e==="value"}createEvent(e,t){const n=t._queryParams.getIndex();return new DataEvent("value",this,new DataSnapshot(e.snapshotNode,new ReferenceImpl(t._repo,t._path),n))}getEventRunner(e){if(e.getEventType()==="cancel"){return()=>this.callbackContext.onCancel(e.error)}else{return()=>this.callbackContext.onValue(e.snapshot,null)}}createCancelEvent(e,t){if(this.callbackContext.hasCancelCallback){return new CancelEvent(this,e,t)}else{return null}}matches(e){if(!(e instanceof ValueEventRegistration)){return false}else if(!e.callbackContext||!this.callbackContext){return true}else{return e.callbackContext.matches(this.callbackContext)}}hasAnyCallback(){return this.callbackContext!==null}}class ChildEventRegistration{constructor(e,t){this.eventType=e;this.callbackContext=t}respondsTo(e){let t=e==="children_added"?"child_added":e;t=t==="children_removed"?"child_removed":t;return this.eventType===t}createCancelEvent(e,t){if(this.callbackContext.hasCancelCallback){return new CancelEvent(this,e,t)}else{return null}}createEvent(e,t){o.assert(e.childName!=null,"Child events should have a childName.");const n=child(new ReferenceImpl(t._repo,t._path),e.childName);const r=t._queryParams.getIndex();return new DataEvent(e.type,this,new DataSnapshot(e.snapshotNode,n,r),e.prevName)}getEventRunner(e){if(e.getEventType()==="cancel"){return()=>this.callbackContext.onCancel(e.error)}else{return()=>this.callbackContext.onValue(e.snapshot,e.prevName)}}matches(e){if(e instanceof ChildEventRegistration){return this.eventType===e.eventType&&(!this.callbackContext||!e.callbackContext||this.callbackContext.matches(e.callbackContext))}return false}hasAnyCallback(){return!!this.callbackContext}}function addEventListener(e,t,n,r,i){let s;if(typeof r==="object"){s=undefined;i=r}if(typeof r==="function"){s=r}if(i&&i.onlyOnce){const t=n;const onceCallback=(n,r)=>{repoRemoveEventCallbackForQuery(e._repo,e,a);t(n,r)};onceCallback.userCallback=n.userCallback;onceCallback.context=n.context;n=onceCallback}const o=new CallbackContext(n,s||undefined);const a=t==="value"?new ValueEventRegistration(o):new ChildEventRegistration(t,o);repoAddEventCallbackForQuery(e._repo,e,a);return()=>repoRemoveEventCallbackForQuery(e._repo,e,a)}function onValue(e,t,n,r){return addEventListener(e,"value",t,n,r)}function onChildAdded(e,t,n,r){return addEventListener(e,"child_added",t,n,r)}function onChildChanged(e,t,n,r){return addEventListener(e,"child_changed",t,n,r)}function onChildMoved(e,t,n,r){return addEventListener(e,"child_moved",t,n,r)}function onChildRemoved(e,t,n,r){return addEventListener(e,"child_removed",t,n,r)}function off(e,t,n){let r=null;const i=n?new CallbackContext(n):null;if(t==="value"){r=new ValueEventRegistration(i)}else if(t){r=new ChildEventRegistration(t,i)}repoRemoveEventCallbackForQuery(e._repo,e,r)}class QueryConstraint{}class QueryEndAtConstraint extends QueryConstraint{constructor(e,t){super();this._value=e;this._key=t;this.type="endAt"}_apply(e){validateFirebaseDataArg("endAt",this._value,e._path,true);const t=queryParamsEndAt(e._queryParams,this._value,this._key);validateLimit(t);validateQueryEndpoints(t);if(e._queryParams.hasEnd()){throw new Error("endAt: Starting point was already set 
2(by another call to endAt, "+"endBefore or equalTo).")}return new QueryImpl(e._repo,e._path,t,e._orderByCalled)}}function endAt(e,t){validateKey("endAt","key",t,true);return new QueryEndAtConstraint(e,t)}class QueryEndBeforeConstraint extends QueryConstraint{constructor(e,t){super();this._value=e;this._key=t;this.type="endBefore"}_apply(e){validateFirebaseDataArg("endBefore",this._value,e._path,false);const t=queryParamsEndBefore(e._queryParams,this._value,this._key);validateLimit(t);validateQueryEndpoints(t);if(e._queryParams.hasEnd()){throw new Error("endBefore: Starting point was already set (by another call to endAt, "+"endBefore or equalTo).")}return new QueryImpl(e._repo,e._path,t,e._orderByCalled)}}function endBefore(e,t){validateKey("endBefore","key",t,true);return new QueryEndBeforeConstraint(e,t)}class QueryStartAtConstraint extends QueryConstraint{constructor(e,t){super();this._value=e;this._key=t;this.type="startAt"}_apply(e){validateFirebaseDataArg("startAt",this._value,e._path,true);const t=queryParamsStartAt(e._queryParams,this._value,this._key);validateLimit(t);validateQueryEndpoints(t);if(e._queryParams.hasStart()){throw new Error("startAt: Starting point was already set (by another call to startAt, "+"startBefore or equalTo).")}return new QueryImpl(e._repo,e._path,t,e._orderByCalled)}}function startAt(e=null,t){validateKey("startAt","key",t,true);return new QueryStartAtConstraint(e,t)}class QueryStartAfterConstraint extends QueryConstraint{constructor(e,t){super();this._value=e;this._key=t;this.type="startAfter"}_apply(e){validateFirebaseDataArg("startAfter",this._value,e._path,false);const t=queryParamsStartAfter(e._queryParams,this._value,this._key);validateLimit(t);validateQueryEndpoints(t);if(e._queryParams.hasStart()){throw new Error("startAfter: Starting point was already set (by another call to startAt, "+"startAfter, or equalTo).")}return new QueryImpl(e._repo,e._path,t,e._orderByCalled)}}function startAfter(e,t){validateKey("startAfter","key",t,true);return new QueryStartAfterConstraint(e,t)}class QueryLimitToFirstConstraint extends QueryConstraint{constructor(e){super();this._limit=e;this.type="limitToFirst"}_apply(e){if(e._queryParams.hasLimit()){throw new Error("limitToFirst: Limit was already set (by another call to limitToFirst "+"or limitToLast).")}return new QueryImpl(e._repo,e._path,queryParamsLimitToFirst(e._queryParams,this._limit),e._orderByCalled)}}function limitToFirst(e){if(typeof e!=="number"||Math.floor(e)!==e||e<=0){throw new Error("limitToFirst: First argument must be a positive integer.")}return new QueryLimitToFirstConstraint(e)}class QueryLimitToLastConstraint extends QueryConstraint{constructor(e){super();this._limit=e;this.type="limitToLast"}_apply(e){if(e._queryParams.hasLimit()){throw new Error("limitToLast: Limit was already set (by another call to limitToFirst "+"or limitToLast).")}return new QueryImpl(e._repo,e._path,queryParamsLimitToLast(e._queryParams,this._limit),e._orderByCalled)}}function limitToLast(e){if(typeof e!=="number"||Math.floor(e)!==e||e<=0){throw new Error("limitToLast: First argument must be a positive integer.")}return new QueryLimitToLastConstraint(e)}class QueryOrderByChildConstraint extends QueryConstraint{constructor(e){super();this._path=e;this.type="orderByChild"}_apply(e){validateNoPreviousOrderByCall(e,"orderByChild");const t=new Path(this._path);if(pathIsEmpty(t)){throw new Error("orderByChild: cannot pass in empty path. Use orderByValue() instead.")}const n=new PathIndex(t);const r=queryParamsOrderBy(e._queryParams,n);validateQueryEndpoints(r);return new QueryImpl(e._repo,e._path,r,true)}}function orderByChild(e){if(e==="$key"){throw new Error('orderByChild: "$key" is invalid.  Use orderByKey() instead.')}else if(e==="$priority"){throw new Error('orderByChild: "$priority" is invalid.  Use orderByPriority() instead.')}else if(e==="$value"){throw new Error('orderByChild: "$value" is invalid.  Use orderByValue() instead.')}validatePathString("orderByChild","path",e,false);return new QueryOrderByChildConstraint(e)}class QueryOrderByKeyConstraint extends QueryConstraint{constructor(){super(...arguments);this.type="orderByKey"}_apply(e){validateNoPreviousOrderByCall(e,"orderByKey");const t=queryParamsOrderBy(e._queryParams,Pe);validateQueryEndpoints(t);return new QueryImpl(e._repo,e._path,t,true)}}function orderByKey(){return new QueryOrderByKeyConstraint}class QueryOrderByPriorityConstraint extends QueryConstraint{constructor(){super(...arguments);this.type="orderByPriority"}_apply(e){validateNoPreviousOrderByCall(e,"orderByPriority");const t=queryParamsOrderBy(e._queryParams,ke);validateQueryEndpoints(t);return new QueryImpl(e._repo,e._path,t,true)}}function orderByPriority(){return new QueryOrderByPriorityConstraint}class QueryOrderByValueConstraint extends QueryConstraint{constructor(){super(...arguments);this.type="orderByValue"}_apply(e){validateNoPreviousOrderByCall(e,"orderByValue");const t=queryParamsOrderBy(e._queryParams,Ue);validateQueryEndpoints(t);return new QueryImpl(e._repo,e._path,t,true)}}function orderByValue(){return new QueryOrderByValueConstraint}class QueryEqualToValueConstraint extends QueryConstraint{constructor(e,t){super();this._value=e;this._key=t;this.type="equalTo"}_apply(e){validateFirebaseDataArg("equalTo",this._value,e._path,false);
2if(e._queryParams.hasStart()){throw new Error("equalTo: Starting point was already set (by another call to startAt/startAfter or "+"equalTo).")}if(e._queryParams.hasEnd()){throw new Error("equalTo: Ending point was already set (by another call to endAt/endBefore or "+"equalTo).")}return new QueryEndAtConstraint(this._value,this._key)._apply(new QueryStartAtConstraint(this._value,this._key)._apply(e))}}function equalTo(e,t){validateKey("equalTo","key",t,true);return new QueryEqualToValueConstraint(e,t)}function query(e,...t){let n=o.getModularInstance(e);for(const e of t){n=e._apply(n)}return n}syncPointSetReferenceConstructor(ReferenceImpl);syncTreeSetReferenceConstructor(ReferenceImpl);const et="FIREBASE_DATABASE_EMULATOR_HOST";const tt={};let nt=false;function repoManagerApplyEmulatorSettings(e,t,n,r){const i=t.lastIndexOf(":");const s=t.substring(0,i);const a=o.isCloudWorkstation(s);e.repoInfo_=new RepoInfo(t,a,e.repoInfo_.namespace,e.repoInfo_.webSocketOnly,e.repoInfo_.nodeAdmin,e.repoInfo_.persistenceKey,e.repoInfo_.includeNamespaceInQueryParams,true,n);if(r){e.authTokenProvider_=r}}function repoManagerDatabaseFromApp(e,t,n,i,s){let o=i||e.options.databaseURL;
2if(o===undefined){if(!e.options.projectId){fatal("Can't determine Firebase Database URL. Be sure to include "+" a Project ID when calling firebase.initializeApp().")}log("Using default host for project ",e.options.projectId);o=`${e.options.projectId}-default-rtdb.firebaseio.com`}let a=parseRepoInfo(o,s);let c=a.repoInfo;let l;let u=undefined;if(typeof r!=="undefined"&&r.env){u=r.env[et]}if(u){l=true;o=`http://${u}?ns=${c.namespace}`;a=parseRepoInfo(o,s);c=a.repoInfo}else{l=!a.repoInfo.secure}const d=s&&l?new EmulatorTokenProvider(EmulatorTokenProvider.OWNER):new FirebaseAuthTokenProvider(e.name,e.options,t);validateUrl("Invalid Firebase Database URL",a);if(!pathIsEmpty(a.path)){fatal("Database URL must point to the root of a Firebase Database "+"(not including a child path).")}const h=repoManagerCreateRepo(c,e,d,new AppCheckTokenProvider(e,n));return new Database(h,e)}function repoManagerDeleteRepo(e,t){const n=tt[t];if(!n||n[e.key]!==e){fatal(`Database ${t}(${e.repoInfo_}) has already been deleted.`)}repoInterrupt(e);delete n[e.key]}function repoManagerCreateRepo(e,t,n,r){let i=tt[t.name];if(!i){i={};tt[t.name]=i}let s=i[e.toURLString()];if(s){fatal("Database initialized multiple times. Please make sure the format of the database URL matches with each database() call.")}s=new Repo(e,nt,n,r);i[e.toURLString()]=s;return s}function repoManagerForceRestClient(e){nt=e}class Database{constructor(e,t){this._repoInternal=e;this.app=t;this["type"]="database";this._instanceStarted=false}get _repo(){if(!this._instanceStarted){repoStart(this._repoInternal,this.app.options.appId,this.app.options["databaseAuthVariableOverride"]);this._instanceStarted=true}return this._repoInternal}get _root(){if(!this._rootInternal){this._rootInternal=new ReferenceImpl(this._repo,newEmptyPath())}return this._rootInternal}_delete(){if(this._rootInternal!==null){repoManagerDeleteRepo(this._repo,this.app.name);this._repoInternal=null;this._rootInternal=null}return Promise.resolve()}_checkNotDeleted(e){if(this._rootInternal===null){fatal("Cannot call "+e+" on a deleted database.")}}}function checkTransportInit(){if(TransportManager.IS_TRANSPORT_INITIALIZED){warn("Transport has already been initialized. Please call this function before calling ref or setting up a listener")}}function forceWebSockets(){checkTransportInit();BrowserPollConnection.forceDisallow()}function forceLongPolling(){checkTransportInit();WebSocketConnection.forceDisallow();BrowserPollConnection.forceAllow()}function getDatabase(e=i.getApp(),t){const n=i._getProvider(e,"database").getImmediate({identifier:t});if(!n._instanceStarted){const e=o.getDefaultEmulatorHostnameAndPort("database");if(e){connectDatabaseEmulator(n,...e)}}return n}function connectDatabaseEmulator(e,t,n,r={}){e=o.getModularInstance(e);e._checkNotDeleted("useEmulator");const i=`${t}:${n}`;const s=e._repoInternal;if(e._instanceStarted){if(i===e._repoInternal.repoInfo_.host&&o.deepEqual(r,s.repoInfo_.emulatorOptions)){return}fatal("connectDatabaseEmulator() cannot initialize or alter the emulator configuration after the database instance has started.")}let a=undefined;if(s.repoInfo_.nodeAdmin){if(r.mockUserToken){fatal('mockUserToken is not supported by the Admin SDK. For client access with mock users, please use the "firebase" package instead of "firebase-admin".')}a=new EmulatorTokenProvider(EmulatorTokenProvider.OWNER)}else if(r.mockUserToken){const t=typeof r.mockUserToken==="string"?r.mockUserToken:o.createMockUserToken(r.mockUserToken,e.app.options.projectId);a=new EmulatorTokenProvider(t)}if(o.isCloudWorkstation(t)){void o.pingServer(t)}repoManagerApplyEmulatorSettings(s,i,r,a)}function goOffline(e){e=o.getModularInstance(e);e._checkNotDeleted("goOffline");repoInterrupt(e._repo)}function goOnline(e){e=o.getModularInstance(e);e._checkNotDeleted("goOnline");repoResume(e._repo)}function enableLogging(e,t){enableLogging$1(e,t)}function registerDatabase(e){setSDKVersion(i.SDK_VERSION);i._registerComponent(new s.Component("database",((e,{instanceIdentifier:t})=>{const n=e.getProvider("app").getImmediate();const r=e.getProvider("auth-internal");const i=e.getProvider("app-check-internal");return repoManagerDatabaseFromApp(n,r,i,t)}),"PUBLIC").setMultipleInstances(true));i.registerVersion(c,l,e);i.registerVersion(c,l,"cjs2020")}const rt={".sv":"timestamp"};function serverTimestamp(){return rt}function increment(e){return{".sv":{increment:e}}}class TransactionResult{constructor(e,t){this.committed=e;this.snapshot=t}toJSON(){return{committed:this.committed,snapshot:this.snapshot.toJSON()}}}function runTransaction(e,t,n){e=o.getModularInstance(e);validateWritablePath("Reference.transaction",e._path);if(e.key===".length"||e.key===".keys"){throw"Reference.transaction failed: "+e.key+" is a read-only object."}const r=n?.applyLocally??true;const i=new o.Deferred;const promiseComplete=(t,n,r)=>{let s=null;if(t){i.reject(t)}else{s=new DataSnapshot(r,new ReferenceImpl(e._repo,e._path),ke);i.resolve(new TransactionResult(n,s))}};const s=onValue(e,(()=>{}));repoStartTransaction(e._repo,e._path,t,promiseComplete,s,r);return i.promise}PersistentConnection;PersistentConnection.prototype.simpleListen=function(e,t){this.sendRequest("q",{p:e},t)};PersistentConnection.prototype.echo=function(e,t){this.sendRequest("echo",{d:e},t)};Connection;const hijackHash=function(e){const t=PersistentConnection.prototype.put;
2PersistentConnection.prototype.put=function(n,r,i,s){if(s!==undefined){s=e()}t.call(this,n,r,i,s)};return function(){PersistentConnection.prototype.put=t}};RepoInfo;const forceRestClient=function(e){repoManagerForceRestClient(e)};function _initStandalone({app:e,url:t,version:n,customAuthImpl:r,customAppCheckImpl:i,nodeAdmin:o=false}){setSDKVersion(n);const a=new s.ComponentContainer("database-standalone");const c=new s.Provider("auth-internal",a);let l;if(i){l=new s.Provider("app-check-internal",a);l.setComponent(new s.Component("app-check-internal",(()=>i),"PRIVATE"))}c.setComponent(new s.Component("auth-internal",(()=>r),"PRIVATE"));return repoManagerDatabaseFromApp(e,c,l,t,o)}registerDatabase();t.DataSnapshot=DataSnapshot;t.Database=Database;t.OnDisconnect=OnDisconnect;t.QueryConstraint=QueryConstraint;t.TransactionResult=TransactionResult;t._QueryImpl=QueryImpl;t._QueryParams=QueryParams;t._ReferenceImpl=ReferenceImpl;t._TEST_ACCESS_forceRestClient=forceRestClient;t._TEST_ACCESS_hijackHash=hijackHash;t._initStandalone=_initStandalone;t._repoManagerDatabaseFromApp=repoManagerDatabaseFromApp;t._setSDKVersion=setSDKVersion;t._validatePathString=validatePathString;t._validateWritablePath=validateWritablePath;t.child=child;t.connectDatabaseEmulator=connectDatabaseEmulator;t.enableLogging=enableLogging;t.endAt=endAt;t.endBefore=endBefore;t.equalTo=equalTo;t.forceLongPolling=forceLongPolling;t.forceWebSockets=forceWebSockets;t.get=get;t.getDatabase=getDatabase;t.goOffline=goOffline;t.goOnline=goOnline;t.increment=increment;t.limitToFirst=limitToFirst;t.limitToLast=limitToLast;t.off=off;t.onChildAdded=onChildAdded;t.onChildChanged=onChildChanged;t.onChildMoved=onChildMoved;t.onChildRemoved=onChildRemoved;t.onDisconnect=onDisconnect;t.onValue=onValue;t.orderByChild=orderByChild;t.orderByKey=orderByKey;t.orderByPriority=orderByPriority;t.orderByValue=orderByValue;t.push=push;t.query=query;t.ref=ref;t.refFromURL=refFromURL;t.remove=remove;t.runTransaction=runTransaction;t.serverTimestamp=serverTimestamp;t.set=set;t.setPriority=setPriority;t.setWithPriority=setWithPriority;t.startAfter=startAfter;t.startAt=startAt;t.update=update},40767(e,t){Object.defineProperty(t,"__esModule",{value:true});const n=[];t.LogLevel=void 0;(function(e){e[e["DEBUG"]=0]="DEBUG";e[e["VERBOSE"]=1]="VERBOSE";e[e["INFO"]=2]="INFO";e[e["WARN"]=3]="WARN";e[e["ERROR"]=4]="ERROR";e[e["SILENT"]=5]="SILENT"})(t.LogLevel||(t.LogLevel={}));const r={debug:t.LogLevel.DEBUG,verbose:t.LogLevel.VERBOSE,info:t.LogLevel.INFO,warn:t.LogLevel.WARN,error:t.LogLevel.ERROR,silent:t.LogLevel.SILENT};const i=t.LogLevel.INFO;const s={[t.LogLevel.DEBUG]:"log",[t.LogLevel.VERBOSE]:"log",[t.LogLevel.INFO]:"info",[t.LogLevel.WARN]:"warn",[t.LogLevel.ERROR]:"error"};const defaultLogHandler=(e,t,...n)=>{if(t<e.logLevel){return}const r=(new Date).toISOString();const i=s[t];if(i){console[i](`[${r}]  ${e.name}:`,...n)}else{throw new Error(`Attempted to log a message with an invalid logType (value: ${t})`)}};class Logger{constructor(e){this.name=e;this._logLevel=i;this._logHandler=defaultLogHandler;this._userLogHandler=null;n.push(this)}get logLevel(){return this._logLevel}set logLevel(e){if(!(e in t.LogLevel)){throw new TypeError(`Invalid value "${e}" assigned to \`logLevel\``)}this._logLevel=e}setLogLevel(e){this._logLevel=typeof e==="string"?r[e]:e}get logHandler(){return this._logHandler}set logHandler(e){if(typeof e!=="function"){throw new TypeError("Value assigned to `logHandler` must be a function")}this._logHandler=e}get userLogHandler(){return this._userLogHandler}set userLogHandler(e){this._userLogHandler=e}debug(...e){this._userLogHandler&&this._userLogHandler(this,t.LogLevel.DEBUG,...e);this._logHandler(this,t.LogLevel.DEBUG,...e)}log(...e){this._userLogHandler&&this._userLogHandler(this,t.LogLevel.VERBOSE,...e);this._logHandler(this,t.LogLevel.VERBOSE,...e)}info(...e){this._userLogHandler&&this._userLogHandler(this,t.LogLevel.INFO,...e);this._logHandler(this,t.LogLevel.INFO,...e)}warn(...e){this._userLogHandler&&this._userLogHandler(this,t.LogLevel.WARN,...e);this._logHandler(this,t.LogLevel.WARN,...e)}error(...e){this._userLogHandler&&this._userLogHandler(this,t.LogLevel.ERROR,...e);this._logHandler(this,t.LogLevel.ERROR,...e)}}
2function setLogLevel(e){n.forEach((t=>{t.setLogLevel(e)}))}function setUserLogHandler(e,i){for(const s of n){let n=null;if(i&&i.level){n=r[i.level]}if(e===null){s.userLogHandler=null}else{s.userLogHandler=(r,i,...s)=>{const o=s.map((e=>{if(e==null){return null}else if(typeof e==="string"){return e}else if(typeof e==="number"||typeof e==="boolean"){return e.toString()}else if(e instanceof Error){return e.message}else{try{return JSON.stringify(e)}catch(e){return null}}})).filter((e=>e)).join(" ");if(i>=(n??r.logLevel)){e({level:t.LogLevel[i].toLowerCase(),message:o,args:s,type:r.name})}}}}}t.Logger=Logger;t.setLogLevel=setLogLevel;t.setUserLogHandler=setUserLogHandler},36183(e,t,n){var r=n(8237);Object.defineProperty(t,"__esModule",{value:true});var i=n(88430);const s={NODE_CLIENT:false,NODE_ADMIN:false,SDK_VERSION:"${JSCORE_VERSION}"};const assert=function(e,t){if(!e){throw assertionError(t)}};const assertionError=function(e){return new Error("Firebase Database ("+s.SDK_VERSION+") INTERNAL ASSERT FAILED: "+e)};const stringToByteArray$1=function(e){const t=[];let n=0;for(let r=0;r<e.length;r++){let i=e.charCodeAt(r);if(i<128){t[n++]=i}else if(i<2048){t[n++]=i>>6|192;t[n++]=i&63|128}else if((i&64512)===55296&&r+1<e.length&&(e.charCodeAt(r+1)&64512)===56320){i=65536+((i&1023)<<10)+(e.charCodeAt(++r)&1023);t[n++]=i>>18|240;t[n++]=i>>12&63|128;t[n++]=i>>6&63|128;t[n++]=i&63|128}else{t[n++]=i>>12|224;t[n++]=i>>6&63|128;t[n++]=i&63|128}}return t};const byteArrayToString=function(e){const t=[];let n=0,r=0;while(n<e.length){const i=e[n++];if(i<128){t[r++]=String.fromCharCode(i)}else if(i>191&&i<224){const s=e[n++];t[r++]=String.fromCharCode((i&31)<<6|s&63)}else if(i>239&&i<365){const s=e[n++];const o=e[n++];const a=e[n++];const c=((i&7)<<18|(s&63)<<12|(o&63)<<6|a&63)-65536;t[r++]=String.fromCharCode(55296+(c>>10));t[r++]=String.fromCharCode(56320+(c&1023))}else{const s=e[n++];const o=e[n++];t[r++]=String.fromCharCode((i&15)<<12|(s&63)<<6|o&63)}}return t.join("")};const o={byteToCharMap_:null,charToByteMap_:null,byteToCharMapWebSafe_:null,charToByteMapWebSafe_:null,ENCODED_VALS_BASE:"ABCDEFGHIJKLMNOPQRSTUVWXYZ"+"abcdefghijklmnopqrstuvwxyz"+"0123456789",get ENCODED_VALS(){return this.ENCODED_VALS_BASE+"+/="},get ENCODED_VALS_WEBSAFE(){return this.ENCODED_VALS_BASE+"-_."},HAS_NATIVE_SUPPORT:typeof atob==="function",encodeByteArray(e,t){if(!Array.isArray(e)){throw Error("encodeByteArray takes an array as a parameter")}this.init_();const n=t?this.byteToCharMapWebSafe_:this.byteToCharMap_;const r=[];for(let t=0;t<e.length;t+=3){const i=e[t];const s=t+1<e.length;const o=s?e[t+1]:0;const a=t+2<e.length;const c=a?e[t+2]:0;const l=i>>2;const u=(i&3)<<4|o>>4;let d=(o&15)<<2|c>>6;let h=c&63;if(!a){h=64;if(!s){d=64}}r.push(n[l],n[u],n[d],n[h])}return r.join("")},encodeString(e,t){if(this.HAS_NATIVE_SUPPORT&&!t){return btoa(e)}return this.encodeByteArray(stringToByteArray$1(e),t)},decodeString(e,t){if(this.HAS_NATIVE_SUPPORT&&!t){return atob(e)}return byteArrayToString(this.decodeStringToByteArray(e,t))},decodeStringToByteArray(e,t){this.init_();const n=t?this.charToByteMapWebSafe_:this.charToByteMap_;const r=[];for(let t=0;t<e.length;){const i=n[e.charAt(t++)];const s=t<e.length;const o=s?n[e.charAt(t)]:0;++t;const a=t<e.length;const c=a?n[e.charAt(t)]:64;++t;const l=t<e.length;const u=l?n[e.charAt(t)]:64;++t;if(i==null||o==null||c==null||u==null){throw new DecodeBase64StringError}const d=i<<2|o>>4;r.push(d);if(c!==64){const e=o<<4&240|c>>2;r.push(e);if(u!==64){const e=c<<6&192|u;r.push(e)}}}return r},init_(){if(!this.byteToCharMap_){this.byteToCharMap_={};this.charToByteMap_={};this.byteToCharMapWebSafe_={};this.charToByteMapWebSafe_={};for(let e=0;e<this.ENCODED_VALS.length;e++){this.byteToCharMap_[e]=this.ENCODED_VALS.charAt(e);this.charToByteMap_[this.byteToCharMap_[e]]=e;this.byteToCharMapWebSafe_[e]=this.ENCODED_VALS_WEBSAFE.charAt(e);this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[e]]=e;if(e>=this.ENCODED_VALS_BASE.length){this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(e)]=e;this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(e)]=e}}}}};
2class DecodeBase64StringError extends Error{constructor(){super(...arguments);this.name="DecodeBase64StringError"}}const base64Encode=function(e){const t=stringToByteArray$1(e);return o.encodeByteArray(t,true)};const base64urlEncodeWithoutPadding=function(e){return base64Encode(e).replace(/\./g,"")};const base64Decode=function(e){try{return o.decodeString(e,true)}catch(e){console.error("base64Decode failed: ",e)}return null};function deepCopy(e){return deepExtend(undefined,e)}function deepExtend(e,t){if(!(t instanceof Object)){return t}switch(t.constructor){case Date:const n=t;return new Date(n.getTime());case Object:if(e===undefined){e={}}break;case Array:e=[];break;default:return t}for(const n in t){if(!t.hasOwnProperty(n)||!isValidKey(n)){continue}e[n]=deepExtend(e[n],t[n])}return e}function isValidKey(e){return e!=="__proto__"}function getGlobal(){if(typeof self!=="undefined"){return self}if(typeof window!=="undefined"){return window}if(typeof n.g!=="undefined"){return n.g}throw new Error("Unable to locate global object.")}const getDefaultsFromGlobal=()=>getGlobal().__FIREBASE_DEFAULTS__;const getDefaultsFromEnvVariable=()=>{if(typeof r==="undefined"||typeof r.env==="undefined"){return}const e=r.env.__FIREBASE_DEFAULTS__;if(e){return JSON.parse(e)}};const getDefaultsFromCookie=()=>{if(typeof document==="undefined"){return}let e;try{e=document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/)}catch(e){return}const t=e&&base64Decode(e[1]);return t&&JSON.parse(t)};const getDefaults=()=>{try{return i.getDefaultsFromPostinstall()||getDefaultsFromGlobal()||getDefaultsFromEnvVariable()||getDefaultsFromCookie()}catch(e){console.info(`Unable to get __FIREBASE_DEFAULTS__ due to: ${e}`);return}};const getDefaultEmulatorHost=e=>getDefaults()?.emulatorHosts?.[e];const getDefaultEmulatorHostnameAndPort=e=>{const t=getDefaultEmulatorHost(e);if(!t){return undefined}const n=t.lastIndexOf(":");if(n<=0||n+1===t.length){throw new Error(`Invalid host ${t} with no separate hostname and port!`)}const r=parseInt(t.substring(n+1),10);if(t[0]==="["){return[t.substring(1,n-1),r]}else{return[t.substring(0,n),r]}};const getDefaultAppConfig=()=>getDefaults()?.config;const getExperimentalSetting=e=>getDefaults()?.[`_${e}`];class Deferred{constructor(){this.reject=()=>{};this.resolve=()=>{};this.promise=new Promise(((e,t)=>{this.resolve=e;this.reject=t}))}wrapCallback(e){return(t,n)=>{if(t){this.reject(t)}else{this.resolve(n)}if(typeof e==="function"){this.promise.catch((()=>{}));if(e.length===1){e(t)}else{e(t,n)}}}}}function createMockUserToken(e,t){if(e.uid){throw new Error('The "uid" field is no longer supported by mockUserToken. Please use "sub" instead for Firebase Auth User ID.')}const n={alg:"none",type:"JWT"};const r=t||"demo-project";const i=e.iat||0;const s=e.sub||e.user_id;if(!s){throw new Error("mockUserToken must contain 'sub' or 'user_id' field!")}const o={iss:`https://securetoken.google.com/${r}`,aud:r,iat:i,exp:i+3600,auth_time:i,sub:s,user_id:s,firebase:{sign_in_provider:"custom",identities:{}},...e};const a="";return[base64urlEncodeWithoutPadding(JSON.stringify(n)),base64urlEncodeWithoutPadding(JSON.stringify(o)),a].join(".")}function getUA(){if(typeof navigator!=="undefined"&&typeof navigator["userAgent"]==="string"){return navigator["userAgent"]}else{return""}}function isMobileCordova(){return typeof window!=="undefined"&&!!(window["cordova"]||window["ph
2onegap"]||window["PhoneGap"])&&/ios|iphone|ipod|ipad|android|blackberry|iemobile/i.test(getUA())}function isNode(){const e=getDefaults()?.forceEnvironment;if(e==="node"){return true}else if(e==="browser"){return false}try{return Object.prototype.toString.call(n.g.process)==="[object process]"}catch(e){return false}}function isBrowser(){return typeof window!=="undefined"||isWebWorker()}function isWebWorker(){return typeof WorkerGlobalScope!=="undefined"&&typeof self!=="undefined"&&self instanceof WorkerGlobalScope}function isCloudflareWorker(){return typeof navigator!=="undefined"&&navigator.userAgent==="Cloudflare-Workers"}function isBrowserExtension(){const e=typeof chrome==="object"?chrome.runtime:typeof browser==="object"?browser.runtime:undefined;return typeof e==="object"&&e.id!==undefined}function isReactNative(){return typeof navigator==="object"&&navigator["product"]==="ReactNative"}function isElectron(){return getUA().indexOf("Electron/")>=0}function isIE(){const e=getUA();return e.indexOf("MSIE ")>=0||e.indexOf("Trident/")>=0}function isUWP(){return getUA().indexOf("MSAppHost/")>=0}function isNodeSdk(){return s.NODE_CLIENT===true||s.NODE_ADMIN===true}function isSafari(){return!isNode()&&!!navigator.userAgent&&navigator.userAgent.includes("Safari")&&!navigator.userAgent.includes("Chrome")}function isSafariOrWebkit(){return!isNode()&&!!navigator.userAgent&&(navigator.userAgent.includes("Safari")||navigator.userAgent.includes("WebKit"))&&!navigator.userAgent.includes("Chrome")}function isIndexedDBAvailable(){try{return typeof indexedDB==="object"}catch(e){return false}}function validateIndexedDBOpenable(){return new Promise(((e,t)=>{try{let n=true;const r="validate-browser-context-for-indexeddb-analytics-module";const i=self.indexedDB.open(r);i.onsuccess=()=>{i.result.close();if(!n){self.indexedDB.deleteDatabase(r)}e(true)};i.onupgradeneeded=()=>{n=false};i.onerror=()=>{t(i.error?.message||"")}}catch(e){t(e)}}))}function areCookiesEnabled(){if(typeof navigator==="undefined"||!navigator.cookieEnabled){return false}return true}const a="FirebaseError";class FirebaseError extends Error{constructor(e,t,n){super(t);this.code=e;this.customData=n;this.name=a;Object.setPrototypeOf(this,FirebaseError.prototype);if(Error.captureStackTrace){Error.captureStackTrace(this,ErrorFactory.prototype.create)}}}class ErrorFactory{constructor(e,t,n){this.service=e;this.serviceName=t;this.errors=n}create(e,...t){const n=t[0]||{};const r=`${this.service}/${e}`;const i=this.errors[e];const s=i?replaceTemplate(i,n):"Error";const o=`${this.serviceName}: ${s} (${r}).`;const a=new FirebaseError(r,o,n);return a}}function replaceTemplate(e,t){return e.replace(c,((e,n)=>{const r=t[n];return r!=null?String(r):`<${n}?>`}))}const c=/\{\$([^}]+)}/g;function jsonEval(e){return JSON.parse(e)}function stringify(e){return JSON.stringify(e)}const decode=function(e){let t={},n={},r={},i="";try{const s=e.split(".");t=jsonEval(base64Decode(s[0])||"");n=jsonEval(base64Decode(s[1])||"");i=s[2];r=n["d"]||{};delete n["d"]}catch(e){}return{header:t,claims:n,data:r,signature:i}};const isValidTimestamp=function(e){const t=decode(e).claims;const n=Math.floor((new Date).getTime()/1e3);let r=0,i=0;if(typeof t==="object"){if(t.hasOwnProperty("nbf")){r=t["nbf"]}else if(t.hasOwnProperty("iat")){r=t["iat"]}if(t.hasOwnProperty("exp")){i=t["exp"]}else{i=r+86400}}return!!n&&!!r&&!!i&&n>=r&&n<=i};const issuedAtTime=function(e){const t=decode(e).claims;if(typeof t==="object"&&t.hasOwnProperty("iat")){return t["iat"]}return null};const isValidFormat=function(e){const t=decode(e),n=t.claims;return!!n&&typeof n==="object"&&n.hasOwnProperty("iat")};const isAdmin=function(e){const t=decode(e).claims;return typeof t==="object"&&t["admin"]===true};function contains(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function safeGet(e,t){if(Object.prototype.hasOwnProperty.call(e,t)){return e[t]}else{return undefined}}function isEmpty(e){for(const t in e){if(Object.prototype.hasOwnProperty.call(e,t)){return false}}return true}function map(e,t,n){const r={};for(const i in e){if(Object.prototype.hasOwnProperty.call(e,i)){r[i]=t.call(n,e[i],i,e)}}return r}function deepEqual(e,t){if(e===t){return true}const n=Object.keys(e);const r=Object.keys(t);for(const i of n){if(!r.includes(i)){return false}const n=e[i];const s=t[i];
2if(isObject(n)&&isObject(s)){if(!deepEqual(n,s)){return false}}else if(n!==s){return false}}for(const e of r){if(!n.includes(e)){return false}}return true}function isObject(e){return e!==null&&typeof e==="object"}function promiseWithTimeout(e,t=2e3){const n=new Deferred;setTimeout((()=>n.reject("timeout!")),t);e.then(n.resolve,n.reject);return n.promise}function querystring(e){const t=[];for(const[n,r]of Object.entries(e)){if(Array.isArray(r)){r.forEach((e=>{t.push(encodeURIComponent(n)+"="+encodeURIComponent(e))}))}else{t.push(encodeURIComponent(n)+"="+encodeURIComponent(r))}}return t.length?"&"+t.join("&"):""}function querystringDecode(e){const t={};const n=e.replace(/^\?/,"").split("&");n.forEach((e=>{if(e){const[n,r]=e.split("=");t[decodeURIComponent(n)]=decodeURIComponent(r)}}));return t}function extractQuerystring(e){const t=e.indexOf("?");if(!t){return""}const n=e.indexOf("#",t);return e.substring(t,n>0?n:undefined)}class Sha1{constructor(){this.chain_=[];this.buf_=[];this.W_=[];this.pad_=[];this.inbuf_=0;this.total_=0;this.blockSize=512/8;this.pad_[0]=128;for(let e=1;e<this.blockSize;++e){this.pad_[e]=0}this.reset()}reset(){this.chain_[0]=1732584193;this.chain_[1]=4023233417;this.chain_[2]=2562383102;this.chain_[3]=271733878;this.chain_[4]=3285377520;this.inbuf_=0;this.total_=0}compress_(e,t){if(!t){t=0}const n=this.W_;if(typeof e==="string"){for(let r=0;r<16;r++){n[r]=e.charCodeAt(t)<<24|e.charCodeAt(t+1)<<16|e.charCodeAt(t+2)<<8|e.charCodeAt(t+3);t+=4}}else{for(let r=0;r<16;r++){n[r]=e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3];t+=4}}for(let e=16;e<80;e++){const t=n[e-3]^n[e-8]^n[e-14]^n[e-16];n[e]=(t<<1|t>>>31)&4294967295}let r=this.chain_[0];let i=this.chain_[1];let s=this.chain_[2];let o=this.chain_[3];let a=this.chain_[4];let c,l;for(let e=0;e<80;e++){if(e<40){if(e<20){c=o^i&(s^o);l=1518500249}else{c=i^s^o;l=1859775393}}else{if(e<60){c=i&s|o&(i|s);l=2400959708}else{c=i^s^o;l=3395469782}}const t=(r<<5|r>>>27)+c+a+l+n[e]&4294967295;a=o;o=s;s=(i<<30|i>>>2)&4294967295;i=r;r=t}this.chain_[0]=this.chain_[0]+r&4294967295;this.chain_[1]=this.chain_[1]+i&4294967295;this.chain_[2]=this.chain_[2]+s&4294967295;this.chain_[3]=this.chain_[3]+o&4294967295;this.chain_[4]=this.chain_[4]+a&4294967295}update(e,t){if(e==null){return}if(t===undefined){t=e.length}const n=t-this.blockSize;let r=0;const i=this.buf_;let s=this.inbuf_;while(r<t){if(s===0){while(r<=n){this.compress_(e,r);r+=this.blockSize}}if(typeof e==="string"){while(r<t){i[s]=e.charCodeAt(r);++s;++r;if(s===this.blockSize){this.compress_(i);s=0;break}}}else{while(r<t){i[s]=e[r];++s;++r;if(s===this.blockSize){this.compress_(i);s=0;break}}}}this.inbuf_=s;this.total_+=t}digest(){const e=[];let t=this.total_*8;if(this.inbuf_<56){this.update(this.pad_,56-this.inbuf_)}else{this.update(this.pad_,this.blockSize-(this.inbuf_-56))}for(let e=this.blockSize-1;e>=56;e--){this.buf_[e]=t&255;t/=256}this.compress_(this.buf_);let n=0;for(let t=0;t<5;t++){for(let r=24;r>=0;r-=8){e[n]=this.chain_[t]>>r&255;++n}}return e}}function createSubscribe(e,t){const n=new ObserverProxy(e,t);return n.subscribe.bind(n)}class ObserverProxy{constructor(e,t){this.observers=[];this.unsubscribes=[];this.observerCount=0;this.task=Promise.resolve();this.finalized=false;this.onNoObservers=t;this.task.then((()=>{e(this)})).catch((e=>{this.error(e)}))}next(e){this.forEachObserver((t=>{t.next(e)}))}error(e){this.forEachObserver((t=>{t.error(e)}));this.close(e)}complete(){this.forEachObserver((e=>{e.complete()}));this.close()}subscribe(e,t,n){let r;if(e===undefined&&t===undefined&&n===undefined){throw new Error("Missing Observer.")}if(implementsAnyMethods(e,["next","error","complete"])){r=e}else{r={next:e,error:t,complete:n}}if(r.next===undefined){r.next=noop}if(r.error===undefined){r.error=noop}if(r.complete===undefined){r.complete=noop}const i=this.unsubscribeOne.bind(this,this.observers.length);if(this.finalized){this.task.then((()=>{try{if(this.finalError){r.error(this.finalError)}else{r.complete()}}catch(e){}return}))}this.observers.push(r);return i}unsubscribeOne(e){if(this.observers===undefined||this.observers[e]===undefined){return}delete this.observers[e];this.observerCount-=1;if(this.observerCount===0&&this.onNoObservers!==undefined){this.onNoObservers(this)}}forEachObserver(e){if(this.finalized){return}for(let t=0;t<this.observers.length;t++){this.sendOne(t,e)}}sendOne(e,t){this.task.then((()=>
2{if(this.observers!==undefined&&this.observers[e]!==undefined){try{t(this.observers[e])}catch(e){if(typeof console!=="undefined"&&console.error){console.error(e)}}}}))}close(e){if(this.finalized){return}this.finalized=true;if(e!==undefined){this.finalError=e}this.task.then((()=>{this.observers=undefined;this.onNoObservers=undefined}))}}function async(e,t){return(...n)=>{Promise.resolve(true).then((()=>{e(...n)})).catch((e=>{if(t){t(e)}}))}}function implementsAnyMethods(e,t){if(typeof e!=="object"||e===null){return false}for(const n of t){if(n in e&&typeof e[n]==="function"){return true}}return false}function noop(){}const validateArgCount=function(e,t,n,r){let i;if(r<t){i="at least "+t}else if(r>n){i=n===0?"none":"no more than "+n}if(i){const t=e+" failed: Was called with "+r+(r===1?" argument.":" arguments.")+" Expects "+i+".";throw new Error(t)}};function errorPrefix(e,t){return`${e} failed: ${t} argument `}function validateNamespace(e,t,n){if(n&&!t){return}if(typeof t!=="string"){throw new Error(errorPrefix(e,"namespace")+"must be a valid firebase namespace.")}}function validateCallback(e,t,n,r){if(r&&!n){return}if(typeof n!=="function"){throw new Error(errorPrefix(e,t)+"must be a valid function.")}}function validateContextObject(e,t,n,r){if(r&&!n){return}if(typeof n!=="object"||n===null){throw new Error(errorPrefix(e,t)+"must be a valid context object.")}}const stringToByteArray=function(e){const t=[];let n=0;for(let r=0;r<e.length;r++){let i=e.charCodeAt(r);if(i>=55296&&i<=56319){const t=i-55296;r++;assert(r<e.length,"Surrogate pair missing trail surrogate.");const n=e.charCodeAt(r)-56320;i=65536+(t<<10)+n}if(i<128){t[n++]=i}else if(i<2048){t[n++]=i>>6|192;t[n++]=i&63|128}else if(i<65536){t[n++]=i>>12|224;t[n++]=i>>6&63|128;t[n++]=i&63|128}else{t[n++]=i>>18|240;t[n++]=i>>12&63|128;t[n++]=i>>6&63|128;t[n++]=i&63|128}}return t};const stringLength=function(e){let t=0;for(let n=0;n<e.length;n++){const r=e.charCodeAt(n);if(r<128){t++}else if(r<2048){t+=2}else if(r>=55296&&r<=56319){t+=4;n++}else{t+=3}}return t};const l=1e3;const u=2;const d=4*60*60*1e3;const h=.5;function calculateBackoffMillis(e,t=l,n=u){const r=t*Math.pow(n,e);const i=Math.round(h*r*(Math.random()-.5)*2);return Math.min(d,r+i)}function ordinal(e){if(!Number.isFinite(e)){return`${e}`}return e+indicator(e)}function indicator(e){e=Math.abs(e);const t=e%100;if(t>=10&&t<=20){return"th"}const n=e%10;if(n===1){return"st"}if(n===2){return"nd"}if(n===3){return"rd"}return"th"}function getModularInstance(e){if(e&&e._delegate){return e._delegate}else{return e}}function isCloudWorkstation(e){try{const t=e.startsWith("http://")||e.startsWith("https://")?new URL(e).hostname:e;return t.endsWith(".cloudworkstations.dev")}catch{return false}}async function pingServer(e){const t=await fetch(e,{credentials:"include"});return t.ok}async function generateSHA256Hash(e){const t=new TextEncoder;const n=t.encode(e);const r=await crypto.subtle.digest("SHA-256",n);const i=Array.from(new Uint8Array(r));const s=i.map((e=>e.toString(16).padStart(2,"0"))).join("");return s}t.CONSTANTS=s;t.DecodeBase64StringError=DecodeBase64StringError;t.Deferred=Deferred;t.ErrorFactory=ErrorFactory;t.FirebaseError=FirebaseError;t.MAX_VALUE_MILLIS=d;t.RANDOM_FACTOR=h;t.Sha1=Sha1;t.areCookiesEnabled=areCookiesEnabled;t.assert=assert;t.assertionError=assertionError;t.async=async;t.base64=o;t.base64Decode=base64Decode;t.base64Encode=base64Encode;t.base64urlEncodeWithoutPadding=base64urlEncodeWithoutPadding;t.calculateBackoffMillis=calculateBackoffMillis;t.contains=contains;t.createMockUserToken=createMockUserToken;t.createSubscribe=createSubscribe;t.decode=decode;t.deepCopy=deepCopy;t.deepEqual=deepEqual;t.deepExtend=deepExtend;t.errorPrefix=errorPrefix;t.extractQuerystring=extractQuerystring;t.generateSHA256Hash=generateSHA256Hash;t.getDefaultAppConfig=getDefaultAppConfig;t.getDefaultEmulatorHost=getDefaultEmulatorHost;t.getDefaultEmulatorHostnameAndPort=getDefaultEmulatorHostnameAndPort;t.getDefaults=getDefaults;t.getExperimentalSetting=getExperimentalSetting;t.getGlobal=getGlobal;t.getModularInstance=getModularInstance;t.getUA=getUA;t.isAdmin=isAdmin;t.isBrowser=isBrowser;t.isBrowserExtension=isBrowserExtension;t.isCloudWorkstation=isCloudWorkstation;t.isCloudflareWorker=isCloudflareWorker;t.isElectron=isElectron;t.isEmpty=isEmpty;t.isIE=isIE;t.isIndexedDBAvailable=isIndexedDBAvailable;t.isMobileCordova=isMobileCordova;t.isNode=isNode;t.isNodeSdk=isNodeSdk;t.isReactNative=isReactNative;t.isSafari=isSafari;t.isSafariOrWebkit=isSafariOrWebkit;t.isUWP=isUWP;t.isValidFormat=isValidFormat;t.isValidTimestamp=isValidTimestamp;t.isWebWorker=isWebWorker;t.issuedAtTime=issuedAtTime;t.jsonEval=jsonEval;t.map=map;t.ordinal=ordinal;t.pingServer=pingServer;t.promiseWithTimeout=promiseWithTimeout;t.querystring=querystring;t.querystringDecode=querystringDecode;t.safeGet=safeGet;t.stringLength=stringLength;t.stringToByteArray=stringToByteArray;t.stringify=stringify;t.validateArgCount=validateArgCount;t.validateCallback=validateCallback;t.validateContextObject=validateContextObject;t.validateIndexedDBOpenable=validateIndexedDBOpenable;t.validateNamespace=validateNamespace}
2,88430(e,t){Object.defineProperty(t,"__esModule",{value:true});t.getDefaultsFromPostinstall=()=>undefined},70916(e){class DbRouter{constructor(e,t,n){this._routes=t||{};this._apps={};this._firebase=e;Object.keys(this._routes).forEach((e=>{const t=this._routes[e];if(!this._apps[t]){this._apps[t]=this._firebase.initializeApp(Object.assign({},n,{databaseURL:t}),t)}}))}getDbInstance(e){const t=/^\/?([^\/]+)(\/|$)/.exec(e);if(!t){throw new Error("Path is not valid: "+e)}const n=t[1];const r=this._routes[n];const i=this._apps[r];return this._firebase.database(i)}db(e){return this.getDbInstance(e).ref(e)}isDefaultDb(e){const t=/^\/?([^\/]+)(\/|$)/.exec(e);if(!t){throw new Error("Path is not valid: "+e)}const n=t[1];const r=this._routes[n];return this._apps[r]===null}getApps(){return Object.keys(this._apps).map((e=>this._apps[e]))}}e.exports=DbRouter},44791(e,t,n){var r=n(19373);Object.defineProperty(t,"__esModule",{value:true});t["default"]=void 0;var i=r(n(12465));var s=r(n(70916));const o=window.baiFirebase||{};const a=new s.default(i.default,o.routes,o.config);function db(e){return a.db(e)}db.isDefaultDb=function(e){return a.isDefaultDb(e)};db.getDbInstance=function(e){return a.getDbInstance(e)};var c=t["default"]=db},22375(e,t,n){var r=n(19373);Object.defineProperty(t,"__esModule",{value:true});t.auth=auth;t.ensureSignedIntoAllInstances=ensureSignedIntoAllInstances;var i=r(n(12465));var s=n(23777);function getPersistence(){var e,t,r;let i;try{i=window.localStorage}catch{}if(n.g.jestTestActive){return[]}const o=(e=(t=i)===null||t===void 0?void 0:t.getItem("firebase:auth:persistence"))!==null&&e!==void 0?e:(r=window.baiFirebase)===null||r===void 0?void 0:r.authPersistence;if(o==="session"){return[s.browserSessionPersistence]}else if(o==="local-indexeddb"){return[s.indexedDBLocalPersistence]}else if(o==="local-localstorage"){return[s.browserLocalPersistence]}else if(o==="local"){return[s.browserLocalPersistence,s.indexedDBLocalPersistence]}else if(o==="none"){return[]}return[s.indexedDBLocalPersistence,s.browserLocalPersistence,s.browserSessionPersistence]}const o={};function getAuthCompat(e){const t=e;t.createUserWithEmailAndPassword=(t,n)=>
2(0,s.createUserWithEmailAndPassword)(e,t,n);t.signInWithCredential=t=>(0,s.signInWithCredential)(e,t);t.signInWithCustomToken=t=>(0,s.signInWithCustomToken)(e,t);t.signInWithEmailAndPassword=(t,n)=>(0,s.signInWithEmailAndPassword)(e,t,n);t.getAdditionalUserInfo=e=>(0,s.getAdditionalUserInfo)(e);t.linkWithCredential=(e,t)=>(0,s.linkWithCredential)(e,t);t.unlinkProvider=(e,t)=>(0,s.unlink)(e,t);t.updateProfile=(e,t)=>(0,s.updateProfile)(e,t);t.sendEmailVerification=(e,t)=>(0,s.sendEmailVerification)(e,t);t.updateEmail=(e,t)=>(0,s.updateEmail)(e,t);t.reauthenticateWithCredential=(e,t)=>(0,s.reauthenticateWithCredential)(e,t);t.updatePassword=(e,t)=>(0,s.updatePassword)(e,t);return t}function getDefaultApp(){try{return i.default.app()}catch{throw new Error("[firebase/auth] Firebase not initialized yet. Ensure js/firebase/init runs before calling auth().")}}function auth(e=getDefaultApp()){let t=o[e.name];if(!t){const n={};const r=getPersistence();if(r){n.persistence=r}t=getAuthCompat((0,s.initializeAuth)(e,n));o[e.name]=t}return t}async function ensureSignedIntoAllInstances(){const e=i.default.app();const t=auth(e);if(!t.currentUser){return}for(const n of i.default.apps){if(n===e){continue}await auth(n).updateCurrentUser(t.currentUser)}}window.auth=auth},97115(e,t,n){var r=n(19373);Object.defineProperty(t,"__esModule",{value:true});t.init=init;var i=r(n(12465));n(9940);n(13325);async function init(){window.firebase=i.default;i.default.initializeApp(window.baiFirebase.config);await Promise.resolve().then(n.bind(n,44791));await Promise.resolve().then(n.bind(n,22375))}},23777(e,t,n){Object.defineProperty(t,"__esModule",{value:true});var r=n(74726);Object.keys(r).forEach((function(e){if(e!=="default"&&!t.hasOwnProperty(e))Object.defineProperty(t,e,{enumerable:true,get:function(){return r[e]}})}))},12465(e,t,n){var r=n(37207);function _interopDefaultLegacy(e){return e&&typeof e==="object"&&"default"in e?e:{default:e}}var i=_interopDefaultLegacy(r);var s="firebase";var o="12.14.0";i["default"].registerVersion(s,o,"app-compat");e.exports=i["default"]},9940(e,t,n){n(89314)},13325(e,t,n){n(84273)},79642(e,t,n){var r=n(50218);var i=n(36183);var s=n(40767);var o=n(95282);const a={PHONE:"phone",TOTP:"totp"};const c={FACEBOOK:"facebook.com",GITHUB:"github.com",GOOGLE:"google.com",PASSWORD:"password",PHONE:"phone",TWITTER:"twitter.com"};const l={EMAIL_LINK:"emailLink",EMAIL_PASSWORD:"password",FACEBOOK:"facebook.com",GITHUB:"github.com",GOOGLE:"google.com",PHONE:"phone",TWITTER:"twitter.com"};const u={LINK:"link",REAUTHENTICATE:"reauthenticate",SIGN_IN:"signIn"};const d={EMAIL_SIGNIN:"EMAIL_SIGNIN",PASSWORD_RESET:"PASSWORD_RESET",RECOVER_EMAIL:"RECOVER_EMAIL",REVERT_SECOND_FACTOR_ADDITION:"REVERT_SECOND_FACTOR_ADDITION",VERIFY_AND_CHANGE_EMAIL:"VERIFY_AND_CHANGE_EMAIL",VERIFY_EMAIL:"VERIFY_EMAIL"};function _debugErrorMap(){return{["admin-restricted-operation"]:"This operation is restricted to administrators only.",["argument-error"]:"",["app-not-authorized"]:"This app, identified by the domain where it's hosted, is not "+"authorized to use Firebase Authentication with the provided API key. "+"Review your key configuration in the Google API console.",["app-not-installed"]:"The requested mobile application corresponding to the identifier ("+"Android package name or iOS bundle ID) provided is not installed on "+"this device.",["captcha-check-failed"]:"The reCAPTCHA response token provided is either invalid, expired, "+"already used or the domain associated with it does not match the list "+"of whitelisted domains.",["code-expired"]:"The SMS code has expired. Please re-send the verification code to try "+"again.",["cordova-not-ready"]:"Cordova framework is not ready.",["cors-unsupported"]:"This browser is not supported.",["credential-already-in-use"]:"This credential is already associated with a different user account.",["custom-token-mismatch"]:"The custom token corresponds to a different audience.",["requires-recent-login"]:"This operation is sensitive and requires recent authentication. Log in "+"again before retrying this request.",["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.",["dynamic-link-not-activated"]:"Please activate Dynamic Links in the Firebase Console and agree to the terms and "+"conditions.",["email-change-needs-verification"]:"Multi-factor users must al
2ways have a verified email.",["email-already-in-use"]:"The email address is already in use by another account.",["emulator-config-failed"]:"Auth instance has already been used to make a network call. Auth can "+"no longer be configured to use the emulator. Try calling "+'"connectAuthEmulator()" sooner.',["expired-action-code"]:"The action code has expired.",["cancelled-popup-request"]:"This operation has been cancelled due to another conflicting popup being opened.",["internal-error"]:"An internal AuthError has occurred.",["invalid-app-credential"]:"The phone verification request contains an invalid application verifier."+" The reCAPTCHA token response is either invalid or expired.",["invalid-app-id"]:"The mobile app identifier is not registered for the current project.",["invalid-user-token"]:"This user's credential isn't valid for this project. This can happen "+"if the user's token has been tampered with, or if the user isn't for "+"the project associated with this API key.",["invalid-auth-event"]:"An internal AuthError has occurred.",["invalid-verification-code"]:"The SMS verification code used to create the phone auth credential is "+"invalid. Please resend the verification code sms and be sure to use the "+"verification code provided by the user.",["invalid-continue-uri"]:"The continue URL provided in the request is invalid.",["invalid-cordova-configuration"]:"The following Cordova plugins must be installed to enable OAuth sign-in: "+"cordova-plugin-buildinfo, cordova-universal-links-plugin, "+"cordova-plugin-browsertab, cordova-plugin-inappbrowser and "+"cordova-plugin-customurlscheme.",["invalid-custom-token"]:"The custom token format is incorrect. Please check the documentation.",["invalid-dynamic-link-domain"]:"The provided dynamic link domain is not configured or authorized for the current project.",["invalid-email"]:"The email address is badly formatted.",["invalid-emulator-scheme"]:"Emulator URL must start with a valid scheme (http:// or https://).",["invalid-api-key"]:"Your API key is invalid, please check you have copied it correctly.",["invalid-cert-hash"]:"The SHA-1 certificate hash provided is invalid.",["invalid-credential"]:"The supplied auth credential is incorrect, malformed or has expired.",["invalid-message-payload"]:"The email template corresponding to this action contains invalid characters in its message. "+"Please fix by going to the Auth email templates section in the Firebase Console.",["invalid-multi-factor-session"]:"The request does not contain a valid proof of first factor successful sign-in.",["invalid-oauth-provider"]:"EmailAuthProvider is not supported for this operation. This operation "+"only supports OAuth providers.",["invalid-oauth-client-id"]:"The OAuth client ID provided is either invalid or does not match the "+"specified API key.",["unauthorized-domain"]:"This domain is not authorized for OAuth operations for your Firebase "+"project. Edit the list of authorized domains from the Firebase console.",["invalid-action-code"]:"The action code is invalid. This can happen if the code is malformed, "+"expired, or has already been used.",["wrong-password"]:"The password is invalid or the user does not have a password.",["invalid-persistence-type"]:"The specified persistence type is invalid. It can only be local, session or none.",["invalid-phone-number"]:"The format of the phone number provided is incorrect. Please enter the "+"phone number in a format that can be parsed into E.164 format. E.164 "+"phone numbers are written in the format [+][country code][subscriber "+"number including area code].",["invalid-provider-id"]:"The specified provider ID is invali
2d.",["invalid-recipient-email"]:"The email corresponding to this action failed to send as the provided "+"recipient email address is invalid.",["invalid-sender"]:"The email template corresponding to this action contains an invalid sender email or name. "+"Please fix by going to the Auth email templates section in the Firebase Console.",["invalid-verification-id"]:"The verification ID used to create the phone auth credential is invalid.",["invalid-tenant-id"]:"The Auth instance's tenant ID is invalid.",["login-blocked"]:"Login blocked by user-provided method: {$originalMessage}",["missing-android-pkg-name"]:"An Android Package Name must be provided if the Android App is required to be installed.",["auth-domain-config-required"]:"Be sure to include authDomain when calling firebase.initializeApp(), "+"by following the instructions in the Firebase console.",["missing-app-credential"]:"The phone verification request is missing an application verifier "+"assertion. A reCAPTCHA response token needs to be provided.",["missing-verification-code"]:"The phone auth credential was created with an empty SMS verification code.",["missing-continue-uri"]:"A continue URL must be provided in the request.",["missing-iframe-start"]:"An internal AuthError has occurred.",["missing-ios-bundle-id"]:"An iOS Bundle ID must be provided if an App Store ID is provided.",["missing-or-invalid-nonce"]:"The request does not contain a valid nonce. This can occur if the "+"SHA-256 hash of the provided raw nonce does not match the hashed nonce "+"in the ID token payload.",["missing-password"]:"A non-empty password must be provided",["missing-multi-factor-info"]:"No second factor identifier is provided.",["missing-multi-factor-session"]:"The request is missing proof of first factor successful sign-in.",["missing-phone-number"]:"To send verification codes, provide a phone number for the recipient.",["missing-verification-id"]:"The phone auth credential was created with an empty verification ID.",["app-deleted"]:"This instance of FirebaseApp has been deleted.",["multi-factor-info-not-found"]:"The user does not have a second factor matching the identifier provided.",["multi-factor-auth-required"]:"Proof of ownership of a second factor is required to complete sign-in.",["account-exists-with-different-credential"]:"An account already exists with the same email address but different "+"sign-in credentials. Sign in using a provider associated with this "+"email address.",["network-request-failed"]:"A network AuthError (such as timeout, interrupted connection or unreachable host) has occurred.",["no-auth-event"]:"An internal AuthError has occurred.",["no-such-provider"]:"User was not linked to an account with the given provider.",["null-user"]:"A null user object was provided as the argument for an operation which "+"requires a non-null user object.",["operation-not-allowed"]:"The given sign-in provider is disabled for this Firebase project. "+"Enable it in the Firebase console, under the sign-in method tab of the "+"Auth section.",["operation-not-supported-in-this-environment"]:"This operation is not supported in the environment this application is "+'running on. "location.protocol" must be http, https or chrome-extension'+" and web storage must be enabled.",["popup-blocked"]:"Unable to establish a connection with the popup. It may have been blocked by the browser.",["popup-closed-by-user"]:"The popup has been closed by the user before finalizing the operation.",["provider-already-linked"]:"User can only be linked to one identity for the given provider.",["quota-exceeded"]:"The project's quota for this operation has been exceeded.",["redirect-cancelled-by-user"]:"The redirect operation has been cancelled by the user before finalizing.",["redirect-operation-pending"]:"A redirect sign-in operation is already pending.",["rejected-credential"]:"The request contains malformed or mismatching credentials.",["second-factor-already-in-use"]:"The second factor is already enrolled on this account.",["maximum-second-factor-count-exceeded"]:"The maximum allowed number of second factors on a user has been exceeded.",["tenant-id-mismatch"]:"The provided tenant ID does not match the Auth instance's tenant ID",["timeout"]:"The operation has timed out.",["user-token-expired"]:"The user's credential is no longer valid. The user must sign in again.",["too-many-requests"]:"We have blocked all requests from this device due to unusual activity. "+"Try again later.",["unauthorized-continue-uri"]:"The domain of the continue URL is not whitelisted.  Please whitelist "+"the domain in the Firebase console.",["unsupported-first-factor"]:"Enrolling a second factor or signing in with a multi-factor account requires sign-in with a supported first factor.",["unsupported-persistence-type"]:"The current environment does not support the specified persistence type.",["unsupported-tenant-operation"]:"This operation is not supported in a multi-tenant context.",["unverified-email"]:"The operation requires a verified email.",["user-cancelled"]:"The user did not grant your application the permissions it requested.",["user-not-found"]:"There is no user record corresponding to this identifier. The user may "+"have been deleted.",["user-disabled"]:"The user account has been disabled by an administrator.",["user-mismatch"]:"The supplied credentials do not correspond to the previously signed in user.",["user-signed-out"]:"",["weak-password"]:"The password must be 6 characters long or more.",["web-storage-unsupported"]:"This browser is not supported or 3rd party cookies and data may be disabled.",["already-initialized"]:"initializeAuth() has already been called with "+"different options. To avoid this error, call initializeAuth() with the "+"same options as when it was originally called, or call getAuth() to return the"+" already initialized instance.",["missing-rec
2aptcha-token"]:"The reCAPTCHA token is missing when sending request to the backend.",["invalid-recaptcha-token"]:"The reCAPTCHA token is invalid when sending request to the backend.",["invalid-recaptcha-action"]:"The reCAPTCHA action is invalid when sending request to the backend.",["recaptcha-not-enabled"]:"reCAPTCHA Enterprise integration is not enabled for this project.",["missing-client-type"]:"The reCAPTCHA client type is missing when sending request to the backend.",["missing-recaptcha-version"]:"The reCAPTCHA version is missing when sending request to the backend.",["invalid-req-type"]:"Invalid request parameters.",["invalid-recaptcha-version"]:"The reCAPTCHA version is invalid when sending request to the backend.",["unsupported-password-policy-schema-version"]:"The password policy received from the backend uses a schema version that is not supported by this version of the Firebase SDK.",["password-does-not-meet-requirements"]:"The password does not meet the requirements.",["invalid-hosting-link-domain"]:"The provided Hosting link domain is not configured in Firebase Hosting or is not owned by "+"the current project. This cannot be a default Hosting domain (`web.app` or `firebaseapp.com`)."}}function _prodErrorMap(){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."}}const h=_debugErrorMap;const p=_prodErrorMap;const f=new i.ErrorFactory("auth","Firebase",_prodErrorMap());const m={ADMIN_ONLY_OPERATION:"auth/admin-restricted-operation",ARGUMENT_ERROR:"auth/argument-error",APP_NOT_AUTHORIZED:"auth/app-not-authorized",APP_NOT_INSTALLED:"auth/app-not-installed",CAPTCHA_CHECK_FAILED:"auth/captcha-check-failed",CODE_EXPIRED:"auth/code-expired",CORDOVA_NOT_READY:"auth/cordova-not-ready",CORS_UNSUPPORTED:"auth/cors-unsupported",CREDENTIAL_ALREADY_IN_USE:"auth/credential-already-in-use",CREDENTIAL_MISMATCH:"auth/custom-token-mismatch",CREDENTIAL_TOO_OLD_LOGIN_AGAIN:"auth/requires-recent-login",DEPENDENT_SDK_INIT_BEFORE_AUTH:"auth/dependent-sdk-initialized-before-auth",DYNAMIC_LINK_NOT_ACTIVATED:"auth/dynamic-link-not-activated",EMAIL_CHANGE_NEEDS_VERIFICATION:"auth/email-change-needs-verification",EMAIL_EXISTS:"auth/email-already-in-use",EMULATOR_CONFIG_FAILED:"auth/emulator-config-failed",EXPIRED_OOB_CODE:"auth/expired-action-code",EXPIRED_POPUP_REQUEST:"auth/cancelled-popup-request",INTERNAL_ERROR:"auth/internal-error",INVALID_API_KEY:"auth/invalid-api-key",INVALID_APP_CREDENTIAL:"auth/invalid-app-credential",INVALID_APP_ID:"auth/invalid-app-id",INVALID_AUTH:"auth/invalid-user-token",INVALID_AUTH_EVENT:"auth/invalid-auth-event",INVALID_CERT_HASH:"auth/invalid-cert-hash",INVALID_CODE:"auth/invalid-verification-code",INVALID_CONTINUE_URI:"auth/invalid-continue-uri",INVALID_CORDOVA_CONFIGURATION:"auth/invalid-cordova-configuration",INVALID_CUSTOM_TOKEN:"auth/invalid-custom-token",INVALID_DYNAMIC_LINK_DOMAIN:"auth/invalid-dynamic-link-domain",INVALID_EMAIL:"auth/invalid-email",INVALID_EMULATOR_SCHEME:"auth/invalid-emulator-scheme",INVALID_IDP_RESPONSE:"auth/invalid-credential",INVALID_LOGIN_CREDENTIALS:"auth/invalid-credential",INVALID_MESSAGE_PAYLOAD:"auth/invalid-message-payload",INVALID_MFA_SESSION:"auth/invalid-multi-factor-session",INVALID_OAUTH_CLIENT_ID:"auth/invalid-oauth-client-id",INVALID_OAUTH_PROVIDER:"auth/invalid-oauth-provider",INVALID_OOB_CODE:"auth/invalid-action-code",INVALID_ORIGIN:"auth/unauthorized-domain",INVALID_PASSWORD:"auth/wrong-password",INVALID_PERSISTENCE:"auth/invalid-persistence-type",INVALID_PHONE_NUMBER:"auth/invalid-phone-number",INVALID_PROVIDER_ID:"auth/invalid-provider-id",INVALID_RECIPIENT_EMAIL:"auth/invalid-recipient-email",INVALID_SENDER:"auth/invalid-sender",INVALID_SESSION_INFO:"auth/invalid-verification-id",INVALID_TENANT_ID:"auth/invalid-tenant-id",MFA_INFO_NOT_FOUND:"auth/multi-factor-info-not-found",MFA_REQUIRED:"auth/multi-factor-auth-required",MISSING_ANDROID_PACKAGE_NAME:"auth/missing-android-pkg-name",MISSING_APP_CREDENTIAL:"auth/missing-app-credential",MISSING_AUTH_DOMAIN:"auth/auth-domain-config-required",MISSING_CODE:"auth/missing-verification-code",MISSING_CONTINUE_URI:"auth/missing-continue-uri",MISSING_IFRAME_START:"auth/missing-iframe-start",MISSING_IOS_BUNDLE_ID:"auth/missing-ios-bundle-id",MISSING_OR_INVALID_
2NONCE:"auth/missing-or-invalid-nonce",MISSING_MFA_INFO:"auth/missing-multi-factor-info",MISSING_MFA_SESSION:"auth/missing-multi-factor-session",MISSING_PHONE_NUMBER:"auth/missing-phone-number",MISSING_PASSWORD:"auth/missing-password",MISSING_SESSION_INFO:"auth/missing-verification-id",MODULE_DESTROYED:"auth/app-deleted",NEED_CONFIRMATION:"auth/account-exists-with-different-credential",NETWORK_REQUEST_FAILED:"auth/network-request-failed",NULL_USER:"auth/null-user",NO_AUTH_EVENT:"auth/no-auth-event",NO_SUCH_PROVIDER:"auth/no-such-provider",OPERATION_NOT_ALLOWED:"auth/operation-not-allowed",OPERATION_NOT_SUPPORTED:"auth/operation-not-supported-in-this-environment",POPUP_BLOCKED:"auth/popup-blocked",POPUP_CLOSED_BY_USER:"auth/popup-closed-by-user",PROVIDER_ALREADY_LINKED:"auth/provider-already-linked",QUOTA_EXCEEDED:"auth/quota-exceeded",REDIRECT_CANCELLED_BY_USER:"auth/redirect-cancelled-by-user",REDIRECT_OPERATION_PENDING:"auth/redirect-operation-pending",REJECTED_CREDENTIAL:"auth/rejected-credential",SECOND_FACTOR_ALREADY_ENROLLED:"auth/second-factor-already-in-use",SECOND_FACTOR_LIMIT_EXCEEDED:"auth/maximum-second-factor-count-exceeded",TENANT_ID_MISMATCH:"auth/tenant-id-mismatch",TIMEOUT:"auth/timeout",TOKEN_EXPIRED:"auth/user-token-expired",TOO_MANY_ATTEMPTS_TRY_LATER:"auth/too-many-requests",UNAUTHORIZED_DOMAIN:"auth/unauthorized-continue-uri",UNSUPPORTED_FIRST_FACTOR:"auth/unsupported-first-factor",UNSUPPORTED_PERSISTENCE:"auth/unsupported-persistence-type",UNSUPPORTED_TENANT_OPERATION:"auth/unsupported-tenant-operation",UNVERIFIED_EMAIL:"auth/unverified-email",USER_CANCELLED:"auth/user-cancelled",USER_DELETED:"auth/user-not-found",USER_DISABLED:"auth/user-disabled",USER_MISMATCH:"auth/user-mismatch",USER_SIGNED_OUT:"auth/user-signed-out",WEAK_PASSWORD:"auth/weak-password",WEB_STORAGE_UNSUPPORTED:"auth/web-storage-unsupported",ALREADY_INITIALIZED:"auth/already-initialized",RECAPTCHA_NOT_ENABLED:"auth/recaptcha-not-enabled",MISSING_RECAPTCHA_TOKEN:"auth/missing-recaptcha-token",INVALID_RECAPTCHA_TOKEN:"auth/invalid-recaptcha-token",INVALID_RECAPTCHA_ACTION:"auth/invalid-recaptcha-action",MISSING_CLIENT_TYPE:"auth/missing-client-type",MISSING_RECAPTCHA_VERSION:"auth/missing-recaptcha-version",INVALID_RECAPTCHA_VERSION:"auth/invalid-recaptcha-version",INVALID_REQ_TYPE:"auth/invalid-req-type",INVALID_HOSTING_LINK_DOMAIN:"auth/invalid-hosting-link-domain"};const g=new s.Logger("@firebase/auth");function _logWarn(e,...t){if(g.logLevel<=s.LogLevel.WARN){g.warn(`Auth (${r.SDK_VERSION}): ${e}`,...t)}}function _logError(e,...t){if(g.logLevel<=s.LogLevel.ERROR){g.error(`Auth (${r.SDK_VERSION}): ${e}`,...t)}}function _fail(e,...t){throw createErrorInternal(e,...t)}function _createError(e,...t){return createErrorInternal(e,...t)}function _errorWithCustomMessage(e,t,n){const r={...p(),[t]:n};const s=new i.ErrorFactory("auth","Firebase",r);return s.create(t,{appName:e.name})}function _serverAppCurrentUserOperationNotSupportedError(e){return _errorWithCustomMessage(e,"operation-not-supported-in-this-environment","Operations that alter the current user are not supported in conjunction with FirebaseServerApp")}function _assertInstanceOf(e,t,n){const r=n;if(!(t instanceof r)){if(r.name!==t.constructor.name){_fail(e,"argument-error")}throw _errorWithCustomMessage(e,"argument-error",`Type of ${t.constructor.name} does not match expected instance.`+`Did you pass a reference from a different Auth SDK?`)}}function createErrorInternal(e,...t){if(typeof e!=="string"){const n=t[0];const r=[...t.slice(1)];if(r[0]){r[0].appName=e.name}return e._errorFactory.create(n,...r)}return f.create(e,...t)}function _assert(e,t,...n){if(!e){throw createErrorInternal(t,...n)}}function debugFail(e){const t=`INTERNAL ASSERTION FAILED: `+e;_logError(t);throw new Error(t)}function debugAssert(e,t){if(!e){debugFail(t)}}function _getCurrentUrl(){return typeof self!=="undefined"&&self.location?.href||""}function _isHttpOrHttps(){return _getCurrentScheme()==="http:"||_getCurrentScheme()==="https:"}function _getCurrentScheme(){return typeof self!=="undefined"&&self.location?.protocol||null}function _isOnline(){if(typeof navigator!=="undefined"&&navigator&&"onLine"in navigator&&typeof navigator.onLine==="boolean"&&(_isHttpOrHttps()||i.isBrowserExtension()||"connection"in navigator)){return navigator.onLine}return true}function _getUserLanguage(){if(typeof navigator==="undefined"){return null}const e=navigator;return e.languages&&e.languages[0]||e.language||null}class Delay{constructor(e,t){this.shortDelay=e;this.longDelay=t;debugAssert(t>
2e,"Short delay should be less than long delay!");this.isMobile=i.isMobileCordova()||i.isReactNative()}get(){if(!_isOnline()){return Math.min(5e3,this.shortDelay)}return this.isMobile?this.longDelay:this.shortDelay}}function _emulatorUrl(e,t){debugAssert(e.emulator,"Emulator should always be set here");const{url:n}=e.emulator;if(!t){return n}return`${n}${t.startsWith("/")?t.slice(1):t}`}class FetchProvider{static initialize(e,t,n){this.fetchImpl=e;if(t){this.headersImpl=t}if(n){this.responseImpl=n}}static fetch(){if(this.fetchImpl){return this.fetchImpl}if(typeof self!=="undefined"&&"fetch"in self){return self.fetch}if(typeof globalThis!=="undefined"&&globalThis.fetch){return globalThis.fetch}if(typeof fetch!=="undefined"){return fetch}debugFail("Could not find fetch implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill")}static headers(){if(this.headersImpl){return this.headersImpl}if(typeof self!=="undefined"&&"Headers"in self){return self.Headers}if(typeof globalThis!=="undefined"&&globalThis.Headers){return globalThis.Headers}if(typeof Headers!=="undefined"){return Headers}debugFail("Could not find Headers implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill")}static response(){if(this.responseImpl){return this.responseImpl}if(typeof self!=="undefined"&&"Response"in self){return self.Response}if(typeof globalThis!=="undefined"&&globalThis.Response){return globalThis.Response}if(typeof Response!=="undefined"){return Response}debugFail("Could not find Response implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill")}}const _={["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-recaptcha-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"};const v=["/v1/accounts:signInWithCustomToken","/v1/accounts:signInWithEmailLink","/v1/accounts:signInWithIdp","/v1/accounts:signInWithPassword","/v1/accounts:signInWithPhoneNumber","/v1/token"];const y=new Delay(3e4,6e4);function _addTidIfNecessary(e,t){if(e.tenantId&&!t.tenantId){return{...t,tenantId:e.tenantId}}return t}async function _performApiRequest(e,t,n,r,s={}){return _performFetchWithErrorHandling(e,s,(async()=>{let s={};let o={};if(r){if(t==="GET"){o=r}else{s={body:JSON.stringify(r)}}}const a=i.querystring({key:e.config.apiKey,...o}).slice(1);const c=await e._getAdditionalHeaders();c["Content-Type"]="application/json";if(e.languageCode){c["X-Firebase-Locale"]=e.languageCode}const l={method:t,headers:c,...s};if(!i.isCloudflareWorker()){l.referrerPolicy="no-referrer"}if(e.emulatorConfig&&i.isCloudWorkstation(e.emulatorConfig.host)){l.credentials="include"}
2return FetchProvider.fetch()(await _getFinalTarget(e,e.config.apiHost,n,a),l)}))}async function _performFetchWithErrorHandling(e,t,n){e._canInitEmulator=false;const r={..._,...t};try{const t=new NetworkTimeout(e);const i=await Promise.race([n(),t.promise]);t.clearNetworkTimeout();const s=await i.json();if("needConfirmation"in s){throw _makeTaggedError(e,"account-exists-with-different-credential",s)}if(i.ok&&!("errorMessage"in s)){return s}else{const t=i.ok?s.errorMessage:s.error.message;const[n,o]=t.split(" : ");if(n==="FEDERATED_USER_ID_ALREADY_LINKED"){throw _makeTaggedError(e,"credential-already-in-use",s)}else if(n==="EMAIL_EXISTS"){throw _makeTaggedError(e,"email-already-in-use",s)}else if(n==="USER_DISABLED"){throw _makeTaggedError(e,"user-disabled",s)}const a=r[n]||n.toLowerCase().replace(/[_\s]+/g,"-");if(o){throw _errorWithCustomMessage(e,a,o)}else{_fail(e,a)}}}catch(t){if(t instanceof i.FirebaseError){throw t}_fail(e,"network-request-failed",{message:String(t)})}}async function _performSignInRequest(e,t,n,r,i={}){const s=await _performApiRequest(e,t,n,r,i);if("mfaPendingCredential"in s){_fail(e,"multi-factor-auth-required",{_serverResponse:s})}return s}async function _getFinalTarget(e,t,n,r){const i=`${t}${n}?${r}`;const s=e;const o=s.config.emulator?_emulatorUrl(e.config,i):`${e.config.apiScheme}://${i}`;if(v.includes(n)){await s._persistenceManagerAvailable;if(s._getPersistenceType()==="COOKIE"){const e=s._getPersistence();return e._getFinalTarget(o).toString()}}return o}function _parseEnforcementState(e){switch(e){case"ENFORCE":return"ENFORCE";case"AUDIT":return"AUDIT";case"OFF":return"OFF";default:return"ENFORCEMENT_STATE_UNSPECIFIED"}}class NetworkTimeout{clearNetworkTimeout(){clearTimeout(this.timer)}constructor(e){this.auth=e;this.timer=null;this.promise=new Promise(((e,t)=>{this.timer=setTimeout((()=>t(_createError(this.auth,"network-request-failed"))),y.get())}))}}function _makeTaggedError(e,t,n){const r={appName:e.name};if(n.email){r.email=n.email}if(n.phoneNumber){r.phoneNumber=n.phoneNumber}const i=_createError(e,t,r);i.customData._tokenResponse=n;return i}function isV2(e){return e!==undefined&&e.getResponse!==undefined}function isEnterprise(e){return e!==undefined&&e.enterprise!==undefined}class RecaptchaConfig{constructor(e){this.siteKey="";this.recaptchaEnforcementState=[];if(e.recaptchaKey===undefined){throw new Error("recaptchaKey undefined")}this.siteKey=e.recaptchaKey.split("/")[3];this.recaptchaEnforcementState=e.recaptchaEnforcementState}getProviderEnforcementState(e){if(!this.recaptchaEnforcementState||this.recaptchaEnforcementState.length===0){return null}for(const t of this.recaptchaEnforcementState){if(t.provider&&t.provider===e){return _parseEnforcementState(t.enforcementState)}}return null}isProviderEnabled(e){return this.getProviderEnforcementState(e)==="ENFORCE"||this.getProviderEnforcementState(e)==="AUDIT"}isAnyProviderEnabled(){return this.isProviderEnabled("EMAIL_PASSWORD_PROVIDER")||this.isProviderEnabled("PHONE_PROVIDER")}}async function getRecaptchaParams(e){return(await _performApiRequest(e,"GET","/v1/recaptchaParams")).recaptchaSiteKey||""}async function getRecaptchaConfig(e,t){return _performApiRequest(e,"GET","/v2/recaptchaConfig",_addTidIfNecessary(e,t))}async function deleteAccount(e,t){return _performApiRequest(e,"POST","/v1/accounts:delete",t)}async function deleteLinkedAccounts(e,t){return _performApiRequest(e,"POST","/v1/accounts:update",t)}async function getAccountInfo(e,t){return _performApiRequest(e,"POST","/v1/accounts:lookup",t)}function utcTimestampToDateString(e){if(!e){return undefined}try{const t=new Date(Number(e));if(!isNaN(t.getTime())){return t.toUTCString()}}catch(e){}return undefined}function getIdToken(e,t=false){return i.getModularInstance(e).getIdToken(t)}async function getIdTokenResult(e,t=false){const n=i.getModularInstance(e);const r=await n.getIdToken(t);const s=_parseToken(r);_assert(s&&s.exp&&s.auth_time&&s.iat,n.auth,"internal-error");const o=typeof s.firebase==="object"?s.firebase:undefined;const a=o?.["sign_in_provider"];return{claims:s,token:r,authTime:utcTimestampToDateString(secondsStringToMilliseconds(s.auth_time)),issuedAtTime:utcTimestampToDateString(secondsStringToMilliseconds(s.iat)),expirationTime:utcTimestampToDateString(secondsStringToMilliseconds(s.exp
2)),signInProvider:a||null,signInSecondFactor:o?.["sign_in_second_factor"]||null}}function secondsStringToMilliseconds(e){return Number(e)*1e3}function _parseToken(e){const[t,n,r]=e.split(".");if(t===undefined||n===undefined||r===undefined){_logError("JWT malformed, contained fewer than 3 sections");return null}try{const e=i.base64Decode(n);if(!e){_logError("Failed to decode base64 JWT payload");return null}return JSON.parse(e)}catch(e){_logError("Caught error parsing JWT payload as JSON",e?.toString());return null}}function _tokenExpiresIn(e){const t=_parseToken(e);_assert(t,"internal-error");_assert(typeof t.exp!=="undefined","internal-error");_assert(typeof t.iat!=="undefined","internal-error");return Number(t.exp)-Number(t.iat)}async function _logoutIfInvalidated(e,t,n=false){if(n){return t}try{return await t}catch(t){if(t instanceof i.FirebaseError&&isUserInvalidated(t)){if(e.auth.currentUser===e){await e.auth.signOut()}}throw t}}function isUserInvalidated({code:e}){return e===`auth/${"user-disabled"}`||e===`auth/${"user-token-expired"}`}class ProactiveRefresh{constructor(e){this.user=e;this.isRunning=false;this.timerId=null;this.errorBackoff=3e4}_start(){if(this.isRunning){return}this.isRunning=true;this.schedule()}_stop(){if(!this.isRunning){return}this.isRunning=false;if(this.timerId!==null){clearTimeout(this.timerId)}}getInterval(e){if(e){const e=this.errorBackoff;this.errorBackoff=Math.min(this.errorBackoff*2,96e4);return e}else{this.errorBackoff=3e4;const e=this.user.stsTokenManager.expirationTime??0;const t=e-Date.now()-3e5;return Math.max(0,t)}}schedule(e=false){if(!this.isRunning){return}const t=this.getInterval(e);this.timerId=setTimeout((async()=>{await this.iteration()}),t)}async iteration(){try{await this.user.getIdToken(true)}catch(e){if(e?.code===`auth/${"network-request-failed"}`){this.schedule(true)}return}this.schedule()}}class UserMetadata{constructor(e,t){this.createdAt=e;this.lastLoginAt=t;this._initializeTime()}_initializeTime(){this.lastSignInTime=utcTimestampToDateString(this.lastLoginAt);this.creationTime=utcTimestampToDateString(this.createdAt)}_copy(e){this.createdAt=e.createdAt;this.lastLoginAt=e.lastLoginAt;this._initializeTime()}toJSON(){return{createdAt:this.createdAt,lastLoginAt:this.lastLoginAt}}}async function _reloadWithoutSaving(e){const t=e.auth;const n=await e.getIdToken();const r=await _logoutIfInvalidated(e,getAccountInfo(t,{idToken:n}));_assert(r?.users.length,t,"internal-error");const i=r.users[0];e._notifyReloadListener(i);const s=i.providerUserInfo?.length?extractProviderData(i.providerUserInfo):[];const o=mergeProviderData(e.providerData,s);const a=e.isAnonymous;const c=!(e.email&&i.passwordHash)&&!o?.length;const l=!a?false:c;const u={uid:i.localId,displayName:i.displayName||null,photoURL:i.photoUrl||null,email:i.email||null,emailVerified:i.emailVerified||false,phoneNumber:i.phoneNumber||null,tenantId:i.tenantId||null,providerData:o,metadata:new UserMetadata(i.createdAt,i.lastLoginAt),isAnonymous:l};Object.assign(e,u)}async function reload(e){const t=i.getModularInstance(e);await _reloadWithoutSaving(t);await t.auth._persistUserIfCurrent(t);t.auth._notifyListenersIfCurrent(t)}function mergeProviderData(e,t){const n=e.filter((e=>!t.some((t=>t.providerId===e.providerId))));return[...n,...t]}function extractProviderData(e){return e.map((({providerId:e,...t})=>({providerId:e,uid:t.rawId||"",displayName:t.displayName||null,email:t.email||null,phoneNumber:t.phoneNumber||null,photoURL:t.photoUrl||null})))}async function requestStsToken(e,t){const n=await _performFetchWithErrorHandling(e,{},(async()=>{const n=i.querystring({grant_type:"refresh_token",refresh_token:t}).slice(1);const{tokenApiHost:r,apiKey:s}=e.config;const o=await _getFinalTarget(e,r,"/v1/token",`key=${s}`);const a=await e._getAdditionalHeaders();a["Content-Type"]="application/x-www-form-urlencoded";const c={method:"POST",headers:a,body:n};if(e.emulatorConfig&&i.isCloudWorkstation(e.emulatorConfig.host)){c.credentials="include"}return FetchProvider.fetch()(o,c)}));return{accessToken:n.access_token,expiresIn:n.expires_in,refreshToken:n.refresh_token}}async function revokeToken(e,t){return _performApiRequest(e,"POST","/v2/accounts:revokeToken",_addTidIfNecessary(e,t))}class StsTokenManager{constructor(){this.refreshToken=null;this.accessToken=null;this.expirationTime=null}get isExpired(){return!this.expirationTime||Date.now()>this.expirationTime-3e4}updateFromServerResponse(e){_assert(e.idToken,"internal-error");_assert(typeof e.idToken!=="undefined","internal-error");_assert(typeof e.refreshToken!=="undefined","internal-error");
2const t="expiresIn"in e&&typeof e.expiresIn!=="undefined"?Number(e.expiresIn):_tokenExpiresIn(e.idToken);this.updateTokensAndExpiration(e.idToken,e.refreshToken,t)}updateFromIdToken(e){_assert(e.length!==0,"internal-error");const t=_tokenExpiresIn(e);this.updateTokensAndExpiration(e,null,t)}async getToken(e,t=false){if(!t&&this.accessToken&&!this.isExpired){return this.accessToken}_assert(this.refreshToken,e,"user-token-expired");if(this.refreshToken){await this.refresh(e,this.refreshToken);return this.accessToken}return null}clearRefreshToken(){this.refreshToken=null}async refresh(e,t){const{accessToken:n,refreshToken:r,expiresIn:i}=await requestStsToken(e,t);this.updateTokensAndExpiration(n,r,Number(i))}updateTokensAndExpiration(e,t,n){this.refreshToken=t||null;this.accessToken=e||null;this.expirationTime=Date.now()+n*1e3}static fromJSON(e,t){const{refreshToken:n,accessToken:r,expirationTime:i}=t;const s=new StsTokenManager;if(n){_assert(typeof n==="string","internal-error",{appName:e});s.refreshToken=n}if(r){_assert(typeof r==="string","internal-error",{appName:e});s.accessToken=r}if(i){_assert(typeof i==="number","internal-error",{appName:e});s.expirationTime=i}return 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 StsTokenManager,this.toJSON())}_performRefresh(){return debugFail("not implemented")}}function assertStringOrUndefined(e,t){_assert(typeof e==="string"||typeof e==="undefined","internal-error",{appName:t})}class UserImpl{constructor({uid:e,auth:t,stsTokenManager:n,...r}){this.providerId="firebase";this.proactiveRefresh=new ProactiveRefresh(this);this.reloadUserInfo=null;this.reloadListener=null;this.uid=e;this.auth=t;this.stsTokenManager=n;this.accessToken=n.accessToken;this.displayName=r.displayName||null;this.email=r.email||null;this.emailVerified=r.emailVerified||false;this.phoneNumber=r.phoneNumber||null;this.photoURL=r.photoURL||null;this.isAnonymous=r.isAnonymous||false;this.tenantId=r.tenantId||null;this.providerData=r.providerData?[...r.providerData]:[];this.metadata=new UserMetadata(r.createdAt||undefined,r.lastLoginAt||undefined)}async getIdToken(e){const t=await _logoutIfInvalidated(this,this.stsTokenManager.getToken(this.auth,e));_assert(t,this.auth,"internal-error");if(this.accessToken!==t){this.accessToken=t;await this.auth._persistUserIfCurrent(this);this.auth._notifyListenersIfCurrent(this)}return t}getIdTokenResult(e){return getIdTokenResult(this,e)}reload(){return reload(this)}_assign(e){if(this===e){return}_assert(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){const t=new UserImpl({...this,auth:e,stsTokenManager:this.stsTokenManager._clone()});t.metadata._copy(this.metadata);return t}_onReload(e){_assert(!this.reloadListener,this.auth,"internal-error");this.reloadListener=e;if(this.reloadUserInfo){this._notifyReloadListener(this.reloadUserInfo);this.reloadUserInfo=null}}_notifyReloadListener(e){if(this.reloadListener){this.reloadListener(e)}else{this.reloadUserInfo=e}}_startProactiveRefresh(){this.proactiveRefresh._start()}_stopProactiveRefresh(){this.proactiveRefresh._stop()}async _updateTokensIfNecessary(e,t=false){let n=false;if(e.idToken&&e.idToken!==this.stsTokenManager.accessToken){this.stsTokenManager.updateFromServerResponse(e);n=true}if(t){await _reloadWithoutSaving(this)}await this.auth._persistUserIfCurrent(this);if(n){this.auth._notifyListenersIfCurrent(this)}}async delete(){if(r._isFirebaseServerApp(this.auth.app)){return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(this.auth))}const e=await this.getIdToken();await _logoutIfInvalidated(this,deleteAccount(this.auth,{idToken:e}));this.stsTokenManager.clearRefreshToken();return this.auth.signOut()}toJSON(){return{uid:this.uid,email:this.email||undefined,emailVerified:this.emailVerified,displayName:this.displayName||undefined,isAnonymous:this.isAnonymous,photoURL:this.photoURL||undefined,phoneNumber:this.phoneNumber||undefined,tenantId:this.tenantId||undefined,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){const n=t.displayName??undefined;const r=t.email??undefined;const i=t.phoneNumber??undefined;const s=t.photoURL??undefined;const o=t.tenantId??undefined;const a=t._redirectEventId??undefined;const c=t.createdAt??undefined;const l=t.lastLoginAt??undefined;const{uid:u,emailVerified:d,isAnonymous:h,providerData:p,stsTokenManager:f}=t;_assert(u&&f,e,"internal-error");const m=StsTokenManager.fromJSON(this.name,f);_assert(typeof u==="string",e,"internal-error");assertStringOrUndefined(n,e.name);assertStringOrUndefined(r,e.name);_assert(typeof d==="boolean",e,"internal-error");_assert(typeof h==="boolean",e,"internal-error");assertStringOrUndefined(i,e.name);assertStringOrUndefined(s,e.name);assertStringOrUndefined(o,e.name);assertStringOrUndefined(a,e.name);assertStringOrUndefined(c,e.name);assertStringOrUndefined(l,e.name);const g=new UserImpl({uid:u,auth:e,email:r,emailVerified:d,displayName:n,isAnonymous:h,photoURL:s,phoneNumber:i,tenantId:o,stsTokenManager:m,createdAt:c,lastLoginAt:l});if(p&&Array.isArray(p)){g.providerData=p.map((e=>({...e})))}if(a){g._redirectEventId=a}return g}static async _fromIdTokenResponse(e,t,n=false){const r=new StsTokenManager;r.updateFromServerResponse(t);const i=new UserImpl({uid:t.localId,auth:e,stsTokenManager:r,isAnonymous:n});await _reloadWithoutSaving(i);return i}static async _fromGetAccountInfoResponse(e,t,n){const r=t.users[0];_assert(r.localId!==undefined,"internal-error");const i=r.providerUserInfo!==undefined?extractProviderData(r.providerUserInfo):[];const s=!(r.email&&r.passwordHash)&&!i?.length;const o=new StsTokenManager;o.updateFromIdToken(n);const a=new UserImpl({uid:r.localId,auth:e,stsTokenManager:o,isAnonymous:s});const c={uid:r.localId,displayName:r.displayName||null,photoURL:r.photoUrl||null,email:r.email||null,emailVerified:r.emailVerified||false,ph
2oneNumber:r.phoneNumber||null,tenantId:r.tenantId||null,providerData:i,metadata:new UserMetadata(r.createdAt,r.lastLoginAt),isAnonymous:!(r.email&&r.passwordHash)&&!i?.length};Object.assign(a,c);return a}}const I=new Map;function _getInstance(e){debugAssert(e instanceof Function,"Expected a class definition");let t=I.get(e);if(t){debugAssert(t instanceof e,"Instance stored in cache mismatched with class");return t}t=new e;I.set(e,t);return t}class InMemoryPersistence{constructor(){this.type="NONE";this.storage={}}async _isAvailable(){return true}async _set(e,t){this.storage[e]=t}async _get(e){const t=this.storage[e];return t===undefined?null:t}async _remove(e){delete this.storage[e]}_addListener(e,t){return}_removeListener(e,t){return}}InMemoryPersistence.type="NONE";const C=InMemoryPersistence;function _persistenceKeyName(e,t,n){return`${"firebase"}:${e}:${t}:${n}`}class PersistenceUserManager{constructor(e,t,n){this.persistence=e;this.auth=t;this.userKey=n;const{config:r,name:i}=this.auth;this.fullUserKey=_persistenceKeyName(this.userKey,r.apiKey,i);this.fullPersistenceKey=_persistenceKeyName("persistence",r.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(){const e=await this.persistence._get(this.fullUserKey);if(!e){return null}if(typeof e==="string"){const t=await getAccountInfo(this.auth,{idToken:e}).catch((()=>undefined));if(!t){return null}return UserImpl._fromGetAccountInfoResponse(this.auth,t,e)}return UserImpl._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}const t=await this.getCurrentUser();await this.removeCurrentUser();this.persistence=e;if(t){return this.setCurrentUser(t)}}delete(){this.persistence._removeListener(this.fullUserKey,this.boundEventHandler)}static async create(e,t,n="authUser"){if(!t.length){return new PersistenceUserManager(_getInstance(C),e,n)}const r=(await Promise.all(t.map((async e=>{if(await e._isAvailable()){return e}return undefined})))).filter((e=>e));let i=r[0]||_getInstance(C);const s=_persistenceKeyName(n,e.config.apiKey,e.name);let o=null;for(const n of t){try{const t=await n._get(s);if(t){let r;if(typeof t==="string"){const n=await getAccountInfo(e,{idToken:t}).catch((()=>undefined));if(!n){break}r=await UserImpl._fromGetAccountInfoResponse(e,n,t)}else{r=UserImpl._fromJSON(e,t)}if(n!==i){o=r}i=n;break}}catch{}}const a=r.filter((e=>e._shouldAllowMigration));if(!i._shouldAllowMigration||!a.length){return new PersistenceUserManager(i,e,n)}i=a[0];if(o){await i._set(s,o.toJSON())}await Promise.all(t.map((async e=>{if(e!==i){try{await e._remove(s)}catch{}}})));return new PersistenceUserManager(i,e,n)}}function _getBrowserName(e){const t=e.toLowerCase();if(t.includes("opera/")||t.includes("opr/")||t.includes("opios/")){return"Opera"}else if(_isIEMobile(t)){return"IEMobile"}else if(t.includes("msie")||t.includes("trident/")){return"IE"}else if(t.includes("edge/")){return"Edge"}else if(_isFirefox(t)){return"Firefox"}else if(t.includes("silk/")){return"Silk"}else if(_isBlackBerry(t)){return"Blackberry"}else if(_isWebOS(t)){return"Webos"}else if(_isSafari(t)){return"Safari"}else if((t.includes("chrome/")||_isChromeIOS(t))&&!t.includes("edge/")){return"Chrome"}else if(_isAndroid(t)){return"Android"}else{const t=/([a-zA-Z\d\.]+)\/[a-zA-Z\d\.]*$/;const n=e.match(t);if(n?.length===2){return n[1]}}return"Other"}function _isFirefox(e=i.getUA()){return/firefox\//i.test(e)}function _isSafari(e=i.getUA()){const t=e.toLowerCase();return t.includes("safari/")&&!t.includes("chrome/")&&!t.includes("crios/")&&!t.includes("android")}function _isChromeIOS(e=i.getUA()){return/crios\//i.test(e)}function _isIEMobile(e=i.getUA()){return/iemobile/i.test(e)}function _isAndroid(e=i.getUA()){return/android/i.test(e)}function _isBlackBerry(e=i.getUA()){return/blackberry/i.test(e)}function _isWebOS(e=i.getUA()){return/webos/i.test(e)}function _isIOS(e=i.getUA()){return/iphone|ipad|ipod/i.test(e)||/macintosh/i.test(e)&&/mobile/i.test(e)}function _isIOS7Or8(e=i.getUA()){return/(iPad|iPhone|iPod).*OS 7_\d/i.test(e)||/(iPad|iPhone|iPod).*OS 8_\d/i.test(e)}function _isIOSStandalone(e=i.getUA()){return _isIOS(e)&&!!window.navigator?.standalone}function _isIE10(){return i.isIE()&&document.documentMode===10}function _isMobileBrowser(e=i.getUA()){return _isIOS(e)||_isAndroid(e)||_isWebOS(e)||_isBlackBerry(e)||/windows phone/i.test(e)||_isIEMobile(e)}function _getClientVersion(e,t=[]){let n;switch(e){case"Browser":n=_getBrowserName(i.getUA());break;case"Worker":n=`${_getBrowserName(i.getUA())}-${e}`;break;default:n=e}const s=t.length?t.join(","):"FirebaseCore-web";return`${n}/${"JsCore"}/${r.SDK_VERSION}/${s}`}class AuthMiddlewareQueue{constructor(e){this.auth=e;this.queue=[]}pushCallback(e,t){const wrappedCallback=t=>new Promise(((n,r)=>{try{const r=e(t);n(r)}catch(e){r(e)}}));wrappedCallback.onAbort=t;this.queue.push(wrappedCallback);const n=this.queue.length-1;return()=>{this.queue[n]=()=>Promise.resolve()}}async runMiddleware(e){if(this.auth.currentUser===e){return}const t=[];try{for(const n of this.queue){await n(e);if(n.onAbort){t.push(n.onAbort)}}}catch(e){t.reverse();for(const e of t){try{e()}catch(e){}}throw this.auth._errorFactory.create("login-blocked",{originalMessage:e?.message})}}}async function _getPasswordPolicy(e,t={}){return _performApiRequest(e,"GET","/v2/passwordPolicy",_addTidIfNecessary(e,t))}const w=6;class PasswordPolicyImpl{constructor(e){const t=e.customStrengthOptions;this.customStrengthOptions={};this.customStrengthOptions.minPasswordLength=t.minPasswordLength??w;if(t.maxPasswordLength){this.customStrengthOptions.maxPasswordLength=t.maxPasswordLength}if(t.containsLowercaseCharacter!==undefined){this.customStrengthOptions.containsLowercaseLetter=t.containsLowercaseCharacter}if(t.containsUppercaseCharacter!==undefined){this.customStrengthOptions.containsUppercaseLetter=t.containsUppercaseCharacter}if(t.containsNumericCharacter!==undefined){this.customStrengthOptions.containsNumericCharacter=t.containsNumericCharacter}if(t.containsNonAlphanumericCharacter!==undefined){this.customStrengthOptions.containsNonAlphanumericCharacter=t.containsNonAlphanumericCharacter}this.enforcementState=e.enforcementState;if(this.enforcementState==="ENFORCEMENT_STATE_UNSPECIFIED"){this.enforcementState="OFF"}this.allowedNonAlphanumericCharacters=e.allowedNonAlphanumericCharacters?.join("")??"";this.forceUpgradeOnSignin=e.forceUpgradeOnSignin??false;this.schemaVersion=e.schemaVersion}validatePassword(e){const t={isValid:true,passwordPolicy:this};this.validatePasswordLengthOptions(e,t);this.validatePasswordCharacterOptions(e,t);
2t.isValid&&(t.isValid=t.meetsMinPasswordLength??true);t.isValid&&(t.isValid=t.meetsMaxPasswordLength??true);t.isValid&&(t.isValid=t.containsLowercaseLetter??true);t.isValid&&(t.isValid=t.containsUppercaseLetter??true);t.isValid&&(t.isValid=t.containsNumericCharacter??true);t.isValid&&(t.isValid=t.containsNonAlphanumericCharacter??true);return t}validatePasswordLengthOptions(e,t){const n=this.customStrengthOptions.minPasswordLength;const r=this.customStrengthOptions.maxPasswordLength;if(n){t.meetsMinPasswordLength=e.length>=n}if(r){t.meetsMaxPasswordLength=e.length<=r}}validatePasswordCharacterOptions(e,t){this.updatePasswordCharacterOptionsStatuses(t,false,false,false,false);let n;for(let r=0;r<e.length;r++){n=e.charAt(r);this.updatePasswordCharacterOptionsStatuses(t,n>="a"&&n<="z",n>="A"&&n<="Z",n>="0"&&n<="9",this.allowedNonAlphanumericCharacters.includes(n))}}updatePasswordCharacterOptionsStatuses(e,t,n,r,i){if(this.customStrengthOptions.containsLowercaseLetter){e.containsLowercaseLetter||(e.containsLowercaseLetter=t)}if(this.customStrengthOptions.containsUppercaseLetter){e.containsUppercaseLetter||(e.containsUppercaseLetter=n)}if(this.customStrengthOptions.containsNumericCharacter){e.containsNumericCharacter||(e.containsNumericCharacter=r)}if(this.customStrengthOptions.containsNonAlphanumericCharacter){e.containsNonAlphanumericCharacter||(e.containsNonAlphanumericCharacter=i)}}}class AuthImpl{constructor(e,t,n,r){this.app=e;this.heartbeatServiceProvider=t;this.appCheckServiceProvider=n;this.config=r;this.currentUser=null;this.emulatorConfig=null;this.operations=Promise.resolve();this.authStateSubscription=new Subscription(this);this.idTokenSubscription=new Subscription(this);this.beforeStateQueue=new AuthMiddlewareQueue(this);this.redirectUser=null;this.isProactiveRefreshEnabled=false;this.EXPECTED_PASSWORD_POLICY_SCHEMA_VERSION=1;this._canInitEmulator=true;this._isInitialized=false;this._deleted=false;this._initializationPromise=null;this._popupRedirectResolver=null;this._errorFactory=f;this._agentRecaptchaConfig=null;this._tenantRecaptchaConfigs={};this._projectPasswordPolicy=null;this._tenantPasswordPolicies={};this._resolvePersistenceManagerAvailable=undefined;this.lastNotifiedUid=undefined;this.languageCode=null;this.tenantId=null;this.settings={appVerificationDisabledForTesting:false};this.frameworks=[];this.name=e.name;this.clientVersion=r.sdkClientVersion;this._persistenceManagerAvailable=new Promise((e=>this._resolvePersistenceManagerAvailable=e))}_initializeWithPersistence(e,t){if(t){this._popupRedirectResolver=_getInstance(t)}this._initializationPromise=this.queue((async()=>{if(this._deleted){return}this.persistenceManager=await PersistenceUserManager.create(this,e);this._resolvePersistenceManagerAvailable?.();if(this._deleted){return}if(this._popupRedirectResolver?._shouldInitProactively){try{await this._popupRedirectResolver._initialize(this)}catch(e){}}await this.initializeCurrentUser(t);this.lastNotifiedUid=this.currentUser?.uid||null;if(this._deleted){return}this._isInitialized=true}));return this._initializationPromise}async _onStorageEvent(){if(this._deleted){return}const e=await this.assertedPersistence.getCurrentUser();if(!this.currentUser&&!e){return}if(this.currentUser&&e&&this.currentUser.uid===e.uid){this._currentUser._assign(e);await this.currentUser.getIdToken();return}await this._updateCurrentUser(e,true)}async initializeCurrentUserFromIdToken(e){try{const t=await getAccountInfo(this,{idToken:e});const n=await UserImpl._fromGetAccountInfoResponse(this,t,e);await this.directlySetCurrentUser(n)}catch(e){console.warn("FirebaseServerApp could not login user with provided authIdToken: ",e);await this.directlySetCurrentUser(null)}}async initializeCurrentUser(e){if(r._isFirebaseServerApp(this.app)){const e=this.app.settings.authIdToken;if(e){return new Promise((t=>{setTimeout((()=>this.initializeCurrentUserFromIdToken(e).then(t,t)))}))}else{return this.directlySetCurrentUser(null)}}const t=await this.assertedPersistence.getCurrentUser();let n=t;let i=false;if(e&&this.config.authDomain){await this.getOrInitRedirectPersistenceManager();const t=this.redirectUser?._redirectEventId;const r=n?._redirectEventId;const s=await this.tryRedirectSignIn(e);if((!t||t===r)&&s?.user){n=s.user;i=true}}if(!n){return this.directlySetCurrentUser(null)}
2if(!n._redirectEventId){if(i){try{await this.beforeStateQueue.runMiddleware(n)}catch(e){n=t;this._popupRedirectResolver._overrideRedirectResult(this,(()=>Promise.reject(e)))}}if(n){return this.reloadAndSetCurrentUserOrClear(n)}else{return this.directlySetCurrentUser(null)}}_assert(this._popupRedirectResolver,this,"argument-error");await this.getOrInitRedirectPersistenceManager();if(this.redirectUser&&this.redirectUser._redirectEventId===n._redirectEventId){return this.directlySetCurrentUser(n)}return this.reloadAndSetCurrentUserOrClear(n)}async tryRedirectSignIn(e){let t=null;try{t=await this._popupRedirectResolver._completeRedirectFn(this,e,true)}catch(e){await this._setRedirectUser(null)}return t}async reloadAndSetCurrentUserOrClear(e){try{await _reloadWithoutSaving(e)}catch(e){if(e?.code!==`auth/${"network-request-failed"}`){return this.directlySetCurrentUser(null)}}return this.directlySetCurrentUser(e)}useDeviceLanguage(){this.languageCode=_getUserLanguage()}async _delete(){this._deleted=true}async updateCurrentUser(e){if(r._isFirebaseServerApp(this.app)){return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(this))}const t=e?i.getModularInstance(e):null;if(t){_assert(t.auth.config.apiKey===this.config.apiKey,this,"invalid-user-token")}return this._updateCurrentUser(t&&t._clone(this))}async _updateCurrentUser(e,t=false){if(this._deleted){return}if(e){_assert(this.tenantId===e.tenantId,this,"tenant-id-mismatch")}if(!t){await this.beforeStateQueue.runMiddleware(e)}return this.queue((async()=>{await this.directlySetCurrentUser(e);this.notifyAuthListeners()}))}async signOut(){if(r._isFirebaseServerApp(this.app)){return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(this))}await this.beforeStateQueue.runMiddleware(null);if(this.redirectPersistenceManager||this._popupRedirectResolver){await this._setRedirectUser(null)}return this._updateCurrentUser(null,true)}setPersistence(e){if(r._isFirebaseServerApp(this.app)){return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(this))}return this.queue((async()=>{await this.assertedPersistence.setPersistence(_getInstance(e))}))}_getRecaptchaConfig(){if(this.tenantId==null){return this._agentRecaptchaConfig}else{return this._tenantRecaptchaConfigs[this.tenantId]}}async validatePassword(e){if(!this._getPasswordPolicyInternal()){await this._updatePasswordPolicy()}const t=this._getPasswordPolicyInternal();if(t.schemaVersion!==this.EXPECTED_PASSWORD_POLICY_SCHEMA_VERSION){return Promise.reject(this._errorFactory.create("unsupported-password-policy-schema-version",{}))}return t.validatePassword(e)}_getPasswordPolicyInternal(){if(this.tenantId===null){return this._projectPasswordPolicy}else{return this._tenantPasswordPolicies[this.tenantId]}}async _updatePasswordPolicy(){const e=await _getPasswordPolicy(this);const t=new PasswordPolicyImpl(e);if(this.tenantId===null){this._projectPasswordPolicy=t}else{this._tenantPasswordPolicies[this.tenantId]=t}}_getPersistenceType(){return this.assertedPersistence.persistence.type}_getPersistence(){return this.assertedPersistence.persistence}_updateErrorMap(e){this._errorFactory=new i.ErrorFactory("auth","Firebase",e())}onAuthStateChanged(e,t,n){return this.registerStateListener(this.authStateSubscription,e,t,n)}beforeAuthStateChanged(e,t){return this.beforeStateQueue.pushCallback(e,t)}onIdTokenChanged(e,t,n){return this.registerStateListener(this.idTokenSubscription,e,t,n)}authStateReady(){return new Promise(((e,t)=>{if(this.currentUser){e()}else{const n=this.onAuthStateChanged((()=>{n();e()}),t)}}))}async revokeAccessToken(e){if(this.currentUser){const t=await this.currentUser.getIdToken();const n={providerId:"apple.com",tokenType:"ACCESS_TOKEN",token:e,idToken:t};if(this.tenantId!=null){n.tenantId=this.tenantId}await revokeToken(this,n)}}toJSON(){return{apiKey:this.config.apiKey,authDomain:this.config.authDomain,appName:this.name,currentUser:this._currentUser?.toJSON()}}async _setRedirectUser(e,t){const n=await this.getOrInitRedirectPersistenceManager(t);return e===null?n.removeCurrentUser():n.setCurrentUser(e)}async getOrInitRedirectPersistenceManager(e){if(!this.redirectPersistenceManager){const t=e&&_getInstance(e)||this._popupRedirectResolver;_assert(t,this,"argument-error");this.redirectPersistenceManager=await PersistenceUserManager.create(this,[_getInstance(t._redirectPersistence)],"redirectUser");this.redirectUser=await this.redirectPersistenceManager.getCurrentUser()}return this.redirectPersistenceManager}async _redirectUserForId(e){if(this._isInitialized){await this.queue((async()=>{}))}if(this._currentUser?._redirectEventId===e){return this._currentUser}if(this.redirectUser?._redirectEventId===e){return this.redirectUser}return null}async _persistUserIfCurrent(e){if(e===this.currentUser){return this.queue((async()=>this.directlySetCurrentUser(e)))}}_notifyListenersIfCurrent(e){if(e===this.currentUser){this.notifyAuthListeners()}}_key(){return`${this.config.authDomain}:${this.config.apiKey}:${this.name}`}_startProactiveRefresh(){this.isProactiveRefreshEnabled=true;if(this.currentUser){this._currentUser._startProactiveRefresh()}}_stopProactiveRefresh(){this.isProactiveRefreshEnabled=false;if(this.currentUser){this._currentUser._stopProactiveRefresh()}}get _currentUser(){return this.currentUser}notifyAuthListeners(){if(!this._isInitialized){return}this.idTokenSubscription.next(this.currentUser);const e=this.currentUser?.uid??null;if(this.lastNotifiedUid!==e){this.lastNotifiedUid=e;this.authStateSubscription.next(this.currentUser)}}registerStateListener(e,t,n,r){if(this._deleted){return()=>{}}const i=typeof t==="function"?t:t.next.bind(t);let s=false;const o=this._isInitialized?Promise.resolve():this._initializationPromise;_assert(o,this,"internal-error");o.then((()=>
2{if(s){return}i(this.currentUser)}));if(typeof t==="function"){const i=e.addObserver(t,n,r);return()=>{s=true;i()}}else{const n=e.addObserver(t);return()=>{s=true;n()}}}async directlySetCurrentUser(e){if(this.currentUser&&this.currentUser!==e){this._currentUser._stopProactiveRefresh()}if(e&&this.isProactiveRefreshEnabled){e._startProactiveRefresh()}this.currentUser=e;if(e){await this.assertedPersistence.setCurrentUser(e)}else{await this.assertedPersistence.removeCurrentUser()}}queue(e){this.operations=this.operations.then(e,e);return this.operations}get assertedPersistence(){_assert(this.persistenceManager,this,"internal-error");return this.persistenceManager}_logFramework(e){if(!e||this.frameworks.includes(e)){return}this.frameworks.push(e);this.frameworks.sort();this.clientVersion=_getClientVersion(this.config.clientPlatform,this._getFrameworks())}_getFrameworks(){return this.frameworks}async _getAdditionalHeaders(){const e={["X-Client-Version"]:this.clientVersion};if(this.app.options.appId){e["X-Firebase-gmpid"]=this.app.options.appId}const t=await(this.heartbeatServiceProvider.getImmediate({optional:true})?.getHeartbeatsHeader());if(t){e["X-Firebase-Client"]=t}const n=await this._getAppCheckToken();if(n){e["X-Firebase-AppCheck"]=n}return e}async _getAppCheckToken(){if(r._isFirebaseServerApp(this.app)&&this.app.settings.appCheckToken){return this.app.settings.appCheckToken}const e=await(this.appCheckServiceProvider.getImmediate({optional:true})?.getToken());if(e?.error){_logWarn(`Error while retrieving App Check token: ${e.error}`)}return e?.token}}function _castAuth(e){return i.getModularInstance(e)}class Subscription{constructor(e){this.auth=e;this.observer=null;this.addObserver=i.createSubscribe((e=>this.observer=e))}get next(){_assert(this.observer,this.auth,"internal-error");return this.observer.next.bind(this.observer)}}let E={async loadJS(){throw new Error("Unable to load external scripts")},recaptchaV2Script:"",recaptchaEnterpriseScript:"",gapiScript:""};function _setExternalJSProvider(e){E=e}function _loadJS(e){return E.loadJS(e)}function _recaptchaV2ScriptUrl(){return E.recaptchaV2Script}function _recaptchaEnterpriseScriptUrl(){return E.recaptchaEnterpriseScript}function _gapiScriptUrl(){return E.gapiScript}function _generateCallbackName(e){return`__${e}${Math.floor(Math.random()*1e6)}`}const T=500;const P=6e4;const A=1e12;class MockReCaptcha{constructor(e){this.auth=e;this.counter=A;this._widgets=new Map}render(e,t){const n=this.counter;this._widgets.set(n,new MockWidget(e,this.auth.name,t||{}));this.counter++;return n}reset(e){const t=e||A;void this._widgets.get(t)?.delete();this._widgets.delete(t)}getResponse(e){const t=e||A;return this._widgets.get(t)?.getResponse()||""}async execute(e){const t=e||A;void this._widgets.get(t)?.execute();return""}}class MockGreCAPTCHATopLevel{constructor(){this.enterprise=new MockGreCAPTCHA}ready(e){e()}execute(e,t){return Promise.resolve("token")}render(e,t){return""}}class MockGreCAPTCHA{ready(e){e()}execute(e,t){return Promise.resolve("token")}render(e,t){return""}}class MockWidget{constructor(e,t,n){this.params=n;this.timerId=null;this.deleted=false;this.responseToken=null;this.clickHandler=()=>{this.execute()};const r=typeof e==="string"?document.getElementById(e):e;_assert(r,"argument-error",{appName:t});this.container=r;this.isVisible=this.params.size!=="invisible";if(this.isVisible){this.execute()}else{this.container.addEventListener("click",this.clickHandler)}}getResponse(){this.checkIfDeleted();return this.responseToken}delete(){this.checkIfDeleted();this.deleted=true;if(this.timerId){clearTimeout(this.timerId);this.timerId=null}this.container.removeEventListener("click",this.clickHandler)}execute(){this.checkIfDeleted();if(this.timerId){return}this.timerId=window.setTimeout((()=>{this.responseToken=generateRandomAlphaNumericString(50);const{callback:e,"expired-callback":t}=this.params;if(e){try{e(this.responseToken)}catch(e){}}this.timerId=window.setTimeout((()=>{this.timerId=null;this.responseToken=null;if(t){try{t()}catch(e){}}if(this.isVisible){this.execute()}}),P)}),T)}checkIfDeleted(){if(this.deleted){throw new Error("reCAPTCHA mock was already deleted!")}}}function generateRandomAlphaNumericString(e){const t=[];const n="1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";for(let r=0;r<e;r++){t.push(n.charAt(Math.floor(Math.random()*n.length)))}return t.join("")}const S="recaptcha-enterprise";const b="NO_RECAPTCHA";class RecaptchaEnterpriseVerifier{constructor(e){this.type=S;this.auth=_castAuth(e)}async verify(e="verify",t=false){async function retrieveSiteKey(e){if(!t){if(e.tenantId==null&&e._agentRecaptchaConfig!=null){return e._agentRecaptchaConfig.siteKey}if(e.tenantId!=null&&e._tenantRecaptchaConfigs[e.tenantId]!==undefined){return e._tenantRecaptchaConfigs[e.tenantId].siteKey}}return new Promise((async(t,n)=>
2{getRecaptchaConfig(e,{clientType:"CLIENT_TYPE_WEB",version:"RECAPTCHA_ENTERPRISE"}).then((r=>{if(r.recaptchaKey===undefined){n(new Error("recaptcha Enterprise site key undefined"))}else{const n=new RecaptchaConfig(r);if(e.tenantId==null){e._agentRecaptchaConfig=n}else{e._tenantRecaptchaConfigs[e.tenantId]=n}return t(n.siteKey)}})).catch((e=>{n(e)}))}))}function retrieveRecaptchaToken(t,n,r){const i=window.grecaptcha;if(isEnterprise(i)){i.enterprise.ready((()=>{i.enterprise.execute(t,{action:e}).then((e=>{n(e)})).catch((()=>{n(b)}))}))}else{r(Error("No reCAPTCHA enterprise script loaded."))}}if(this.auth.settings.appVerificationDisabledForTesting){const e=new MockGreCAPTCHATopLevel;return e.execute("siteKey",{action:"verify"})}return new Promise(((e,n)=>{retrieveSiteKey(this.auth).then((r=>{if(!t&&isEnterprise(window.grecaptcha)){retrieveRecaptchaToken(r,e,n)}else{if(typeof window==="undefined"){n(new Error("RecaptchaVerifier is only supported in browser"));return}let t=_recaptchaEnterpriseScriptUrl();if(t.length!==0){t+=r}_loadJS(t).then((()=>{retrieveRecaptchaToken(r,e,n)}
2)).catch((e=>{n(e)}))}})).catch((e=>{n(e)}))}))}}async function injectRecaptchaFields(e,t,n,r=false,i=false){const s=new RecaptchaEnterpriseVerifier(e);let o;if(i){o=b}else{try{o=await s.verify(n)}catch(e){o=await s.verify(n,true)}}const a={...t};if(n==="mfaSmsEnrollment"||n==="mfaSmsSignIn"){if("phoneEnrollmentInfo"in a){const e=a.phoneEnrollmentInfo.phoneNumber;const t=a.phoneEnrollmentInfo.recaptchaToken;Object.assign(a,{phoneEnrollmentInfo:{phoneNumber:e,recaptchaToken:t,captchaResponse:o,clientType:"CLIENT_TYPE_WEB",recaptchaVersion:"RECAPTCHA_ENTERPRISE"}})}else if("phoneSignInInfo"in a){const e=a.phoneSignInInfo.recaptchaToken;Object.assign(a,{phoneSignInInfo:{recaptchaToken:e,captchaResponse:o,clientType:"CLIENT_TYPE_WEB",recaptchaVersion:"RECAPTCHA_ENTERPRISE"}})}return a}if(!r){Object.assign(a,{captchaResponse:o})}else{Object.assign(a,{captchaResp:o})}Object.assign(a,{clientType:"CLIENT_TYPE_WEB"});Object.assign(a,{recaptchaVersion:"RECAPTCHA_ENTERPRISE"});return a}async function handleRecaptchaFlow(e,t,n,r,i){if(i==="EMAIL_PASSWORD_PROVIDER"){if(e._getRecaptchaConfig()?.isProviderEnabled("EMAIL_PASSWORD_PROVIDER")){const i=await injectRecaptchaFields(e,t,n,n==="getOobCode");return r(e,i)}else{return r(e,t).catch((async i=>{if(i.code===`auth/${"missing-recaptcha-token"}`){console.log(`${n} is protected by reCAPTCHA Enterprise for this project. Automatically triggering the reCAPTCHA flow and restarting the flow.`);const i=await injectRecaptchaFields(e,t,n,n==="getOobCode");return r(e,i)}else{return Promise.reject(i)}}))}}else if(i==="PHONE_PROVIDER"){if(e._getRecaptchaConfig()?.isProviderEnabled("PHONE_PROVIDER")){const i=await injectRecaptchaFields(e,t,n);return r(e,i).catch((async i=>{if(e._getRecaptchaConfig()?.getProviderEnforcementState("PHONE_PROVIDER")==="AUDIT"){if(i.code===`auth/${"missing-recaptcha-token"}`||i.code===`auth/${"invalid-app-credential"}`){console.log(`Failed to verify with reCAPTCHA Enterprise. Automatically triggering the reCAPTCHA v2 flow to complete the ${n} flow.`);const i=await injectRecaptchaFields(e,t,n,false,true);return r(e,i)}}return Promise.reject(i)}))}else{const i=await injectRecaptchaFields(e,t,n,false,true);return r(e,i)}}else{return Promise.reject(i+" provider is not supported.")}}async function _initializeRecaptchaConfig(e){const t=_castAuth(e);const n=await getRecaptchaConfig(t,{clientType:"CLIENT_TYPE_WEB",version:"RECAPTCHA_ENTERPRISE"});const r=new RecaptchaConfig(n);if(t.tenantId==null){t._agentRecaptchaConfig=r}else{t._tenantRecaptchaConfigs[t.tenantId]=r}if(r.isAnyProviderEnabled()){const e=new RecaptchaEnterpriseVerifier(t);void e.verify()}}function initializeAuth(e,t){const n=r._getProvider(e,"auth");if(n.isInitialized()){const e=n.getImmediate();const r=n.getOptions();if(i.deepEqual(r,t??{})){return e}else{_fail(e,"already-initialized")}}const s=n.initialize({options:t});return s}function _initializeAuthInstance(e,t){const n=t?.persistence||[];const r=(Array.isArray(n)?n:[n]).map(_getInstance);if(t?.errorMap){e._updateErrorMap(t.errorMap)}e._initializeWithPersistence(r,t?.popupRedirectResolver)}function connectAuthEmulator(e,t,n){const r=_castAuth(e);_assert(/^https?:\/\//.test(t),r,"invalid-emulator-scheme");const s=!!n?.disableWarnings;const o=extractProtocol(t);const{host:a,port:c}=extractHostAndPort(t);const l=c===null?"":`:${c}`;const u={url:`${o}//${a}${l}/`};const d=Object.freeze({host:a,port:c,protocol:o.replace(":",""),options:Object.freeze({disableWarnings:s})});if(!r._canInitEmulator){_assert(r.config.emulator&&r.emulatorConfig,r,"emulator-config-failed");_assert(i.deepEqual(u,r.config.emulator)&&i.deepEqual(d,r.emulatorConfig),r,"emulator-config-failed");return}r.config.emulator=u;r.emulatorConfig=d;r.settings.appVerificationDisabledForTesting=true;if(i.isCloudWorkstation(a)){void i.pingServer(`${o}//${a}${l}`)}else if(!s){emitEmulatorWarning()}}function extractProtocol(e){const t=e.indexOf(":");return t<0?"":e.substr(0,t+1)}function extractHostAndPort(e){const t=extractProtocol(e);const n=/(\/\/)?([^?#/]+)/.exec(e.substr(t.length));if(!n){return{host:"",port:null}}const r=n[2].split("@").pop()||"";const i=/^(\[[^\]]+\])(:|$)/.exec(r);if(i){const e=i[1];return{host:e,port:parsePort(r.substr(e.length+1))}}else{const[e,t]=r.split(":");return{host:e,port:parsePort(t)}}}function parsePort(e){if(!e){return null}const t=Number(e);if(isNaN(t)){return null}return t}function emitEmulatorWarning(){function attachBanner(){const e=document.createElement("p");const 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)}if(typeof console!=="undefined"&&typeof console.info==="function"){console.info("WARNING: You are using the Auth Emulator,"+" which is intended for local testing only.  Do not use with"+" production credentials.")}if(typeof window!=="undefined"&&typeof document!=="undefined"){if(document.readyState==="loading"){window.addEventListener("DOMContentLoaded",attachBanner)}else{attachBanner()}}}class AuthCredential{constructor(e,t){this.providerId=e;this.signInMethod=t}toJSON(){return debugFail("not implemented")}_getIdTokenResponse(e){return debugFail("not implemented")}_linkToIdToken(e,t){return debugFail("not implemented")}_getReauthenticationResolver(e){return debugFail("not implemented")}}async function resetPassword(e,t){return _performApiRequest(e,"POST","/v1/accounts:resetPassword",_addTidIfNecessary(e,t))}async function updateEmailPassword(e,t){return _performApiRequest(e,"POST","/v1/accounts:update",t)}async function linkEmailPassword(e,t){return _performApiRequest(e,"POST","/v1/accounts:signUp",t)}async function applyActionCode$1(e,t){return _performApiRequest(e,"POST","/v1/accounts:update",_addTidIfNecessary(e,t))}async function signInWithPassword(e,t){return _performSignInRequest(e,"POST","/v1/accounts:signInWithPassword",_addTidIfNecessary(e,t))}async function sendOobCode(e,t){return _performApiRequest(e,"POST","/v1/accounts:sendOobCode",_addTidIfNecessary(e,t))}async function sendEmailVerification$1(e,t){return sendOobCode(e,t)}async function sendPasswordResetEmail$1(e,t){return sendOobCode(e,t)}async function sendSignInLinkToEmail$1(e,t){return sendOobCode(e,t)}async function verifyAndChangeEmail(e,t){return sendOobCode(e,t)}async function signInWithEmailLink$1(e,t){return _performSignInRequest(e,"POST","/v1/accounts:signInWithEmailLink",_addTidIfNecessary(e,t))}async function signInWithEmailLinkForLinking(e,t){return _performSignInRequest(e,"POST","/v1/accounts:signInWithEmailLink",_addTidIfNecessary(e,t))}class EmailAuthCredential extends AuthCredential{constructor(e,t,n,r=null){super("password",n);this._email=e;this._password=t;this._tenantId=r}static _fromEmailAndPassword(e,t){return new EmailAuthCredential(e,t,"password")}static _fromEmailAndCode(e,t,n=null){return new EmailAuthCredential(e,t,"emailLink",n)}toJSON(){return{email:this._email,password:this._password,signInMethod:this.signInMethod,tenantId:this._tenantId}}static fromJSON(e){const t=typeof e==="string"?JSON.parse(e):e;if(t?.email&&t?.password){if(t.signInMethod==="password"){return this._fromEmailAndPassword(t.email,t.password)}else if(t.signInMethod==="emailLink"){return this._fromEmailAndCode(t.email,t.password,t.tenantId)}}return null}async _getIdTokenResponse(e){switch(this.signInMethod){case"password":const t={returnSecureToken:true,email:this._email,password:this._password,clientType:"CLIENT_TYPE_WEB"};return handleRecaptchaFlow(e,t,"signInWithPassword",signInWithPassword,"EMAIL_PASSWORD_PROVIDER");case"emailLink":return signInWithEmailLink$1(e,{email:this._email,oobCode:this._password});default:_fail(e,"internal-error")}}async _linkToIdToken(e,t){switch(this.signInMethod){case"password":const n={idToken:t,returnSecureToken:true,email:this._email,password:this._password,clientType:"CLIENT_TYPE_WEB"};return handleRecaptchaFlow(e,n,"signUpPassword",linkEmailPassword,"EMAIL_PASSWORD_PROVIDER");case"emailLink":return signInWithEmailLinkForLinking(e,{idToken:t,email:this._email,oobCode:this._password});default:_fail(e,"internal-error")}}_getReauthenticationResolver(e){return this._getIdTokenResponse(e)}}async function signInWithIdp(e,t){return _performSignInRequest(e,"POST","/v1/accounts:signInWithIdp",_addTidIfNecessary(e,t))}const R="http://localhost";class OAuthCredential extends AuthCredential{constructor(){super(...arguments);this.pendingToken=null}static _fromParams(e){const t=new OAuthCredential(e.providerId,e.signInMethod);if(e.idToken||e.accessToken){if(e.idToken){t.idToken=e.idToken}if(e.accessToken){t.accessToken=e.accessToken}if(e.nonce&&!e.pendingToken){t.nonce=e.nonce}if(e.pendingToken){t.pendingToken=e.pendingToken}}else if(e.oauthToken&&e.oauthTokenSecret){t.accessToken=e.oauthToken;t.secret=e.oauthTokenSecret}else{_fail("argument-error")}return t}toJSON(){return{idToken:this.idToken,accessToken:this.accessToken,secret:this.secret,n
2once:this.nonce,pendingToken:this.pendingToken,providerId:this.providerId,signInMethod:this.signInMethod}}static fromJSON(e){const t=typeof e==="string"?JSON.parse(e):e;const{providerId:n,signInMethod:r,...i}=t;if(!n||!r){return null}const s=new OAuthCredential(n,r);s.idToken=i.idToken||undefined;s.accessToken=i.accessToken||undefined;s.secret=i.secret;s.nonce=i.nonce;s.pendingToken=i.pendingToken||null;return s}_getIdTokenResponse(e){const t=this.buildRequest();return signInWithIdp(e,t)}_linkToIdToken(e,t){const n=this.buildRequest();n.idToken=t;return signInWithIdp(e,n)}_getReauthenticationResolver(e){const t=this.buildRequest();t.autoCreate=false;return signInWithIdp(e,t)}buildRequest(){const e={requestUri:R,returnSecureToken:true};if(this.pendingToken){e.pendingToken=this.pendingToken}else{const t={};if(this.idToken){t["id_token"]=this.idToken}if(this.accessToken){t["access_token"]=this.accessToken}if(this.secret){t["oauth_token_secret"]=this.secret}t["providerId"]=this.providerId;if(this.nonce&&!this.pendingToken){t["nonce"]=this.nonce}e.postBody=i.querystring(t)}return e}}async function sendPhoneVerificationCode(e,t){return _performApiRequest(e,"POST","/v1/accounts:sendVerificationCode",_addTidIfNecessary(e,t))}async function signInWithPhoneNumber$1(e,t){return _performSignInRequest(e,"POST","/v1/accounts:signInWithPhoneNumber",_addTidIfNecessary(e,t))}async function linkWithPhoneNumber$1(e,t){const n=await _performSignInRequest(e,"POST","/v1/accounts:signInWithPhoneNumber",_addTidIfNecessary(e,t));if(n.temporaryProof){throw _makeTaggedError(e,"account-exists-with-different-credential",n)}return n}const k={["USER_NOT_FOUND"]:"user-not-found"};async function verifyPhoneNumberForExisting(e,t){const n={...t,operation:"REAUTH"};return _performSignInRequest(e,"POST","/v1/accounts:signInWithPhoneNumber",_addTidIfNecessary(e,n),k)}class PhoneAuthCredential extends AuthCredential{constructor(e){super("phone","phone");this.params=e}static _fromVerification(e,t){return new PhoneAuthCredential({verificationId:e,verificationCode:t})}static _fromTokenResponse(e,t){return new PhoneAuthCredential({phoneNumber:e,temporaryProof:t})}_getIdTokenResponse(e){return signInWithPhoneNumber$1(e,this._makeVerificationRequest())}_linkToIdToken(e,t){return linkWithPhoneNumber$1(e,{idToken:t,...this._makeVerificationRequest()})}_getReauthenticationResolver(e){return verifyPhoneNumberForExisting(e,this._makeVerificationRequest())}_makeVerificationRequest(){const{temporaryProof:e,phoneNumber:t,verificationId:n,verificationCode:r}=this.params;if(e&&t){return{temporaryProof:e,phoneNumber:t}}return{sessionInfo:n,code:r}}toJSON(){const e={providerId:this.providerId};if(this.params.phoneNumber){e.phoneNumber=this.params.phoneNumber}if(this.params.temporaryProof){e.temporaryProof=this.params.temporaryProof}if(this.params.verificationCode){e.verificationCode=this.params.verificationCode}if(this.params.verificationId){e.verificationId=this.params.verificationId}return e}static fromJSON(e){if(typeof e==="string"){e=JSON.parse(e)}const{verificationId:t,verificationCode:n,phoneNumber:r,temporaryProof:i}=e;if(!n&&!t&&!r&&!i){return null}return new PhoneAuthCredential({verificationId:t,verificationCode:n,phoneNumber:r,temporaryProof:i})}}function parseMode(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}}function parseDeepLink(e){const t=i.querystringDecode(i.extractQuerystring(e))["link"];const n=t?i.querystringDecode(i.extractQuerystring(t))["deep_link_id"]:null;const r=i.querystringDecode(i.extractQuerystring(e))["deep_link_id"];const s=r?i.querystringDecode(i.extractQuerystring(r))["link"]:null;return s||r||n||t||e}class ActionCodeURL{constructor(e){const t=i.querystringDecode(i.extractQuerystring(e));const n=t["apiKey"]??null;const r=t["oobCode"]??null;const s=parseMode(t["mode"]??null);_assert(n&&r&&s,"argument-error");this.apiKey=n;this.operation=s;
2this.code=r;this.continueUrl=t["continueUrl"]??null;this.languageCode=t["lang"]??null;this.tenantId=t["tenantId"]??null}static parseLink(e){const t=parseDeepLink(e);try{return new ActionCodeURL(t)}catch{return null}}}function parseActionCodeURL(e){return ActionCodeURL.parseLink(e)}class EmailAuthProvider{constructor(){this.providerId=EmailAuthProvider.PROVIDER_ID}static credential(e,t){return EmailAuthCredential._fromEmailAndPassword(e,t)}static credentialWithLink(e,t){const n=ActionCodeURL.parseLink(t);_assert(n,"argument-error");return EmailAuthCredential._fromEmailAndCode(e,n.code,n.tenantId)}}EmailAuthProvider.PROVIDER_ID="password";EmailAuthProvider.EMAIL_PASSWORD_SIGN_IN_METHOD="password";EmailAuthProvider.EMAIL_LINK_SIGN_IN_METHOD="emailLink";class FederatedAuthProvider{constructor(e){this.providerId=e;this.defaultLanguageCode=null;this.customParameters={}}setDefaultLanguage(e){this.defaultLanguageCode=e}setCustomParameters(e){this.customParameters=e;return this}getCustomParameters(){return this.customParameters}}class BaseOAuthProvider extends FederatedAuthProvider{constructor(){super(...arguments);this.scopes=[]}addScope(e){if(!this.scopes.includes(e)){this.scopes.push(e)}return this}getScopes(){return[...this.scopes]}}class OAuthProvider extends BaseOAuthProvider{static credentialFromJSON(e){const t=typeof e==="string"?JSON.parse(e):e;_assert("providerId"in t&&"signInMethod"in t,"argument-error");return OAuthCredential._fromParams(t)}credential(e){return this._credential({...e,nonce:e.rawNonce})}_credential(e){_assert(e.idToken||e.accessToken,"argument-error");return OAuthCredential._fromParams({...e,providerId:this.providerId,sign
2InMethod:this.providerId})}static credentialFromResult(e){return OAuthProvider.oauthCredentialFromTaggedObject(e)}static credentialFromError(e){return OAuthProvider.oauthCredentialFromTaggedObject(e.customData||{})}static oauthCredentialFromTaggedObject({_tokenResponse:e}){if(!e){return null}const{oauthIdToken:t,oauthAccessToken:n,oauthTokenSecret:r,pendingToken:i,nonce:s,providerId:o}=e;if(!n&&!r&&!t&&!i){return null}if(!o){return null}try{return new OAuthProvider(o)._credential({idToken:t,accessToken:n,nonce:s,pendingToken:i})}catch(e){return null}}}class FacebookAuthProvider extends BaseOAuthProvider{constructor(){super("facebook.com")}static credential(e){return OAuthCredential._fromParams({providerId:FacebookAuthProvider.PROVIDER_ID,signInMethod:FacebookAuthProvider.FACEBOOK_SIGN_IN_METHOD,accessToken:e})}static credentialFromResult(e){return FacebookAuthProvider.credentialFromTaggedObject(e)}static credentialFromError(e){return FacebookAuthProvider.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e||!("oauthAccessToken"in e)){return null}if(!e.oauthAccessToken){return null}try{return FacebookAuthProvider.credential(e.oauthAccessToken)}catch{return null}}}FacebookAuthProvider.FACEBOOK_SIGN_IN_METHOD="facebook.com";FacebookAuthProvider.PROVIDER_ID="facebook.com";class GoogleAuthProvider extends BaseOAuthProvider{constructor(){super("google.com");this.addScope("profile")}static credential(e,t){return OAuthCredential._fromParams({providerId:GoogleAuthProvider.PROVIDER_ID,signInMethod:GoogleAuthProvider.GOOGLE_SIGN_IN_METHOD,idToken:e,accessToken:t})}static credentialFromResult(e){return GoogleAuthProvider.credentialFromTaggedObject(e)}static credentialFromError(e){return GoogleAuthProvider.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e){return null}const{oauthIdToken:t,oauthAccessToken:n}=e;if(!t&&!n){return null}try{return GoogleAuthProvider.credential(t,n)}catch{return null}}}GoogleAuthProvider.GOOGLE_SIGN_IN_METHOD="google.com";GoogleAuthProvider.PROVIDER_ID="google.com";class GithubAuthProvider extends BaseOAuthProvider{constructor(){super("github.com")}static credential(e){return OAuthCredential._fromParams({providerId:GithubAuthProvider.PROVIDER_ID,signInMethod:GithubAuthProvider.GITHUB_SIGN_IN_METHOD,accessToken:e})}static credentialFromResult(e){return GithubAuthProvider.credentialFromTaggedObject(e)}static credentialFromError(e){return GithubAuthProvider.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e||!("oauthAccessToken"in e)){return null}if(!e.oauthAccessToken){return null}try{return GithubAuthProvider.credential(e.oauthAccessToken)}catch{return null}}}GithubAuthProvider.GITHUB_SIGN_IN_METHOD="github.com";GithubAuthProvider.PROVIDER_ID="github.com";const N="http://localhost";class SAMLAuthCredential extends AuthCredential{constructor(e,t){super(e,e);this.pendingToken=t}_getIdTokenResponse(e){const t=this.buildRequest();return signInWithIdp(e,t)}_linkToIdToken(e,t){const n=this.buildRequest();n.idToken=t;return signInWithIdp(e,n)}_getReauthenticationResolver(e){const t=this.buildRequest();t.autoCreate=false;return signInWithIdp(e,t)}toJSON(){return{signInMethod:this.signInMethod,providerId:this.providerId,pendingToken:this.pendingToken}}static fromJSON(e){const t=typeof e==="string"?JSON.parse(e):e;const{providerId:n,signInMethod:r,pendingToken:i}=t;if(!n||!r||!i||n!==r){return null}return new SAMLAuthCredential(n,i)}static _create(e,t){return new SAMLAuthCredential(e,t)}buildRequest(){return{requestUri:N,returnSecureToken:true,pendingToken:this.pendingToken}}}const O="saml.";class SAMLAuthProvider extends FederatedAuthProvider{constructor(e){_assert(e.startsWith(O),"argument-error");super(e)}static credentialFromResult(e){return SAMLAuthProvider.samlCredentialFromTaggedObject(e)}static credentialFromError(e){return SAMLAuthProvider.samlCredentialFromTaggedObject(e.customData||{})}static credentialFromJSON(e){const t=SAMLAuthCredential.fromJSON(e);_assert(t,"argument-error");return t}
2static samlCredentialFromTaggedObject({_tokenResponse:e}){if(!e){return null}const{pendingToken:t,providerId:n}=e;if(!t||!n){return null}try{return SAMLAuthCredential._create(n,t)}catch(e){return null}}}class TwitterAuthProvider extends BaseOAuthProvider{constructor(){super("twitter.com")}static credential(e,t){return OAuthCredential._fromParams({providerId:TwitterAuthProvider.PROVIDER_ID,signInMethod:TwitterAuthProvider.TWITTER_SIGN_IN_METHOD,oauthToken:e,oauthTokenSecret:t})}static credentialFromResult(e){return TwitterAuthProvider.credentialFromTaggedObject(e)}static credentialFromError(e){return TwitterAuthProvider.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e){return null}const{oauthAccessToken:t,oauthTokenSecret:n}=e;if(!t||!n){return null}try{return TwitterAuthProvider.credential(t,n)}catch{return null}}}TwitterAuthProvider.TWITTER_SIGN_IN_METHOD="twitter.com";TwitterAuthProvider.PROVIDER_ID="twitter.com";async function signUp(e,t){return _performSignInRequest(e,"POST","/v1/accounts:signUp",_addTidIfNecessary(e,t))}class UserCredentialImpl{constructor(e){this.user=e.user;this.providerId=e.providerId;this._tokenResponse=e._tokenResponse;this.operationType=e.operationType}static async _fromIdTokenResponse(e,t,n,r=false){const i=await UserImpl._fromIdTokenResponse(e,n,r);const s=providerIdForResponse(n);const o=new UserCredentialImpl({user:i,providerId:s,_tokenResponse:n,operationType:t});return o}static async _forOperation(e,t,n){await e._updateTokensIfNecessary(n,true);const r=providerIdForResponse(n);return new UserCredentialImpl({user:e,providerId:r,_tokenResponse:n,operationType:t})}}function providerIdForResponse(e){if(e.providerId){return e.providerId}if("phoneNumber"in e){return"phone"}return null}async function signInAnonymously(e){if(r._isFirebaseServerApp(e.app)){return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(e))}const t=_castAuth(e);await t._initializationPromise;if(t.currentUser?.isAnonymous){return new UserCredentialImpl({user:t.currentUser,providerId:null,operationType:"signIn"})}const n=await signUp(t,{returnSecureToken:true});const i=await UserCredentialImpl._fromIdTokenResponse(t,"signIn",n,true);await t._updateCurrentUser(i.user);return i}class MultiFactorError extends i.FirebaseError{constructor(e,t,n,r){super(t.code,t.message);this.operationType=n;this.user=r;Object.setPrototypeOf(this,MultiFactorError.prototype);this.customData={appName:e.name,tenantId:e.tenantId??undefined,_serverResponse:t.customData._serverResponse,operationType:n}}static _fromErrorAndOperation(e,t,n,r){return new MultiFactorError(e,t,n,r)}}function _processCredentialSavingMfaContextIfNecessary(e,t,n,r){const i=t==="reauthenticate"?n._getReauthenticationResolver(e):n._getIdTokenResponse(e);return i.catch((n=>{if(n.code===`auth/${"multi-factor-auth-required"}`){throw MultiFactorError._fromErrorAndOperation(e,n,t,r)}throw n}))}function providerDataAsNames(e){return new Set(e.map((({providerId:e})=>e)).filter((e=>!!e)))}async function unlink(e,t){const n=i.getModularInstance(e);await _assertLinkedStatus(true,n,t);const{providerUserInfo:r}=await deleteLinkedAccounts(n.auth,{idToken:await n.getIdToken(),deleteProvider:[t]});const s=providerDataAsNames(r||[]);n.providerData=n.providerData.filter((e=>s.has(e.providerId)));if(!s.has("phone")){n.phoneNumber=null}await n.auth._persistUserIfCurrent(n);return n}async function _link$1(e,t,n=false){const r=await _logoutIfInvalidated(e,t._linkToIdToken(e.auth,await e.getIdToken()),n);return UserCredentialImpl._forOperation(e,"link",r)}async function _assertLinkedStatus(e,t,n){await _reloadWithoutSaving(t);const r=providerDataAsNames(t.providerData);const i=e===false?"provider-already-linked":"no-such-provider";_assert(r.has(n)===e,t.auth,i)}async function _reauthenticate(e,t,n=false){const{auth:i}=e;if(r._isFirebaseServerApp(i.app)){return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(i))}const s="reauthenticate";try{const r=await _logoutIfInvalidated(e,_processCredentialSavingMfaContextIfNecessary(i,s,t,e),n);_assert(r.idToken,i,"internal-error");const o=_parseToken(r.idToken);_assert(o,i,"internal-error");const{sub:a}=o;_assert(e.uid===a,i,"user-mismatch");return UserCredentialImpl._forOperation(e,s,r)}catch(e){if(e?.code===`auth/${"user-not-found"}`){_fail(i,"user-mismatch")}throw e}}async function _signInWithCredential(e,t,n=false){if(r._isFirebaseServerApp(e.app)){return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(e))}const i="signIn";const s=await _processCredentialSavingMfaContextIfNecessary(e,i,t);const o=await UserCredentialImpl._fromIdTokenResponse(e,i,s);if(!n){await e._updateCurrentUser(o.user)}return o}async function signInWithCredential(e,t){return _signInWithCredential(_castAuth(e),t)}async function linkWithCredential(e,t){const n=i.getModularInstance(e);await _assertLinkedStatus(false,n,t.providerId);return _link$1(n,t)}async function reauthenticateWithCredential(e,t){return _reauthenticate(i.getModularInstance(e),t)}async function signInWithCustomToken$1(e,t){return _performSignInRequest(e,"POST","/v1/accounts:signInWithCustomToken",_addTidIfNecessary(e,t))}async function signInWithCustomToken(e,t){if(r._isFirebaseServerApp(e.app)){return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(e))}const n=_castAuth(e);const i=await signInWithCustomToken$1(n,{token:t,returnSecureToken:true});const s=await UserCredentialImpl._fromIdTokenResponse(n,"signIn",i);await n._updateCurrentUser(s.user);return s}class MultiFactorInfoImpl{constructor(e,t){this.factorId=e;this.uid=t.mfaEnrollmentId;this.enrollmentTime=new Date(t.enrolledAt).toUTCString();this.displayName=t.displayName}static _fromServerResponse(e,t){if("phoneInfo"in t){return PhoneMultiFactorInfoImpl._fromServerResponse(e,t)}else if("totpInfo"in t){return TotpMultiFactorInfoImpl._fromServerResponse(e,t)}return _fail(e,"internal-error")}}class PhoneMultiFactorInfoImpl extends MultiFactorInfoImpl{constructor(e){super("phone",e);this.phoneNumber=e.phoneInfo}static _fromServerResponse(e,t){return new PhoneMultiFactorInfoImpl(t)}}class TotpMultiFactorInfoImpl extends MultiFactorInfoImpl{constructor(e){super("totp",e)}static _fromServerResponse(e,t){return new TotpMultiFactorInfoImpl(t)}}function _setActionCodeSettingsOnRequest(e,t,n){_assert(n.url?.length>
20,e,"invalid-continue-uri");_assert(typeof n.dynamicLinkDomain==="undefined"||n.dynamicLinkDomain.length>0,e,"invalid-dynamic-link-domain");_assert(typeof n.linkDomain==="undefined"||n.linkDomain.length>0,e,"invalid-hosting-link-domain");t.continueUrl=n.url;t.dynamicLinkDomain=n.dynamicLinkDomain;t.linkDomain=n.linkDomain;t.canHandleCodeInApp=n.handleCodeInApp;if(n.iOS){_assert(n.iOS.bundleId.length>0,e,"missing-ios-bundle-id");t.iOSBundleId=n.iOS.bundleId}if(n.android){_assert(n.android.packageName.length>0,e,"missing-android-pkg-name");t.androidInstallApp=n.android.installApp;t.androidMinimumVersionCode=n.android.minimumVersion;t.androidPackageName=n.android.packageName}}async function recachePasswordPolicy(e){const t=_castAuth(e);if(t._getPasswordPolicyInternal()){await t._updatePasswordPolicy()}}async function sendPasswordResetEmail(e,t,n){const r=_castAuth(e);const i={requestType:"PASSWORD_RESET",email:t,clientType:"CLIENT_TYPE_WEB"};if(n){_setActionCodeSettingsOnRequest(r,i,n)}await handleRecaptchaFlow(r,i,"getOobCode",sendPasswordResetEmail$1,"EMAIL_PASSWORD_PROVIDER")}async function confirmPasswordReset(e,t,n){await resetPassword(i.getModularInstance(e),{oobCode:t,newPassword:n}).catch((async t=>{if(t.code===`auth/${"password-does-not-meet-requirements"}`){void recachePasswordPolicy(e)}throw t}))}async function applyActionCode(e,t){await applyActionCode$1(i.getModularInstance(e),{oobCode:t})}async function checkActionCode(e,t){const n=i.getModularInstance(e);const r=await resetPassword(n,{oobCode:t});const s=r.requestType;_assert(s,n,"internal-error");switch(s){case"EMAIL_SIGNIN":break;case"VERIFY_AND_CHANGE_EMAIL":_assert(r.newEmail,n,"internal-error");break;case"REVERT_SECOND_FACTOR_ADDITION":_assert(r.mfaInfo,n,"internal-error");default:_assert(r.email,n,"internal-error")}let o=null;if(r.mfaInfo){o=MultiFactorInfoImpl._fromServerResponse(_castAuth(n),r.mfaInfo)}return{data:{email:(r.requestType==="VERIFY_AND_CHANGE_EMAIL"?r.newEmail:r.email)||null,previousEmail:(r.requestType==="VERIFY_AND_CHANGE_EMAIL"?r.email:r.newEmail)||null,multiFactorInfo:o},operation:s}}async function verifyPasswordResetCode(e,t){const{data:n}=await checkActionCode(i.getModularInstance(e),t);return n.email}async function createUserWithEmailAndPassword(e,t,n){if(r._isFirebaseServerApp(e.app)){return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(e))}const i=_castAuth(e);const s={returnSecureToken:true,email:t,password:n,clientType:"CLIENT_TYPE_WEB"};const o=handleRecaptchaFlow(i,s,"signUpPassword",signUp,"EMAIL_PASSWORD_PROVIDER");const a=await o.catch((t=>{if(t.code===`auth/${"password-does-not-meet-requirements"}`){void recachePasswordPolicy(e)}throw t}));const c=await UserCredentialImpl._fromIdTokenResponse(i,"signIn",a);await i._updateCurrentUser(c.user);return c}function signInWithEmailAndPassword(e,t,n){if(r._isFirebaseServerApp(e.app)){return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(e))}return signInWithCredential(i.getModularInstance(e),EmailAuthProvider.credential(t,n)).catch((async t=>{if(t.code===`auth/${"password-does-not-meet-requirements"}`){void recachePasswordPolicy(e)}throw t}))}async function sendSignInLinkToEmail(e,t,n){const r=_castAuth(e);const i={requestType:"EMAIL_SIGNIN",email:t,clientType:"CLIENT_TYPE_WEB"};function setActionCodeSettings(e,t){_assert(t.handleCodeInApp,r,"argument-error");if(t){_setActionCodeSettingsOnRequest(r,e,t)}}setActionCodeSettings(i,n);await handleRecaptchaFlow(r,i,"getOobCode",sendSignInLinkToEmail$1,"EMAIL_PASSWORD_PROVIDER")}function isSignInWithEmailLink(e,t){const n=ActionCodeURL.parseLink(t);return n?.operation==="EMAIL_SIGNIN"}async function signInWithEmailLink(e,t,n){if(r._isFirebaseServerApp(e.app)){return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(e))}const s=i.getModularInstance(e);const o=EmailAuthProvider.credentialWithLink(t,n||_getCurrentUrl());_assert(o._tenantId===(s.tenantId||null),s,"tenant-id-mismatch");return signInWithCredential(s,o)}async function createAuthUri(e,t){return _performApiRequest(e,"POST","/v1/accounts:createAuthUri",_addTidIfNecessary(e,t))}async function fetchSignInMethodsForEmail(e,t){const n=_isHttpOrHttps()?_getCurrentUrl():"http://localhost";const r={identifier:t,continueUri:n};const{signinMethods:s}=await createAuthUri(i.getModularInstance(e),r);return s||[]}async function sendEmailVerification(e,t){const n=i.getModularInstance(e);const r=await e.getIdToken();const s={requestType:"VERIFY_EMAIL",idToken:r};if(t){_setActionCodeSettingsOnRequest(n.auth,s,t)}const{email:o}=await sendEmailVerification$1(n.auth,s);if(o!==e.email){await e.reload()}}async function verifyBeforeUpdateEmail(e,t,n){const r=i.getModularInstance(e);const s=await e.getIdToken();const o={requestType:"VERIFY_AND_CHANGE_EMAIL",idToken:s,newEmail:t};if(n){_setActionCodeSettingsOnRequest(r.auth,o,n)}const{email:a}=await verifyAndChangeEmail(r.auth,o);if(a!==e.email){await e.reload()}}async function updateProfile$1(e,t){return _performApiRequest(e,"POST","/v1/accounts:update",t)}async function updateProfile(e,{displayName:t,photoURL:n}){if(t===undefined&&n===undefined){return}const r=i.getModularInstance(e);const s=await r.getIdToken();const o={idToken:s,displayName:t,photoUrl:n,returnSecureToken:true};const a=await _logoutIfInvalidated(r,updateProfile$1(r.auth,o));r.displayName=a.displayName||null;r.photoURL=a.photoUrl||null;const c=r.providerData.find((({providerId:e})=>e==="password"));if(c){c.displayName=r.displayName;c.photoURL=r.photoURL}await r._updateTokensIfNecessary(a)}function updateEmail(e,t){const n=i.getModularInstance(e);if(r._isFirebaseServerApp(n.auth.app)){return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(n.auth))}return updateEmailOrPassword(n,t,null)}function updatePassword(e,t){return updateEmailOrPassword(i.getModularInstance(e),null,t)}async function updateEmailOrPassword(e,t,n){const{auth:r}=e;const i=await e.getIdToken();const s={idToken:i,returnSecureToken:true};if(t){s.email=t}if(n){s.password=n}const o=await _logoutIfInvalidated(e,updateEmailPassword(r,s));await e._updateTokensIfNecessary(o,true)}function _fromIdTokenResponse(e){if(!e){return null}const{providerId:t}=e;const n=e.rawUserInfo?JSON.parse(e.rawUserInfo):{};const r=e.isNewUser||e.kind==="identitytoolkit#SignupNewUserResponse";if(!t&&e?.idToken){const t=_parseToken(e.idToken)?.firebase?.["sign_in_provider"];if(t){const e=t!=="anonymous"&&t!=="custom"?t:null;return new GenericAdditionalUserInfo(r,e)}}if(!t){return null}switch(t){case"facebook.com":return new FacebookAdditionalUserInfo(r,n);case"github.com":return new GithubAdditionalUserInfo(r,n);case"google.com":return new GoogleAdditionalUserInfo(r,n);case"twitter.com":return new TwitterAdditionalUserInfo(r,n,e.screenName||null);
2case"custom":case"anonymous":return new GenericAdditionalUserInfo(r,null);default:return new GenericAdditionalUserInfo(r,t,n)}}class GenericAdditionalUserInfo{constructor(e,t,n={}){this.isNewUser=e;this.providerId=t;this.profile=n}}class FederatedAdditionalUserInfoWithUsername extends GenericAdditionalUserInfo{constructor(e,t,n,r){super(e,t,n);this.username=r}}class FacebookAdditionalUserInfo extends GenericAdditionalUserInfo{constructor(e,t){super(e,"facebook.com",t)}}class GithubAdditionalUserInfo extends FederatedAdditionalUserInfoWithUsername{constructor(e,t){super(e,"github.com",t,typeof t?.login==="string"?t?.login:null)}}class GoogleAdditionalUserInfo extends GenericAdditionalUserInfo{constructor(e,t){super(e,"google.com",t)}}class TwitterAdditionalUserInfo extends FederatedAdditionalUserInfoWithUsername{constructor(e,t,n){super(e,"twitter.com",t,n)}}function getAdditionalUserInfo(e){const{user:t,_tokenResponse:n}=e;if(t.isAnonymous&&!n){return{providerId:null,isNewUser:false,profile:null}}return _fromIdTokenResponse(n)}function setPersistence(e,t){return i.getModularInstance(e).setPersistence(t)}function initializeRecaptchaConfig(e){return _initializeRecaptchaConfig(e)}async function validatePassword(e,t){const n=_castAuth(e);return n.validatePassword(t)}function onIdTokenChanged(e,t,n,r){return i.getModularInstance(e).onIdTokenChanged(t,n,r)}function beforeAuthStateChanged(e,t,n){return i.getModularInstance(e).beforeAuthStateChanged(t,n)}function onAuthStateChanged(e,t,n,r){return i.getModularInstance(e).onAuthStateChanged(t,n,r)}function useDeviceLanguage(e){i.getModularInstance(e).useDeviceLanguage()}function updateCurrentUser(e,t){return i.getModularInstance(e).updateCurrentUser(t)}function signOut(e){return i.getModularInstance(e).signOut()}function revokeAccessToken(e,t){const n=_castAuth(e);return n.revokeAccessToken(t)}async function deleteUser(e){return i.getModularInstance(e).delete()}class MultiFactorSessionImpl{constructor(e,t,n){this.type=e;this.credential=t;this.user=n}static _fromIdtoken(e,t){return new MultiFactorSessionImpl("enroll",e,t)}static _fromMfaPendingCredential(e){return new MultiFactorSessionImpl("signin",e)}toJSON(){const e=this.type==="enroll"?"idToken":"pendingCredential";return{multiFactorSession:{[e]:this.credential}}}static fromJSON(e){if(e?.multiFactorSession){if(e.multiFactorSession?.pendingCredential){return MultiFactorSessionImpl._fromMfaPendingCredential(e.multiFactorSession.pendingCredential)}else if(e.multiFactorSession?.idToken){return MultiFactorSessionImpl._fromIdtoken(e.multiFactorSession.idToken)}}return null}}class MultiFactorResolverImpl{constructor(e,t,n){this.session=e;this.hints=t;this.signInResolver=n}static _fromError(e,t){const n=_castAuth(e);const r=t.customData._serverResponse;const i=(r.mfaInfo||[]).map((e=>MultiFactorInfoImpl._fromServerResponse(n,e)));_assert(r.mfaPendingCredential,n,"internal-error");const s=MultiFactorSessionImpl._fromMfaPendingCredential(r.mfaPendingCredential);return new MultiFactorResolverImpl(s,i,(async e=>{const i=await e._process(n,s);delete r.mfaInfo;delete r.mfaPendingCredential;const o={...r,idToken:i.idToken,refreshToken:i.refreshToken};switch(t.operationType){case"signIn":const e=await UserCredentialImpl._fromIdTokenResponse(n,t.operationType,o);await n._updateCurrentUser(e.user);return e;case"reauthenticate":_assert(t.user,n,"internal-error");return UserCredentialImpl._forOperation(t.user,t.operationType,o);default:_fail(n,"internal-error")}}))}async resolveSignIn(e){const t=e;return this.signInResolver(t)}}function getMultiFactorResolver(e,t){const n=i.getModularInstance(e);const r=t;_assert(t.customData.operationType,n,"argument-error");_assert(r.customData._serverResponse?.mfaPendingCredential,n,"argument-error");return MultiFactorResolverImpl._fromError(n,r)}function startEnrollPhoneMfa(e,t){return _performApiRequest(e,"POST","/v2/accounts/mfaEnrollment:start",_addTidIfNecessary(e,t))}function finalizeEnrollPhoneMfa(e,t){return _performApiRequest(e,"POST","/v2/accounts/mfaEnrollment:finalize",_addTidIfNecessary(e,t))}function startEnrollTotpMfa(e,t){return _performApiRequest(e,"POST","/v2/accounts/mfaEnrollment:start",_addTidIfNecessary(e,t))}function finalizeEnrollTotpMfa(e,t){return _performApiRequest(e,"POST","/v2/accounts/mfaEnrollment:finalize",_addTidIfNecessary(e,t))}function withdrawMfa(e,t){return _performApiRequest(e,"POST","/v2/accounts/mfaEnrollment:withdraw",_addTidIfNecessary(e,t))}class MultiFactorUserImpl{constructor(e){this.user=e;this.enrolledFactors=[];e._onReload((t=>{if(t.mfaInfo){this.enrolledFactors=t.mfaInfo.map((t=>MultiFactorInfoImpl._fromServerResponse(e.auth,t)))}}))}static _fromUser(e){return new MultiFactorUserImpl(e)}async getSession(){return MultiFactorSessionImpl._fromIdtoken(await this.user.getIdToken(),this.user)}async enroll(e,t){const n=e;
2const r=await this.getSession();const i=await _logoutIfInvalidated(this.user,n._process(this.user.auth,r,t));await this.user._updateTokensIfNecessary(i);return this.user.reload()}async unenroll(e){const t=typeof e==="string"?e:e.uid;const n=await this.user.getIdToken();try{const e=await _logoutIfInvalidated(this.user,withdrawMfa(this.user.auth,{idToken:n,mfaEnrollmentId:t}));this.enrolledFactors=this.enrolledFactors.filter((({uid:e})=>e!==t));await this.user._updateTokensIfNecessary(e);await this.user.reload()}catch(e){throw e}}}const D=new WeakMap;function multiFactor(e){const t=i.getModularInstance(e);if(!D.has(t)){D.set(t,MultiFactorUserImpl._fromUser(t))}return D.get(t)}const L="__sak";class BrowserPersistenceClass{constructor(e,t){this.storageRetriever=e;this.type=t}_isAvailable(){try{if(!this.storage){return Promise.resolve(false)}this.storage.setItem(L,"1");this.storage.removeItem(L);return Promise.resolve(true)}catch{return Promise.resolve(false)}}_set(e,t){this.storage.setItem(e,JSON.stringify(t));return Promise.resolve()}_get(e){const t=this.storage.getItem(e);return Promise.resolve(t?JSON.parse(t):null)}_remove(e){this.storage.removeItem(e);return Promise.resolve()}get storage(){return this.storageRetriever()}}const M=1e3;const F=10;class BrowserLocalPersistence extends BrowserPersistenceClass{constructor(){super((()=>window.localStorage),"LOCAL");this.boundEventHandler=(e,t)=>this.onStorageEvent(e,t);this.listeners={};this.localCache={};this.pollTimer=null;this.fallbackToPolling=_isMobileBrowser();this._shouldAllowMigration=true}forAllChangedKeys(e){for(const t of Object.keys(this.listeners)){const n=this.storage.getItem(t);const r=this.localCache[t];if(n!==r){e(t,r,n)}}}onStorageEvent(e,t=false){if(!e.key){this.forAllChangedKeys(((e,t,n)=>{this.notifyListeners(e,n)}));return}const n=e.key;if(t){this.detachListener()}else{this.stopPolling()}const triggerListeners=()=>{const e=this.storage.getItem(n);if(!t&&this.localCache[n]===e){return}this.notifyListeners(n,e)};const r=this.storage.getItem(n);if(_isIE10()&&r!==e.newValue&&e.newValue!==e.oldValue){setTimeout(triggerListeners,F)}else{triggerListeners()}}notifyListeners(e,t){this.localCache[e]=t;const n=this.listeners[e];if(n){for(const e of Array.from(n)){e(t?JSON.parse(t):t)}}}startPolling(){this.stopPolling();this.pollTimer=setInterval((()=>{this.forAllChangedKeys(((e,t,n)=>{this.onStorageEvent(new StorageEvent("storage",{key:e,oldValue:t,newValue:n}),true)}))}),M)}stopPolling(){if(this.pollTimer){clearInterval(this.pollTimer);this.pollTimer=null}}attachListener(){window.addEventListener("storage",this.boundEventHandler)}detachListener(){window.removeEventListener("storage",this.boundEventHandler)}_addListener(e,t){if(Object.keys(this.listeners).length===0){if(this.fallbackToPolling){this.startPolling()}else{this.attachListener()}}if(!this.listeners[e]){this.listeners[e]=new Set;this.localCache[e]=this.storage.getItem(e)}this.listeners[e].add(t)}_removeListener(e,t){if(this.listeners[e]){this.listeners[e].delete(t);if(this.listeners[e].size===0){delete this.listeners[e]}}if(Object.keys(this.listeners).length===0){this.detachListener();this.stopPolling()}}async _set(e,t){await super._set(e,t);this.localCache[e]=JSON.stringify(t)}async _get(e){const t=await super._get(e);this.localCache[e]=JSON.stringify(t);return t}async _remove(e){await super._remove(e);delete this.localCache[e]}}BrowserLocalPersistence.type="LOCAL";const U=BrowserLocalPersistence;const x=1e3;function getDocumentCookie(e){const t=e.replace(/[\\^$.*+?()[\]{}|]/g,"\\$&");const n=RegExp(`${t}=([^;]+)`);return document.cookie.match(n)?.[1]??null}function getCookieName(e){const t=window.location.protocol==="http:";return`${t?"__dev_":"__HOST-"}FIREBASE_${e.split(":")[3]}`}class CookiePersistence{constructor(){this.type="COOKIE";this.listenerUnsubscribes=new Map}_getFinalTarget(e){if(typeof window===undefined){return e}const t=new URL(`${window.location.origin}/__cookies__`);t.searchParams.set("finalTarget",e);return t}async _isAvailable(){if(typeof isSecureContext==="boolean"&&!isSecureContext){return false}if(typeof navigator==="undefined"||typeof document==="undefined"){return false}return navigator.cookieEnabled??true}async _set(e,t){return}async _get(e){if(!this._isAvailable()){return null}const t=getCookieName(e);
2if(window.cookieStore){const e=await window.cookieStore.get(t);return e?.value}return getDocumentCookie(t)}async _remove(e){if(!this._isAvailable()){return}const t=await this._get(e);if(!t){return}const n=getCookieName(e);document.cookie=`${n}=;Max-Age=34560000;Partitioned;Secure;SameSite=Strict;Path=/;Priority=High`;await fetch(`/__cookies__`,{method:"DELETE"}).catch((()=>undefined))}_addListener(e,t){if(!this._isAvailable()){return}const n=getCookieName(e);if(window.cookieStore){const cb=e=>{const r=e.changed.find((e=>e.name===n));if(r){t(r.value)}const i=e.deleted.find((e=>e.name===n));if(i){t(null)}};const unsubscribe=()=>window.cookieStore.removeEventListener("change",cb);this.listenerUnsubscribes.set(t,unsubscribe);return window.cookieStore.addEventListener("change",cb)}let r=getDocumentCookie(n);const i=setInterval((()=>{const e=getDocumentCookie(n);if(e!==r){t(e);r=e}}),x);const unsubscribe=()=>clearInterval(i);this.listenerUnsubscribes.set(t,unsubscribe)}_removeListener(e,t){const n=this.listenerUnsubscribes.get(t);if(!n){return}n();this.listenerUnsubscribes.delete(t)}}CookiePersistence.type="COOKIE";const W=CookiePersistence;class BrowserSessionPersistence extends BrowserPersistenceClass{constructor(){super((()=>window.sessionStorage),"SESSION")}_addListener(e,t){return}_removeListener(e,t){return}}BrowserSessionPersistence.type="SESSION";const V=BrowserSessionPersistence;function _allSettled(e){return Promise.all(e.map((async e=>{try{const t=await e;return{fulfilled:true,value:t}}catch(e){return{fulfilled:false,reason:e}}})))}class Receiver{constructor(e){this.eventTarget=e;this.handlersMap={};this.boundEventHandler=this.handleEvent.bind(this)}static _getInstance(e){const t=this.receivers.find((t=>t.isListeningto(e)));if(t){return t}const n=new Receiver(e);this.receivers.push(n);return n}isListeningto(e){return this.eventTarget===e}async handleEvent(e){const t=e;const{eventId:n,eventType:r,data:i}=t.data;const s=this.handlersMap[r];if(!s?.size){return}t.ports[0].postMessage({status:"ack",eventId:n,eventType:r});const o=Array.from(s).map((async e=>e(t.origin,i)));const a=await _allSettled(o);t.ports[0].postMessage({status:"done",eventId:n,eventType:r,response:a})}_subscribe(e,t){if(Object.keys(this.handlersMap).length===0){this.eventTarget.addEventListener("message",this.boundEventHandler)}if(!this.handlersMap[e]){this.handlersMap[e]=new Set}this.handlersMap[e].add(t)}_unsubscribe(e,t){if(this.handlersMap[e]&&t){this.handlersMap[e].delete(t)}if(!t||this.handlersMap[e].size===0){delete this.handlersMap[e]}if(Object.keys(this.handlersMap).length===0){this.eventTarget.removeEventListener("message",this.boundEventHandler)}}}Receiver.receivers=[];function _generateEventId(e="",t=10){let n="";for(let e=0;e<t;e++){n+=Math.floor(Math.random()*10)}return e+n}class Sender{constructor(e){this.target=e;this.handlers=new Set}removeMessageHandler(e){if(e.messageChannel){e.messageChannel.port1.removeEventListener("message",e.onMessage);e.messageChannel.port1.close()}this.handlers.delete(e)}async _send(e,t,n=50){const r=typeof MessageChannel!=="undefined"?new MessageChannel:null;if(!r){throw new Error("connection_unavailable")}let i;let s;return new Promise(((o,a)=>{const c=_generateEventId("",20);r.port1.start();const l=setTimeout((()=>{a(new Error("unsupported_event"))}),n);s={messageChannel:r,onMessage(e){const t=e;if(t.data.eventId!==c){return}switch(t.data.status){case"ack":clearTimeout(l);i=setTimeout((()=>{a(new Error("timeout"))}),3e3);break;case"done":clearTimeout(i);o(t.data.response);break;default:clearTimeout(l);clearTimeout(i);a(new Error("invalid_response"));break}}};this.handlers.add(s);r.port1.addEventListener("message",s.onMessage);this.target.postMessage({eventType:e,eventId:c,data:t},[r.port2])})).finally((()=>{if(s){this.removeMessageHandler(s)}}))}}function _window(){return window}function _setWindowLocation(e){_window().location.href=e}function _isWorker(){return typeof _window()["WorkerGlobalScope"]!=="undefined"&&typeof _window()["importScripts"]==="function"}async function _getActiveServiceWorker(){if(!navigator?.serviceWorker){return null}try{const e=await navigator.serviceWorker.ready;return e.active}catch{return null}}function _getServiceWorkerController(){return navigator?.serviceWorker?.controller||null}function _getWorkerGlobalScope(){return _isWorker()?self:null}const q="firebaseLocalStorageDb";const G=1;const B="firebaseLocalStorage";const H="fbase_key";class DBPromise{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)}))}
2))}}function getObjectStore(e,t){return e.transaction([B],t?"readwrite":"readonly").objectStore(B)}function _deleteDatabase(){const e=indexedDB.deleteDatabase(q);return new DBPromise(e).toPromise()}function _openDatabase(){const e=indexedDB.open(q,G);return new Promise(((t,n)=>{e.addEventListener("error",(()=>{n(e.error)}));e.addEventListener("upgradeneeded",(()=>{const t=e.result;try{t.createObjectStore(B,{keyPath:H})}catch(e){n(e)}}));e.addEventListener("success",(async()=>{const n=e.result;if(!n.objectStoreNames.contains(B)){n.close();await _deleteDatabase();t(await _openDatabase())}else{t(n)}}))}))}async function _putObject(e,t,n){const r=getObjectStore(e,true).put({[H]:t,value:n});return new DBPromise(r).toPromise()}async function getObject(e,t){const n=getObjectStore(e,false).get(t);const r=await new DBPromise(n).toPromise();return r===undefined?null:r.value}function _deleteObject(e,t){const n=getObjectStore(e,true).delete(t);return new DBPromise(n).toPromise()}const j=800;const z=3;class IndexedDBLocalPersistence{constructor(){this.type="LOCAL";this.dbPromise=null;this._shouldAllowMigration=true;this.listeners={};this.localCache={};this.pollTimer=null;this.pendingWrites=0;this.receiver=null;this.sender=null;this.serviceWorkerReceiverAvailable=false;this.activeServiceWorker=null;this._workerInitializationPromise=this.initializeServiceWorkerMessaging().then((()=>{}),(()=>{}))}async _openDb(){if(this.dbPromise){return this.dbPromise}this.dbPromise=_openDatabase();this.dbPromise.catch((()=>{this.dbPromise=null}));return this.dbPromise}async _withRetries(e){let t=0;while(true){try{const t=await this._openDb();return await e(t)}catch(e){if(t++>z){throw e}if(this.dbPromise){const e=await this.dbPromise;e.close();this.dbPromise=null}}}}async initializeServiceWorkerMessaging(){return _isWorker()?this.initializeReceiver():this.initializeSender()}async initializeReceiver(){this.receiver=Receiver._getInstance(_getWorkerGlobalScope());this.receiver._subscribe("keyChanged",(async(e,t)=>{const n=await this._poll();return{keyProcessed:n.includes(t.key)}}));this.receiver._subscribe("ping",(async(e,t)=>["keyChanged"]))}async initializeSender(){this.activeServiceWorker=await _getActiveServiceWorker();if(!this.activeServiceWorker){return}this.sender=new Sender(this.activeServiceWorker);const e=await this.sender._send("ping",{},800);if(!e){return}if(e[0]?.fulfilled&&e[0]?.value.includes("keyChanged")){this.serviceWorkerReceiverAvailable=true}}async notifyServiceWorker(e){if(!this.sender||!this.activeServiceWorker||_getServiceWorkerController()!==this.activeServiceWorker){return}try{await this.sender._send("keyChanged",{key:e},this.serviceWorkerReceiverAvailable?800:50)}catch{}}async _isAvailable(){try{if(!indexedDB){return false}await this._withRetries((async e=>{await _putObject(e,L,"1");await _deleteObject(e,L)}));return true}catch{}return false}async _withPendingWrite(e){this.pendingWrites++;try{await e()}finally{this.pendingWrites--}}async _set(e,t){return this._withPendingWrite((async()=>{await this._withRetries((n=>_putObject(n,e,t)));this.localCache[e]=t;return this.notifyServiceWorker(e)}))}async _get(e){const t=await this._withRetries((t=>getObject(t,e)));this.localCache[e]=t;return t}async _remove(e){return this._withPendingWrite((async()=>{await this._withRetries((t=>_deleteObject(t,e)));delete this.localCache[e];return this.notifyServiceWorker(e)}))}async _poll(){const e=await this._withRetries((e=>{const t=getObjectStore(e,false).getAll();return new DBPromise(t).toPromise()}));if(!e){return[]}if(this.pendingWrites!==0){return[]}const t=[];const n=new Set;if(e.length!==0){for(const{fbase_key:r,value:i}of e){n.add(r);if(JSON.stringify(this.localCache[r])!==JSON.stringify(i)){this.notifyListeners(r,i);t.push(r)}}}for(const e of Object.keys(this.localCache)){if(this.localCache[e]&&!n.has(e)){this.notifyListeners(e,null);t.push(e)}}return t}notifyListeners(e,t){this.localCache[e]=t;const n=this.listeners[e];if(n){for(const e of Array.from(n)){e(t)}}}startPolling(){this.stopPolling();this.pollTimer=setInterval((async()=>this._poll()),j)}stopPolling(){if(this.pollTimer){clearInterval(this.pollTimer);this.pollTimer=null}}_addListener(e,t){if(Object.keys(this.listeners).length===0){this.startPolling()}if(!this.listeners[e]){this.listeners[e]=new Set;void this._get(e)}this.listeners[e].add(t)}_removeListener(e,t){if(this.listeners[e]){this.listeners[e].delete(t);if(this.listeners[e].size===0){delete this.listeners[e]}}if(Object.keys(this.listeners).length===0){this.stopPolling()}}}IndexedDBLocalPersistence.type="LOCAL";const K=IndexedDBLocalPersistence;function startSignInPhoneMfa(e,t){return _performApiRequest(e,"POST","/v2/accounts/mfaSignIn:start",_addTidIfNecessary(e,t))}function finalizeSignInPhoneMfa(e,t){return _performApiRequest(e,"POST","/v2/accounts/mfaSignIn:finalize",_addTidIfNecessary(e,t))}function finalizeSignInTotpMfa(e,t){return _performApiRequest(e,"POST","/v2/accounts/mfaSignIn:finalize",_addTidIfNecessary(e,t))}const $=_generateCallbackName("rcb");const Q=new Delay(3e4,6e4);class ReCaptchaLoaderImpl{constructor(){this.hostLanguage="";this.counter=0;this.librarySeparatelyLoaded=!!_window().grecaptcha?.render}load(e,t=""){_assert(isHostLanguageValid(t),e,"argument-error");
2if(this.shouldResolveImmediately(t)&&isV2(_window().grecaptcha)){return Promise.resolve(_window().grecaptcha)}return new Promise(((n,r)=>{const s=_window().setTimeout((()=>{r(_createError(e,"network-request-failed"))}),Q.get());_window()[$]=()=>{_window().clearTimeout(s);delete _window()[$];const i=_window().grecaptcha;if(!i||!isV2(i)){r(_createError(e,"internal-error"));return}const o=i.render;i.render=(e,t)=>{const n=o(e,t);this.counter++;return n};this.hostLanguage=t;n(i)};const o=`${_recaptchaV2ScriptUrl()}?${i.querystring({onload:$,render:"explicit",hl:t})}`;_loadJS(o).catch((()=>{clearTimeout(s);r(_createError(e,"internal-error"))}))}))}clearedOneInstance(){this.counter--}shouldResolveImmediately(e){return!!_window().grecaptcha?.render&&(e===this.hostLanguage||this.counter>0||this.librarySeparatelyLoaded)}}function isHostLanguageValid(e){return e.length<=6&&/^\s*[a-zA-Z0-9\-]*\s*$/.test(e)}class MockReCaptchaLoaderImpl{async load(e){return new MockReCaptcha(e)}clearedOneInstance(){}}const Y="recaptcha";const J={theme:"light",type:"image"};class RecaptchaVerifier{constructor(e,t,n={...J}){this.parameters=n;this.type=Y;this.destroyed=false;this.widgetId=null;this.tokenChangeListeners=new Set;this.renderPromise=null;this.recaptcha=null;this.auth=_castAuth(e);this.isInvisible=this.parameters.size==="invisible";_assert(typeof document!=="undefined",this.auth,"operation-not-supported-in-this-environment");const r=typeof t==="string"?document.getElementById(t):t;_assert(r,this.auth,"argument-error");this.container=r;this.parameters.callback=this.makeTokenCallback(this.parameters.callback);this._recaptchaLoader=this.auth.settings.appVerificationDisabledForTesting?new MockReCaptchaLoaderImpl:new ReCaptchaLoaderImpl;this.validateStartingState()}async verify(){this.assertNotDestroyed();const e=await this.render();const t=this.getAssertedRecaptcha();const n=t.getResponse(e);if(n){return n}return new Promise((n=>{const tokenChange=e=>{if(!e){return}this.tokenChangeListeners.delete(tokenChange);n(e)};this.tokenChangeListeners.add(tokenChange);if(this.isInvisible){t.execute(e)}}))}render(){try{this.assertNotDestroyed()}catch(e){return Promise.reject(e)}if(this.renderPromise){return this.renderPromise}this.renderPromise=this.makeRenderPromise().catch((e=>{this.renderPromise=null;throw e}));return this.renderPromise}_reset(){this.assertNotDestroyed();if(this.widgetId!==null){this.getAssertedRecaptcha().reset(this.widgetId)}}clear(){this.assertNotDestroyed();this.destroyed=true;this._recaptchaLoader.clearedOneInstance();if(!this.isInvisible){this.container.childNodes.forEach((e=>{this.container.removeChild(e)}))}}validateStartingState(){_assert(!this.parameters.sitekey,this.auth,"argument-error");_assert(this.isInvisible||!this.container.hasChildNodes(),this.auth,"argument-error");_assert(typeof document!=="undefined",this.auth,"operation-not-supported-in-this-environment")}makeTokenCallback(e){return t=>{this.tokenChangeListeners.forEach((e=>e(t)));if(typeof e==="function"){e(t)}else if(typeof e==="string"){const n=_window()[e];if(typeof n==="function"){n(t)}}}}
2assertNotDestroyed(){_assert(!this.destroyed,this.auth,"internal-error")}async makeRenderPromise(){await this.init();if(!this.widgetId){let e=this.container;if(!this.isInvisible){const t=document.createElement("div");e.appendChild(t);e=t}this.widgetId=this.getAssertedRecaptcha().render(e,this.parameters)}return this.widgetId}async init(){_assert(_isHttpOrHttps()&&!_isWorker(),this.auth,"internal-error");await domReady();this.recaptcha=await this._recaptchaLoader.load(this.auth,this.auth.languageCode||undefined);const e=await getRecaptchaParams(this.auth);_assert(e,this.auth,"internal-error");this.parameters.sitekey=e}getAssertedRecaptcha(){_assert(this.recaptcha,this.auth,"internal-error");return this.recaptcha}}function domReady(){let e=null;return new Promise((t=>{if(document.readyState==="complete"){t();return}e=()=>t();window.addEventListener("load",e)})).catch((t=>{if(e){window.removeEventListener("load",e)}throw t}))}class ConfirmationResultImpl{constructor(e,t){this.verificationId=e;this.onConfirmation=t}confirm(e){const t=PhoneAuthCredential._fromVerification(this.verificationId,e);return this.onConfirmation(t)}}async function signInWithPhoneNumber(e,t,n){if(r._isFirebaseServerApp(e.app)){return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(e))}const s=_castAuth(e);const o=await _verifyPhoneNumber(s,t,i.getModularInstance(n));return new ConfirmationResultImpl(o,(e=>signInWithCredential(s,e)))}async function linkWithPhoneNumber(e,t,n){const r=i.getModularInstance(e);await _assertLinkedStatus(false,r,"phone");const s=await _verifyPhoneNumber(r.auth,t,i.getModularInstance(n));return new ConfirmationResultImpl(s,(e=>linkWithCredential(r,e)))}async function reauthenticateWithPhoneNumber(e,t,n){const s=i.getModularInstance(e);if(r._isFirebaseServerApp(s.auth.app)){return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(s.auth))}const o=await _verifyPhoneNumber(s.auth,t,i.getModularInstance(n));return new ConfirmationResultImpl(o,(e=>reauthenticateWithCredential(s,e)))}async function _verifyPhoneNumber(e,t,n){if(!e._getRecaptchaConfig()){try{await _initializeRecaptchaConfig(e)}catch(e){console.log("Failed to initialize reCAPTCHA Enterprise config. Triggering the reCAPTCHA v2 verification.")}}try{let r;if(typeof t==="string"){r={phoneNumber:t}}else{r=t}if("session"in r){const t=r.session;if("phoneNumber"in r){_assert(t.type==="enroll",e,"internal-error");const i={idToken:t.credential,phoneEnrollmentInfo:{phoneNumber:r.phoneNumber,clientType:"CLIENT_TYPE_WEB"}};const startEnrollPhoneMfaActionCallback=async(e,t)=>{if(t.phoneEnrollmentInfo.captchaResponse===b){_assert(n?.type===Y,e,"argument-error");const r=await injectRecaptchaV2Token(e,t,n);return startEnrollPhoneMfa(e,r)}return startEnrollPhoneMfa(e,t)};const s=handleRecaptchaFlow(e,i,"mfaSmsEnrollment",startEnrollPhoneMfaActionCallback,"PHONE_PROVIDER");const o=await s.catch((e=>Promise.reject(e)));return o.phoneSessionInfo.sessionInfo}else{_assert(t.type==="signin",e,"internal-error");const i=r.multiFactorHint?.uid||r.multiFactorUid;_assert(i,e,"missing-multi-factor-info");const s={mfaPendingCredential:t.credential,mfaEnrollmentId:i,phoneSignInInfo:{clientType:"CLIENT_TYPE_WEB"}};const startSignInPhoneMfaActionCallback=async(e,t)=>{if(t.phoneSignInInfo.captchaResponse===b){_assert(n?.type===Y,e,"argument-error");const r=await injectRecaptchaV2Token(e,t,n);return startSignInPhoneMfa(e,r)}return startSignInPhoneMfa(e,t)};const o=handleRecaptchaFlow(e,s,"mfaSmsSignIn",startSignInPhoneMfaActionCallback,"PHONE_PROVIDER");const a=await o.catch((e=>Promise.reject(e)));return a.phoneResponseInfo.sessionInfo}}else{const t={phoneNumber:r.phoneNumber,clientType:"CLIENT_TYPE_WEB"};const sendPhoneVerificationCodeActionCallback=async(e,t)=>{if(t.captchaResponse===b){_assert(n?.type===Y,e,"argument-error");const r=await injectRecaptchaV2Token(e,t,n);return sendPhoneVerificationCode(e,r)}return sendPhoneVerificationCode(e,t)};const i=handleRecaptchaFlow(e,t,"sendVerificationCode",sendPhoneVerificationCodeActionCallback,"PHONE_PROVIDER");const s=await i.catch((e=>Promise.reject(e)));return s.sessionInfo}}finally{n?._reset()}}async function updatePhoneNumber(e,t){const n=i.getModularInstance(e);if(r._isFirebaseServerApp(n.auth.app)){return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(n.auth))}await _link$1(n,t)}async function injectRecaptchaV2Token(e,t,n){_assert(n.type===Y,e,"argument-error");const r=await n.verify();_assert(typeof r==="string",e,"argument-error");const i={...t};if("phoneEnrollmentInfo"in i){const e=i.phoneEnrollmentInfo.phoneNumber;const t=i.phoneEnrollmentInfo.captchaResponse;const n=i.phoneEnrollmentInfo.clientType;const s=i.phoneEnrollmentInfo.recaptchaVersion;Object.assign(i,{phoneEnrollmentInfo:{phoneNumber:e,recaptchaToken:r,captchaResponse:t,clientType:n,recaptchaVersion:s}});return i}else if("phoneSignInInfo"in i){const e=i.phoneSignInInfo.captchaResponse;const t=i.phoneSignInInfo.clientType;const n=i.phoneSignInInfo.recaptchaVersion;Object.assign(i,{phoneSignInInfo:{recaptchaToken:r,captchaResponse:e,clientType:t,recaptchaVersion:n}});return i}else{Object.assign(i,{recaptchaToken:r});return i}}class PhoneAuthProvider{constructor(e){this.providerId=PhoneAuthProvider.PROVIDER_ID;this.auth=_castAuth(e)}verifyPhoneNumber(e,t){return _verifyPhoneNumber(this.auth,e,i.getModularInstance(t))}static credential(e,t){return PhoneAuthCredential._fromVerification(e,t)}static credentialFromResult(e){const t=e;return PhoneAuthProvider.credentialFromTaggedObject(t)}static credentialFromError(e){return PhoneAuthProvider.credentialFromTaggedObject(e.customData||{})}
2static credentialFromTaggedObject({_tokenResponse:e}){if(!e){return null}const{phoneNumber:t,temporaryProof:n}=e;if(t&&n){return PhoneAuthCredential._fromTokenResponse(t,n)}return null}}PhoneAuthProvider.PROVIDER_ID="phone";PhoneAuthProvider.PHONE_SIGN_IN_METHOD="phone";function _withDefaultResolver(e,t){if(t){return _getInstance(t)}_assert(e._popupRedirectResolver,e,"argument-error");return e._popupRedirectResolver}class IdpCredential extends AuthCredential{constructor(e){super("custom","custom");this.params=e}_getIdTokenResponse(e){return signInWithIdp(e,this._buildIdpRequest())}_linkToIdToken(e,t){return signInWithIdp(e,this._buildIdpRequest(t))}_getReauthenticationResolver(e){return signInWithIdp(e,this._buildIdpRequest())}_buildIdpRequest(e){const t={requestUri:this.params.requestUri,sessionId:this.params.sessionId,postBody:this.params.postBody,tenantId:this.params.tenantId,pendingToken:this.params.pendingToken,returnSecureToken:true,returnIdpCredential:true};if(e){t.idToken=e}return t}}function _signIn(e){return _signInWithCredential(e.auth,new IdpCredential(e),e.bypassAuthState)}function _reauth(e){const{auth:t,user:n}=e;_assert(n,t,"internal-error");return _reauthenticate(n,new IdpCredential(e),e.bypassAuthState)}async function _link(e){const{auth:t,user:n}=e;_assert(n,t,"internal-error");return _link$1(n,new IdpCredential(e),e.bypassAuthState)}class AbstractPopupRedirectOperation{constructor(e,t,n,r,i=false){this.auth=e;this.resolver=n;this.user=r;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){const{urlResponse:t,sessionId:n,postBody:r,tenantId:i,error:s,type:o}=e;if(s){this.reject(s);return}const a={auth:this.auth,requestUri:t,sessionId:n,tenantId:i||undefined,postBody:r||undefined,user:this.user,bypassAuthState:this.bypassAuthState};try{this.resolve(await this.getIdpTask(o)(a))}catch(e){this.reject(e)}}onError(e){this.reject(e)}getIdpTask(e){switch(e){case"signInViaPopup":case"signInViaRedirect":return _signIn;case"linkViaPopup":case"linkViaRedirect":return _link;case"reauthViaPopup":case"reauthViaRedirect":return _reauth;default:_fail(this.auth,"internal-error")}}resolve(e){debugAssert(this.pendingPromise,"Pending promise was never set");this.pendingPromise.resolve(e);this.unregisterAndCleanUp()}reject(e){debugAssert(this.pendingPromise,"Pending promise was never set");this.pendingPromise.reject(e);this.unregisterAndCleanUp()}unregisterAndCleanUp(){if(this.eventManager){this.eventManager.unregisterConsumer(this)}this.pendingPromise=null;this.cleanUp()}}const X=new Delay(2e3,1e4);async function signInWithPopup(e,t,n){if(r._isFirebaseServerApp(e.app)){return Promise.reject(_createError(e,"operation-not-supported-in-this-environment"))}const i=_castAuth(e);_assertInstanceOf(e,t,FederatedAuthProvider);const s=_withDefaultResolver(i,n);const o=new PopupOperation(i,"signInViaPopup",t,s);return o.executeNotNull()}async function reauthenticateWithPopup(e,t,n){const s=i.getModularInstance(e);if(r._isFirebaseServerApp(s.auth.app)){return Promise.reject(_createError(s.auth,"operation-not-supported-in-this-environment"))}_assertInstanceOf(s.auth,t,FederatedAuthProvider);const o=_withDefaultResolver(s.auth,n);const a=new PopupOperation(s.auth,"reauthViaPopup",t,o,s);return a.executeNotNull()}async function linkWithPopup(e,t,n){const r=i.getModularInstance(e);_assertInstanceOf(r.auth,t,FederatedAuthProvider);const s=_withDefaultResolver(r.auth,n);const o=new PopupOperation(r.auth,"linkViaPopup",t,s,r);return o.executeNotNull()}class PopupOperation extends AbstractPopupRedirectOperation{constructor(e,t,n,r,i){super(e,t,r,i);this.provider=n;this.authWindow=null;this.pollId=null;if(PopupOperation.currentPopupAction){PopupOperation.currentPopupAction.cancel()}PopupOperation.currentPopupAction=this}async executeNotNull(){const e=await this.execute();_assert(e,this.auth,"internal-error");return e}async onExecution(){debugAssert(this.filter.length===1,"Popup operations only handle one event");const e=_generateEventId();this.authWindow=await this.resolver._openPopup(this.auth,this.provider,this.filter[0],e);this.authWindow.associatedEvent=e;this.resolver._originValidation(this.auth).catch((e=>{this.reject(e)}));this.resolver._isIframeWebStorageSupported(this.auth,(e=>{if(!e){this.reject(_createError(this.auth,"web-storage-unsupported"))}}));this.pollUserCancellation()}get eventId(){return this.authWindow?.associatedEvent||null}cancel(){this.reject(_createError(this.auth,"cancelled-popup-request"))}cleanUp(){if(this.authWindow){this.authWindow.close()}if(this.pollId){window.clearTimeout(this.pollId)}this.authWindow=null;this.pollId=null;PopupOperation.currentPopupAction=null}pollUserCancellation(){const poll=()=>{if(this.authWindow?.window?.closed){this.pollId=window.setTimeout((()=>{this.pollId=null;this.reject(_createError(this.auth,"popup-closed-by-user"))}),8e3);return}this.pollId=window.setTimeout(poll,X.get())};poll()}}PopupOperation.currentPopupAction=null;const Z="pendingRedirect";const ee=new Map;class RedirectAction extends AbstractPopupRedirectOperation{constructor(e,t,n=false){super(e,["signInViaRedirect","linkViaRedirect","reauthViaRedirect","unknown"],t,undefined,n);this.eventId=null}async execute(){let e=ee.get(this.auth._key());if(!e){try{const t=await _getAndClearPendingRedirectStatus(this.resolver,this.auth);const n=t?await super.execute():null;e=()=>Promise.resolve(n)}catch(t){e=()=>Promise.reject(t)}ee.set(this.auth._key(),e)}if(!this.bypassAuthState){ee.set(this.auth._key(),(()=>Promise.resolve(null)))}return e()}
2async onAuthEvent(e){if(e.type==="signInViaRedirect"){return super.onAuthEvent(e)}else if(e.type==="unknown"){this.resolve(null);return}if(e.eventId){const t=await this.auth._redirectUserForId(e.eventId);if(t){this.user=t;return super.onAuthEvent(e)}else{this.resolve(null)}}}async onExecution(){}cleanUp(){}}async function _getAndClearPendingRedirectStatus(e,t){const n=pendingRedirectKey(t);const r=resolverPersistence(e);if(!await r._isAvailable()){return false}const i=await r._get(n)==="true";await r._remove(n);return i}async function _setPendingRedirectStatus(e,t){return resolverPersistence(e)._set(pendingRedirectKey(t),"true")}function _clearRedirectOutcomes(){ee.clear()}function _overrideRedirectResult(e,t){ee.set(e._key(),t)}function resolverPersistence(e){return _getInstance(e._redirectPersistence)}function pendingRedirectKey(e){return _persistenceKeyName(Z,e.config.apiKey,e.name)}function signInWithRedirect(e,t,n){return _signInWithRedirect(e,t,n)}async function _signInWithRedirect(e,t,n){if(r._isFirebaseServerApp(e.app)){return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(e))}const i=_castAuth(e);_assertInstanceOf(e,t,FederatedAuthProvider);await i._initializationPromise;const s=_withDefaultResolver(i,n);await _setPendingRedirectStatus(s,i);return s._openRedirect(i,t,"signInViaRedirect")}function reauthenticateWithRedirect(e,t,n){return _reauthenticateWithRedirect(e,t,n)}async function _reauthenticateWithRedirect(e,t,n){const s=i.getModularInstance(e);_assertInstanceOf(s.auth,t,FederatedAuthProvider);if(r._isFirebaseServerApp(s.auth.app)){return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(s.auth))}await s.auth._initializationPromise;const o=_withDefaultResolver(s.auth,n);await _setPendingRedirectStatus(o,s.auth);const a=await prepareUserForRedirect(s);return o._openRedirect(s.auth,t,"reauthViaRedirect",a)}function linkWithRedirect(e,t,n){return _linkWithRedirect(e,t,n)}async function _linkWithRedirect(e,t,n){const r=i.getModularInstance(e);_assertInstanceOf(r.auth,t,FederatedAuthProvider);await r.auth._initializationPromise;const s=_withDefaultResolver(r.auth,n);await _assertLinkedStatus(false,r,t.providerId);await _setPendingRedirectStatus(s,r.auth);const o=await prepareUserForRedirect(r);return s._openRedirect(r.auth,t,"linkViaRedirect",o)}async function getRedirectResult(e,t){await _castAuth(e)._initializationPromise;return _getRedirectResult(e,t,false)}async function _getRedirectResult(e,t,n=false){if(r._isFirebaseServerApp(e.app)){return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(e))}const i=_castAuth(e);const s=_withDefaultResolver(i,t);const o=new RedirectAction(i,s,n);const a=await o.execute();if(a&&!n){delete a.user._redirectEventId;await i._persistUserIfCurrent(a.user);await i._setRedirectUser(null,t)}return a}async function prepareUserForRedirect(e){const t=_generateEventId(`${e.uid}:::`);e._redirectEventId=t;await e.auth._setRedirectUser(e);await e.auth._persistUserIfCurrent(e);return t}const te=10*60*1e3;class AuthEventManager{constructor(e){this.auth=e;this.cachedEventUids=new Set;this.consumers=new Set;this.queuedRedirectEvent=null;this.hasHandledPotentialRedirect=false;this.lastProcessedEventTime=Date.now()}registerConsumer(e){this.consumers.add(e);if(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 false}let t=false;this.consumers.forEach((n=>{if(this.isEventForConsumer(e,n)){t=true;this.sendToConsumer(e,n);this.saveEventToCache(e)}}));if(this.hasHandledPotentialRedirect||!isRedirectEvent(e)){return t}this.hasHandledPotentialRedirect=true;if(!t){this.queuedRedirectEvent=e;t=true}return t}sendToConsumer(e,t){if(e.error&&!isNullRedirectEvent(e)){const n=e.error.code?.split("auth/")[1]||"internal-error";t.onError(_createError(this.auth,n))}else{t.onAuthEvent(e)}}isEventForConsumer(e,t){const n=t.eventId===null||!!e.eventId&&e.eventId===t.eventId;return t.filter.includes(e.type)&&n}hasEventBeenHandled(e){if(Date.now()-this.lastProcessedEventTime>=te){this.cachedEventUids.clear()}return this.cachedEventUids.has(eventUid(e))}saveEventToCache(e){this.cachedEventUids.add(eventUid(e));
2this.lastProcessedEventTime=Date.now()}}function eventUid(e){return[e.type,e.eventId,e.sessionId,e.tenantId].filter((e=>e)).join("-")}function isNullRedirectEvent({type:e,error:t}){return e==="unknown"&&t?.code===`auth/${"no-auth-event"}`}function isRedirectEvent(e){switch(e.type){case"signInViaRedirect":case"linkViaRedirect":case"reauthViaRedirect":return true;case"unknown":return isNullRedirectEvent(e);default:return false}}async function _getProjectConfig(e,t={}){return _performApiRequest(e,"GET","/v1/projects",t)}const ne=/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;const re=/^https?/;async function _validateOrigin(e){if(e.config.emulator){return}const{authorizedDomains:t}=await _getProjectConfig(e);for(const e of t){try{if(matchDomain(e)){return}}catch{}}_fail(e,"unauthorized-domain")}function matchDomain(e){const t=_getCurrentUrl();const{protocol:n,hostname:r}=new URL(t);if(e.startsWith("chrome-extension://")){const i=new URL(e);if(i.hostname===""&&r===""){return n==="chrome-extension:"&&e.replace("chrome-extension://","")===t.replace("chrome-extension://","")}return n==="chrome-extension:"&&i.hostname===r}if(!re.test(n)){return false}if(ne.test(e)){return r===e}const i=e.replace(/\./g,"\\.");const s=new RegExp("^(.+\\."+i+"|"+i+")$","i");return s.test(r)}const ie=new Delay(3e4,6e4);function resetUnloadedGapiModules(){const e=_window().___jsl;if(e?.H){for(const t of Object.keys(e.H)){e.H[t].r=e.H[t].r||[];e.H[t].L=e.H[t].L||[];e.H[t].r=[...e.H[t].L];if(e.CP){for(let t=0;t<e.CP.length;t++){e.CP[t]=null}}}}}function loadGapi(e){return new Promise(((t,n)=>{function loadGapiIframe(){resetUnloadedGapiModules();gapi.load("gapi.iframes",{callback:()=>{t(gapi.iframes.getContext())},ontimeout:()=>{resetUnloadedGapiModules();n(_createError(e,"network-request-failed"))},timeout:ie.get()})}if(_window().gapi?.iframes?.Iframe){t(gapi.iframes.getContext())}else if(!!_window().gapi?.load){loadGapiIframe()}else{const t=_generateCallbackName("iframefcb");_window()[t]=()=>{if(!!gapi.load){loadGapiIframe()}else{n(_createError(e,"network-request-failed"))}};return _loadJS(`${_gapiScriptUrl()}?onload=${t}`).catch((e=>n(e)))}})).catch((e=>{se=null;throw e}))}let se=null;function _loadGapi(e){se=se||loadGapi(e);return se}const oe=new Delay(5e3,15e3);const ae="__/auth/iframe";const ce="emulator/auth/iframe";const le={style:{position:"absolute",top:"-100px",width:"1px",height:"1px"},"aria-hidden":"true",tabindex:"-1"};const ue=new Map([["identitytoolkit.googleapis.com","p"],["staging-identitytoolkit.sandbox.googleapis.com","s"],["test-identitytoolkit.sandbox.googleapis.com","t"]]);function getIframeUrl(e){const t=e.config;_assert(t.authDomain,e,"auth-domain-config-required");const n=t.emulator?_emulatorUrl(t,ce):`https://${e.config.authDomain}/${ae}`;const s={apiKey:t.apiKey,appName:e.name,v:r.SDK_VERSION};const o=ue.get(e.config.apiHost);if(o){s.eid=o}const a=e._getFrameworks();if(a.length){s.fw=a.join(",")}return`${n}?${i.querystring(s).slice(1)}`}async function _openIframe(e){const t=await _loadGapi(e);const n=_window().gapi;_assert(n,e,"internal-error");return t.open({where:document.body,url:getIframeUrl(e),messageHandlersFilter:n.iframes.CROSS_ORIGIN_IFRAMES_FILTER,attributes:le,dontclear:true},(t=>new Promise((async(n,r)=>{await t.restyle({setHideOnLeave:false});const i=_createError(e,"network-request-failed");const s=_window().setTimeout((()=>{r(i)}),oe.get());function clearTimerAndResolve(){_window().clearTimeout(s);n(t)}t.ping(clearTimerAndResolve).then(clearTimerAndResolve,(()=>{r(i)}))}))))}const de={location:"yes",resizable:"yes",statusbar:"yes",toolbar:"no"};const he=500;const pe=600;const fe="_blank";const me="http://localhost";class AuthPopup{constructor(e){this.window=e;this.associatedEvent=null}close(){if(this.window){try{this.window.close()}catch(e){}}}}function _open(e,t,n,r=he,s=pe){const o=Math.max((window.screen.availHeight-s)/2,0).toString();const a=Math.max((window.screen.availWidth-r)/2,0).toString();let c="";const l={...de,width:r.toString(),height:s.toString(),top:o,left:a};const u=i.getUA().toLowerCase();if(n){c=_isChromeIOS(u)?fe:n}if(_isFirefox(u)){t=t||me;l.scrollbars="yes"}const d=Object.entries(l).reduce(((e,[t,n])=>`${e}${t}=${n},`),"");if(_isIOSStandalone(u)&&c!=="_self"){openAsNewWindowIOS(t||"",c);return new AuthPopup(null)}const h=window.open(t||"",c,d);_assert(h,e,"popup-blocked");try{h.focus()}catch(e){}return new AuthPopup(h)}function openAsNewWindowIOS(e,t){const n=document.createElement("a");n.href=e;n.target=t;const r=document.createEvent("MouseEvent");r.initMouseEvent("click",true,true,window,1,0,0,0,0,false,false,false,false,1,null);n.dispatchEvent(r)}const ge="__/auth/handler";const _e="emulator/auth/handler";const ve=encodeURIComponent("fac");async function _getRedirectUrl(e,t,n,s,o,a){_assert(e.config.authDomain,e,"auth-domain-config-required");
2_assert(e.config.apiKey,e,"invalid-api-key");const c={apiKey:e.config.apiKey,appName:e.name,authType:n,redirectUrl:s,v:r.SDK_VERSION,eventId:o};if(t instanceof FederatedAuthProvider){t.setDefaultLanguage(e.languageCode);c.providerId=t.providerId||"";if(!i.isEmpty(t.getCustomParameters())){c.customParameters=JSON.stringify(t.getCustomParameters())}for(const[e,t]of Object.entries(a||{})){c[e]=t}}if(t instanceof BaseOAuthProvider){const e=t.getScopes().filter((e=>e!==""));if(e.length>0){c.scopes=e.join(",")}}if(e.tenantId){c.tid=e.tenantId}const l=c;for(const e of Object.keys(l)){if(l[e]===undefined){delete l[e]}}const u=await e._getAppCheckToken();const d=u?`#${ve}=${encodeURIComponent(u)}`:"";return`${getHandlerBase(e)}?${i.querystring(l).slice(1)}${d}`}function getHandlerBase({config:e}){if(!e.emulator){return`https://${e.authDomain}/${ge}`}return _emulatorUrl(e,_e)}const ye="webStorageSupport";class BrowserPopupRedirectResolver{constructor(){this.eventManagers={};this.iframes={};this.originValidationPromises={};this._redirectPersistence=V;this._completeRedirectFn=_getRedirectResult;this._overrideRedirectResult=_overrideRedirectResult}async _openPopup(e,t,n,r){debugAssert(this.eventManagers[e._key()]?.manager,"_initialize() not called before _openPopup()");const i=await _getRedirectUrl(e,t,n,_getCurrentUrl(),r);return _open(e,i,_generateEventId())}async _openRedirect(e,t,n,r){await this._originValidation(e);const i=await _getRedirectUrl(e,t,n,_getCurrentUrl(),r);_setWindowLocation(i);return new Promise((()=>{}))}_initialize(e){const t=e._key();if(this.eventManagers[t]){const{manager:e,promise:n}=this.eventManagers[t];if(e){return Promise.resolve(e)}else{debugAssert(n,"If manager is not set, promise should be");return n}}const n=this.initAndGetManager(e);this.eventManagers[t]={promise:n};n.catch((()=>{delete this.eventManagers[t]}));return n}async initAndGetManager(e){const t=await _openIframe(e);const n=new AuthEventManager(e);t.register("authEvent",(t=>{_assert(t?.authEvent,e,"invalid-auth-event");const r=n.onEvent(t.authEvent);return{status:r?"ACK":"ERROR"}}),gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER);this.eventManagers[e._key()]={manager:n};this.iframes[e._key()]=t;return n}_isIframeWebStorageSupported(e,t){const n=this.iframes[e._key()];n.send(ye,{type:ye},(n=>{const r=n?.[0]?.[ye];if(r!==undefined){t(!!r)}_fail(e,"internal-error")}),gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER)}_originValidation(e){const t=e._key();if(!this.originValidationPromises[t]){this.originValidationPromises[t]=_validateOrigin(e)}return this.originValidationPromises[t]}get _shouldInitProactively(){return _isMobileBrowser()||_isSafari()||_isIOS()}}const Ie=BrowserPopupRedirectResolver;class MultiFactorAssertionImpl{constructor(e){this.factorId=e}_process(e,t,n){switch(t.type){case"enroll":return this._finalizeEnroll(e,t.credential,n);case"signin":return this._finalizeSignIn(e,t.credential);default:return debugFail("unexpected MultiFactorSessionType")}}}class PhoneMultiFactorAssertionImpl extends MultiFactorAssertionImpl{constructor(e){super("phone");this.credential=e}static _fromCredential(e){return new PhoneMultiFactorAssertionImpl(e)}_finalizeEnroll(e,t,n){return finalizeEnrollPhoneMfa(e,{idToken:t,displayName:n,phoneVerificationInfo:this.credential._makeVerificationRequest()})}_finalizeSignIn(e,t){return finalizeSignInPhoneMfa(e,{mfaPendingCredential:t,phoneVerificationInfo:this.credential._makeVerificationRequest()})}}class PhoneMultiFactorGenerator{constructor(){}static assertion(e){return PhoneMultiFactorAssertionImpl._fromCredential(e)}}PhoneMultiFactorGenerator.FACTOR_ID="phone";class TotpMultiFactorGenerator{static assertionForEnrollment(e,t){return TotpMultiFactorAssertionImpl._fromSecret(e,t)}static assertionForSignIn(e,t){return TotpMultiFactorAssertionImpl._fromEnrollmentId(e,t)}static async generateSecret(e){const t=e;_assert(typeof t.user?.auth!=="undefined","internal-error");const n=await startEnrollTotpMfa(t.user.auth,{idToken:t.credential,totpEnrollmentInfo:{}});return TotpSecret._fromStartTotpMfaEnrollmentResponse(n,t.user.auth)}}TotpMultiFactorGenerator.FACTOR_ID="totp";class TotpMultiFactorAssertionImpl extends MultiFactorAssertionImpl{constructor(e,t,n){super("totp");this.otp=e;this.enrollmentId=t;this.secret=n}static _fromSecret(e,t){return new TotpMultiFactorAssertionImpl(t,undefined,e)}static _fromEnrollmentId(e,t){return new TotpMultiFactorAssertionImpl(t,e)}async _finalizeEnroll(e,t,n){_assert(typeof this.secret!=="undefined",e,"argument-error");return finalizeEnrollTotpMfa(e,{idToken:t,displayName:n,totpVerificationInfo:this.secret._makeTotpVerificationInfo(this.otp)})}async _finalizeSignIn(e,t){_assert(this.enrollmentId!==undefined&&this.otp!==undefined,e,"argument-error");const n={verificationCode:this.otp};return finalizeSignInTotpMfa(e,{mfaPendingCredential:t,mfaEnrollmentId:this.enrollmentId,totpVerificationInfo:n})}}class TotpSecret{constructor(e,t,n,r,i,s,o){this.sessionInfo=s;this.auth=o;this.secretKey=e;this.hashingAlgorithm=t;this.codeLength=n;
2this.codeIntervalSeconds=r;this.enrollmentCompletionDeadline=i}static _fromStartTotpMfaEnrollmentResponse(e,t){return new TotpSecret(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 n=false;if(_isEmptyString(e)||_isEmptyString(t)){n=true}if(n){if(_isEmptyString(e)){e=this.auth.currentUser?.email||"unknownuser"}if(_isEmptyString(t)){t=this.auth.name}}return`otpauth://totp/${t}:${e}?secret=${this.secretKey}&issuer=${t}&algorithm=${this.hashingAlgorithm}&digits=${this.codeLength}`}}function _isEmptyString(e){return typeof e==="undefined"||e?.length===0}var Ce="@firebase/auth";var we="1.13.2";class AuthInterop{constructor(e){this.auth=e;this.internalListeners=new Map}getUid(){this.assertAuthConfigured();return this.auth.currentUser?.uid||null}async getToken(e){this.assertAuthConfigured();await this.auth._initializationPromise;if(!this.auth.currentUser){return null}const t=await this.auth.currentUser.getIdToken(e);return{accessToken:t}}addAuthTokenListener(e){this.assertAuthConfigured();if(this.internalListeners.has(e)){return}const t=this.auth.onIdTokenChanged((t=>{e(t?.stsTokenManager.accessToken||null)}));this.internalListeners.set(e,t);this.updateProactiveRefresh()}removeAuthTokenListener(e){this.assertAuthConfigured();const t=this.internalListeners.get(e);if(!t){return}this.internalListeners.delete(e);t();this.updateProactiveRefresh()}assertAuthConfigured(){_assert(this.auth._initializationPromise,"dependent-sdk-initialized-before-auth")}updateProactiveRefresh(){if(this.internalListeners.size>0){this.auth._startProactiveRefresh()}else{this.auth._stopProactiveRefresh()}}}function getVersionForPlatform(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 undefined}}function registerAuth(e){r._registerComponent(new o.Component("auth",((t,{options:n})=>{const r=t.getProvider("app").getImmediate();const i=t.getProvider("heartbeat");const s=t.getProvider("app-check-internal");const{apiKey:o,authDomain:a}=r.options;_assert(o&&!o.includes(":"),"invalid-api-key",{appName:r.name});const c={apiKey:o,authDomain:a,clientPlatform:e,apiHost:"identitytoolkit.googleapis.com",tokenApiHost:"securetoken.googleapis.com",apiScheme:"https",sdkClientVersion:_getClientVersion(e)};const l=new AuthImpl(r,i,s,c);_initializeAuthInstance(l,n);return l}),"PUBLIC").setInstantiationMode("EXPLICIT").setInstanceCreatedCallback(((e,t,n)=>{const r=e.getProvider("auth-internal");r.initialize()})));r._registerComponent(new o.Component("auth-internal",(e=>{const t=_castAuth(e.getProvider("auth").getImmediate());return(e=>new AuthInterop(e))(t)}),"PRIVATE").setInstantiationMode("EXPLICIT"));r.registerVersion(Ce,we,getVersionForPlatform(e));r.registerVersion(Ce,we,"cjs2020")}const Ee=5*60;const Te=i.getExperimentalSetting("authIdTokenMaxAge")||Ee;let Pe=null;const mintCookieFactory=e=>async t=>{const n=t&&await t.getIdTokenResult();const r=n&&((new Date).getTime()-Date.parse(n.issuedAtTime))/1e3;if(r&&r>Te){return}const i=n?.token;if(Pe===i){return}Pe=i;await fetch(e,{method:i?"POST":"DELETE",headers:i?{Authorization:`Bearer ${i}`}:{}})};function getAuth(e=r.getApp()){const t=r._getProvider(e,"auth");if(t.isInitialized()){return t.getImmediate()}const n=initializeAuth(e,{popupRedirectResolver:Ie,persistence:[K,U,V]});const s=i.getExperimentalSetting("authTokenSyncURL");if(s&&typeof isSecureContext==="boolean"&&isSecureContext){const e=new URL(s,location.origin);if(location.origin===e.origin){const t=mintCookieFactory(e.toString());beforeAuthStateChanged(n,t,(()=>t(n.currentUser)));onIdTokenChanged(n,(e=>t(e)))}}const o=i.getDefaultEmulatorHost("auth");if(o){connectAuthEmulator(n,`http://${o}`)}return n}function getScriptParentElement(){return document.getElementsByTagName("head")?.[0]??document}
2_setExternalJSProvider({loadJS(e){return new Promise(((t,n)=>{const r=document.createElement("script");r.setAttribute("src",e);r.onload=t;r.onerror=e=>{const t=_createError("internal-error");t.customData=e;n(t)};r.type="text/javascript";r.charset="UTF-8";getScriptParentElement().appendChild(r)}))},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="});registerAuth("Browser");t.AUTH_ERROR_CODES_MAP_DO_NOT_USE_INTERNALLY=m;t.ActionCodeOperation=d;t.ActionCodeURL=ActionCodeURL;t.AuthCredential=AuthCredential;t.AuthEventManager=AuthEventManager;t.AuthImpl=AuthImpl;t.AuthPopup=AuthPopup;t.EmailAuthCredential=EmailAuthCredential;t.EmailAuthProvider=EmailAuthProvider;t.FacebookAuthProvider=FacebookAuthProvider;t.FactorId=a;t.FetchProvider=FetchProvider;t.GithubAuthProvider=GithubAuthProvider;t.GoogleAuthProvider=GoogleAuthProvider;t.OAuthCredential=OAuthCredential;t.OAuthProvider=OAuthProvider;t.OperationType=u;t.PhoneAuthCredential=PhoneAuthCredential;t.PhoneAuthProvider=PhoneAuthProvider;t.PhoneMultiFactorGenerator=PhoneMultiFactorGenerator;t.ProviderId=c;t.RecaptchaVerifier=RecaptchaVerifier;t.SAMLAuthCredential=SAMLAuthCredential;t.SAMLAuthProvider=SAMLAuthProvider;t.SignInMethod=l;t.TotpMultiFactorGenerator=TotpMultiFactorGenerator;t.TotpSecret=TotpSecret;t.TwitterAuthProvider=TwitterAuthProvider;t.UserImpl=UserImpl;t._assert=_assert;t._castAuth=_castAuth;t._clearRedirectOutcomes=_clearRedirectOutcomes;t._createError=_createError;t._fail=_fail;t._generateEventId=_generateEventId;t._getClientVersion=_getClientVersion;t._getInstance=_getInstance;t._getProjectConfig=_getProjectConfig;t._getRedirectResult=_getRedirectResult;t._getRedirectUrl=_getRedirectUrl;t._isAndroid=_isAndroid;t._isIOS=_isIOS;t._isIOS7Or8=_isIOS7Or8;t._overrideRedirectResult=_overrideRedirectResult;t._persistenceKeyName=_persistenceKeyName;t.applyActionCode=applyActionCode;t.beforeAuthStateChanged=beforeAuthStateChanged;t.browserCookiePersistence=W;t.browserLocalPersistence=U;t.browserPopupRedirectResolver=Ie;t.browserSessionPersistence=V;t.checkActionCode=checkActionCode;t.confirmPasswordReset=confirmPasswordReset;t.connectAuthEmulator=connectAuthEmulator;t.createUserWithEmailAndPassword=createUserWithEmailAndPassword;t.debugAssert=debugAssert;t.debugErrorMap=h;t.deleteUser=deleteUser;t.fetchSignInMethodsForEmail=fetchSignInMethodsForEmail;t.getAdditionalUserInfo=getAdditionalUserInfo;t.getAuth=getAuth;t.getIdToken=getIdToken;t.getIdTokenResult=getIdTokenResult;t.getMultiFactorResolver=getMultiFactorResolver;t.getRedirectResult=getRedirectResult;t.inMemoryPersistence=C;t.indexedDBLocalPersistence=K;t.initializeAuth=initializeAuth;t.initializeRecaptchaConfig=initializeRecaptchaConfig;t.isSignInWithEmailLink=isSignInWithEmailLink;t.linkWithCredential=linkWithCredential;t.linkWithPhoneNumber=linkWithPhoneNumber;t.linkWithPopup=linkWithPopup;t.linkWithRedirect=linkWithRedirect;t.multiFactor=multiFactor;t.onAuthStateChanged=onAuthStateChanged;t.onIdTokenChanged=onIdTokenChanged;t.parseActionCodeURL=parseActionCodeURL;t.prodErrorMap=p;t.reauthenticateWithCredential=reauthenticateWithCredential;t.reauthenticateWithPhoneNumber=reauthenticateWithPhoneNumber;t.reauthenticateWithPopup=reauthenticateWithPopup;t.reauthenticateWithRedirect=reauthenticateWithRedirect;t.reload=reload;t.revokeAccessToken=revokeAccessToken;t.sendEmailVerification=sendEmailVerification;t.sendPasswordResetEmail=sendPasswordResetEmail;t.sendSignInLinkToEmail=sendSignInLinkToEmail;t.setPersistence=setPersistence;t.signInAnonymously=signInAnonymously;t.signInWithCredential=signInWithCredential;t.signInWithCustomToken=signInWithCustomToken;t.signInWithEmailAndPassword=signInWithEmailAndPassword;t.signInWithEmailLink=signInWithEmailLink;t.signInWithPhoneNumber=signInWithPhoneNumber;t.signInWithPopup=signInWithPopup;t.signInWithRedirect=signInWithRedirect;t.signOut=signOut;t.unlink=unlink;t.updateCurrentUser=updateCurrentUser;t.updateEmail=updateEmail;t.updatePassword=updatePassword;t.updatePhoneNumber=updatePhoneNumber;t.updateProfile=updateProfile;t.useDeviceLanguage=useDeviceLanguage;t.validatePassword=validatePassword;t.verifyBeforeUpdateEmail=verifyBeforeUpdateEmail;t.verifyPasswordResetCode=verifyPasswordResetCode}
2,74726(e,t,n){Object.defineProperty(t,"__esModule",{value:true});var r=n(79642);n(50218);n(36183);n(40767);n(95282);t.ActionCodeOperation=r.ActionCodeOperation;t.ActionCodeURL=r.ActionCodeURL;t.AuthCredential=r.AuthCredential;t.AuthErrorCodes=r.AUTH_ERROR_CODES_MAP_DO_NOT_USE_INTERNALLY;t.EmailAuthCredential=r.EmailAuthCredential;t.EmailAuthProvider=r.EmailAuthProvider;t.FacebookAuthProvider=r.FacebookAuthProvider;t.FactorId=r.FactorId;t.GithubAuthProvider=r.GithubAuthProvider;t.GoogleAuthProvider=r.GoogleAuthProvider;t.OAuthCredential=r.OAuthCredential;t.OAuthProvider=r.OAuthProvider;t.OperationType=r.OperationType;t.PhoneAuthCredential=r.PhoneAuthCredential;t.PhoneAuthProvider=r.PhoneAuthProvider;t.PhoneMultiFactorGenerator=r.PhoneMultiFactorGenerator;t.ProviderId=r.ProviderId;t.RecaptchaVerifier=r.RecaptchaVerifier;t.SAMLAuthProvider=r.SAMLAuthProvider;t.SignInMethod=r.SignInMethod;t.TotpMultiFactorGenerator=r.TotpMultiFactorGenerator;t.TotpSecret=r.TotpSecret;t.TwitterAuthProvider=r.TwitterAuthProvider;t.applyActionCode=r.applyActionCode;t.beforeAuthStateChanged=r.beforeAuthStateChanged;t.browserCookiePersistence=r.browserCookiePersistence;t.browserLocalPersistence=r.browserLocalPersistence;t.browserPopupRedirectResolver=r.browserPopupRedirectResolver;t.browserSessionPersistence=r.browserSessionPersistence;t.checkActionCode=r.checkActionCode;t.confirmPasswordReset=r.confirmPasswordReset;t.connectAuthEmulator=r.connectAuthEmulator;t.createUserWithEmailAndPassword=r.createUserWithEmailAndPassword;t.debugErrorMap=r.debugErrorMap;t.deleteUser=r.deleteUser;t.fetchSignInMethodsForEmail=r.fetchSignInMethodsForEmail;t.getAdditionalUserInfo=r.getAdditionalUserInfo;t.getAuth=r.getAuth;t.getIdToken=r.getIdToken;t.getIdTokenResult=r.getIdTokenResult;t.getMultiFactorResolver=r.getMultiFactorResolver;t.getRedirectResult=r.getRedirectResult;t.inMemoryPersistence=r.inMemoryPersistence;t.indexedDBLocalPersistence=r.indexedDBLocalPersistence;t.initializeAuth=r.initializeAuth;t.initializeRecaptchaConfig=r.initializeRecaptchaConfig;t.isSignInWithEmailLink=r.isSignInWithEmailLink;t.linkWithCredential=r.linkWithCredential;t.linkWithPhoneNumber=r.linkWithPhoneNumber;t.linkWithPopup=r.linkWithPopup;t.linkWithRedirect=r.linkWithRedirect;t.multiFactor=r.multiFactor;t.onAuthStateChanged=r.onAuthStateChanged;t.onIdTokenChanged=r.onIdTokenChanged;t.parseActionCodeURL=r.parseActionCodeURL;t.prodErrorMap=r.prodErrorMap;t.reauthenticateWithCredential=r.reauthenticateWithCredential;t.reauthenticateWithPhoneNumber=r.reauthenticateWithPhoneNumber;t.reauthenticateWithPopup=r.reauthenticateWithPopup;t.reauthenticateWithRedirect=r.reauthenticateWithRedirect;t.reload=r.reload;t.revokeAccessToken=r.revokeAccessToken;t.sendEmailVerification=r.sendEmailVerification;t.sendPasswordResetEmail=r.sendPasswordResetEmail;t.sendSignInLinkToEmail=r.sendSignInLinkToEmail;t.setPersistence=r.setPersistence;t.signInAnonymously=r.signInAnonymously;t.signInWithCredential=r.signInWithCredential;t.signInWithCustomToken=r.signInWithCustomToken;t.signInWithEmailAndPassword=r.signInWithEmailAndPassword;t.signInWithEmailLink=r.signInWithEmailLink;t.signInWithPhoneNumber=r.signInWithPhoneNumber;t.signInWithPopup=r.signInWithPopup;t.signInWithRedirect=r.signInWithRedirect;t.signOut=r.signOut;t.unlink=r.unlink;t.updateCurrentUser=r.updateCurrentUser;t.updateEmail=r.updateEmail;t.updatePassword=r.updatePassword;t.updatePhoneNumber=r.updatePhoneNumber;t.updateProfile=r.updateProfile;t.useDeviceLanguage=r.useDeviceLanguage;t.validatePassword=r.validatePassword;t.verifyBeforeUpdateEmail=r.verifyBeforeUpdateEmail;t.verifyPasswordResetCode=r.verifyPasswordResetCode},42650(e,t,n){n.r(t);n.d(t,{deleteDB:()=>deleteDB,openDB:()=>openDB,unwrap:()=>unwrap,wrap:()=>wrap});const instanceOfAny=(e,t)=>t.some((t=>e instanceof t));let r;let i;function getIdbProxyableTypes(){return r||(r=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function getCursorAdvanceMethods(){return i||(i=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}const s=new WeakMap;const o=new WeakMap;const a=new WeakMap;const c=new WeakMap;const l=new WeakMap;function promisifyRequest(e){const t=new Promise(((t,n)=>{const unlisten=()=>{e.removeEventListener("success",success);e.removeEventListener("error",error)};const success=()=>{t(wrap(e.result));unlisten()};const error=()=>{n(e.error);unlisten()};e.addEventListener("success",success);e.addEventListener("error",error)}));t.then((t=>{if(t instanceof IDBCursor){s.set(t,e)}})).catch((()=>{}));l.set(t,e);return t}function cacheDonePromiseForTransaction(e){if(o.has(e))return;const t=new Promise(((t,n)=>{const unlisten=()=>{e.removeEventListener("complete",complete);e.removeEventListener("error",error);e.removeEventListener("abort",error)};const complete=()=>{t();unlisten()};const error=()=>{n(e.error||new DOMException("AbortError","AbortError"));unlisten()};e.addEventListener("complete",complete);e.addEventListener("error",error);e.addEventListener("abort",error)}));o.set(e,t)}let u={get(e,t,n){if(e instanceof IDBTransaction){if(t==="done")return o.get(e);if(t==="objectStoreNames"){return e.objectStoreNames||a.get(e)}if(t==="store"){return n.objectStoreNames[1]?undefined:n.objectStore(n.objectStoreNames[0])}}return wrap(e[t])},set(e,t,n){e[t]=n;return true},has(e,t){if(e instanceof IDBTransaction&&(t==="done"||t==="store")){return true}return t in e}};function replaceTraps(e){u=e(u)}function wrapFunction(e){if(e===IDBDatabase.prototype.transaction&&!("objectStoreNames"in IDBTransaction.prototype)){return function(t,...n){const r=e.call(unwrap(this),t,...n);a.set(r,t.sort?t.sort():[t]);return wrap(r)}}if(getCursorAdvanceMethods().includes(e)){return function(...t){e.apply(unwrap(this),t);return wrap(s.get(this))}}return function(...t){return wrap(e.apply(unwrap(this),t))}}function transformCachableValue(e){if(typeof e==="function")return wrapFunction(e);if(e instanceof IDBTransaction)cacheDonePromiseForTransaction(e);if(instanceOfAny(e,getIdbProxyableTypes()))return new Proxy(e,u);return e}function wrap(e){if(e instanceof IDBRequest)return promisifyRequest(e);
2if(c.has(e))return c.get(e);const t=transformCachableValue(e);if(t!==e){c.set(e,t);l.set(t,e)}return t}const unwrap=e=>l.get(e);function openDB(e,t,{blocked:n,upgrade:r,blocking:i,terminated:s}={}){const o=indexedDB.open(e,t);const a=wrap(o);if(r){o.addEventListener("upgradeneeded",(e=>{r(wrap(o.result),e.oldVersion,e.newVersion,wrap(o.transaction),e)}))}if(n){o.addEventListener("blocked",(e=>n(e.oldVersion,e.newVersion,e)))}a.then((e=>{if(s)e.addEventListener("close",(()=>s()));if(i){e.addEventListener("versionchange",(e=>i(e.oldVersion,e.newVersion,e)))}})).catch((()=>{}));return a}function deleteDB(e,{blocked:t}={}){const n=indexedDB.deleteDatabase(e);if(t){n.addEventListener("blocked",(e=>t(e.oldVersion,e)))}return wrap(n).then((()=>undefined))}const d=["get","getKey","getAll","getAllKeys","count"];const h=["put","add","delete","clear"];const p=new Map;function getMethod(e,t){if(!(e instanceof IDBDatabase&&!(t in e)&&typeof t==="string")){return}if(p.get(t))return p.get(t);const n=t.replace(/FromIndex$/,"");const r=t!==n;const i=h.includes(n);if(!(n in(r?IDBIndex:IDBObjectStore).prototype)||!(i||d.includes(n))){return}const method=async function(e,...t){const s=this.transaction(e,i?"readwrite":"readonly");let o=s.store;if(r)o=o.index(t.shift());return(await Promise.all([o[n](...t),i&&s.done]))[0]};p.set(t,method);return method}replaceTraps((e=>({...e,get:(t,n,r)=>getMethod(t,n)||e.get(t,n,r),has:(t,n)=>!!getMethod(t,n)||e.has(t,n)})))}}]);
3//# sourceMappingURL=onboarding-firebase-init.6a8e5397e438c6aba54c.js.map

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.