PageSourceSearch

https://singsharp.com/_next/static/chunks/2t37wk-emu0th.js

js singsharp.com collected 2026-09-24 10:54:16 UTC 239,083 bytes, 1 lines download raw bytes

1(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,485086,733015,965233,68483,344435,e=>{"use strict";let t,n,i;var r,s,o=e.i(247167);let a=function(e,t){if(!e)throw l(t)},l=function(e){return Error("Firebase Database (${JSCORE_VERSION}) INTERNAL ASSERT FAILED: "+e)},h=function(e){let t=[],n=0;for(let i=0;i<e.length;i++){let r=e.charCodeAt(i);r<128?t[n++]=r:(r<2048?t[n++]=r>>6|192:((64512&r)==55296&&i+1<e.length&&(64512&e.charCodeAt(i+1))==56320?(r=65536+((1023&r)<<10)+(1023&e.charCodeAt(++i)),t[n++]=r>>18|240,t[n++]=r>>12&63|128):t[n++]=r>>12|224,t[n++]=r>>6&63|128),t[n++]=63&r|128)}return t},c=function(e){let t=[],n=0,i=0;for(;n<e.length;){let r=e[n++];if(r<128)t[i++]=String.fromCharCode(r);else if(r>191&&r<224){let s=e[n++];t[i++]=String.fromCharCode((31&r)<<6|63&s)}else if(r>239&&r<365){let s=((7&r)<<18|(63&e[n++])<<12|(63&e[n++])<<6|63&e[n++])-65536;t[i++]=String.fromCharCode(55296+(s>>10)),t[i++]=String.fromCharCode(56320+(1023&s))}else{let s=e[n++],o=e[n++];t[i++]=String.fromCharCode((15&r)<<12|(63&s)<<6|63&o)}}return t.join("")},u={byteToCharMap_:null,charToByteMap_:null,byteToCharMapWebSafe_:null,charToByteMapWebSafe_:null,ENCODED_VALS_BASE:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",get ENCODED_VALS(){return this.ENCODED_VALS_BASE+"+/="},get ENCODED_VALS_WEBSAFE(){return this.ENCODED_VALS_BASE+"-_."},HAS_NATIVE_SUPPORT:"function"==typeof atob,encodeByteArray(e,t){if(!Array.isArray(e))throw Error("encodeByteArray takes an array as a parameter");this.init_();let n=t?this.byteToCharMapWebSafe_:this.byteToCharMap_,i=[];for(let t=0;t<e.length;t+=3){let r=e[t],s=t+1<e.length,o=s?e[t+1]:0,a=t+2<e.length,l=a?e[t+2]:0,h=r>>2,c=(3&r)<<4|o>>4,u=(15&o)<<2|l>>6,d=63&l;!a&&(d=64,s||(u=64)),i.push(n[h],n[c],n[u],n[d])}return i.join("")},encodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?btoa(e):this.encodeByteArray(h(e),t)},decodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?atob(e):c(this.decodeStringToByteArray(e,t))},decodeStringToByteArray(e,t){this.init_();let n=t?this.charToByteMapWebSafe_:this.charToByteMap_,i=[];for(let t=0;t<e.length;){let r=n[e.charAt(t++)],s=t<e.length?n[e.charAt(t)]:0,o=++t<e.length?n[e.charAt(t)]:64,a=++t<e.length?n[e.charAt(t)]:64;if(++t,null==r||null==s||null==o||null==a)throw new d;let l=r<<2|s>>4;if(i.push(l),64!==o){let e=s<<4&240|o>>2;if(i.push(e),64!==a){let e=o<<6&192|a;i.push(e)}}}return i},init_(){if(!this.byteToCharMap_){this.byteToCharMap_={},this.charToByteMap_={},this.byteToCharMapWebSafe_={},this.charToByteMapWebSafe_={};for(let e=0;e<this.ENCODED_VALS.length;e++)this.byteToCharMap_[e]=this.ENCODED_VALS.charAt(e),this.charToByteMap_[this.byteToCharMap_[e]]=e,this.byteToCharMapWebSafe_[e]=this.ENCODED_VALS_WEBSAFE.charAt(e),this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[e]]=e,e>=this.ENCODED_VALS_BASE.length&&(this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(e)]=e,this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(e)]=e)}}};class d extends Error{constructor(){super(...arguments),this.name="DecodeBase64StringError"}}let p=function(e){let t=h(e);return u.encodeByteArray(t,!0)},f=function(e){return p(e).replace(/\./g,"")},_=function(e){try{return u.decodeString(e,!0)}catch(e){console.error("base64Decode failed: ",e)}return null},g=()=>{try{return("u">typeof self?self:"u">typeof window?window:e.g).__FIREBASE_DEFAULTS__||(()=>{if(void 0===o.default||void 0===o.default.env)return;let e=o.default.env.__FIREBASE_DEFAULTS__;if(e)return JSON.parse(e)})()||(()=>{let e;if("u"<typeof document)return;try{e=document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/)}catch(e){return}let t=e&&_(e[1]);return t&&JSON.parse(t)})()}catch(e){console.info(`Unable to get __FIREBASE_DEFAULTS__ due to: ${e}`);return}},m=e=>{var t,n;return null==(n=null==(t=g())?void 0:t.emulatorHosts)?void 0:n[e]},y=()=>{var e;return null==(e=g())?void 0:e.config};class v{constructor(){this.reject=()=>{},this.resolve=()=>{},this.promise=new Promise((e,t)=>{this.resolve=e,this.reject=t})}wrapCallback(e){return(t,n)=>{t?this.reject(t):this.resolve(n),"function"==typeof e&&(this.promise.catch(()=>{}),1===e.length?e(t):e(t,n))}}}function w(){return"u">typeof navigator&&"string"==typeof navigator.userAgent?navigator.userAgent:""}function I(){return"u">typeof WorkerGlobalScope&&"u">typeof self&&self instanceof WorkerGlobalScope}function C(){try{return"object"==typeof indexedDB}catch(e){return!1}}function b(){return new Promise((e,t)=>
1{try{let n=!0,i="validate-browser-context-for-indexeddb-analytics-module",r=self.indexedDB.open(i);r.onsuccess=()=>{r.result.close(),n||self.indexedDB.deleteDatabase(i),e(!0)},r.onupgradeneeded=()=>{n=!1},r.onerror=()=>{var e;t((null==(e=r.error)?void 0:e.message)||"")}}catch(e){t(e)}})}class E extends Error{constructor(e,t,n){super(t),this.code=e,this.customData=n,this.name="FirebaseError",Object.setPrototypeOf(this,E.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,T.prototype.create)}}class T{constructor(e,t,n){this.service=e,this.serviceName=t,this.errors=n}create(e,...t){var n,i;let r=t[0]||{},s=`${this.service}/${e}`,o=this.errors[e],a=o?(n=o,i=r,n.replace(S,(e,t)=>{let n=i[t];return null!=n?String(n):`<${t}?>`})):"Error",l=`${this.serviceName}: ${a} (${s}).`;return new E(s,l,r)}}let S=/\{\$([^}]+)}/g;function k(e){return JSON.parse(e)}let P=function(e){let t={},n={},i={},r="";try{let s=e.split(".");t=k(_(s[0])||""),n=k(_(s[1])||""),r=s[2],i=n.d||{},delete n.d}catch(e){}return{header:t,claims:n,data:i,signature:r}};function N(e,t){if(e===t)return!0;let n=Object.keys(e),i=Object.keys(t);for(let r of n){if(!i.includes(r))return!1;let n=e[r],s=t[r];if(R(n)&&R(s)){if(!N(n,s))return!1}else if(n!==s)return!1}for(let e of i)if(!n.includes(e))return!1;return!0}function R(e){return null!==e&&"object"==typeof e}class A{constructor(e,t){this.observers=[],this.unsubscribes=[],this.observerCount=0,this.task=Promise.resolve(),this.finalized=!1,this.onNoObservers=t,this.task.then(()=>{e(this)}).catch(e=>{this.error(e)})}next(e){this.forEachObserver(t=>{t.next(e)})}error(e){this.forEachObserver(t=>{t.error(e)}),this.close(e)}complete(){this.forEachObserver(e=>{e.complete()}),this.close()}subscribe(e,t,n){let i;if(void 0===e&&void 0===t&&void 0===n)throw Error("Missing Observer.");void 0===(i=!function(e,t){if("object"!=typeof e||null===e)return!1;for(let n of t)if(n in e&&"function"==typeof e[n])return!0;return!1}(e,["next","error","complete"])?{next:e,error:t,complete:n}:e).next&&(i.next=O),void 0===i.error&&(i.error=O),void 0===i.complete&&(i.complete=O);let r=this.unsubscribeOne.bind(this,this.observers.length);return this.finalized&&this.task.then(()=>{try{this.finalError?i.error(this.finalError):i.complete()}catch(e){}}),this.observers.push(i),r}unsubscribeOne(e){void 0!==this.observers&&void 0!==this.observers[e]&&(delete this.observers[e],this.observerCount-=1,0===this.observerCount&&void 0!==this.onNoObservers&&this.onNoObservers(this))}forEachObserver(e){if(!this.finalized)for(let t=0;t<this.observers.length;t++)this.sendOne(t,e)}sendOne(e,t){this.task.then(()=>{if(void 0!==this.observers&&void 0!==this.observers[e])try{t(this.observers[e])}catch(e){"u">typeof console&&console.error&&console.error(e)}})}close(e){this.finalized||(this.finalized=!0,void 0!==e&&(this.finalError=e),this.task.then(()=>{this.observers=void 0,this.onNoObservers=void 0}))}}function O(){}e.s(["Deferred",0,v,"ErrorFactory",0,T,"FirebaseError",0,E,"Sha1",0,class{constructor(){this.chain_=[],this.buf_=[],this.W_=[],this.pad_=[],this.inbuf_=0,this.total_=0,this.blockSize=64,this.pad_[0]=128;for(let e=1;e<this.blockSize;++e)this.pad_[e]=0;this.reset()}reset(){this.chain_[0]=0x67452301,this.chain_[1]=0xefcdab89,this.chain_[2]=0x98badcfe,this.chain_[3]=0x10325476,this.chain_[4]=0xc3d2e1f0,this.inbuf_=0,this.total_=0}compress_(e,t){let n,i;t||(t=0);let r=this.W_;if("string"==typeof e)for(let n=0;n<16;n++)r[n]=e.charCodeAt(t)<<24|e.charCodeAt(t+1)<<16|e.charCodeAt(t+2)<<8|e.charCodeAt(t+3),t+=4;else for(let n=0;n<16;n++)r[n]=e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3],t+=4;for(let e=16;e<80;e++){let t=r[e-3]^r[e-8]^r[e-14]^r[e-16];r[e]=(t<<1|t>>>31)&0xffffffff}let s=this.chain_[0],o=this.chain_[1],a=this.chain_[2],l=this.chain_[3],h=this.chain_[4];for(let e=0;e<80;e++){e<40?e<20?(n=l^o&(a^l),i=0x5a827999):(n=o^a^l,i=0x6ed9eba1):e<60?(n=o&a|l&(o|a),i=0x8f1bbcdc):(n=o^a^l,i=0xca62c1d6);let t=(s<<5|s>>>27)+n+h+i+r[e]|0;h=l,l=a,a=(o<<30|o>>>2)&0xffffffff,o=s,s=t}this.chain_[0]=this.chain_[0]+s|0,this.chain_[1]=this.chain_[1]+o|0,this.chain_[2]=this.chain_[2]+a|0,this.chain_[3]=this.chain_[3]+l|0,this.chain_[4]=this.chain_[4]+h|0}update(e,t){if(null==e)return;void 0===t&&(t=e.length);let n=t-this.blockSize,i=0,r=this.buf_,s=this.inbuf_;for(;i<t;){if(0===s)for(;i<=n;)this.compress_(e,i),i+=this.blockSize;if("string"==typeof e){for(;i<t;)if(r[s]=e.charCodeAt(i),++s,++i,s===this.blockSize){this.compress_(r),s=0;break}}else for(;i<t;)if(r[s]=e[i],++s,++i,s===this.blockSize){this.compress_(r),s=0;break}}this.inbuf_=s,this.total_+=t}digest(){let e=[],t=8*this.total_;this.inbuf_<56?this.update(this.pad_,56-this.inbuf_):this.update(this.pad_,this.blockSize-(this.inbuf_-56));for(let e=this.blockSize-1;e>=56;e--)this.buf_[e]=255&t,t/=256;this.compress_(this.buf_);let n=0;for(let t=0;t<5;t++)for(let i=24;i>=0;i-=8)e[n]=this.chain_[t]>>i&255,++n;return e}},"areCookiesEnabled",0,function(){return!("u"<typeof navigator)&&!!navigator.cookieEnabled},"assert",0,a,"assertionError",0,l,"base64",0,u,"base64Decode",0,_,"base64Encode",0,p,"base64urlEncodeWithoutPadding",0,f,"calculateBackoffMillis",0,function(e,t=1e3,n=2){let i=t*Math.pow(n,e),r=Math.round(.5*i*(Math.random()-.5)*2);return Math.min(144e5,i+r)},"contains",0,function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},"createMockUserToken",0,function(e,t){if(e.uid)throw Error('The "uid" field is no longer supported by mockUserToken. Please use "sub" instead for Firebase Auth User ID.');
1let n=t||"demo-project",i=e.iat||0,r=e.sub||e.user_id;if(!r)throw Error("mockUserToken must contain 'sub' or 'user_id' field!");let s=Object.assign({iss:`https://securetoken.google.com/${n}`,aud:n,iat:i,exp:i+3600,auth_time:i,sub:r,user_id:r,firebase:{sign_in_provider:"custom",identities:{}}},e);return[f(JSON.stringify({alg:"none",type:"JWT"})),f(JSON.stringify(s)),""].join(".")},"createSubscribe",0,function(e,t){let n=new A(e,t);return n.subscribe.bind(n)},"deepCopy",0,function(e){return function e(t,n){if(!(n instanceof Object))return n;switch(n.constructor){case Date:return new Date(n.getTime());case Object:void 0===t&&(t={});break;case Array:t=[];break;default:return n}for(let i in n)n.hasOwnProperty(i)&&"__proto__"!==i&&(t[i]=e(t[i],n[i]));return t}(void 0,e)},"deepEqual",0,N,"errorPrefix",0,function(e,t){return`${e} failed: ${t} argument `},"extractQuerystring",0,function(e){let t=e.indexOf("?");if(!t)return"";let n=e.indexOf("#",t);return e.substring(t,n>0?n:void 0)},"getDefaultAppConfig",0,y,"getDefaultEmulatorHost",0,m,"getDefaultEmulatorHostnameAndPort",0,e=>{let t=m(e);if(!t)return;let n=t.lastIndexOf(":");if(n<=0||n+1===t.length)throw Error(`Invalid host ${t} with no separate hostname and port!`);let i=parseInt(t.substring(n+1),10);return"["===t[0]?[t.substring(1,n-1),i]:[t.substring(0,n),i]},"getExperimentalSetting",0,e=>{var t;return null==(t=g())?void 0:t[`_${e}`]},"getModularInstance",0,function(e){return e&&e._delegate?e._delegate:e},"getUA",0,w,"isAdmin",0,function(e){let t=P(e).claims;return"object"==typeof t&&!0===t.admin},"isBrowser",0,function(){return"u">typeof window||I()},"isBrowserExtension",0,function(){let e="object"==typeof chrome?chrome.runtime:"object"==typeof browser?browser.runtime:void 0;return"object"==typeof e&&void 0!==e.id},"isCloudflareWorker",0,function(){return"u">typeof navigator&&"Cloudflare-Workers"===navigator.userAgent},"isEmpty",0,function(e){for(let t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0},"isIE",0,function(){let e=w();return e.indexOf("MSIE ")>=0||e.indexOf("Trident/")>=0},"isIndexedDBAvailable",0,C,"isMobileCordova",0,function(){return"u">typeof window&&!!(window.cordova||window.phonegap||window.PhoneGap)&&/ios|iphone|ipod|ipad|android|blackberry|iemobile/i.test(w())},"isNodeSdk",0,function(){return false},"isReactNative",0,function(){return"object"==typeof navigator&&"ReactNative"===navigator.product},"isValidFormat",0,function(e){let t=P(e).claims;return!!t&&"object"==typeof t&&t.hasOwnProperty("iat")},"isWebWorker",0,I,"jsonEval",0,k,"map",0,function(e,t,n){let i={};for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&(i[r]=t.call(n,e[r],r,e));return i},"querystring",0,function(e){let t=[];for(let[n,i]of Object.entries(e))Array.isArray(i)?i.forEach(e=>{t.push(encodeURIComponent(n)+"="+encodeURIComponent(e))}):t.push(encodeURIComponent(n)+"="+encodeURIComponent(i));return t.length?"&"+t.join("&"):""},"querystringDecode",0,function(e){let t={};return e.replace(/^\?/,"").split("&").forEach(e=>{if(e){let[n,i]=e.split("=");
1t[decodeURIComponent(n)]=decodeURIComponent(i)}}),t},"safeGet",0,function(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0},"stringLength",0,function(e){let t=0;for(let n=0;n<e.length;n++){let i=e.charCodeAt(n);i<128?t++:i<2048?t+=2:i>=55296&&i<=56319?(t+=4,n++):t+=3}return t},"stringToByteArray",0,function(e){let t=[],n=0;for(let i=0;i<e.length;i++){let r=e.charCodeAt(i);if(r>=55296&&r<=56319){let t=r-55296;a(++i<e.length,"Surrogate pair missing trail surrogate."),r=65536+(t<<10)+(e.charCodeAt(i)-56320)}r<128?t[n++]=r:(r<2048?t[n++]=r>>6|192:(r<65536?t[n++]=r>>12|224:(t[n++]=r>>18|240,t[n++]=r>>12&63|128),t[n++]=r>>6&63|128),t[n++]=63&r|128)}return t},"stringify",0,function(e){return JSON.stringify(e)},"validateIndexedDBOpenable",0,b],733015);class D{constructor(e,t,n){this.name=e,this.instanceFactory=t,this.type=n,this.multipleInstances=!1,this.serviceProps={},this.instantiationMode="LAZY",this.onInstanceCreated=null}setInstantiationMode(e){return this.instantiationMode=e,this}setMultipleInstances(e){return this.multipleInstances=e,this}setServiceProps(e){return this.serviceProps=e,this}setInstanceCreatedCallback(e){return this.onInstanceCreated=e,this}}let x="[DEFAULT]";class L{constructor(e,t){this.name=e,this.container=t,this.component=null,this.instances=new Map,this.instancesDeferred=new Map,this.instancesOptions=new Map,this.onInitCallbacks=new Map}get(e){let t=this.normalizeInstanceIdentifier(e);if(!this.instancesDeferred.has(t)){let e=new v;if(this.instancesDeferred.set(t,e),this.isInitialized(t)||this.shouldAutoInitialize())try{let n=this.getOrInitializeService({instanceIdentifier:t});n&&e.resolve(n)}catch(e){}}return this.instancesDeferred.get(t).promise}getImmediate(e){var t;let n=this.normalizeInstanceIdentifier(null==e?void 0:e.identifier),i=null!=(t=null==e?void 0:e.optional)&&t;if(this.isInitialized(n)||this.shouldAutoInitialize())try{return this.getOrInitializeService({instanceIdentifier:n})}catch(e){if(i)return null;throw e}if(i)return null;throw Error(`Service ${this.name} is not available`)}getComponent(){return this.component}setComponent(e){if(e.name!==this.name)throw Error(`Mismatching Component ${e.name} for Provider ${this.name}.`);if(this.component)throw Error(`Component for ${this.name} has already been provided`);if(this.component=e,this.shouldAutoInitialize()){if("EAGER"===e.instantiationMode)try{this.getOrInitializeService({instanceIdentifier:x})}catch(e){}for(let[e,t]of this.instancesDeferred.entries()){let n=this.normalizeInstanceIdentifier(e);try{let e=this.getOrInitializeService({instanceIdentifier:n});t.resolve(e)}catch(e){}}}}clearInstance(e=x){this.instancesDeferred.delete(e),this.instancesOptions.delete(e),this.instances.delete(e)}async delete(){let e=Array.from(this.instances.values());await Promise.all([...e.filter(e=>"INTERNAL"in e).map(e=>e.INTERNAL.delete()),...e.filter(e=>"_delete"in e).map(e=>e._delete())])}isComponentSet(){return null!=this.component}isInitialized(e=x){return this.instances.has(e)}getOptions(e=x){return this.instancesOptions.get(e)||{}}initialize(e={}){let{options:t={}}=e,n=this.normalizeInstanceIdentifier(e.instanceIdentifier);if(this.isInitialized(n))throw Error(`${this.name}(${n}) has already been initialized`);if(!this.isComponentSet())throw Error(`Component ${this.name} has not been registered yet`);let i=this.getOrInitializeService({instanceIdentifier:n,options:t});for(let[e,t]of this.instancesDeferred.entries())n===this.normalizeInstanceIdentifier(e)&&t.resolve(i);return i}onInit(e,t){var n;let i=this.normalizeInstanceIdentifier(t),r=null!=(n=this.onInitCallbacks.get(i))?n:new Set;r.add(e),this.onInitCallbacks.set(i,r);let s=this.instances.get(i);return s&&e(s,i),()=>{r.delete(e)}}invokeOnInitCallbacks(e,t){let n=this.onInitCallbacks.get(t);if(n)for(let i of n)try{i(e,t)}catch(e){}}getOrInitializeService({instanceIdentifier:e,options:t={}}){var n;let i=this.instances.get(e);if(!i&&this.component&&(i=this.component.instanceFactory(this.container,{instanceIdentifier:(n=e)===x?void 0:n,options:t}),this.instances.set(e,i),this.instancesOptions.set(e,t),this.invokeOnInitCallbacks(i,e),this.component.onInstanceCreated))try{this.component.onInstanceCreated(this.container,e,i)}catch(e){}return i||null}normalizeInstanceIdentifier(e=x){return this.component?this.component.multipleInstances?e:x:e}shouldAutoInitialize(){return!!this.component&&"EXPLICIT"!==this.component.instantiationMode}}class M{constructor(e){this.name=e,this.providers=new Map}addComponent(e){let t=this.getProvider(e.name);if(t.isComponentSet())throw Error(`Component ${e.name} has already been registered with ${this.name}`);t.setComponent(e)}addOrOverwriteComponent(e){this.getProvider(e.name).isComponentSet()&&this.providers.delete(e.name),this.addComponent(e)}getProvider(e){if(this.providers.has(e))return this.providers.get(e);let t=new L(e,this);return this.providers.set(e,t),t}getProviders(){return Array.from(this.providers.values())}}e.s(["Component",0,D,"ComponentContainer",0,M,"Provider",0,L],965233);let F=[];(r=s||(s={}))[r.DEBUG=0]="DEBUG",r[r.VERBOSE=1]="VERBOSE",r[r.INFO=2]="INFO",r[r.WARN=3]="WARN",r[r.ERROR=4]="ERROR",r[r.SILENT=5]="SILENT";
1let U={debug:s.DEBUG,verbose:s.VERBOSE,info:s.INFO,warn:s.WARN,error:s.ERROR,silent:s.SILENT},q=s.INFO,j={[s.DEBUG]:"log",[s.VERBOSE]:"log",[s.INFO]:"info",[s.WARN]:"warn",[s.ERROR]:"error"},W=(e,t,...n)=>{if(t<e.logLevel)return;let i=new Date().toISOString(),r=j[t];if(r)console[r](`[${i}]  ${e.name}:`,...n);else throw Error(`Attempted to log a message with an invalid logType (value: ${t})`)};class V{constructor(e){this.name=e,this._logLevel=q,this._logHandler=W,this._userLogHandler=null,F.push(this)}get logLevel(){return this._logLevel}set logLevel(e){if(!(e in s))throw TypeError(`Invalid value "${e}" assigned to \`logLevel\``);this._logLevel=e}setLogLevel(e){this._logLevel="string"==typeof e?U[e]:e}get logHandler(){return this._logHandler}set logHandler(e){if("function"!=typeof e)throw TypeError("Value assigned to `logHandler` must be a function");this._logHandler=e}get userLogHandler(){return this._userLogHandler}set userLogHandler(e){this._userLogHandler=e}debug(...e){this._userLogHandler&&this._userLogHandler(this,s.DEBUG,...e),this._logHandler(this,s.DEBUG,...e)}log(...e){this._userLogHandler&&this._userLogHandler(this,s.VERBOSE,...e),this._logHandler(this,s.VERBOSE,...e)}info(...e){this._userLogHandler&&this._userLogHandler(this,s.INFO,...e),this._logHandler(this,s.INFO,...e)}warn(...e){this._userLogHandler&&this._userLogHandler(this,s.WARN,...e),this._logHandler(this,s.WARN,...e)}error(...e){this._userLogHandler&&this._userLogHandler(this,s.ERROR,...e),this._logHandler(this,s.ERROR,...e)}}e.s(["LogLevel",0,s,"Logger",0,V,"setLogLevel",0,function(e){F.forEach(t=>{t.setLogLevel(e)})},"setUserLogHandler",0,function(e,t){for(let n of F){let i=null;t&&t.level&&(i=U[t.level]),null===e?n.userLogHandler=null:n.userLogHandler=(t,n,...r)=>{let o=r.map(e=>{if(null==e)return null;if("string"==typeof e)return e;if("number"==typeof e||"boolean"==typeof e)return e.toString();if(e instanceof Error)return e.message;try{return JSON.stringify(e)}catch(e){return null}}).filter(e=>e).join(" ");n>=(null!=i?i:t.logLevel)&&e({level:s[n].toLowerCase(),message:o,args:r,type:t.name})}}}],68483);let H=new WeakMap,B=new WeakMap,z=new WeakMap,$=new WeakMap,K=new WeakMap,G={get(e,t,n){if(e instanceof IDBTransaction){if("done"===t)return B.get(e);if("objectStoreNames"===t)return e.objectStoreNames||z.get(e);if("store"===t)return n.objectStoreNames[1]?void 0:n.objectStore(n.objectStoreNames[0])}return Y(e[t])},set:(e,t,n)=>(e[t]=n,!0),has:(e,t)=>e instanceof IDBTransaction&&("done"===t||"store"===t)||t in e};function Y(e){if(e instanceof IDBRequest){let t;return(t=new Promise((t,n)=>{let i=()=>{e.removeEventListener("success",r),e.removeEventListener("error",s)},r=()=>{t(Y(e.result)),i()},s=()=>{n(e.error),i()};e.addEventListener("success",r),e.addEventListener("error",s)})).then(t=>{t instanceof IDBCursor&&H.set(t,e)}).catch(()=>{}),K.set(t,e),t}if($.has(e))return $.get(e);let i=function(e){if("function"==typeof e)return e!==IDBDatabase.prototype.transaction||"objectStoreNames"in IDBTransaction.prototype?(n||(n=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])).includes(e)?function(...t){return e.apply(J(this),t),Y(H.get(this))}:function(...t){return Y(e.apply(J(this),t))}:function(t,...n){let i=e.call(J(this),t,...n);return z.set(i,t.sort?t.sort():[t]),Y(i)};return e instanceof IDBTransaction&&function(e){if(B.has(e))return;let t=new Promise((t,n)=>{let i=()=>{e.removeEventListener("complete",r),e.removeEventListener("error",s),e.removeEventListener("abort",s)},r=()=>{t(),i()},s=()=>{n(e.error||new DOMException("AbortError","AbortError")),i()};e.addEventListener("complete",r),e.addEventListener("error",s),e.addEventListener("abort",s)});B.set(e,t)}(e),(t||(t=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])).some(t=>e instanceof t)?new Proxy(e,G):e}(e);return i!==e&&($.set(e,i),K.set(i,e)),i}let J=e=>K.get(e);function Q(e,t,{blocked:n,upgrade:i,blocking:r,terminated:s}={}){let o=indexedDB.open(e,t),a=Y(o);return i&&o.addEventListener("upgradeneeded",e=>{i(Y(o.result),e.oldVersion,e.newVersion,Y(o.transaction),e)}),n&&o.addEventListener("blocked",e=>n(e.oldVersion,e.newVersion,e)),a.then(e=>{s&&e.addEventListener("close",()=>s()),r&&e.addEventListener("versionchange",e=>r(e.oldVersion,e.newVersion,e))}).catch(()=>{}),a}let X=["get","getKey","getAll","getAllKeys","count"],Z=["put","add","delete","clear"],ee=new Map;function et(e,t){if(!(e instanceof IDBDatabase&&!(t in e)&&"string"==typeof t))return;if(ee.get(t))return ee.get(t);let n=t.replace(/FromIndex$/,""),i=t!==n,r=Z.includes(n);if(!(n in(i?IDBIndex:IDBObjectStore).prototype)||!(r||X.includes(n)))return;let s=async function(e,...t){let s=this.transaction(e,r?"readwrite":"readonly"),o=s.store;
1return i&&(o=o.index(t.shift())),(await Promise.all([o[n](...t),r&&s.done]))[0]};return ee.set(t,s),s}G={...i=G,get:(e,t,n)=>et(e,t)||i.get(e,t,n),has:(e,t)=>!!et(e,t)||i.has(e,t)},e.s(["openDB",0,Q],344435);class en{constructor(e){this.container=e}getPlatformInfoString(){return this.container.getProviders().map(e=>{let t;if((null==(t=e.getComponent())?void 0:t.type)!=="VERSION")return null;{let t=e.getImmediate();return`${t.library}/${t.version}`}}).filter(e=>e).join(" ")}}let ei="@firebase/app",er="0.10.13",es=new V("@firebase/app"),eo="[DEFAULT]",ea={[ei]:"fire-core","@firebase/app-compat":"fire-core-compat","@firebase/analytics":"fire-analytics","@firebase/analytics-compat":"fire-analytics-compat","@firebase/app-check":"fire-app-check","@firebase/app-check-compat":"fire-app-check-compat","@firebase/auth":"fire-auth","@firebase/auth-compat":"fire-auth-compat","@firebase/database":"fire-rtdb","@firebase/data-connect":"fire-data-connect","@firebase/database-compat":"fire-rtdb-compat","@firebase/functions":"fire-fn","@firebase/functions-compat":"fire-fn-compat","@firebase/installations":"fire-iid","@firebase/installations-compat":"fire-iid-compat","@firebase/messaging":"fire-fcm","@firebase/messaging-compat":"fire-fcm-compat","@firebase/performance":"fire-perf","@firebase/performance-compat":"fire-perf-compat","@firebase/remote-config":"fire-rc","@firebase/remote-config-compat":"fire-rc-compat","@firebase/storage":"fire-gcs","@firebase/storage-compat":"fire-gcs-compat","@firebase/firestore":"fire-fst","@firebase/firestore-compat":"fire-fst-compat","@firebase/vertexai-preview":"fire-vertex","fire-js":"fire-js",firebase:"fire-js-all"},el=new Map,eh=new Map,ec=new Map;function eu(e,t){try{e.container.addComponent(t)}catch(n){es.debug(`Component ${t.name} failed to register with FirebaseApp ${e.name}`,n)}}function ed(e){let t=e.name;if(ec.has(t))return es.debug(`There were multiple attempts to register component ${t}.`),!1;
1for(let n of(ec.set(t,e),el.values()))eu(n,e);for(let t of eh.values())eu(t,e);return!0}let ep=new T("app","Firebase",{"no-app":"No Firebase App '{$appName}' has been created - call initializeApp() first","bad-app-name":"Illegal App name: '{$appName}'","duplicate-app":"Firebase App named '{$appName}' already exists with different options or config","app-deleted":"Firebase App named '{$appName}' already deleted","server-app-deleted":"Firebase Server App has been deleted","no-options":"Need to provide options, when not being deployed to hosting via source.","invalid-app-argument":"firebase.{$appName}() takes either no argument or a Firebase App instance.","invalid-log-argument":"First argument to `onLog` must be null or a function.","idb-open":"Error thrown when opening IndexedDB. Original error: {$originalErrorMessage}.","idb-get":"Error thrown when reading from IndexedDB. Original error: {$originalErrorMessage}.","idb-set":"Error thrown when writing to IndexedDB. Original error: {$originalErrorMessage}.","idb-delete":"Error thrown when deleting from IndexedDB. Original error: {$originalErrorMessage}.","finalization-registry-not-supported":"FirebaseServerApp deleteOnDeref field defined but the JS runtime does not support FinalizationRegistry.","invalid-server-app-environment":"FirebaseServerApp is not for use in browser environments."});class ef{constructor(e,t,n){this._isDeleted=!1,this._options=Object.assign({},e),this._config=Object.assign({},t),this._name=t.name,this._automaticDataCollectionEnabled=t.automaticDataCollectionEnabled,this._container=n,this.container.addComponent(new D("app",()=>this,"PUBLIC"))}get automaticDataCollectionEnabled(){return this.checkDestroyed(),this._automaticDataCollectionEnabled}set automaticDataCollectionEnabled(e){this.checkDestroyed(),this._automaticDataCollectionEnabled=e}get name(){return this.checkDestroyed(),this._name}get options(){return this.checkDestroyed(),this._options}get config(){return this.checkDestroyed(),this._config}get container(){return this._container}get isDeleted(){return this._isDeleted}set isDeleted(e){this._isDeleted=e}checkDestroyed(){if(this.isDeleted)throw ep.create("app-deleted",{appName:this._name})}}function e_(e,t={}){let n=e;"object"!=typeof t&&(t={name:t});let i=Object.assign({name:eo,automaticDataCollectionEnabled:!1},t),r=i.name;if("string"!=typeof r||!r)throw ep.create("bad-app-name",{appName:String(r)});if(n||(n=y()),!n)throw ep.create("no-options");let s=el.get(r);if(s)if(N(n,s.options)&&N(i,s.config))return s;else throw ep.create("duplicate-app",{appName:r});let o=new M(r);for(let e of ec.values())o.addComponent(e);let a=new ef(n,i,o);return el.set(r,a),a}function eg(e,t,n){var i;let r=null!=(i=ea[e])?i:e;n&&(r+=`-${n}`);let s=r.match(/\s|\//),o=t.match(/\s|\//);if(s||o){let e=[`Unable to register library "${r}" with version "${t}":`];s&&e.push(`library name "${r}" contains illegal characters (whitespace or "/")`),s&&o&&e.push("and"),o&&e.push(`version name "${t}" contains illegal characters (whitespace or "/")`),es.warn(e.join(" "));return}ed(new D(`${r}-version`,()=>({library:r,version:t}),"VERSION"))}let em="firebase-heartbeat-store",ey=null;function ev(){return ey||(ey=Q("firebase-heartbeat-database",1,{upgrade:(e,t)=>{if(0===t)try{e.createObjectStore(em)}catch(e){console.warn(e)}}}).catch(e=>{throw ep.create("idb-open",{originalErrorMessage:e.message})})),ey}async function ew(e){try{let t=(await ev()).transaction(em),n=await t.objectStore(em).get(eC(e));return await t.done,n}catch(e){if(e instanceof E)es.warn(e.message);else{let t=ep.create("idb-get",{originalErrorMessage:null==e?void 0:e.message});es.warn(t.message)}}}async function eI(e,t){try{let n=(await ev()).transaction(em,"readwrite"),i=n.objectStore(em);await i.put(t,eC(e)),await n.done}catch(e){if(e instanceof E)es.warn(e.message);else{let t=ep.create("idb-set",{originalErrorMessage:null==e?void 0:e.message});es.warn(t.message)}}}function eC(e){return`${e.name}!${e.options.appId}`}class eb{constructor(e){this.container=e,this._heartbeatsCache=null;const t=this.container.getProvider("app").getImmediate();this._storage=new eT(t),this._heartbeatsCachePromise=this._storage.read().then(e=>(this._heartbeatsCache=e,e))}async triggerHeartbeat(){var e,t;try{let n=this.container.getProvider("platform-logger").getImmediate().getPlatformInfoString(),i=eE();if((null==(e=this._heartbeatsCache)?void 0:e.heartbeats)==null&&(this._heartbeatsCache=await this._heartbeatsCachePromise,(null==(t=this._heartbeatsCache)?void 0:t.heartbeats)==null)||this._heartbeatsCache.lastSentHeartbeatDate===i||this._heartbeatsCache.heartbeats.some(e=>e.date===i))return;return this._heartbeatsCache.heartbeats.push({date:i,agent:n}),this._heartbeatsCache.heartbeats=this._heartbeatsCache.heartbeats.filter(e=>{let t=new Date(e.date).valueOf();return Date.now()-t<=2592e6}),this._storage.overwrite(this._heartbeatsCache)}catch(e){es.warn(e)}}async getHeartbeatsHeader(){var e;try{if(null===this._heartbeatsCache&&await this._heartbeatsCachePromise,(null==(e=this._heartbeatsCache)?void 0:e.heartbeats)==null||0===this._heartbeatsCache.heartbeats.length)return"";let t=eE(),{heartbeatsToSend:n,unsentEntries:i}=function(e,t=1024){let n=[],i=e.slice();for(let r of e){let e=n.find(e=>e.agent===r.agent);if(e){if(e.dates.push(r.date),eS(n)>t){e.dates.pop();break}}else if(n.push({agent:r.agent,dates:[r.date]}),eS(n)>t){n.pop();break}i=i.slice(1)}return{heartbeatsToSend:n,unsentEntries:i}}(this._heartbeatsCache.heartbeats),r=f(JSON.stringify({version:2,heartbeats:n}));return this._heartbeatsCache.lastSentHeartbeatDate=t,i.length>0?(this._heartbeatsCache.heartbeats=i,await this._storage.overwrite(this._heartbeatsCache)):(this._heartbeatsCache.heartbeats=[],this._storage.overwrite(this._heartbeatsCache)),r}catch(e){return es.warn(e),""}}}function eE(){return new Date().toISOString().substring(0,10)}class eT{constructor(e){this.app=e,this._canUseIndexedDBPromise=this.runIndexedDBEnvironmentCheck()}async runIndexedDBEnvironmentCheck(){return!!C()&&b().then(()=>!0).catch(()=>!1)}async read(){if(!await this._canUseIndexedDBPromise)return{heartbeats:[]};{let e=await ew(this.app);return(null==e?void 0:e.heartbeats)?e:{heartbeats:[]}}}async overwrite(e){var t;if(await this._canUseIndexedDBPromise){let n=await this.read();return eI(this.app,{lastSentHeartbeatDate:null!=(t=e.lastSentHeartbeatDate)?t:n.lastSentHeartbeatDate,heartbeats:e.heartbeats})}}async add(e){var t;if(await this._canUseIndexedDBPromise){let n=await this.read();return eI(this.app,{lastSentHeartbeatDate:null!=(t=e.lastSentHeartbeatDate)?t:n.lastSentHeartbeatDate,heartbeats:[...n.heartbeats,...e.heartbeats]})}}}function eS(e){return f(JSON.stringify({version:2,heartbeats:e})).length}ed(new D("platform-logger",e=>new en(e),"PRIVATE")),ed(new D("heartbeat",e=>new eb(e),"PRIVATE")),eg(ei,er,""),eg(ei,er,"esm2017"),eg("fire-js",""),e.s(["SDK_VERSION",0,"10.14.1","_getProvider",0,function(e,t){let n=e.container.getProvider("heartbeat").getImmediate({optional:!0});return n&&n.triggerHeartbeat(),e.container.getProvider(t)},"_isFirebaseServerApp",0,function(e){return void 0!==e.settings},"_registerComponent",0,ed,"getApp",0,function(e=eo){let t=el.get(e);if(!t&&e===eo&&y())return e_();if(!t)throw ep.create("no-app",{appName:e});return t},"initializeApp",0,e_,"registerVersion",0,eg],485086)},151718,854762,e=>{"use strict";var t,n=e.i(485086),i=e.i(733015),r=e.i(68483),s=e.i(290571),o=e.i(965233);function a(){return{"dependent-sdk-initialized-before-auth":"Another Firebase SDK was initialized and is trying to use Auth before Auth is initialized. Please be sure to call `initializeAuth` or `getAuth` before starting any other Firebase SDK."}}let l=new i.ErrorFactory("auth","Firebase",a()),h=new r.Logger("@firebase/auth");function c(e,...t){h.logLevel<=r.LogLevel.ERROR&&h.error(`Auth (${n.SDK_VERSION}): ${e}`,...t)}function u(e,...t){throw _(e,...t)}function d(e,...t){return _(e,...t)}function p(e,t,n){let r=Object.assign(Object.assign({},a()),{[t]:n});return new i.ErrorFactory("auth","Firebase",r).create(t,{appName:e.n
1ame})}function f(e){return p(e,"operation-not-supported-in-this-environment","Operations that alter the current user are not supported in conjunction with FirebaseServerApp")}function _(e,...t){if("string"!=typeof e){let n=t[0],i=[...t.slice(1)];return i[0]&&(i[0].appName=e.name),e._errorFactory.create(n,...i)}return l.create(e,...t)}function g(e,t,...n){if(!e)throw _(t,...n)}function m(e){let t="INTERNAL ASSERTION FAILED: "+e;throw c(t),Error(t)}function y(){var e;return"u">typeof self&&(null==(e=self.location)?void 0:e.href)||""}function v(){var e;return"u">typeof self&&(null==(e=self.location)?void 0:e.protocol)||null}class w{constructor(e,t){this.shortDelay=e,this.longDelay=t,function(e,t){e||m(t)}(t>e,"Short delay should be less than long delay!"),this.isMobile=(0,i.isMobileCordova)()||(0,i.isReactNative)()}get(){return!("u">typeof navigator&&navigator&&"onLine"in navigator&&"boolean"==typeof navigator.onLine&&("http:"===v()||"https:"===v()||(0,i.isBrowserExtension)()||"connection"in navigator))||navigator.onLine?this.isMobile?this.longDelay:this.shortDelay:Math.min(5e3,this.shortDelay)}}function I(e,t){var n,i;n=e.emulator,i="Emulator should always be set here",n||m(i);let{url:r}=e.emulator;return t?`${r}${t.startsWith("/")?t.slice(1):t}`:r}class C{static initialize(e,t,n){this.fetchImpl=e,t&&(this.headersImpl=t),n&&(this.responseImpl=n)}static fetch(){return this.fetchImpl?this.fetchImpl:"u">typeof self&&"fetch"in self?self.fetch:"u">typeof globalThis&&globalThis.fetch?globalThis.fetch:"u">typeof fetch?fetch:void m("Could not find fetch implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill")}static headers(){return this.headersImpl?this.headersImpl:"u">typeof self&&"Headers"in self?self.Headers:"u">typeof globalThis&&globalThis.Headers?globalThis.Headers:"u">typeof Headers?Headers:void m("Could not find Headers implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill")}static response(){return this.responseImpl?this.responseImpl:"u">typeof self&&"Response"in self?self.Response:"u">typeof globalThis&&globalThis.Response?globalThis.Response:"u">typeof Response?Response:void m("Could not find Response implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill")}}let b={CREDENTIAL_MISMATCH:"custom-token-mismatch",MISSING_CUSTOM_TOKEN:"internal-error",INVALID_IDENTIFIER:"invalid-email",MISSING_CONTINUE_URI:"internal-error",INVALID_PASSWORD:"wrong-password",MISSING_PASSWORD:"missing-password",INVALID_LOGIN_CREDENTIALS:"invalid-credential",EMAIL_EXISTS:"email-already-in-use",PASSWORD_LOGIN_DISABLED:"operation-not-allowed",INVALID_IDP_RESPONSE:"invalid-credential",INVALID_PENDING_TOKEN:"invalid-credential",FEDERATED_USER_ID_ALREADY_LINKED:"credential-already-in-use",MISSING_REQ_TYPE:"internal-error",EMAIL_NOT_FOUND:"user-not-found",RESET_PASSWORD_EXCEED_LIMIT:"too-many-requests",EXPIRED_OOB_CODE:"expired-action-code",INVALID_OOB_CODE:"invalid-action-code",MISSING_OOB_CODE:"internal-error",CREDENTIAL_TOO_OLD_LOGIN_AGAIN:"requires-recent-login",INVALID_ID_TOKEN:"invalid-user-token",TOKEN_EXPIRED:"user-token-expired",USER_NOT_FOUND:"user-token-expired",TOO_MANY_ATTEMPTS_TRY_LATER:"too-many-requests",PASSWORD_DOES_NOT_MEET_REQUIREMENTS:"password-does-not-meet-requirements",INVALID_CODE:"invalid-verification-code",INVALID_SESSION_INFO:"invalid-verification-id",INVALID_TEMPORARY_PROOF:"invalid-credential",MISSING_SESSION_INFO:"missing-verification-id",SESSION_EXPIRED:"code-expired",MISSING_ANDROID_PACKAGE_NAME:"missing-android-pkg-name",UNAUTHORIZED_DOMAIN:"unauthorized-continue-uri",INVALID_OAUTH_CLIENT_ID:"invalid-oauth-client-id",ADMIN_ONLY_OPERATION:"admin-restricted-operation",INVALID_MFA_PENDING_CREDENTIAL:"invalid-multi-factor-session",MFA_ENROLLMENT_NOT_FOUND:"multi-factor-info-not-found",MISSING_MFA_ENROLLMENT_ID:"missing-multi-factor-info",MISSING_MFA_PENDING_CREDENTIAL:"missing-multi-factor-session",SECOND_FACTOR_EXISTS:"second-factor-already-in-use",SECOND_FACTOR_LIMIT_EXCEEDED:"maximum-second-factor-count-exceeded",BLOCKING_FUNCTION_ERROR_RESPONSE:"internal-error",RECAPTCHA_NOT_ENABLED:"recaptcha-not-enabled",MISSING_RECAPTCHA_TOKEN:"missing-rec
1aptcha-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"},E=new w(3e4,6e4);function T(e,t){return e.tenantId&&!t.tenantId?Object.assign(Object.assign({},t),{tenantId:e.tenantId}):t}async function S(e,t,n,r,s={}){return k(e,s,async()=>{let s={},o={};r&&("GET"===t?o=r:s={body:JSON.stringify(r)});let a=(0,i.querystring)(Object.assign({key:e.config.apiKey},o)).slice(1),l=await e._getAdditionalHeaders();l["Content-Type"]="application/json",e.languageCode&&(l["X-Firebase-Locale"]=e.languageCode);let h=Object.assign({method:t,headers:l},s);return(0,i.isCloudflareWorker)()||(h.referrerPolicy="no-referrer"),C.fetch()(N(e,e.config.apiHost,n,a),h)})}async function k(e,t,n){e._canInitEmulator=!1;let r=Object.assign(Object.assign({},b),t);try{let t=new R(e),i=await Promise.race([n(),t.promise]);t.clearNetworkTimeout();let s=await i.json();if("needConfirmation"in s)throw A(e,"account-exists-with-different-credential",s);if(i.ok&&!("errorMessage"in s))return s;{let[t,n]=(i.ok?s.errorMessage:s.error.message).split(" : ");if("FEDERATED_USER_ID_ALREADY_LINKED"===t)throw A(e,"credential-already-in-use",s);if("EMAIL_EXISTS"===t)throw A(e,"email-already-in-use",s);if("USER_DISABLED"===t)throw A(e,"user-disabled",s);let o=r[t]||t.toLowerCase().replace(/[_\s]+/g,"-");if(n)throw p(e,o,n);u(e,o)}}catch(t){if(t instanceof i.FirebaseError)throw t;u(e,"network-request-failed",{message:String(t)})}}async function P(e,t,n,i,r={}){let s=await S(e,t,n,i,r);return"mfaPendingCredential"in s&&u(e,"multi-factor-auth-required",{_serverResponse:s}),s}function N(e,t,n,i){let r=`${t}${n}?${i}`;return e.config.emulator?I(e.config,r):`${e.config.apiScheme}://${r}`}class R{constructor(e){this.auth=e,this.timer=null,this.promise=new Promise((e,t)=>{this.timer=setTimeout(()=>t(d(this.auth,"network-request-failed")),E.get())})}clearNetworkTimeout(){clearTimeout(this.timer)}}function A(e,t,n){let i={appName:e.name};n.email&&(i.email=n.email),n.phoneNumber&&(i.phoneNumber=n.phoneNumber);let r=d(e,t,i);return r.customData._tokenResponse=n,r}function O(e){return void 0!==e&&void 0!==e.enterprise}class D{constructor(e){if(this.siteKey="",this.recaptchaEnforcementState=[],void 0===e.recaptchaKey)throw Error("recaptchaKey undefined");this.siteKey=e.recaptchaKey.split("/")[3],this.recaptchaEnforcementState=e.recaptchaEnforcementState}getProviderEnforcementState(e){if(!this.recaptchaEnforcementState||0===this.recaptchaEnforcementState.length)return null;for(let t of this.recaptchaEnforcementState)if(t.provider&&t.provider===e)switch(t.enforcementState){case"ENFORCE":return"ENFORCE";case"AUDIT":return"AUDIT";case"OFF":return"OFF";default:return"ENFORCEMENT_STATE_UNSPECIFIED"}return null}isProviderEnabled(e){return"ENFORCE"===this.getProviderEnforcementState(e)||"AUDIT"===this.getProviderEnforcementState(e)}}async function x(e,t){return S(e,"GET","/v2/recaptchaConfig",T(e,t))}async function L(e,t){return S(e,"POST","/v1/accounts:delete",t)}async function M(e,t){return S(e,"POST","/v1/accounts:lookup",t)}function F(e){if(e)try{let t=new Date(Number(e));if(!isNaN(t.getTime()))return t.toUTCString()}catch(e){}}async function U(e,t=!1){let n=(0,i.getModularInstance)(e),r=await n.getIdToken(t),s=j(r);g(s&&s.exp&&s.auth_time&&s.iat,n.auth,"internal-error");let o="object"==typeof s.firebase?s.firebase:void 0,a=null==o?void 0:o.sign_in_provider;return{claims:s,token:r,authTime:F(q(s.auth_time)),issuedAtTime:F(q(s.iat)),expirationTime:F(q(s.exp)),signInProvider:a||null,signInSecondFactor:(null==o?void 0:o.sign_in_second_factor)||null}}function q(e){return 1e3*Number(e)}function j(e){let[t,n,r]=e.split(".");if(void 0===t||void 0===n||void 0===r)return c("JWT malformed, contained fewer than 3 sections"),null;try{let e=(0,i.base64Decode)(n);if(!e)return c("Failed to decode base64 JWT payload"),null;return JSON.parse(e)}catch(e){return c("Caught error parsing JWT payload as JSON",null==e?void 0:e.toString()),null}}function W(e){let t=j(e);return g(t,"internal-error"),g(void 0!==t.exp,"internal-error"),g(void 0!==t.iat,"internal-error"),Number(t.exp)-Number(t.iat)}async function V(e,t,n=!1){if(n)return t;try{return await t}catch(t){throw t instanceof i.FirebaseError&&function({code:e}){return"auth/user-disabled"===e||"auth/user-token-expired"===e}(t)&&e.auth.currentUser===e&&await e.auth.signOut(),t}}class H{constructor(e){this.user=e,this.isRunning=!1,this.timerId=null,this.errorBackoff=3e4}_start(){this.isRunning||(this.isRunning=!0,this.schedule())}_stop(){this.isRunning&&(this.isRunning=!1,null!==this.timerId&&clearTimeout(this.timerId))}getInterval(e){var t;if(!e)return this.errorBackoff=3e4,Math.max(0,(null!=(t=this.user.stsTokenManager.expirationTime)?t:0)-Date.now()-3e5);{let e=this.errorBackoff;return this.errorBackoff=Math.min(2*this.errorBackoff,96e4),e}}schedule(e=!1){if(!this.isRunning)return;let t=this.getInterval(e);this.timerId=setTimeout(async()=>{await this.iteration()},t)}async iteration(){try{await this.user.getIdToken(!0)}catch(e){(null==e?void 0:e.code)==="auth/network-request-failed"&&this.schedule(!0);return}this.schedule()}}class B{constructor(e,t){this.createdAt=e,this.lastLoginAt=t,this._initializeTime()}_initializeTime(){this.lastSignInTime=F(this.lastLoginAt),this.creationTime=F(this.createdAt)}_copy(e){this.createdAt=e.createdAt,this.lastLoginAt=e.lastLoginAt,this._initializeTime()}toJSON(){return{createdAt:this.createdAt,lastLoginAt:this.lastLoginAt}}}async function z(e){var t,n,i;let r=e.auth,s=await e.getIdToken(),o=await V(e,M(r,{idToken:s}));g(null==o?void 0:o.users.length,r,"internal-error");let a=o.users[0];e._notifyReloadListener(a);let l=(null==(t=a.providerUserInfo)?void 0:t.length)?K(a.providerUserInfo):[],h=(n=e.providerData,i=l,[...n.filter(e=>!i.some(t=>t.providerId===e.providerId)),...i]),c=e.isAnonymous,u=!(e.email&&a.passwordHash)&&!(null==h?void 0:h.length);Object.assign(e,{uid:a.localId,displayName:a.displayName||null,photoURL:a.photoUrl||null,email:a.email||null,emailVerified:a.emailVerified||!1,phoneNumber:a.phoneNumber||null,tenantId:a.tenantId||null,providerData:h,metadata:new B(a.createdAt,a.lastLoginAt),isAnonymous:!!c&&u})}async function $(e){let t=(0,i.getModularInstance)(e);await z(t),await t.auth._persistUserIfCurrent(t),t.auth._notifyListenersIfCurrent(t)}function K(e){return e.map(e=>{var{providerId:t}=e,n=(0,s.__rest)(e,["providerId"]);
1return{providerId:t,uid:n.rawId||"",displayName:n.displayName||null,email:n.email||null,phoneNumber:n.phoneNumber||null,photoURL:n.photoUrl||null}})}async function G(e,t){let n=await k(e,{},async()=>{let n=(0,i.querystring)({grant_type:"refresh_token",refresh_token:t}).slice(1),{tokenApiHost:r,apiKey:s}=e.config,o=N(e,r,"/v1/token",`key=${s}`),a=await e._getAdditionalHeaders();return a["Content-Type"]="application/x-www-form-urlencoded",C.fetch()(o,{method:"POST",headers:a,body:n})});return{accessToken:n.access_token,expiresIn:n.expires_in,refreshToken:n.refresh_token}}async function Y(e,t){return S(e,"POST","/v2/accounts:revokeToken",T(e,t))}class J{constructor(){this.refreshToken=null,this.accessToken=null,this.expirationTime=null}get isExpired(){return!this.expirationTime||Date.now()>this.expirationTime-3e4}updateFromServerResponse(e){g(e.idToken,"internal-error"),g(void 0!==e.idToken,"internal-error"),g(void 0!==e.refreshToken,"internal-error");let t="expiresIn"in e&&void 0!==e.expiresIn?Number(e.expiresIn):W(e.idToken);this.updateTokensAndExpiration(e.idToken,e.refreshToken,t)}updateFromIdToken(e){g(0!==e.length,"internal-error");let t=W(e);this.updateTokensAndExpiration(e,null,t)}async getToken(e,t=!1){return t||!this.accessToken||this.isExpired?(g(this.refreshToken,e,"user-token-expired"),this.refreshToken)?(await this.refresh(e,this.refreshToken),this.accessToken):null:this.accessToken}clearRefreshToken(){this.refreshToken=null}async refresh(e,t){let{accessToken:n,refreshToken:i,expiresIn:r}=await G(e,t);this.updateTokensAndExpiration(n,i,Number(r))}updateTokensAndExpiration(e,t,n){this.refreshToken=t||null,this.accessToken=e||null,this.expirationTime=Date.now()+1e3*n}static fromJSON(e,t){let{refreshToken:n,accessToken:i,expirationTime:r}=t,s=new J;return n&&(g("string"==typeof n,"internal-error",{appName:e}),s.refreshToken=n),i&&(g("string"==typeof i,"internal-error",{appName:e}),s.accessToken=i),r&&(g("number"==typeof r,"internal-error",{appName:e}),s.expirationTime=r),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 J,this.toJSON())}_performRefresh(){return m("not implemented")}}function Q(e,t){g("string"==typeof e||void 0===e,"internal-error",{appName:t})}class X{constructor(e){var{uid:t,auth:n,stsTokenManager:i}=e,r=(0,s.__rest)(e,["uid","auth","stsTokenManager"]);this.providerId="firebase",this.proactiveRefresh=new H(this),this.reloadUserInfo=null,this.reloadListener=null,this.uid=t,this.auth=n,this.stsTokenManager=i,this.accessToken=i.accessToken,this.displayName=r.displayName||null,this.email=r.email||null,this.emailVerified=r.emailVerified||!1,this.phoneNumber=r.phoneNumber||null,this.photoURL=r.photoURL||null,this.isAnonymous=r.isAnonymous||!1,this.tenantId=r.tenantId||null,this.providerData=r.providerData?[...r.providerData]:[],this.metadata=new B(r.createdAt||void 0,r.lastLoginAt||void 0)}async getIdToken(e){let t=await V(this,this.stsTokenManager.getToken(this.auth,e));return g(t,this.auth,"internal-error"),this.accessToken!==t&&(this.accessToken=t,await this.auth._persistUserIfCurrent(this),this.auth._notifyListenersIfCurrent(this)),t}getIdTokenResult(e){return U(this,e)}reload(){return $(this)}_assign(e){this!==e&&(g(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=>Object.assign({},e)),this.metadata._copy(e.metadata),this.stsTokenManager._assign(e.stsTokenManager))}_clone(e){let t=new X(Object.assign(Object.assign({},this),{auth:e,stsTokenManager:this.stsTokenManager._clone()}));return t.metadata._copy(this.metadata),t}_onReload(e){g(!this.reloadListener,this.auth,"internal-error"),this.reloadListener=e,this.reloadUserInfo&&(this._notifyReloadListener(this.reloadUserInfo),this.reloadUserInfo=null)}_notifyReloadListener(e){this.reloadListener?this.reloadListener(e):this.reloadUserInfo=e}_startProactiveRefresh(){this.proactiveRefresh._start()}_stopProactiveRefresh(){this.proactiveRefresh._stop()}async _updateTokensIfNecessary(e,t=!1){let n=!1;e.idToken&&e.idToken!==this.stsTokenManager.accessToken&&(this.stsTokenManager.updateFromServerResponse(e),n=!0),t&&await z(this),await this.auth._persistUserIfCurrent(this),n&&this.auth._notifyListenersIfCurrent(this)}async delete(){if((0,n._isFirebaseServerApp)(this.auth.app))return Promise.reject(f(this.auth));let e=await this.getIdToken();return await V(this,L(this.auth,{idToken:e})),this.stsTokenManager.clearRefreshToken(),this.auth.signOut()}toJSON(){return Object.assign(Object.assign({uid:this.uid,email:this.email||void 0,emailVerified:this.emailVerified,displayName:this.displayName||void 0,isA
1nonymous:this.isAnonymous,photoURL:this.photoURL||void 0,phoneNumber:this.phoneNumber||void 0,tenantId:this.tenantId||void 0,providerData:this.providerData.map(e=>Object.assign({},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){var n,i,r,s,o,a,l,h;let c=null!=(n=t.displayName)?n:void 0,u=null!=(i=t.email)?i:void 0,d=null!=(r=t.phoneNumber)?r:void 0,p=null!=(s=t.photoURL)?s:void 0,f=null!=(o=t.tenantId)?o:void 0,_=null!=(a=t._redirectEventId)?a:void 0,m=null!=(l=t.createdAt)?l:void 0,y=null!=(h=t.lastLoginAt)?h:void 0,{uid:v,emailVerified:w,isAnonymous:I,providerData:C,stsTokenManager:b}=t;g(v&&b,e,"internal-error");let E=J.fromJSON(this.name,b);g("string"==typeof v,e,"internal-error"),Q(c,e.name),Q(u,e.name),g("boolean"==typeof w,e,"internal-error"),g("boolean"==typeof I,e,"internal-error"),Q(d,e.name),Q(p,e.name),Q(f,e.name),Q(_,e.name),Q(m,e.name),Q(y,e.name);let T=new X({uid:v,auth:e,email:u,emailVerified:w,displayName:c,isAnonymous:I,photoURL:p,phoneNumber:d,tenantId:f,stsTokenManager:E,createdAt:m,lastLoginAt:y});return C&&Array.isArray(C)&&(T.providerData=C.map(e=>Object.assign({},e))),_&&(T._redirectEventId=_),T}static async _fromIdTokenResponse(e,t,n=!1){let i=new J;i.updateFromServerResponse(t);let r=new X({uid:t.localId,auth:e,stsTokenManager:i,isAnonymous:n});return await z(r),r}static async _fromGetAccountInfoResponse(e,t,n){let i=t.users[0];g(void 0!==i.localId,"internal-error");let r=void 0!==i.providerUserInfo?K(i.providerUserInfo):[],s=!(i.email&&i.passwordHash)&&!(null==r?void 0:r.length),o=new J;o.updateFromIdToken(n);let a=new X({uid:i.localId,auth:e,stsTokenManager:o,isAnonymous:s});return Object.assign(a,{uid:i.localId,displayName:i.displayName||null,photoURL:i.photoUrl||null,email:i.email||null,emailVerified:i.emailVerified||!1,phoneNumber:i.phoneNumber||null,tenantId:i.tenantId||null,providerData:r,metadata:new B(i.createdAt,i.lastLoginAt),isAnonymous:!(i.email&&i.passwordHash)&&!(null==r?void 0:r.length)}),a}}let Z=new Map;function ee(e){var t,n;t="Expected a class definition",e instanceof Function||m(t);let i=Z.get(e);return i?(n="Instance stored in cache mismatched with class",i instanceof e||m(n)):(i=new e,Z.set(e,i)),i}class et{constructor(){this.type="NONE",this.storage={}}async _isAvailable(){return!0}async _set(e,t){this.storage[e]=t}async _get(e){let t=this.storage[e];return void 0===t?null:t}async _remove(e){delete this.storage[e]}_addListener(e,t){}_removeListener(e,t){}}function en(e,t,n){return`firebase:${e}:${t}:${n}`}et.type="NONE";class ei{constructor(e,t,n){this.persistence=e,this.auth=t,this.userKey=n;const{config:i,name:r}=this.auth;this.fullUserKey=en(this.userKey,i.apiKey,r),this.fullPersistenceKey=en("persistence",i.apiKey,r),this.boundEventHandler=t._onStorageEvent.bind(t),this.persistence._addListener(this.fullUserKey,this.boundEventHandler)}setCurrentUser(e){return this.persistence._set(this.fullUserKey,e.toJSON())}async getCurrentUser(){let e=await this.persistence._get(this.fullUserKey);return e?X._fromJSON(this.auth,e):null}removeCurrentUser(){return this.persistence._remove(this.fullUserKey)}savePersistenceForRedirect(){return this.persistence._set(this.fullPersistenceKey,this.persistence.type)}async setPersistence(e){if(this.persistence===e)return;let t=await this.getCurrentUser();if(await this.removeCurrentUser(),this.persistence=e,t)return this.setCurrentUser(t)}delete(){this.persistence._removeListener(this.fullUserKey,this.boundEventHandler)}static async create(e,t,n="authUser"){if(!t.length)return new ei(ee(et),e,n);let i=(await Promise.all(t.map(async e=>{if(await e._isAvailable())return e}))).filter(e=>e),r=i[0]||ee(et),s=en(n,e.config.apiKey,e.name),o=null;for(let n of t)try{let t=await n._get(s);if(t){let i=X._fromJSON(e,t);n!==r&&(o=i),r=n;break}}catch(e){}let a=i.filter(e=>e._shouldAllowMigration);return r._shouldAllowMigration&&a.length&&(r=a[0],o&&await r._set(s,o.toJSON()),await Promise.all(t.map(async e=>{if(e!==r)try{await e._remove(s)}catch(e){}}))),new ei(r,e,n)}}function er(e){let t=e.toLowerCase();if(t.includes("opera/")||t.includes("opr/")||t.includes("opios/"))return"Opera";{if(el(t))return"IEMobile";if(t.includes("msie")||t.includes("trident/"))return"IE";if(t.includes("edge/"))return"Edge";if(es(t))return"Firefox";if(t.includes("silk/"))return"Silk";if(ec(t))return"Blackberry";if(eu(t))return"Webos";if(eo(t))return"Safari";if((t.includes("chrome/")||ea(t))&&!t.includes("edge/"))return"Chrome";if(eh(t))return"Android";let n=e.match(/([a-zA-Z\d\.]+)\/[a-zA-Z\d\.]*$/);if((null==n?void 0:n.length)===2)return n[1]}return"Other"}function es(e=(0,i.getUA)()){return/firefox\//i.test(e)}function eo(e=(0,i.getUA)()){let t=e.toLowerCase();return t.includes("safari/")&&!t.includes("chrome/")&&!t.includes("crios/")&&!t.includes("android")}function ea(e=(0,i.getUA)()){return/crios\//i.test(e)}function el(e=(0,i.getUA)()){return/iemobile/i.test(e)}function eh(e=(0,i.getUA)()){return/android/i.test(e)}function ec(e=(0,i.getUA)()){return/blackberry/i.test(e)}function eu(e=(0,i.getUA)()){return/webos/i.test(e)}function ed(e=(0,i.getUA)()){return/iphone|ipad|ipod/i.test(e)||/macintosh/i.test(e)&&/mobile/i.test(e)}function ep(e=(0,i.getUA)()){return ed(e)||eh(e)||eu(e)||ec(e)||/windows phone/i.test(e)||el(e)}function ef(e,t=[]){let r;switch(e){case"Browser":r=er((0,i.getUA)());break;case"Worker":r=`${er((0,i.getUA)())}-${e}`;break;default:r=e}let s=t.length?t.join(","):"FirebaseCore-web";return`${r}/JsCore/${n.SDK_VERSION}/${s}`}class e_{constructor(e){this.auth=e,this.queue=[]}pushCallback(e,t){let n=t=>new Promise((n,i)=>{try{let i=e(t);n(i)}catch(e){i(e)}});n.onAbort=t,this.queue.push(n);let i=this.queue.length-1;return()=>{this.queue[i]=()=>Promise.resolve()}}async runMiddleware(e){if(this.auth.currentUser===e)return;let t=[];try{for(let n of this.queue)await n(e),n.onAbort&&t.push(n.onAbort)}catch(e){for(let e of(t.reverse(),t))try{e()}catch(e){}throw this.auth._errorFactory.create("login-blocked",{originalMessage:null==e?void 0:e.message})}}}async function eg(e,t={}){return S(e,"GET","/v2/passwordPolicy",T(e,t))}class em{constructor(e){var t,n,i,r;const s=e.customStrengthOptions;this.customStrengthOptions={},this.customStrengthOptions.minPasswordLength=null!=(t=s.minPasswordLength)?t:6,s.maxPasswordLength&&(this.customStrengthOptions.maxPasswordLength=s.maxPasswordLength),void 0!==s.containsLowercaseCharacter&&(this.customStrengthOptions.containsLowercaseLetter=s.containsLowercaseCharacter),void 0!==s.containsUppercaseCharacter&&(this.customStrengthOptions.containsUppercaseLetter=s.containsUppercaseCharacter),void 0!==s.containsNumericCharacter&&(this.customStrengthOptions.containsNumericCharacter=s.containsNumericCharacter),void 0!==s.containsNonAlphanumericCharacter&&(this.customStrengthOptions.containsNonAlphanumericCharacter=s.containsNonAlphanumericCharacter),this.enforcementState=e.enforcementState,"ENFORCEMENT_STATE_UNSPECIFIED"===this.enforcementState&&(this.enforcementState="OFF"),this.allowedNonAlphanumericCharacters=null!=(i=null==(n=e.allowedNonAlphanumericCharacters)?void 0:n.join(""))?i:"",this.forceUpgradeOnSignin=null!=(r=e.forceUpgradeOnSignin)&&r,this.schemaVersion=e.schemaVersion}validatePassword(e){var t,n,i,r,s,o;let a={isValid:!0,passwordPolicy:this};return this.validatePasswordLengthOptions(e,a),this.validatePasswordCharacterOptions(e,a),a.isValid&&
1(a.isValid=null==(t=a.meetsMinPasswordLength)||t),a.isValid&&(a.isValid=null==(n=a.meetsMaxPasswordLength)||n),a.isValid&&(a.isValid=null==(i=a.containsLowercaseLetter)||i),a.isValid&&(a.isValid=null==(r=a.containsUppercaseLetter)||r),a.isValid&&(a.isValid=null==(s=a.containsNumericCharacter)||s),a.isValid&&(a.isValid=null==(o=a.containsNonAlphanumericCharacter)||o),a}validatePasswordLengthOptions(e,t){let n=this.customStrengthOptions.minPasswordLength,i=this.customStrengthOptions.maxPasswordLength;n&&(t.meetsMinPasswordLength=e.length>=n),i&&(t.meetsMaxPasswordLength=e.length<=i)}validatePasswordCharacterOptions(e,t){let n;this.updatePasswordCharacterOptionsStatuses(t,!1,!1,!1,!1);for(let i=0;i<e.length;i++)n=e.charAt(i),this.updatePasswordCharacterOptionsStatuses(t,n>="a"&&n<="z",n>="A"&&n<="Z",n>="0"&&n<="9",this.allowedNonAlphanumericCharacters.includes(n))}updatePasswordCharacterOptionsStatuses(e,t,n,i,r){this.customStrengthOptions.containsLowercaseLetter&&(e.containsLowercaseLetter||(e.containsLowercaseLetter=t)),this.customStrengthOptions.containsUppercaseLetter&&(e.containsUppercaseLetter||(e.containsUppercaseLetter=n)),this.customStrengthOptions.containsNumericCharacter&&(e.containsNumericCharacter||(e.containsNumericCharacter=i)),this.customStrengthOptions.containsNonAlphanumericCharacter&&(e.containsNonAlphanumericCharacter||(e.containsNonAlphanumericCharacter=r))}}class ey{constructor(e,t,n,i){this.app=e,this.heartbeatServiceProvider=t,this.appCheckServiceProvider=n,this.config=i,this.currentUser=null,this.emulatorConfig=null,this.operations=Promise.resolve(),this.authStateSubscription=new ew(this),this.idTokenSubscription=new ew(this),this.beforeStateQueue=new e_(this),this.redirectUser=null,this.isProactiveRefreshEnabled=!1,this.EXPECTED_PASSWORD_POLICY_SCHEMA_VERSION=1,this._canInitEmulator=!0,this._isInitialized=!1,this._deleted=!1,this._initializationPromise=null,this._popupRedirectResolver=null,this._errorFactory=l,this._agentRecaptchaConfig=null,this._tenantRecaptchaConfigs={},this._projectPasswordPolicy=null,this._tenantPasswordPolicies={},this.lastNotifiedUid=void 0,this.languageCode=null,this.tenantId=null,this.settings={appVerificationDisabledForTesting:!1},this.frameworks=[],this.name=e.name,this.clientVersion=i.sdkClientVersion}_initializeWithPersistence(e,t){return t&&(this._popupRedirectResolver=ee(t)),this._initializationPromise=this.queue(async()=>{var n,i;if(!this._deleted){if(this.persistenceManager=await ei.create(this,e),!this._deleted){if(null==(n=this._popupRedirectResolver)?void 0:n._shouldInitProactively)try{await this._popupRedirectResolver._initialize(this)}catch(e){}await this.initializeCurrentUser(t),this.lastNotifiedUid=(null==(i=this.currentUser)?void 0:i.uid)||null,this._deleted||(this._isInitialized=!0)}}}),this._initializationPromise}async _onStorageEvent(){if(this._deleted)return;let e=await this.assertedPersistence.getCurrentUser();if(this.currentUser||e){if(this.currentUser&&e&&this.currentUser.uid===e.uid){this._currentUser._assign(e),await this.currentUser.getIdToken();return}await this._updateCurrentUser(e,!0)}}async initializeCurrentUserFromIdToken(e){try{let t=await M(this,{idToken:e}),n=await X._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){var t;if((0,n._isFirebaseServerApp)(this.app)){let e=this.app.settings.authIdToken;return e?new Promise(t=>{setTimeout(()=>this.initializeCurrentUserFromIdToken(e).then(t,t))}):this.directlySetCurrentUser(null)}let i=await this.assertedPersistence.getCurrentUser(),r=i,s=!1;if(e&&this.config.authDomain){await this.getOrInitRedirectPersistenceManager();let n=null==(t=this.redirectUser)?void 0:t._redirectEventId,i=null==r?void 0:r._redirectEventId,o=await this.tryRedirectSignIn(e);(!n||n===i)&&(null==o?void 0:o.user)&&(r=o.user,s=!0)}if(!r)return this.directlySetCurrentUser(null);if(!r._redirectEventId){if(s)try{await this.beforeStateQueue.runMiddleware(r)}catch(e){r=i,this._popupRedirectResolver._overrideRedirectResult(this,()=>Promise.reject(e))}return r?this.reloadAndSetCurrentUserOrClear(r):this.directlySetCurrentUser(null)}return(g(this._popupRedirectResolver,this,"argument-error"),await this.getOrInitRedirectPersistenceManager(),this.redirectUser&&this.redirectUser._redirectEventId===r._redirectEventId)?this.directlySetCurrentUser(r):this.reloadAndSetCurrentUserOrClear(r)}async tryRedirectSignIn(e){let t=null;try{t=await this._popupRedirectResolver._completeRedirectFn(this,e,!0)}catch(e){await this._setRedirectUser(null)}return t}async reloadAndSetCurrentUserOrClear(e){try{await z(e)}catch(e){if((null==e?void 0:e.code)!=="auth/network-request-failed")return this.directlySetCurrentUser(null)}return this.directlySetCurrentUser(e)}useDeviceLanguage(){this.languageCode=function(){if("u"<typeof navigator)return null;let e=navigator;return e.languages&&e.languages[0]||e.language||null}()}async _delete(){this._deleted=!0}
1async updateCurrentUser(e){if((0,n._isFirebaseServerApp)(this.app))return Promise.reject(f(this));let t=e?(0,i.getModularInstance)(e):null;return t&&g(t.auth.config.apiKey===this.config.apiKey,this,"invalid-user-token"),this._updateCurrentUser(t&&t._clone(this))}async _updateCurrentUser(e,t=!1){if(!this._deleted)return e&&g(this.tenantId===e.tenantId,this,"tenant-id-mismatch"),t||await this.beforeStateQueue.runMiddleware(e),this.queue(async()=>{await this.directlySetCurrentUser(e),this.notifyAuthListeners()})}async signOut(){return(0,n._isFirebaseServerApp)(this.app)?Promise.reject(f(this)):(await this.beforeStateQueue.runMiddleware(null),(this.redirectPersistenceManager||this._popupRedirectResolver)&&await this._setRedirectUser(null),this._updateCurrentUser(null,!0))}setPersistence(e){return(0,n._isFirebaseServerApp)(this.app)?Promise.reject(f(this)):this.queue(async()=>{await this.assertedPersistence.setPersistence(ee(e))})}_getRecaptchaConfig(){return null==this.tenantId?this._agentRecaptchaConfig:this._tenantRecaptchaConfigs[this.tenantId]}async validatePassword(e){this._getPasswordPolicyInternal()||await this._updatePasswordPolicy();let t=this._getPasswordPolicyInternal();return t.schemaVersion!==this.EXPECTED_PASSWORD_POLICY_SCHEMA_VERSION?Promise.reject(this._errorFactory.create("unsupported-password-policy-schema-version",{})):t.validatePassword(e)}_getPasswordPolicyInternal(){return null===this.tenantId?this._projectPasswordPolicy:this._tenantPasswordPolicies[this.tenantId]}async _updatePasswordPolicy(){let e=new em(await eg(this));null===this.tenantId?this._projectPasswordPolicy=e:this._tenantPasswordPolicies[this.tenantId]=e}_getPersistence(){return this.assertedPersistence.persistence.type}_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{let n=this.onAuthStateChanged(()=>{n(),e()},t)}})}async revokeAccessToken(e){if(this.currentUser){let t={providerId:"apple.com",tokenType:"ACCESS_TOKEN",token:e,idToken:await this.currentUser.getIdToken()};null!=this.tenantId&&(t.tenantId=this.tenantId),await Y(this,t)}}toJSON(){var e;return{apiKey:this.config.apiKey,authDomain:this.config.authDomain,appName:this.name,currentUser:null==(e=this._currentUser)?void 0:e.toJSON()}}async _setRedirectUser(e,t){let n=await this.getOrInitRedirectPersistenceManager(t);return null===e?n.removeCurrentUser():n.setCurrentUser(e)}async getOrInitRedirectPersistenceManager(e){if(!this.redirectPersistenceManager){let t=e&&ee(e)||this._popupRedirectResolver;g(t,this,"argument-error"),this.redirectPersistenceManager=await ei.create(this,[ee(t._redirectPersistence)],"redirectUser"),this.redirectUser=await this.redirectPersistenceManager.getCurrentUser()}return this.redirectPersistenceManager}async _redirectUserForId(e){var t,n;return(this._isInitialized&&await this.queue(async()=>{}),(null==(t=this._currentUser)?void 0:t._redirectEventId)===e)?this._currentUser:(null==(n=this.redirectUser)?void 0:n._redirectEventId)===e?this.redirectUser:null}async _persistUserIfCurrent(e){if(e===this.currentUser)return this.queue(async()=>this.directlySetCurrentUser(e))}_notifyListenersIfCurrent(e){e===this.currentUser&&this.notifyAuthListeners()}_key(){return`${this.config.authDomain}:${this.config.apiKey}:${this.name}`}_startProactiveRefresh(){this.isProactiveRefreshEnabled=!0,this.currentUser&&this._currentUser._startProactiveRefresh()}_stopProactiveRefresh(){this.isProactiveRefreshEnabled=!1,this.currentUser&&this._currentUser._stopProactiveRefresh()}get _currentUser(){return this.currentUser}notifyAuthListeners(){var e,t;if(!this._isInitialized)return;this.idTokenSubscription.next(this.currentUser);let n=null!=(t=null==(e=this.currentUser)?void 0:e.uid)?t:null;this.lastNotifiedUid!==n&&(this.lastNotifiedUid=n,this.authStateSubscription.next(this.currentUser))}registerStateListener(e,t,n,i){if(this._deleted)return()=>{};let r="function"==typeof t?t:t.next.bind(t),s=!1,o=this._isInitialized?Promise.resolve():this._initializationPromise;if(g(o,this,"internal-error"),o.then(()=>{s||r(this.currentUser)}),"function"==typeof t){let r=e.addObserver(t,n,i);return()=>{s=!0,r()}}{let n=e.addObserver(t);return()=>{s=!0,n()}}}async directlySetCurrentUser(e){this.currentUser&&this.currentUser!==e&&this._currentUser._stopProactiveRefresh(),e&&this.isProactiveRefreshEnabled&&e._startProactiveRefresh(),this.currentUser=e,e?await this.assertedPersistence.setCurrentUser(e):await this.assertedPersistence.removeCurrentUser()}queue(e){return this.operations=this.operations.then(e,e),this.operations}get assertedPersistence(){return g(this.persistenceManager,this,"internal-error"),this.persistenceManager}_logFramework(e){!e||this.frameworks.includes(e)||(this.frameworks.push(e),this.frameworks.sort(),this.clientVersion=ef(this.config.clientPlatform,this._getFrameworks()))}_getFrameworks(){return this.frameworks}async _getAdditionalHeaders(){var e;let t={"X-Client-Version":this.clientVersion};this.app.options.appId&&(t["X-Firebase-gmpid"]=this.app.options.appId);let n=await (null==(e=this.heartbeatServiceProvider.getImmediate({optional:!0}))?void 0:e.getHeartbeatsHeader());n&&(t["X-Firebase-Client"]=n);let i=await this._getAppCheckToken();return i&&(t["X-Firebase-AppCheck"]=i),t}async _getAppCheckToken(){var e;let t=await (null==(e=this.appCheckServiceProvider.getImmediate({optional:!0}))?void 0:e.getToken());return(null==t?void 0:t.error)&&function(e,...t){h.logLevel<=r.LogLevel.WARN&&h.warn(`Auth (${n.SDK_VERSION}): ${e}`,...t)}(`Error while retrieving App Check token: ${t.error}`),null==t?void 0:t.token}}function ev(e){return(0,i.getModularInstance)(e)}class ew{constructor(e){this.auth=e,this.observer=null,this.addObserver=(0,i.createSubscribe)(e=>this.observer=e)}get next(){return g(this.observer,this.auth,"internal-error"),this.observer.next.bind(this.observer)}}let eI={async loadJS(){throw Error("Unable to load external scripts")},recaptchaV2Script:"",recaptchaEnterpriseScript:"",gapiScript:""};function eC(e){return`__${e}${Math.floor(1e6*Math.random())}`}class eb{constructor(e){this.type="recaptcha-enterprise",this.auth=ev
1(e)}async verify(e="verify",t=!1){async function n(e){if(!t){if(null==e.tenantId&&null!=e._agentRecaptchaConfig)return e._agentRecaptchaConfig.siteKey;if(null!=e.tenantId&&void 0!==e._tenantRecaptchaConfigs[e.tenantId])return e._tenantRecaptchaConfigs[e.tenantId].siteKey}return new Promise(async(t,n)=>{x(e,{clientType:"CLIENT_TYPE_WEB",version:"RECAPTCHA_ENTERPRISE"}).then(i=>{if(void 0===i.recaptchaKey)n(Error("recaptcha Enterprise site key undefined"));else{let n=new D(i);return null==e.tenantId?e._agentRecaptchaConfig=n:e._tenantRecaptchaConfigs[e.tenantId]=n,t(n.siteKey)}}).catch(e=>{n(e)})})}function i(t,n,i){let r=window.grecaptcha;O(r)?r.enterprise.ready(()=>{r.enterprise.execute(t,{action:e}).then(e=>{n(e)}).catch(()=>{n("NO_RECAPTCHA")})}):i(Error("No reCAPTCHA enterprise script loaded."))}return new Promise((e,r)=>{n(this.auth).then(n=>{if(!t&&O(window.grecaptcha))i(n,e,r);else{var s;if("u"<typeof window)return void r(Error("RecaptchaVerifier is only supported in browser"));let t=eI.recaptchaEnterpriseScript;0!==t.length&&(t+=n),(s=t,eI.loadJS(s)).then(()=>{i(n,e,r)}).catch(e=>{r(e)})}}).catch(e=>{r(e)})})}}async function eE(e,t,n,i=!1){let r,s=new eb(e);try{r=await s.verify(n)}catch(e){r=await s.verify(n,!0)}let o=Object.assign({},t);return i?Object.assign(o,{captchaResp:r}):Object.assign(o,{captchaResponse:r}),Object.assign(o,{clientType:"CLIENT_TYPE_WEB"}),Object.assign(o,{recaptchaVersion:"RECAPTCHA_ENTERPRISE"}),o}async function eT(e,t,n,i){var r;if(null==(r=e._getRecaptchaConfig())||!r.isProviderEnabled("EMAIL_PASSWORD_PROVIDER"))return i(e,t).catch(async r=>{if("auth/missing-recaptcha-token"!==r.code)return Promise.reject(r);{console.log(`${n} is protected by reCAPTCHA Enterprise for this project. Automatically triggering the reCAPTCHA flow and restarting the flow.`);let r=await eE(e,t,n,"getOobCode"===n);return i(e,r)}});{let r=await eE(e,t,n,"getOobCode"===n);return i(e,r)}}function eS(e){let t=e.indexOf(":");return t<0?"":e.substr(0,t+1)}function ek(e){if(!e)return null;let t=Number(e);return isNaN(t)?null:t}class eP{constructor(e,t){this.providerId=e,this.signInMethod=t}toJSON(){return m("not implemented")}_getIdTokenResponse(e){return m("not implemented")}_linkToIdToken(e,t){return m("not implemented")}_getReauthenticationResolver(e){return m("not implemented")}}async function eN(e,t){return S(e,"POST","/v1/accounts:signUp",t)}async function eR(e,t){return P(e,"POST","/v1/accounts:signInWithPassword",T(e,t))}async function eA(e,t){return P(e,"POST","/v1/accounts:signInWithEmailLink",T(e,t))}async function eO(e,t){return P(e,"POST","/v1/accounts:signInWithEmailLink",T(e,t))}class eD extends eP{constructor(e,t,n,i=null){super("password",n),this._email=e,this._password=t,this._tenantId=i}static _fromEmailAndPassword(e,t){return new eD(e,t,"password")}static _fromEmailAndCode(e,t,n=null){return new eD(e,t,"emailLink",n)}toJSON(){return{email:this._email,password:this._password,signInMethod:this.signInMethod,tenantId:this._tenantId}}static fromJSON(e){let t="string"==typeof e?JSON.parse(e):e;if((null==t?void 0:t.email)&&(null==t?void 0:t.password)){if("password"===t.signInMethod)return this._fromEmailAndPassword(t.email,t.password);else if("emailLink"===t.signInMethod)return this._fromEmailAndCode(t.email,t.password,t.tenantId)}return null}async _getIdTokenResponse(e){switch(this.signInMethod){case"password":return eT(e,{returnSecureToken:!0,email:this._email,password:this._password,clientType:"CLIENT_TYPE_WEB"},"signInWithPassword",eR);case"emailLink":return eA(e,{email:this._email,oobCode:this._password});default:u(e,"internal-error")}}async _linkToIdToken(e,t){switch(this.signInMethod){case"password":return eT(e,{idToken:t,returnSecureToken:!0,email:this._email,password:this._password,clientType:"CLIENT_TYPE_WEB"},"signUpPassword",eN);case"emailLink":return eO(e,{idToken:t,email:this._email,oobCode:this._password});default:u(e,"internal-error")}}_getReauthenticationResolver(e){return this._getIdTokenResponse(e)}}async function ex(e,t){return P(e,"POST","/v1/accounts:signInWithIdp",T(e,t))}class eL extends eP{constructor(){super(...arguments),this.pendingToken=null}static _fromParams(e){let t=new eL(e.providerId,e.signInMethod);return e.idToken||e.accessToken?(e.idToken&&(t.idToken=e.idToken),e.accessToken&&(t.accessToken=e.accessToken),e.nonce&&!e.pendingToken&&
1(t.nonce=e.nonce),e.pendingToken&&(t.pendingToken=e.pendingToken)):e.oauthToken&&e.oauthTokenSecret?(t.accessToken=e.oauthToken,t.secret=e.oauthTokenSecret):u("argument-error"),t}toJSON(){return{idToken:this.idToken,accessToken:this.accessToken,secret:this.secret,nonce:this.nonce,pendingToken:this.pendingToken,providerId:this.providerId,signInMethod:this.signInMethod}}static fromJSON(e){let t="string"==typeof e?JSON.parse(e):e,{providerId:n,signInMethod:i}=t,r=(0,s.__rest)(t,["providerId","signInMethod"]);if(!n||!i)return null;let o=new eL(n,i);return o.idToken=r.idToken||void 0,o.accessToken=r.accessToken||void 0,o.secret=r.secret,o.nonce=r.nonce,o.pendingToken=r.pendingToken||null,o}_getIdTokenResponse(e){return ex(e,this.buildRequest())}_linkToIdToken(e,t){let n=this.buildRequest();return n.idToken=t,ex(e,n)}_getReauthenticationResolver(e){let t=this.buildRequest();return t.autoCreate=!1,ex(e,t)}buildRequest(){let e={requestUri:"http://localhost",returnSecureToken:!0};if(this.pendingToken)e.pendingToken=this.pendingToken;else{let t={};this.idToken&&(t.id_token=this.idToken),this.accessToken&&(t.access_token=this.accessToken),this.secret&&(t.oauth_token_secret=this.secret),t.providerId=this.providerId,this.nonce&&!this.pendingToken&&(t.nonce=this.nonce),e.postBody=(0,i.querystring)(t)}return e}}async function eM(e,t){return S(e,"POST","/v1/accounts:sendVerificationCode",T(e,t))}async function eF(e,t){return P(e,"POST","/v1/accounts:signInWithPhoneNumber",T(e,t))}async function eU(e,t){let n=await P(e,"POST","/v1/accounts:signInWithPhoneNumber",T(e,t));if(n.temporaryProof)throw A(e,"account-exists-with-different-credential",n);return n}let eq={USER_NOT_FOUND:"user-not-found"};async function ej(e,t){return P(e,"POST","/v1/accounts:signInWithPhoneNumber",T(e,Object.assign(Object.assign({},t),{operation:"REAUTH"})),eq)}class eW extends eP{constructor(e){super("phone","phone"),this.params=e}static _fromVerification(e,t){return new eW({verificationId:e,verificationCode:t})}static _fromTokenResponse(e,t){return new eW({phoneNumber:e,temporaryProof:t})}_getIdTokenResponse(e){return eF(e,this._makeVerificationRequest())}_linkToIdToken(e,t){return eU(e,Object.assign({idToken:t},this._makeVerificationRequest()))}_getReauthenticationResolver(e){return ej(e,this._makeVerificationRequest())}_makeVerificationRequest(){let{temporaryProof:e,phoneNumber:t,verificationId:n,verificationCode:i}=this.params;return e&&t?{temporaryProof:e,phoneNumber:t}:{sessionInfo:n,code:i}}toJSON(){let e={providerId:this.providerId};return this.params.phoneNumber&&(e.phoneNumber=this.params.phoneNumber),this.params.temporaryProof&&(e.temporaryProof=this.params.temporaryProof),this.params.verificationCode&&(e.verificationCode=this.params.verificationCode),this.params.verificationId&&(e.verificationId=this.params.verificationId),e}static fromJSON(e){"string"==typeof e&&(e=JSON.parse(e));let{verificationId:t,verificationCode:n,phoneNumber:i,temporaryProof:r}=e;return n||t||i||r?new eW({verificationId:t,verificationCode:n,phoneNumber:i,temporaryProof:r}):null}}class eV{constructor(e){var t,n,r,s,o,a;const l=(0,i.querystringDecode)((0,i.extractQuerystring)(e)),h=null!=(t=l.apiKey)?t:null,c=null!=(n=l.oobCode)?n:null,u=function(e){switch(e){case"recoverEmail":return"RECOVER_EMAIL";case"resetPassword":return"PASSWORD_RESET";case"signIn":return"EMAIL_SIGNIN";case"verifyEmail":return"VERIFY_EMAIL";case"verifyAndChangeEmail":return"VERIFY_AND_CHANGE_EMAIL";case"revertSecondFactorAddition":return"REVERT_SECOND_FACTOR_ADDITION";default:return null}}(null!=(r=l.mode)?r:null);g(h&&c&&u,"argument-error"),this.apiKey=h,this.operation=u,this.code=c,this.continueUrl=null!=(s=l.continueUrl)?s:null,this.languageCode=null!=(o=l.languageCode)?o:null,this.tenantId=null!=(a=l.tenantId)?a:null}static parseLink(e){let t,n,r,s=(n=(t=(0,i.querystringDecode)((0,i.extractQuerystring)(e)).link)?(0,i.querystringDecode)((0,i.extractQuerystring)(t)).deep_link_id:null,((r=(0,i.querystringDecode)((0,i.extractQuerystring)(e)).deep_link_id)?(0,i.querystringDecode)((0,i.extractQuerystring)(r)).link:null)||r||n||t||e);try{return new eV(s)}catch(e){return null}}}class eH{constructor(){this.providerId=eH.PROVIDER_ID}static credential(e,t){return eD._fromEmailAndPassword(e,t)}static credentialWithLink(e,t){let n=eV.parseLink(t);return g(n,"argument-error"),eD._fromEmailAndCode(e,n.code,n.tenantId)}}eH.PROVIDER_ID="password",eH.EMAIL_PASSWORD_SIGN_IN_METHOD="password",eH.EMAIL_LINK_SIGN_IN_METHOD="emailLink";class eB{constructor(e){this.providerId=e,this.defaultLanguageCode=null,this.customParameters={}}setDefaultLanguage(e){this.defaultLanguageCode=e}setCustomParameters(e){return this.customParameters=e,this}getCustomParameters(){return this.customParameters}}class ez extends eB{constructor(){super(...arguments),this.scopes=[]}addScope(e){return this.scopes.includes(e)||this.scopes.push(e),this}getScopes(){return[...this.scopes]}}class e$ extends ez{constructor(){super("facebook.com")}static credential(e){return eL._fromParams({providerId:e$.PROVIDER_ID,signInMethod:e$.FACEBOOK_SIGN_IN_METHOD,accessToken:e})}static credentialFromResult(e){return e$.credentialFromTaggedObject(e)}static credentialFromError(e){return e$.credentialFromTaggedObject(e.customData||{})}
1static credentialFromTaggedObject({_tokenResponse:e}){if(!e||!("oauthAccessToken"in e)||!e.oauthAccessToken)return null;try{return e$.credential(e.oauthAccessToken)}catch(e){return null}}}e$.FACEBOOK_SIGN_IN_METHOD="facebook.com",e$.PROVIDER_ID="facebook.com";class eK extends ez{constructor(){super("google.com"),this.addScope("profile")}static credential(e,t){return eL._fromParams({providerId:eK.PROVIDER_ID,signInMethod:eK.GOOGLE_SIGN_IN_METHOD,idToken:e,accessToken:t})}static credentialFromResult(e){return eK.credentialFromTaggedObject(e)}static credentialFromError(e){return eK.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;let{oauthIdToken:t,oauthAccessToken:n}=e;if(!t&&!n)return null;try{return eK.credential(t,n)}catch(e){return null}}}eK.GOOGLE_SIGN_IN_METHOD="google.com",eK.PROVIDER_ID="google.com";class eG extends ez{constructor(){super("github.com")}static credential(e){return eL._fromParams({providerId:eG.PROVIDER_ID,signInMethod:eG.GITHUB_SIGN_IN_METHOD,accessToken:e})}static credentialFromResult(e){return eG.credentialFromTaggedObject(e)}static credentialFromError(e){return eG.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e||!("oauthAccessToken"in e)||!e.oauthAccessToken)return null;try{return eG.credential(e.oauthAccessToken)}catch(e){return null}}}eG.GITHUB_SIGN_IN_METHOD="github.com",eG.PROVIDER_ID="github.com";class eY extends ez{constructor(){super("twitter.com")}static credential(e,t){return eL._fromParams({providerId:eY.PROVIDER_ID,signInMethod:eY.TWITTER_SIGN_IN_METHOD,oauthToken:e,oauthTokenSecret:t})}static credentialFromResult(e){return eY.credentialFromTaggedObject(e)}static credentialFromError(e){return eY.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;let{oauthAccessToken:t,oauthTokenSecret:n}=e;if(!t||!n)return null;try{return eY.credential(t,n)}catch(e){return null}}}eY.TWITTER_SIGN_IN_METHOD="twitter.com",eY.PROVIDER_ID="twitter.com";class eJ{constructor(e){this.user=e.user,this.providerId=e.providerId,this._tokenResponse=e._tokenResponse,this.operationType=e.operationType}static async _fromIdTokenResponse(e,t,n,i=!1){return new eJ({user:await X._fromIdTokenResponse(e,n,i),providerId:eQ(n),_tokenResponse:n,operationType:t})}static async _forOperation(e,t,n){return await e._updateTokensIfNecessary(n,!0),new eJ({user:e,providerId:eQ(n),_tokenResponse:n,operationType:t})}}function eQ(e){return e.providerId?e.providerId:"phoneNumber"in e?"phone":null}class eX extends i.FirebaseError{constructor(e,t,n,i){var r;super(t.code,t.message),this.operationType=n,this.user=i,Object.setPrototypeOf(this,eX.prototype),this.customData={appName:e.name,tenantId:null!=(r=e.tenantId)?r:void 0,_serverResponse:t.customData._serverResponse,operationType:n}}static _fromErrorAndOperation(e,t,n,i){return new eX(e,t,n,i)}}function eZ(e,t,n,i){return("reauthenticate"===t?n._getReauthenticationResolver(e):n._getIdTokenResponse(e)).catch(n=>{if("auth/multi-factor-auth-required"===n.code)throw eX._fromErrorAndOperation(e,n,t,i);throw n})}async function e0(e,t,n=!1){let i=await V(e,t._linkToIdToken(e.auth,await e.getIdToken()),n);return eJ._forOperation(e,"link",i)}async function e1(e,t,i=!1){let{auth:r}=e;if((0,n._isFirebaseServerApp)(r.app))return Promise.reject(f(r));let s="reauthenticate";try{let n=await V(e,eZ(r,s,t,e),i);g(n.idToken,r,"internal-error");let o=j(n.idToken);g(o,r,"internal-error");let{sub:a}=o;return g(e.uid===a,r,"user-mismatch"),eJ._forOperation(e,s,n)}catch(e){throw(null==e?void 0:e.code)==="auth/user-not-found"&&u(r,"user-mismatch"),e}}async function e2(e,t,i=!1){if((0,n._isFirebaseServerApp)(e.app))return Promise.reject(f(e));let r="signIn",s=await eZ(e,r,t),o=await eJ._fromIdTokenResponse(e,r,s);return i||await e._updateCurrentUser(o.user),o}async function e3(e,t){return P(e,"POST","/v1/accounts:signInWithCustomToken",T(e,t))}async function e4(e,t){if((0,n._isFirebaseServerApp)(e.app))return Promise.reject(f(e));let i=ev(e),r=await e3(i,{token:t,returnSecureToken:!0}),s=await eJ._fromIdTokenResponse(i,"signIn",r);return await i._updateCurrentUser(s.user),s}class e6{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){return"phoneInfo"in t?e5._fromServerResponse(e,t):"totpInfo"in t?e8._fromServerResponse(e,t):u(e,"internal-error")}}class e5 extends e6{constructor(e){super("phone",e),this.phoneNumber=e.phoneInfo}static _fromServerResponse(e,t){return new e5(t)}}class e8 extends e6{constructor(e){super("totp",e)}static _fromServerResponse(e,t){return new e8(t)}
1}new WeakMap;let e7="__sak";class e9{constructor(e,t){this.storageRetriever=e,this.type=t}_isAvailable(){try{if(!this.storage)return Promise.resolve(!1);return this.storage.setItem(e7,"1"),this.storage.removeItem(e7),Promise.resolve(!0)}catch(e){return Promise.resolve(!1)}}_set(e,t){return this.storage.setItem(e,JSON.stringify(t)),Promise.resolve()}_get(e){let t=this.storage.getItem(e);return Promise.resolve(t?JSON.parse(t):null)}_remove(e){return this.storage.removeItem(e),Promise.resolve()}get storage(){return this.storageRetriever()}}class te extends e9{constructor(){super(()=>window.localStorage,"LOCAL"),this.boundEventHandler=(e,t)=>this.onStorageEvent(e,t),this.listeners={},this.localCache={},this.pollTimer=null,this.fallbackToPolling=ep(),this._shouldAllowMigration=!0}forAllChangedKeys(e){for(let t of Object.keys(this.listeners)){let n=this.storage.getItem(t),i=this.localCache[t];n!==i&&e(t,i,n)}}onStorageEvent(e,t=!1){if(!e.key)return void this.forAllChangedKeys((e,t,n)=>{this.notifyListeners(e,n)});let n=e.key;t?this.detachListener():this.stopPolling();let r=()=>{let e=this.storage.getItem(n);(t||this.localCache[n]!==e)&&this.notifyListeners(n,e)},s=this.storage.getItem(n);(0,i.isIE)()&&10===document.documentMode&&s!==e.newValue&&e.newValue!==e.oldValue?setTimeout(r,10):r()}notifyListeners(e,t){this.localCache[e]=t;let n=this.listeners[e];if(n)for(let 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}),!0)})},1e3)}stopPolling(){this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=null)}attachListener(){window.addEventListener("storage",this.boundEventHandler)}detachListener(){window.removeEventListener("storage",this.boundEventHandler)}_addListener(e,t){0===Object.keys(this.listeners).length&&(this.fallbackToPolling?this.startPolling():this.attachListener()),this.listeners[e]||(this.listeners[e]=new Set,this.localCache[e]=this.storage.getItem(e)),this.listeners[e].add(t)}_removeListener(e,t){this.listeners[e]&&(this.listeners[e].delete(t),0===this.listeners[e].size&&delete this.listeners[e]),0===Object.keys(this.listeners).length&&(this.detachListener(),this.stopPolling())}async _set(e,t){await super._set(e,t),this.localCache[e]=JSON.stringify(t)}async _get(e){let t=await super._get(e);return this.localCache[e]=JSON.stringify(t),t}async _remove(e){await super._remove(e),delete this.localCache[e]}}te.type="LOCAL";class tt extends e9{constructor(){super(()=>window.sessionStorage,"SESSION")}_addListener(e,t){}_removeListener(e,t){}}tt.type="SESSION";class tn{constructor(e){this.eventTarget=e,this.handlersMap={},this.boundEventHandler=this.handleEvent.bind(this)}static _getInstance(e){let t=this.receivers.find(t=>t.isListeningto(e));if(t)return t;let n=new tn(e);return this.receivers.push(n),n}isListeningto(e){return this.eventTarget===e}async handleEvent(e){let{eventId:t,eventType:n,data:i}=e.data,r=this.handlersMap[n];if(!(null==r?void 0:r.size))return;e.ports[0].postMessage({status:"ack",eventId:t,eventType:n});let s=Array.from(r).map(async t=>t(e.origin,i)),o=await Promise.all(s.map(async e=>{try{let t=await e;return{fulfilled:!0,value:t}}catch(e){return{fulfilled:!1,reason:e}}}));e.ports[0].postMessage({status:"done",eventId:t,eventType:n,response:o})}_subscribe(e,t){0===Object.keys(this.handlersMap).length&&this.eventTarget.addEventListener("message",this.boundEventHandler),this.handlersMap[e]||(this.handlersMap[e]=new Set),this.handlersMap[e].add(t)}_unsubscribe(e,t){this.handlersMap[e]&&t&&this.handlersMap[e].delete(t),t&&0!==this.handlersMap[e].size||delete this.handlersMap[e],0===Object.keys(this.handlersMap).length&&this.eventTarget.removeEventListener("message",this.boundEventHandler)}}function ti(e="",t=10){let n="";for(let e=0;e<t;e++)n+=Math.floor(10*Math.random());return e+n}tn.receivers=[];class tr{constructor(e){this.target=e,this.handlers=new Set}removeMessageHandler(e){e.messageChannel&&(e.messageChannel.port1.removeEventListener("message",e.onMessage),e.messageChannel.port1.close()),this.handlers.delete(e)}async _send(e,t,n=50){let i,r,s="u">typeof MessageChannel?new MessageChannel:null;if(!s)throw Error("connection_unavailable");return new Promise((o,a)=>{let l=ti("",20);s.port1.start();let h=setTimeout(()=>{a(Error("unsupported_event"))},n);r={messageChannel:s,onMessage(e){if(e.data.eventId===l)switch(e.data.status){case"ack":clearTimeout(h),i=setTimeout(()=>{a(Error("timeout"))},3e3);break;case"done":clearTimeout(i),o(e.data.response);break;default:clearTimeout(h),clearTimeout(i),a(Error("invalid_response"))}}},this.handlers.add(r),s.port1.addEventListener("message",r.onMessage),this.target.postMessage({eventType:e,eventId:l,data:t},[s.port2])}).finally(()=>{r&&this.removeMessageHandler(r)})}}function ts(){return window}
1function to(){return void 0!==ts().WorkerGlobalScope&&"function"==typeof ts().importScripts}async function ta(){if(!(null==navigator?void 0:navigator.serviceWorker))return null;try{return(await navigator.serviceWorker.ready).active}catch(e){return null}}let tl="firebaseLocalStorageDb",th="firebaseLocalStorage",tc="fbase_key";class tu{constructor(e){this.request=e}toPromise(){return new Promise((e,t)=>{this.request.addEventListener("success",()=>{e(this.request.result)}),this.request.addEventListener("error",()=>{t(this.request.error)})})}}function td(e,t){return e.transaction([th],t?"readwrite":"readonly").objectStore(th)}function tp(){let e=indexedDB.open(tl,1);return new Promise((t,n)=>{e.addEventListener("error",()=>{n(e.error)}),e.addEventListener("upgradeneeded",()=>{let t=e.result;try{t.createObjectStore(th,{keyPath:tc})}catch(e){n(e)}}),e.addEventListener("success",async()=>{let n=e.result;n.objectStoreNames.contains(th)?t(n):(n.close(),await new tu(indexedDB.deleteDatabase(tl)).toPromise(),t(await tp()))})})}async function tf(e,t,n){return new tu(td(e,!0).put({[tc]:t,value:n})).toPromise()}async function t_(e,t){let n=td(e,!1).get(t),i=await new tu(n).toPromise();return void 0===i?null:i.value}function tg(e,t){return new tu(td(e,!0).delete(t)).toPromise()}class tm{constructor(){this.type="LOCAL",this._shouldAllowMigration=!0,this.listeners={},this.localCache={},this.pollTimer=null,this.pendingWrites=0,this.receiver=null,this.sender=null,this.serviceWorkerReceiverAvailable=!1,this.activeServiceWorker=null,this._workerInitializationPromise=this.initializeServiceWorkerMessaging().then(()=>{},()=>{})}async _openDb(){return this.db||(this.db=await tp()),this.db}async _withRetries(e){let t=0;for(;;)try{let t=await this._openDb();return await e(t)}catch(e){if(t++>3)throw e;this.db&&(this.db.close(),this.db=void 0)}}async initializeServiceWorkerMessaging(){return to()?this.initializeReceiver():this.initializeSender()}async initializeReceiver(){this.receiver=tn._getInstance(to()?self:null),this.receiver._subscribe("keyChanged",async(e,t)=>({keyProcessed:(await this._poll()).includes(t.key)})),this.receiver._subscribe("ping",async(e,t)=>["keyChanged"])}async initializeSender(){var e,t;if(this.activeServiceWorker=await ta(),!this.activeServiceWorker)return;this.sender=new tr(this.activeServiceWorker);let n=await this.sender._send("ping",{},800);n&&(null==(e=n[0])?void 0:e.fulfilled)&&(null==(t=n[0])?void 0:t.value.includes("keyChanged"))&&(this.serviceWorkerReceiverAvailable=!0)}async notifyServiceWorker(e){var t;if(this.sender&&this.activeServiceWorker&&((null==(t=null==navigator?void 0:navigator.serviceWorker)?void 0:t.controller)||null)===this.activeServiceWorker)try{await this.sender._send("keyChanged",{key:e},this.serviceWorkerReceiverAvailable?800:50)}catch(e){}}async _isAvailable(){try{if(!indexedDB)return!1;let e=await tp();return await tf(e,e7,"1"),await tg(e,e7),!0}catch(e){}return!1}async _withPendingWrite(e){this.pendingWrites++;try{await e()}finally{this.pendingWrites--}}async _set(e,t){return this._withPendingWrite(async()=>(await this._withRetries(n=>tf(n,e,t)),this.localCache[e]=t,this.notifyServiceWorker(e)))}async _get(e){let t=await this._withRetries(t=>t_(t,e));return this.localCache[e]=t,t}async _remove(e){return this._withPendingWrite(async()=>(await this._withRetries(t=>tg(t,e)),delete this.localCache[e],this.notifyServiceWorker(e)))}async _poll(){let e=await this._withRetries(e=>new tu(td(e,!1).getAll()).toPromise());if(!e||0!==this.pendingWrites)return[];let t=[],n=new Set;if(0!==e.length)for(let{fbase_key:i,value:r}of e)n.add(i),JSON.stringify(this.localCache[i])!==JSON.stringify(r)&&(this.notifyListeners(i,r),t.push(i));for(let e of Object.keys(this.localCache))this.localCache[e]&&!n.has(e)&&(this.notifyListeners(e,null),t.push(e));return t}notifyListeners(e,t){this.localCache[e]=t;let n=this.listeners[e];if(n)for(let e of Array.from(n))e(t)}startPolling(){this.stopPolling(),this.pollTimer=setInterval(async()=>this._poll(),800)}stopPolling(){this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=null)}_addListener(e,t){0===Object.keys(this.listeners).length&&this.startPolling(),this.listeners[e]||(this.listeners[e]=new Set,this._get(e)),this.listeners[e].add(t)}_removeListener(e,t){this.listeners[e]&&(this.listeners[e].delete(t),0===this.listeners[e].size&&delete this.listeners[e]),0===Object.keys(this.listeners).length&&this.stopPolling()}}async function ty(e,t,n){var i,r,s;let o=await n.verify();try{let a;if(g("string"==typeof o,e,"argument-error"),g("recaptcha"===n.type,e,"argument-error"),a="string"==typeof t?{phoneNumber:t}
1:t,"session"in a){let t=a.session;if("phoneNumber"in a)return g("enroll"===t.type,e,"internal-error"),(await (r={idToken:t.credential,phoneEnrollmentInfo:{phoneNumber:a.phoneNumber,recaptchaToken:o}},S(e,"POST","/v2/accounts/mfaEnrollment:start",T(e,r)))).phoneSessionInfo.sessionInfo;{g("signin"===t.type,e,"internal-error");let n=(null==(i=a.multiFactorHint)?void 0:i.uid)||a.multiFactorUid;return g(n,e,"missing-multi-factor-info"),(await (s={mfaPendingCredential:t.credential,mfaEnrollmentId:n,phoneSignInInfo:{recaptchaToken:o}},S(e,"POST","/v2/accounts/mfaSignIn:start",T(e,s)))).phoneResponseInfo.sessionInfo}}{let{sessionInfo:t}=await eM(e,{phoneNumber:a.phoneNumber,recaptchaToken:o});return t}}finally{n._reset()}}tm.type="LOCAL",eC("rcb"),new w(3e4,6e4);class tv{constructor(e){this.providerId=tv.PROVIDER_ID,this.auth=ev(e)}verifyPhoneNumber(e,t){return ty(this.auth,e,(0,i.getModularInstance)(t))}static credential(e,t){return eW._fromVerification(e,t)}static credentialFromResult(e){return tv.credentialFromTaggedObject(e)}static credentialFromError(e){return tv.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;let{phoneNumber:t,temporaryProof:n}=e;return t&&n?eW._fromTokenResponse(t,n):null}}function tw(e,t){return t?ee(t):(g(e._popupRedirectResolver,e,"argument-error"),e._popupRedirectResolver)}tv.PROVIDER_ID="phone",tv.PHONE_SIGN_IN_METHOD="phone";class tI extends eP{constructor(e){super("custom","custom"),this.params=e}_getIdTokenResponse(e){return ex(e,this._buildIdpRequest())}_linkToIdToken(e,t){return ex(e,this._buildIdpRequest(t))}_getReauthenticationResolver(e){return ex(e,this._buildIdpRequest())}_buildIdpRequest(e){let t={requestUri:this.params.requestUri,sessionId:this.params.sessionId,postBody:this.params.postBody,tenantId:this.params.tenantId,pendingToken:this.params.pendingToken,returnSecureToken:!0,returnIdpCredential:!0};return e&&(t.idToken=e),t}}function tC(e){return e2(e.auth,new tI(e),e.bypassAuthState)}function tb(e){let{auth:t,user:n}=e;return g(n,t,"internal-error"),e1(n,new tI(e),e.bypassAuthState)}async function tE(e){let{auth:t,user:n}=e;return g(n,t,"internal-error"),e0(n,new tI(e),e.bypassAuthState)}class tT{constructor(e,t,n,i,r=!1){this.auth=e,this.resolver=n,this.user=i,this.bypassAuthState=r,this.pendingPromise=null,this.eventManager=null,this.filter=Array.isArray(t)?t:[t]}execute(){return new Promise(async(e,t)=>{this.pendingPromise={resolve:e,reject:t};try{this.eventManager=await this.resolver._initialize(this.auth),await this.onExecution(),this.eventManager.registerConsumer(this)}catch(e){this.reject(e)}})}async onAuthEvent(e){let{urlResponse:t,sessionId:n,postBody:i,tenantId:r,error:s,type:o}=e;if(s)return void this.reject(s);let a={auth:this.auth,requestUri:t,sessionId:n,tenantId:r||void 0,postBody:i||void 0,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 tC;case"linkViaPopup":case"linkViaRedirect":return tE;case"reauthViaPopup":case"reauthViaRedirect":return tb;default:u(this.auth,"internal-error")}}resolve(e){var t,n;t=this.pendingPromise,n="Pending promise was never set",t||m(n),this.pendingPromise.resolve(e),this.unregisterAndCleanUp()}reject(e){var t,n;t=this.pendingPromise,n="Pending promise was never set",t||m(n),this.pendingPromise.reject(e),this.unregisterAndCleanUp()}unregisterAndCleanUp(){this.eventManager&&this.eventManager.unregisterConsumer(this),this.pendingPromise=null,this.cleanUp()}}let tS=new w(2e3,1e4);async function tk(e,t,i){if((0,n._isFirebaseServerApp)(e.app))return Promise.reject(d(e,"operation-not-supported-in-this-environment"));let r=ev(e);if(!(t instanceof eB))throw eB.name!==t.constructor.name&&u(e,"argument-error"),p(e,"argument-error",`Type of ${t.constructor.name} does not match expected instance.Did you pass a reference from a different Auth SDK?`);let s=tw(r,i);return new tP(r,"signInViaPopup",t,s).executeNotNull()}class tP extends tT{constructor(e,t,n,i,r){super(e,t,i,r),this.provider=n,this.authWindow=null,this.pollId=null,tP.currentPopupAction&&tP.currentPopupAction.cancel(),tP.currentPopupAction=this}async executeNotNull(){let e=await this.execute();return g(e,this.auth,"internal-error"),e}async onExecution(){var e,t;e=1===this.filter.length,t="Popup operations only handle one event",e||m(t);let n=ti();this.authWindow=await this.resolver._openPopup(this.auth,this.provider,this.filter[0],n),this.authWindow.associatedEvent=n,this.resolver._originValidation(this.auth).catch(e=>{this.reject(e)}),this.resolver._isIframeWebStorageSupported(this.auth,e=>{e||this.reject(d(this.auth,"web-storage-unsupported"))}),this.pollUserCancellation()}get eventId(){var e;return(null==(e=this.authWindow)?void 0:e.associatedEvent)||null}cancel(){this.reject(d(this.auth,"cancelled-popup-request"))}cleanUp(){this.authWindow&&this.authWindow.close(),this.pollId&&window.clearTimeout(this.pollId),this.authWindow=null,this.pollId=null,tP.currentPopupAction=null}pollUserCancellation(){let e=()=>{var t,n;if(null==(n=null==(t=this.authWindow)?void 0:t.window)?void 0:n.closed){this.pollId=window.setTimeout(()=>{this.pollId=null,this.reject(d(this.auth,"popup-closed-by-user"))},8e3);return}this.pollId=window.setTimeout(e,tS.get())};e()}}tP.currentPopupAction=null;let tN=new Map;class tR extends tT{constructor(e,t,n=!1){super(e,["signInViaRedirect","linkViaRedirect","reauthViaRedirect","unknown"],t,void 0,n),this.eventId=null}async execute(){let e=tN.get(this.auth._key());if(!e){try{let t=await tA(this.resolver,this.auth)?await super.execute():null;e=()=>Promise.resolve(t)}catch(t){e=()=>Promise.reject(t)}tN.set(this.auth._key(),e)}return this.bypassAuthState||tN.set(this.auth._key(),()=>Promise.resolve(null)),e()}async onAuthEvent(e){if("signInViaRedirect"===e.type)return super.onAuthEvent(e);
1if("unknown"===e.type)return void this.resolve(null);if(e.eventId){let t=await this.auth._redirectUserForId(e.eventId);if(t)return this.user=t,super.onAuthEvent(e);this.resolve(null)}}async onExecution(){}cleanUp(){}}async function tA(e,t){var n;let i=en("pendingRedirect",(n=t).config.apiKey,n.name),r=ee(e._redirectPersistence);if(!await r._isAvailable())return!1;let s=await r._get(i)==="true";return await r._remove(i),s}function tO(e,t){tN.set(e._key(),t)}async function tD(e,t,i=!1){if((0,n._isFirebaseServerApp)(e.app))return Promise.reject(f(e));let r=ev(e),s=tw(r,t),o=new tR(r,s,i),a=await o.execute();return a&&!i&&(delete a.user._redirectEventId,await r._persistUserIfCurrent(a.user),await r._setRedirectUser(null,t)),a}class tx{constructor(e){this.auth=e,this.cachedEventUids=new Set,this.consumers=new Set,this.queuedRedirectEvent=null,this.hasHandledPotentialRedirect=!1,this.lastProcessedEventTime=Date.now()}registerConsumer(e){this.consumers.add(e),this.queuedRedirectEvent&&this.isEventForConsumer(this.queuedRedirectEvent,e)&&(this.sendToConsumer(this.queuedRedirectEvent,e),this.saveEventToCache(this.queuedRedirectEvent),this.queuedRedirectEvent=null)}unregisterConsumer(e){this.consumers.delete(e)}onEvent(e){if(this.hasEventBeenHandled(e))return!1;let t=!1;return this.consumers.forEach(n=>{this.isEventForConsumer(e,n)&&(t=!0,this.sendToConsumer(e,n),this.saveEventToCache(e))}),this.hasHandledPotentialRedirect||!function(e){switch(e.type){case"signInViaRedirect":case"linkViaRedirect":case"reauthViaRedirect":return!0;case"unknown":return tM(e);default:return!1}}(e)||(this.hasHandledPotentialRedirect=!0,t||(this.queuedRedirectEvent=e,t=!0)),t}sendToConsumer(e,t){var n;if(e.error&&!tM(e)){let i=(null==(n=e.error.code)?void 0:n.split("auth/")[1])||"internal-error";t.onError(d(this.auth,i))}else t.onAuthEvent(e)}isEventForConsumer(e,t){let n=null===t.eventId||!!e.eventId&&e.eventId===t.eventId;return t.filter.includes(e.type)&&n}hasEventBeenHandled(e){return Date.now()-this.lastProcessedEventTime>=6e5&&this.cachedEventUids.clear(),this.cachedEventUids.has(tL(e))}saveEventToCache(e){this.cachedEventUids.add(tL(e)),this.lastProcessedEventTime=Date.now()}}function tL(e){return[e.type,e.eventId,e.sessionId,e.tenantId].filter(e=>e).join("-")}function tM({type:e,error:t}){return"unknown"===e&&(null==t?void 0:t.code)==="auth/no-auth-event"}async function tF(e,t={}){return S(e,"GET","/v1/projects",t)}let tU=/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/,tq=/^https?/;async function tj(e){if(e.config.emulator)return;let{authorizedDomains:t}=await tF(e);for(let e of t)try{if(function(e){let t=y(),{protocol:n,hostname:i}=new URL(t);if(e.startsWith("chrome-extension://")){let r=new URL(e);return""===r.hostname&&""===i?"chrome-extension:"===n&&e.replace("chrome-extension://","")===t.replace("chrome-extension://",""):"chrome-extension:"===n&&r.hostname===i}if(!tq.test(n))return!1;if(tU.test(e))return i===e;let r=e.replace(/\./g,"\\.");return RegExp("^(.+\\."+r+"|"+r+")$","i").test(i)}(e))return}catch(e){}u(e,"unauthorized-domain")}let tW=new w(3e4,6e4);function tV(){let e=ts().___jsl;if(null==e?void 0:e.H){for(let t of Object.keys(e.H))if(e.H[t].r=e.H[t].r||[],e.H[t].L=e.H[t].L||[],e.H[t].r=[...e.H[t].L],e.CP)for(let t=0;t<e.CP.length;t++)e.CP[t]=null}}let tH=null,tB=new w(5e3,15e3),tz={style:{position:"absolute",top:"-100px",width:"1px",height:"1px"},"aria-hidden":"true",tabindex:"-1"},t$=new Map([["identitytoolkit.googleapis.com","p"],["staging-identitytoolkit.sandbox.googleapis.com","s"],["test-identitytoolkit.sandbox.googleapis.com","t"]]);async function tK(e){let t,r,s,o,a,l=await (tH=tH||new Promise((t,n)=>{var i,r,s,o;function a(){tV(),gapi.load("gapi.iframes",{callback:()=>{t(gapi.iframes.getContext())},ontimeout:()=>{tV(),n(d(e,"network-request-failed"))},timeout:tW.get()})}if(null==(r=null==(i=ts().gapi)?void 0:i.iframes)?void 0:r.Iframe)t(gapi.iframes.getContext());else if(null==(s=ts().gapi)?void 0:s.load)a();else{let t=eC("iframefcb");return ts()[t]=()=>{gapi.load?a():n(d(e,"network-request-failed"))},(o=`${eI.gapiScript}?onload=${t}`,eI.loadJS(o)).catch(e=>n(e))}}).catch(e=>{throw tH=null,e})),h=ts().gapi;return g(h,e,"internal-error"),l.open({where:document.body,url:(g((t=e.config).authDomain,e,"auth-domain-config-required"),r=t.emulator?I(t,"emulator/auth/iframe"):`https://${e.config.authDomain}
1/__/auth/iframe`,s={apiKey:t.apiKey,appName:e.name,v:n.SDK_VERSION},(o=t$.get(e.config.apiHost))&&(s.eid=o),(a=e._getFrameworks()).length&&(s.fw=a.join(",")),`${r}?${(0,i.querystring)(s).slice(1)}`),messageHandlersFilter:h.iframes.CROSS_ORIGIN_IFRAMES_FILTER,attributes:tz,dontclear:!0},t=>new Promise(async(n,i)=>{await t.restyle({setHideOnLeave:!1});let r=d(e,"network-request-failed"),s=ts().setTimeout(()=>{i(r)},tB.get());function o(){ts().clearTimeout(s),n(t)}t.ping(o).then(o,()=>{i(r)})}))}let tG={location:"yes",resizable:"yes",statusbar:"yes",toolbar:"no"};class tY{constructor(e){this.window=e,this.associatedEvent=null}close(){if(this.window)try{this.window.close()}catch(e){}}}let tJ=encodeURIComponent("fac");async function tQ(e,t,r,s,o,a){g(e.config.authDomain,e,"auth-domain-config-required"),g(e.config.apiKey,e,"invalid-api-key");let l={apiKey:e.config.apiKey,appName:e.name,authType:r,redirectUrl:s,v:n.SDK_VERSION,eventId:o};if(t instanceof eB)for(let[n,r]of(t.setDefaultLanguage(e.languageCode),l.providerId=t.providerId||"",(0,i.isEmpty)(t.getCustomParameters())||(l.customParameters=JSON.stringify(t.getCustomParameters())),Object.entries(a||{})))l[n]=r;if(t instanceof ez){let e=t.getScopes().filter(e=>""!==e);e.length>0&&(l.scopes=e.join(","))}for(let t of(e.tenantId&&(l.tid=e.tenantId),Object.keys(l)))void 0===l[t]&&delete l[t];let h=await e._getAppCheckToken(),c=h?`#${tJ}=${encodeURIComponent(h)}`:"";return`${function({config:e}){return e.emulator?I(e,"emulator/auth/handler"):`https://${e.authDomain}/__/auth/handler`}(e)}?${(0,i.querystring)(l).slice(1)}${c}`}let tX="webStorageSupport",tZ=class{constructor(){this.eventManagers={},this.iframes={},this.originValidationPromises={},this._redirectPersistence=tt,this._completeRedirectFn=tD,this._overrideRedirectResult=tO}async _openPopup(e,t,n,r){var s,o,a;o=null==(s=this.eventManagers[e._key()])?void 0:s.manager,a="_initialize() not called before _openPopup()",o||m(a);let l=await tQ(e,t,n,y(),r);return function(e,t,n,r=500,s=600){let o=Math.max((window.screen.availHeight-s)/2,0).toString(),a=Math.max((window.screen.availWidth-r)/2,0).toString(),l="",h=Object.assign(Object.assign({},tG),{width:r.toString(),height:s.toString(),top:o,left:a}),c=(0,i.getUA)().toLowerCase();n&&(l=ea(c)?"_blank":n),es(c)&&(t=t||"http://localhost",h.scrollbars="yes");let u=Object.entries(h).reduce((e,[t,n])=>`${e}${t}=${n},`,"");if(function(e=(0,i.getUA)()){var t;return ed(e)&&!!(null==(t=window.navigator)?void 0:t.standalone)}(c)&&"_self"!==l){var d,p;let e,n;return d=t||"",p=l,(e=document.createElement("a")).href=d,e.target=p,(n=document.createEvent("MouseEvent")).initMouseEvent("click",!0,!0,window,1,0,0,0,0,!1,!1,!1,!1,1,null),e.dispatchEvent(n),new tY(null)}let f=window.open(t||"",l,u);g(f,e,"popup-blocked");try{f.focus()}catch(e){}return new tY(f)}(e,l,ti())}async _openRedirect(e,t,n,i){var r;return await this._originValidation(e),r=await tQ(e,t,n,y(),i),ts().location.href=r,new Promise(()=>{})}_initialize(e){let t=e._key();if(this.eventManagers[t]){var n;let{manager:e,promise:i}=this.eventManagers[t];return e?Promise.resolve(e):(n="If manager is not set, promise should be",i||m(n),i)}let i=this.initAndGetManager(e);return this.eventManagers[t]={promise:i},i.catch(()=>{delete this.eventManagers[t]}),i}async initAndGetManager(e){let t=await tK(e),n=new tx(e);return t.register("authEvent",t=>(g(null==t?void 0:t.authEvent,e,"invalid-auth-event"),{status:n.onEvent(t.authEvent)?"ACK":"ERROR"}),gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER),this.eventManagers[e._key()]={manager:n},this.iframes[e._key()]=t,n}_isIframeWebStorageSupported(e,t){this.iframes[e._key()].send(tX,{type:tX},n=>{var i;let r=null==(i=null==n?void 0:n[0])?void 0:i[tX];void 0!==r&&t(!!r),u(e,"internal-error")},gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER)}_originValidation(e){let t=e._key();return this.originValidationPromises[t]||(this.originValidationPromises[t]=tj(e)),this.originValidationPromises[t]}get _shouldInitProactively(){return ep()||eo()||ed()}};var t0="@firebase/auth",t1="1.7.9";class t2{constructor(e){this.auth=e,this.internalListeners=new Map}getUid(){var e;return this.assertAuthConfigured(),(null==(e=this.auth.currentUser)?void 0:e.uid)||null}async getToken(e){return(this.assertAuthConfigured(),await this.auth._initializationPromise,this.auth.currentUser)?{accessToken:await this.auth.currentUser.getIdToken(e)}:null}addAuthTokenListener(e){if(this.assertAuthConfigured(),this.internalListeners.has(e))return;let t=this.auth.onIdTokenChanged(t=>{e((null==t?void 0:t.stsTokenManager.accessToken)||null)});this.internalListeners.set(e,t),this.updateProactiveRefresh()}removeAuthTokenListener(e){this.assertAuthConfigured();let t=this.internalListeners.get(e);t&&(this.internalListeners.delete(e),t(),this.updateProactiveRefresh())}assertAuthConfigured(){g(this.auth._initializationPromise,"dependent-sdk-initialized-before-auth")}updateProactiveRefresh(){this.internalListeners.size>0?this.auth._startProactiveRefresh():this.auth._stopProactiveRefresh()}}let t3=(0,i.getExperimentalSetting)("authIdTokenMaxAge")||300,t4=null;eI={loadJS:e=>
1new Promise((t,n)=>{var i,r;let s=document.createElement("script");s.setAttribute("src",e),s.onload=t,s.onerror=e=>{let t=d("internal-error");t.customData=e,n(t)},s.type="text/javascript",s.charset="UTF-8",(null!=(r=null==(i=document.getElementsByTagName("head"))?void 0:i[0])?r:document).appendChild(s)}),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="},t="Browser",(0,n._registerComponent)(new o.Component("auth",(e,{options:n})=>{let i,r,s=e.getProvider("app").getImmediate(),o=e.getProvider("heartbeat"),a=e.getProvider("app-check-internal"),{apiKey:l,authDomain:h}=s.options;g(l&&!l.includes(":"),"invalid-api-key",{appName:s.name});let c=new ey(s,o,a,{apiKey:l,authDomain:h,clientPlatform:t,apiHost:"identitytoolkit.googleapis.com",tokenApiHost:"securetoken.googleapis.com",apiScheme:"https",sdkClientVersion:ef(t)});return r=(Array.isArray(i=(null==n?void 0:n.persistence)||[])?i:[i]).map(ee),(null==n?void 0:n.errorMap)&&c._updateErrorMap(n.errorMap),c._initializeWithPersistence(r,null==n?void 0:n.popupRedirectResolver),c},"PUBLIC").setInstantiationMode("EXPLICIT").setInstanceCreatedCallback((e,t,n)=>{e.getProvider("auth-internal").initialize()})),(0,n._registerComponent)(new o.Component("auth-internal",e=>new t2(ev(e.getProvider("auth").getImmediate())),"PRIVATE").setInstantiationMode("EXPLICIT")),(0,n.registerVersion)(t0,t1,function(e){switch(e){case"Node":return"node";case"ReactNative":return"rn";case"Worker":return"webworker";case"Cordova":return"cordova";case"WebExtension":return"web-extension";default:return}}(t)),(0,n.registerVersion)(t0,t1,"esm2017"),e.s(["W",0,e$,"X",0,eK,"a4",0,e4,"c",0,tk,"o",0,function(e=(0,n.getApp)()){let t=(0,n._getProvider)(e,"auth");if(t.isInitialized())return t.getImmediate();let r=function(e,t){let r=(0,n._getProvider)(e,"auth");if(r.isInitialized()){let e=r.getImmediate(),n=r.getOptions();if((0,i.deepEqual)(n,null!=t?t:{}))return e;u(e,"already-initialized")}return r.initialize({options:t})}(e,{popupRedirectResolver:tZ,persistence:[tm,te,tt]}),s=(0,i.getExperimentalSetting)("authTokenSyncURL");if(s&&"boolean"==typeof isSecureContext&&isSecureContext){let e=new URL(s,location.origin);if(location.origin===e.origin){let t,n=(t=e.toString(),async e=>{let n=e&&await e.getIdTokenResult(),i=n&&(new Date().getTime()-Date.parse(n.issuedAtTime))/1e3;if(i&&i>t3)return;let r=null==n?void 0:n.token;t4!==r&&(t4=r,await fetch(t,{method:r?"POST":"DELETE",headers:r?{Authorization:`Bearer ${r}`}:{}}))});(0,i.getModularInstance)(r).beforeAuthStateChanged(n,()=>n(r.currentUser)),(0,i.getModularInstance)(r).onIdTokenChanged(e=>n(e),void 0,void 0)}}let o=(0,i.getDefaultEmulatorHost)("auth");return o&&function(e,t){let n=ev(e);g(n._canInitEmulator,n,"emulator-config-failed"),g(/^https?:\/\//.test(t),n,"invalid-emulator-scheme");let i=eS(t),{host:r,port:s}=function(e){let t=eS(e),n=/(\/\/)?([^?#/]+)/.exec(e.substr(t.length));if(!n)return{host:"",port:null};let i=n[2].split("@").pop()||"",r=/^(\[[^\]]+\])(:|$)/.exec(i);if(r){let e=r[1];return{host:e,port:ek(i.substr(e.length+1))}}{let[e,t]=i.split(":");return{host:e,port:ek(t)}}}(t),o=null===s?"":`:${s}`;n.config.emulator={url:`${i}//${r}${o}/`},n.settings.appVerificationDisabledForTesting=!0,n.emulatorConfig=Object.freeze({host:r,port:s,protocol:i.replace(":",""),options:Object.freeze({disableWarnings:!1})}),function(){function e(){let e=document.createElement("p"),t=e.style;e.innerText="Running in emulator mode. Do not use with production credentials.",t.position="fixed",t.width="100%",t.backgroundColor="#ffffff",t.border=".1em solid #000000",t.color="#b50000",t.bottom="0px",t.left="0px",t.margin="0px",t.zIndex="10000",t.textAlign="center",e.classList.add("firebase-emulator-warning"),document.body.appendChild(e)}"u">typeof console&&"function"==typeof console.info&&console.info("WARNING: You are using the Auth Emulator, which is intended for local testing only.  Do not use with production credentials."),"u">typeof window&&"u">typeof document&&("loading"===document.readyState?window.addEventListener("DOMContentLoaded",e):e())}()}(r,`http://${o}`),r},"y",0,function(e,t,n,r){return(0,i.getModularInstance)(e).onAuthStateChanged(t,n,r)}],854762),e.s([],151718)},214539,e=>{"use strict";(0,e.i(485086).registerVersion)("firebase","10.14.1","app"),e.s([])},401465,476686,e=>{"use strict";let t,n,i,r,s,o,a,l,h,c,u;var d,p,f=e.i(247167),_=e.i(485086),g=e.i(965233),m=e.i(733015),y=e.i(68483);let v="@firebase/database",w="1.0.8",I="";class C{constructor(e){this.domStorage_=e,this.prefix_="firebase:"}set(e,t){null==t?this.domStorage_.removeItem(this.prefixedName_(e)):this.domStorage_.setItem(this.prefixedName_(e),(0,m.stringify)(t))}get(e){let t=this.domStorage_.getItem(this.prefixedName_(e));return null==t?null:(0,m.jsonEval)(t)}remove(e){this.domStorage_.removeItem(this.prefixedName_(e))}prefixedName_(e){return this.prefix_+e}toString(){return this.domStorage_.toString()}}class b{constructor(){this.cache_={},this.isInMemoryStorage=!0}set(e,t){null==t?delete this.cache_[e]:this.cache_[e]=t}get(e){return(0,m.contains)(this.cache_,e)?this.cache_[e]:null}remove(e){delete this.cache_[e]}}let E=function(e){try{if("u">typeof window&&void 0!==window[e]){let t=window[e];return t.setItem("firebase:sentinel","cache"),t.removeItem("firebase:sentinel"),new C(t)}}catch(e){}return new b},T=E("localStorage"),S=E("sessionStorage"),k=new y.Logger("@firebase/database"),P=(u=1,function(){return u++}
1),N=function(e){let t=(0,m.stringToByteArray)(e),n=new m.Sha1;n.update(t);let i=n.digest();return m.base64.encodeByteArray(i)},R=function(...e){let t="";for(let n=0;n<e.length;n++){let i=e[n];Array.isArray(i)||i&&"object"==typeof i&&"number"==typeof i.length?t+=R.apply(null,i):"object"==typeof i?t+=(0,m.stringify)(i):t+=i,t+=" "}return t},A=null,O=!0,D=function(e,t){(0,m.assert)(!t||!0===e||!1===e,"Can't turn on custom loggers persistently."),!0===e?(k.logLevel=y.LogLevel.VERBOSE,A=k.log.bind(k),t&&S.set("logging_enabled",!0)):"function"==typeof e?A=e:(A=null,S.remove("logging_enabled"))},x=function(...e){if(!0===O&&(O=!1,null===A&&!0===S.get("logging_enabled")&&D(!0)),A){let t=R.apply(null,e);A(t)}},L=function(e){return function(...t){x(e,...t)}},M=function(...e){let t="FIREBASE INTERNAL ERROR: "+R(...e);k.error(t)},F=function(...e){let t=`FIREBASE FATAL ERROR: ${R(...e)}`;throw k.error(t),Error(t)},U=function(...e){let t="FIREBASE WARNING: "+R(...e);k.warn(t)},q=function(){"u">typeof window&&window.location&&window.location.protocol&&-1!==window.location.protocol.indexOf("https:")&&U("Insecure Firebase access from a secure page. Please use https in calls to new Firebase().")},j=function(e){return"number"==typeof e&&(e!=e||e===1/0||e===-1/0)},W=function(e){if((0,m.isNodeSdk)()||"complete"===document.readyState)e();else{let t=!1,n=function(){document.body?t||(t=!0,e()):setTimeout(n,Math.floor(10))};document.addEventListener?(document.addEventListener("DOMContentLoaded",n,!1),window.addEventListener("load",n,!1)):document.attachEvent&&(document.attachEvent("onreadystatechange",()=>{"complete"===document.readyState&&n()}),window.attachEvent("onload",n))}},V="[MIN_NAME]",H="[MAX_NAME]",B=function(e,t){if(e===t)return 0;{if(e===V||t===H)return -1;if(t===V||e===H)return 1;let n=X(e),i=X(t);if(null!==n)if(null!==i)return n-i==0?e.length-t.length:n-i;else return -1;return null!==i?1:e<t?-1:1}},z=function(e,t){return e===t?0:e<t?-1:1},$=function(e,t){if(t&&e in t)return t[e];throw Error("Missing required key ("+e+") in object: "+(0,m.stringify)(t))},K=function(e){if("object"!=typeof e||null===e)return(0,m.stringify)(e);let t=[];for(let n in e)t.push(n);t.sort();let n="{";for(let i=0;i<t.length;i++)0!==i&&(n+=","),n+=(0,m.stringify)(t[i]),n+=":",n+=K(e[t[i]]);return n+"}"},G=function(e,t){let n=e.length;if(n<=t)return[e];let i=[];for(let r=0;r<n;r+=t)r+t>n?i.push(e.substring(r,n)):i.push(e.substring(r,r+t));return i};function Y(e,t){for(let n in e)e.hasOwnProperty(n)&&t(n,e[n])}let J=function(e){let t,n,i,r,s;(0,m.assert)(!j(e),"Invalid JSON number");0===e?(n=0,i=0,t=+(1/e==-1/0)):(t=e<0,(e=Math.abs(e))>=22250738585072014e-324?(n=(r=Math.min(Math.floor(Math.log(e)/Math.LN2),1023))+1023,i=Math.round(e*Math.pow(2,52-r)-0x10000000000000)):(n=0,i=Math.round(e/5e-324)));let o=[];for(s=52;s;s-=1)o.push(i%2?1:0),i=Math.floor(i/2);for(s=11;s;s-=1)o.push(n%2?1:0),n=Math.floor(n/2);o.push(+!!t),o.reverse();let a=o.join(""),l="";for(s=0;s<64;s+=8){let e=parseInt(a.substr(s,8),2).toString(16);1===e.length&&(e="0"+e),l+=e}return l.toLowerCase()},Q=RegExp("^-?(0*)\\d{1,10}$"),X=function(e){if(Q.test(e)){let t=Number(e);if(t>=-0x80000000&&t<=0x7fffffff)return t}return null},Z=function(e){try{e()}catch(e){setTimeout(()=>{throw U("Exception was thrown by user callback.",e.stack||""),e},Math.floor(0))}},ee=function(e,t){let n=setTimeout(e,t);return"number"==typeof n&&"u">typeof Deno&&Deno.unrefTimer?Deno.unrefTimer(n):"object"==typeof n&&n.unref&&n.unref(),n};class et{constructor(e,t){this.appName_=e,this.appCheckProvider=t,this.appCheck=null==t?void 0:t.getImmediate({optional:!0}),this.appCheck||null==t||t.get().then(e=>this.appCheck=e)}getToken(e){return this.appCheck?this.appCheck.getToken(e):new Promise((t,n)=>{setTimeout(()=>{this.appCheck?this.getToken(e).then(t,n):t(null)},0)})}addTokenChangeListener(e){var t;null==(t=this.appCheckProvider)||t.get().then(t=>t.addTokenListener(e))}notifyForInvalidToken(){U(`Provided AppCheck credentials for the app named "${this.appName_}" are invalid. This usually indicates your app was not initialized correctly.`)}}class en{constructor(e,t,n){this.appName_=e,this.firebaseOptions_=t,this.authProvider_=n,this.auth_=null,this.auth_=n.getImmediate({optional:!0}),this.auth_||n.onInit(e=>this.auth_=e)}getToken(e){return this.auth_?this.auth_.getToken(e).catch(e=>e&&"auth/token-not-initialized"===e.code?(x("Got auth/token-not-initialized error.  Treating as null token."),null):Promise.reject(e)):new Promise((t,n)=>{setTimeout(()=>{this.auth_?this.getToken(e).then(t,n):t(null)},0)})}addTokenChangeListener(e){this.auth_?this.auth_.addAuthTokenListener(e):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. ';"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.':"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.':e+='Make sure the "apiKey" and "databaseURL" properties provided to initializeApp() match the values provided for your app at https://console.firebase.google.com/.',U(e)}}class ei{constructor(e){this.accessToken=e}getToken(e){return Promise.resolve({accessToken:this.accessToken})}addTokenChangeListener(e){e(this.accessToken)}removeTokenChangeListener(e){}notifyForInvalidToken(){}}ei.OWNER="owner";
1let er=/(console\.firebase|firebase-console-\w+\.corp|firebase\.corp)\.google\.com/,es="websocket",eo="long_polling";class ea{constructor(e,t,n,i,r=!1,s="",o=!1,a=!1){this.secure=t,this.namespace=n,this.webSocketOnly=i,this.nodeAdmin=r,this.persistenceKey=s,this.includeNamespaceInQueryParams=o,this.isUsingEmulator=a,this._host=e.toLowerCase(),this._domain=this._host.substr(this._host.indexOf(".")+1),this.internalHost=T.get("host:"+e)||this._host}isCacheableHost(){return"s-"===this.internalHost.substr(0,2)}isCustomHost(){return"firebaseio.com"!==this._domain&&"firebaseio-demo.com"!==this._domain}get host(){return this._host}set host(e){e!==this.internalHost&&(this.internalHost=e,this.isCacheableHost()&&T.set("host:"+this._host,this.internalHost))}toString(){let e=this.toURLString();return this.persistenceKey&&(e+="<"+this.persistenceKey+">"),e}toURLString(){let e=this.secure?"https://":"http://",t=this.includeNamespaceInQueryParams?`?ns=${this.namespace}`:"";return`${e}${this.host}/${t}`}}function el(e,t,n){let i;if((0,m.assert)("string"==typeof t,"typeof type must == string"),(0,m.assert)("object"==typeof n,"typeof params must == object"),t===es)i=(e.secure?"wss://":"ws://")+e.internalHost+"/.ws?";else if(t===eo)i=(e.secure?"https://":"http://")+e.internalHost+"/.lp?";else throw Error("Unknown connection type: "+t);(e.host!==e.internalHost||e.isCustomHost()||e.includeNamespaceInQueryParams)&&(n.ns=e.namespace);let r=[];return Y(n,(e,t)=>{r.push(e+"="+t)}),i+r.join("&")}class eh{constructor(){this.counters_={}}incrementCounter(e,t=1){(0,m.contains)(this.counters_,e)||(this.counters_[e]=0),this.counters_[e]+=t}get(){return(0,m.deepCopy)(this.counters_)}}let ec={},eu={};function ed(e){let t=e.toString();return ec[t]||(ec[t]=new eh),ec[t]}class ep{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,this.closeAfterResponse<this.currentResponseNum&&(this.onClose(),this.onClose=null)}handleResponse(e,t){for(this.pendingResponses[e]=t;this.pendingResponses[this.currentResponseNum];){let e=this.pendingResponses[this.currentResponseNum];delete this.pendingResponses[this.currentResponseNum];for(let t=0;t<e.length;++t)e[t]&&Z(()=>{this.onMessage_(e[t])});if(this.currentResponseNum===this.closeAfterResponse){this.onClose&&(this.onClose(),this.onClose=null);break}this.currentResponseNum++}}}let ef="start";class e_{constructor(e,t,n,i,r,s,o){this.connId=e,this.repoInfo=t,this.applicationId=n,this.appCheckToken=i,this.authToken=r,this.transportSessionId=s,this.lastSessionId=o,this.bytesSent=0,this.bytesReceived=0,this.everConnected_=!1,this.log_=L(e),this.stats_=ed(t),this.urlFn=e=>(this.appCheckToken&&(e.ac=this.appCheckToken),el(t,eo,e))}open(e,t){this.curSegmentNum=0,this.onDisconnect_=t,this.myPacketOrderer=new ep(e),this.isClosed_=!1,this.connectTimeoutTimer_=setTimeout(()=>{this.log_("Timed out trying to connect."),this.onClosed_(),this.connectTimeoutTimer_=null},Math.floor(3e4)),W(()=>{if(this.isClosed_)return;this.scriptTagHolder=new eg((...e)=>{let[t,n,i,r,s]=e;if(this.incrementIncomingBytes_(e),this.scriptTagHolder)if(this.connectTimeoutTimer_&&(clearTimeout(this.connectTimeoutTimer_),this.connectTimeoutTimer_=null),this.everConnected_=!0,t===ef)this.id=n,this.password=i;else if("close"===t)n?(this.scriptTagHolder.sendNewPolls=!1,this.myPacketOrderer.closeAfter(n,()=>{this.onClosed_()})):this.onClosed_();else throw Error("Unrecognized command received: "+t)},(...e)=>{let[t,n]=e;this.incrementIncomingBytes_(e),this.myPacketOrderer.handleResponse(t,n)},()=>{this.onClosed_()},this.urlFn);let e={};e[ef]="t",e.ser=Math.floor(1e8*Math.random()),this.scriptTagHolder.uniqueCallbackIdentifier&&(e.cb=this.scriptTagHolder.uniqueCallbackIdentifier),e.v="5",this.transportSessionId&&(e.s=this.transportSessionId),this.lastSessionId&&(e.ls=this.lastSessionId),this.applicationId&&(e.p=this.applicationId),this.appCheckToken&&(e.ac=this.appCheckToken),"u">typeof location&&location.hostname&&er.test(location.hostname)&&(e.r="f");let 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(){e_.forceAllow_=!0}static forceDisallow(){e_.forceDisallow_=!0}
1static isAvailable(){return!(0,m.isNodeSdk)()&&(!!e_.forceAllow_||!e_.forceDisallow_&&"u">typeof document&&null!=document.createElement&&!("object"==typeof window&&window.chrome&&window.chrome.extension&&!/^chrome/.test(window.location.href))&&("object"!=typeof Windows||"object"!=typeof Windows.UI))}markConnectionHealthy(){}shutdown_(){this.isClosed_=!0,this.scriptTagHolder&&(this.scriptTagHolder.close(),this.scriptTagHolder=null),this.myDisconnFrame&&(document.body.removeChild(this.myDisconnFrame),this.myDisconnFrame=null),this.connectTimeoutTimer_&&(clearTimeout(this.connectTimeoutTimer_),this.connectTimeoutTimer_=null)}onClosed_(){!this.isClosed_&&(this.log_("Longpoll is closing itself"),this.shutdown_(),this.onDisconnect_&&(this.onDisconnect_(this.everConnected_),this.onDisconnect_=null))}close(){this.isClosed_||(this.log_("Longpoll is being closed."),this.shutdown_())}send(e){let t=(0,m.stringify)(e);this.bytesSent+=t.length,this.stats_.incrementCounter("bytes_sent",t.length);let n=G((0,m.base64Encode)(t),1840);for(let e=0;e<n.length;e++)this.scriptTagHolder.enqueueSegment(this.curSegmentNum,n.length,n[e]),this.curSegmentNum++}addDisconnectPingFrame(e,t){if((0,m.isNodeSdk)())return;this.myDisconnFrame=document.createElement("iframe");let n={};n.dframe="t",n.id=e,n.pw=t,this.myDisconnFrame.src=this.urlFn(n),this.myDisconnFrame.style.display="none",document.body.appendChild(this.myDisconnFrame)}incrementIncomingBytes_(e){let t=(0,m.stringify)(e).length;this.bytesReceived+=t,this.stats_.incrementCounter("bytes_received",t)}}class eg{constructor(e,t,n,i){if(this.onDisconnect=n,this.urlFn=i,this.outstandingRequests=new Set,this.pendingSegs=[],this.currentSerial=Math.floor(1e8*Math.random()),this.sendNewPolls=!0,(0,m.isNodeSdk)())this.commandCB=e,this.onMessageCB=t;else{this.uniqueCallbackIdentifier=P(),window["pLPCommand"+this.uniqueCallbackIdentifier]=e,window["pRTLPCB"+this.uniqueCallbackIdentifier]=t,this.myIFrame=eg.createIFrame_();let n="";this.myIFrame.src&&"javascript:"===this.myIFrame.src.substr(0,11)&&(n='<script>document.domain="'+document.domain+'";</script>');const i="<html><body>"+n+"</body></html>";try{this.myIFrame.doc.open(),this.myIFrame.doc.write(i),this.myIFrame.doc.close()}catch(e){x("frame writing exception"),e.stack&&x(e.stack),x(e)}}}static createIFrame_(){let e=document.createElement("iframe");if(e.style.display="none",document.body){document.body.appendChild(e);try{e.contentWindow.document||x("No IE domain setting required")}catch(t){e.src="javascript:void((function(){document.open();document.domain='"+document.domain+"';document.close();})())"}}else throw"Document body has not initialized. Wait to initialize Firebase until after the document is ready.";return e.contentDocument?e.doc=e.contentDocument:e.contentWindow?e.doc=e.contentWindow.document:e.document&&(e.doc=e.document),e}close(){this.alive=!1,this.myIFrame&&(this.myIFrame.doc.body.textContent="",setTimeout(()=>{null!==this.myIFrame&&(document.body.removeChild(this.myIFrame),this.myIFrame=null)},Math.floor(0)));let e=this.onDisconnect;e&&(this.onDisconnect=null,e())}startLongPoll(e,t){for(this.myID=e,this.myPW=t,this.alive=!0;this.newRequest_(););}newRequest_(){if(!this.alive||!this.sendNewPolls||!(this.outstandingRequests.size<(this.pendingSegs.length>0?2:1)))return!1;{this.currentSerial++;let e={};e.id=this.myID,e.pw=this.myPW,e.ser=this.currentSerial;let t=this.urlFn(e),n="",i=0;for(;this.pendingSegs.length>0;)if(this.pendingSegs[0].d.length+30+n.length<=1870){let e=this.pendingSegs.shift();n=n+"&seg"+i+"="+e.seg+"&ts"+i+"="+e.ts+"&d"+i+"="+e.d,i++}else break;return t+=n,this.addLongPollTag_(t,this.currentSerial),!0}}enqueueSegment(e,t,n){this.pendingSegs.push({seg:e,ts:t,d:n}),this.alive&&this.newRequest_()}addLongPollTag_(e,t){this.outstandingRequests.add(t);let n=()=>{this.outstandingRequests.delete(t),this.newRequest_()},i=setTimeout(n,Math.floor(25e3));this.addTag(e,()=>{clearTimeout(i),n()})}addTag(e,t){(0,m.isNodeSdk)()?this.doNodeLongPoll(e,t):setTimeout(()=>{try{if(!this.sendNewPolls)return;let n=this.myIFrame.doc.createElement("script");n.type="text/javascript",n.async=!0,n.src=e,n.onload=n.onreadystatechange=function(){let e=n.readyState;e&&"loaded"!==e&&"complete"!==e||(n.onload=n.onreadystatechange=null,n.parentNode&&n.parentNode.removeChild(n),t())},n.onerror=()=>{x("Long-poll script failed to load: "+e),this.sendNewPolls=!1,this.close()},this.myIFrame.doc.body.appendChild(n)}catch(e){}},Math.floor(1))}}let em=null;"u">typeof MozWebSocket?em=MozWebSocket:"u">typeof WebSocket&&(em=WebSocket);class ey{constructor(e,t,n,i,r,s,o){this.connId=e,this.applicationId=n,this.appCheckToken=i,this.authToken=r,this.keepaliveTimer=null,this.frames=null,this.totalFrames=0,this.bytesSent=0,this.bytesReceived=0,this.log_=L(this.connId),this.stats_=ed(t),this.connURL=ey.connectionURL_(t,s,o,i,n),this.nodeAdmin=t.nodeAdmin}static connectionURL_(e,t,n,i,r){let s={};return s.v="5",!(0,m.isNodeSdk)()&&"u">typeof location&&location.hostname&&er.test(location.hostname)&&(s.r="f"),t&&(s.s=t),n&&(s.ls=n),i&&(s.ac=i),r&&(s.p=r),el(e,es,s)}open(e,t){this.onDisconnect=t,this.onMessage=e,this.log_("Websocket connecting to "+this.connURL),this.everConnected_=!1,T.set("previous_websocket_failure",!0);try{let e;if((0,m.isNodeSdk)()){let t=this.nodeAdmin?"AdminNode":"Node";e={headers:{"User-Agent":`Firebase/5/${I}/${f.default.platform}/${t}`,"X-Firebase-GMPID":this.applicationId||""}},this.authToken&&(e.headers.Authorization=`Bearer ${this.authToken}`),this.appCheckToken&&(e.headers["X-Firebase-AppCheck"]=this.appCheckToken);let n=f.default.env,i=0===this.connURL.indexOf("wss://")?n.HTTPS_PROXY||n.https_proxy:n.HTTP_PROXY||n.http_proxy;i&&(e.proxy={origin:i})}this.mySock=new em(this.connURL,[],e)}catch(t){this.log_("Error instantiating WebSocket.");let e=t.message||t.data;e&&this.log_(e),this.onClosed_();return}this.mySock.onopen=()=>{this.log_("Websocket connected."),this.everConnected_=!0}
1,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.");let t=e.message||e.data;t&&this.log_(t),this.onClosed_()}}start(){}static forceDisallow(){ey.forceDisallow_=!0}static isAvailable(){let e=!1;if("u">typeof navigator&&navigator.userAgent){let t=navigator.userAgent.match(/Android ([0-9]{0,}\.[0-9]{0,})/);t&&t.length>1&&4.4>parseFloat(t[1])&&(e=!0)}return!e&&null!==em&&!ey.forceDisallow_}static previouslyFailed(){return T.isInMemoryStorage||!0===T.get("previous_websocket_failure")}markConnectionHealthy(){T.remove("previous_websocket_failure")}appendFrame_(e){if(this.frames.push(e),this.frames.length===this.totalFrames){let e=this.frames.join("");this.frames=null;let t=(0,m.jsonEval)(e);this.onMessage(t)}}handleNewFrameCount_(e){this.totalFrames=e,this.frames=[]}extractFrameCount_(e){if((0,m.assert)(null===this.frames,"We already have a frame buffer"),e.length<=6){let t=Number(e);if(!isNaN(t))return this.handleNewFrameCount_(t),null}return this.handleNewFrameCount_(1),e}handleIncomingFrame(e){if(null===this.mySock)return;let t=e.data;if(this.bytesReceived+=t.length,this.stats_.incrementCounter("bytes_received",t.length),this.resetKeepAlive(),null!==this.frames)this.appendFrame_(t);else{let e=this.extractFrameCount_(t);null!==e&&this.appendFrame_(e)}}send(e){this.resetKeepAlive();let t=(0,m.stringify)(e);this.bytesSent+=t.length,this.stats_.incrementCounter("bytes_sent",t.length);let n=G(t,16384);n.length>1&&this.sendString_(String(n.length));for(let e=0;e<n.length;e++)this.sendString_(n[e])}shutdown_(){this.isClosed_=!0,this.keepaliveTimer&&(clearInterval(this.keepaliveTimer),this.keepaliveTimer=null),this.mySock&&(this.mySock.close(),this.mySock=null)}onClosed_(){!this.isClosed_&&(this.log_("WebSocket is closing itself"),this.shutdown_(),this.onDisconnect&&(this.onDisconnect(this.everConnected_),this.onDisconnect=null))}close(){this.isClosed_||(this.log_("WebSocket is being closed"),this.shutdown_())}resetKeepAlive(){clearInterval(this.keepaliveTimer),this.keepaliveTimer=setInterval(()=>{this.mySock&&this.sendString_("0"),this.resetKeepAlive()},Math.floor(45e3))}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)}}}ey.responsesRequiredToBeHealthy=2,ey.healthyTimeout=3e4;class ev{constructor(e){this.initTransports_(e)}static get ALL_TRANSPORTS(){return[e_,ey]}static get IS_TRANSPORT_INITIALIZED(){return this.globalTransportInitialized_}initTransports_(e){let t=ey&&ey.isAvailable(),n=t&&!ey.previouslyFailed();if(e.webSocketOnly&&(t||U("wss:// URL used, but browser isn't known to support websockets.  Trying anyway."),n=!0),n)this.transports_=[ey];else{let e=this.transports_=[];for(let t of ev.ALL_TRANSPORTS)t&&t.isAvailable()&&e.push(t);ev.globalTransportInitialized_=!0}}initialTransport(){if(this.transports_.length>0)return this.transports_[0];throw Error("No transports available")}upgradeTransport(){return this.transports_.length>1?this.transports_[1]:null}}ev.globalTransportInitialized_=!1;class ew{constructor(e,t,n,i,r,s,o,a,l,h){this.id=e,this.repoInfo_=t,this.applicationId_=n,this.appCheckToken_=i,this.authToken_=r,this.onMessage_=s,this.onReady_=o,this.onDisconnect_=a,this.onKill_=l,this.lastSessionId=h,this.connectionCount=0,this.pendingDataMessages=[],this.state_=0,this.log_=L("c:"+this.id+":"),this.transportManager_=new ev(t),this.log_("Connection created"),this.start_()}start_(){let 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;let t=this.connReceiver_(this.conn_),n=this.disconnReceiver_(this.conn_);this.tx_=this.conn_,this.rx_=this.conn_,this.secondaryConn_=null,this.isHealthy_=!1,setTimeout(()=>{this.conn_&&this.conn_.open(t,n)},Math.floor(0));let i=e.healthyTimeout||0;i>0&&(this.healthyTimeout_=ee(()=>{this.healthyTimeout_=null,this.isHealthy_||(this.conn_&&this.conn_.bytesReceived>102400?(this.log_("Connection exceeded healthy timeout but has received "+this.conn_.bytesReceived+" bytes.  Marking connection healthy."),this.isHealthy_=!0,this.conn_.markConnectionHealthy()):this.conn_&&this.conn_.bytesSent>10240?this.log_("Connection exceeded healthy timeout but has sent "+this.conn_.bytesSent+" bytes.  Leaving connection alive."):(this.log_("Closing unhealthy connection after timeout."),this.close()))},Math.floor(i)))}nextTransportId_(){return"c:"+this.id+":"+this.connectionCount++}disconnReceiver_(e){return t=>{e===this.conn_?this.onConnectionLost_(t):e===this.secondaryConn_?(this.log_("Secondary connection lost."),this.onSecondaryConnectionLost_()):this.log_("closing an old connection")}}connReceiver_(e){return t=>{2!==this.state_&&(e===this.rx_?this.onPrimaryMessageReceived_(t):e===this.secondaryConn_?this.onSecondaryMessageReceived_(t):this.log_("message on old connection"))}}sendRequest(e){this.sendData_({t:"d",d:e})}tryCleanupConnection(){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("t"in e){let t=e.t;"a"===t?this.upgradeIfSecondaryHealthy_():"r"===t?(this.log_("Got a reset on secondary, closing it"),this.secondaryConn_.close(),(this.tx_===this.secondaryConn_||this.rx_===this.secondaryConn_)&&this.close()):"o"===t&&(this.log_("got pong on secondary."),this.secondaryResponsesRequired_--,this.upgradeIfSecondaryHealthy_())}}onSecondaryMessageReceived_(e){let t=$("t",e),n=$("d",e);if("c"===t)this.onSecondaryControl_(n);else if("d"===t)this.pendingDataMessages.push(n);else throw Error("Unknown protocol layer: "+t)}upgradeIfSecondaryHealthy_(){this.secondaryResponsesRequired_<=0?(this.log_("Secondary connection is healthy."),this.isHealthy_=!0,this.secondaryConn_.markConnectionHealthy(),this.proceedWithUpgrade_()):(this.log_("sending ping on secondary."),this.secondaryConn_.send({t
1:"c",d:{t:"p",d:{}}}))}proceedWithUpgrade_(){this.secondaryConn_.start(),this.log_("sending client ack on secondary"),this.secondaryConn_.send({t:"c",d:{t:"a",d:{}}}),this.log_("Ending transmission on primary"),this.conn_.send({t:"c",d:{t:"n",d:{}}}),this.tx_=this.secondaryConn_,this.tryCleanupConnection()}onPrimaryMessageReceived_(e){let t=$("t",e),n=$("d",e);"c"===t?this.onControl_(n):"d"===t&&this.onDataMessage_(n)}onDataMessage_(e){this.onPrimaryResponse_(),this.onMessage_(e)}onPrimaryResponse_(){!this.isHealthy_&&(this.primaryResponsesRequired_--,this.primaryResponsesRequired_<=0&&(this.log_("Primary connection is healthy."),this.isHealthy_=!0,this.conn_.markConnectionHealthy()))}onControl_(e){let t=$("t",e);if("d"in e){let n=e.d;if("h"===t){let e=Object.assign({},n);this.repoInfo_.isUsingEmulator&&(e.h=this.repoInfo_.host),this.onHandshake_(e)}else if("n"===t){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"s"===t?this.onConnectionShutdown_(n):"r"===t?this.onReset_(n):"e"===t?M("Server Error: "+n):"o"===t?(this.log_("got pong on primary."),this.onPrimaryResponse_(),this.sendPingOnPrimaryIfNecessary_()):M("Unknown control packet command: "+t)}}onHandshake_(e){let t=e.ts,n=e.v,i=e.h;this.sessionId=e.s,this.repoInfo_.host=i,0===this.state_&&(this.conn_.start(),this.onConnectionEstablished_(this.conn_,t),"5"!==n&&U("Protocol version mismatch detected"),this.tryStartUpgrade_())}tryStartUpgrade_(){let e=this.transportManager_.upgradeTransport();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;let t=this.connReceiver_(this.secondaryConn_),n=this.disconnReceiver_(this.secondaryConn_);this.secondaryConn_.open(t,n),ee(()=>{this.secondaryConn_&&(this.log_("Timed out trying to upgrade."),this.secondaryConn_.close())},Math.floor(6e4))}onReset_(e){this.log_("Reset packet received.  New host: "+e),this.repoInfo_.host=e,1===this.state_?this.close():(this.closeConnections_(),this.start_())}onConnectionEstablished_(e,t){this.log_("Realtime connection established."),this.conn_=e,this.state_=1,this.onReady_&&(this.onReady_(t,this.sessionId),this.onReady_=null),0===this.primaryResponsesRequired_?(this.log_("Primary connection is healthy."),this.isHealthy_=!0):ee(()=>{this.sendPingOnPrimaryIfNecessary_()},Math.floor(5e3))}sendPingOnPrimaryIfNecessary_(){this.isHealthy_||1!==this.state_||(this.log_("sending ping on primary."),this.sendData_({t:"c",d:{t:"p",d:{}}}))}onSecondaryConnectionLost_(){let e=this.secondaryConn_;this.secondaryConn_=null,(this.tx_===e||this.rx_===e)&&this.close()}onConnectionLost_(e){this.conn_=null,e||0!==this.state_?1===this.state_&&this.log_("Realtime connection lost."):(this.log_("Realtime connection failed."),this.repoInfo_.isCacheableHost()&&(T.remove("host:"+this.repoInfo_.host),this.repoInfo_.internalHost=this.repoInfo_.host)),this.close()}onConnectionShutdown_(e){this.log_("Connection shutdown command received. Shutting down..."),this.onKill_&&(this.onKill_(e),this.onKill_=null),this.onDisconnect_=null,this.close()}sendData_(e){if(1!==this.state_)throw"Connection is not connected";this.tx_.send(e)}close(){2!==this.state_&&(this.log_("Closing realtime connection."),this.state_=2,this.closeConnections_(),this.onDisconnect_&&(this.onDisconnect_(),this.onDisconnect_=null))}closeConnections_(){this.log_("Shutting down all connections"),this.conn_&&(this.conn_.close(),this.conn_=null),this.secondaryConn_&&(this.secondaryConn_.close(),this.secondaryConn_=null),this.healthyTimeout_&&(clearTimeout(this.healthyTimeout_),this.healthyTimeout_=null)}}class eI{put(e,t,n,i){}merge(e,t,n,i){}refreshAuthToken(e){}refreshAppCheckToken(e){}onDisconnectPut(e,t,n){}onDisconnectMerge(e,t,n){}onDisconnectCancel(e,t){}reportStats(e){}}class eC{constructor(e){this.allowedEvents_=e,this.listeners_={},(0,m.assert)(Array.isArray(e)&&e.length>0,"Requires a non-empty array")}trigger(e,...t){if(Array.isArray(this.listeners_[e])){let 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});let i=this.getInitialEvent(e);i&&t.apply(n,i)}off(e,t,n){this.validateEventType_(e);let i=this.listeners_[e]||[];for(let e=0;e<i.length;e++)if(i[e].callback===t&&(!n||n===i[e].context))return void i.splice(e,1)}validateEventType_(e){(0,m.assert)(this.allowedEvents_.find(t=>t===e),"Unknown event: "+e)}}class eb extends eC{constructor(){super(["online"]),this.online_=!0,"u">typeof window&&void 0!==window.addEventListener&&!(0,m.isMobileCordova)()&&(window.addEventListener("online",()=>{this.online_||(this.online_=!0,this.trigger("online",!0))},!1),window.addEventListener("offline",()=>{this.online_&&(this.online_=!1,this.trigger("online",!1))},!1))}static getInstance(){return new eb}getInitialEvent(e){return(0,m.assert)("online"===e,"Unknown event type: "+e),[this.online_]}currentlyOnline(){return this.online_}}class eE{constructor(e,t){if(void 0===t){this.pieces_=e.split("/");let t=0;for(let e=0;e<this.pieces_.length;e++)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++)""!==this.pieces_[t]&&(e+="/"+this.pieces_[t]);return e||"/"}}function eT(){return new eE("")}function eS(e){return e.pieceNum_>=e.pieces_.length?null:e.pieces_[e.pieceNum_]}function ek(e){return e.pieces_.length-e.pieceNum_}function eP(e){let t=e.pieceNum_;return t<e.pieces_.length&&t++,new eE(e.pieces_,t)}function eN(e){return e.pieceNum_<e.pieces_.length?e.pieces_[e.pieces_.length-1]:null}function eR(e,t=0){return e.pieces_.slice(e.pieceNum_+t)}function eA(e){if(e.pieceNum_>=e.pieces_.length)return null;let t=[];for(let n=e.pieceNum_;n<e.pieces_.length-1;n++)t.push(e.pieces_[n]);return new eE(t,0)}function eO(e,t){let n=[];for(let t=e.pieceNum_;t<e.pieces_.length;t++)n.push(e.pieces_[t]);if(t instanceof eE)for(let e=t.pieceNum_;e<t.pieces_.length;e++)n.push(t.pieces_[e]);else{let e=t.split("/");for(let t=0;t<e.length;t++)e[t].length>0&&n.push(e[t])}return new eE(n,0)}function eD(e){return e.pieceNum_>=e.pieces_.length}function ex(e,t){let n=eS(e),i=eS(t);if(null===n)return t;if(n===i)return ex(eP(e),eP(t));
1throw Error("INTERNAL ERROR: innerPath ("+t+") is not within outerPath ("+e+")")}function eL(e,t){if(ek(e)!==ek(t))return!1;for(let n=e.pieceNum_,i=t.pieceNum_;n<=e.pieces_.length;n++,i++)if(e.pieces_[n]!==t.pieces_[i])return!1;return!0}function eM(e,t){let n=e.pieceNum_,i=t.pieceNum_;if(ek(e)>ek(t))return!1;for(;n<e.pieces_.length;){if(e.pieces_[n]!==t.pieces_[i])return!1;++n,++i}return!0}class eF{constructor(e,t){this.errorPrefix_=t,this.parts_=eR(e,0),this.byteLength_=Math.max(1,this.parts_.length);for(let e=0;e<this.parts_.length;e++)this.byteLength_+=(0,m.stringLength)(this.parts_[e]);eU(this)}}function eU(e){if(e.byteLength_>768)throw Error(e.errorPrefix_+"has a key path longer than 768 bytes ("+e.byteLength_+").");if(e.parts_.length>32)throw Error(e.errorPrefix_+"path specified exceeds the maximum depth that can be written (32) or object contains a cycle "+eq(e))}function eq(e){return 0===e.parts_.length?"":"in property '"+e.parts_.join(".")+"'"}class ej extends eC{constructor(){let e,t;super(["visible"]),"u">typeof document&&void 0!==document.addEventListener&&(void 0!==document.hidden?(t="visibilitychange",e="hidden"):void 0!==document.mozHidden?(t="mozvisibilitychange",e="mozHidden"):void 0!==document.msHidden?(t="msvisibilitychange",e="msHidden"):void 0!==document.webkitHidden&&(t="webkitvisibilitychange",e="webkitHidden")),this.visible_=!0,t&&document.addEventListener(t,()=>{let t=!document[e];t!==this.visible_&&(this.visible_=t,this.trigger("visible",t))},!1)}static getInstance(){return new ej}getInitialEvent(e){return(0,m.assert)("visible"===e,"Unknown event type: "+e),[this.visible_]}}class eW extends eI{constructor(e,t,n,i,r,s,o,a){if(super(),this.repoInfo_=e,this.applicationId_=t,this.onDataUpdate_=n,this.onConnectStatus_=i,this.onServerInfoUpdate_=r,this.authTokenProvider_=s,this.appCheckTokenProvider_=o,this.authOverride_=a,this.id=eW.nextPersistentConnectionId_++,this.log_=L("p:"+this.id+":"),this.interruptReasons_={},this.listens=new Map,this.outstandingPuts_=[],this.outstandingGets_=[],this.outstandingPutCount_=0,this.outstandingGetCount_=0,this.onDisconnectRequestQueue_=[],this.connected_=!1,this.reconnectDelay_=1e3,this.maxReconnectDelay_=3e5,this.securityDebugCallback_=null,this.lastSessionId=null,this.establishConnectionTimer_=null,this.visible_=!1,this.requestCBHash_={},this.requestNumber_=0,this.realtime_=null,this.authToken_=null,this.appCheckToken_=null,this.forceTokenRefresh_=!1,this.invalidAuthTokenCount_=0,this.invalidAppCheckTokenCount_=0,this.firstConnection_=!0,this.lastConnectionAttemptTime_=null,this.lastConnectionEstablishedTime_=null,a&&!(0,m.isNodeSdk)())throw Error("Auth override specified in options, but not supported on non Node.js platforms");ej.getInstance().on("visible",this.onVisible_,this),-1===e.host.indexOf("fblocal")&&eb.getInstance().on("online",this.onOnline_,this)}sendRequest(e,t,n){let i=++this.requestNumber_,r={r:i,a:e,b:t};this.log_((0,m.stringify)(r)),(0,m.assert)(this.connected_,"sendRequest call when we're not connected not allowed."),this.realtime_.sendRequest(r),n&&(this.requestCBHash_[i]=n)}get(e){this.initConnection_();let t=new m.Deferred,n={p:e._path.toString(),q:e._queryObject};this.outstandingGets_.push({action:"g",request:n,onComplete:e=>{let n=e.d;"ok"===e.s?t.resolve(n):t.reject(n)}}),this.outstandingGetCount_++;let i=this.outstandingGets_.length-1;return this.connected_&&this.sendGet_(i),t.promise}listen(e,t,n,i){this.initConnection_();let r=e._queryIdentifier,s=e._path.toString();this.log_("Listen called for "+s+" "+r),this.listens.has(s)||this.listens.set(s,new Map),(0,m.assert)(e._queryParams.isDefault()||!e._queryParams.loadsAllData(),"listen() called for non-default but complete query"),(0,m.assert)(!this.listens.get(s).has(r),"listen() called twice for same path/queryId.");let o={onComplete:i,hashFn:t,query:e,tag:n};this.listens.get(s).set(r,o),this.connected_&&this.sendListen_(o)}sendGet_(e){let t=this.outstandingGets_[e];this.sendRequest("g",t.request,n=>{delete this.outstandingGets_[e],this.outstandingGetCount_--,0===this.outstandingGetCount_&&(this.outstandingGets_=[]),t.onComplete&&t.onComplete(n)})}sendListen_(e){let t=e.query,n=t._path.toString(),i=t._queryIdentifier;this.log_("Listen on "+n+" for "+i);let r={p:n};e.tag&&(r.q=t._queryObject,r.t=e.tag),r.h=e.hashFn(),this.sendRequest("q",r,r=>{let s=r.d,o=r.s;eW.warnOnListenWarnings_(s,t),(this.listens.get(n)&&this.listens.get(n).get(i))===e&&(this.log_("listen response",r),"ok"!==o&&this.removeListen_(n,i),e.onComplete&&e.onComplete(o,s))})}static warnOnListenWarnings_(e,t){if(e&&"object"==typeof e&&(0,m.contains)(e,"w")){let n=(0,m.safeGet)(e,"w");if(Array.isArray(n)&&~n.indexOf("no_index")){let e='".indexOn": "'+t._queryParams.getIndex().toString()+'"',n=t._path.toString();U(`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"),this.authToken_?this.tryAuth():this.connected_&&this.sendRequest("unauth",{},()=>{}),this.reduceReconnectDelayIfAdminCredential_(e)}reduceReconnectDelayIfAdminCredential_(e){(e&&40===e.length||(0,m.isAdmin)(e))&&(this.log_("Admin auth credential detected.  Reducing max reconnect time."),this.maxReconnectDelay_=3e4)}refreshAppCheckToken(e){this.appCheckToken_=e,this.log_("App check token refreshed"),this.appCheckToken_?this.tryAppCheck():this.connected_&&this.sendRequest("unappeck",{},()=>{})}tryAuth(){if(this.connected_&&this.authToken_){let e=this.authToken_,t=(0,m.isValidFormat)(e)?"auth":"gauth",n={cred:e};null===this.authOverride_?n.noauth=!0:"object"==typeof this.authOverride_&&(n.authvar=this.authOverride_),this.sendRequest(t,n,t=>{let n=t.s,i=t.d||"error";this.authToken_===e&&("ok"===n?this.invalidAuthTokenCount_=0:this.onAuthRevoked_(n,i))})}}tryAppCheck(){this.connected_&&this.appCheckToken_&&this.sendRequest("appcheck",{token:this.appCheckToken_},e=>{let t=e.s,n=e.d||"error";"ok"===t?this.invalidAppCheckTokenCount_=0:this.onAppCheckRevoked_(t,n)})}unlisten(e,t){let n=e._path.toString(),i=e._queryIdentifier;this.log_("Unlisten called for "+n+" "+i),(0,m.assert)(e._queryParams.isDefault()||!e._queryParams.loadsAllData(),"unlisten() called for non-default but complete query"),this.removeListen_(n,i)&&this.connected_&&this.sendUnlisten_(n,i,e._queryObject,t)}sendUnlisten_(e,t,n,i){this.log_("Unlisten on "+e+" for "+t);let r={p:e};i&&(r.q=n,r.t=i),this.sendRequest("n",r)}onDisconnectPut(e,t,n){this.initConnection_(),this.connected_?this.sendOnDisconnect_("o",e,t,n):this.onDisconnectRequestQueue_.push({pathString:e,action:"o",data:t,onComplete:n})}onDisconnectMerge(e,t,n){this.initConnection_(),this.connected_?this.sendOnDisconnect_("om",e,t,n):this.onDisconnectRequestQueue_.push({pathString:e,action:"om",data:t,onComplete:n})}onDisconnectCancel(e,t){this.initConnection_(),this.connected_?this.sendOnDisconnect_("oc",e,null,t):this.onDisconnectRequestQueue_.push({pathString:e,action:"oc",data:null,onComplete:t})}sendOnDisconnect_(e,t,n,i){let r={p:t,d:n};this.log_("onDisconnect "+e,r),this.sendRequest(e,r,e=>
1{i&&setTimeout(()=>{i(e.s,e.d)},Math.floor(0))})}put(e,t,n,i){this.putInternal("p",e,t,n,i)}merge(e,t,n,i){this.putInternal("m",e,t,n,i)}putInternal(e,t,n,i,r){this.initConnection_();let s={p:t,d:n};void 0!==r&&(s.h=r),this.outstandingPuts_.push({action:e,request:s,onComplete:i}),this.outstandingPutCount_++;let o=this.outstandingPuts_.length-1;this.connected_?this.sendPut_(o):this.log_("Buffering put: "+t)}sendPut_(e){let t=this.outstandingPuts_[e].action,n=this.outstandingPuts_[e].request,i=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_--,0===this.outstandingPutCount_&&(this.outstandingPuts_=[]),i&&i(n.s,n.d)})}reportStats(e){if(this.connected_){let t={c:e};this.log_("reportStats",t),this.sendRequest("s",t,e=>{if("ok"!==e.s){let t=e.d;this.log_("reportStats","Error sending stats: "+t)}})}}onDataMessage_(e){if("r"in e){this.log_("from server: "+(0,m.stringify)(e));let t=e.r,n=this.requestCBHash_[t];n&&(delete this.requestCBHash_[t],n(e.b))}else if("error"in e)throw"A server-side error has occurred: "+e.error;else"a"in e&&this.onDataPush_(e.a,e.b)}onDataPush_(e,t){this.log_("handleServerMessage",e,t),"d"===e?this.onDataUpdate_(t.p,t.d,!1,t.t):"m"===e?this.onDataUpdate_(t.p,t.d,!0,t.t):"c"===e?this.onListenRevoked_(t.p,t.q):"ac"===e?this.onAuthRevoked_(t.s,t.d):"apc"===e?this.onAppCheckRevoked_(t.s,t.d):"sd"===e?this.onSecurityDebugPacket_(t):M("Unrecognized action received from server: "+(0,m.stringify)(e)+"\nAre you using the latest client?")}onReady_(e,t){this.log_("connection ready"),this.connected_=!0,this.lastConnectionEstablishedTime_=new Date().getTime(),this.handleTimestamp_(e),this.lastSessionId=t,this.firstConnection_&&this.sendConnectStats_(),this.restoreState_(),this.firstConnection_=!1,this.onConnectStatus_(!0)}scheduleConnect_(e){(0,m.assert)(!this.realtime_,"Scheduling a connect when we're already connected/ing?"),this.establishConnectionTimer_&&clearTimeout(this.establishConnectionTimer_),this.establishConnectionTimer_=setTimeout(()=>{this.establishConnectionTimer_=null,this.establishConnection_()},Math.floor(e))}initConnection_(){!this.realtime_&&this.firstConnection_&&this.scheduleConnect_(0)}onVisible_(e){e&&!this.visible_&&this.reconnectDelay_===this.maxReconnectDelay_&&(this.log_("Window became visible.  Reducing delay."),this.reconnectDelay_=1e3,this.realtime_||this.scheduleConnect_(0)),this.visible_=e}onOnline_(e){e?(this.log_("Browser went online."),this.reconnectDelay_=1e3,this.realtime_||this.scheduleConnect_(0)):(this.log_("Browser went offline.  Killing connection."),this.realtime_&&this.realtime_.close())}onRealtimeDisconnect_(){if(this.log_("data client disconnected"),this.connected_=!1,this.realtime_=null,this.cancelSentTransactions_(),this.requestCBHash_={},this.shouldReconnect_()){this.visible_?this.lastConnectionEstablishedTime_&&(new Date().getTime()-this.lastConnectionEstablishedTime_>3e4&&(this.reconnectDelay_=1e3),this.lastConnectionEstablishedTime_=null):(this.log_("Window isn't visible.  Delaying reconnect."),this.reconnectDelay_=this.maxReconnectDelay_,this.lastConnectionAttemptTime_=new Date().getTime());let e=new Date().getTime()-this.lastConnectionAttemptTime_,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_,1.3*this.reconnectDelay_)}this.onConnectStatus_(!1)}async establishConnection_(){if(this.shouldReconnect_()){this.log_("Making a connection attempt"),this.lastConnectionAttemptTime_=new Date().getTime(),this.lastConnectionEstablishedTime_=null;let e=this.onDataMessage_.bind(this),t=this.onReady_.bind(this),n=this.onRealtimeDisconnect_.bind(this),i=this.id+":"+eW.nextConnectionId_++,r=this.lastSessionId,s=!1,o=null,a=function(){o?o.close():(s=!0,n())};this.realtime_={close:a,sendRequest:function(e){(0,m.assert)(o,"sendRequest call when we're not connected not allowed."),o.send
1Request(e)}};let l=this.forceTokenRefresh_;this.forceTokenRefresh_=!1;try{let[a,h]=await Promise.all([this.authTokenProvider_.getToken(l),this.appCheckTokenProvider_.getToken(l)]);s?x("getToken() completed but was canceled"):(x("getToken() completed. Creating connection."),this.authToken_=a&&a.accessToken,this.appCheckToken_=h&&h.token,o=new ew(i,this.repoInfo_,this.applicationId_,this.appCheckToken_,this.authToken_,e,t,n,e=>{U(e+" ("+this.repoInfo_.toString()+")"),this.interrupt("server_kill")},r))}catch(e){this.log_("Failed to get token: "+e),s||(this.repoInfo_.nodeAdmin&&U(e),a())}}}interrupt(e){x("Interrupting connection for reason: "+e),this.interruptReasons_[e]=!0,this.realtime_?this.realtime_.close():(this.establishConnectionTimer_&&(clearTimeout(this.establishConnectionTimer_),this.establishConnectionTimer_=null),this.connected_&&this.onRealtimeDisconnect_())}resume(e){x("Resuming connection for reason: "+e),delete this.interruptReasons_[e],(0,m.isEmpty)(this.interruptReasons_)&&(this.reconnectDelay_=1e3,this.realtime_||this.scheduleConnect_(0))}handleTimestamp_(e){let t=e-new Date().getTime();this.onServerInfoUpdate_({serverTimeOffset:t})}cancelSentTransactions_(){for(let e=0;e<this.outstandingPuts_.length;e++){let t=this.outstandingPuts_[e];t&&"h"in t.request&&t.queued&&(t.onComplete&&t.onComplete("disconnect"),delete this.outstandingPuts_[e],this.outstandingPutCount_--)}0===this.outstandingPutCount_&&(this.outstandingPuts_=[])}onListenRevoked_(e,t){let n;n=t?t.map(e=>K(e)).join("$"):"default";let i=this.removeListen_(e,n);i&&i.onComplete&&i.onComplete("permission_denied")}removeListen_(e,t){let n,i=new eE(e).toString();if(this.listens.has(i)){let e=this.listens.get(i);n=e.get(t),e.delete(t),0===e.size&&this.listens.delete(i)}else n=void 0;return n}onAuthRevoked_(e,t){x("Auth token revoked: "+e+"/"+t),this.authToken_=null,this.forceTokenRefresh_=!0,this.realtime_.close(),("invalid_token"===e||"permission_denied"===e)&&(this.invalidAuthTokenCount_++,this.invalidAuthTokenCount_>=3&&(this.reconnectDelay_=3e4,this.authTokenProvider_.notifyForInvalidToken()))}onAppCheckRevoked_(e,t){x("App check token revoked: "+e+"/"+t),this.appCheckToken_=null,this.forceTokenRefresh_=!0,("invalid_token"===e||"permission_denied"===e)&&(this.invalidAppCheckTokenCount_++,this.invalidAppCheckTokenCount_>=3&&this.appCheckTokenProvider_.notifyForInvalidToken())}onSecurityDebugPacket_(e){this.securityDebugCallback_?this.securityDebugCallback_(e):"msg"in e&&console.log("FIREBASE: "+e.msg.replace("\n","\nFIREBASE: "))}restoreState_(){for(let e of(this.tryAuth(),this.tryAppCheck(),this.listens.values()))for(let t of e.values())this.sendListen_(t);for(let e=0;e<this.outstandingPuts_.length;e++)this.outstandingPuts_[e]&&this.sendPut_(e);for(;this.onDisconnectRequestQueue_.length;){let e=this.onDisconnectRequestQueue_.shift();this.sendOnDisconnect_(e.action,e.pathString,e.data,e.onComplete)}for(let e=0;e<this.outstandingGets_.length;e++)this.outstandingGets_[e]&&this.sendGet_(e)}sendConnectStats_(){let e={},t="js";(0,m.isNodeSdk)()&&(t=this.repoInfo_.nodeAdmin?"admin_node":"node"),e["sdk."+t+"."+I.replace(/\./g,"-")]=1,(0,m.isMobileCordova)()?e["framework.cordova"]=1:(0,m.isReactNative)()&&(e["framework.reactnative"]=1),this.reportStats(e)}shouldReconnect_(){let e=eb.getInstance().currentlyOnline();return(0,m.isEmpty)(this.interruptReasons_)&&e}}eW.nextPersistentConnectionId_=0,eW.nextConnectionId_=0;class eV{constructor(e,t){this.name=e,this.node=t}static Wrap(e,t){return new eV(e,t)}}class eH{getCompare(){return this.compare.bind(this)}indexedValueChanged(e,t){let n=new eV(V,e),i=new eV(V,t);return 0!==this.compare(n,i)}minPost(){return eV.MIN}}class eB extends eH{static get __EMPTY_NODE(){return t}static set __EMPTY_NODE(e){t=e}compare(e,t){return B(e.name,t.name)}isDefinedOn(e){throw(0,m.assertionError)("KeyIndex.isDefinedOn not expected to be called.")}indexedValueChanged(e,t){return!1}minPost(){return eV.MIN}maxPost(){return new eV(H,t)}makePost(e,n){return(0,m.assert)("string"==typeof e,"KeyIndex indexValue must always be a string."),new eV(e,t)}toString(){return".key"}}let ez=new eB;class e${constructor(e,t,n,i,r=null){this.isReverse_=i,this.resultGenerator_=r,this.nodeStack_=[];let s=1;for(;!e.isEmpty();)if(s=t?n(e.key,t):1,i&&(s*=-1),s<0)e=this.isReverse_?e.left:e.right;else if(0===s){this.nodeStack_.push(e);break}else this.nodeStack_.push(e),e=this.isReverse_?e.right:e.left}getNext(){let e;if(0===this.nodeStack_.length)return null;let t=this.nodeStack_.pop();if(e=this.resultGenerator_?this.resultGenerator_(t.key,t.value):{key:t.key,value:t.value},this.isReverse_)for(t=t.left;!t.isEmpty();)this.nodeStack_.push(t),t=t.right;else for(t=t.right;!t.isEmpty();)this.nodeStack_.push(t),t=t.left;return e}hasNext(){return this.nodeStack_.length>0}peek(){if(0===this.nodeStack_.length)return null;let e=this.nodeStack_[this.nodeStack_.length-1];return this.resultGenerator_?this.resultGenerator_(e.key,e.value):{key:e.key,value:e.value}}}class eK{constructor(e,t,n,i,r){this.key=e,this.value=t,this.color=null!=n?n:eK.RED,this.left=null!=i?i:eG.EMPTY_NODE,this.right=null!=r?r:eG.EMPTY_NODE}copy(e,t,n,i,r){return new eK(null!=e?e:this.key,null!=t?t:this.value,
1null!=n?n:this.color,null!=i?i:this.left,null!=r?r:this.right)}count(){return this.left.count()+1+this.right.count()}isEmpty(){return!1}inorderTraversal(e){return this.left.inorderTraversal(e)||!!e(this.key,this.value)||this.right.inorderTraversal(e)}reverseTraversal(e){return this.right.reverseTraversal(e)||e(this.key,this.value)||this.left.reverseTraversal(e)}min_(){return this.left.isEmpty()?this:this.left.min_()}minKey(){return this.min_().key}maxKey(){return this.right.isEmpty()?this.key:this.right.maxKey()}insert(e,t,n){let i=this,r=n(e,i.key);return(i=r<0?i.copy(null,null,null,i.left.insert(e,t,n),null):0===r?i.copy(null,t,null,null,null):i.copy(null,null,null,null,i.right.insert(e,t,n))).fixUp_()}removeMin_(){if(this.left.isEmpty())return eG.EMPTY_NODE;let e=this;return e.left.isRed_()||e.left.left.isRed_()||(e=e.moveRedLeft_()),(e=e.copy(null,null,null,e.left.removeMin_(),null)).fixUp_()}remove(e,t){let n,i;if(n=this,0>t(e,n.key))n.left.isEmpty()||n.left.isRed_()||n.left.left.isRed_()||(n=n.moveRedLeft_()),n=n.copy(null,null,null,n.left.remove(e,t),null);else{if(n.left.isRed_()&&(n=n.rotateRight_()),n.right.isEmpty()||n.right.isRed_()||n.right.left.isRed_()||(n=n.moveRedRight_()),0===t(e,n.key))if(n.right.isEmpty())return eG.EMPTY_NODE;else i=n.right.min_(),n=n.copy(i.key,i.value,null,null,n.right.removeMin_());n=n.copy(null,null,null,null,n.right.remove(e,t))}return n.fixUp_()}isRed_(){return this.color}fixUp_(){let e=this;return e.right.isRed_()&&!e.left.isRed_()&&(e=e.rotateLeft_()),e.left.isRed_()&&e.left.left.isRed_()&&(e=e.rotateRight_()),e.left.isRed_()&&e.right.isRed_()&&(e=e.colorFlip_()),e}moveRedLeft_(){let e=this.colorFlip_();return e.right.left.isRed_()&&(e=(e=(e=e.copy(null,null,null,null,e.right.rotateRight_())).rotateLeft_()).colorFlip_()),e}moveRedRight_(){let e=this.colorFlip_();return e.left.left.isRed_()&&(e=(e=e.rotateRight_()).colorFlip_()),e}rotateLeft_(){let e=this.copy(null,null,eK.RED,null,this.right.left);return this.right.copy(null,null,this.color,e,null)}rotateRight_(){let e=this.copy(null,null,eK.RED,this.left.right,null);return this.left.copy(null,null,this.color,null,e)}colorFlip_(){let e=this.left.copy(null,null,!this.left.color,null,null),t=this.right.copy(null,null,!this.right.color,null,null);return this.copy(null,null,!this.color,e,t)}checkMaxDepth_(){return Math.pow(2,this.check_())<=this.count()+1}check_(){if(this.isRed_()&&this.left.isRed_())throw Error("Red node has red child("+this.key+","+this.value+")");
1if(this.right.isRed_())throw Error("Right child of ("+this.key+","+this.value+") is red");let e=this.left.check_();if(e===this.right.check_())return e+ +!this.isRed_();throw Error("Black depths differ")}}eK.RED=!0,eK.BLACK=!1;class eG{constructor(e,t=eG.EMPTY_NODE){this.comparator_=e,this.root_=t}insert(e,t){return new eG(this.comparator_,this.root_.insert(e,t,this.comparator_).copy(null,null,eK.BLACK,null,null))}remove(e){return new eG(this.comparator_,this.root_.remove(e,this.comparator_).copy(null,null,eK.BLACK,null,null))}get(e){let t,n=this.root_;for(;!n.isEmpty();){if(0===(t=this.comparator_(e,n.key)))return n.value;t<0?n=n.left:t>0&&(n=n.right)}return null}getPredecessorKey(e){let t,n=this.root_,i=null;for(;!n.isEmpty();){if(0===(t=this.comparator_(e,n.key)))if(n.left.isEmpty())if(i)return i.key;else return null;else{for(n=n.left;!n.right.isEmpty();)n=n.right;return n.key}t<0?n=n.left:t>0&&(i=n,n=n.right)}throw 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 e$(this.root_,null,this.comparator_,!1,e)}getIteratorFrom(e,t){return new e$(this.root_,e,this.comparator_,!1,t)}getReverseIteratorFrom(e,t){return new e$(this.root_,e,this.comparator_,!0,t)}getReverseIterator(e){return new e$(this.root_,null,this.comparator_,!0,e)}}function eY(e,t){return B(e.name,t.name)}function eJ(e,t){return B(e,t)}eG.EMPTY_NODE=new class{copy(e,t,n,i,r){return this}insert(e,t,n){return new eK(e,t,null)}remove(e,t){return this}count(){return 0}isEmpty(){return!0}inorderTraversal(e){return!1}reverseTraversal(e){return!1}minKey(){return null}maxKey(){return null}check_(){return 0}isRed_(){return!1}};let eQ=function(e){return"number"==typeof e?"number:"+J(e):"string:"+e},eX=function(e){if(e.isLeafNode()){let t=e.val();(0,m.assert)("string"==typeof t||"number"==typeof t||"object"==typeof t&&(0,m.contains)(t,".sv"),"Priority must be a string or number.")}else(0,m.assert)(e===n||e.isEmpty(),"priority of unexpected type.");(0,m.assert)(e===n||e.getPriority().isEmpty(),"Priority nodes can't have a priority of their own.")};class eZ{constructor(e,t=eZ.__childrenNodeConstructor.EMPTY_NODE){this.value_=e,this.priorityNode_=t,this.lazyHash_=null,(0,m.assert)(void 0!==this.value_&&null!==this.value_,"LeafNode shouldn't be created with null/undefined value."),eX(this.priorityNode_)}static set __childrenNodeConstructor(e){i=e}static get __childrenNodeConstructor(){return i}isLeafNode(){return!0}getPriority(){return this.priorityNode_}updatePriority(e){return new eZ(this.value_,e)}getImmediateChild(e){return".priority"===e?this.priorityNode_:eZ.__childrenNodeConstructor.EMPTY_NODE}getChild(e){return eD(e)?this:".priority"===eS(e)?this.priorityNode_:eZ.__childrenNodeConstructor.EMPTY_NODE}hasChild(){return!1}getPredecessorChildName(e,t){return null}updateImmediateChild(e,t){return".priority"===e?this.updatePriority(t):t.isEmpty()&&".priority"!==e?this:eZ.__childrenNodeConstructor.EMPTY_NODE.updateImmediateChild(e,t).updatePriority(this.priorityNode_)}updateChild(e,t){let n=eS(e);return null===n?t:t.isEmpty()&&".priority"!==n?this:((0,m.assert)(".priority"!==n||1===ek(e),".priority must be the last token in a path"),this.updateImmediateChild(n,eZ.__childrenNodeConstructor.EMPTY_NODE.updateChild(eP(e),t)))}isEmpty(){return!1}numChildren(){return 0}forEachChild(e,t){return!1}val(e){return e&&!this.getPriority().isEmpty()?{".value":this.getValue(),".priority":this.getPriority().val()}:this.getValue()}hash(){if(null===this.lazyHash_){let e="";this.priorityNode_.isEmpty()||(e+="priority:"+eQ(this.priorityNode_.val())+":");let t=typeof this.value_;e+=t+":","number"===t?e+=J(this.value_):e+=this.value_,this.lazyHash_=N(e)}return this.lazyHash_}getValue(){return this.value_}compareTo(e){return e===eZ.__childrenNodeConstructor.EMPTY_NODE?1:e instanceof eZ.__childrenNodeConstructor?-1:((0,m.assert)(e.isLeafNode(),"Unknown node type"),this.compareToLeafNode_(e))}compareToLeafNode_(e){let t=typeof e.value_,n=typeof this.value_,i=eZ.VALUE_TYPE_ORDER.indexOf(t),r=eZ.VALUE_TYPE_ORDER.indexOf(n);return((0,m.assert)(i>=0,"Unknown leaf type: "+t),(0,m.assert)(r>=0,"Unknown leaf type: "+n),i!==r)?r-i:"object"===n?0:this.value_<e.value_?-1:1*(this.value_!==e.value_)}withIndex(){return this}isIndexed(){return!0}equals(e){return e===this||!!e.isLeafNode()&&this.value_===e.value_&&this.priorityNode_.equals(e.priorityNode_)}}eZ.VALUE_TYPE_ORDER=["object","boolean","number","string"];let e0=new class extends eH{compare(e,t){let n=e.node.getPriority(),i=t.node.getPriority(),r=n.compareTo(i);return 0===r?B(e.name,t.name):r}isDefinedOn(e){return!e.getPriority().isEmpty()}indexedValueChanged(e,t){return!e.getPriority().equals(t.getPriority())}
1minPost(){return eV.MIN}maxPost(){return new eV(H,new eZ("[PRIORITY-POST]",s))}makePost(e,t){return new eV(t,new eZ("[PRIORITY-POST]",r(e)))}toString(){return".priority"}},e1=Math.log(2);class e2{constructor(e){this.count=(e=>parseInt(Math.log(e)/e1,10))(e+1),this.current_=this.count-1;const t=(e=>parseInt(Array(e+1).join("1"),2))(this.count);this.bits_=e+1&t}nextBitIsOne(){let e=!(this.bits_&1<<this.current_);return this.current_--,e}}let e3=function(e,t,n,i){e.sort(t);let r=function(t,i){let s,o=i-t;if(0===o)return null;if(1===o)return s=e[t],new eK(n?n(s):s,s.node,eK.BLACK,null,null);{let a=parseInt(o/2,10)+t,l=r(t,a),h=r(a+1,i);return s=e[a],new eK(n?n(s):s,s.node,eK.BLACK,l,h)}};return new eG(i||t,function(t){let i=null,s=null,o=e.length,a=function(t,i){let s=o-t,a=o;o-=t;let h=r(s+1,a),c=e[s];l(new eK(n?n(c):c,c.node,i,null,h))},l=function(e){i?i.left=e:s=e,i=e};for(let e=0;e<t.count;++e){let n=t.nextBitIsOne(),i=Math.pow(2,t.count-(e+1));n?a(i,eK.BLACK):(a(i,eK.BLACK),a(i,eK.RED))}return s}(new e2(e.length)))},e4={};class e6{constructor(e,t){this.indexes_=e,this.indexSet_=t}static get Default(){return(0,m.assert)(e4&&e0,"ChildrenNode.ts has not been loaded"),o=o||new e6({".priority":e4},{".priority":e0})}get(e){let t=(0,m.safeGet)(this.indexes_,e);if(!t)throw Error("No index defined for "+e);return t instanceof eG?t:null}hasIndex(e){return(0,m.contains)(this.indexSet_,e.toString())}addIndex(e,t){let n;(0,m.assert)(e!==ez,"KeyIndex always exists and isn't meant to be added to the IndexMap.");let i=[],r=!1,s=t.getIterator(eV.Wrap),o=s.getNext();for(;o;)r=r||e.isDefinedOn(o.node),i.push(o),o=s.getNext();n=r?e3(i,e.getCompare()):e4;let a=e.toString(),l=Object.assign({},this.indexSet_);l[a]=e;let h=Object.assign({},this.indexes_);return h[a]=n,new e6(h,l)}addToIndexes(e,t){return new e6((0,m.map)(this.indexes_,(n,i)=>{let r=(0,m.safeGet)(this.indexSet_,i);if((0,m.assert)(r,"Missing index implementation for "+i),n===e4)if(!r.isDefinedOn(e.node))return e4;else{let n=[],i=t.getIterator(eV.Wrap),s=i.getNext();for(;s;)s.name!==e.name&&n.push(s),s=i.getNext();return n.push(e),e3(n,r.getCompare())}{let i=t.get(e.name),r=n;return i&&(r=r.remove(new eV(e.name,i))),r.insert(e,e.node)}}),this.indexSet_)}removeFromIndexes(e,t){return new e6((0,m.map)(this.indexes_,n=>{if(n===e4)return n;{let i=t.get(e.name);return i?n.remove(new eV(e.name,i)):n}}),this.indexSet_)}}class e5{constructor(e,t,n){this.children_=e,this.priorityNode_=t,this.indexMap_=n,this.lazyHash_=null,this.priorityNode_&&eX(this.priorityNode_),this.children_.isEmpty()&&(0,m.assert)(!this.priorityNode_||this.priorityNode_.isEmpty(),"An empty node cannot have a priority")}static get EMPTY_NODE(){return a||(a=new e5(new eG(eJ),null,e6.Default))}isLeafNode(){return!1}getPriority(){return this.priorityNode_||a}updatePriority(e){return this.children_.isEmpty()?this:new e5(this.children_,e,this.indexMap_)}getImmediateChild(e){if(".priority"===e)return this.getPriority();{let t=this.children_.get(e);return null===t?a:t}}getChild(e){let t=eS(e);return null===t?this:this.getImmediateChild(t).getChild(eP(e))}hasChild(e){return null!==this.children_.get(e)}updateImmediateChild(e,t){if((0,m.assert)(t,"We should always be passing snapshot nodes"),".priority"===e)return this.updatePriority(t);{let n,i,r=new eV(e,t);t.isEmpty()?(n=this.children_.remove(e),i=this.indexMap_.removeFromIndexes(r,this.children_)):(n=this.children_.insert(e,t),i=this.indexMap_.addToIndexes(r,this.children_));let s=n.isEmpty()?a:this.priorityNode_;return new e5(n,s,i)}}updateChild(e,t){let n=eS(e);if(null===n)return t;{(0,m.assert)(".priority"!==eS(e)||1===ek(e),".priority must be the last token in a path");let i=this.getImmediateChild(n).updateChild(eP(e),t);return this.updateImmediateChild(n,i)}}isEmpty(){return this.children_.isEmpty()}numChildren(){return this.children_.count()}val(e){if(this.isEmpty())return null;let t={},n=0,i=0,r=!0;if(this.forEachChild(e0,(s,o)=>{t[s]=o.val(e),n++,r&&e5.INTEGER_REGEXP_.test(s)?i=Math.max(i,Number(s)):r=!1}),e||!r||!(i<2*n))return e&&!this.getPriority().isEmpty()&&(t[".priority"]=this.getPri
1ority().val()),t;{let e=[];for(let n in t)e[n]=t[n];return e}}hash(){if(null===this.lazyHash_){let e="";this.getPriority().isEmpty()||(e+="priority:"+eQ(this.getPriority().val())+":"),this.forEachChild(e0,(t,n)=>{let i=n.hash();""!==i&&(e+=":"+t+":"+i)}),this.lazyHash_=""===e?"":N(e)}return this.lazyHash_}getPredecessorChildName(e,t,n){let i=this.resolveIndex_(n);if(!i)return this.children_.getPredecessorKey(e);{let n=i.getPredecessorKey(new eV(e,t));return n?n.name:null}}getFirstChildName(e){let t=this.resolveIndex_(e);if(!t)return this.children_.minKey();{let e=t.minKey();return e&&e.name}}getFirstChild(e){let t=this.getFirstChildName(e);return t?new eV(t,this.children_.get(t)):null}getLastChildName(e){let t=this.resolveIndex_(e);if(!t)return this.children_.maxKey();{let e=t.maxKey();return e&&e.name}}getLastChild(e){let t=this.getLastChildName(e);return t?new eV(t,this.children_.get(t)):null}forEachChild(e,t){let n=this.resolveIndex_(e);return n?n.inorderTraversal(e=>t(e.name,e.node)):this.children_.inorderTraversal(t)}getIterator(e){return this.getIteratorFrom(e.minPost(),e)}getIteratorFrom(e,t){let n=this.resolveIndex_(t);if(n)return n.getIteratorFrom(e,e=>e);{let n=this.children_.getIteratorFrom(e.name,eV.Wrap),i=n.peek();for(;null!=i&&0>t.compare(i,e);)n.getNext(),i=n.peek();return n}}getReverseIterator(e){return this.getReverseIteratorFrom(e.maxPost(),e)}getReverseIteratorFrom(e,t){let n=this.resolveIndex_(t);if(n)return n.getReverseIteratorFrom(e,e=>e);{let n=this.children_.getReverseIteratorFrom(e.name,eV.Wrap),i=n.peek();for(;null!=i&&t.compare(i,e)>0;)n.getNext(),i=n.peek();return n}}compareTo(e){if(this.isEmpty())if(e.isEmpty())return 0;else return -1;return e.isLeafNode()||e.isEmpty()?1:e===e8?-1:0}withIndex(e){if(e===ez||this.indexMap_.hasIndex(e))return this;{let t=this.indexMap_.addIndex(e,this.children_);return new e5(this.children_,this.priorityNode_,t)}}isIndexed(e){return e===ez||this.indexMap_.hasIndex(e)}equals(e){if(e===this)return!0;if(e.isLeafNode()||!this.getPriority().equals(e.getPriority()))return!1;if(this.children_.count()!==e.children_.count())return!1;{let t=this.getIterator(e0),n=e.getIterator(e0),i=t.getNext(),r=n.getNext();for(;i&&r;){if(i.name!==r.name||!i.node.equals(r.node))return!1;i=t.getNext(),r=n.getNext()}return null===i&&null===r}}resolveIndex_(e){return e===ez?null:this.indexMap_.get(e.toString())}}e5.INTEGER_REGEXP_=/^(0|[1-9]\d*)$/;let e8=new class extends e5{constructor(){super(new eG(eJ),e5.EMPTY_NODE,e6.Default)}compareTo(e){return+(e!==this)}equals(e){return e===this}getPriority(){return this}getImmediateChild(e){return e5.EMPTY_NODE}isEmpty(){return!1}};function e7(e,t=null){if(null===e)return e5.EMPTY_NODE;if("object"==typeof e&&".priority"in e&&(t=e[".priority"]),(0,m.assert)(null===t||"string"==typeof t||"number"==typeof t||"object"==typeof t&&".sv"in t,"Invalid priority type found: "+typeof t),"object"==typeof e&&".value"in e&&null!==e[".value"]&&(e=e[".value"]),"object"!=typeof e||".sv"in e)return new eZ(e,e7(t));if(e instanceof Array){let n=e5.EMPTY_NODE;return Y(e,(t,i)=>{if((0,m.contains)(e,t)&&"."!==t.substring(0,1)){let e=e7(i);(e.isLeafNode()||!e.isEmpty())&&(n=n.updateImmediateChild(t,e))}}),n.updatePriority(e7(t))}{let n=[],i=!1;if(Y(e,(e,t)=>{if("."!==e.substring(0,1)){let r=e7(t);r.isEmpty()||(i=i||!r.getPriority().isEmpty(),n.push(new eV(e,r)))}}),0===n.length)return e5.EMPTY_NODE;let r=e3(n,eY,e=>e.name,eJ);if(!i)return new e5(r,e7(t),e6.Default);{let e=e3(n,e0.getCompare());return new e5(r,e7(t),new e6({".priority":e},{".priority":e0}))}}}Object.defineProperties(eV,{MIN:{value:new eV(V,e5.EMPTY_NODE)},MAX:{value:new eV(H,e8)}}),eB.__EMPTY_NODE=e5.EMPTY_NODE,eZ.__childrenNodeConstructor=e5,n=e8,s=e8,r=e7;class e9 extends eH{constructor(e){super(),this.indexPath_=e,(0,m.assert)(!eD(e)&&".priority"!==eS(e),"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){let n=this.extractChild(e.node),i=this.extractChild(t.node),r=n.compareTo(i);return 0===r?B(e.name,t.name):r}makePost(e,t){let n=e7(e);return new eV(t,e5.EMPTY_NODE.updateChild(this.indexPath_,n))}maxPost(){return new eV(H,e5.EMPTY_NODE.updateChild(this.indexPath_,e8))}toString(){return eR(this.indexPath_,0).join("/")}}let te=new class extends eH{compare(e,t){let n=e.node.compareTo(t.node);return 0===n?B(e.name,t.name):n}isDefinedOn(e){return!0}indexedValueChanged(e,t){return!e.equals(t)}
1minPost(){return eV.MIN}maxPost(){return eV.MAX}makePost(e,t){return new eV(t,e7(e))}toString(){return".value"}};function tt(e){return{type:"value",snapshotNode:e}}function tn(e,t){return{type:"child_added",snapshotNode:t,childName:e}}function ti(e,t){return{type:"child_removed",snapshotNode:t,childName:e}}function tr(e,t,n){return{type:"child_changed",snapshotNode:t,childName:e,oldSnap:n}}class ts{constructor(e){this.index_=e}updateChild(e,t,n,i,r,s){(0,m.assert)(e.isIndexed(this.index_),"A node must be indexed if only a child is updated");let o=e.getImmediateChild(t);return o.getChild(i).equals(n.getChild(i))&&o.isEmpty()===n.isEmpty()||(null!=s&&(n.isEmpty()?e.hasChild(t)?s.trackChildChange(ti(t,o)):(0,m.assert)(e.isLeafNode(),"A child remove without an old child only makes sense on a leaf node"):o.isEmpty()?s.trackChildChange(tn(t,n)):s.trackChildChange(tr(t,n,o))),e.isLeafNode()&&n.isEmpty())?e:e.updateImmediateChild(t,n).withIndex(this.index_)}updateFullNode(e,t,n){return null!=n&&(e.isLeafNode()||e.forEachChild(e0,(e,i)=>{t.hasChild(e)||n.trackChildChange(ti(e,i))}),t.isLeafNode()||t.forEachChild(e0,(t,i)=>{if(e.hasChild(t)){let r=e.getImmediateChild(t);r.equals(i)||n.trackChildChange(tr(t,i,r))}else n.trackChildChange(tn(t,i))})),t.withIndex(this.index_)}updatePriority(e,t){return e.isEmpty()?e5.EMPTY_NODE:e.updatePriority(t)}filtersNodes(){return!1}getIndexedFilter(){return this}getIndex(){return this.index_}}class to{constructor(e){this.indexedFilter_=new ts(e.getIndex()),this.index_=e.getIndex(),this.startPost_=to.getStartPost_(e),this.endPost_=to.getEndPost_(e),this.startIsInclusive_=!e.startAfterSet_,this.endIsInclusive_=!e.endBeforeSet_}getStartPost(){return this.startPost_}getEndPost(){return this.endPost_}matches(e){let t=this.startIsInclusive_?0>=this.index_.compare(this.getStartPost(),e):0>this.index_.compare(this.getStartPost(),e),n=this.endIsInclusive_?0>=this.index_.compare(e,this.getEndPost()):0>this.index_.compare(e,this.getEndPost());return t&&n}updateChild(e,t,n,i,r,s){return this.matches(new eV(t,n))||(n=e5.EMPTY_NODE),this.indexedFilter_.updateChild(e,t,n,i,r,s)}updateFullNode(e,t,n){t.isLeafNode()&&(t=e5.EMPTY_NODE);let i=t.withIndex(this.index_);i=i.updatePriority(e5.EMPTY_NODE);let r=this;return t.forEachChild(e0,(e,t)=>{r.matches(new eV(e,t))||(i=i.updateImmediateChild(e,e5.EMPTY_NODE))}),this.indexedFilter_.updateFullNode(e,i,n)}updatePriority(e,t){return e}filtersNodes(){return!0}getIndexedFilter(){return this.indexedFilter_}getIndex(){return this.index_}static getStartPost_(e){if(!e.hasStart())return e.getIndex().minPost();{let t=e.getIndexStartName();return e.getIndex().makePost(e.getIndexStartValue(),t)}}static getEndPost_(e){if(!e.hasEnd())return e.getIndex().maxPost();{let t=e.getIndexEndName();return e.getIndex().makePost(e.getIndexEndValue(),t)}}}class ta{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=>{let t=this.index_.compare(this.rangedFilter_.getStartPost(),e);return this.startIsInclusive_?t<=0:t<0},this.withinEndPost=e=>{let t=this.index_.compare(e,this.rangedFilter_.getEndPost());return this.endIsInclusive_?t<=0:t<0},this.rangedFilter_=new to(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,i,r,s){return(this.rangedFilter_.matches(new eV(t,n))||(n=e5.EMPTY_NODE),e.getImmediateChild(t).equals(n))?e:e.numChildren()<this.limit_?this.rangedFilter_.getIndexedFilter().updateChild(e,t,n,i,r,s):this.fullLimitUpdateChild_(e,t,n,r,s)}updateFullNode(e,t,n){let i;if(t.isLeafNode()||t.isEmpty())i=e5.EMPTY_NODE.withIndex(this.index_);else if(2*this.limit_<t.numChildren()&&t.isIndexed(this.index_)){let e;i=e5.EMPTY_NODE.withIndex(this.index_),e=this.reverse_?t.getReverseIteratorFrom(this.rangedFilter_.getEndPost(),this.index_):t.getIteratorFrom(this.rangedFilter_.getStartPost(),this.index_);let n=0;for(;e.hasNext()&&n<this.limit_;){let t=e.getNext();if(this.withinDirectionalStart(t))if(this.withinDirectionalEnd(t))i=i.updateImmediateChild(t.name,t.node),n++;else break}}else{let e;i=(i=t.withIndex(this.index_)).updatePriority(e5.EMPTY_NODE),e=this.reverse_?i.getReverseIterator(this.index_):i.getIterator(this.index_);let n=0;for(;e.hasNext();){let t=e.getNext();n<this.limit_&&this.withinDirectionalStart(t)&&this.withinDirectionalEnd(t)?n++:i=i.updateImmediateChild(t.name,e5.EMPTY_NODE)}}return this.rangedFilter_.getIndexedFilter().updateFullNode(e,i,n)}updatePriority(e,t){return e}filtersNodes(){return!0}getIndexedFilter(){return this.rangedFilter_.getIndexedFilter()}getIndex(){return this.index_}
1fullLimitUpdateChild_(e,t,n,i,r){let s;if(this.reverse_){let e=this.index_.getCompare();s=(t,n)=>e(n,t)}else s=this.index_.getCompare();(0,m.assert)(e.numChildren()===this.limit_,"");let o=new eV(t,n),a=this.reverse_?e.getFirstChild(this.index_):e.getLastChild(this.index_),l=this.rangedFilter_.matches(o);if(e.hasChild(t)){let h=e.getImmediateChild(t),c=i.getChildAfterChild(this.index_,a,this.reverse_);for(;null!=c&&(c.name===t||e.hasChild(c.name));)c=i.getChildAfterChild(this.index_,c,this.reverse_);let u=null==c?1:s(c,o);if(l&&!n.isEmpty()&&u>=0)return null!=r&&r.trackChildChange(tr(t,n,h)),e.updateImmediateChild(t,n);{null!=r&&r.trackChildChange(ti(t,h));let n=e.updateImmediateChild(t,e5.EMPTY_NODE);return null!=c&&this.rangedFilter_.matches(c)?(null!=r&&r.trackChildChange(tn(c.name,c.node)),n.updateImmediateChild(c.name,c.node)):n}}return n.isEmpty()?e:l?s(a,o)>=0?(null!=r&&(r.trackChildChange(ti(a.name,a.node)),r.trackChildChange(tn(t,n))),e.updateImmediateChild(t,n).updateImmediateChild(a.name,e5.EMPTY_NODE)):e:e}}class tl{constructor(){this.limitSet_=!1,this.startSet_=!1,this.startNameSet_=!1,this.startAfterSet_=!1,this.endSet_=!1,this.endNameSet_=!1,this.endBeforeSet_=!1,this.limit_=0,this.viewFrom_="",this.indexStartValue_=null,this.indexStartName_="",this.indexEndValue_=null,this.indexEndName_="",this.index_=e0}hasStart(){return this.startSet_}isViewFromLeft(){return""===this.viewFrom_?this.startSet_:"l"===this.viewFrom_}getIndexStartValue(){return(0,m.assert)(this.startSet_,"Only valid if start has been set"),this.indexStartValue_}getIndexStartName(){return((0,m.assert)(this.startSet_,"Only valid if start has been set"),this.startNameSet_)?this.indexStartName_:V}hasEnd(){return this.endSet_}getIndexEndValue(){return(0,m.assert)(this.endSet_,"Only valid if end has been set"),this.indexEndValue_}getIndexEndName(){return((0,m.assert)(this.endSet_,"Only valid if end has been set"),this.endNameSet_)?this.indexEndName_:H}hasLimit(){return this.limitSet_}hasAnchoredLimit(){return this.limitSet_&&""!==this.viewFrom_}getLimit(){return(0,m.assert)(this.limitSet_,"Only valid if limit has been set"),this.limit_}getIndex(){return this.index_}loadsAllData(){return!(this.startSet_||this.endSet_||this.limitSet_)}isDefault(){return this.loadsAllData()&&this.index_===e0}copy(){let e=new tl;return 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_,e}}function th(e,t,n){let i=e.copy();return i.startSet_=!0,void 0===t&&(t=null),i.indexStartValue_=t,null!=n?(i.startNameSet_=!0,i.indexStartName_=n):(i.startNameSet_=!1,i.indexStartName_=""),i}function tc(e){let t,n={};if(e.isDefault())return n;if(e.index_===e0?t="$priority":e.index_===te?t="$value":e.index_===ez?t="$key":((0,m.assert)(e.index_ instanceof e9,"Unrecognized index type!"),t=e.index_.toString()),n.orderBy=(0,m.stringify)(t),e.startSet_){let t=e.startAfterSet_?"startAfter":"startAt";n[t]=(0,m.stringify)(e.indexStartValue_),e.startNameSet_&&(n[t]+=","+(0,m.stringify)(e.indexStartName_))}if(e.endSet_){let t=e.endBeforeSet_?"endBefore":"endAt";n[t]=(0,m.stringify)(e.indexEndValue_),e.endNameSet_&&(n[t]+=","+(0,m.stringify)(e.indexEndName_))}return e.limitSet_&&(e.isViewFromLeft()?n.limitToFirst=e.limit_:n.limitToLast=e.limit_),n}function tu(e){let t={};if(e.startSet_&&(t.sp=e.indexStartValue_,e.startNameSet_&&(t.sn=e.indexStartName_),t.sin=!e.startAfterSet_),e.endSet_&&(t.ep=e.indexEndValue_,e.endNameSet_&&(t.en=e.indexEndName_),t.ein=!e.endBeforeSet_),e.limitSet_){t.l=e.limit_;let n=e.viewFrom_;""===n&&(n=e.isViewFromLeft()?"l":"r"),t.vf=n}return e.index_!==e0&&(t.i=e.index_.toString()),t}class td extends eI{constructor(e,t,n,i){super(),this.repoInfo_=e,this.onDataUpdate_=t,this.authTokenProvider_=n,this.appCheckTokenProvider_=i,this.log_=L("p:rest:"),this.listens_={}}reportStats(e){throw Error("Method not implemented.")}static getListenId_(e,t){return void 0!==t?"tag$"+t:((0,m.assert)(e._queryParams.isDefault(),"should have a tag if it's not a default query."),e._path.toString())}listen(e,t,n,i){let r=e._path.toString();this.log_("Listen called for "+r+" "+e._queryIdentifier);let s=td.getListenId_(e,n),o={};this.listens_[s]=o;let a=tc(e._queryParams);this.restRequest_(r+".json",a,(e,t)=>{let a=t;(404===e&&(a=null,e=null),null===e&&this.onDataUpdate_(r,a,!1,n),(0,m.safeGet)(this.listens_,s)===o)&&i(e?401===e?"permission_denied":"rest_error:"+e:"ok",null)})}unlisten(e,t){let n=td.getListenId_(e,t);delete this.listens_[n]}get(e){let t=tc(e._queryParams),n=e._path.toString(),i=new m.Deferred;return this.restRequest_(n+".json",t,(e,t)=>{let r=t;404===e&&(r=null,e=null),null===e?(this.onDataUpdate_(n,r,!1,null),i.resolve(r)):i.reject(Error(r))}),i.promise}refreshAuthToken(e){}restRequest_(e,t={},n){return t.format="export",Promise.all([this.authTokenProvider_.getToken(!1),this.appCheckTokenProvider_.getToken(!1)]).then(([i,r])=>{i&&i.accessToken&&(t.auth=i.accessToken),r&&r.token&&(t.ac=r.token);let s=(this.repoInfo_.secure?"https://":"http://")+this.repoInfo_.host+e+"?ns="+this.repoInfo_.namespace+(0,m.querystring)(t);this.log_("Sending REST request for "+s);let o=new XMLHttpRequest;o.onreadystatechange=()=>{if(n&&4===o.readyState){this.log_("REST Response for "+s+" received. status:",o.status,"response:",o.responseText);let e=null;if(o.status>=200&&o.status<300){try{e=(0,m.jsonEval)(o.responseText)}catch(e){U("Failed to parse JSON response for "+s+": "+o.responseText)}n(null,e)}else 401!==o.status&&404!==o.status&&U("Got unsuccessful REST response for "+s+" Status: "+o.status),n(o.status);n=null}},o.open("GET",s,!0),o.send()})}}class tp{constructor(){this.rootNode_=e5.EMPTY_NODE}getNode(e){return this.rootNode_.getChild(e)}updateSnapshot(e,t){this.rootNode_=this.rootNode_.updateChild(e,t)}}function tf(){return{value:null,children:new Map}}function t_(e,t,n){var i,r;null!==e.value?n(t,e.value):(i=e,r=(e,i)=>{t_(i,new eE(t.toString()+"/"+e),n)}
1,i.children.forEach((e,t)=>{r(t,e)}))}class tg{constructor(e){this.collection_=e,this.last_=null}get(){let e=this.collection_.get(),t=Object.assign({},e);return this.last_&&Y(this.last_,(e,n)=>{t[e]=t[e]-n}),this.last_=e,t}}class tm{constructor(e,t){this.server_=t,this.statsToReport_={},this.statsListener_=new tg(e);const n=1e4+2e4*Math.random();ee(this.reportStats_.bind(this),Math.floor(n))}reportStats_(){let e=this.statsListener_.get(),t={},n=!1;Y(e,(e,i)=>{i>0&&(0,m.contains)(this.statsToReport_,e)&&(t[e]=i,n=!0)}),n&&this.server_.reportStats(t),ee(this.reportStats_.bind(this),Math.floor(2*Math.random()*3e5))}}function ty(){return{fromUser:!0,fromServer:!1,queryId:null,tagged:!1}}function tv(){return{fromUser:!1,fromServer:!0,queryId:null,tagged:!1}}function tw(e){return{fromUser:!1,fromServer:!0,queryId:e,tagged:!0}}(d=p||(p={}))[d.OVERWRITE=0]="OVERWRITE",d[d.MERGE=1]="MERGE",d[d.ACK_USER_WRITE=2]="ACK_USER_WRITE",d[d.LISTEN_COMPLETE=3]="LISTEN_COMPLETE";class tI{constructor(e,t,n){this.path=e,this.affectedTree=t,this.revert=n,this.type=p.ACK_USER_WRITE,this.source=ty()}operationForChild(e){if(!eD(this.path))return(0,m.assert)(eS(this.path)===e,"operationForChild called for unrelated child."),new tI(eP(this.path),this.affectedTree,this.revert);if(null!=this.affectedTree.value)return(0,m.assert)(this.affectedTree.children.isEmpty(),"affectedTree should not have overlapping affected paths."),this;{let t=this.affectedTree.subtree(new eE(e));return new tI(eT(),t,this.revert)}}}class tC{constructor(e,t){this.source=e,this.path=t,this.type=p.LISTEN_COMPLETE}operationForChild(e){return eD(this.path)?new tC(this.source,eT()):new tC(this.source,eP(this.path))}}class tb{constructor(e,t,n){this.source=e,this.path=t,this.snap=n,this.type=p.OVERWRITE}operationForChild(e){return eD(this.path)?new tb(this.source,eT(),this.snap.getImmediateChild(e)):new tb(this.source,eP(this.path),this.snap)}}class tE{constructor(e,t,n){this.source=e,this.path=t,this.children=n,this.type=p.MERGE}operationForChild(e){if(!eD(this.path))return(0,m.assert)(eS(this.path)===e,"Can't get a merge for a child not on the path of the operation"),new tE(this.source,eP(this.path),this.children);{let t=this.children.subtree(new eE(e));return t.isEmpty()?null:t.value?new tb(this.source,eT(),t.value):new tE(this.source,eT(),t)}}toString(){return"Operation("+this.path+": "+this.source.toString()+" merge: "+this.children.toString()+")"}}class tT{constructor(e,t,n){this.node_=e,this.fullyInitialized_=t,this.filtered_=n}isFullyInitialized(){return this.fullyInitialized_}isFiltered(){return this.filtered_}isCompleteForPath(e){if(eD(e))return this.isFullyInitialized()&&!this.filtered_;let t=eS(e);return this.isCompleteForChild(t)}isCompleteForChild(e){return this.isFullyInitialized()&&!this.filtered_||this.node_.hasChild(e)}getNode(){return this.node_}}class tS{constructor(e){this.query_=e,this.index_=this.query_._queryParams.getIndex()}}function tk(e,t,n,i,r,s){let o=i.filter(e=>e.type===n);o.sort((t,n)=>(function(e,t,n){if(null==t.childName||null==n.childName)throw(0,m.assertionError)("Should only compare child_ events.");let i=new eV(t.childName,t.snapshotNode),r=new eV(n.childName,n.snapshotNode);return e.index_.compare(i,r)})(e,t,n)),o.forEach(n=>{var i,o,a;let l=(i=e,o=n,a=s,"value"===o.type||"child_removed"===o.type||(o.prevName=a.getPredecessorChildName(o.childName,o.snapshotNode,i.index_)),o);r.forEach(i=>{i.respondsTo(n.type)&&t.push(i.createEvent(l,e.query_))})})}function tP(e,t){return{eventCache:e,serverCache:t}}function tN(e,t,n,i){return tP(new tT(t,n,i),e.serverCache)}function tR(e,t,n,i){return tP(e.eventCache,new tT(t,n,i))}function tA(e){return e.eventCache.isFullyInitialized()?e.eventCache.getNode():null}function tO(e){return e.serverCache.isFullyInitialized()?e.serverCache.getNode():null}class tD{constructor(e,t=(!l&&(l=new eG(z)),l)){this.value=e,this.children=t}static fromObject(e){let t=new tD(null);return Y(e,(e,n)=>{t=t.set(new eE(e),n)}),t}isEmpty(){return null===this.value&&this.children.isEmpty()}findRootMostMatchingPathAndValue(e,t){if(null!=this.value&&t(this.value))return{path:eT(),value:this.value};{if(eD(e))return null;let n=eS(e),i=this.children.get(n);if(null===i)return null;{let r=i.findRootMostMatchingPathAndValue(eP(e),t);return null!=r?{path:eO(new eE(n),r.path),value:r.value}:null}}}findRootMostValueAndPath(e){return this.findRootMostMatchingPathAndValue(e,()=>!0)}subtree(e){if(eD(e))return this;{let t=eS(e),n=this.children.get(t);return null!==n?n.subtree(eP(e)):new tD(null)}}set(e,t){if(eD(e))return new tD(t,this.children);{let n=eS(e),i=(this.children.get(n)||new tD(null)).set(eP(e),t),r=this.children.insert(n,i);return new tD(this.value,r)}}remove(e){if(eD(e))if(this.children.isEmpty())return new tD(null);else return new tD(null,this.children);{let t=eS(e),n=this.children.get(t);if(!n)return this;{let i,r=n.remove(eP(e));return(i=r.isEmpty()?this.children.remove(t):this.children.insert(t,r),null===this.value&&i.isEmpty())?new tD(null):new tD(this.value,i)}}}get(e){if(eD(e))return this.value;{let t=eS(e),n=this.children.get(t);return n?n.get(eP(e)):null}}setTree(e,t){if(eD(e))return t;{let n,i=eS(e),r=(this.children.get(i)||new tD(null)).setTree(eP(e),t);return n=r.isEmpty()?this.children.remove(i):this.children.insert(i,r),new tD(this.value,
1n)}}fold(e){return this.fold_(eT(),e)}fold_(e,t){let n={};return this.children.inorderTraversal((i,r)=>{n[i]=r.fold_(eO(e,i),t)}),t(e,this.value,n)}findOnPath(e,t){return this.findOnPath_(e,eT(),t)}findOnPath_(e,t,n){let i=!!this.value&&n(t,this.value);if(i)return i;{if(eD(e))return null;let i=eS(e),r=this.children.get(i);return r?r.findOnPath_(eP(e),eO(t,i),n):null}}foreachOnPath(e,t){return this.foreachOnPath_(e,eT(),t)}foreachOnPath_(e,t,n){if(eD(e))return this;{this.value&&n(t,this.value);let i=eS(e),r=this.children.get(i);return r?r.foreachOnPath_(eP(e),eO(t,i),n):new tD(null)}}foreach(e){this.foreach_(eT(),e)}foreach_(e,t){this.children.inorderTraversal((n,i)=>{i.foreach_(eO(e,n),t)}),this.value&&t(e,this.value)}foreachChild(e){this.children.inorderTraversal((t,n)=>{n.value&&e(t,n.value)})}}class tx{constructor(e){this.writeTree_=e}static empty(){return new tx(new tD(null))}}function tL(e,t,n){if(eD(t))return new tx(new tD(n));{let i=e.writeTree_.findRootMostValueAndPath(t);if(null!=i){let r=i.path,s=i.value,o=ex(r,t);return s=s.updateChild(o,n),new tx(e.writeTree_.set(r,s))}{let i=new tD(n);return new tx(e.writeTree_.setTree(t,i))}}}function tM(e,t,n){let i=e;return Y(n,(e,n)=>{i=tL(i,eO(t,e),n)}),i}function tF(e,t){return eD(t)?tx.empty():new tx(e.writeTree_.setTree(t,new tD(null)))}function tU(e,t){return null!=tq(e,t)}function tq(e,t){let n=e.writeTree_.findRootMostValueAndPath(t);return null!=n?e.writeTree_.get(n.path).getChild(ex(n.path,t)):null}function tj(e){let t=[],n=e.writeTree_.value;return null!=n?n.isLeafNode()||n.forEachChild(e0,(e,n)=>{t.push(new eV(e,n))}):e.writeTree_.children.inorderTraversal((e,n)=>{null!=n.value&&t.push(new eV(e,n.value))}),t}function tW(e,t){if(eD(t))return e;{let n=tq(e,t);return new tx(null!=n?new tD(n):e.writeTree_.subtree(t))}}function tV(e){return e.writeTree_.isEmpty()}function tH(e,t){return function e(t,n,i){if(null!=n.value)return i.updateChild(t,n.value);{let r=null;return n.children.inorderTraversal((n,s)=>{".priority"===n?((0,m.assert)(null!==s.value,"Priority writes must always be leaf nodes"),r=s.value):i=e(eO(t,n),s,i)}),i.getChild(t).isEmpty()||null===r||(i=i.updateChild(eO(t,".priority"),r)),i}}(eT(),e.writeTree_,t)}function tB(e){return e.visible}function tz(e,t,n){let i=tx.empty();for(let r=0;r<e.length;++r){let s=e[r];if(t(s)){let e,t=s.path;if(s.snap)eM(n,t)?i=tL(i,e=ex(n,t),s.snap):eM(t,n)&&(e=ex(t,n),i=tL(i,eT(),s.snap.getChild(e)));else if(s.children){if(eM(n,t))i=tM(i,e=ex(n,t),s.children);else if(eM(t,n))if(eD(e=ex(t,n)))i=tM(i,eT(),s.children);else{let t=(0,m.safeGet)(s.children,eS(e));if(t){let n=t.getChild(eP(e));i=tL(i,eT(),n)}}}else throw(0,m.assertionError)("WriteRecord should have .snap or .children")}}return i}function t$(e,t,n,i,r){if(i||r){let s=tW(e.visibleWrites,t);return!r&&tV(s)?n:r||null!=n||tU(s,eT())?tH(tz(e.allWrites,function(e){return(e.visible||r)&&(!i||!~i.indexOf(e.writeId))&&(eM(e.path,t)||eM(t,e.path))},t),n||e5.EMPTY_NODE):null}{let i=tq(e.visibleWrites,t);if(null!=i)return i;{let i=tW(e.visibleWrites,t);return tV(i)?n:null!=n||tU(i,eT())?tH(i,n||e5.EMPTY_NODE):null}}}function tK(e,t,n,i){return t$(e.writeTree,e.treePath,t,n,i)}function tG(e,t){return function(e,t,n){let i=e5.EMPTY_NODE,r=tq(e.visibleWrites,t);if(r)return r.isLeafNode()||r.forEachChild(e0,(e,t)=>{i=i.updateImmediateChild(e,t)}),i;
1if(!n)return tj(tW(e.visibleWrites,t)).forEach(e=>{i=i.updateImmediateChild(e.name,e.node)}),i;{let r=tW(e.visibleWrites,t);return n.forEachChild(e0,(e,t)=>{let n=tH(tW(r,new eE(e)),t);i=i.updateImmediateChild(e,n)}),tj(r).forEach(e=>{i=i.updateImmediateChild(e.name,e.node)}),i}}(e.writeTree,e.treePath,t)}function tY(e,t,n,i){return function(e,t,n,i,r){(0,m.assert)(i||r,"Either existingEventSnap or existingServerSnap must exist");let s=eO(t,n);if(tU(e.visibleWrites,s))return null;{let t=tW(e.visibleWrites,s);return tV(t)?r.getChild(n):tH(t,r.getChild(n))}}(e.writeTree,e.treePath,t,n,i)}function tJ(e,t){var n,i;return n=e.writeTree,i=eO(e.treePath,t),tq(n.visibleWrites,i)}function tQ(e,t,n){var i,r;let s,o;return i=e.writeTree,r=e.treePath,s=eO(r,t),null!=(o=tq(i.visibleWrites,s))?o:n.isCompleteForChild(t)?tH(tW(i.visibleWrites,s),n.getNode().getImmediateChild(t)):null}function tX(e,t){return tZ(eO(e.treePath,t),e.writeTree)}function tZ(e,t){return{treePath:e,writeTree:t}}class t0{constructor(){this.changeMap=new Map}trackChildChange(e){let t=e.type,n=e.childName;(0,m.assert)("child_added"===t||"child_changed"===t||"child_removed"===t,"Only child changes supported for tracking"),(0,m.assert)(".priority"!==n,"Only non-priority child changes can be tracked.");let i=this.changeMap.get(n);if(i){let r=i.type;if("child_added"===t&&"child_removed"===r)this.changeMap.set(n,tr(n,e.snapshotNode,i.snapshotNode));else if("child_removed"===t&&"child_added"===r)this.changeMap.delete(n);else if("child_removed"===t&&"child_changed"===r)this.changeMap.set(n,ti(n,i.oldSnap));else if("child_changed"===t&&"child_added"===r)this.changeMap.set(n,tn(n,e.snapshotNode));else if("child_changed"===t&&"child_changed"===r)this.changeMap.set(n,tr(n,e.snapshotNode,i.oldSnap));else throw(0,m.assertionError)("Illegal combination of changes: "+e+" occurred after "+i)}else this.changeMap.set(n,e)}getChanges(){return Array.from(this.changeMap.values())}}let t1=new class{getCompleteChild(e){return null}getChildAfterChild(e,t,n){return null}};class t2{constructor(e,t,n=null){this.writes_=e,this.viewCache_=t,this.optCompleteServerCache_=n}getCompleteChild(e){let t=this.viewCache_.eventCache;if(t.isCompleteForChild(e))return t.getNode().getImmediateChild(e);{let t=null!=this.optCompleteServerCache_?new tT(this.optCompleteServerCache_,!0,!1):this.viewCache_.serverCache;return tQ(this.writes_,e,t)}}getChildAfterChild(e,t,n){var i;let r=null!=this.optCompleteServerCache_?this.optCompleteServerCache_:tO(this.viewCache_),s=(i=this.writes_,function(e,t,n,i,r,s){let o,a=tW(e.visibleWrites,t),l=tq(a,eT());if(null!=l)o=l;else{if(null==n)return[];o=tH(a,n)}if((o=o.withIndex(s)).isEmpty()||o.isLeafNode())return[];{let e=[],t=s.getCompare(),n=r?o.getReverseIteratorFrom(i,s):o.getIteratorFrom(i,s),a=n.getNext();for(;a&&e.length<1;)0!==t(a,i)&&e.push(a),a=n.getNext();return e}}(i.writeTree,i.treePath,r,t,n,e));return 0===s.length?null:s[0]}}function t3(e,t,n,i,r,s){let o=t.eventCache;if(null!=tJ(i,n))return t;{let a,l;if(eD(n))if((0,m.assert)(t.serverCache.isFullyInitialized(),"If change path is empty, we must have complete server data"),t.serverCache.isFiltered()){let n=tO(t),r=tG(i,n instanceof e5?n:e5.EMPTY_NODE);a=e.filter.updateFullNode(t.eventCache.getNode(),r,s)}else{let n=tK(i,tO(t));a=e.filter.updateFullNode(t.eventCache.getNode(),n,s)}else{let h=eS(n);if(".priority"===h){(0,m.assert)(1===ek(n),"Can't have a priority with additional path components");let r=o.getNode(),s=tY(i,n,r,l=t.serverCache.getNode());a=null!=s?e.filter.updatePriority(r,s):o.getNode()}else{let c,u=eP(n);if(o.isCompleteForChild(h)){l=t.serverCache.getNode();let e=tY(i,n,o.getNode(),l);c=null!=e?o.getNode().getImmediateChild(h).updateChild(u,e):o.getNode().getImmediateChild(h)}else c=tQ(i,h,t.serverCache);a=null!=c?e.filter.updateChild(o.getNode(),h,c,u,r,s):o.getNode()}}return tN(t,a,o.isFullyInitialized()||eD(n),e.filter.filtersNodes())}}function t4(e,t,n,i,r,s,o,a){let l,h=t.serverCache,c=o?e.filter:e.filter.getIndexedFilter();if(eD(n))l=c.updateFullNode(h.getNode(),i,null);else if(c.filtersNodes()&&!h.isFiltered()){let e=h.getNode().updateChild(n,i);l=c.updateFullNode(h.getNode(),e,null)}else{let e=eS(n);if(!h.isCompleteForPath(n)&&ek(n)>1)return t;let r=eP(n),s=h.getNode().getImmediateChild(e).updateChild(r,i);l=".priority"===e?c.updatePriority(h.getNode(),s):c.updateChild(h.getNode(),e,s,r,t1,null)}let u=tR(t,l,h.isFullyInitialized()||eD(n),c.filtersNodes()),d=new t2(r,u,s);return t3(e,u,n,r,d,a)}function t6(e,t,n,i,r,s,o){let a,l,h=t.eventCache,c=new t2(r,t,s);if(eD(n))l=e.filter.updateFullNode(t.eventCache.getNode(),i,o),a=tN(t,l,!0,e.filter.filtersNodes());else{let r=eS(n);if(".priority"===r)l=e.filter.updatePriority(t.eventCache.getNode(),i),a=tN(t,l,h.isFullyInitialized(),h.isFiltered());else{let s,l=eP(n),u=h.getNode().getImmediateChild(r);if(eD(l))s=i;else{let e=c.getCompleteChild(r);s=null!=e?".priority"===eN(l)&&e.getChild(eA(l)).isEmpty()?e:e.updateChild(l,i):e5.EMPTY_NODE}a=u.equals(s)?t:tN(t,e.filter.updateChild(h.getNode(),r,s,l,c,o),h.isFullyInitialized(),e.filter.filtersNodes())}}return a}function t5(e,t){return e.eventCache.isCompleteForChild(t)}function t8(e,t,n){return n.foreach((e,n)=>{t=t.updateChild(e,n)}),t}function t7(e,t,n,i,r,s,o,a){let l;if(t.serverCache.getNode().isEmpty()&&!t.serverCache.isFullyInitialized())return t;let h=t;l=eD(n)?i:new tD(null).setTree(n,i);let c=t.serverCache.getNode();return l.children.inorderTraversal((n,i)=>{if(c.hasChild(n)){let l=t8(e,t.serverCache.getNode().getImmediateChild(n),i);h=t4(e,h,new eE(n),l,r,s,o,a)}}),l.children.inorderTraversal((n,i)=>{let l=!t.serverCache.isCompleteForChild(n)&&null===i.value;if(!c.hasChild(n)&&!l){let l=t8(e,t.serverCache.getNode().getImmediateChild(n),i);h=t4(e,h,new eE(n),l,r,s,o,a)}}),h}class t9{constructor(e,t){this.query_=e,this.eventRegistrations_=[];const n=this.query_._queryParams,i=new ts(n.getIndex()),r=function(e){return e.loadsAllData()?new ts(e.getIndex()):e.hasLimit()?new ta(e):new to(e)}(n);this.processor_=function(e){return{filter:e}}(r);const s=t.serverCache,o=t.eventCache,a=i.updateFullNode(e5.EMPTY_NODE,s.getNode(),null),l=r.updateFullNode(e5.EMPTY_NODE,o.getNode(),null),h=new tT(a,s.isFullyInitialized(),i.filtersNodes()),c=new tT(l,o.isFullyInitialized(),r.filtersNodes());this.viewCache_=tP(c,h),this.eventGenerator_=new tS(this.query_)}get query(){return this.query_}}function ne(e){return 0===e.eventRegistrations_.length}function nt(e,t,n){let i=[];if(n){(0,m.assert)(null==t,"A cancel should cancel all event registrations.");let r=e.query._path;
1e.eventRegistrations_.forEach(e=>{let t=e.createCancelEvent(n,r);t&&i.push(t)})}if(t){let n=[];for(let i=0;i<e.eventRegistrations_.length;++i){let r=e.eventRegistrations_[i];if(r.matches(t)){if(t.hasAnyCallback()){n=n.concat(e.eventRegistrations_.slice(i+1));break}}else n.push(r)}e.eventRegistrations_=n}else e.eventRegistrations_=[];return i}function nn(e,t,n,i){var r,s;t.type===p.MERGE&&null!==t.source.queryId&&((0,m.assert)(tO(e.viewCache_),"We should always have a full cache before handling merges"),(0,m.assert)(tA(e.viewCache_),"Missing event cache, even though we have a server cache"));let o=e.viewCache_,a=function(e,t,n,i,r){var s,o,a,l,h,c,u,d,f,_,g,y;let v,w,I=new t0;if(n.type===p.OVERWRITE)n.source.fromUser?v=t6(e,t,n.path,n.snap,i,r,I):((0,m.assert)(n.source.fromServer,"Unknown source."),w=n.source.tagged||t.serverCache.isFiltered()&&!eD(n.path),v=t4(e,t,n.path,n.snap,i,r,w,I));else if(n.type===p.MERGE){let d;n.source.fromUser?(s=e,o=t,a=n.path,l=n.children,h=i,c=r,u=I,d=o,l.foreach((e,t)=>{let n=eO(a,e);t5(o,eS(n))&&(d=t6(s,d,n,t,h,c,u))}),l.foreach((e,t)=>{let n=eO(a,e);t5(o,eS(n))||(d=t6(s,d,n,t,h,c,u))}),v=d):((0,m.assert)(n.source.fromServer,"Unknown source."),w=n.source.tagged||t.serverCache.isFiltered(),v=t7(e,t,n.path,n.children,i,r,w,I))}else if(n.type===p.ACK_USER_WRITE)v=n.revert?function(e,t,n,i,r,s){let o;if(null!=tJ(i,n))return t;{let a,l=new t2(i,t,r),h=t.eventCache.getNode();if(eD(n)||".priority"===eS(n)){let n;if(t.serverCache.isFullyInitialized())n=tK(i,tO(t));else{let e=t.serverCache.getNode();(0,m.assert)(e instanceof e5,"serverChildren would be complete if leaf node"),n=tG(i,e)}a=e.filter.updateFullNode(h,n,s)}else{let r=eS(n),c=tQ(i,r,t.serverCache);null==c&&t.serverCache.isCompleteForChild(r)&&(c=h.getImmediateChild(r)),(a=null!=c?e.filter.updateChild(h,r,c,eP(n),l,s):t.eventCache.getNode().hasChild(r)?e.filter.updateChild(h,r,e5.EMPTY_NODE,eP(n),l,s):h).isEmpty()&&t.serverCache.isFullyInitialized()&&(o=tK(i,tO(t))).isLeafNode()&&(a=e.filter.updateFullNode(a,o,s))}return o=t.serverCache.isFullyInitialized()||null!=tJ(i,eT()),tN(t,a,o,e.filter.filtersNodes())}}(e,t,n.path,i,r,I):function(e,t,n,i,r,s,o){if(null!=tJ(r,n))return t;let a=t.serverCache.isFiltered(),l=t.serverCache;if(null!=i.value)if(eD(n)&&l.isFullyInitialized()||l.isCompleteForPath(n))return t4(e,t,n,l.getNode().getChild(n),r,s,a,o);else{if(!eD(n))return t;let i=new tD(null);return l.getNode().forEachChild(ez,(e,t)=>{i=i.set(new eE(e),t)}),t7(e,t,n,i,r,s,a,o)}{let h=new tD(null);return i.foreach((e,t)=>{let i=eO(n,e);l.isCompleteForPath(i)&&(h=h.set(e,l.getNode().getChild(i)))}),t7(e,t,n,h,r,s,a,o)}}(e,t,n.path,n.affectedTree,i,r,I);else if(n.type===p.LISTEN_COMPLETE){let r;d=e,f=t,_=n.path,g=i,y=I,r=f.serverCache,v=t3(d,tR(f,r.getNode(),r.isFullyInitialized()||eD(_),r.isFiltered()),_,g,t1,y)}else throw(0,m.assertionError)("Unknown operation type: "+n.type);let C=I.getChanges();return function(e,t,n){let i=t.eventCache;if(i.isFullyInitialized()){let r=i.getNode().isLeafNode()||i.getNode().isEmpty(),s=tA(e);!(n.length>0)&&e.eventCache.isFullyInitialized()&&(!r||i.getNode().equals(s))&&i.getNode().getPriority().equals(s.getPriority())||n.push(tt(tA(t)))}}(t,v,C),{viewCache:v,changes:C}}(e.processor_,o,t,n,i);return r=e.processor_,s=a.viewCache,(0,m.assert)(s.eventCache.getNode().isIndexed(r.filter.getIndex()),"Event snap not indexed"),(0,m.assert)(s.serverCache.getNode().isIndexed(r.filter.getIndex()),"Server snap not indexed"),(0,m.assert)(a.viewCache.serverCache.isFullyInitialized()||!o.serverCache.isFullyInitialized(),"Once a server snap is complete, it should never go back"),e.viewCache_=a.viewCache,ni(e,a.changes,a.viewCache.eventCache.getNode(),null)}function ni(e,t,n,i){var r;let s,o,a=i?[i]:e.eventRegistrations_;return r=e.eventGenerator_,s=[],o=[],t.forEach(e=>{var t;"child_changed"===e.type&&r.index_.indexedValueChanged(e.oldSnap,e.snapshotNode)&&o.push((t=e.childName,{type:"child_moved",snapshotNode:e.snapshotNode,childName:t}))}),tk(r,s,"child_removed",t,a,n),tk(r,s,"child_added",t,a,n),tk(r,s,"child_moved",o,a,n),tk(r,s,"child_changed",t,a,n),tk(r,s,"value",t,a,n),s}class nr{constructor(){this.views=new Map}}function ns(e,t,n,i){let r=t.source.queryId;if(null!==r){let s=e.views.get(r);return(0,m.assert)(null!=s,"SyncTree gave us an op for an invali
1d query."),nn(s,t,n,i)}{let r=[];for(let s of e.views.values())r=r.concat(nn(s,t,n,i));return r}}function no(e){let t=[];for(let n of e.views.values())n.query._queryParams.loadsAllData()||t.push(n);return t}function na(e,t){let n=null;for(let i of e.views.values())n=n||function(e,t){let n=tO(e.viewCache_);return n&&(e.query._queryParams.loadsAllData()||!eD(t)&&!n.getImmediateChild(eS(t)).isEmpty())?n.getChild(t):null}(i,t);return n}function nl(e,t){if(t._queryParams.loadsAllData())return nc(e);{let n=t._queryIdentifier;return e.views.get(n)}}function nh(e){return null!=nc(e)}function nc(e){for(let t of e.views.values())if(t.query._queryParams.loadsAllData())return t;return null}let nu=1;class nd{constructor(e){this.listenProvider_=e,this.syncPointTree_=new tD(null),this.pendingWriteTree_={visibleWrites:tx.empty(),allWrites:[],lastWriteId:-1},this.tagToQueryMap=new Map,this.queryToTagMap=new Map}}function np(e,t,n=!1){let i=function(e,t){for(let n=0;n<e.allWrites.length;n++){let i=e.allWrites[n];if(i.writeId===t)return i}return null}(e.pendingWriteTree_,t);if(!function(e,t){var n;let i=e.allWrites.findIndex(e=>e.writeId===t);(0,m.assert)(i>=0,"removeWrite called with nonexistent writeId.");let r=e.allWrites[i];e.allWrites.splice(i,1);let s=r.visible,o=!1,a=e.allWrites.length-1;for(;s&&a>=0;){let t=e.allWrites[a];t.visible&&(a>=i&&function(e,t){if(e.snap)return eM(e.path,t);for(let n in e.children)if(e.children.hasOwnProperty(n)&&eM(eO(e.path,n),t))return!0;return!1}(t,r.path)?s=!1:eM(r.path,t.path)&&(o=!0)),a--}return!!s&&(o?((n=e).visibleWrites=tz(n.allWrites,tB,eT()),n.allWrites.length>0?n.lastWriteId=n.allWrites[n.allWrites.length-1].writeId:n.lastWriteId=-1):r.snap?e.visibleWrites=tF(e.visibleWrites,r.path):Y(r.children,t=>{e.visibleWrites=tF(e.visibleWrites,eO(r.path,t))}),!0)}(e.pendingWriteTree_,t))return[];{let t=new tD(null);return null!=i.snap?t=t.set(eT(),!0):Y(i.children,e=>{t=t.set(new eE(e),!0)}),ny(e,new tI(i.path,t,n))}}function nf(e,t,n){return ny(e,new tb(tv(),t,n))}function n_(e,t,n,i,r=!1){let s=t._path,o=e.syncPointTree_.get(s),a=[];if(o&&("default"===t._queryIdentifier||null!=nl(o,t))){let u=function(e,t,n,i){let r=t._queryIdentifier,s=[],o=[],a=nh(e);if("default"===r)for(let[t,r]of e.views.entries())o=o.concat(nt(r,n,i)),ne(r)&&(e.views.delete(t),r.query._queryParams.loadsAllData()||s.push(r.query));else{let t=e.views.get(r);t&&(o=o.concat(nt(t,n,i)),ne(t)&&(e.views.delete(r),t.query._queryParams.loadsAllData()||s.push(t.query)))}return a&&!nh(e)&&s.push(new((0,m.assert)(h,"Reference.ts has not been loaded"),h)(t._repo,t._path)),{removed:s,events:o}}(o,t,n,i);0===o.views.size&&(e.syncPointTree_=e.syncPointTree_.remove(s));let d=u.removed;if(a=u.events,!r){let n=-1!==d.findIndex(e=>e._queryParams.loadsAllData()),r=e.syncPointTree_.findOnPath(s,(e,t)=>nh(t));if(n&&!r){let t=e.syncPointTree_.subtree(s);if(!t.isEmpty()){let n=t.fold((e,t,n)=>{if(t&&nh(t))return[nc(t)];{let e=[];return t&&(e=no(t)),Y(n,(t,n)=>{e=e.concat(n)}),e}});for(let t=0;t<n.length;++t){let i=n[t],r=i.query,s=nv(e,i);e.listenProvider_.startListening(nT(r),nw(e,r),s.hashFn,s.onComplete)}}}r||!(d.length>0)||i||(n?e.listenProvider_.stopListening(nT(t),null):d.forEach(t=>{let n=e.queryToTagMap.get(nI(t));e.listenProvider_.stopListening(nT(t),n)}))}var l=e,c=d;for(let e=0;e<c.length;++e){let t=c[e];if(!t._queryParams.loadsAllData()){let e=nI(t),n=l.queryToTagMap.get(e);l.queryToTagMap.delete(e),l.tagToQueryMap.delete(n)}}}return a}function ng(e,t,n,i=!1){var r;let s,o,a,l,h=t._path,c=null,u=!1;e.syncPointTree_.foreachOnPath(h,(e,t)=>{let n=ex(e,h);c=c||na(t,n),u=u||nh(t)});let d=e.syncPointTree_.get(h);d?(u=u||nh(d),c=c||na(d,eT())):(d=new nr,e.syncPointTree_=e.syncPointTree_.set(h,d)),null!=c?s=!0:(s=!1,c=e5.EMPTY_NODE,e.syncPointTree_.subtree(h).foreachChild((e,t)=>{let n=na(t,eT());n&&(c=c.updateImmediateChild(e,n))}));let p=null!=nl(d,t);if(!p&&!t._queryParams.loadsAllData()){let n=nI(t);(0,m.assert)(!e.queryToTagMap.has(n),"View does not exist, but we have a tag");let i=nu++;e.queryToTagMap.set(n,i),e.tagToQueryMap.set(i,n)}let f=tZ(h,e.pendingWriteTree_),_=(o=function(e,t,n,i,r){let s=t._queryIdentifier,o=e.views.get(s);if(!o){let e=tK(n,r?i:null),s=!1;return e?s=!0:(e=i instanceof e5?tG(n,i):e5.EMPTY_NODE,s=!1),new t9(t,tP(new tT(e,s,!1),new tT(i,r,!1)))}return o}(r=d,t,f,c,s),r.views.has(t._queryIdentifier)||r.views.set(t._queryIdentifier,o),o.eventRegistrations_.push(n),a=o.viewCache_.eventCache,l=[],a.getNode().isLeafNode()||a.getNode().forEac
1hChild(e0,(e,t)=>{l.push(tn(e,t))}),a.isFullyInitialized()&&l.push(tt(a.getNode())),ni(o,l,a.getNode(),n));if(!p&&!u&&!i){let n=nl(d,t);_=_.concat(function(e,t,n){let i=t._path,r=nw(e,t),s=nv(e,n),o=e.listenProvider_.startListening(nT(t),r,s.hashFn,s.onComplete),a=e.syncPointTree_.subtree(i);if(r)(0,m.assert)(!nh(a.value),"If we're adding a query, it shouldn't be shadowed");else{let t=a.fold((e,t,n)=>{if(!eD(e)&&t&&nh(t))return[nc(t).query];{let e=[];return t&&(e=e.concat(no(t).map(e=>e.query))),Y(n,(t,n)=>{e=e.concat(n)}),e}});for(let n=0;n<t.length;++n){let i=t[n];e.listenProvider_.stopListening(nT(i),nw(e,i))}}return o}(e,t,n))}return _}function nm(e,t,n){let i=e.pendingWriteTree_,r=e.syncPointTree_.findOnPath(t,(e,n)=>{let i=na(n,ex(e,t));if(i)return i});return t$(i,t,r,n,!0)}function ny(e,t){var n;return function e(t,n,i,r){if(eD(t.path))return function e(t,n,i,r){let s=n.get(eT());null==i&&null!=s&&(i=na(s,eT()));let o=[];return n.children.inorderTraversal((n,s)=>{let a=i?i.getImmediateChild(n):null,l=tX(r,n),h=t.operationForChild(n);h&&(o=o.concat(e(h,s,a,l)))}),s&&(o=o.concat(ns(s,t,r,i))),o}(t,n,i,r);{let s=n.get(eT());null==i&&null!=s&&(i=na(s,eT()));let o=[],a=eS(t.path),l=t.operationForChild(a),h=n.children.get(a);if(h&&l){let t=i?i.getImmediateChild(a):null,n=tX(r,a);o=o.concat(e(l,h,t,n))}return s&&(o=o.concat(ns(s,t,r,i))),o}}(t,e.syncPointTree_,null,(n=e.pendingWriteTree_,tZ(eT(),n)))}function nv(e,t){let n=t.query,i=nw(e,n);return{hashFn:()=>(t.viewCache_.serverCache.getNode()||e5.EMPTY_NODE).hash(),onComplete:t=>{var r;if("ok"===t)if(i)return function(e,t,n){let i=nC(e,n);if(!i)return[];{let n=nb(i),r=n.path,s=n.queryId,o=ex(r,t);return nE(e,r,new tC(tw(s),o))}}(e,n._path,i);else return r=n._path,ny(e,new tC(tv(),r));{let i,r,s=(i="Unknown Error","too_big"===t?i="The data requested exceeds the maximum size that can be accessed with a single request.":"permission_denied"===t?i="Client doesn't have permission to access the desired data.":"unavailable"===t&&(i="The service is unavailable"),(r=Error(t+" at "+n._path.toString()+": "+i)).code=t.toUpperCase(),r);return n_(e,n,null,s)}}}}function nw(e,t){let n=nI(t);return e.queryToTagMap.get(n)}function nI(e){return e._path.toString()+"$"+e._queryIdentifier}function nC(e,t){return e.tagToQueryMap.get(t)}function nb(e){let t=e.indexOf("$");return(0,m.assert)(-1!==t&&t<e.length-1,"Bad queryKey."),{queryId:e.substr(t+1),path:new eE(e.substr(0,t))}}function nE(e,t,n){let i=e.syncPointTree_.get(t);return(0,m.assert)(i,"Missing sync point for query tag that we're tracking"),ns(i,n,tZ(t,e.pendingWriteTree_),null)}
1function nT(e){return e._queryParams.loadsAllData()&&!e._queryParams.isDefault()?new((0,m.assert)(c,"Reference.ts has not been loaded"),c)(e._repo,e._path):e}class nS{constructor(e){this.node_=e}getImmediateChild(e){return new nS(this.node_.getImmediateChild(e))}node(){return this.node_}}class nk{constructor(e,t){this.syncTree_=e,this.path_=t}getImmediateChild(e){let t=eO(this.path_,e);return new nk(this.syncTree_,t)}node(){return nm(this.syncTree_,this.path_)}}let nP=function(e,t,n){return e&&"object"==typeof e?((0,m.assert)(".sv"in e,"Unexpected leaf node or priority contents"),"string"==typeof e[".sv"])?nN(e[".sv"],t,n):"object"==typeof e[".sv"]?nR(e[".sv"],t):void(0,m.assert)(!1,"Unexpected server value: "+JSON.stringify(e,null,2)):e},nN=function(e,t,n){if("timestamp"===e)return n.timestamp;(0,m.assert)(!1,"Unexpected server value: "+e)},nR=function(e,t,n){e.hasOwnProperty("increment")||(0,m.assert)(!1,"Unexpected server value: "+JSON.stringify(e,null,2));let i=e.increment;"number"!=typeof i&&(0,m.assert)(!1,"Unexpected increment value: "+i);let r=t.node();if((0,m.assert)(null!=r,"Expected ChildrenNode.EMPTY_NODE for nulls"),!r.isLeafNode())return i;let s=r.getValue();return"number"!=typeof s?i:s+i};function nA(e,t,n){let i,r=nP(e.getPriority().val(),t.getImmediateChild(".priority"),n);if(!e.isLeafNode())return i=e,r!==e.getPriority().val()&&(i=i.updatePriority(new eZ(r))),e.forEachChild(e0,(e,r)=>{let s=nA(r,t.getImmediateChild(e),n);s!==r&&(i=i.updateImmediateChild(e,s))}),i;{let i=nP(e.getValue(),t,n);return i!==e.getValue()||r!==e.getPriority().val()?new eZ(i,e7(r)):e}}class nO{constructor(e="",t=null,n={children:{},childCount:0}){this.name=e,this.parent=t,this.node=n}}function nD(e,t){let n=t instanceof eE?t:new eE(t),i=e,r=eS(n);for(;null!==r;){let e=(0,m.safeGet)(i.node.children,r)||{children:{},childCount:0};i=new nO(r,i,e),r=eS(n=eP(n))}return i}function nx(e){return e.node.value}function nL(e,t){e.node.value=t,function e(t){null!==t.parent&&function(t,n,i){let r=void 0===nx(i)&&!nM(i),s=(0,m.contains)(t.node.children,n);r&&s?(delete t.node.children[n],t.node.childCount--,e(t)):r||s||(t.node.children[n]=i.node,t.node.childCount++,e(t))}(t.parent,t.name,t)}(e)}function nM(e){return e.node.childCount>0}function nF(e,t){Y(e.node.children,(n,i)=>{t(new nO(n,e,i))})}function nU(e){return new eE(null===e.parent?e.name:nU(e.parent)+"/"+e.name)}let nq=/[\[\].#$\/\u0000-\u001F\u007F]/,nj=/[\[\].#$\u0000-\u001F\u007F]/,nW=function(e){return"string"==typeof e&&0!==e.length&&!nq.test(e)},nV=function(e){return"string"==typeof e&&0!==e.length&&!nj.test(e)},nH=function(e){return null===e||"string"==typeof e||"number"==typeof e&&!j(e)||e&&"object"==typeof e&&(0,m.contains)(e,".sv")},nB=function(e,t,n,i){i&&void 0===t||nz((0,m.errorPrefix)(e,"value"),t,n)},nz=function(e,t,n){let i=n instanceof eE?new eF(n,e):n;if(void 0===t)throw Error(e+"contains undefined "+eq(i));if("function"==typeof t)throw Error(e+"contains a function "+eq(i)+" with contents = "+t.toString());if(j(t))throw Error(e+"contains "+t.toString()+" "+eq(i));if("string"==typeof t&&t.length>3495253.3333333335&&(0,m.stringLength)(t)>0xa00000)throw Error(e+"contains a string greater than 10485760 utf8 bytes "+eq(i)+" ('"+t.substring(0,50)+"...')");if(t&&"object"==typeof t){let n=!1,r=!1;if(Y(t,(t,s)=>{let o;if(".value"===t)n=!0;else if(".priority"!==t&&".sv"!==t&&(r=!0,!nW(t)))throw Error(e+" contains an invalid key ("+t+") "+eq(i)+'.  Keys must be non-empty strings and can\'t contain ".", "#", "$", "/", "[", or "]"');i.parts_.length>0&&(i.byteLength_+=1),i.parts_.push(t),i.byteLength_+=(0,m.stringLength)(t),eU(i),nz(e,s,i),o=i.parts_.pop(),i.byteLength_-=(0,m.stringLength)(o),i.parts_.length>0&&(i.byteLength_-=1)}),n&&r)throw Error(e+' contains ".value" child '+eq(i)+" in addition to actual children.")}},n$=function(e,t,n,i){if((!i||void 0!==n)&&!nW(n))throw Error((0,m.errorPrefix)(e,t)+'was an invalid key = "'+n+'".  Firebase keys must be non-empty strings and can\'t contain ".", "#", "$", "/", "[", or "]").')},nK=function(e,t,n,i){if((!i||void 0!==n)&&!nV(n))throw Error((0,m.errorPrefix)(e,t)+'was an invali
1d path = "'+n+'". Paths must be non-empty strings and can\'t contain ".", "#", "$", "[", or "]"')},nG=function(e,t,n,i){n&&(n=n.replace(/^\/*\.info(\/|$)/,"/")),nK(e,t,n,i)},nY=function(e,t){var n;let i=t.path.toString();if("string"!=typeof t.repoInfo.host||0===t.repoInfo.host.length||!nW(t.repoInfo.namespace)&&"localhost"!==t.repoInfo.host.split(":")[0]||0!==i.length&&((n=i)&&(n=n.replace(/^\/*\.info(\/|$)/,"/")),!nV(n)))throw Error((0,m.errorPrefix)(e,"url")+'must be a valid firebase URL and the path can\'t contain ".", "#", "$", "[", or "]".')};class nJ{constructor(){this.eventLists_=[],this.recursionDepth_=0}}function nQ(e,t){let n=null;for(let i=0;i<t.length;i++){let r=t[i],s=r.getPath();null===n||eL(s,n.path)||(e.eventLists_.push(n),n=null),null===n&&(n={events:[],path:s}),n.events.push(r)}n&&e.eventLists_.push(n)}function nX(e,t,n){nQ(e,n),n0(e,e=>eL(e,t))}function nZ(e,t,n){nQ(e,n),n0(e,e=>eM(e,t)||eM(t,e))}function n0(e,t){e.recursionDepth_++;let n=!0;for(let i=0;i<e.eventLists_.length;i++){let r=e.eventLists_[i];r&&(t(r.path)?(function(e){for(let t=0;t<e.events.length;t++){let n=e.events[t];if(null!==n){e.events[t]=null;let i=n.getEventRunner();A&&x("event: "+n.toString()),Z(i)}}}(e.eventLists_[i]),e.eventLists_[i]=null):n=!1)}n&&(e.eventLists_=[]),e.recursionDepth_--}class n1{constructor(e,t,n,i){this.repoInfo_=e,this.forceRestClient_=t,this.authTokenProvider_=n,this.appCheckProvider_=i,this.dataUpdateCount=0,this.statsListener_=null,this.eventQueue_=new nJ,this.nextWriteId_=1,this.interceptServerDataCallback_=null,this.onDisconnect_=tf(),this.transactionQueueTree_=new nO,this.persistentConnection_=null,this.key=this.repoInfo_.toURLString()}toString(){return(this.repoInfo_.secure?"https://":"http://")+this.repoInfo_.host}}function n2(e){var t;let n;return(t=t={timestamp:(n=e.infoData_.getNode(new eE(".info/serverTimeOffset")).val()||0,new Date().getTime()+n)}).timestamp=t.timestamp||new Date().getTime(),t}function n3(e,t,n,i,r){e.dataUpdateCount++;let s=new eE(t);n=e.interceptServerDataCallback_?e.interceptServerDataCallback_(t,n):n;let o=[];if(r)if(i){let t=(0,m.map)(n,e=>e7(e));o=function(e,t,n,i){let r=nC(e,i);if(!r)return[];{let i=nb(r),s=i.path,o=i.queryId,a=ex(s,t),l=tD.fromObject(n);return nE(e,s,new tE(tw(o),a,l))}}(e.serverSyncTree_,s,t,r)}else{let t=e7(n);o=function(e,t,n,i){let r=nC(e,i);if(null==r)return[];{let i=nb(r),s=i.path,o=i.queryId,a=ex(s,t);return nE(e,s,new tb(tw(o),a,n))}}(e.serverSyncTree_,s,t,r)}else if(i){var a;let t,i=(0,m.map)(n,e=>e7(e));a=e.serverSyncTree_,t=tD.fromObject(i),o=ny(a,new tE(tv(),s,t))}else{let t=e7(n);o=nf(e.serverSyncTree_,s,t)}let l=s;o.length>0&&(l=n9(e,s)),nZ(e.eventQueue_,l,o)}function n4(e,t){var n;let i,r,s;n6(e,"connected",t),!1===t&&(n8(n=e,"onDisconnectEvents"),i=n2(n),r=tf(),t_(n.onDisconnect_,eT(),(e,t)=>{var s;let o=(s=n.serverSyncTree_,nA(t,new nk(s,e),i));!function e(t,n,i){if(eD(n))t.value=i,t.children.clear();else if(null!==t.value)t.value=t.value.updateChild(n,i);else{let r=eS(n);t.children.has(r)||t.children.set(r,tf()),e(t.children.get(r),n=eP(n),i)}}(r,e,o)}),s=[],t_(r,eT(),(e,t)=>{var i,r;let o,a;s=s.concat(nf(n.serverSyncTree_,e,t));let l=(o=nU(ie(i=n,r=e)),!function(e,t){let n=e.parent;for(;null!==n;){if(t(n))return!0;n=n.parent}}(a=nD(i.transactionQueueTree_,r),e=>{ir(i,e)}),ir(i,a),!function e(t,n,i,r){i&&!r&&n(t),nF(t,t=>{e(t,n,!0,r)}),i&&r&&n(t)}(a,e=>{ir(i,e)}),o);n9(n,l)}),n.onDisconnect_=tf(),nZ(n.eventQueue_,eT(),s))}function n6(e,t,n){let i=new eE("/.info/"+t),r=e7(n);e.infoData_.updateSnapshot(i,r);let s=nf(e.infoSyncTree_,i,r);nZ(e.eventQueue_,i,s)}function n5(e,t,n){let i;i=".info"===eS(t._path)?n_(e.infoSyncTree_,t,n):n_(e.serverSyncTree_,t,n),nX(e.eventQueue_,t._path,i)}function n8(e,...t){let n="";e.persistentConnection_&&(n=e.persistentConnection_.id+":"),x(n,...t)}
1function n7(e,t,n){return nm(e.serverSyncTree_,t,n)||e5.EMPTY_NODE}function n9(e,t){let n=ie(e,t),i=nU(n),r=it(e,n);return function(e,t,n){if(0===t.length)return;let i=[],r=[],s=t.filter(e=>0===e.status).map(e=>e.currentWriteId);for(let o=0;o<t.length;o++){let a=t[o],l=ex(n,a.path),h=!1,c;if((0,m.assert)(null!==l,"rerunTransactionsUnderNode_: relativePath should not be null."),4===a.status)h=!0,c=a.abortReason,r=r.concat(np(e.serverSyncTree_,a.currentWriteId,!0));else if(0===a.status)if(a.retryCount>=25)h=!0,c="maxretry",r=r.concat(np(e.serverSyncTree_,a.currentWriteId,!0));else{let n=n7(e,a.path,s);a.currentInputSnapshot=n;let i=t[o].update(n.val());if(void 0!==i){nz("transaction failed: Data returned ",i,a.path);let t=e7(i);"object"==typeof i&&null!=i&&(0,m.contains)(i,".priority")||(t=t.updatePriority(n.getPriority()));let o=a.currentWriteId,l=n2(e),h=nA(t,new nS(n),l);a.currentOutputSnapshotRaw=t,a.currentOutputSnapshotResolved=h,a.currentWriteId=e.nextWriteId_++,s.splice(s.indexOf(o),1),r=(r=r.concat(function(e,t,n,i,r){var s,o;return(s=e.pendingWriteTree_,o=r,(0,m.assert)(i>s.lastWriteId,"Stacking an older write on top of newer ones"),void 0===o&&(o=!0),s.allWrites.push({path:t,snap:n,writeId:i,visible:o}),o&&(s.visibleWrites=tL(s.visibleWrites,t,n)),s.lastWriteId=i,r)?ny(e,new tb(ty(),t,n)):[]}(e.serverSyncTree_,a.path,h,a.currentWriteId,a.applyLocally))).concat(np(e.serverSyncTree_,o,!0))}else h=!0,c="nodata",r=r.concat(np(e.serverSyncTree_,a.currentWriteId,!0))}nZ(e.eventQueue_,n,r),r=[],h&&(t[o].status=2,setTimeout(t[o].unwatcher,Math.floor(0)),t[o].onComplete&&("nodata"===c?i.push(()=>t[o].onComplete(null,!1,t[o].currentInputSnapshot)):i.push(()=>t[o].onComplete(Error(c),!1,null))))}ii(e,e.transactionQueueTree_);for(let e=0;e<i.length;e++)Z(i[e]);!function e(t,n=t.transactionQueueTree_){if(n||ii(t,n),nx(n)){let i=it(t,n);(0,m.assert)(i.length>0,"Sending zero length transaction queue"),i.every(e=>0===e.status)&&function(t,n,i){let r=n7(t,n,i.map(e=>e.currentWriteId)),s=r,o=r.hash();for(let e=0;e<i.length;e++){let t=i[e];(0,m.assert)(0===t.status,"tryToSendTransactionQueue_: items in queue should all be run."),t.status=1,t.retryCount++;let r=ex(n,t.path);s=s.updateChild(r,t.currentOutputSnapshotRaw)}let a=s.val(!0);t.server_.put(n.toString(),a,r=>{n8(t,"transaction put response",{path:n.toString(),status:r});let s=[];if("ok"===r){let r=[];for(let e=0;e<i.length;e++)i[e].status=2,s=s.concat(np(t.serverSyncTree_,i[e].currentWriteId)),i[e].onComplete&&r.push(()=>i[e].onComplete(null,!0,i[e].currentOutputSnapshotResolved)),i[e].unwatcher();ii(t,nD(t.transactionQueueTree_,n)),e(t,t.transactionQueueTree_),nZ(t.eventQueue_,n,s);for(let e=0;e<r.length;e++)Z(r[e])}else{if("datastale"===r)for(let e=0;e<i.length;e++)3===i[e].status?i[e].status=4:i[e].status=0;else{U("transaction at "+n.toString()+" failed: "+r);for(let e=0;e<i.length;e++)i[e].status=4,i[e].abortReason=r}n9(t,n)}},o)}(t,nU(n),i)}else nM(n)&&nF(n,n=>{e(t,n)})}(e,e.transactionQueueTree_)}(e,r,i),i}function ie(e,t){let n,i=e.transactionQueueTree_;for(n=eS(t);null!==n&&void 0===nx(i);)i=nD(i,n),n=eS(t=eP(t));return i}function it(e,t){let n=[];return function e(t,n,i){let r=nx(n);if(r)for(let e=0;e<r.length;e++)i.push(r[e]);nF(n,n=>{e(t,n,i)})}(e,t,n),n.sort((e,t)=>e.order-t.order),n}function ii(e,t){let n=nx(t);if(n){let e=0;for(let t=0;t<n.length;t++)2!==n[t].status&&(n[e]=n[t],e++);n.length=e,nL(t,n.length>0?n:void 0)}nF(t,t=>{ii(e,t)})}function ir(e,t){let n=nx(t);if(n){let i=[],r=[],s=-1;for(let t=0;t<n.length;t++)3===n[t].status||(1===n[t].status?((0,m.assert)(s===t-1,"All SENT items should be at beginning of queue."),s=t,n[t].status=3,n[t].abortReason="set"):((0,m.assert)(0===n[t].status,"Unexpected transaction status in abort"),n[t].unwatcher(),r=r.concat(np(e.serverSyncTree_,n[t].currentWriteId,!0)),n[t].onComplete&&i.push(n[t].onComplete.bind(null,Error("set"),!1,null))));-1===s?nL(t,void 0):n.length=s+1,nZ(e.eventQueue_,nU(t),r);for(let e=0;e<i.length;e++)Z(i[e])}}let is=function(e,t){let n=io(e),i=n.namespace;"firebase.com"===n.domain&&F(n.host+" is no longer supported. Please use <YOUR FIREBASE>.firebaseio.com instead"),i&&"undefined"!==i||"localhost"===n.domain||F("Cannot parse Firebase url. Please use https://<YOUR FIREBASE>.firebaseio.com"),n.secure||q();let r="ws"===n.scheme||"wss"===n.scheme;return{repoInfo:new ea(n.host,n.secure,i,r,t,"",i!==n.subdomain),path:new eE(n.pathString)}},io=function(e){let t="",n="",i="",r="",s="",o=!0,a="https",l=443;if("string"==typeof e){let h=e.indexOf("//");h>=0&&(a=e.substring(0,h-1),e=e.substring(h+2));let c=e.indexOf("/");-1===c&&(c=e.length);let u=e.indexOf("?");-1===u&&(u=e.length),t=e.substring(0,Math.min(c,u)),c<u&&(r=function(e){let t="",n=e.split("/");for(let e=0;e<n.length;e++)if(n[e].length>0){let i=n[e];try{i=decodeURIComponent(i.replace(/\+/g," "))}catch(e){}t+="/"+i}return t}(e.substring(c,u)));let d=function(e){let t={};for(let n of("?"===e.charAt(0)&&(e=e.substring(1)),e.split("&"))){if(0===n.length)continue;let i=n.split("=");
12===i.length?t[decodeURIComponent(i[0])]=decodeURIComponent(i[1]):U(`Invalid query segment '${n}' in query '${e}'`)}return t}(e.substring(Math.min(e.length,u)));(h=t.indexOf(":"))>=0?(o="https"===a||"wss"===a,l=parseInt(t.substring(h+1),10)):h=t.length;let p=t.slice(0,h);if("localhost"===p.toLowerCase())n="localhost";else if(p.split(".").length<=2)n=p;else{let e=t.indexOf(".");i=t.substring(0,e).toLowerCase(),n=t.substring(e+1),s=i}"ns"in d&&(s=d.ns)}return{host:t,port:l,domain:n,subdomain:i,secure:o,scheme:a,pathString:r,namespace:s}};class ia{constructor(e,t,n,i){this.eventType=e,this.eventRegistration=t,this.snapshot=n,this.prevName=i}getPath(){let e=this.snapshot.ref;return"value"===this.eventType?e._path:e.parent._path}getEventType(){return this.eventType}getEventRunner(){return this.eventRegistration.getEventRunner(this)}toString(){return this.getPath().toString()+":"+this.eventType+":"+(0,m.stringify)(this.snapshot.exportVal())}}class il{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 ih{constructor(e,t){this.snapshotCallback=e,this.cancelCallback=t}onValue(e,t){this.snapshotCallback.call(null,e,t)}onCancel(e){return(0,m.assert)(this.hasCancelCallback,"Raising a cancel event on a listener with no cancel callback"),this.cancelCallback.call(null,e)}get hasCancelCallback(){return!!this.cancelCallback}matches(e){return this.snapshotCallback===e.snapshotCallback||void 0!==this.snapshotCallback.userCallback&&this.snapshotCallback.userCallback===e.snapshotCallback.userCallback&&this.snapshotCallback.context===e.snapshotCallback.context}}class ic{constructor(e,t,n,i){this._repo=e,this._path=t,this._queryParams=n,this._orderByCalled=i}get key(){return eD(this._path)?null:eN(this._path)}get ref(){return new id(this._repo,this._path)}get _queryIdentifier(){let e=K(tu(this._queryParams));return"{}"===e?"default":e}get _queryObject(){return tu(this._queryParams)}isEqual(e){if(!((e=(0,m.getModularInstance)(e))instanceof ic))return!1;let t=this._repo===e._repo,n=eL(this._path,e._path),i=this._queryIdentifier===e._queryIdentifier;return t&&n&&i}toJSON(){return this.toString()}toString(){return this._repo.toString()+function(e){let t="";for(let n=e.pieceNum_;n<e.pieces_.length;n++)""!==e.pieces_[n]&&(t+="/"+encodeURIComponent(String(e.pieces_[n])));return t||"/"}(this._path)}}function iu(e){let t=null,n=null;if(e.hasStart()&&(t=e.getIndexStartValue()),e.hasEnd()&&(n=e.getIndexEndValue()),e.getIndex()===ez){let i="Query: When ordering by key, you may only pass one argument to startAt(), endAt(), or equalTo().",r="Query: When ordering by key, the argument passed to startAt(), startAfter(), endAt(), endBefore(), or equalTo() must be a string.";if(e.hasStart()){if(e.getIndexStartName()!==V)throw Error(i);if("string"!=typeof t)throw Error(r)}if(e.hasEnd()){if(e.getIndexEndName()!==H)throw Error(i);if("string"!=typeof n)throw Error(r)}}else if(e.getIndex()===e0){if(null!=t&&!nH(t)||null!=n&&!nH(n))throw 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 if((0,m.assert)(e.getIndex()instanceof e9||e.getIndex()===te,"unknown index type."),null!=t&&"object"==typeof t||null!=n&&"object"==typeof n)throw Error("Query: First argument passed to startAt(), startAfter(), endAt(), endBefore(), or equalTo() cannot be an object.")}class id extends ic{constructor(e,t){super(e,t,new tl,!1)}get parent(){let e=eA(this._path);return null===e?null:new id(this._repo,e)}get root(){let e=this;for(;null!==e.parent;)e=e.parent;return e}}class ip{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){let t=new eE(e),n=i_(this.ref,e);return new ip(this._node.getChild(t),n,e0)}exists(){return!this._node.isEmpty()}exportVal(){return this._node.val(!0)}forEach(e){return!this._node.isLeafNode()&&!!this._node.forEachChild(this._index,(t,n)=>e(new ip(n,i_(this.ref,t),e0)))}hasChild(e){let t=new eE(e);return!this._node.getChild(t).isEmpty()}hasChildren(){return!this._node.isLeafNode()&&!this._node.isEmpty()}toJSON(){return this.exportVal()}val(){return this._node.val()}}function i_(e,t){return null===eS((e=(0,m.getModularInstance)(e))._path)?nG("child","path",t,!1):nK("child","path",t,!1),new id(e._repo,eO(e._path,t))}class ig{constructor(e){this.callbackContext=e}respondsTo(e){return"value"===e}createEvent(e,t){let n=t._queryParams.getIndex();return new ia("value",this,new ip(e.snapshotNode,new id(t._repo,t._path),n))}getEventRunner(e){return"cancel"===e.getEventType()?()=>this.callbackContext.onCancel(e.error):()=>this.callbackContext.onValue(e.snapshot,null)}createCancelEvent(e,t){return this.callbackContext.hasCancelCallback?new il(this,e,t):null}matches(e){return e instanceof ig&&(!e.callbackContext||!this.callbackContext||e.callbackContext.matches(this.callbackContext))}hasAnyCallback(){return null!==this.callbackContext}}class im{constructor(e,t){this.eventType=e,this.callbackContext=t}respondsTo(e){let t="children_added"===e?"child_added":e;return t="children_removed"===t?"child_removed":t,this.eventType===t}createCancelEvent(e,t){return this.callbackContext.hasCancelCallback?new il(this,e,t):null}createEvent(e,t){(0,m.assert)(null!=e.childName,"Child events should have a childName.");let n=i_(new id(t._repo,t._path),e.childName),i=t._queryParams.getIndex();return new ia(e.type,this,new ip(e.snapshotNode,n,i),e.prevName)}getEventRunner(e){return"cancel"===e.getEventType()?()=>this.callbackContext.onCancel(e.error):()=>this.callbackContext.onValue(e.snapshot,e.prevName)}matches(e){return e instanceof im&&this.eventType===e.eventType&&(!this.callbackContext||!e.callbackContext||this.callbackContext.matches(e.callbackContext))}hasAnyCallback(){return!!this.callbackContext}}function iy(e,t,n,i,r){var s;let o,a;if("object"==typeof i&&(o=void 0,r=i),"function"==typeof i&&(o=i),r&&r.onlyOnce){let t=n,i=(n,i)=>{n5(e._repo,e,h),t(n,i)};i.userCallback=n.userCallback,i.context=n.context,n=i}let l=new ih(n,o||void 0),h="value"===t?new ig(l):new im(t,l);return s=e._repo,a=".info"===eS(e._path)?ng(s.infoSyncTree_,e,h):ng(s.serverSyncTree_,e,h),nX(s.eventQueue_,e._path,a),()=>n5(e._repo,e,h)}class iv{}class iw extends iv{constructor(e,t){super(),this._value=e,this._key=t,this.type="startAfter"}_apply(e){var t,n,i;let r;nB("startAfter",this._value,e._path,!1);let s=(t=e._queryParams,n=this._value,i=this._key,(r=t.index_===ez||i?th(t,n,i):th(t,n,H)).startAfterSet_=!0,r);if(s.hasStart()&&s.hasEnd()&&s.hasLimit()&&!s.hasAnchoredLimit())throw Error("Query: Can't combine startAt(), startAfter(), endAt(), endBefore(), and limit(). Use limitToFirst() or limitToLast() instead.");if(iu(s),e._queryParams.hasStart())throw Error("startAfter: Starting point was already set 
1(by another call to startAt, startAfter, or equalTo).");return new ic(e._repo,e._path,s,e._orderByCalled)}}class iI extends iv{constructor(){super(...arguments),this.type="orderByKey"}_apply(e){var t;let n;if(!0===e._orderByCalled)throw Error("orderByKey: You can't combine multiple orderBy calls.");let i=(t=e._queryParams,(n=t.copy()).index_=ez,n);return iu(i),new ic(e._repo,e._path,i,!0)}}(0,m.assert)(!h,"__referenceConstructor has already been defined"),h=id,(0,m.assert)(!c,"__referenceConstructor has already been defined"),c=id;let iC={};class ib{constructor(e,t){this._repoInternal=e,this.app=t,this.type="database",this._instanceStarted=!1}get _repo(){return this._instanceStarted||(!function(e,t,n){var i;let r;if(e.stats_=ed(e.repoInfo_),e.forceRestClient_||("object"==typeof window&&window.navigator&&window.navigator.userAgent||"").search(/googlebot|google webmaster tools|bingbot|yahoo! slurp|baiduspider|yandexbot|duckduckbot/i)>=0)e.server_=new td(e.repoInfo_,(t,n,i,r)=>{n3(e,t,n,i,r)},e.authTokenProvider_,e.appCheckProvider_),setTimeout(()=>n4(e,!0),0);else{if(null!=n){if("object"!=typeof n)throw Error("Only objects are supported for option databaseAuthVariableOverride");try{(0,m.stringify)(n)}catch(e){throw Error("Invalid authOverride provided: "+e)}}e.persistentConnection_=new eW(e.repoInfo_,t,(t,n,i,r)=>{n3(e,t,n,i,r)},t=>{n4(e,t)},t=>{var n;n=e,Y(t,(e,t)=>{n6(n,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)}),i=e.repoInfo_,eu[r=i.toString()]||(eu[r]=(()=>new tm(e.stats_,e.server_))()),e.statsReporter_=eu[r],e.infoData_=new tp,e.infoSyncTree_=new nd({startListening:(t,n,i,r)=>{let s=[],o=e.infoData_.getNode(t._path);return o.isEmpty()||(s=nf(e.infoSyncTree_,t._path,o),setTimeout(()=>{r("ok")},0)),s},stopListening:()=>{}}),n6(e,"connected",!1),e.serverSyncTree_=new nd({startListening:(t,n,i,r)=>(e.server_.listen(t,i,n,(n,i)=>{let s=r(n,i);nZ(e.eventQueue_,t._path,s)}),[]),stopListening:(t,n)=>{e.server_.unlisten(t,n)}})}(this._repoInternal,this.app.options.appId,this.app.options.databaseAuthVariableOverride),this._instanceStarted=!0),this._repoInternal}get _root(){return this._rootInternal||(this._rootInternal=new id(this._repo,eT())),this._rootInternal}_delete(){if(null!==this._rootInternal){var e,t;let n;e=this._repo,(n=iC[t=this.app.name])&&n[e.key]===e||F(`Database ${t}(${e.repoInfo_}) has already been deleted.`),e.persistentConnection_&&e.persistentConnection_.interrupt("repo_interrupt"),delete n[e.key],this._repoInternal=null,this._rootInternal=null}return Promise.resolve()}_checkNotDeleted(e){null===this._rootInternal&&F("Cannot call "+e+" on a deleted database.")}}eW.prototype.simpleListen=function(e,t){this.sendRequest("q",{p:e},t)},eW.prototype.echo=function(e,t){this.sendRequest("echo",{d:e},t)},I=_.SDK_VERSION,(0,_._registerComponent)(new g.Component("database",(e,{instanceIdentifier:t})=>{var n,i,r,s;let o,a,l,h,c,u,d,p=e.getProvider("app").getImmediate(),_=e.getProvider("auth-internal"),g=e.getProvider("app-check-internal");return void 0===(l=t||p.options.databaseURL)&&(p.options.projectId||F("Can't determine Firebase Database URL. Be sure to include  a Project ID when calling firebase.initializeApp()."),x("Using default host for project ",p.options.projectId),l=`${p.options.projectId}-default-rtdb.firebaseio.com`),c=(h=is(l,void 0)).repoInfo,void 0!==f.default&&f.default.env&&(u=f.default.env.FIREBASE_DATABASE_EMULATOR_HOST),u?c=(h=is(l=`http://${u}?ns=${c.namespace}`,void 0)).repoInfo:!h.repoInfo.secure,d=new en(p.name,p.options,_),nY("Invalid Firebase Database URL",h),eD(h.path)||F("Database URL must point to the root of a Firebase Database (not including a child path)."),new ib((n=c,i=p,r=d,s=new et(p.name,g),(o=iC[i.name])||(o={},iC[i.name]=o),(a=o[n.toURLString()])&&F("Database initialized multiple times. Please make sure the format of the database URL matches with each database() call."),a=new n1(n,!1,r,s),o[n.toURLString()]=a,a),p)},"PUBLIC").setMultipleInstances(!0)),(0,_.registerVersion)(v,w,void 0),(0,_.registerVersion)(v,w,"esm2017"),e.s(["getDatabase",0,function(e=(0,_.getApp)(),t){let n=(0,_._getProvider)(e,"database").getImmediate({identifier:t});if(!n._instanceStarted){let e=(0,m.getDefaultEmulatorHostnameAndPort)("database");e&&function(e,t,n,i={}){var r;let s;(e=(0,m.getModularInstance)(e))._checkNotDeleted("useEmulator"),e._instanceStarted&&F("Cannot call useEmulator() after instance has already been initialized.");let o=e._repoInternal;o.repoInfo_.nodeAdmin?(i.mockUserToken&&F('mockUserToken is not supported by the Admin SDK. For client access with mock users, please use the "firebase" package instead of "firebase-admin".'),s=new ei(ei.OWNER)):i.mockUserToken&&(s=new ei("string"==typeof i.mockUserToken?i.mockUserToken:(0,m.createMockUserToken)(i.mockUserToken,e.app.options.projectId))),r=s,o.repoInfo_=new ea(`${t}:${n}`,!1,o.repoInfo_.namespace,o.repoInfo_.webSocketOnly,o.repoInfo_.nodeAdmin,o.repoInfo_.persistenceKey,o.repoInfo_.includeNamespaceInQueryParams,!0),r&&(o.authTokenProvider_=r)}(n,...e)}return n},"onChildAdded",0,function(e,t,n,i){return iy(e,"child_added",t,n,i)},"onValue",0,function(e,t,n,i){return iy(e,"value",t,n,i)},"orderByKey",0,function(){return new iI},"query",0,function(e,...t){let n=(0,m.getModularInstance)(e);for(let e of t)n=e._apply(n);return n},"ref",0,function(e,t){return(e=(0,m.getModularInstance)(e))._checkNotDeleted("ref"),void 0!==t?i_(e._root,t):e._root},"startAfter",0,function(e,t){return n$("startAfter","key",t,!0),new iw(e,t)}],476686),e.s([],401465)},340798,e=>{"use strict";e.i(247167),e.i(214539);var t=e.i(485086);e.i(401465);var n=e.i(476686);e.i(151718);var i=e.i(854762),i=i;let r=(0,t.initializeApp)({apiKey:"AIzaSyB-QFMqJhTgL7-FiXvlni6xlJ3OzJC8GNE",authDomain:"academic-volt-572.firebaseapp.com",databaseURL:"https://academic-volt-572.firebaseio.com",projectId:"academic-volt-572",storageBucket:"academic-volt-572.appspot.com",messagingSenderId:"76494134898",appId:"1:76494134898:web:757a3ff7c2fd2516ac2ceb",measurementId:"G-ESSL2S05W0"}),s=(0,i.o)(r),o=(0,n.getDatabase)(r);e.s(["app",0,r,"auth",0,s,"firebaseDatabase",0,o],340798)}]);

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.